title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
Find sum of all left leaves in a given Binary Tree
|
24 Jun, 2022
Given a Binary Tree, find the sum of all left leaves in it. For example, sum of all left leaves in below Binary Tree is 5+1=6.
The idea is to traverse the tree, starting from root. For every node, check if its left subtree is a leaf. If it is, then add it to the result. Following is the implementation of the above idea.
C++
C
Java
Python3
C#
Javascript
// A C++ program to find sum of all left leaves#include <bits/stdc++.h>using namespace std; /* A binary tree Node has key, pointer to left and right children */struct Node{ int key; struct Node* left, *right;}; /* Helper function that allocates a new node with the given data and NULL left and right pointer. */Node *newNode(int k){ Node *node = new Node; node->key = k; node->right = node->left = NULL; return node;} // A utility function to check if a given node is leaf or notbool isLeaf(Node *node){ if (node == NULL) return false; if (node->left == NULL && node->right == NULL) return true; return false;} // This function returns sum of all left leaves in a given// binary treeint leftLeavesSum(Node *root){ // Initialize result int res = 0; // Update result if root is not NULL if (root != NULL) { // If left of root is NULL, then add key of // left child if (isLeaf(root->left)) res += root->left->key; else // Else recur for left child of root res += leftLeavesSum(root->left); // Recur for right child of root and update res res += leftLeavesSum(root->right); } // return result return res;} /* Driver program to test above functions*/int main(){ // Let us a construct the Binary Tree struct Node *root = newNode(20); root->left = newNode(9); root->right = newNode(49); root->right->left = newNode(23); root->right->right = newNode(52); root->right->right->left = newNode(50); root->left->left = newNode(5); root->left->right = newNode(12); root->left->right->right = newNode(12); cout << "Sum of left leaves is " << leftLeavesSum(root); return 0;} // This code is contributed by Aditya kumar (adityakumar129)
// A C++ program to find sum of all left leaves#include <stdio.h>#include <stdlib.h>#include <stdbool.h> /* A binary tree Node has key, pointer to left and right children */struct Node{ int key; struct Node* left, *right;}; /* Helper function that allocates a new node with the given data and NULL left and right pointer. */struct Node *newNode(int k){ struct Node *node = (struct Node *)malloc(sizeof(struct Node)); node->key = k; node->right = node->left = NULL; return node;} // A utility function to check if a given node is leaf or notbool isLeaf(struct Node *node){ if (node == NULL) return false; if (node->left == NULL && node->right == NULL) return true; return false;} // This function returns sum of all left leaves in a given// binary treeint leftLeavesSum(struct Node *root){ // Initialize result int res = 0; // Update result if root is not NULL if (root != NULL) { // If left of root is NULL, then add key of // left child if (isLeaf(root->left)) res += root->left->key; else // Else recur for left child of root res += leftLeavesSum(root->left); // Recur for right child of root and update res res += leftLeavesSum(root->right); } // return result return res;} /* Driver program to test above functions*/int main(){ // Let us a construct the Binary Tree struct Node *root = newNode(20); root->left = newNode(9); root->right = newNode(49); root->right->left = newNode(23); root->right->right = newNode(52); root->right->right->left = newNode(50); root->left->left = newNode(5); root->left->right = newNode(12); root->left->right->right = newNode(12); printf("Sum of left leaves is %d",leftLeavesSum(root)); return 0;} // This code is contributed by Aditya kumar (adityakumar129)
// Java program to find sum of all left leavesclass Node{ int data; Node left, right; Node(int item) { data = item; left = right = null; }} class BinaryTree{ Node root; // A utility function to check if a given node is leaf or not boolean isLeaf(Node node) { if (node == null) return false; if (node.left == null && node.right == null) return true; return false; } // This function returns sum of all left leaves in a given // binary tree int leftLeavesSum(Node node) { // Initialize result int res = 0; // Update result if root is not NULL if (node != null) { // If left of root is NULL, then add key of // left child if (isLeaf(node.left)) res += node.left.data; else // Else recur for left child of root res += leftLeavesSum(node.left); // Recur for right child of root and update res res += leftLeavesSum(node.right); } // return result return res; } // Driver program public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node(20); tree.root.left = new Node(9); tree.root.right = new Node(49); tree.root.left.right = new Node(12); tree.root.left.left = new Node(5); tree.root.right.left = new Node(23); tree.root.right.right = new Node(52); tree.root.left.right.right = new Node(12); tree.root.right.right.left = new Node(50); System.out.println("The sum of leaves is " + tree.leftLeavesSum(tree.root)); }} // This code is contributed by Mayank Jaiswal
# Python program to find sum of all left leaves # A Binary tree nodeclass Node: # Constructor to create a new Node def __init__(self, key): self.key = key self.left = None self.right = None # A utility function to check if a given node is leaf or notdef isLeaf(node): if node is None: return False if node.left is None and node.right is None: return True return False # This function return sum of all left leaves in a# given binary treedef leftLeavesSum(root): # Initialize result res = 0 # Update result if root is not None if root is not None: # If left of root is None, then add key of # left child if isLeaf(root.left): res += root.left.key else: # Else recur for left child of root res += leftLeavesSum(root.left) # Recur for right child of root and update res res += leftLeavesSum(root.right) return res # Driver program to test above function # Let us construct the Binary Tree shown in the above functionroot = Node(20)root.left = Node(9)root.right = Node(49)root.right.left = Node(23) root.right.right = Node(52)root.right.right.left = Node(50)root.left.left = Node(5)root.left.right = Node(12)root.left.right.right = Node(12)print ("Sum of left leaves is", leftLeavesSum(root)) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)
using System; // C# program to find sum of all left leavespublic class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} public class BinaryTree{ public Node root; // A utility function to check if a given node is leaf or not public virtual bool isLeaf(Node node) { if (node == null) { return false; } if (node.left == null && node.right == null) { return true; } return false; } // This function returns sum of all left leaves in a given // binary tree public virtual int leftLeavesSum(Node node) { // Initialize result int res = 0; // Update result if root is not NULL if (node != null) { // If left of root is NULL, then add key of // left child if (isLeaf(node.left)) { res += node.left.data; } else // Else recur for left child of root { res += leftLeavesSum(node.left); } // Recur for right child of root and update res res += leftLeavesSum(node.right); } // return result return res; } // Driver program public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(20); tree.root.left = new Node(9); tree.root.right = new Node(49); tree.root.left.right = new Node(12); tree.root.left.left = new Node(5); tree.root.right.left = new Node(23); tree.root.right.right = new Node(52); tree.root.left.right.right = new Node(12); tree.root.right.right.left = new Node(50); Console.WriteLine("The sum of leaves is " + tree.leftLeavesSum(tree.root)); }} // This code is contributed by Shrikant13
<script>// Javascript program to find sum of all left leaves class Node { constructor(k) { this.data = k; this.left = null; this.right = null; } } // A utility function to check if a given node is leaf or not function isLeaf(node) { if (node == null) return false; if (node.left == null && node.right == null) return true; return false; } // This function returns sum of all left leaves in a given // binary tree function leftLeavesSum(node) { // Initialize result let res = 0; // Update result if root is not NULL if (node != null) { // If left of root is NULL, then add key of // left child if (isLeaf(node.left)) res += node.left.data; else // Else recur for left child of root res += leftLeavesSum(node.left); // Recur for right child of root and update res res += leftLeavesSum(node.right); } // return result return res; } // Driver program root = new Node(20); root.left = new Node(9); root.right = new Node(49); root.left.right = new Node(12); root.left.left = new Node(5); root.right.left = new Node(23); root.right.right = new Node(52); root.left.right.right = new Node(12); root.right.right.left = new Node(50); document.write("The sum of leaves is " +leftLeavesSum(root)); // This code is contributed by unknown2108</script>
Sum of left leaves is 78
Time Complexity: O(N), where n is number of nodes in Binary Tree.
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
default, selected
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Following is Another Method to solve the above problem. This solution passes in a sum variable as an accumulator. When a left leaf is encountered, the leaf’s data is added to sum. Time complexity of this method is also O(n). Thanks to Xin Tong (geeksforgeeks userid trent.tong) for suggesting this method.
C++
Java
Python3
C#
Javascript
// A C++ program to find sum of all left leaves#include <bits/stdc++.h>using namespace std; /* A binary tree Node has key, pointer to left and right children */struct Node{ int key; struct Node* left, *right;}; /* Helper function that allocates a new node with the given data and NULL left and right pointer. */Node *newNode(char k){ Node *node = new Node; node->key = k; node->right = node->left = NULL; return node;} /* Pass in a sum variable as an accumulator */void leftLeavesSumRec(Node *root, bool isleft, int *sum){ if (!root) return; // Check whether this node is a leaf node and is left. if (!root->left && !root->right && isleft) *sum += root->key; // Pass 1 for left and 0 for right leftLeavesSumRec(root->left, 1, sum); leftLeavesSumRec(root->right, 0, sum);} // A wrapper over above recursive functionint leftLeavesSum(Node *root){ int sum = 0; //Initialize result // use the above recursive function to evaluate sum leftLeavesSumRec(root, 0, &sum); return sum;} /* Driver program to test above functions*/int main(){ // Let us construct the Binary Tree shown in the // above figure int sum = 0; struct Node *root = newNode(20); root->left = newNode(9); root->right = newNode(49); root->right->left = newNode(23); root->right->right = newNode(52); root->right->right->left = newNode(50); root->left->left = newNode(5); root->left->right = newNode(12); root->left->right->right = newNode(12); cout << "Sum of left leaves is " << leftLeavesSum(root) << endl; return 0;}
// Java program to find sum of all left leavesclass Node{ int data; Node left, right; Node(int item) { data = item; left = right = null; }} // Passing sum as accumulator and implementing pass by reference// of sum variableclass Sum{ int sum = 0;} class BinaryTree{ Node root; /* Pass in a sum variable as an accumulator */ void leftLeavesSumRec(Node node, boolean isleft, Sum summ) { if (node == null) return; // Check whether this node is a leaf node and is left. if (node.left == null && node.right == null && isleft) summ.sum = summ.sum + node.data; // Pass true for left and false for right leftLeavesSumRec(node.left, true, summ); leftLeavesSumRec(node.right, false, summ); } // A wrapper over above recursive function int leftLeavesSum(Node node) { Sum suum = new Sum(); // use the above recursive function to evaluate sum leftLeavesSumRec(node, false, suum); return suum.sum; } // Driver program public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node(20); tree.root.left = new Node(9); tree.root.right = new Node(49); tree.root.left.right = new Node(12); tree.root.left.left = new Node(5); tree.root.right.left = new Node(23); tree.root.right.right = new Node(52); tree.root.left.right.right = new Node(12); tree.root.right.right.left = new Node(50); System.out.println("The sum of leaves is " + tree.leftLeavesSum(tree.root)); }} // This code is contributed by Mayank Jaiswal
# Python program to find sum of all left leaves # A binary tree nodeclass Node: # A constructor to create a new Node def __init__(self, key): self.key = key self.left = None self.right = None def leftLeavesSumRec(root, isLeft, summ): if root is None: return # Check whether this node is a leaf node and is left if root.left is None and root.right is None and isLeft == True: summ[0] += root.key # Pass 1 for left and 0 for right leftLeavesSumRec(root.left, 1, summ) leftLeavesSumRec(root.right, 0, summ) # A wrapper over above recursive functiondef leftLeavesSum(root): summ = [0] # initialize result # Use the above recursive function to evaluate sum leftLeavesSumRec(root, 0, summ) return summ[0] # Driver program to test above function # Let us construct the Binary Tree shown in the# above figureroot = Node(20);root.left= Node(9);root.right = Node(49);root.right.left = Node(23);root.right.right= Node(52);root.right.right.left = Node(50);root.left.left = Node(5);root.left.right = Node(12);root.left.right.right = Node(12); print ("Sum of left leaves is", leftLeavesSum(root)) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)
using System; // C# program to find sum of all left leavespublic class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} // Passing sum as accumulator and implementing pass by reference // of sum variable public class Sum{ public int sum = 0;} public class BinaryTree{ public Node root; /* Pass in a sum variable as an accumulator */ public virtual void leftLeavesSumRec(Node node, bool isleft, Sum summ) { if (node == null) { return; } // Check whether this node is a leaf node and is left. if (node.left == null && node.right == null && isleft) { summ.sum = summ.sum + node.data; } // Pass true for left and false for right leftLeavesSumRec(node.left, true, summ); leftLeavesSumRec(node.right, false, summ); } // A wrapper over above recursive function public virtual int leftLeavesSum(Node node) { Sum suum = new Sum(); // use the above recursive function to evaluate sum leftLeavesSumRec(node, false, suum); return suum.sum; } // Driver program public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(20); tree.root.left = new Node(9); tree.root.right = new Node(49); tree.root.left.right = new Node(12); tree.root.left.left = new Node(5); tree.root.right.left = new Node(23); tree.root.right.right = new Node(52); tree.root.left.right.right = new Node(12); tree.root.right.right.left = new Node(50); Console.WriteLine("The sum of leaves is " + tree.leftLeavesSum(tree.root)); }} // This code is contributed by Shrikant13
<script>// javascript program to find sum of all left leavesclass Node { constructor(item) { this.data = item; this.left = this.right = null; }} // Passing sum as accumulator and implementing pass by reference// of sum variableclass Sum {constructor(){ this.sum = 0; }} var root; /* Pass in a sum variable as an accumulator */ function leftLeavesSumRec( node, isleft, summ) { if (node == null) return; // Check whether this node is a leaf node and is left. if (node.left == null && node.right == null && isleft) summ.sum = summ.sum + node.data; // Pass true for left and false for right leftLeavesSumRec(node.left, true, summ); leftLeavesSumRec(node.right, false, summ); } // A wrapper over above recursive function function leftLeavesSum( node) { suum = new Sum(); // use the above recursive function to evaluate sum leftLeavesSumRec(node, false, suum); return suum.sum; } // Driver program root = new Node(20); root.left = new Node(9); root.right = new Node(49); root.left.right = new Node(12); root.left.left = new Node(5); root.right.left = new Node(23); root.right.right = new Node(52); root.left.right.right = new Node(12); root.right.right.left = new Node(50); document.write("The sum of leaves is " + leftLeavesSum(root)); // This code contributed by gauravrajput1</script>
Sum of left leaves is 78
Following is Another Method to solve the above problem. We can pass bool as parameter in the function to check if it is a left or right node. Time complexity of this method is also O(n).
C
Java
#include <stdbool.h>#include <stdio.h>#include <stdlib.h> struct Node { int data; struct Node* left; struct Node* right;}; typedef struct Node str_node; str_node* create(int item);int sumAllLeaftLeaves(str_node* node, bool isLeft); int main(void){ int d = 0; str_node* root = create(20); root->left = create(9); root->right = create(49); root->right->left = create(23); root->right->right = create(52); root->right->right->left = create(50); root->left->left = create(5); root->left->right = create(12); root->left->right->right = create(12); printf("\nSum of left leaves is: %d ", sumAllLeaftLeaves(root, false)); return 0;} str_node* create(int item){ str_node* newnode = (str_node*)malloc(sizeof(str_node)); newnode->data = item; newnode->left = NULL; newnode->right = NULL; return newnode;} int sumAllLeaftLeaves(str_node* node, bool isLeft){ // base case: if (node == NULL) return 0; // check whether this node is a leaf node and is left. if (node->left == NULL && node->right == NULL && isLeft) return node->data; // recursive case return sumAllLeaftLeaves(node->left, true) + sumAllLeaftLeaves(node->right, false);}
class GFG{ static class Node { int data; Node left; Node right; }; static Node str_node; static Node create(int item) { Node newnode = new Node(); newnode.data = item; newnode.left = null; newnode.right = null; return newnode; } static int sumAllLeaftLeaves(Node node, boolean isLeft) { // base case: if (node == null) return 0; // check whether this node is a leaf node and is left. if (node.left == null && node.right == null && isLeft) return node.data; // recursive case return sumAllLeaftLeaves(node.left, true) + sumAllLeaftLeaves(node.right, false); } public static void main(String[] args) { int d = 0; Node root = create(20); root.left = create(9); root.right = create(49); root.right.left = create(23); root.right.right = create(52); root.right.right.left = create(50); root.left.left = create(5); root.left.right = create(12); root.left.right.right = create(12); System.out.printf("\nSum of left leaves is: %d ", sumAllLeaftLeaves(root, false)); }} // This code is contributed by umadevi9616
Sum of left leaves is: 78
Iterative Approach :
This is the Iterative Way to find the sum of the left leaves. Idea is to perform Depth-First Traversal on the tree (either Inorder, Preorder or Postorder) using a stack and checking if the Left Child is a Leaf node. If it is, then add the nodes value to the sum variable
C++
Java
Python3
C#
Javascript
// C++ program to find sum of all left leaves#include<bits/stdc++.h>using namespace std; // A binary tree nodeclass Node{ public: int key; Node* left, *right; // A constructor to create a new Node Node(int key_) { key = key_; left = NULL; right = NULL; }}; // Return the sum of left leaf nodesint sumOfLeftLeaves(Node* root){ if(root == NULL) return 0; // Using a stack_ for Depth-First // Traversal of the tree stack<Node*> stack_; stack_.push(root); // sum holds the sum of all the left leaves int sum = 0; while(stack_.size() > 0) { Node* currentNode = stack_.top(); stack_.pop(); if (currentNode->left != NULL) { stack_.push(currentNode->left); // Check if currentNode's left // child is a leaf node if(currentNode->left->left == NULL && currentNode->left->right == NULL) { // if currentNode is a leaf, // add its data to the sum sum = sum + currentNode->left->key ; } } if (currentNode->right != NULL) stack_.push(currentNode->right); } return sum;} // Driver Codeint main(){ Node *root = new Node(20); root->left= new Node(9); root->right = new Node(49); root->right->left = new Node(23); root->right->right= new Node(52); root->right->right->left = new Node(50); root->left->left = new Node(5); root->left->right = new Node(12); root->left->right->right = new Node(12); cout << "Sum of left leaves is " << sumOfLeftLeaves(root) << endl; return 0;} // This code is contributed by Arnab Kundu
// Java program to find sum of all left leavesimport java.util.*;class GFG{ // A binary tree nodestatic class Node{ int key; Node left, right; // A constructor to create a new Node Node(int key_) { this.key = key_; this.left = null; this.right = null; }}; // Return the sum of left leaf nodesstatic int sumOfLeftLeaves(Node root){ if(root == null) return 0; // Using a stack_ for Depth-First // Traversal of the tree Stack<Node> stack_ = new Stack<>(); stack_.push(root); // sum holds the sum of all the left leaves int sum = 0; while(stack_.size() > 0) { Node currentNode = stack_.peek(); stack_.pop(); if (currentNode.left != null) { stack_.add(currentNode.left); // Check if currentNode's left // child is a leaf node if(currentNode.left.left == null && currentNode.left.right == null) { // if currentNode is a leaf, // add its data to the sum sum = sum + currentNode.left.key ; } } if (currentNode.right != null) stack_.add(currentNode.right); } return sum;} // Driver Codepublic static void main(String[] args){ Node root = new Node(20); root.left= new Node(9); root.right = new Node(49); root.right.left = new Node(23); root.right.right= new Node(52); root.right.right.left = new Node(50); root.left.left = new Node(5); root.left.right = new Node(12); root.left.right.right = new Node(12); System.out.print("Sum of left leaves is " + sumOfLeftLeaves(root) +"\n");}} // This code is contributed by aashish1995
# Python3 program to find sum of all left leaves # A binary tree nodeclass Node: # A constructor to create a new Node def __init__(self, key): self.data = key self.left = None self.right = None # Return the sum of left leaf nodesdef sumOfLeftLeaves(root): if(root is None): return # Using a stack for Depth-First Traversal of the tree stack = [] stack.append(root) # sum holds the sum of all the left leaves sum = 0 while len(stack) > 0: currentNode = stack.pop() if currentNode.left is not None: stack.append(currentNode.left) # Check if currentNode's left child is a leaf node if currentNode.left.left is None and currentNode.left.right is None: # if currentNode is a leaf, add its data to the sum sum = sum + currentNode.left.data if currentNode.right is not None: stack.append(currentNode.right) return sum # Driver Coderoot = Node(20);root.left= Node(9);root.right = Node(49);root.right.left = Node(23);root.right.right= Node(52);root.right.right.left = Node(50);root.left.left = Node(5);root.left.right = Node(12);root.left.right.right = Node(12); print('Sum of left leaves is {}'.format(sumOfLeftLeaves(root)))
// C# program to find sum of all left leavesusing System;using System.Collections.Generic;class GFG{ // A binary tree node public class Node { public int key; public Node left, right; // A constructor to create a new Node public Node(int key_) { this.key = key_; this.left = null; this.right = null; } }; // Return the sum of left leaf nodes static int sumOfLeftLeaves(Node root) { if(root == null) return 0; // Using a stack_ for Depth-First // Traversal of the tree Stack<Node> stack_ = new Stack<Node>(); stack_.Push(root); // sum holds the sum of all the left leaves int sum = 0; while(stack_.Count > 0) { Node currentNode = stack_.Peek(); stack_.Pop(); if (currentNode.left != null) { stack_.Push(currentNode.left); // Check if currentNode's left // child is a leaf node if(currentNode.left.left == null && currentNode.left.right == null) { // if currentNode is a leaf, // add its data to the sum sum = sum + currentNode.left.key ; } } if (currentNode.right != null) stack_.Push(currentNode.right); } return sum; } // Driver Code public static void Main(String[] args) { Node root = new Node(20); root.left= new Node(9); root.right = new Node(49); root.right.left = new Node(23); root.right.right= new Node(52); root.right.right.left = new Node(50); root.left.left = new Node(5); root.left.right = new Node(12); root.left.right.right = new Node(12); Console.Write("Sum of left leaves is " + sumOfLeftLeaves(root) +"\n"); }} // This code is contributed by Rajput-Ji
<script> // JavaScript program to find sum of all left leaves// A binary tree nodeclass Node{ // A constructor to create a new Node constructor(key_) { this.key = key_; this.left = null; this.right = null; }};// Return the sum of left leaf nodesfunction sumOfLeftLeaves(root){ if(root == null) return 0; // Using a stack_ for Depth-First // Traversal of the tree var stack_ = []; stack_.push(root); // sum holds the sum of all the left leaves var sum = 0; while(stack_.length > 0) { var currentNode = stack_[stack_.length-1]; stack_.pop(); if (currentNode.left != null) { stack_.push(currentNode.left); // Check if currentNode's left // child is a leaf node if(currentNode.left.left == null && currentNode.left.right == null) { // if currentNode is a leaf, // add its data to the sum sum = sum + currentNode.left.key ; } } if (currentNode.right != null) stack_.push(currentNode.right); } return sum;} // Driver Codevar root = new Node(20);root.left= new Node(9);root.right = new Node(49);root.right.left = new Node(23);root.right.right= new Node(52);root.right.right.left = new Node(50);root.left.left = new Node(5);root.left.right = new Node(12);root.left.right.right = new Node(12);document.write("Sum of left leaves is " + sumOfLeftLeaves(root) +"<br>"); </script>
Sum of left leaves is 78
Thanks to Shubham Tambere for suggesting this approach.
BFS Approach: We can do BFS traversal and keep a separate variable for denoting if it is a left child or right child of a node. As soon as we encounter a leaf, we check if it is a left child of its parent or right child of its parent. If it is a left child, we add its value in the sum.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to find sum of all left leaves#include <bits/stdc++.h>using namespace std; // A binary tree nodeclass Node {public: int key; Node *left, *right; // constructor to create a new Node Node(int key_) { key = key_; left = NULL; right = NULL; }}; // Return the sum of left leaf nodesint sumOfLeftLeaves(Node* root){ if (root == NULL) return 0; // A queue of pairs to do bfs traversal // and keep track if the node is a left // or right child if boolean value // is true then it is a left child. queue<pair<Node*, bool> > q; q.push({ root, 0 }); int sum = 0; // do bfs traversal while (!q.empty()) { Node* temp = q.front().first; bool is_left_child = q.front().second; q.pop(); // if temp is a leaf node and // left child of its parent if (!temp->left && !temp->right && is_left_child) sum = sum + temp->key; // if it is not leaf then // push its children nodes // into queue if (temp->left) { // boolean value is true // here because it is left // child of its parent q.push({ temp->left, 1 }); } if (temp->right) { // boolean value is false // here because it is // right child of its parent q.push({ temp->right, 0 }); } } return sum;} // Driver Codeint main(){ Node* root = new Node(20); root->left = new Node(9); root->right = new Node(49); root->right->left = new Node(23); root->right->right = new Node(52); root->right->right->left = new Node(50); root->left->left = new Node(5); root->left->right = new Node(12); root->left->right->right = new Node(12); cout << "Sum of left leaves is " << sumOfLeftLeaves(root) << endl; return 0;}
// Java program to find sum of all left leavesimport java.util.*;class GFG{ // A binary tree nodestatic class Node{ int key; Node left, right; // constructor to create a new Node Node(int key_) { key = key_; left = null; right = null; }};static class pair{ Node first; boolean second; public pair(Node first, boolean second) { this.first = first; this.second = second; } } // Return the sum of left leaf nodesstatic int sumOfLeftLeaves(Node root){ if (root == null) return 0; // A queue of pairs to do bfs traversal // and keep track if the node is a left // or right child if boolean value // is true then it is a left child. Queue<pair > q = new LinkedList<>(); q.add(new pair( root, false )); int sum = 0; // do bfs traversal while (!q.isEmpty()) { Node temp = q.peek().first; boolean is_left_child = q.peek().second; q.remove(); // if temp is a leaf node and // left child of its parent if (is_left_child) sum = sum + temp.key; if(temp.left != null && temp.right != null && is_left_child) sum = sum-temp.key; // if it is not leaf then // push its children nodes // into queue if (temp.left != null) { // boolean value is true // here because it is left // child of its parent q.add(new pair( temp.left, true)); } if (temp.right != null) { // boolean value is false // here because it is // right child of its parent q.add(new pair( temp.right, false)); } } return sum;} // Driver Codepublic static void main(String[] args){ Node root = new Node(20); root.left = new Node(9); root.right = new Node(49); root.right.left = new Node(23); root.right.right = new Node(52); root.right.right.left = new Node(50); root.left.left = new Node(5); root.left.right = new Node(12); root.left.right.right = new Node(12); System.out.print("Sum of left leaves is " + sumOfLeftLeaves(root) +"\n");}} // This code is contributed by gauravrajput1.
# Python3 program to find sum of# all left leavesfrom collections import deque # A binary tree nodeclass Node: def __init__(self, x): self.key = x self.left = None self.right = None # Return the sum of left leaf nodesdef sumOfLeftLeaves(root): if (root == None): return 0 # A queue of pairs to do bfs traversal # and keep track if the node is a left # or right child if boolean value # is true then it is a left child. q = deque() q.append([root, 0]) sum = 0 # Do bfs traversal while (len(q) > 0): temp = q[0][0] is_left_child = q[0][1] q.popleft() # If temp is a leaf node and # left child of its parent if (not temp.left and not temp.right and is_left_child): sum = sum + temp.key # If it is not leaf then # push its children nodes # into queue if (temp.left): # Boolean value is true # here because it is left # child of its parent q.append([temp.left, 1]) if (temp.right): # Boolean value is false # here because it is # right child of its parent q.append([temp.right, 0]) return sum # Driver Codeif __name__ == '__main__': root = Node(20) root.left = Node(9) root.right = Node(49) root.right.left = Node(23) root.right.right = Node(52) root.right.right.left = Node(50) root.left.left = Node(5) root.left.right = Node(12) root.left.right.right = Node(12) print("Sum of left leaves is", sumOfLeftLeaves(root)) # This code is contributed by mohit kumar 29
// C# program to find sum of all left leavesusing System;using System.Collections.Generic;public class GFG{ // A binary tree node public class Node { public int key; public Node left, right; // constructor to create a new Node public Node(int key_) { key = key_; left = null; right = null; } }; public class pair { public Node first; public bool second; public pair(Node first, bool second) { this.first = first; this.second = second; } } // Return the sum of left leaf nodes static int sumOfLeftLeaves(Node root) { if (root == null) return 0; // A queue of pairs to do bfs traversal // and keep track if the node is a left // or right child if bool value // is true then it is a left child. Queue<pair> q = new Queue<pair>(); q.Enqueue(new pair(root, false)); int sum = 0; // do bfs traversal while (q.Count != 0) { Node temp = q.Peek().first; bool is_left_child = q.Peek().second; q.Dequeue(); // if temp is a leaf node and // left child of its parent if (is_left_child) sum = sum + temp.key; if (temp.left != null && temp.right != null && is_left_child) sum = sum - temp.key; // if it is not leaf then // push its children nodes // into queue if (temp.left != null) { // bool value is true // here because it is left // child of its parent q.Enqueue(new pair(temp.left, true)); } if (temp.right != null) { // bool value is false // here because it is // right child of its parent q.Enqueue(new pair(temp.right, false)); } } return sum; } // Driver Code public static void Main(String[] args) { Node root = new Node(20); root.left = new Node(9); root.right = new Node(49); root.right.left = new Node(23); root.right.right = new Node(52); root.right.right.left = new Node(50); root.left.left = new Node(5); root.left.right = new Node(12); root.left.right.right = new Node(12); Console.Write("Sum of left leaves is " + sumOfLeftLeaves(root) + "\n"); }} // This code is contributed by gauravrajput1
<script> // JavaScript program to find sum of all left leaves class Node { constructor(key_) { this.left = null; this.right = null; this.key = key_; } } // Return the sum of left leaf nodes function sumOfLeftLeaves(root) { if (root == null) return 0; // A queue of pairs to do bfs traversal // and keep track if the node is a left // or right child if boolean value // is true then it is a left child. let q = []; q.push([root, false ]); let sum = 0; // do bfs traversal while (q.length > 0) { let temp = q[0][0]; let is_left_child = q[0][1]; q.shift(); // if temp is a leaf node and // left child of its parent if (is_left_child) sum = sum + temp.key; if(temp.left != null && temp.right != null && is_left_child) sum = sum-temp.key; // if it is not leaf then // push its children nodes // into queue if (temp.left != null) { // boolean value is true // here because it is left // child of its parent q.push([temp.left, true]); } if (temp.right != null) { // boolean value is false // here because it is // right child of its parent q.push([temp.right, false]); } } return sum; } let root = new Node(20); root.left = new Node(9); root.right = new Node(49); root.right.left = new Node(23); root.right.right = new Node(52); root.right.right.left = new Node(50); root.left.left = new Node(5); root.left.right = new Node(12); root.left.right.right = new Node(12); document.write("Sum of left leaves is " + sumOfLeftLeaves(root) +"</br>"); </script>
Sum of left leaves is 78
Time Complexity: O(N)Auxiliary Space: O(N)
shrikanth13
andrew1234
sri_srajit
mohit kumar 29
aashish1995
Rajput-Ji
GauravRajput1
tmeid
unknown2108
akshaysingh98088
noob2000
mukesh07
umadevi9616
amartyaghoshgfg
surinderdawra388
adityakumar129
hardikkoriintern
Amazon
Traversal
Tree
Amazon
Traversal
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
AVL Tree | Set 1 (Insertion)
Introduction to Data Structures
What is Data Structure: Types, Classifications and Applications
A program to check if a binary tree is BST or not
Decision Tree
Top 50 Tree Coding Problems for Interviews
Segment Tree | Set 1 (Sum of given range)
Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
Sorted Array to Balanced BST
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n24 Jun, 2022"
},
{
"code": null,
"e": 179,
"s": 52,
"text": "Given a Binary Tree, find the sum of all left leaves in it. For example, sum of all left leaves in below Binary Tree is 5+1=6."
},
{
"code": null,
"e": 374,
"s": 179,
"text": "The idea is to traverse the tree, starting from root. For every node, check if its left subtree is a leaf. If it is, then add it to the result. Following is the implementation of the above idea."
},
{
"code": null,
"e": 378,
"s": 374,
"text": "C++"
},
{
"code": null,
"e": 380,
"s": 378,
"text": "C"
},
{
"code": null,
"e": 385,
"s": 380,
"text": "Java"
},
{
"code": null,
"e": 393,
"s": 385,
"text": "Python3"
},
{
"code": null,
"e": 396,
"s": 393,
"text": "C#"
},
{
"code": null,
"e": 407,
"s": 396,
"text": "Javascript"
},
{
"code": "// A C++ program to find sum of all left leaves#include <bits/stdc++.h>using namespace std; /* A binary tree Node has key, pointer to left and right children */struct Node{ int key; struct Node* left, *right;}; /* Helper function that allocates a new node with the given data and NULL left and right pointer. */Node *newNode(int k){ Node *node = new Node; node->key = k; node->right = node->left = NULL; return node;} // A utility function to check if a given node is leaf or notbool isLeaf(Node *node){ if (node == NULL) return false; if (node->left == NULL && node->right == NULL) return true; return false;} // This function returns sum of all left leaves in a given// binary treeint leftLeavesSum(Node *root){ // Initialize result int res = 0; // Update result if root is not NULL if (root != NULL) { // If left of root is NULL, then add key of // left child if (isLeaf(root->left)) res += root->left->key; else // Else recur for left child of root res += leftLeavesSum(root->left); // Recur for right child of root and update res res += leftLeavesSum(root->right); } // return result return res;} /* Driver program to test above functions*/int main(){ // Let us a construct the Binary Tree struct Node *root = newNode(20); root->left = newNode(9); root->right = newNode(49); root->right->left = newNode(23); root->right->right = newNode(52); root->right->right->left = newNode(50); root->left->left = newNode(5); root->left->right = newNode(12); root->left->right->right = newNode(12); cout << \"Sum of left leaves is \" << leftLeavesSum(root); return 0;} // This code is contributed by Aditya kumar (adityakumar129)",
"e": 2267,
"s": 407,
"text": null
},
{
"code": "// A C++ program to find sum of all left leaves#include <stdio.h>#include <stdlib.h>#include <stdbool.h> /* A binary tree Node has key, pointer to left and right children */struct Node{ int key; struct Node* left, *right;}; /* Helper function that allocates a new node with the given data and NULL left and right pointer. */struct Node *newNode(int k){ struct Node *node = (struct Node *)malloc(sizeof(struct Node)); node->key = k; node->right = node->left = NULL; return node;} // A utility function to check if a given node is leaf or notbool isLeaf(struct Node *node){ if (node == NULL) return false; if (node->left == NULL && node->right == NULL) return true; return false;} // This function returns sum of all left leaves in a given// binary treeint leftLeavesSum(struct Node *root){ // Initialize result int res = 0; // Update result if root is not NULL if (root != NULL) { // If left of root is NULL, then add key of // left child if (isLeaf(root->left)) res += root->left->key; else // Else recur for left child of root res += leftLeavesSum(root->left); // Recur for right child of root and update res res += leftLeavesSum(root->right); } // return result return res;} /* Driver program to test above functions*/int main(){ // Let us a construct the Binary Tree struct Node *root = newNode(20); root->left = newNode(9); root->right = newNode(49); root->right->left = newNode(23); root->right->right = newNode(52); root->right->right->left = newNode(50); root->left->left = newNode(5); root->left->right = newNode(12); root->left->right->right = newNode(12); printf(\"Sum of left leaves is %d\",leftLeavesSum(root)); return 0;} // This code is contributed by Aditya kumar (adityakumar129)",
"e": 4102,
"s": 2267,
"text": null
},
{
"code": "// Java program to find sum of all left leavesclass Node{ int data; Node left, right; Node(int item) { data = item; left = right = null; }} class BinaryTree{ Node root; // A utility function to check if a given node is leaf or not boolean isLeaf(Node node) { if (node == null) return false; if (node.left == null && node.right == null) return true; return false; } // This function returns sum of all left leaves in a given // binary tree int leftLeavesSum(Node node) { // Initialize result int res = 0; // Update result if root is not NULL if (node != null) { // If left of root is NULL, then add key of // left child if (isLeaf(node.left)) res += node.left.data; else // Else recur for left child of root res += leftLeavesSum(node.left); // Recur for right child of root and update res res += leftLeavesSum(node.right); } // return result return res; } // Driver program public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node(20); tree.root.left = new Node(9); tree.root.right = new Node(49); tree.root.left.right = new Node(12); tree.root.left.left = new Node(5); tree.root.right.left = new Node(23); tree.root.right.right = new Node(52); tree.root.left.right.right = new Node(12); tree.root.right.right.left = new Node(50); System.out.println(\"The sum of leaves is \" + tree.leftLeavesSum(tree.root)); }} // This code is contributed by Mayank Jaiswal",
"e": 5900,
"s": 4102,
"text": null
},
{
"code": "# Python program to find sum of all left leaves # A Binary tree nodeclass Node: # Constructor to create a new Node def __init__(self, key): self.key = key self.left = None self.right = None # A utility function to check if a given node is leaf or notdef isLeaf(node): if node is None: return False if node.left is None and node.right is None: return True return False # This function return sum of all left leaves in a# given binary treedef leftLeavesSum(root): # Initialize result res = 0 # Update result if root is not None if root is not None: # If left of root is None, then add key of # left child if isLeaf(root.left): res += root.left.key else: # Else recur for left child of root res += leftLeavesSum(root.left) # Recur for right child of root and update res res += leftLeavesSum(root.right) return res # Driver program to test above function # Let us construct the Binary Tree shown in the above functionroot = Node(20)root.left = Node(9)root.right = Node(49)root.right.left = Node(23) root.right.right = Node(52)root.right.right.left = Node(50)root.left.left = Node(5)root.left.right = Node(12)root.left.right.right = Node(12)print (\"Sum of left leaves is\", leftLeavesSum(root)) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)",
"e": 7306,
"s": 5900,
"text": null
},
{
"code": "using System; // C# program to find sum of all left leavespublic class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} public class BinaryTree{ public Node root; // A utility function to check if a given node is leaf or not public virtual bool isLeaf(Node node) { if (node == null) { return false; } if (node.left == null && node.right == null) { return true; } return false; } // This function returns sum of all left leaves in a given // binary tree public virtual int leftLeavesSum(Node node) { // Initialize result int res = 0; // Update result if root is not NULL if (node != null) { // If left of root is NULL, then add key of // left child if (isLeaf(node.left)) { res += node.left.data; } else // Else recur for left child of root { res += leftLeavesSum(node.left); } // Recur for right child of root and update res res += leftLeavesSum(node.right); } // return result return res; } // Driver program public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(20); tree.root.left = new Node(9); tree.root.right = new Node(49); tree.root.left.right = new Node(12); tree.root.left.left = new Node(5); tree.root.right.left = new Node(23); tree.root.right.right = new Node(52); tree.root.left.right.right = new Node(12); tree.root.right.right.left = new Node(50); Console.WriteLine(\"The sum of leaves is \" + tree.leftLeavesSum(tree.root)); }} // This code is contributed by Shrikant13",
"e": 9223,
"s": 7306,
"text": null
},
{
"code": "<script>// Javascript program to find sum of all left leaves class Node { constructor(k) { this.data = k; this.left = null; this.right = null; } } // A utility function to check if a given node is leaf or not function isLeaf(node) { if (node == null) return false; if (node.left == null && node.right == null) return true; return false; } // This function returns sum of all left leaves in a given // binary tree function leftLeavesSum(node) { // Initialize result let res = 0; // Update result if root is not NULL if (node != null) { // If left of root is NULL, then add key of // left child if (isLeaf(node.left)) res += node.left.data; else // Else recur for left child of root res += leftLeavesSum(node.left); // Recur for right child of root and update res res += leftLeavesSum(node.right); } // return result return res; } // Driver program root = new Node(20); root.left = new Node(9); root.right = new Node(49); root.left.right = new Node(12); root.left.left = new Node(5); root.right.left = new Node(23); root.right.right = new Node(52); root.left.right.right = new Node(12); root.right.right.left = new Node(50); document.write(\"The sum of leaves is \" +leftLeavesSum(root)); // This code is contributed by unknown2108</script>",
"e": 10848,
"s": 9223,
"text": null
},
{
"code": null,
"e": 10873,
"s": 10848,
"text": "Sum of left leaves is 78"
},
{
"code": null,
"e": 10939,
"s": 10873,
"text": "Time Complexity: O(N), where n is number of nodes in Binary Tree."
},
{
"code": null,
"e": 10948,
"s": 10939,
"text": "Chapters"
},
{
"code": null,
"e": 10975,
"s": 10948,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 11025,
"s": 10975,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 11048,
"s": 11025,
"text": "captions off, selected"
},
{
"code": null,
"e": 11056,
"s": 11048,
"text": "English"
},
{
"code": null,
"e": 11074,
"s": 11056,
"text": "default, selected"
},
{
"code": null,
"e": 11098,
"s": 11074,
"text": "This is a modal window."
},
{
"code": null,
"e": 11167,
"s": 11098,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 11189,
"s": 11167,
"text": "End of dialog window."
},
{
"code": null,
"e": 11495,
"s": 11189,
"text": "Following is Another Method to solve the above problem. This solution passes in a sum variable as an accumulator. When a left leaf is encountered, the leaf’s data is added to sum. Time complexity of this method is also O(n). Thanks to Xin Tong (geeksforgeeks userid trent.tong) for suggesting this method."
},
{
"code": null,
"e": 11499,
"s": 11495,
"text": "C++"
},
{
"code": null,
"e": 11504,
"s": 11499,
"text": "Java"
},
{
"code": null,
"e": 11512,
"s": 11504,
"text": "Python3"
},
{
"code": null,
"e": 11515,
"s": 11512,
"text": "C#"
},
{
"code": null,
"e": 11526,
"s": 11515,
"text": "Javascript"
},
{
"code": "// A C++ program to find sum of all left leaves#include <bits/stdc++.h>using namespace std; /* A binary tree Node has key, pointer to left and right children */struct Node{ int key; struct Node* left, *right;}; /* Helper function that allocates a new node with the given data and NULL left and right pointer. */Node *newNode(char k){ Node *node = new Node; node->key = k; node->right = node->left = NULL; return node;} /* Pass in a sum variable as an accumulator */void leftLeavesSumRec(Node *root, bool isleft, int *sum){ if (!root) return; // Check whether this node is a leaf node and is left. if (!root->left && !root->right && isleft) *sum += root->key; // Pass 1 for left and 0 for right leftLeavesSumRec(root->left, 1, sum); leftLeavesSumRec(root->right, 0, sum);} // A wrapper over above recursive functionint leftLeavesSum(Node *root){ int sum = 0; //Initialize result // use the above recursive function to evaluate sum leftLeavesSumRec(root, 0, &sum); return sum;} /* Driver program to test above functions*/int main(){ // Let us construct the Binary Tree shown in the // above figure int sum = 0; struct Node *root = newNode(20); root->left = newNode(9); root->right = newNode(49); root->right->left = newNode(23); root->right->right = newNode(52); root->right->right->left = newNode(50); root->left->left = newNode(5); root->left->right = newNode(12); root->left->right->right = newNode(12); cout << \"Sum of left leaves is \" << leftLeavesSum(root) << endl; return 0;}",
"e": 13190,
"s": 11526,
"text": null
},
{
"code": "// Java program to find sum of all left leavesclass Node{ int data; Node left, right; Node(int item) { data = item; left = right = null; }} // Passing sum as accumulator and implementing pass by reference// of sum variableclass Sum{ int sum = 0;} class BinaryTree{ Node root; /* Pass in a sum variable as an accumulator */ void leftLeavesSumRec(Node node, boolean isleft, Sum summ) { if (node == null) return; // Check whether this node is a leaf node and is left. if (node.left == null && node.right == null && isleft) summ.sum = summ.sum + node.data; // Pass true for left and false for right leftLeavesSumRec(node.left, true, summ); leftLeavesSumRec(node.right, false, summ); } // A wrapper over above recursive function int leftLeavesSum(Node node) { Sum suum = new Sum(); // use the above recursive function to evaluate sum leftLeavesSumRec(node, false, suum); return suum.sum; } // Driver program public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node(20); tree.root.left = new Node(9); tree.root.right = new Node(49); tree.root.left.right = new Node(12); tree.root.left.left = new Node(5); tree.root.right.left = new Node(23); tree.root.right.right = new Node(52); tree.root.left.right.right = new Node(12); tree.root.right.right.left = new Node(50); System.out.println(\"The sum of leaves is \" + tree.leftLeavesSum(tree.root)); }} // This code is contributed by Mayank Jaiswal",
"e": 14917,
"s": 13190,
"text": null
},
{
"code": "# Python program to find sum of all left leaves # A binary tree nodeclass Node: # A constructor to create a new Node def __init__(self, key): self.key = key self.left = None self.right = None def leftLeavesSumRec(root, isLeft, summ): if root is None: return # Check whether this node is a leaf node and is left if root.left is None and root.right is None and isLeft == True: summ[0] += root.key # Pass 1 for left and 0 for right leftLeavesSumRec(root.left, 1, summ) leftLeavesSumRec(root.right, 0, summ) # A wrapper over above recursive functiondef leftLeavesSum(root): summ = [0] # initialize result # Use the above recursive function to evaluate sum leftLeavesSumRec(root, 0, summ) return summ[0] # Driver program to test above function # Let us construct the Binary Tree shown in the# above figureroot = Node(20);root.left= Node(9);root.right = Node(49);root.right.left = Node(23);root.right.right= Node(52);root.right.right.left = Node(50);root.left.left = Node(5);root.left.right = Node(12);root.left.right.right = Node(12); print (\"Sum of left leaves is\", leftLeavesSum(root)) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)",
"e": 16161,
"s": 14917,
"text": null
},
{
"code": "using System; // C# program to find sum of all left leavespublic class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} // Passing sum as accumulator and implementing pass by reference // of sum variable public class Sum{ public int sum = 0;} public class BinaryTree{ public Node root; /* Pass in a sum variable as an accumulator */ public virtual void leftLeavesSumRec(Node node, bool isleft, Sum summ) { if (node == null) { return; } // Check whether this node is a leaf node and is left. if (node.left == null && node.right == null && isleft) { summ.sum = summ.sum + node.data; } // Pass true for left and false for right leftLeavesSumRec(node.left, true, summ); leftLeavesSumRec(node.right, false, summ); } // A wrapper over above recursive function public virtual int leftLeavesSum(Node node) { Sum suum = new Sum(); // use the above recursive function to evaluate sum leftLeavesSumRec(node, false, suum); return suum.sum; } // Driver program public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(20); tree.root.left = new Node(9); tree.root.right = new Node(49); tree.root.left.right = new Node(12); tree.root.left.left = new Node(5); tree.root.right.left = new Node(23); tree.root.right.right = new Node(52); tree.root.left.right.right = new Node(12); tree.root.right.right.left = new Node(50); Console.WriteLine(\"The sum of leaves is \" + tree.leftLeavesSum(tree.root)); }} // This code is contributed by Shrikant13",
"e": 17967,
"s": 16161,
"text": null
},
{
"code": "<script>// javascript program to find sum of all left leavesclass Node { constructor(item) { this.data = item; this.left = this.right = null; }} // Passing sum as accumulator and implementing pass by reference// of sum variableclass Sum {constructor(){ this.sum = 0; }} var root; /* Pass in a sum variable as an accumulator */ function leftLeavesSumRec( node, isleft, summ) { if (node == null) return; // Check whether this node is a leaf node and is left. if (node.left == null && node.right == null && isleft) summ.sum = summ.sum + node.data; // Pass true for left and false for right leftLeavesSumRec(node.left, true, summ); leftLeavesSumRec(node.right, false, summ); } // A wrapper over above recursive function function leftLeavesSum( node) { suum = new Sum(); // use the above recursive function to evaluate sum leftLeavesSumRec(node, false, suum); return suum.sum; } // Driver program root = new Node(20); root.left = new Node(9); root.right = new Node(49); root.left.right = new Node(12); root.left.left = new Node(5); root.right.left = new Node(23); root.right.right = new Node(52); root.left.right.right = new Node(12); root.right.right.left = new Node(50); document.write(\"The sum of leaves is \" + leftLeavesSum(root)); // This code contributed by gauravrajput1</script>",
"e": 19488,
"s": 17967,
"text": null
},
{
"code": null,
"e": 19514,
"s": 19488,
"text": "Sum of left leaves is 78\n"
},
{
"code": null,
"e": 19702,
"s": 19514,
"text": "Following is Another Method to solve the above problem. We can pass bool as parameter in the function to check if it is a left or right node. Time complexity of this method is also O(n). "
},
{
"code": null,
"e": 19704,
"s": 19702,
"text": "C"
},
{
"code": null,
"e": 19709,
"s": 19704,
"text": "Java"
},
{
"code": "#include <stdbool.h>#include <stdio.h>#include <stdlib.h> struct Node { int data; struct Node* left; struct Node* right;}; typedef struct Node str_node; str_node* create(int item);int sumAllLeaftLeaves(str_node* node, bool isLeft); int main(void){ int d = 0; str_node* root = create(20); root->left = create(9); root->right = create(49); root->right->left = create(23); root->right->right = create(52); root->right->right->left = create(50); root->left->left = create(5); root->left->right = create(12); root->left->right->right = create(12); printf(\"\\nSum of left leaves is: %d \", sumAllLeaftLeaves(root, false)); return 0;} str_node* create(int item){ str_node* newnode = (str_node*)malloc(sizeof(str_node)); newnode->data = item; newnode->left = NULL; newnode->right = NULL; return newnode;} int sumAllLeaftLeaves(str_node* node, bool isLeft){ // base case: if (node == NULL) return 0; // check whether this node is a leaf node and is left. if (node->left == NULL && node->right == NULL && isLeft) return node->data; // recursive case return sumAllLeaftLeaves(node->left, true) + sumAllLeaftLeaves(node->right, false);}",
"e": 20947,
"s": 19709,
"text": null
},
{
"code": "class GFG{ static class Node { int data; Node left; Node right; }; static Node str_node; static Node create(int item) { Node newnode = new Node(); newnode.data = item; newnode.left = null; newnode.right = null; return newnode; } static int sumAllLeaftLeaves(Node node, boolean isLeft) { // base case: if (node == null) return 0; // check whether this node is a leaf node and is left. if (node.left == null && node.right == null && isLeft) return node.data; // recursive case return sumAllLeaftLeaves(node.left, true) + sumAllLeaftLeaves(node.right, false); } public static void main(String[] args) { int d = 0; Node root = create(20); root.left = create(9); root.right = create(49); root.right.left = create(23); root.right.right = create(52); root.right.right.left = create(50); root.left.left = create(5); root.left.right = create(12); root.left.right.right = create(12); System.out.printf(\"\\nSum of left leaves is: %d \", sumAllLeaftLeaves(root, false)); }} // This code is contributed by umadevi9616",
"e": 22080,
"s": 20947,
"text": null
},
{
"code": null,
"e": 22107,
"s": 22080,
"text": "Sum of left leaves is: 78 "
},
{
"code": null,
"e": 22129,
"s": 22107,
"text": "Iterative Approach : "
},
{
"code": null,
"e": 22401,
"s": 22129,
"text": "This is the Iterative Way to find the sum of the left leaves. Idea is to perform Depth-First Traversal on the tree (either Inorder, Preorder or Postorder) using a stack and checking if the Left Child is a Leaf node. If it is, then add the nodes value to the sum variable "
},
{
"code": null,
"e": 22405,
"s": 22401,
"text": "C++"
},
{
"code": null,
"e": 22410,
"s": 22405,
"text": "Java"
},
{
"code": null,
"e": 22418,
"s": 22410,
"text": "Python3"
},
{
"code": null,
"e": 22421,
"s": 22418,
"text": "C#"
},
{
"code": null,
"e": 22432,
"s": 22421,
"text": "Javascript"
},
{
"code": "// C++ program to find sum of all left leaves#include<bits/stdc++.h>using namespace std; // A binary tree nodeclass Node{ public: int key; Node* left, *right; // A constructor to create a new Node Node(int key_) { key = key_; left = NULL; right = NULL; }}; // Return the sum of left leaf nodesint sumOfLeftLeaves(Node* root){ if(root == NULL) return 0; // Using a stack_ for Depth-First // Traversal of the tree stack<Node*> stack_; stack_.push(root); // sum holds the sum of all the left leaves int sum = 0; while(stack_.size() > 0) { Node* currentNode = stack_.top(); stack_.pop(); if (currentNode->left != NULL) { stack_.push(currentNode->left); // Check if currentNode's left // child is a leaf node if(currentNode->left->left == NULL && currentNode->left->right == NULL) { // if currentNode is a leaf, // add its data to the sum sum = sum + currentNode->left->key ; } } if (currentNode->right != NULL) stack_.push(currentNode->right); } return sum;} // Driver Codeint main(){ Node *root = new Node(20); root->left= new Node(9); root->right = new Node(49); root->right->left = new Node(23); root->right->right= new Node(52); root->right->right->left = new Node(50); root->left->left = new Node(5); root->left->right = new Node(12); root->left->right->right = new Node(12); cout << \"Sum of left leaves is \" << sumOfLeftLeaves(root) << endl; return 0;} // This code is contributed by Arnab Kundu",
"e": 24172,
"s": 22432,
"text": null
},
{
"code": "// Java program to find sum of all left leavesimport java.util.*;class GFG{ // A binary tree nodestatic class Node{ int key; Node left, right; // A constructor to create a new Node Node(int key_) { this.key = key_; this.left = null; this.right = null; }}; // Return the sum of left leaf nodesstatic int sumOfLeftLeaves(Node root){ if(root == null) return 0; // Using a stack_ for Depth-First // Traversal of the tree Stack<Node> stack_ = new Stack<>(); stack_.push(root); // sum holds the sum of all the left leaves int sum = 0; while(stack_.size() > 0) { Node currentNode = stack_.peek(); stack_.pop(); if (currentNode.left != null) { stack_.add(currentNode.left); // Check if currentNode's left // child is a leaf node if(currentNode.left.left == null && currentNode.left.right == null) { // if currentNode is a leaf, // add its data to the sum sum = sum + currentNode.left.key ; } } if (currentNode.right != null) stack_.add(currentNode.right); } return sum;} // Driver Codepublic static void main(String[] args){ Node root = new Node(20); root.left= new Node(9); root.right = new Node(49); root.right.left = new Node(23); root.right.right= new Node(52); root.right.right.left = new Node(50); root.left.left = new Node(5); root.left.right = new Node(12); root.left.right.right = new Node(12); System.out.print(\"Sum of left leaves is \" + sumOfLeftLeaves(root) +\"\\n\");}} // This code is contributed by aashish1995",
"e": 25916,
"s": 24172,
"text": null
},
{
"code": "# Python3 program to find sum of all left leaves # A binary tree nodeclass Node: # A constructor to create a new Node def __init__(self, key): self.data = key self.left = None self.right = None # Return the sum of left leaf nodesdef sumOfLeftLeaves(root): if(root is None): return # Using a stack for Depth-First Traversal of the tree stack = [] stack.append(root) # sum holds the sum of all the left leaves sum = 0 while len(stack) > 0: currentNode = stack.pop() if currentNode.left is not None: stack.append(currentNode.left) # Check if currentNode's left child is a leaf node if currentNode.left.left is None and currentNode.left.right is None: # if currentNode is a leaf, add its data to the sum sum = sum + currentNode.left.data if currentNode.right is not None: stack.append(currentNode.right) return sum # Driver Coderoot = Node(20);root.left= Node(9);root.right = Node(49);root.right.left = Node(23);root.right.right= Node(52);root.right.right.left = Node(50);root.left.left = Node(5);root.left.right = Node(12);root.left.right.right = Node(12); print('Sum of left leaves is {}'.format(sumOfLeftLeaves(root)))",
"e": 27223,
"s": 25916,
"text": null
},
{
"code": "// C# program to find sum of all left leavesusing System;using System.Collections.Generic;class GFG{ // A binary tree node public class Node { public int key; public Node left, right; // A constructor to create a new Node public Node(int key_) { this.key = key_; this.left = null; this.right = null; } }; // Return the sum of left leaf nodes static int sumOfLeftLeaves(Node root) { if(root == null) return 0; // Using a stack_ for Depth-First // Traversal of the tree Stack<Node> stack_ = new Stack<Node>(); stack_.Push(root); // sum holds the sum of all the left leaves int sum = 0; while(stack_.Count > 0) { Node currentNode = stack_.Peek(); stack_.Pop(); if (currentNode.left != null) { stack_.Push(currentNode.left); // Check if currentNode's left // child is a leaf node if(currentNode.left.left == null && currentNode.left.right == null) { // if currentNode is a leaf, // add its data to the sum sum = sum + currentNode.left.key ; } } if (currentNode.right != null) stack_.Push(currentNode.right); } return sum; } // Driver Code public static void Main(String[] args) { Node root = new Node(20); root.left= new Node(9); root.right = new Node(49); root.right.left = new Node(23); root.right.right= new Node(52); root.right.right.left = new Node(50); root.left.left = new Node(5); root.left.right = new Node(12); root.left.right.right = new Node(12); Console.Write(\"Sum of left leaves is \" + sumOfLeftLeaves(root) +\"\\n\"); }} // This code is contributed by Rajput-Ji",
"e": 29000,
"s": 27223,
"text": null
},
{
"code": "<script> // JavaScript program to find sum of all left leaves// A binary tree nodeclass Node{ // A constructor to create a new Node constructor(key_) { this.key = key_; this.left = null; this.right = null; }};// Return the sum of left leaf nodesfunction sumOfLeftLeaves(root){ if(root == null) return 0; // Using a stack_ for Depth-First // Traversal of the tree var stack_ = []; stack_.push(root); // sum holds the sum of all the left leaves var sum = 0; while(stack_.length > 0) { var currentNode = stack_[stack_.length-1]; stack_.pop(); if (currentNode.left != null) { stack_.push(currentNode.left); // Check if currentNode's left // child is a leaf node if(currentNode.left.left == null && currentNode.left.right == null) { // if currentNode is a leaf, // add its data to the sum sum = sum + currentNode.left.key ; } } if (currentNode.right != null) stack_.push(currentNode.right); } return sum;} // Driver Codevar root = new Node(20);root.left= new Node(9);root.right = new Node(49);root.right.left = new Node(23);root.right.right= new Node(52);root.right.right.left = new Node(50);root.left.left = new Node(5);root.left.right = new Node(12);root.left.right.right = new Node(12);document.write(\"Sum of left leaves is \" + sumOfLeftLeaves(root) +\"<br>\"); </script>",
"e": 30400,
"s": 29000,
"text": null
},
{
"code": null,
"e": 30426,
"s": 30400,
"text": "Sum of left leaves is 78\n"
},
{
"code": null,
"e": 30482,
"s": 30426,
"text": "Thanks to Shubham Tambere for suggesting this approach."
},
{
"code": null,
"e": 30769,
"s": 30482,
"text": "BFS Approach: We can do BFS traversal and keep a separate variable for denoting if it is a left child or right child of a node. As soon as we encounter a leaf, we check if it is a left child of its parent or right child of its parent. If it is a left child, we add its value in the sum."
},
{
"code": null,
"e": 30820,
"s": 30769,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 30824,
"s": 30820,
"text": "C++"
},
{
"code": null,
"e": 30829,
"s": 30824,
"text": "Java"
},
{
"code": null,
"e": 30837,
"s": 30829,
"text": "Python3"
},
{
"code": null,
"e": 30840,
"s": 30837,
"text": "C#"
},
{
"code": null,
"e": 30851,
"s": 30840,
"text": "Javascript"
},
{
"code": "// C++ program to find sum of all left leaves#include <bits/stdc++.h>using namespace std; // A binary tree nodeclass Node {public: int key; Node *left, *right; // constructor to create a new Node Node(int key_) { key = key_; left = NULL; right = NULL; }}; // Return the sum of left leaf nodesint sumOfLeftLeaves(Node* root){ if (root == NULL) return 0; // A queue of pairs to do bfs traversal // and keep track if the node is a left // or right child if boolean value // is true then it is a left child. queue<pair<Node*, bool> > q; q.push({ root, 0 }); int sum = 0; // do bfs traversal while (!q.empty()) { Node* temp = q.front().first; bool is_left_child = q.front().second; q.pop(); // if temp is a leaf node and // left child of its parent if (!temp->left && !temp->right && is_left_child) sum = sum + temp->key; // if it is not leaf then // push its children nodes // into queue if (temp->left) { // boolean value is true // here because it is left // child of its parent q.push({ temp->left, 1 }); } if (temp->right) { // boolean value is false // here because it is // right child of its parent q.push({ temp->right, 0 }); } } return sum;} // Driver Codeint main(){ Node* root = new Node(20); root->left = new Node(9); root->right = new Node(49); root->right->left = new Node(23); root->right->right = new Node(52); root->right->right->left = new Node(50); root->left->left = new Node(5); root->left->right = new Node(12); root->left->right->right = new Node(12); cout << \"Sum of left leaves is \" << sumOfLeftLeaves(root) << endl; return 0;}",
"e": 32760,
"s": 30851,
"text": null
},
{
"code": "// Java program to find sum of all left leavesimport java.util.*;class GFG{ // A binary tree nodestatic class Node{ int key; Node left, right; // constructor to create a new Node Node(int key_) { key = key_; left = null; right = null; }};static class pair{ Node first; boolean second; public pair(Node first, boolean second) { this.first = first; this.second = second; } } // Return the sum of left leaf nodesstatic int sumOfLeftLeaves(Node root){ if (root == null) return 0; // A queue of pairs to do bfs traversal // and keep track if the node is a left // or right child if boolean value // is true then it is a left child. Queue<pair > q = new LinkedList<>(); q.add(new pair( root, false )); int sum = 0; // do bfs traversal while (!q.isEmpty()) { Node temp = q.peek().first; boolean is_left_child = q.peek().second; q.remove(); // if temp is a leaf node and // left child of its parent if (is_left_child) sum = sum + temp.key; if(temp.left != null && temp.right != null && is_left_child) sum = sum-temp.key; // if it is not leaf then // push its children nodes // into queue if (temp.left != null) { // boolean value is true // here because it is left // child of its parent q.add(new pair( temp.left, true)); } if (temp.right != null) { // boolean value is false // here because it is // right child of its parent q.add(new pair( temp.right, false)); } } return sum;} // Driver Codepublic static void main(String[] args){ Node root = new Node(20); root.left = new Node(9); root.right = new Node(49); root.right.left = new Node(23); root.right.right = new Node(52); root.right.right.left = new Node(50); root.left.left = new Node(5); root.left.right = new Node(12); root.left.right.right = new Node(12); System.out.print(\"Sum of left leaves is \" + sumOfLeftLeaves(root) +\"\\n\");}} // This code is contributed by gauravrajput1.",
"e": 35028,
"s": 32760,
"text": null
},
{
"code": "# Python3 program to find sum of# all left leavesfrom collections import deque # A binary tree nodeclass Node: def __init__(self, x): self.key = x self.left = None self.right = None # Return the sum of left leaf nodesdef sumOfLeftLeaves(root): if (root == None): return 0 # A queue of pairs to do bfs traversal # and keep track if the node is a left # or right child if boolean value # is true then it is a left child. q = deque() q.append([root, 0]) sum = 0 # Do bfs traversal while (len(q) > 0): temp = q[0][0] is_left_child = q[0][1] q.popleft() # If temp is a leaf node and # left child of its parent if (not temp.left and not temp.right and is_left_child): sum = sum + temp.key # If it is not leaf then # push its children nodes # into queue if (temp.left): # Boolean value is true # here because it is left # child of its parent q.append([temp.left, 1]) if (temp.right): # Boolean value is false # here because it is # right child of its parent q.append([temp.right, 0]) return sum # Driver Codeif __name__ == '__main__': root = Node(20) root.left = Node(9) root.right = Node(49) root.right.left = Node(23) root.right.right = Node(52) root.right.right.left = Node(50) root.left.left = Node(5) root.left.right = Node(12) root.left.right.right = Node(12) print(\"Sum of left leaves is\", sumOfLeftLeaves(root)) # This code is contributed by mohit kumar 29",
"e": 36788,
"s": 35028,
"text": null
},
{
"code": "// C# program to find sum of all left leavesusing System;using System.Collections.Generic;public class GFG{ // A binary tree node public class Node { public int key; public Node left, right; // constructor to create a new Node public Node(int key_) { key = key_; left = null; right = null; } }; public class pair { public Node first; public bool second; public pair(Node first, bool second) { this.first = first; this.second = second; } } // Return the sum of left leaf nodes static int sumOfLeftLeaves(Node root) { if (root == null) return 0; // A queue of pairs to do bfs traversal // and keep track if the node is a left // or right child if bool value // is true then it is a left child. Queue<pair> q = new Queue<pair>(); q.Enqueue(new pair(root, false)); int sum = 0; // do bfs traversal while (q.Count != 0) { Node temp = q.Peek().first; bool is_left_child = q.Peek().second; q.Dequeue(); // if temp is a leaf node and // left child of its parent if (is_left_child) sum = sum + temp.key; if (temp.left != null && temp.right != null && is_left_child) sum = sum - temp.key; // if it is not leaf then // push its children nodes // into queue if (temp.left != null) { // bool value is true // here because it is left // child of its parent q.Enqueue(new pair(temp.left, true)); } if (temp.right != null) { // bool value is false // here because it is // right child of its parent q.Enqueue(new pair(temp.right, false)); } } return sum; } // Driver Code public static void Main(String[] args) { Node root = new Node(20); root.left = new Node(9); root.right = new Node(49); root.right.left = new Node(23); root.right.right = new Node(52); root.right.right.left = new Node(50); root.left.left = new Node(5); root.left.right = new Node(12); root.left.right.right = new Node(12); Console.Write(\"Sum of left leaves is \" + sumOfLeftLeaves(root) + \"\\n\"); }} // This code is contributed by gauravrajput1",
"e": 39102,
"s": 36788,
"text": null
},
{
"code": "<script> // JavaScript program to find sum of all left leaves class Node { constructor(key_) { this.left = null; this.right = null; this.key = key_; } } // Return the sum of left leaf nodes function sumOfLeftLeaves(root) { if (root == null) return 0; // A queue of pairs to do bfs traversal // and keep track if the node is a left // or right child if boolean value // is true then it is a left child. let q = []; q.push([root, false ]); let sum = 0; // do bfs traversal while (q.length > 0) { let temp = q[0][0]; let is_left_child = q[0][1]; q.shift(); // if temp is a leaf node and // left child of its parent if (is_left_child) sum = sum + temp.key; if(temp.left != null && temp.right != null && is_left_child) sum = sum-temp.key; // if it is not leaf then // push its children nodes // into queue if (temp.left != null) { // boolean value is true // here because it is left // child of its parent q.push([temp.left, true]); } if (temp.right != null) { // boolean value is false // here because it is // right child of its parent q.push([temp.right, false]); } } return sum; } let root = new Node(20); root.left = new Node(9); root.right = new Node(49); root.right.left = new Node(23); root.right.right = new Node(52); root.right.right.left = new Node(50); root.left.left = new Node(5); root.left.right = new Node(12); root.left.right.right = new Node(12); document.write(\"Sum of left leaves is \" + sumOfLeftLeaves(root) +\"</br>\"); </script>",
"e": 41140,
"s": 39102,
"text": null
},
{
"code": null,
"e": 41166,
"s": 41140,
"text": "Sum of left leaves is 78\n"
},
{
"code": null,
"e": 41209,
"s": 41166,
"text": "Time Complexity: O(N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 41221,
"s": 41209,
"text": "shrikanth13"
},
{
"code": null,
"e": 41232,
"s": 41221,
"text": "andrew1234"
},
{
"code": null,
"e": 41243,
"s": 41232,
"text": "sri_srajit"
},
{
"code": null,
"e": 41258,
"s": 41243,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 41270,
"s": 41258,
"text": "aashish1995"
},
{
"code": null,
"e": 41280,
"s": 41270,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 41294,
"s": 41280,
"text": "GauravRajput1"
},
{
"code": null,
"e": 41300,
"s": 41294,
"text": "tmeid"
},
{
"code": null,
"e": 41312,
"s": 41300,
"text": "unknown2108"
},
{
"code": null,
"e": 41329,
"s": 41312,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 41338,
"s": 41329,
"text": "noob2000"
},
{
"code": null,
"e": 41347,
"s": 41338,
"text": "mukesh07"
},
{
"code": null,
"e": 41359,
"s": 41347,
"text": "umadevi9616"
},
{
"code": null,
"e": 41375,
"s": 41359,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 41392,
"s": 41375,
"text": "surinderdawra388"
},
{
"code": null,
"e": 41407,
"s": 41392,
"text": "adityakumar129"
},
{
"code": null,
"e": 41424,
"s": 41407,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 41431,
"s": 41424,
"text": "Amazon"
},
{
"code": null,
"e": 41441,
"s": 41431,
"text": "Traversal"
},
{
"code": null,
"e": 41446,
"s": 41441,
"text": "Tree"
},
{
"code": null,
"e": 41453,
"s": 41446,
"text": "Amazon"
},
{
"code": null,
"e": 41463,
"s": 41453,
"text": "Traversal"
},
{
"code": null,
"e": 41468,
"s": 41463,
"text": "Tree"
},
{
"code": null,
"e": 41566,
"s": 41468,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 41595,
"s": 41566,
"text": "AVL Tree | Set 1 (Insertion)"
},
{
"code": null,
"e": 41627,
"s": 41595,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 41691,
"s": 41627,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 41741,
"s": 41691,
"text": "A program to check if a binary tree is BST or not"
},
{
"code": null,
"e": 41755,
"s": 41741,
"text": "Decision Tree"
},
{
"code": null,
"e": 41798,
"s": 41755,
"text": "Top 50 Tree Coding Problems for Interviews"
},
{
"code": null,
"e": 41840,
"s": 41798,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 41910,
"s": 41840,
"text": "Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)"
},
{
"code": null,
"e": 41993,
"s": 41910,
"text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree"
}
] |
Generative Adversarial Network (GAN)
|
15 Jan, 2019
Generative Adversarial Networks (GANs) are a powerful class of neural networks that are used for unsupervised learning. It was developed and introduced by Ian J. Goodfellow in 2014. GANs are basically made up of a system of two competing neural network models which compete with each other and are able to analyze, capture and copy the variations within a dataset.
Why were GANs developed in the first place?It has been noticed most of the mainstream neural nets can be easily fooled into misclassifying things by adding only a small amount of noise into the original data. Surprisingly, the model after adding noise has higher confidence in the wrong prediction than when it predicted correctly. The reason for such adversary is that most machine learning models learn from a limited amount of data, which is a huge drawback, as it is prone to overfitting. Also, the mapping between the input and the output is almost linear. Although, it may seem that the boundaries of separation between the various classes are linear, but in reality, they are composed of linearities and even a small change in a point in the feature space might lead to misclassification of data.
How does GANs work?
Generative Adversarial Networks (GANs) can be broken down into three parts:
Generative: To learn a generative model, which describes how data is generated in terms of a probabilistic model.
Adversarial: The training of a model is done in an adversarial setting.
Networks: Use deep neural networks as the artificial intelligence (AI) algorithms for training purpose.
In GANs, there is a generator and a discriminator. The Generator generates fake samples of data(be it an image, audio, etc.) and tries to fool the Discriminator. The Discriminator, on the other hand, tries to distinguish between the real and fake samples. The Generator and the Discriminator are both Neural Networks and they both run in competition with each other in the training phase. The steps are repeated several times and in this, the Generator and Discriminator get better and better in their respective jobs after each repetition. The working can be visualized by the diagram given below:
Here, the generative model captures the distribution of data and is trained in such a manner that it tries to maximize the probability of the Discriminator in making a mistake. The Discriminator, on the other hand, is based on a model that estimates the probability that the sample that it got is received from the training data and not from the Generator.The GANs are formulated as a minimax game, where the Discriminator is trying to minimize its reward V(D, G) and the Generator is trying to minimize the Discriminator’s reward or in other words, maximize its loss. It can be mathematically described by the formula below:
where,G = GeneratorD = DiscriminatorPdata(x) = distribution of real dataP(z) = distribution of generatorx = sample from Pdata(x)z = sample from P(z)D(x) = Discriminator networkG(z) = Generator network
So, basically, training a GAN has two parts:
Part 1: The Discriminator is trained while the Generator is idle. In this phase, the network is only forward propagated and no back-propagation is done. The Discriminator is trained on real data for n epochs, and see if it can correctly predict them as real. Also, in this phase, the Discriminator is also trained on the fake generated data from the Generator and see if it can correctly predict them as fake.
Part 2: The Generator is trained while the Discriminator is idle. After the Discriminator is trained by the generated fake data of the Generator, we can get its predictions and use the results for training the Generator and get better from the previous state to try and fool the Discriminator.
The above method is repeated for a few epochs and then manually check the fake data if it seems genuine. If it seems acceptable, then the training is stopped, otherwise, its allowed to continue for few more epochs.
Different types of GANs:GANs are now a very active topic of research and there have been many different types of GAN implementation. Some of the important ones that are actively being used currently are described below:
Vanilla GAN: This is the simplest type GAN. Here, the Generator and the Discriminator are simple multi-layer perceptrons. In vanilla GAN, the algorithm is really simple, it tries to optimize the mathematical equation using stochastic gradient descent.Conditional GAN (CGAN): CGAN can be described as a deep learning method in which some conditional parameters are put into place. In CGAN, an additional parameter ‘y’ is added to the Generator for generating the corresponding data. Labels are also put into the input to the Discriminator in order for the Discriminator to help distinguish the real data from the fake generated data.Deep Convolutional GAN (DCGAN): DCGAN is one of the most popular also the most successful implementation of GAN. It is composed of ConvNets in place of multi-layer perceptrons. The ConvNets are implemented without max pooling, which is in fact replaced by convolutional stride. Also, the layers are not fully connected.Laplacian Pyramid GAN (LAPGAN): The Laplacian pyramid is a linear invertible image representation consisting of a set of band-pass images, spaced an octave apart, plus a low-frequency residual. This approach uses multiple numbers of Generator and Discriminator networks and different levels of the Laplacian Pyramid. This approach is mainly used because it produces very high-quality images. The image is down-sampled at first at each layer of the pyramid and then it is again up-scaled at each layer in a backward pass where the image acquires some noise from the Conditional GAN at these layers until it reaches its original size.Super Resolution GAN (SRGAN): SRGAN as the name suggests is a way of designing a GAN in which a deep neural network is used along with an adversarial network in order to produce higher resolution images. This type of GAN is particularly useful in optimally up-scaling native low-resolution images to enhance its details minimizing errors while doing so.
Vanilla GAN: This is the simplest type GAN. Here, the Generator and the Discriminator are simple multi-layer perceptrons. In vanilla GAN, the algorithm is really simple, it tries to optimize the mathematical equation using stochastic gradient descent.
Conditional GAN (CGAN): CGAN can be described as a deep learning method in which some conditional parameters are put into place. In CGAN, an additional parameter ‘y’ is added to the Generator for generating the corresponding data. Labels are also put into the input to the Discriminator in order for the Discriminator to help distinguish the real data from the fake generated data.
Deep Convolutional GAN (DCGAN): DCGAN is one of the most popular also the most successful implementation of GAN. It is composed of ConvNets in place of multi-layer perceptrons. The ConvNets are implemented without max pooling, which is in fact replaced by convolutional stride. Also, the layers are not fully connected.
Laplacian Pyramid GAN (LAPGAN): The Laplacian pyramid is a linear invertible image representation consisting of a set of band-pass images, spaced an octave apart, plus a low-frequency residual. This approach uses multiple numbers of Generator and Discriminator networks and different levels of the Laplacian Pyramid. This approach is mainly used because it produces very high-quality images. The image is down-sampled at first at each layer of the pyramid and then it is again up-scaled at each layer in a backward pass where the image acquires some noise from the Conditional GAN at these layers until it reaches its original size.
Super Resolution GAN (SRGAN): SRGAN as the name suggests is a way of designing a GAN in which a deep neural network is used along with an adversarial network in order to produce higher resolution images. This type of GAN is particularly useful in optimally up-scaling native low-resolution images to enhance its details minimizing errors while doing so.
Sample Python code implementing a Generative Adversarial Network:GANs are very computationally expensive. They require high powered GPUs and a lot of time (a large number of epochs) to produce good results. For our example, we will be using the famous MNIST dataset and use it to produce a clone of a random digit.
# importing the necessary libraries and the MNIST datasetimport tensorflow as tfimport numpy as npimport matplotlib.pyplot as pltfrom tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data") # defining functions for the two networks.# Both the networks have two hidden layers# and an output layer which are densely or # fully connected layers defining the # Generator network functiondef generator(z, reuse = None): with tf.variable_scope('gen', reuse = reuse): hidden1 = tf.layers.dense(inputs = z, units = 128, activation = tf.nn.leaky_relu) hidden2 = tf.layers.dense(inputs = hidden1, units = 128, activation = tf.nn.leaky_relu) output = tf.layers.dense(inputs = hidden2, units = 784, activation = tf.nn.tanh) return output # defining the Discriminator network function def discriminator(X, reuse = None): with tf.variable_scope('dis', reuse = reuse): hidden1 = tf.layers.dense(inputs = X, units = 128, activation = tf.nn.leaky_relu) hidden2 = tf.layers.dense(inputs = hidden1, units = 128, activation = tf.nn.leaky_relu) logits = tf.layers.dense(hidden2, units = 1) output = tf.sigmoid(logits) return output, logits # creating placeholders for the outputstf.reset_default_graph() real_images = tf.placeholder(tf.float32, shape =[None, 784])z = tf.placeholder(tf.float32, shape =[None, 100]) G = generator(z)D_output_real, D_logits_real = discriminator(real_images)D_output_fake, D_logits_fake = discriminator(G, reuse = True) # defining the loss functiondef loss_func(logits_in, labels_in): return tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits( logits = logits_in, labels = labels_in)) # Smoothing for generalizationD_real_loss = loss_func(D_logits_real, tf.ones_like(D_logits_real)*0.9)D_fake_loss = loss_func(D_logits_fake, tf.zeros_like(D_logits_real))D_loss = D_real_loss + D_fake_loss G_loss = loss_func(D_logits_fake, tf.ones_like(D_logits_fake)) # defining the learning rate, batch size,# number of epochs and using the Adam optimizerlr = 0.001 # learning rate # Do this when multiple networks# interact with each other # returns all variables created(the two# variable scopes) and makes trainable truetvars = tf.trainable_variables() d_vars =[var for var in tvars if 'dis' in var.name]g_vars =[var for var in tvars if 'gen' in var.name] D_trainer = tf.train.AdamOptimizer(lr).minimize(D_loss, var_list = d_vars)G_trainer = tf.train.AdamOptimizer(lr).minimize(G_loss, var_list = g_vars) batch_size = 100 # batch sizeepochs = 500 # number of epochs. The higher the better the resultinit = tf.global_variables_initializer() # creating a session to train the networkssamples =[] # generator examples with tf.Session() as sess: sess.run(init) for epoch in range(epochs): num_batches = mnist.train.num_examples//batch_size for i in range(num_batches): batch = mnist.train.next_batch(batch_size) batch_images = batch[0].reshape((batch_size, 784)) batch_images = batch_images * 2-1 batch_z = np.random.uniform(-1, 1, size =(batch_size, 100)) _= sess.run(D_trainer, feed_dict ={real_images:batch_images, z:batch_z}) _= sess.run(G_trainer, feed_dict ={z:batch_z}) print("on epoch{}".format(epoch)) sample_z = np.random.uniform(-1, 1, size =(1, 100)) gen_sample = sess.run(generator(z, reuse = True), feed_dict ={z:sample_z}) samples.append(gen_sample) # result after 0th epochplt.imshow(samples[0].reshape(28, 28)) # result after 499th epochplt.imshow(samples[49].reshape(28, 28))
on epoch0
on epoch1
...
...
...
on epoch498
on epoch499
Result after 0th epoch:Resulr after 499th epoch:
So, from the above example, we see that in the first image after 0th epoch, the pixels are scattered all over the place and we couldn’t figure anything out from it.But from the second image, we could see that the pixels are more systematically organized and we could figure out that it is the digit ‘7’ that the code has randomly chosen and the network has tried to make a clone of it. In our example, we have taken 500 as the number of epochs. But you could increase that number to further refine your result.
Advanced Computer Subject
Machine Learning
Python
Technical Scripter
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n15 Jan, 2019"
},
{
"code": null,
"e": 419,
"s": 54,
"text": "Generative Adversarial Networks (GANs) are a powerful class of neural networks that are used for unsupervised learning. It was developed and introduced by Ian J. Goodfellow in 2014. GANs are basically made up of a system of two competing neural network models which compete with each other and are able to analyze, capture and copy the variations within a dataset."
},
{
"code": null,
"e": 1223,
"s": 419,
"text": "Why were GANs developed in the first place?It has been noticed most of the mainstream neural nets can be easily fooled into misclassifying things by adding only a small amount of noise into the original data. Surprisingly, the model after adding noise has higher confidence in the wrong prediction than when it predicted correctly. The reason for such adversary is that most machine learning models learn from a limited amount of data, which is a huge drawback, as it is prone to overfitting. Also, the mapping between the input and the output is almost linear. Although, it may seem that the boundaries of separation between the various classes are linear, but in reality, they are composed of linearities and even a small change in a point in the feature space might lead to misclassification of data."
},
{
"code": null,
"e": 1243,
"s": 1223,
"text": "How does GANs work?"
},
{
"code": null,
"e": 1319,
"s": 1243,
"text": "Generative Adversarial Networks (GANs) can be broken down into three parts:"
},
{
"code": null,
"e": 1433,
"s": 1319,
"text": "Generative: To learn a generative model, which describes how data is generated in terms of a probabilistic model."
},
{
"code": null,
"e": 1505,
"s": 1433,
"text": "Adversarial: The training of a model is done in an adversarial setting."
},
{
"code": null,
"e": 1609,
"s": 1505,
"text": "Networks: Use deep neural networks as the artificial intelligence (AI) algorithms for training purpose."
},
{
"code": null,
"e": 2208,
"s": 1609,
"text": "In GANs, there is a generator and a discriminator. The Generator generates fake samples of data(be it an image, audio, etc.) and tries to fool the Discriminator. The Discriminator, on the other hand, tries to distinguish between the real and fake samples. The Generator and the Discriminator are both Neural Networks and they both run in competition with each other in the training phase. The steps are repeated several times and in this, the Generator and Discriminator get better and better in their respective jobs after each repetition. The working can be visualized by the diagram given below:"
},
{
"code": null,
"e": 2834,
"s": 2208,
"text": "Here, the generative model captures the distribution of data and is trained in such a manner that it tries to maximize the probability of the Discriminator in making a mistake. The Discriminator, on the other hand, is based on a model that estimates the probability that the sample that it got is received from the training data and not from the Generator.The GANs are formulated as a minimax game, where the Discriminator is trying to minimize its reward V(D, G) and the Generator is trying to minimize the Discriminator’s reward or in other words, maximize its loss. It can be mathematically described by the formula below:"
},
{
"code": null,
"e": 3035,
"s": 2834,
"text": "where,G = GeneratorD = DiscriminatorPdata(x) = distribution of real dataP(z) = distribution of generatorx = sample from Pdata(x)z = sample from P(z)D(x) = Discriminator networkG(z) = Generator network"
},
{
"code": null,
"e": 3080,
"s": 3035,
"text": "So, basically, training a GAN has two parts:"
},
{
"code": null,
"e": 3490,
"s": 3080,
"text": "Part 1: The Discriminator is trained while the Generator is idle. In this phase, the network is only forward propagated and no back-propagation is done. The Discriminator is trained on real data for n epochs, and see if it can correctly predict them as real. Also, in this phase, the Discriminator is also trained on the fake generated data from the Generator and see if it can correctly predict them as fake."
},
{
"code": null,
"e": 3784,
"s": 3490,
"text": "Part 2: The Generator is trained while the Discriminator is idle. After the Discriminator is trained by the generated fake data of the Generator, we can get its predictions and use the results for training the Generator and get better from the previous state to try and fool the Discriminator."
},
{
"code": null,
"e": 3999,
"s": 3784,
"text": "The above method is repeated for a few epochs and then manually check the fake data if it seems genuine. If it seems acceptable, then the training is stopped, otherwise, its allowed to continue for few more epochs."
},
{
"code": null,
"e": 4219,
"s": 3999,
"text": "Different types of GANs:GANs are now a very active topic of research and there have been many different types of GAN implementation. Some of the important ones that are actively being used currently are described below:"
},
{
"code": null,
"e": 6156,
"s": 4219,
"text": "Vanilla GAN: This is the simplest type GAN. Here, the Generator and the Discriminator are simple multi-layer perceptrons. In vanilla GAN, the algorithm is really simple, it tries to optimize the mathematical equation using stochastic gradient descent.Conditional GAN (CGAN): CGAN can be described as a deep learning method in which some conditional parameters are put into place. In CGAN, an additional parameter ‘y’ is added to the Generator for generating the corresponding data. Labels are also put into the input to the Discriminator in order for the Discriminator to help distinguish the real data from the fake generated data.Deep Convolutional GAN (DCGAN): DCGAN is one of the most popular also the most successful implementation of GAN. It is composed of ConvNets in place of multi-layer perceptrons. The ConvNets are implemented without max pooling, which is in fact replaced by convolutional stride. Also, the layers are not fully connected.Laplacian Pyramid GAN (LAPGAN): The Laplacian pyramid is a linear invertible image representation consisting of a set of band-pass images, spaced an octave apart, plus a low-frequency residual. This approach uses multiple numbers of Generator and Discriminator networks and different levels of the Laplacian Pyramid. This approach is mainly used because it produces very high-quality images. The image is down-sampled at first at each layer of the pyramid and then it is again up-scaled at each layer in a backward pass where the image acquires some noise from the Conditional GAN at these layers until it reaches its original size.Super Resolution GAN (SRGAN): SRGAN as the name suggests is a way of designing a GAN in which a deep neural network is used along with an adversarial network in order to produce higher resolution images. This type of GAN is particularly useful in optimally up-scaling native low-resolution images to enhance its details minimizing errors while doing so."
},
{
"code": null,
"e": 6408,
"s": 6156,
"text": "Vanilla GAN: This is the simplest type GAN. Here, the Generator and the Discriminator are simple multi-layer perceptrons. In vanilla GAN, the algorithm is really simple, it tries to optimize the mathematical equation using stochastic gradient descent."
},
{
"code": null,
"e": 6790,
"s": 6408,
"text": "Conditional GAN (CGAN): CGAN can be described as a deep learning method in which some conditional parameters are put into place. In CGAN, an additional parameter ‘y’ is added to the Generator for generating the corresponding data. Labels are also put into the input to the Discriminator in order for the Discriminator to help distinguish the real data from the fake generated data."
},
{
"code": null,
"e": 7110,
"s": 6790,
"text": "Deep Convolutional GAN (DCGAN): DCGAN is one of the most popular also the most successful implementation of GAN. It is composed of ConvNets in place of multi-layer perceptrons. The ConvNets are implemented without max pooling, which is in fact replaced by convolutional stride. Also, the layers are not fully connected."
},
{
"code": null,
"e": 7743,
"s": 7110,
"text": "Laplacian Pyramid GAN (LAPGAN): The Laplacian pyramid is a linear invertible image representation consisting of a set of band-pass images, spaced an octave apart, plus a low-frequency residual. This approach uses multiple numbers of Generator and Discriminator networks and different levels of the Laplacian Pyramid. This approach is mainly used because it produces very high-quality images. The image is down-sampled at first at each layer of the pyramid and then it is again up-scaled at each layer in a backward pass where the image acquires some noise from the Conditional GAN at these layers until it reaches its original size."
},
{
"code": null,
"e": 8097,
"s": 7743,
"text": "Super Resolution GAN (SRGAN): SRGAN as the name suggests is a way of designing a GAN in which a deep neural network is used along with an adversarial network in order to produce higher resolution images. This type of GAN is particularly useful in optimally up-scaling native low-resolution images to enhance its details minimizing errors while doing so."
},
{
"code": null,
"e": 8413,
"s": 8097,
"text": " Sample Python code implementing a Generative Adversarial Network:GANs are very computationally expensive. They require high powered GPUs and a lot of time (a large number of epochs) to produce good results. For our example, we will be using the famous MNIST dataset and use it to produce a clone of a random digit."
},
{
"code": "# importing the necessary libraries and the MNIST datasetimport tensorflow as tfimport numpy as npimport matplotlib.pyplot as pltfrom tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets(\"MNIST_data\") # defining functions for the two networks.# Both the networks have two hidden layers# and an output layer which are densely or # fully connected layers defining the # Generator network functiondef generator(z, reuse = None): with tf.variable_scope('gen', reuse = reuse): hidden1 = tf.layers.dense(inputs = z, units = 128, activation = tf.nn.leaky_relu) hidden2 = tf.layers.dense(inputs = hidden1, units = 128, activation = tf.nn.leaky_relu) output = tf.layers.dense(inputs = hidden2, units = 784, activation = tf.nn.tanh) return output # defining the Discriminator network function def discriminator(X, reuse = None): with tf.variable_scope('dis', reuse = reuse): hidden1 = tf.layers.dense(inputs = X, units = 128, activation = tf.nn.leaky_relu) hidden2 = tf.layers.dense(inputs = hidden1, units = 128, activation = tf.nn.leaky_relu) logits = tf.layers.dense(hidden2, units = 1) output = tf.sigmoid(logits) return output, logits # creating placeholders for the outputstf.reset_default_graph() real_images = tf.placeholder(tf.float32, shape =[None, 784])z = tf.placeholder(tf.float32, shape =[None, 100]) G = generator(z)D_output_real, D_logits_real = discriminator(real_images)D_output_fake, D_logits_fake = discriminator(G, reuse = True) # defining the loss functiondef loss_func(logits_in, labels_in): return tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits( logits = logits_in, labels = labels_in)) # Smoothing for generalizationD_real_loss = loss_func(D_logits_real, tf.ones_like(D_logits_real)*0.9)D_fake_loss = loss_func(D_logits_fake, tf.zeros_like(D_logits_real))D_loss = D_real_loss + D_fake_loss G_loss = loss_func(D_logits_fake, tf.ones_like(D_logits_fake)) # defining the learning rate, batch size,# number of epochs and using the Adam optimizerlr = 0.001 # learning rate # Do this when multiple networks# interact with each other # returns all variables created(the two# variable scopes) and makes trainable truetvars = tf.trainable_variables() d_vars =[var for var in tvars if 'dis' in var.name]g_vars =[var for var in tvars if 'gen' in var.name] D_trainer = tf.train.AdamOptimizer(lr).minimize(D_loss, var_list = d_vars)G_trainer = tf.train.AdamOptimizer(lr).minimize(G_loss, var_list = g_vars) batch_size = 100 # batch sizeepochs = 500 # number of epochs. The higher the better the resultinit = tf.global_variables_initializer() # creating a session to train the networkssamples =[] # generator examples with tf.Session() as sess: sess.run(init) for epoch in range(epochs): num_batches = mnist.train.num_examples//batch_size for i in range(num_batches): batch = mnist.train.next_batch(batch_size) batch_images = batch[0].reshape((batch_size, 784)) batch_images = batch_images * 2-1 batch_z = np.random.uniform(-1, 1, size =(batch_size, 100)) _= sess.run(D_trainer, feed_dict ={real_images:batch_images, z:batch_z}) _= sess.run(G_trainer, feed_dict ={z:batch_z}) print(\"on epoch{}\".format(epoch)) sample_z = np.random.uniform(-1, 1, size =(1, 100)) gen_sample = sess.run(generator(z, reuse = True), feed_dict ={z:sample_z}) samples.append(gen_sample) # result after 0th epochplt.imshow(samples[0].reshape(28, 28)) # result after 499th epochplt.imshow(samples[49].reshape(28, 28))",
"e": 12358,
"s": 8413,
"text": null
},
{
"code": null,
"e": 12415,
"s": 12358,
"text": "on epoch0\non epoch1\n...\n...\n...\non epoch498\non epoch499\n"
},
{
"code": null,
"e": 12464,
"s": 12415,
"text": "Result after 0th epoch:Resulr after 499th epoch:"
},
{
"code": null,
"e": 12975,
"s": 12464,
"text": "So, from the above example, we see that in the first image after 0th epoch, the pixels are scattered all over the place and we couldn’t figure anything out from it.But from the second image, we could see that the pixels are more systematically organized and we could figure out that it is the digit ‘7’ that the code has randomly chosen and the network has tried to make a clone of it. In our example, we have taken 500 as the number of epochs. But you could increase that number to further refine your result."
},
{
"code": null,
"e": 13001,
"s": 12975,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 13018,
"s": 13001,
"text": "Machine Learning"
},
{
"code": null,
"e": 13025,
"s": 13018,
"text": "Python"
},
{
"code": null,
"e": 13044,
"s": 13025,
"text": "Technical Scripter"
},
{
"code": null,
"e": 13061,
"s": 13044,
"text": "Machine Learning"
}
] |
Print a Spirograph using turtle in Python
|
11 Sep, 2021
Pre-requisites: Turtle Programming in Python
A spirograph is a very interesting geometrical figure which is often symmetrical to both the axes. It produces mathematical roulette curves of the variety technically known as hypotrochoids and epitrochoids. Here, we’ve used a range of colors to draw circles, you can use your combination as per your color choice.
Below is the implementation.
Python3
# Import the turtle library for# drawing the required curveimport turtle as tt # Set the background color as black,# pensize as 2 and speed of drawing# curve as 10(relative)tt.bgcolor('black')tt.pensize(2)tt.speed(10) # Iterate six times in totalfor i in range(6): # Choose your color combination for color in ('red', 'magenta', 'blue', 'cyan', 'green', 'white', 'yellow'): tt.color(color) # Draw a circle of chosen size, 100 here tt.circle(100) # Move 10 pixels left to draw another circle tt.left(10) # Hide the cursor(or turtle) which drew the circle tt.hideturtle()
Output:
gabaa406
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n11 Sep, 2021"
},
{
"code": null,
"e": 98,
"s": 53,
"text": "Pre-requisites: Turtle Programming in Python"
},
{
"code": null,
"e": 413,
"s": 98,
"text": "A spirograph is a very interesting geometrical figure which is often symmetrical to both the axes. It produces mathematical roulette curves of the variety technically known as hypotrochoids and epitrochoids. Here, we’ve used a range of colors to draw circles, you can use your combination as per your color choice."
},
{
"code": null,
"e": 442,
"s": 413,
"text": "Below is the implementation."
},
{
"code": null,
"e": 450,
"s": 442,
"text": "Python3"
},
{
"code": "# Import the turtle library for# drawing the required curveimport turtle as tt # Set the background color as black,# pensize as 2 and speed of drawing# curve as 10(relative)tt.bgcolor('black')tt.pensize(2)tt.speed(10) # Iterate six times in totalfor i in range(6): # Choose your color combination for color in ('red', 'magenta', 'blue', 'cyan', 'green', 'white', 'yellow'): tt.color(color) # Draw a circle of chosen size, 100 here tt.circle(100) # Move 10 pixels left to draw another circle tt.left(10) # Hide the cursor(or turtle) which drew the circle tt.hideturtle()",
"e": 1129,
"s": 450,
"text": null
},
{
"code": null,
"e": 1139,
"s": 1129,
"text": "Output: "
},
{
"code": null,
"e": 1150,
"s": 1141,
"text": "gabaa406"
},
{
"code": null,
"e": 1164,
"s": 1150,
"text": "Python-turtle"
},
{
"code": null,
"e": 1171,
"s": 1164,
"text": "Python"
}
] |
Program to Convert Km/hr to miles/hr and vice versa
|
31 May, 2022
Given a speed in km/hr, Convert it to m/hr and m/hr to km/hr.
Examples:
Input : 150 (km/hr)
Output : 93.21
Input : 100 (m/hr)
Output : 160.92693917
The conversion formula for kph to mph is –
1 kilo-meter = 0.621371192 miles
The conversion formula for mph to kph is –
1 miles = 1.60934 kilo-meter
C++
Java
Python
C#
PHP
Javascript
// Cpp program for conversion of// kmph to mph and vice versa#include <bits/stdc++.h>using namespace std; // Function to convert kmph to mphdouble kmphTOmph(double kmph){ return 0.6214 * kmph;}// Function to convert mph to kmphdouble mphTOkmph(double mph){ return mph * 1.60934;} // Driver code to check the above functionint main(){ double kmph = 150; double mph = 100; cout << "the speed in mph is " << kmphTOmph(kmph) << endl; cout << "the speed in kmph is " << mphTOkmph(mph); return 0;}
// Java program for the conversion// kmph to mph and vice versaimport java.io.*;class GFG { // Function to convert kmph to mph static double kmphTOmph(double kmph) { return 0.6214 * kmph; } // Function to convert mph to kmph static double mphTOkmph(double mph) { return mph * 1.60934; } // Driver code to check the above function public static void main(String[] args) { double kmph = 150; double mph = 100; System.out.println("speed in miles/hr is " + kmphTOmph(kmph)); System.out.println("speed in km/hr is " + mphTOkmph(mph)); }}
# Python program for the conversion# kmph to mph and vice versa # Function to convert kmph to mphdef kmphTOmph(kmph): mph = 0.6214 * kmph return mph # Function to convert mph to kmph def mphTOkmph(mph): kmph =(float)(mph * 1.60934) return kmph kmph = 150mph = 100print "speed in miles / hr is ", kmphTOmph(kmph) print "speed in km / hr is ", mphTOkmph(mph)
// C# program for the conversion// kmph to mph and vice versausing System; class GFG { // Function to convert kmph to mph static double kmphTOmph(double kmph) { return 0.6214 * kmph; } // Function to convert mph to kmph static double mphTOkmph(double mph) { return mph * 1.60934; } // Driver code to check the above function public static void Main() { double kmph = 150; double mph = 100; Console.WriteLine("speed in miles/hr is " + kmphTOmph(kmph)); Console.WriteLine("speed in km/hr is " + mphTOkmph(mph)); }} // This code is contributed by vt_m
<?php// PHP program for conversion of// kmph to mph and vice versa // Function to convert// kmph to mphfunction kmphTOmph($kmph){ return 0.6214 * $kmph;} // Function to convert// mph to kmphfunction mphTOkmph($mph){ return $mph * 1.60934;} // Driver Code $kmph = 150; $mph = 100; echo "speed in mph is " , kmphTOmph($kmph),"\n"; echo "speed in kmph is " , mphTOkmph($mph); // This code is contributed by anuj_67.?>
<script> // javascript program for the conversion// kmph to mph and vice versa // Function to convert kmph to mphfunction kmphTOmph(kmph){ return (0.6214 * kmph);} // Function to convert mph to kmphfunction mphTOkmph(mph){ return (1.60934 * mph) ;} // Driver Codevar kmph = 150var mph = 100 document.write("speed in miles/hr is " + kmphTOmph(kmph) + "<br>"); document.write("speed in km/hr is " + mphTOkmph(mph)); // This code is contributed by bunnyram19.</script>
Output:
speed in miles/hr is 93.21
speed in km/hr is 160.934
Time Complexity: O(1), as we are not using any loops or recursion.
Auxiliary Space: O(1), as we are not using any extra space.
vt_m
bunnyram19
adnanirshad158
rohitsingh07052
C Programs
Java Programs
Mathematical
Python Programs
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 May, 2022"
},
{
"code": null,
"e": 91,
"s": 28,
"text": "Given a speed in km/hr, Convert it to m/hr and m/hr to km/hr. "
},
{
"code": null,
"e": 102,
"s": 91,
"text": "Examples: "
},
{
"code": null,
"e": 181,
"s": 102,
"text": "Input : 150 (km/hr)\nOutput : 93.21 \n \nInput : 100 (m/hr)\nOutput : 160.92693917"
},
{
"code": null,
"e": 225,
"s": 181,
"text": "The conversion formula for kph to mph is – "
},
{
"code": null,
"e": 258,
"s": 225,
"text": "1 kilo-meter = 0.621371192 miles"
},
{
"code": null,
"e": 302,
"s": 258,
"text": "The conversion formula for mph to kph is – "
},
{
"code": null,
"e": 331,
"s": 302,
"text": "1 miles = 1.60934 kilo-meter"
},
{
"code": null,
"e": 335,
"s": 331,
"text": "C++"
},
{
"code": null,
"e": 340,
"s": 335,
"text": "Java"
},
{
"code": null,
"e": 347,
"s": 340,
"text": "Python"
},
{
"code": null,
"e": 350,
"s": 347,
"text": "C#"
},
{
"code": null,
"e": 354,
"s": 350,
"text": "PHP"
},
{
"code": null,
"e": 365,
"s": 354,
"text": "Javascript"
},
{
"code": "// Cpp program for conversion of// kmph to mph and vice versa#include <bits/stdc++.h>using namespace std; // Function to convert kmph to mphdouble kmphTOmph(double kmph){ return 0.6214 * kmph;}// Function to convert mph to kmphdouble mphTOkmph(double mph){ return mph * 1.60934;} // Driver code to check the above functionint main(){ double kmph = 150; double mph = 100; cout << \"the speed in mph is \" << kmphTOmph(kmph) << endl; cout << \"the speed in kmph is \" << mphTOkmph(mph); return 0;}",
"e": 879,
"s": 365,
"text": null
},
{
"code": "// Java program for the conversion// kmph to mph and vice versaimport java.io.*;class GFG { // Function to convert kmph to mph static double kmphTOmph(double kmph) { return 0.6214 * kmph; } // Function to convert mph to kmph static double mphTOkmph(double mph) { return mph * 1.60934; } // Driver code to check the above function public static void main(String[] args) { double kmph = 150; double mph = 100; System.out.println(\"speed in miles/hr is \" + kmphTOmph(kmph)); System.out.println(\"speed in km/hr is \" + mphTOkmph(mph)); }}",
"e": 1492,
"s": 879,
"text": null
},
{
"code": "# Python program for the conversion# kmph to mph and vice versa # Function to convert kmph to mphdef kmphTOmph(kmph): mph = 0.6214 * kmph return mph # Function to convert mph to kmph def mphTOkmph(mph): kmph =(float)(mph * 1.60934) return kmph kmph = 150mph = 100print \"speed in miles / hr is \", kmphTOmph(kmph) print \"speed in km / hr is \", mphTOkmph(mph)",
"e": 1864,
"s": 1492,
"text": null
},
{
"code": "// C# program for the conversion// kmph to mph and vice versausing System; class GFG { // Function to convert kmph to mph static double kmphTOmph(double kmph) { return 0.6214 * kmph; } // Function to convert mph to kmph static double mphTOkmph(double mph) { return mph * 1.60934; } // Driver code to check the above function public static void Main() { double kmph = 150; double mph = 100; Console.WriteLine(\"speed in miles/hr is \" + kmphTOmph(kmph)); Console.WriteLine(\"speed in km/hr is \" + mphTOkmph(mph)); }} // This code is contributed by vt_m",
"e": 2494,
"s": 1864,
"text": null
},
{
"code": "<?php// PHP program for conversion of// kmph to mph and vice versa // Function to convert// kmph to mphfunction kmphTOmph($kmph){ return 0.6214 * $kmph;} // Function to convert// mph to kmphfunction mphTOkmph($mph){ return $mph * 1.60934;} // Driver Code $kmph = 150; $mph = 100; echo \"speed in mph is \" , kmphTOmph($kmph),\"\\n\"; echo \"speed in kmph is \" , mphTOkmph($mph); // This code is contributed by anuj_67.?>",
"e": 2954,
"s": 2494,
"text": null
},
{
"code": "<script> // javascript program for the conversion// kmph to mph and vice versa // Function to convert kmph to mphfunction kmphTOmph(kmph){ return (0.6214 * kmph);} // Function to convert mph to kmphfunction mphTOkmph(mph){ return (1.60934 * mph) ;} // Driver Codevar kmph = 150var mph = 100 document.write(\"speed in miles/hr is \" + kmphTOmph(kmph) + \"<br>\"); document.write(\"speed in km/hr is \" + mphTOkmph(mph)); // This code is contributed by bunnyram19.</script>",
"e": 3435,
"s": 2954,
"text": null
},
{
"code": null,
"e": 3444,
"s": 3435,
"text": "Output: "
},
{
"code": null,
"e": 3499,
"s": 3444,
"text": "speed in miles/hr is 93.21\nspeed in km/hr is 160.934"
},
{
"code": null,
"e": 3566,
"s": 3499,
"text": "Time Complexity: O(1), as we are not using any loops or recursion."
},
{
"code": null,
"e": 3626,
"s": 3566,
"text": "Auxiliary Space: O(1), as we are not using any extra space."
},
{
"code": null,
"e": 3631,
"s": 3626,
"text": "vt_m"
},
{
"code": null,
"e": 3642,
"s": 3631,
"text": "bunnyram19"
},
{
"code": null,
"e": 3657,
"s": 3642,
"text": "adnanirshad158"
},
{
"code": null,
"e": 3673,
"s": 3657,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 3684,
"s": 3673,
"text": "C Programs"
},
{
"code": null,
"e": 3698,
"s": 3684,
"text": "Java Programs"
},
{
"code": null,
"e": 3711,
"s": 3698,
"text": "Mathematical"
},
{
"code": null,
"e": 3727,
"s": 3711,
"text": "Python Programs"
},
{
"code": null,
"e": 3746,
"s": 3727,
"text": "School Programming"
},
{
"code": null,
"e": 3759,
"s": 3746,
"text": "Mathematical"
}
] |
norm() function in C++ with Examples
|
10 Oct, 2018
The norm() function is defined in the complex header file. This function is used to return the squared magnitude of the complex number z.
Syntax:
template<class T> T norm (const complex<T>& z);
Parameter:
z: It represents the given complex number.
Return: It returns the squared magnitude of the complex number.
Below programs illustrate the above function:-
Example 1:-
// C++ program to demonstrate// example of norm() function. #include <bits/stdc++.h>using namespace std; // driver functionint main (){ // initializing the complex: (5.0+12.0i) complex<double> complexnumber (5.0, 12.0); // use of norm()function cout << "The norm of " << complexnumber << " is "; cout << norm(complexnumber) << endl; return 0;}
The norm of (5,12) is 169
Example 2:-
// C++ program to demonstrate// example of norm() function. #include <bits/stdc++.h>using namespace std; // driver functionint main (){ // initializing the complex: (4.0+3.0i) complex<double> complexnumber (4.0, 3.0); // use of norm()function cout << "The norm of " << complexnumber << " is "; cout << norm(complexnumber) << endl; return 0;}
The norm of (4,3) is 25
CPP-Library
cpp-numerics-library
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
std::string class in C++
Pair in C++ Standard Template Library (STL)
Queue in C++ Standard Template Library (STL)
Unordered Sets in C++ Standard Template Library
List in C++ Standard Template Library (STL)
std::find in C++
Inline Functions in C++
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Oct, 2018"
},
{
"code": null,
"e": 166,
"s": 28,
"text": "The norm() function is defined in the complex header file. This function is used to return the squared magnitude of the complex number z."
},
{
"code": null,
"e": 174,
"s": 166,
"text": "Syntax:"
},
{
"code": null,
"e": 223,
"s": 174,
"text": "template<class T> T norm (const complex<T>& z);\n"
},
{
"code": null,
"e": 234,
"s": 223,
"text": "Parameter:"
},
{
"code": null,
"e": 277,
"s": 234,
"text": "z: It represents the given complex number."
},
{
"code": null,
"e": 341,
"s": 277,
"text": "Return: It returns the squared magnitude of the complex number."
},
{
"code": null,
"e": 388,
"s": 341,
"text": "Below programs illustrate the above function:-"
},
{
"code": null,
"e": 400,
"s": 388,
"text": "Example 1:-"
},
{
"code": "// C++ program to demonstrate// example of norm() function. #include <bits/stdc++.h>using namespace std; // driver functionint main (){ // initializing the complex: (5.0+12.0i) complex<double> complexnumber (5.0, 12.0); // use of norm()function cout << \"The norm of \" << complexnumber << \" is \"; cout << norm(complexnumber) << endl; return 0;}",
"e": 760,
"s": 400,
"text": null
},
{
"code": null,
"e": 787,
"s": 760,
"text": "The norm of (5,12) is 169\n"
},
{
"code": null,
"e": 799,
"s": 787,
"text": "Example 2:-"
},
{
"code": "// C++ program to demonstrate// example of norm() function. #include <bits/stdc++.h>using namespace std; // driver functionint main (){ // initializing the complex: (4.0+3.0i) complex<double> complexnumber (4.0, 3.0); // use of norm()function cout << \"The norm of \" << complexnumber << \" is \"; cout << norm(complexnumber) << endl; return 0;}",
"e": 1158,
"s": 799,
"text": null
},
{
"code": null,
"e": 1183,
"s": 1158,
"text": "The norm of (4,3) is 25\n"
},
{
"code": null,
"e": 1195,
"s": 1183,
"text": "CPP-Library"
},
{
"code": null,
"e": 1216,
"s": 1195,
"text": "cpp-numerics-library"
},
{
"code": null,
"e": 1220,
"s": 1216,
"text": "C++"
},
{
"code": null,
"e": 1224,
"s": 1220,
"text": "CPP"
},
{
"code": null,
"e": 1322,
"s": 1224,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1346,
"s": 1322,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 1366,
"s": 1346,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 1399,
"s": 1366,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 1424,
"s": 1399,
"text": "std::string class in C++"
},
{
"code": null,
"e": 1468,
"s": 1424,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 1513,
"s": 1468,
"text": "Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 1561,
"s": 1513,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 1605,
"s": 1561,
"text": "List in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 1622,
"s": 1605,
"text": "std::find in C++"
}
] |
HTML DOM createRange() Method
|
29 Jul, 2020
The createRange() method creates a new Range object for the document.
Syntax:
range = document.createRange();
Parameters: This method does not accept any parameters.
Return Value: This method returns the created Range.
Example: In this example, we will create a range using this method, a range should not be empty, so we will make starting and ending points in the range using setEnd() and setStart() method.
HTML
<!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <p id="parent"> Child 1<br> Child 2<br> </p> <script> const example = document.getElementById('parent'); const range = document.createRange(); range.setStart(example, 0); range.setEnd(example, 3); console.log(range); console.log(range.toString()); </script></body> </html>
Output: In console, created range can be seen.
Supported Browsers:
Google Chrome
Edge
Firefox
Safari
Opera
HTML-DOM
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Angular File Upload
Form validation using jQuery
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
How to append HTML code to a div using JavaScript ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Jul, 2020"
},
{
"code": null,
"e": 98,
"s": 28,
"text": "The createRange() method creates a new Range object for the document."
},
{
"code": null,
"e": 106,
"s": 98,
"text": "Syntax:"
},
{
"code": null,
"e": 138,
"s": 106,
"text": "range = document.createRange();"
},
{
"code": null,
"e": 194,
"s": 138,
"text": "Parameters: This method does not accept any parameters."
},
{
"code": null,
"e": 247,
"s": 194,
"text": "Return Value: This method returns the created Range."
},
{
"code": null,
"e": 438,
"s": 247,
"text": "Example: In this example, we will create a range using this method, a range should not be empty, so we will make starting and ending points in the range using setEnd() and setStart() method."
},
{
"code": null,
"e": 443,
"s": 438,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <p id=\"parent\"> Child 1<br> Child 2<br> </p> <script> const example = document.getElementById('parent'); const range = document.createRange(); range.setStart(example, 0); range.setEnd(example, 3); console.log(range); console.log(range.toString()); </script></body> </html>",
"e": 843,
"s": 443,
"text": null
},
{
"code": null,
"e": 890,
"s": 843,
"text": "Output: In console, created range can be seen."
},
{
"code": null,
"e": 910,
"s": 890,
"text": "Supported Browsers:"
},
{
"code": null,
"e": 924,
"s": 910,
"text": "Google Chrome"
},
{
"code": null,
"e": 929,
"s": 924,
"text": "Edge"
},
{
"code": null,
"e": 937,
"s": 929,
"text": "Firefox"
},
{
"code": null,
"e": 944,
"s": 937,
"text": "Safari"
},
{
"code": null,
"e": 950,
"s": 944,
"text": "Opera"
},
{
"code": null,
"e": 959,
"s": 950,
"text": "HTML-DOM"
},
{
"code": null,
"e": 964,
"s": 959,
"text": "HTML"
},
{
"code": null,
"e": 975,
"s": 964,
"text": "JavaScript"
},
{
"code": null,
"e": 992,
"s": 975,
"text": "Web Technologies"
},
{
"code": null,
"e": 997,
"s": 992,
"text": "HTML"
},
{
"code": null,
"e": 1095,
"s": 997,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1119,
"s": 1095,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 1158,
"s": 1119,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 1197,
"s": 1158,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 1217,
"s": 1197,
"text": "Angular File Upload"
},
{
"code": null,
"e": 1246,
"s": 1217,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 1307,
"s": 1246,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1379,
"s": 1307,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 1419,
"s": 1379,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 1460,
"s": 1419,
"text": "Difference Between PUT and PATCH Request"
}
] |
How to trigger the same function with jQuery multiple events?
|
To trigger the same function with multiple events, use the jQuery on() method with multiple events such as click, dblclick, mouse enter, mouse leave, hover, etc.
You can try to run the following code to learn how to work the same function with jQuery multiple events:
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("p").on({
mouseenter: function(){
$(this).css("background-color", "gray");
},
mouseleave: function(){
$(this).css("background-color", "red");
},
dblclick: function(){
$(this).css("background-color", "yellow");
}
});
});
</script>
</head>
<body>
<p>Click, double click and move the mouse pointer.</p>
</body>
</html>
|
[
{
"code": null,
"e": 1224,
"s": 1062,
"text": "To trigger the same function with multiple events, use the jQuery on() method with multiple events such as click, dblclick, mouse enter, mouse leave, hover, etc."
},
{
"code": null,
"e": 1330,
"s": 1224,
"text": "You can try to run the following code to learn how to work the same function with jQuery multiple events:"
},
{
"code": null,
"e": 1340,
"s": 1330,
"text": "Live Demo"
},
{
"code": null,
"e": 1940,
"s": 1340,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n<script>\n$(document).ready(function(){\n $(\"p\").on({\n \n mouseenter: function(){\n $(this).css(\"background-color\", \"gray\");\n }, \n \n mouseleave: function(){\n $(this).css(\"background-color\", \"red\");\n },\n \n dblclick: function(){\n $(this).css(\"background-color\", \"yellow\");\n }\n \n });\n});\n</script>\n</head>\n<body>\n\n<p>Click, double click and move the mouse pointer.</p>\n\n</body>\n</html>"
}
] |
How to create a blink text using JavaScript?
|
To create a blinking text, use the JavaScript blink() method. This method causes a string to blink as if it were in a BLINK tag.
Note − HTML <blink> tag deprecated and is not expected to work in every browser.
You can try to run the following code to create a blinking text with the JavaScript blink() method −
Live Demo
<html>
<head>
<title>JavaScript String blink() Method</title>
</head>
<body>
<script>
var str = new String("Demo Text");
document.write(str.blink());
document.write("<br><br> Note: HTML <blink> tag deprecated and is not expected to work in every browser.")
</script>
</body>
</html>
|
[
{
"code": null,
"e": 1191,
"s": 1062,
"text": "To create a blinking text, use the JavaScript blink() method. This method causes a string to blink as if it were in a BLINK tag."
},
{
"code": null,
"e": 1272,
"s": 1191,
"text": "Note − HTML <blink> tag deprecated and is not expected to work in every browser."
},
{
"code": null,
"e": 1373,
"s": 1272,
"text": "You can try to run the following code to create a blinking text with the JavaScript blink() method −"
},
{
"code": null,
"e": 1383,
"s": 1373,
"text": "Live Demo"
},
{
"code": null,
"e": 1724,
"s": 1383,
"text": "<html>\n <head>\n <title>JavaScript String blink() Method</title>\n </head>\n\n <body>\n <script>\n var str = new String(\"Demo Text\");\n document.write(str.blink());\n document.write(\"<br><br> Note: HTML <blink> tag deprecated and is not expected to work in every browser.\")\n </script>\n </body>\n</html>"
}
] |
scipy.stats.chi2() | Python - GeeksforGeeks
|
20 Mar, 2019
scipy.stats.chi2() is an chi square continuous random variable that is defined with a standard format and some shape parameters to complete its specification.
Parameters :q : lower and upper tail probabilityx : quantilesloc : [optional]location parameter. Default = 0scale : [optional]scale parameter. Default = 1size : [tuple of ints, optional] shape or random variates.moments : [optional] composed of letters [‘mvsk’]; ‘m’ = mean, ‘v’ = variance, ‘s’ = Fisher’s skew and ‘k’ = Fisher’s kurtosis. (default = ‘mv’).
Results : chi squared continuous random variable
Code #1 : Creating chi squared continuous random variable
# importing scipyfrom scipy.stats import chi2 numargs = chi2.numargs[a] = [0.6, ] * numargsrv = chi2(a) print ("RV : \n", rv)
Output :
RV :
<scipy.stats._distn_infrastructure.rv_frozen object at 0x0000029485196DD8>
Code #2 : chi2 random variates and probability distribution function.
import numpy as npquantile = np.arange (0.01, 1, 0.1) # Random VariatesR = chi2.rvs(a, scale = 2, size = 10)print ("Random Variates : \n", R) # PDFR = chi2.pdf(a, quantile, loc = 0, scale = 1)print ("\nProbability Distribution : \n", R)
Output :
Random Variates :
[6.20115012e-01 4.82717678e-01 1.43760444e-02 1.19755537e+00
3.00093606e-05 6.11268950e-01 5.99940774e-01 3.20509994e-01
1.94220599e-01 6.63225404e-01]
Probability Distribution :
[0.00615404 0.06544849 0.12034254 0.1704933 0.21568622 0.25581903
0.29088625 0.32096438 0.34619796 0.36678666]
Code #3 : Graphical Representation.
import numpy as npimport matplotlib.pyplot as plt distribution = np.linspace(0, np.minimum(rv.dist.b, 5))print("Distribution : \n", distribution) plot = plt.plot(distribution, rv.pdf(distribution))
Output :
Distribution :
[0. 0.10204082 0.20408163 0.30612245 0.40816327 0.51020408
0.6122449 0.71428571 0.81632653 0.91836735 1.02040816 1.12244898
1.2244898 1.32653061 1.42857143 1.53061224 1.63265306 1.73469388
1.83673469 1.93877551 2.04081633 2.14285714 2.24489796 2.34693878
2.44897959 2.55102041 2.65306122 2.75510204 2.85714286 2.95918367
3.06122449 3.16326531 3.26530612 3.36734694 3.46938776 3.57142857
3.67346939 3.7755102 3.87755102 3.97959184 4.08163265 4.18367347
4.28571429 4.3877551 4.48979592 4.59183673 4.69387755 4.79591837
4.89795918 5. ]
Code #4 : Varying Positional Arguments
import matplotlib.pyplot as pltimport numpy as np x = np.linspace(0, 5, 100) # Varying positional argumentsy1 = chi2.pdf(x, 1, 6)y2 = chi2.pdf(x, 1, 4)plt.plot(x, y1, "*", x, y2, "r--")
Output :
Python scipy-stats-functions
Python-scipy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
*args and **kwargs in Python
sum() function in Python
|
[
{
"code": null,
"e": 24806,
"s": 24778,
"text": "\n20 Mar, 2019"
},
{
"code": null,
"e": 24965,
"s": 24806,
"text": "scipy.stats.chi2() is an chi square continuous random variable that is defined with a standard format and some shape parameters to complete its specification."
},
{
"code": null,
"e": 25323,
"s": 24965,
"text": "Parameters :q : lower and upper tail probabilityx : quantilesloc : [optional]location parameter. Default = 0scale : [optional]scale parameter. Default = 1size : [tuple of ints, optional] shape or random variates.moments : [optional] composed of letters [‘mvsk’]; ‘m’ = mean, ‘v’ = variance, ‘s’ = Fisher’s skew and ‘k’ = Fisher’s kurtosis. (default = ‘mv’)."
},
{
"code": null,
"e": 25372,
"s": 25323,
"text": "Results : chi squared continuous random variable"
},
{
"code": null,
"e": 25430,
"s": 25372,
"text": "Code #1 : Creating chi squared continuous random variable"
},
{
"code": "# importing scipyfrom scipy.stats import chi2 numargs = chi2.numargs[a] = [0.6, ] * numargsrv = chi2(a) print (\"RV : \\n\", rv) ",
"e": 25559,
"s": 25430,
"text": null
},
{
"code": null,
"e": 25568,
"s": 25559,
"text": "Output :"
},
{
"code": null,
"e": 25651,
"s": 25568,
"text": "RV : \n <scipy.stats._distn_infrastructure.rv_frozen object at 0x0000029485196DD8>\n"
},
{
"code": null,
"e": 25721,
"s": 25651,
"text": "Code #2 : chi2 random variates and probability distribution function."
},
{
"code": "import numpy as npquantile = np.arange (0.01, 1, 0.1) # Random VariatesR = chi2.rvs(a, scale = 2, size = 10)print (\"Random Variates : \\n\", R) # PDFR = chi2.pdf(a, quantile, loc = 0, scale = 1)print (\"\\nProbability Distribution : \\n\", R)",
"e": 25962,
"s": 25721,
"text": null
},
{
"code": null,
"e": 25971,
"s": 25962,
"text": "Output :"
},
{
"code": null,
"e": 26290,
"s": 25971,
"text": "Random Variates : \n [6.20115012e-01 4.82717678e-01 1.43760444e-02 1.19755537e+00\n 3.00093606e-05 6.11268950e-01 5.99940774e-01 3.20509994e-01\n 1.94220599e-01 6.63225404e-01]\n\nProbability Distribution : \n [0.00615404 0.06544849 0.12034254 0.1704933 0.21568622 0.25581903\n 0.29088625 0.32096438 0.34619796 0.36678666]\n "
},
{
"code": null,
"e": 26326,
"s": 26290,
"text": "Code #3 : Graphical Representation."
},
{
"code": "import numpy as npimport matplotlib.pyplot as plt distribution = np.linspace(0, np.minimum(rv.dist.b, 5))print(\"Distribution : \\n\", distribution) plot = plt.plot(distribution, rv.pdf(distribution))",
"e": 26526,
"s": 26326,
"text": null
},
{
"code": null,
"e": 26535,
"s": 26526,
"text": "Output :"
},
{
"code": null,
"e": 27112,
"s": 26535,
"text": "Distribution : \n [0. 0.10204082 0.20408163 0.30612245 0.40816327 0.51020408\n 0.6122449 0.71428571 0.81632653 0.91836735 1.02040816 1.12244898\n 1.2244898 1.32653061 1.42857143 1.53061224 1.63265306 1.73469388\n 1.83673469 1.93877551 2.04081633 2.14285714 2.24489796 2.34693878\n 2.44897959 2.55102041 2.65306122 2.75510204 2.85714286 2.95918367\n 3.06122449 3.16326531 3.26530612 3.36734694 3.46938776 3.57142857\n 3.67346939 3.7755102 3.87755102 3.97959184 4.08163265 4.18367347\n 4.28571429 4.3877551 4.48979592 4.59183673 4.69387755 4.79591837\n 4.89795918 5. ]"
},
{
"code": null,
"e": 27151,
"s": 27112,
"text": "Code #4 : Varying Positional Arguments"
},
{
"code": "import matplotlib.pyplot as pltimport numpy as np x = np.linspace(0, 5, 100) # Varying positional argumentsy1 = chi2.pdf(x, 1, 6)y2 = chi2.pdf(x, 1, 4)plt.plot(x, y1, \"*\", x, y2, \"r--\")",
"e": 27339,
"s": 27151,
"text": null
},
{
"code": null,
"e": 27348,
"s": 27339,
"text": "Output :"
},
{
"code": null,
"e": 27377,
"s": 27348,
"text": "Python scipy-stats-functions"
},
{
"code": null,
"e": 27390,
"s": 27377,
"text": "Python-scipy"
},
{
"code": null,
"e": 27397,
"s": 27390,
"text": "Python"
},
{
"code": null,
"e": 27495,
"s": 27397,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27513,
"s": 27495,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27548,
"s": 27513,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27570,
"s": 27548,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27602,
"s": 27570,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27644,
"s": 27602,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27670,
"s": 27644,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27707,
"s": 27670,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 27751,
"s": 27707,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 27780,
"s": 27751,
"text": "*args and **kwargs in Python"
}
] |
TypeScript - Array indexOf()
|
indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
array.indexOf(searchElement[, fromIndex]);
searchElement − Element to locate in the array.
searchElement − Element to locate in the array.
fromIndex − The index at which to begin the search. Defaults to 0, i.e. the whole array will be searched. If the index is greater than or equal to the length of the array, -1 is returned.
fromIndex − The index at which to begin the search. Defaults to 0, i.e. the whole array will be searched. If the index is greater than or equal to the length of the array, -1 is returned.
Returns the index of the found element.
var index = [12, 5, 8, 130, 44].indexOf(8);
console.log("index is : " + index );
On compiling, it will generate the same code in JavaScript.
Its output is as follows −
index is : 2
45 Lectures
4 hours
Antonio Papa
41 Lectures
7 hours
Haider Malik
60 Lectures
2.5 hours
Skillbakerystudios
77 Lectures
8 hours
Sean Bradley
77 Lectures
3.5 hours
TELCOMA Global
19 Lectures
3 hours
Christopher Frewin
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2169,
"s": 2048,
"text": "indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present."
},
{
"code": null,
"e": 2213,
"s": 2169,
"text": "array.indexOf(searchElement[, fromIndex]);\n"
},
{
"code": null,
"e": 2261,
"s": 2213,
"text": "searchElement − Element to locate in the array."
},
{
"code": null,
"e": 2309,
"s": 2261,
"text": "searchElement − Element to locate in the array."
},
{
"code": null,
"e": 2497,
"s": 2309,
"text": "fromIndex − The index at which to begin the search. Defaults to 0, i.e. the whole array will be searched. If the index is greater than or equal to the length of the array, -1 is returned."
},
{
"code": null,
"e": 2685,
"s": 2497,
"text": "fromIndex − The index at which to begin the search. Defaults to 0, i.e. the whole array will be searched. If the index is greater than or equal to the length of the array, -1 is returned."
},
{
"code": null,
"e": 2725,
"s": 2685,
"text": "Returns the index of the found element."
},
{
"code": null,
"e": 2808,
"s": 2725,
"text": "var index = [12, 5, 8, 130, 44].indexOf(8); \nconsole.log(\"index is : \" + index );\n"
},
{
"code": null,
"e": 2868,
"s": 2808,
"text": "On compiling, it will generate the same code in JavaScript."
},
{
"code": null,
"e": 2895,
"s": 2868,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 2909,
"s": 2895,
"text": "index is : 2\n"
},
{
"code": null,
"e": 2942,
"s": 2909,
"text": "\n 45 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 2956,
"s": 2942,
"text": " Antonio Papa"
},
{
"code": null,
"e": 2989,
"s": 2956,
"text": "\n 41 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3003,
"s": 2989,
"text": " Haider Malik"
},
{
"code": null,
"e": 3038,
"s": 3003,
"text": "\n 60 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3058,
"s": 3038,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 3091,
"s": 3058,
"text": "\n 77 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3105,
"s": 3091,
"text": " Sean Bradley"
},
{
"code": null,
"e": 3140,
"s": 3105,
"text": "\n 77 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3156,
"s": 3140,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 3189,
"s": 3156,
"text": "\n 19 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 3209,
"s": 3189,
"text": " Christopher Frewin"
},
{
"code": null,
"e": 3216,
"s": 3209,
"text": " Print"
},
{
"code": null,
"e": 3227,
"s": 3216,
"text": " Add Notes"
}
] |
Convert an Array to an Object in JavaScript - GeeksforGeeks
|
14 May, 2019
Here is a need to convert an array into an object. To do so we are going to use a few of the most preferred methods. First here is a method to know.Object.assign() methodThis method copies the values of all enumerable own properties from source objects(one or more) to a target object.Syntax:
Object.assign(target, ...sources)
Parameters:
target: It specifies the target object.
sources: It specifies the source object(s).
Example-1: This example converts the array to object by using Object.assign() method. For display it, JSON.stringify() method is used.
<!DOCTYPE html><html> <head> <title> JavaScript | Convert Array to Object. </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 16px;"> </p> <button onclick="gfg_Run()"> Convert </button> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var array = [1, 2, 3, 4]; el_up.innerHTML = "Original Array = [" + array + "]";; function gfg_Run() { el_down.innerHTML = JSON.stringify(Object.assign({}, array)); } </script></body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Example-2: This example converts the array to object by creating a function which adds the array values one by one to the object. For display it, JSON.stringify() method is used.
<!DOCTYPE html><html> <head> <title> JavaScript | Convert Array to Object. </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 16px; font-weight: bold;"> </p> <button onclick="gfg_Run()"> Convert </button> <p id="GFG_DOWN" style="color:green; font-size: 22px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var array = ['GFG1', 'GFG2', 'GFG3', 'GFG4']; el_up.innerHTML = "Original Array = [" + array + "]"; function toObject(arr) { var rv = {}; for (var i = 0; i < arr.length; ++i) rv[i] = arr[i]; return rv; } function gfg_Run() { el_down.innerHTML = JSON.stringify(toObject(array)); } </script></body> </html>
Output:
Before clicking on the button:
After clicking on the button:
javascript-array
javascript-object
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
Remove elements from a JavaScript Array
How to get character array from string in JavaScript?
How to get selected value in dropdown list using JavaScript ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 24909,
"s": 24881,
"text": "\n14 May, 2019"
},
{
"code": null,
"e": 25202,
"s": 24909,
"text": "Here is a need to convert an array into an object. To do so we are going to use a few of the most preferred methods. First here is a method to know.Object.assign() methodThis method copies the values of all enumerable own properties from source objects(one or more) to a target object.Syntax:"
},
{
"code": null,
"e": 25237,
"s": 25202,
"text": "Object.assign(target, ...sources)\n"
},
{
"code": null,
"e": 25249,
"s": 25237,
"text": "Parameters:"
},
{
"code": null,
"e": 25289,
"s": 25249,
"text": "target: It specifies the target object."
},
{
"code": null,
"e": 25333,
"s": 25289,
"text": "sources: It specifies the source object(s)."
},
{
"code": null,
"e": 25468,
"s": 25333,
"text": "Example-1: This example converts the array to object by using Object.assign() method. For display it, JSON.stringify() method is used."
},
{
"code": "<!DOCTYPE html><html> <head> <title> JavaScript | Convert Array to Object. </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 16px;\"> </p> <button onclick=\"gfg_Run()\"> Convert </button> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var array = [1, 2, 3, 4]; el_up.innerHTML = \"Original Array = [\" + array + \"]\";; function gfg_Run() { el_down.innerHTML = JSON.stringify(Object.assign({}, array)); } </script></body> </html>",
"e": 26323,
"s": 25468,
"text": null
},
{
"code": null,
"e": 26331,
"s": 26323,
"text": "Output:"
},
{
"code": null,
"e": 26362,
"s": 26331,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 26392,
"s": 26362,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 26571,
"s": 26392,
"text": "Example-2: This example converts the array to object by creating a function which adds the array values one by one to the object. For display it, JSON.stringify() method is used."
},
{
"code": "<!DOCTYPE html><html> <head> <title> JavaScript | Convert Array to Object. </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 16px; font-weight: bold;\"> </p> <button onclick=\"gfg_Run()\"> Convert </button> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 22px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var array = ['GFG1', 'GFG2', 'GFG3', 'GFG4']; el_up.innerHTML = \"Original Array = [\" + array + \"]\"; function toObject(arr) { var rv = {}; for (var i = 0; i < arr.length; ++i) rv[i] = arr[i]; return rv; } function gfg_Run() { el_down.innerHTML = JSON.stringify(toObject(array)); } </script></body> </html>",
"e": 27636,
"s": 26571,
"text": null
},
{
"code": null,
"e": 27644,
"s": 27636,
"text": "Output:"
},
{
"code": null,
"e": 27675,
"s": 27644,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 27705,
"s": 27675,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 27722,
"s": 27705,
"text": "javascript-array"
},
{
"code": null,
"e": 27740,
"s": 27722,
"text": "javascript-object"
},
{
"code": null,
"e": 27751,
"s": 27740,
"text": "JavaScript"
},
{
"code": null,
"e": 27768,
"s": 27751,
"text": "Web Technologies"
},
{
"code": null,
"e": 27866,
"s": 27768,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27875,
"s": 27866,
"text": "Comments"
},
{
"code": null,
"e": 27888,
"s": 27875,
"text": "Old Comments"
},
{
"code": null,
"e": 27949,
"s": 27888,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27990,
"s": 27949,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 28030,
"s": 27990,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28084,
"s": 28030,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 28146,
"s": 28084,
"text": "How to get selected value in dropdown list using JavaScript ?"
},
{
"code": null,
"e": 28202,
"s": 28146,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 28235,
"s": 28202,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28297,
"s": 28235,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28340,
"s": 28297,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How to create your own Question-Answering system easily with python | by André Macedo Farias | Towards Data Science
|
The history of Machine Comprehension (MC) has its origins along with the birth of first concepts in Artificial Intelligence (AI). The brilliant Allan Turing proposed in his famous article “Computing Machinery and Intelligence” what is now called the Turing test as a criterion of intelligence. Almost 70 years later, Question Answering (QA), a sub-domain of MC, is still one of the most difficult tasks in AI.
However, since last year, the field of Natural Language Processing (NLP) has experienced a fast evolution thanks to the development in Deep Learning research and the advent of Transfer Learning techniques. Powerful pre-trained NLP models such as OpenAI-GPT, ELMo, BERT and XLNet have been made available by the best researchers of the domain.
With such progress, several improved systems and applications to NLP tasks are expected to come out. One of such systems is the cdQA-suite, a package developed by some colleagues and me in a partnership between Telecom ParisTech, a French engineering school, and BNP Paribas Personal Finance, a European leader in financing for individuals.
When we think about QA systems we should be aware of two different kinds of systems: open-domain QA (ODQA) systems and closed-domain QA (CDQA) systems.
Open-domain systems deal with questions about nearly anything, and can only rely on general ontologies and world knowledge. One example of such a system is DrQA, an ODQA developed by Facebook Research that uses a large base of articles from Wikipedia as its source of knowledge. As these documents are related to several different topics and subjects we can understand why this system is considered an ODQA.
On the other hand, closed-domain systems deal with questions under a specific domain (for example, medicine or automotive maintenance), and can exploit domain-specific knowledge by using a model that is fitted to a unique-domain database. The cdQA-suite was built to enable anyone who wants to build a closed-domain QA system easily.
github.com
The cdQA-suite is comprised of three blocks:
cdQA: an easy-to-use python package to implement a QA pipeline
cdQA-annotator: a tool built to facilitate the annotation of question-answering datasets for model evaluation and fine-tuning
cdQA-ui: a user-interface that can be coupled to any website and can be connected to the back-end system.
I will explain how each module works and how you can use it to build your QA system on your own data.
The cdQA architecture is based on two main components: the Retriever and the Reader. You can see below a schema of the system mechanism.
When a question is sent to the system, the Retriever selects a list of documents in the database that are the most likely to contain the answer. It is based on the same retriever of DrQA, which creates TF-IDF features based on uni-grams and bi-grams and compute the cosine similarity between the question sentence and each document of the database.
After selecting the most probable documents, the system divides each document into paragraphs and send them with the question to the Reader, which is basically a pre-trained Deep Learning model. The model used was the Pytorch version of the well known NLP model BERT, which was made available by HuggingFace. Then, the Reader outputs the most probable answer it can find in each paragraph. After the Reader, there is a final layer in the system that compares the answers by using an internal score function and outputs the most likely one according to the scores.
Before starting using the package, let's install it. You can install it using pip or clone the repository from source. For this tutorial I will also download the BNP Paribas’ dataset (a dataset with articles extracted from their public news webpage).
# Installing cdQA package with pippip install cdqa# From sourcegit clone https://github.com/cdqa-suite/cdQA.git &&cd cdQA &&pip install .
Now, you can open a jupyter notebook and follow the steps below to see how cdQA works:
You should have something like the following as output:
You can notice that the system not only outputs an answer, but also the paragraph where the answer was found and the title of the document / article.
In the snippet above, the preprocessing / filtering steps were needed to transform the BNP Paribas dataframe to the following structure:
If you use your own dataset, please be sure that your dataframe has such structure.
When using the CPU version of the model, each prediction takes between 10 and 20 seconds to be done. This moderate execution time is due to the BERT Reader, which is a very large deep learning model (~110M parameters). If you have a GPU, you can use directly the GPU version of the model models/bert_qa_vGPU-sklearn.joblib. These pre-trained models are also available on the releases page of cdQA github: https://github.com/cdqa-suite/cdQA/releases
You can also improve the performance of the pre-trained Reader, which was pre-trained on SQuAD 1.1 dataset. If you have an annotated dataset (that can be generated by the help of the cdQA-annotator) in the same format as SQuAD dataset you can fine-tune the reader on it:
# Put the path to your json file in SQuAD format herepath_to_data = './data/SQuAD_1.1/train-v1.1.json'cdqa_pipeline.fit_reader(path_to_data)
Please be aware that such fine-tuning should be performed using GPU as the BERT model is too large to be trained with CPU.
You can also check out other ways to do the same steps on the official tutorials: https://github.com/cdqa-suite/cdQA/tree/master/examples
In order to facilitate the data annotation, the team has built a web-based application, the cdQA-annotator.
In order to use it, you should have your dataset transformed to a JSON file with SQuAD-like format:
from cdqa.utils.converters import df2squad# Converting dataframe to SQuAD formatjson_data = df2squad(df=df, squad_version='v1.1', output_dir='.', filename='dataset-name.json')
Now you can install the annotator and run it:
# Clone the repogit clone https://github.com/cdqa-suite/cdQA-annotator# Install dependenciescd cdQA-annotatornpm install# Start development servercd srcvue serve
Now you can go to http://localhost:8080/ and after loading your JSON file you will see something like this:
To start annotating question-answer pairs you just need to write a question, highlight the answer with the mouse cursor (the answer will be written automatically), and then click on Add annotation:
After the annotation, you can download it and use it to fine-tune the BERT Reader on your own data as explained in the previous section.
The team also has provided a web-based user interface to couple with cdQA. In this section, I will describe how you can use de UI linked to the back-end of cdQA.
First, you have to deploy a cdQA REST API by executing on your shell (be sure you run it on cdQA folder):
export dataset_path=path-to-dataset.csvexport reader_path=path-to-reader-modelFLASK_APP=api.py flask run -h 0.0.0.0
Second, you should proceed to the installation of the cdQA-ui package:
git clone https://github.com/cdqa-suite/cdQA-ui &&cd cdQA-ui &&npm install
Then, you start the develpoment server:
npm run serve
You can now access the web application on http://localhost:8080/. You will see something like the figure below:
As the application is well connected to the back-end, via the REST API, you can ask a question and the application will display an answer, the passage context where the answer was found and the title of the article:
If you want to couple the interface on your website you just need do the following imports in your Vue app:
import Vue from 'vue'import CdqaUI from 'cdqa-ui'Vue.use(CdqaUI)import Vue from 'vue'import BootstrapVue from "bootstrap-vue"Vue.use(BootstrapVue)import "bootstrap/dist/css/bootstrap.css"import "bootstrap-vue/dist/bootstrap-vue.css"
Then you insert the cdQA interface component:
You can also check out a demo of the application on the official website: https://cdqa-suite.github.io/cdQA-website/#demo
In this article, I presented cdQA-suite, a software suite for the deployment of an end-to-end Closed Domain Question Answering System.
If you are interested in learning more about the project, feel free to check out the official GitHub repository: https://github.com/cdqa-suite. Do not hesitate to star and to follow the repositories if you liked the project and consider it valuable for you and your applications.
We recently released the version 1.0.2 of the cdQA package, which is performant and shows very promising results. However, there is still headroom for improvement. If you wish to contribute to the project and help with such improvements, you can take a look at our current issues: https://github.com/cdqa-suite/cdQA/issues. Feel free to choose one and to do a Pull Request :).
Cheers!
cdQA-suite repositories on GitHub: https://github.com/cdqa-suite
official BERT version from Google: https://github.com/google-research/bert
Pytorch version of BERT by HuggingFace: https://github.com/huggingface/pytorch-pretrained-BERT
SQuAD dataset: https://rajpurkar.github.io/SQuAD-explorer/
DrQA by Facebook Research: https://github.com/facebookresearch/DrQA/
DeepPavlov, a library that has an Open-Domain QA system: https://medium.com/deeppavlov/open-domain-question-answering-with-deeppavlov-c665d2ee4d65
OpenAI GPT: https://openai.com/blog/better-language-models/
|
[
{
"code": null,
"e": 581,
"s": 171,
"text": "The history of Machine Comprehension (MC) has its origins along with the birth of first concepts in Artificial Intelligence (AI). The brilliant Allan Turing proposed in his famous article “Computing Machinery and Intelligence” what is now called the Turing test as a criterion of intelligence. Almost 70 years later, Question Answering (QA), a sub-domain of MC, is still one of the most difficult tasks in AI."
},
{
"code": null,
"e": 924,
"s": 581,
"text": "However, since last year, the field of Natural Language Processing (NLP) has experienced a fast evolution thanks to the development in Deep Learning research and the advent of Transfer Learning techniques. Powerful pre-trained NLP models such as OpenAI-GPT, ELMo, BERT and XLNet have been made available by the best researchers of the domain."
},
{
"code": null,
"e": 1265,
"s": 924,
"text": "With such progress, several improved systems and applications to NLP tasks are expected to come out. One of such systems is the cdQA-suite, a package developed by some colleagues and me in a partnership between Telecom ParisTech, a French engineering school, and BNP Paribas Personal Finance, a European leader in financing for individuals."
},
{
"code": null,
"e": 1417,
"s": 1265,
"text": "When we think about QA systems we should be aware of two different kinds of systems: open-domain QA (ODQA) systems and closed-domain QA (CDQA) systems."
},
{
"code": null,
"e": 1825,
"s": 1417,
"text": "Open-domain systems deal with questions about nearly anything, and can only rely on general ontologies and world knowledge. One example of such a system is DrQA, an ODQA developed by Facebook Research that uses a large base of articles from Wikipedia as its source of knowledge. As these documents are related to several different topics and subjects we can understand why this system is considered an ODQA."
},
{
"code": null,
"e": 2159,
"s": 1825,
"text": "On the other hand, closed-domain systems deal with questions under a specific domain (for example, medicine or automotive maintenance), and can exploit domain-specific knowledge by using a model that is fitted to a unique-domain database. The cdQA-suite was built to enable anyone who wants to build a closed-domain QA system easily."
},
{
"code": null,
"e": 2170,
"s": 2159,
"text": "github.com"
},
{
"code": null,
"e": 2215,
"s": 2170,
"text": "The cdQA-suite is comprised of three blocks:"
},
{
"code": null,
"e": 2278,
"s": 2215,
"text": "cdQA: an easy-to-use python package to implement a QA pipeline"
},
{
"code": null,
"e": 2404,
"s": 2278,
"text": "cdQA-annotator: a tool built to facilitate the annotation of question-answering datasets for model evaluation and fine-tuning"
},
{
"code": null,
"e": 2510,
"s": 2404,
"text": "cdQA-ui: a user-interface that can be coupled to any website and can be connected to the back-end system."
},
{
"code": null,
"e": 2612,
"s": 2510,
"text": "I will explain how each module works and how you can use it to build your QA system on your own data."
},
{
"code": null,
"e": 2749,
"s": 2612,
"text": "The cdQA architecture is based on two main components: the Retriever and the Reader. You can see below a schema of the system mechanism."
},
{
"code": null,
"e": 3098,
"s": 2749,
"text": "When a question is sent to the system, the Retriever selects a list of documents in the database that are the most likely to contain the answer. It is based on the same retriever of DrQA, which creates TF-IDF features based on uni-grams and bi-grams and compute the cosine similarity between the question sentence and each document of the database."
},
{
"code": null,
"e": 3662,
"s": 3098,
"text": "After selecting the most probable documents, the system divides each document into paragraphs and send them with the question to the Reader, which is basically a pre-trained Deep Learning model. The model used was the Pytorch version of the well known NLP model BERT, which was made available by HuggingFace. Then, the Reader outputs the most probable answer it can find in each paragraph. After the Reader, there is a final layer in the system that compares the answers by using an internal score function and outputs the most likely one according to the scores."
},
{
"code": null,
"e": 3913,
"s": 3662,
"text": "Before starting using the package, let's install it. You can install it using pip or clone the repository from source. For this tutorial I will also download the BNP Paribas’ dataset (a dataset with articles extracted from their public news webpage)."
},
{
"code": null,
"e": 4051,
"s": 3913,
"text": "# Installing cdQA package with pippip install cdqa# From sourcegit clone https://github.com/cdqa-suite/cdQA.git &&cd cdQA &&pip install ."
},
{
"code": null,
"e": 4138,
"s": 4051,
"text": "Now, you can open a jupyter notebook and follow the steps below to see how cdQA works:"
},
{
"code": null,
"e": 4194,
"s": 4138,
"text": "You should have something like the following as output:"
},
{
"code": null,
"e": 4344,
"s": 4194,
"text": "You can notice that the system not only outputs an answer, but also the paragraph where the answer was found and the title of the document / article."
},
{
"code": null,
"e": 4481,
"s": 4344,
"text": "In the snippet above, the preprocessing / filtering steps were needed to transform the BNP Paribas dataframe to the following structure:"
},
{
"code": null,
"e": 4565,
"s": 4481,
"text": "If you use your own dataset, please be sure that your dataframe has such structure."
},
{
"code": null,
"e": 5014,
"s": 4565,
"text": "When using the CPU version of the model, each prediction takes between 10 and 20 seconds to be done. This moderate execution time is due to the BERT Reader, which is a very large deep learning model (~110M parameters). If you have a GPU, you can use directly the GPU version of the model models/bert_qa_vGPU-sklearn.joblib. These pre-trained models are also available on the releases page of cdQA github: https://github.com/cdqa-suite/cdQA/releases"
},
{
"code": null,
"e": 5285,
"s": 5014,
"text": "You can also improve the performance of the pre-trained Reader, which was pre-trained on SQuAD 1.1 dataset. If you have an annotated dataset (that can be generated by the help of the cdQA-annotator) in the same format as SQuAD dataset you can fine-tune the reader on it:"
},
{
"code": null,
"e": 5426,
"s": 5285,
"text": "# Put the path to your json file in SQuAD format herepath_to_data = './data/SQuAD_1.1/train-v1.1.json'cdqa_pipeline.fit_reader(path_to_data)"
},
{
"code": null,
"e": 5549,
"s": 5426,
"text": "Please be aware that such fine-tuning should be performed using GPU as the BERT model is too large to be trained with CPU."
},
{
"code": null,
"e": 5687,
"s": 5549,
"text": "You can also check out other ways to do the same steps on the official tutorials: https://github.com/cdqa-suite/cdQA/tree/master/examples"
},
{
"code": null,
"e": 5795,
"s": 5687,
"text": "In order to facilitate the data annotation, the team has built a web-based application, the cdQA-annotator."
},
{
"code": null,
"e": 5895,
"s": 5795,
"text": "In order to use it, you should have your dataset transformed to a JSON file with SQuAD-like format:"
},
{
"code": null,
"e": 6071,
"s": 5895,
"text": "from cdqa.utils.converters import df2squad# Converting dataframe to SQuAD formatjson_data = df2squad(df=df, squad_version='v1.1', output_dir='.', filename='dataset-name.json')"
},
{
"code": null,
"e": 6117,
"s": 6071,
"text": "Now you can install the annotator and run it:"
},
{
"code": null,
"e": 6279,
"s": 6117,
"text": "# Clone the repogit clone https://github.com/cdqa-suite/cdQA-annotator# Install dependenciescd cdQA-annotatornpm install# Start development servercd srcvue serve"
},
{
"code": null,
"e": 6387,
"s": 6279,
"text": "Now you can go to http://localhost:8080/ and after loading your JSON file you will see something like this:"
},
{
"code": null,
"e": 6585,
"s": 6387,
"text": "To start annotating question-answer pairs you just need to write a question, highlight the answer with the mouse cursor (the answer will be written automatically), and then click on Add annotation:"
},
{
"code": null,
"e": 6722,
"s": 6585,
"text": "After the annotation, you can download it and use it to fine-tune the BERT Reader on your own data as explained in the previous section."
},
{
"code": null,
"e": 6884,
"s": 6722,
"text": "The team also has provided a web-based user interface to couple with cdQA. In this section, I will describe how you can use de UI linked to the back-end of cdQA."
},
{
"code": null,
"e": 6990,
"s": 6884,
"text": "First, you have to deploy a cdQA REST API by executing on your shell (be sure you run it on cdQA folder):"
},
{
"code": null,
"e": 7106,
"s": 6990,
"text": "export dataset_path=path-to-dataset.csvexport reader_path=path-to-reader-modelFLASK_APP=api.py flask run -h 0.0.0.0"
},
{
"code": null,
"e": 7177,
"s": 7106,
"text": "Second, you should proceed to the installation of the cdQA-ui package:"
},
{
"code": null,
"e": 7252,
"s": 7177,
"text": "git clone https://github.com/cdqa-suite/cdQA-ui &&cd cdQA-ui &&npm install"
},
{
"code": null,
"e": 7292,
"s": 7252,
"text": "Then, you start the develpoment server:"
},
{
"code": null,
"e": 7306,
"s": 7292,
"text": "npm run serve"
},
{
"code": null,
"e": 7418,
"s": 7306,
"text": "You can now access the web application on http://localhost:8080/. You will see something like the figure below:"
},
{
"code": null,
"e": 7634,
"s": 7418,
"text": "As the application is well connected to the back-end, via the REST API, you can ask a question and the application will display an answer, the passage context where the answer was found and the title of the article:"
},
{
"code": null,
"e": 7742,
"s": 7634,
"text": "If you want to couple the interface on your website you just need do the following imports in your Vue app:"
},
{
"code": null,
"e": 7975,
"s": 7742,
"text": "import Vue from 'vue'import CdqaUI from 'cdqa-ui'Vue.use(CdqaUI)import Vue from 'vue'import BootstrapVue from \"bootstrap-vue\"Vue.use(BootstrapVue)import \"bootstrap/dist/css/bootstrap.css\"import \"bootstrap-vue/dist/bootstrap-vue.css\""
},
{
"code": null,
"e": 8021,
"s": 7975,
"text": "Then you insert the cdQA interface component:"
},
{
"code": null,
"e": 8143,
"s": 8021,
"text": "You can also check out a demo of the application on the official website: https://cdqa-suite.github.io/cdQA-website/#demo"
},
{
"code": null,
"e": 8278,
"s": 8143,
"text": "In this article, I presented cdQA-suite, a software suite for the deployment of an end-to-end Closed Domain Question Answering System."
},
{
"code": null,
"e": 8558,
"s": 8278,
"text": "If you are interested in learning more about the project, feel free to check out the official GitHub repository: https://github.com/cdqa-suite. Do not hesitate to star and to follow the repositories if you liked the project and consider it valuable for you and your applications."
},
{
"code": null,
"e": 8935,
"s": 8558,
"text": "We recently released the version 1.0.2 of the cdQA package, which is performant and shows very promising results. However, there is still headroom for improvement. If you wish to contribute to the project and help with such improvements, you can take a look at our current issues: https://github.com/cdqa-suite/cdQA/issues. Feel free to choose one and to do a Pull Request :)."
},
{
"code": null,
"e": 8943,
"s": 8935,
"text": "Cheers!"
},
{
"code": null,
"e": 9008,
"s": 8943,
"text": "cdQA-suite repositories on GitHub: https://github.com/cdqa-suite"
},
{
"code": null,
"e": 9083,
"s": 9008,
"text": "official BERT version from Google: https://github.com/google-research/bert"
},
{
"code": null,
"e": 9178,
"s": 9083,
"text": "Pytorch version of BERT by HuggingFace: https://github.com/huggingface/pytorch-pretrained-BERT"
},
{
"code": null,
"e": 9237,
"s": 9178,
"text": "SQuAD dataset: https://rajpurkar.github.io/SQuAD-explorer/"
},
{
"code": null,
"e": 9306,
"s": 9237,
"text": "DrQA by Facebook Research: https://github.com/facebookresearch/DrQA/"
},
{
"code": null,
"e": 9453,
"s": 9306,
"text": "DeepPavlov, a library that has an Open-Domain QA system: https://medium.com/deeppavlov/open-domain-question-answering-with-deeppavlov-c665d2ee4d65"
}
] |
C# | Array Class - GeeksforGeeks
|
05 Aug, 2021
The Array class gives methods for creating, manipulating, searching, and sorting arrays. The Array class is not part of the System.Collections namespace, but it is still considered as a collection because it is based on the IList interface. The Array class is the base class for language implementations that support arrays.
Characteristics of Array Class:
In Array, the elements are the value of the array and the length of the array is the total number of item present in the array.
The lower bound of an Array is the index of its first element and the default value of the lower bound is 0.
The default size of an Array is 2GB.
Array objects with the same array type share the same Type object.
Example:
C#
// C# program to creating an array// of the string as coffee name, store// coffee name in the store,// and prints each value.using System;namespace geeksforgeeks { class GFG { // Main Method public static void Main() { // declares an 1D Array of string string[] store; // allocating memory for coffee names. store = new string[] {"Americano, ", "Cafe au lait, ", "Espresso, ", "Cappuccino, ", "Long Black, ", "Macchiato" }; // Displaying Elements of the array Console.WriteLine("Different types of coffee: "); Console.WriteLine(); foreach(string coffeename in store) Console.WriteLine(coffeename + " "); }}}
Different types of coffee:
Americano,
Cafe au lait,
Espresso,
Cappuccino,
Long Black,
Macchiato
Example 1:
C#
// C# program to illustrate// Length property of Array classusing System;namespace geeksforgeeks { class GFG { // Main Method public static void Main() { // declares an 1D Array of string. string[] topic; // allocating memory for topic. topic = new string[] {"Array, ", "String, ", "Stack, ", "Queue, ", "Exception, ", "Operators"}; // Displaying Elements of the array Console.WriteLine("Topic of C#:"); Console.WriteLine(); // Here we calculate and print // the length of the array, i.e. 6 Console.WriteLine("Length of the array: {0}", topic.Length); foreach(string ele in topic) Console.WriteLine(ele + " "); }}}
Topic of C#:
Length of the array: 6
Array,
String,
Stack,
Queue,
Exception,
Operators
Example 2:
C#
// C# program to illustrate the// Rank property of Array classusing System;namespace geeksforgeeks { class GFG { // Main Method public static void Main() { // declares an 1D Array of string. string[] topic; // allocating memory for topic. topic = new string[] {"Array, ", "String, ", "Stack, ", "Queue, ", "Exception, ", "Operators" }; // Displaying Elements of array Console.WriteLine("Topic of C#:"); Console.WriteLine(); // Rank property provides the dimension rank // here we use 1-D array so it return 1 // if we use 2-D array then it will return 2 Console.WriteLine("Rank of the array: {0}", topic.Rank); foreach(string ele in topic) Console.WriteLine(ele + " "); }}}
Topic of C#:
Rank of the array: 1
Array,
String,
Stack,
Queue,
Exception,
Operators
Example 1:
C#
// C# program to illustrate the Reverse() Methodusing System;namespace geeksforgeeks { class GFG { // Main Method public static void Main() { // declares an 1D Array of string. string[] topic; // allocating memory for topic. topic = new string[] {"Array, ", "String, ", "Stack, ", "Queue, ", "Exception, ", "Operators" }; // Displaying Elements of // the array before reverse Console.WriteLine("Topic of C# before reverse:"); Console.WriteLine(); foreach(string ele in topic) { Console.WriteLine(ele + " "); } Console.WriteLine(); // using Reverse() method to // reverse the given array Array.Reverse(topic); // Displaying Elements of array after reverse Console.WriteLine("Topic of C# after reverse:"); Console.WriteLine(); foreach(string val in topic) { Console.WriteLine(val + " "); } }}}
Topic of C# before reverse:
Array,
String,
Stack,
Queue,
Exception,
Operators
Topic of C# after reverse:
Operators
Exception,
Queue,
Stack,
String,
Array,
Example 2:
C#
// C# program to illustrate the Sort() Methodusing System;namespace geeksforgeeks { class GFG { // Main Method public static void Main() { // declares an 1D Array of string. string[] topic; // allocating memory for topic. topic = new string[] {"Array, ", "String, ", "Stack, ", "Queue, ", "Exception, ", "Operators" }; // Displaying Elements of the array before sort Console.WriteLine("Topic of C# before reverse:"); Console.WriteLine(); foreach(string ele in topic) { Console.WriteLine(ele + " "); } Console.WriteLine(); // using Sort() method to // sort the given array Array.Sort(topic); // Displaying Elements of // array after sort Console.WriteLine("Topic of C# after reverse:"); Console.WriteLine(); foreach(string val in topic) { Console.WriteLine(val + " "); } }}}
Topic of C# before reverse:
Array,
String,
Stack,
Queue,
Exception,
Operators
Topic of C# after reverse:
Array,
Exception,
Operators
Queue,
Stack,
String,
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.array?view=netframework-4.7.2
shubham_singh
anikakapoor
CSharp-Arrays
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between Abstract Class and Interface in C#
C# | How to check whether a List contains a specified element
C# | IsNullOrEmpty() Method
String.Split() Method in C# with Examples
Difference between Ref and Out keywords in C#
C# | Arrays of Strings
C# | Delegates
Top 50 C# Interview Questions & Answers
Extension Method in C#
C# | Abstract Classes
|
[
{
"code": null,
"e": 24889,
"s": 24861,
"text": "\n05 Aug, 2021"
},
{
"code": null,
"e": 25214,
"s": 24889,
"text": "The Array class gives methods for creating, manipulating, searching, and sorting arrays. The Array class is not part of the System.Collections namespace, but it is still considered as a collection because it is based on the IList interface. The Array class is the base class for language implementations that support arrays."
},
{
"code": null,
"e": 25247,
"s": 25214,
"text": "Characteristics of Array Class: "
},
{
"code": null,
"e": 25375,
"s": 25247,
"text": "In Array, the elements are the value of the array and the length of the array is the total number of item present in the array."
},
{
"code": null,
"e": 25484,
"s": 25375,
"text": "The lower bound of an Array is the index of its first element and the default value of the lower bound is 0."
},
{
"code": null,
"e": 25521,
"s": 25484,
"text": "The default size of an Array is 2GB."
},
{
"code": null,
"e": 25588,
"s": 25521,
"text": "Array objects with the same array type share the same Type object."
},
{
"code": null,
"e": 25598,
"s": 25588,
"text": "Example: "
},
{
"code": null,
"e": 25601,
"s": 25598,
"text": "C#"
},
{
"code": "// C# program to creating an array// of the string as coffee name, store// coffee name in the store,// and prints each value.using System;namespace geeksforgeeks { class GFG { // Main Method public static void Main() { // declares an 1D Array of string string[] store; // allocating memory for coffee names. store = new string[] {\"Americano, \", \"Cafe au lait, \", \"Espresso, \", \"Cappuccino, \", \"Long Black, \", \"Macchiato\" }; // Displaying Elements of the array Console.WriteLine(\"Different types of coffee: \"); Console.WriteLine(); foreach(string coffeename in store) Console.WriteLine(coffeename + \" \"); }}}",
"e": 26350,
"s": 25601,
"text": null
},
{
"code": null,
"e": 26458,
"s": 26350,
"text": "Different types of coffee: \n\nAmericano, \nCafe au lait, \nEspresso, \nCappuccino, \nLong Black, \nMacchiato"
},
{
"code": null,
"e": 26471,
"s": 26460,
"text": "Example 1:"
},
{
"code": null,
"e": 26474,
"s": 26471,
"text": "C#"
},
{
"code": "// C# program to illustrate// Length property of Array classusing System;namespace geeksforgeeks { class GFG { // Main Method public static void Main() { // declares an 1D Array of string. string[] topic; // allocating memory for topic. topic = new string[] {\"Array, \", \"String, \", \"Stack, \", \"Queue, \", \"Exception, \", \"Operators\"}; // Displaying Elements of the array Console.WriteLine(\"Topic of C#:\"); Console.WriteLine(); // Here we calculate and print // the length of the array, i.e. 6 Console.WriteLine(\"Length of the array: {0}\", topic.Length); foreach(string ele in topic) Console.WriteLine(ele + \" \"); }}}",
"e": 27290,
"s": 26474,
"text": null
},
{
"code": null,
"e": 27387,
"s": 27290,
"text": "Topic of C#:\n\nLength of the array: 6\nArray, \nString, \nStack, \nQueue, \nException, \nOperators"
},
{
"code": null,
"e": 27400,
"s": 27389,
"text": "Example 2:"
},
{
"code": null,
"e": 27403,
"s": 27400,
"text": "C#"
},
{
"code": "// C# program to illustrate the// Rank property of Array classusing System;namespace geeksforgeeks { class GFG { // Main Method public static void Main() { // declares an 1D Array of string. string[] topic; // allocating memory for topic. topic = new string[] {\"Array, \", \"String, \", \"Stack, \", \"Queue, \", \"Exception, \", \"Operators\" }; // Displaying Elements of array Console.WriteLine(\"Topic of C#:\"); Console.WriteLine(); // Rank property provides the dimension rank // here we use 1-D array so it return 1 // if we use 2-D array then it will return 2 Console.WriteLine(\"Rank of the array: {0}\", topic.Rank); foreach(string ele in topic) Console.WriteLine(ele + \" \"); }}}",
"e": 28287,
"s": 27403,
"text": null
},
{
"code": null,
"e": 28382,
"s": 28287,
"text": "Topic of C#:\n\nRank of the array: 1\nArray, \nString, \nStack, \nQueue, \nException, \nOperators"
},
{
"code": null,
"e": 28395,
"s": 28384,
"text": "Example 1:"
},
{
"code": null,
"e": 28398,
"s": 28395,
"text": "C#"
},
{
"code": "// C# program to illustrate the Reverse() Methodusing System;namespace geeksforgeeks { class GFG { // Main Method public static void Main() { // declares an 1D Array of string. string[] topic; // allocating memory for topic. topic = new string[] {\"Array, \", \"String, \", \"Stack, \", \"Queue, \", \"Exception, \", \"Operators\" }; // Displaying Elements of // the array before reverse Console.WriteLine(\"Topic of C# before reverse:\"); Console.WriteLine(); foreach(string ele in topic) { Console.WriteLine(ele + \" \"); } Console.WriteLine(); // using Reverse() method to // reverse the given array Array.Reverse(topic); // Displaying Elements of array after reverse Console.WriteLine(\"Topic of C# after reverse:\"); Console.WriteLine(); foreach(string val in topic) { Console.WriteLine(val + \" \"); } }}}",
"e": 29435,
"s": 28398,
"text": null
},
{
"code": null,
"e": 29613,
"s": 29435,
"text": "Topic of C# before reverse:\n\nArray, \nString, \nStack, \nQueue, \nException, \nOperators \n\nTopic of C# after reverse:\n\nOperators \nException, \nQueue, \nStack, \nString, \nArray,"
},
{
"code": null,
"e": 29626,
"s": 29615,
"text": "Example 2:"
},
{
"code": null,
"e": 29629,
"s": 29626,
"text": "C#"
},
{
"code": "// C# program to illustrate the Sort() Methodusing System;namespace geeksforgeeks { class GFG { // Main Method public static void Main() { // declares an 1D Array of string. string[] topic; // allocating memory for topic. topic = new string[] {\"Array, \", \"String, \", \"Stack, \", \"Queue, \", \"Exception, \", \"Operators\" }; // Displaying Elements of the array before sort Console.WriteLine(\"Topic of C# before reverse:\"); Console.WriteLine(); foreach(string ele in topic) { Console.WriteLine(ele + \" \"); } Console.WriteLine(); // using Sort() method to // sort the given array Array.Sort(topic); // Displaying Elements of // array after sort Console.WriteLine(\"Topic of C# after reverse:\"); Console.WriteLine(); foreach(string val in topic) { Console.WriteLine(val + \" \"); } }}}",
"e": 30648,
"s": 29629,
"text": null
},
{
"code": null,
"e": 30826,
"s": 30648,
"text": "Topic of C# before reverse:\n\nArray, \nString, \nStack, \nQueue, \nException, \nOperators \n\nTopic of C# after reverse:\n\nArray, \nException, \nOperators \nQueue, \nStack, \nString,"
},
{
"code": null,
"e": 30840,
"s": 30828,
"text": "Reference: "
},
{
"code": null,
"e": 30921,
"s": 30840,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.array?view=netframework-4.7.2"
},
{
"code": null,
"e": 30937,
"s": 30923,
"text": "shubham_singh"
},
{
"code": null,
"e": 30949,
"s": 30937,
"text": "anikakapoor"
},
{
"code": null,
"e": 30963,
"s": 30949,
"text": "CSharp-Arrays"
},
{
"code": null,
"e": 30966,
"s": 30963,
"text": "C#"
},
{
"code": null,
"e": 31064,
"s": 30966,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31073,
"s": 31064,
"text": "Comments"
},
{
"code": null,
"e": 31086,
"s": 31073,
"text": "Old Comments"
},
{
"code": null,
"e": 31140,
"s": 31086,
"text": "Difference between Abstract Class and Interface in C#"
},
{
"code": null,
"e": 31202,
"s": 31140,
"text": "C# | How to check whether a List contains a specified element"
},
{
"code": null,
"e": 31230,
"s": 31202,
"text": "C# | IsNullOrEmpty() Method"
},
{
"code": null,
"e": 31272,
"s": 31230,
"text": "String.Split() Method in C# with Examples"
},
{
"code": null,
"e": 31318,
"s": 31272,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 31341,
"s": 31318,
"text": "C# | Arrays of Strings"
},
{
"code": null,
"e": 31356,
"s": 31341,
"text": "C# | Delegates"
},
{
"code": null,
"e": 31396,
"s": 31356,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 31419,
"s": 31396,
"text": "Extension Method in C#"
}
] |
How to access Pandas Series elements by using indexing?
|
The data present in the pandas Series object has indexing labels, those index labels are used to access or retrieve elements. Each index value addresses an element in series.
Indexes are basically represented in two types: positional indexing and labeled indexing. Positional indexing is nothing but integer values starting from 0 to n-1 (n number of elements present in series). Whereas labeled indexing is user-defined labels that can be anything like integers, objects, date times and etc.,
# importing required packages
import pandas as pd
import numpy as np
# creating pandas Series object
series = pd.Series(np.random.rand(10))
print(series)
print('\nAccessing elements by using index values')
# accessing elements by using index values
print(series[[2,7]])
The following example will create a positional indexed pandas Series object with 10 randomly generated values by using the NumPy.random model.
The series[[2,7]] will access the 2 and 7 addressed elements from our series object at a time. If you want to access one element then we can say it like this series[index_values].
0 0.517225
1 0.933815
2 0.183132
3 0.333059
4 0.993192
5 0.826969
6 0.761213
7 0.274025
8 0.129120
9 0.901257
dtype: float64
Accessing elements by using index values
2 0.183132
7 0.274025
dtype: float64
0.183132 and 0.274025 are the values for the positional index of 2,7 from our series object.
If we have labeled index data, and we want to access the series elements then we can specify those labeled index addresses to retrieve elements.
# importing required packages
import pandas as pd
import numpy as np
# creating pandas Series object
series = pd.Series({'black':'white', 'body':'soul', 'bread':'butter', 'first':'last'})
print(series)
print('\nAccessing elements by using index labels')
# accessing elements by using index values
print(series['black'])
Initially, we have created a Series object with labeled index data using a python dictionary with string-type keys and values, and these keys act as our index values.
In this example, we are accessing an element with an address ‘black’ so the resultant output will be seen in the output block.
black white
body soul
bread butter
first last
dtype: object
Accessing elements by using index labels
white
The output for the label ‘black’ is ‘white’, in the same way, we can access labeled elements from a series. The first block of the above output is an entire series object.
|
[
{
"code": null,
"e": 1237,
"s": 1062,
"text": "The data present in the pandas Series object has indexing labels, those index labels are used to access or retrieve elements. Each index value addresses an element in series."
},
{
"code": null,
"e": 1556,
"s": 1237,
"text": "Indexes are basically represented in two types: positional indexing and labeled indexing. Positional indexing is nothing but integer values starting from 0 to n-1 (n number of elements present in series). Whereas labeled indexing is user-defined labels that can be anything like integers, objects, date times and etc.,"
},
{
"code": null,
"e": 1828,
"s": 1556,
"text": "# importing required packages\nimport pandas as pd\nimport numpy as np\n\n# creating pandas Series object\nseries = pd.Series(np.random.rand(10))\nprint(series)\n\nprint('\\nAccessing elements by using index values')\n# accessing elements by using index values\nprint(series[[2,7]])"
},
{
"code": null,
"e": 1971,
"s": 1828,
"text": "The following example will create a positional indexed pandas Series object with 10 randomly generated values by using the NumPy.random model."
},
{
"code": null,
"e": 2151,
"s": 1971,
"text": "The series[[2,7]] will access the 2 and 7 addressed elements from our series object at a time. If you want to access one element then we can say it like this series[index_values]."
},
{
"code": null,
"e": 2379,
"s": 2151,
"text": "0 0.517225\n1 0.933815\n2 0.183132\n3 0.333059\n4 0.993192\n5 0.826969\n6 0.761213\n7 0.274025\n8 0.129120\n9 0.901257\ndtype: float64\n\nAccessing elements by using index values\n2 0.183132\n7 0.274025\ndtype: float64"
},
{
"code": null,
"e": 2472,
"s": 2379,
"text": "0.183132 and 0.274025 are the values for the positional index of 2,7 from our series object."
},
{
"code": null,
"e": 2617,
"s": 2472,
"text": "If we have labeled index data, and we want to access the series elements then we can specify those labeled index addresses to retrieve elements."
},
{
"code": null,
"e": 2939,
"s": 2617,
"text": "# importing required packages\nimport pandas as pd\nimport numpy as np\n\n# creating pandas Series object\nseries = pd.Series({'black':'white', 'body':'soul', 'bread':'butter', 'first':'last'})\nprint(series)\n\nprint('\\nAccessing elements by using index labels')\n# accessing elements by using index values\nprint(series['black'])"
},
{
"code": null,
"e": 3106,
"s": 2939,
"text": "Initially, we have created a Series object with labeled index data using a python dictionary with string-type keys and values, and these keys act as our index values."
},
{
"code": null,
"e": 3233,
"s": 3106,
"text": "In this example, we are accessing an element with an address ‘black’ so the resultant output will be seen in the output block."
},
{
"code": null,
"e": 3351,
"s": 3233,
"text": "black white\nbody soul\nbread butter\nfirst last\ndtype: object\n\nAccessing elements by using index labels\nwhite"
},
{
"code": null,
"e": 3523,
"s": 3351,
"text": "The output for the label ‘black’ is ‘white’, in the same way, we can access labeled elements from a series. The first block of the above output is an entire series object."
}
] |
Understanding and Coding a ResNet in Keras | by Priya Dwivedi | Towards Data Science
|
ResNet, short for Residual Networks is a classic neural network used as a backbone for many computer vision tasks. This model was the winner of ImageNet challenge in 2015. The fundamental breakthrough with ResNet was it allowed us to train extremely deep neural networks with 150+layers successfully. Prior to ResNet training very deep neural networks was difficult due to the problem of vanishing gradients.
AlexNet, the winner of ImageNet 2012 and the model that apparently kick started the focus on deep learning had only 8 convolutional layers, the VGG network had 19 and Inception or GoogleNet had 22 layers and ResNet 152 had 152 layers. In this blog we will code a ResNet-50 that is a smaller version of ResNet 152 and frequently used as a starting point for transfer learning.
However, increasing network depth does not work by simply stacking layers together. Deep networks are hard to train because of the notorious vanishing gradient problem — as the gradient is back-propagated to earlier layers, repeated multiplication may make the gradient extremely small. As a result, as the network goes deeper, its performance gets saturated or even starts degrading rapidly.
I learnt about coding ResNets from DeepLearning.AI course by Andrew Ng. I highly recommend this course.
On my Github repo, I have shared two notebooks one that codes ResNet from scratch as explained in DeepLearning.AI and the other that uses the pretrained model in Keras. I hope you pull the code and try it for yourself.
ResNet first introduced the concept of skip connection. The diagram below illustrates skip connection. The figure on the left is stacking convolution layers together one after the other. On the right we still stack convolution layers as before but we now also add the original input to the output of the convolution block. This is called skip connection
It can be written as two lines of code :
X_shortcut = X # Store the initial value of X in a variable## Perform convolution + batch norm operations on XX = Add()([X, X_shortcut]) # SKIP Connection
The coding is quite simple but there is one important consideration — since X, X_shortcut above are two matrixes, you can add them only if they have the same shape. So if the convolution + batch norm operations are done in a way that the output shape is the same,then we can simply add them as shown below.
Otherwise, the x_shortcut goes through a convolution layer chosen such that the output from it is the same dimension as the output from the convolution block as shown below:
In the notebook on Github, the two functions identity_block and convolution_block implement above. These functions use Keras to implement Convolution and Batch Norm layers with ReLU activation. Skip connection is technically the one line X = Add()([X, X_shortcut]).
One important thing to note here is that the skip connection is applied before the RELU activation as shown in the diagram above. Research has found that this has the best results.
This is an interesting question. I think there are two reasons why Skip connections work here:
They mitigate the problem of vanishing gradient by allowing this alternate shortcut path for gradient to flow throughThey allow the model to learn an identity function which ensures that the higher layer will perform at least as good as the lower layer, and not worse
They mitigate the problem of vanishing gradient by allowing this alternate shortcut path for gradient to flow through
They allow the model to learn an identity function which ensures that the higher layer will perform at least as good as the lower layer, and not worse
Infact since ResNet skip connections are used in a lot more model architectures like the Fully Convolutional Network (FCN) and U-Net. They are used to flow information from earlier layers in the model to later layers. In these architectures they are used to pass information from the downsampling layers to the upsampling layers.
The identity and convolution blocks coded in the notebook are then combined to create a ResNet-50 model with the architecture shown below:
The ResNet-50 model consists of 5 stages each with a convolution and Identity block. Each convolution block has 3 convolution layers and each identity block also has 3 convolution layers. The ResNet-50 has over 23 million trainable parameters.
I have tested this model on the signs data set which is also included in my Github repo. This data set has hand images corresponding to 6 classes. We have 1080 train images and 120 test images.
Our ResNet-50 gets to 86% test accuracy in 25 epochs of training. Not bad!
I loved coding the ResNet model myself since it allowed me a better understanding of a network that I frequently use in many transfer learning tasks related to image classification, object localization, segmentation etc.
However for more regular use it is faster to use the pretrained ResNet-50 in Keras. Keras has many of these backbone models with their Imagenet weights available in its library.
I have uploaded a notebook on my Github that uses Keras to load the pretrained ResNet-50. You can load the model with 1 line code:
base_model = applications.resnet50.ResNet50(weights= None, include_top=False, input_shape= (img_height,img_width,3))
Here weights=None since I want to initialize the model with random weights as I did on the ResNet-50 I coded. Otherwise I can also load the pretrained ImageNet weights. I set include_top=False to not include the final pooling and fully connected layer in the original model. I added Global Average Pooling and a dense output layaer to the ResNet-50 model.
x = base_model.outputx = GlobalAveragePooling2D()(x)x = Dropout(0.7)(x)predictions = Dense(num_classes, activation= 'softmax')(x)model = Model(inputs = base_model.input, outputs = predictions)
As shown above Keras provides a very convenient interface to load the pretrained models but it is important to code the ResNet yourself as well at least once so you understand the concept and can maybe apply this learning to another new architecture you are creating.
The Keras ResNet got to an accuracy of 75% after training on 100 epochs with Adam optimizer and a learning rate of 0.0001. The accuracy is a bit lower than our own coded model and I guess this has to do with weight initializations.
Keras also provides an easy interface for data augmentation so if you get a chance, try augmenting this data set and see if that results in better performance.
ResNet is a powerful backbone model that is used very frequently in many computer vision tasks
ResNet uses skip connection to add the output from an earlier layer to a later layer. This helps it mitigate the vanishing gradient problem
You can use Keras to load their pretrained ResNet 50 or use the code I have shared to code ResNet yourself.
I have my own deep learning consultancy and love to work on interesting problems. I have helped many startups deploy innovative AI based solutions. Check us out at — http://deeplearninganalytics.org/.
You can also see my other writings at: https://medium.com/@priya.dwivedi
If you have a project that we can collaborate on, then please contact me through my website or at info@deeplearninganalytics.org
|
[
{
"code": null,
"e": 580,
"s": 171,
"text": "ResNet, short for Residual Networks is a classic neural network used as a backbone for many computer vision tasks. This model was the winner of ImageNet challenge in 2015. The fundamental breakthrough with ResNet was it allowed us to train extremely deep neural networks with 150+layers successfully. Prior to ResNet training very deep neural networks was difficult due to the problem of vanishing gradients."
},
{
"code": null,
"e": 956,
"s": 580,
"text": "AlexNet, the winner of ImageNet 2012 and the model that apparently kick started the focus on deep learning had only 8 convolutional layers, the VGG network had 19 and Inception or GoogleNet had 22 layers and ResNet 152 had 152 layers. In this blog we will code a ResNet-50 that is a smaller version of ResNet 152 and frequently used as a starting point for transfer learning."
},
{
"code": null,
"e": 1349,
"s": 956,
"text": "However, increasing network depth does not work by simply stacking layers together. Deep networks are hard to train because of the notorious vanishing gradient problem — as the gradient is back-propagated to earlier layers, repeated multiplication may make the gradient extremely small. As a result, as the network goes deeper, its performance gets saturated or even starts degrading rapidly."
},
{
"code": null,
"e": 1453,
"s": 1349,
"text": "I learnt about coding ResNets from DeepLearning.AI course by Andrew Ng. I highly recommend this course."
},
{
"code": null,
"e": 1672,
"s": 1453,
"text": "On my Github repo, I have shared two notebooks one that codes ResNet from scratch as explained in DeepLearning.AI and the other that uses the pretrained model in Keras. I hope you pull the code and try it for yourself."
},
{
"code": null,
"e": 2026,
"s": 1672,
"text": "ResNet first introduced the concept of skip connection. The diagram below illustrates skip connection. The figure on the left is stacking convolution layers together one after the other. On the right we still stack convolution layers as before but we now also add the original input to the output of the convolution block. This is called skip connection"
},
{
"code": null,
"e": 2067,
"s": 2026,
"text": "It can be written as two lines of code :"
},
{
"code": null,
"e": 2222,
"s": 2067,
"text": "X_shortcut = X # Store the initial value of X in a variable## Perform convolution + batch norm operations on XX = Add()([X, X_shortcut]) # SKIP Connection"
},
{
"code": null,
"e": 2529,
"s": 2222,
"text": "The coding is quite simple but there is one important consideration — since X, X_shortcut above are two matrixes, you can add them only if they have the same shape. So if the convolution + batch norm operations are done in a way that the output shape is the same,then we can simply add them as shown below."
},
{
"code": null,
"e": 2703,
"s": 2529,
"text": "Otherwise, the x_shortcut goes through a convolution layer chosen such that the output from it is the same dimension as the output from the convolution block as shown below:"
},
{
"code": null,
"e": 2969,
"s": 2703,
"text": "In the notebook on Github, the two functions identity_block and convolution_block implement above. These functions use Keras to implement Convolution and Batch Norm layers with ReLU activation. Skip connection is technically the one line X = Add()([X, X_shortcut])."
},
{
"code": null,
"e": 3150,
"s": 2969,
"text": "One important thing to note here is that the skip connection is applied before the RELU activation as shown in the diagram above. Research has found that this has the best results."
},
{
"code": null,
"e": 3245,
"s": 3150,
"text": "This is an interesting question. I think there are two reasons why Skip connections work here:"
},
{
"code": null,
"e": 3513,
"s": 3245,
"text": "They mitigate the problem of vanishing gradient by allowing this alternate shortcut path for gradient to flow throughThey allow the model to learn an identity function which ensures that the higher layer will perform at least as good as the lower layer, and not worse"
},
{
"code": null,
"e": 3631,
"s": 3513,
"text": "They mitigate the problem of vanishing gradient by allowing this alternate shortcut path for gradient to flow through"
},
{
"code": null,
"e": 3782,
"s": 3631,
"text": "They allow the model to learn an identity function which ensures that the higher layer will perform at least as good as the lower layer, and not worse"
},
{
"code": null,
"e": 4112,
"s": 3782,
"text": "Infact since ResNet skip connections are used in a lot more model architectures like the Fully Convolutional Network (FCN) and U-Net. They are used to flow information from earlier layers in the model to later layers. In these architectures they are used to pass information from the downsampling layers to the upsampling layers."
},
{
"code": null,
"e": 4251,
"s": 4112,
"text": "The identity and convolution blocks coded in the notebook are then combined to create a ResNet-50 model with the architecture shown below:"
},
{
"code": null,
"e": 4495,
"s": 4251,
"text": "The ResNet-50 model consists of 5 stages each with a convolution and Identity block. Each convolution block has 3 convolution layers and each identity block also has 3 convolution layers. The ResNet-50 has over 23 million trainable parameters."
},
{
"code": null,
"e": 4689,
"s": 4495,
"text": "I have tested this model on the signs data set which is also included in my Github repo. This data set has hand images corresponding to 6 classes. We have 1080 train images and 120 test images."
},
{
"code": null,
"e": 4764,
"s": 4689,
"text": "Our ResNet-50 gets to 86% test accuracy in 25 epochs of training. Not bad!"
},
{
"code": null,
"e": 4985,
"s": 4764,
"text": "I loved coding the ResNet model myself since it allowed me a better understanding of a network that I frequently use in many transfer learning tasks related to image classification, object localization, segmentation etc."
},
{
"code": null,
"e": 5163,
"s": 4985,
"text": "However for more regular use it is faster to use the pretrained ResNet-50 in Keras. Keras has many of these backbone models with their Imagenet weights available in its library."
},
{
"code": null,
"e": 5294,
"s": 5163,
"text": "I have uploaded a notebook on my Github that uses Keras to load the pretrained ResNet-50. You can load the model with 1 line code:"
},
{
"code": null,
"e": 5411,
"s": 5294,
"text": "base_model = applications.resnet50.ResNet50(weights= None, include_top=False, input_shape= (img_height,img_width,3))"
},
{
"code": null,
"e": 5767,
"s": 5411,
"text": "Here weights=None since I want to initialize the model with random weights as I did on the ResNet-50 I coded. Otherwise I can also load the pretrained ImageNet weights. I set include_top=False to not include the final pooling and fully connected layer in the original model. I added Global Average Pooling and a dense output layaer to the ResNet-50 model."
},
{
"code": null,
"e": 5960,
"s": 5767,
"text": "x = base_model.outputx = GlobalAveragePooling2D()(x)x = Dropout(0.7)(x)predictions = Dense(num_classes, activation= 'softmax')(x)model = Model(inputs = base_model.input, outputs = predictions)"
},
{
"code": null,
"e": 6228,
"s": 5960,
"text": "As shown above Keras provides a very convenient interface to load the pretrained models but it is important to code the ResNet yourself as well at least once so you understand the concept and can maybe apply this learning to another new architecture you are creating."
},
{
"code": null,
"e": 6460,
"s": 6228,
"text": "The Keras ResNet got to an accuracy of 75% after training on 100 epochs with Adam optimizer and a learning rate of 0.0001. The accuracy is a bit lower than our own coded model and I guess this has to do with weight initializations."
},
{
"code": null,
"e": 6620,
"s": 6460,
"text": "Keras also provides an easy interface for data augmentation so if you get a chance, try augmenting this data set and see if that results in better performance."
},
{
"code": null,
"e": 6715,
"s": 6620,
"text": "ResNet is a powerful backbone model that is used very frequently in many computer vision tasks"
},
{
"code": null,
"e": 6855,
"s": 6715,
"text": "ResNet uses skip connection to add the output from an earlier layer to a later layer. This helps it mitigate the vanishing gradient problem"
},
{
"code": null,
"e": 6963,
"s": 6855,
"text": "You can use Keras to load their pretrained ResNet 50 or use the code I have shared to code ResNet yourself."
},
{
"code": null,
"e": 7164,
"s": 6963,
"text": "I have my own deep learning consultancy and love to work on interesting problems. I have helped many startups deploy innovative AI based solutions. Check us out at — http://deeplearninganalytics.org/."
},
{
"code": null,
"e": 7237,
"s": 7164,
"text": "You can also see my other writings at: https://medium.com/@priya.dwivedi"
}
] |
Comparator thenComparingInt() method in Java with examples - GeeksforGeeks
|
29 Apr, 2019
The thenComparingInt(java.util.function.ToIntFunction) method of Comparator Interface in Java returns a lexicographic-order comparator with a function that extracts a int sort key.
Syntax:
default Comparator <T>
thenComparingInt(ToIntFunction <T> keyExtractor)
Parameters: This method accepts keyExtractor which is the function used to extract the Int sort key.
Return value: This method returns a lexicographic-order comparator composed of this and then the Int sort key.
Exception: This method throws NullPointerException if the argument is null.
Below programs illustrate thenComparingInt(java.util.function.ToIntFunction) method:Program 1:
// Java program to demonstrate Comparator// thenComparingInt(ToIntFunction) method import java.util.Arrays;import java.util.Collections;import java.util.Comparator;import java.util.List; public class GFG { public static void main(String... args) { List<HardwareItems> list = getItems(); System.out.println("before sort:"); list.forEach(System.out::println); // Apply sorting and // also apply thenComparingInt() Collections .sort( list, Comparator .comparing(HardwareItems::getName) .thenComparingInt(HardwareItems::getPrice)); System.out.println("after sort:"); list.forEach(System.out::println); } private static List<HardwareItems> getItems() { return Arrays.asList( new HardwareItems("Laptop", 40000), new HardwareItems("Desktop", 20000), new HardwareItems("Laptop", 45500), new HardwareItems("Monitor", 10000), new HardwareItems("Desktop", 22000)); } private static class HardwareItems { private String name; private int price; public HardwareItems(String name, int price) { this.name = name; this.price = price; } public String getName() { return name; } public int getPrice() { return price; } @Override public String toString() { return "HardwareItems [name=" + name + ", price=" + price + "]"; } }}
The output printed on console of IDE is shown below.Output:You can see in example first sorting is done on name wise and if the name is same then price wise which is int type.
Program 2:
// Java program to demonstrate Comparator// thenComparingInt(ToIntFunction) method import java.util.Arrays;import java.util.Comparator;import java.util.List; public class GFG { public static void main(String... args) { List<Double> list = Arrays.asList(1.12, 2.4, 3.43, 4.343, 5.434); try { // apply thenComparingInt Comparator.comparing(list::get) .thenComparingInt(null); } catch (Exception e) { System.out.printf("Exception:" + e); } }}
The output printed on console is shown below.Output:
References: https://docs.oracle.com/javase/10/docs/api/java/util/Comparator.html#thenComparingInt(java.util.function.ToIntFunction)()
Java - util package
Java-Comparator
Java-Functions
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Generics in Java
Comparator Interface in Java with Examples
Strings in Java
Difference between Abstract Class and Interface in Java
How to remove an element from ArrayList in Java?
|
[
{
"code": null,
"e": 23557,
"s": 23529,
"text": "\n29 Apr, 2019"
},
{
"code": null,
"e": 23738,
"s": 23557,
"text": "The thenComparingInt(java.util.function.ToIntFunction) method of Comparator Interface in Java returns a lexicographic-order comparator with a function that extracts a int sort key."
},
{
"code": null,
"e": 23746,
"s": 23738,
"text": "Syntax:"
},
{
"code": null,
"e": 23824,
"s": 23746,
"text": "default Comparator <T> \n thenComparingInt(ToIntFunction <T> keyExtractor)\n"
},
{
"code": null,
"e": 23925,
"s": 23824,
"text": "Parameters: This method accepts keyExtractor which is the function used to extract the Int sort key."
},
{
"code": null,
"e": 24036,
"s": 23925,
"text": "Return value: This method returns a lexicographic-order comparator composed of this and then the Int sort key."
},
{
"code": null,
"e": 24112,
"s": 24036,
"text": "Exception: This method throws NullPointerException if the argument is null."
},
{
"code": null,
"e": 24207,
"s": 24112,
"text": "Below programs illustrate thenComparingInt(java.util.function.ToIntFunction) method:Program 1:"
},
{
"code": "// Java program to demonstrate Comparator// thenComparingInt(ToIntFunction) method import java.util.Arrays;import java.util.Collections;import java.util.Comparator;import java.util.List; public class GFG { public static void main(String... args) { List<HardwareItems> list = getItems(); System.out.println(\"before sort:\"); list.forEach(System.out::println); // Apply sorting and // also apply thenComparingInt() Collections .sort( list, Comparator .comparing(HardwareItems::getName) .thenComparingInt(HardwareItems::getPrice)); System.out.println(\"after sort:\"); list.forEach(System.out::println); } private static List<HardwareItems> getItems() { return Arrays.asList( new HardwareItems(\"Laptop\", 40000), new HardwareItems(\"Desktop\", 20000), new HardwareItems(\"Laptop\", 45500), new HardwareItems(\"Monitor\", 10000), new HardwareItems(\"Desktop\", 22000)); } private static class HardwareItems { private String name; private int price; public HardwareItems(String name, int price) { this.name = name; this.price = price; } public String getName() { return name; } public int getPrice() { return price; } @Override public String toString() { return \"HardwareItems [name=\" + name + \", price=\" + price + \"]\"; } }}",
"e": 25861,
"s": 24207,
"text": null
},
{
"code": null,
"e": 26037,
"s": 25861,
"text": "The output printed on console of IDE is shown below.Output:You can see in example first sorting is done on name wise and if the name is same then price wise which is int type."
},
{
"code": null,
"e": 26048,
"s": 26037,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate Comparator// thenComparingInt(ToIntFunction) method import java.util.Arrays;import java.util.Comparator;import java.util.List; public class GFG { public static void main(String... args) { List<Double> list = Arrays.asList(1.12, 2.4, 3.43, 4.343, 5.434); try { // apply thenComparingInt Comparator.comparing(list::get) .thenComparingInt(null); } catch (Exception e) { System.out.printf(\"Exception:\" + e); } }}",
"e": 26631,
"s": 26048,
"text": null
},
{
"code": null,
"e": 26684,
"s": 26631,
"text": "The output printed on console is shown below.Output:"
},
{
"code": null,
"e": 26818,
"s": 26684,
"text": "References: https://docs.oracle.com/javase/10/docs/api/java/util/Comparator.html#thenComparingInt(java.util.function.ToIntFunction)()"
},
{
"code": null,
"e": 26838,
"s": 26818,
"text": "Java - util package"
},
{
"code": null,
"e": 26854,
"s": 26838,
"text": "Java-Comparator"
},
{
"code": null,
"e": 26869,
"s": 26854,
"text": "Java-Functions"
},
{
"code": null,
"e": 26874,
"s": 26869,
"text": "Java"
},
{
"code": null,
"e": 26879,
"s": 26874,
"text": "Java"
},
{
"code": null,
"e": 26977,
"s": 26879,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26986,
"s": 26977,
"text": "Comments"
},
{
"code": null,
"e": 26999,
"s": 26986,
"text": "Old Comments"
},
{
"code": null,
"e": 27029,
"s": 26999,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 27044,
"s": 27029,
"text": "Stream In Java"
},
{
"code": null,
"e": 27065,
"s": 27044,
"text": "Constructors in Java"
},
{
"code": null,
"e": 27111,
"s": 27065,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 27130,
"s": 27111,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 27147,
"s": 27130,
"text": "Generics in Java"
},
{
"code": null,
"e": 27190,
"s": 27147,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 27206,
"s": 27190,
"text": "Strings in Java"
},
{
"code": null,
"e": 27262,
"s": 27206,
"text": "Difference between Abstract Class and Interface in Java"
}
] |
Can a method have the same name as the class?
|
Yes, you can write a method in Java with method name same as class name. But it is not suggestable because of the following reasons −
Using upper case letter at the starting of the name of the method violates the coding conventions of Java for writing a methods name.
There is a chance of assuming such methods with constructors of the class.
Live Demo
public class Sample {
public void Sample(){
System.out.println("This is a sample method");
}
public static void main(String args[]){
Sample obj = new Sample();
obj.Sample();
}
}
This is a sample method
|
[
{
"code": null,
"e": 1196,
"s": 1062,
"text": "Yes, you can write a method in Java with method name same as class name. But it is not suggestable because of the following reasons −"
},
{
"code": null,
"e": 1330,
"s": 1196,
"text": "Using upper case letter at the starting of the name of the method violates the coding conventions of Java for writing a methods name."
},
{
"code": null,
"e": 1405,
"s": 1330,
"text": "There is a chance of assuming such methods with constructors of the class."
},
{
"code": null,
"e": 1416,
"s": 1405,
"text": " Live Demo"
},
{
"code": null,
"e": 1624,
"s": 1416,
"text": "public class Sample {\n public void Sample(){\n System.out.println(\"This is a sample method\");\n }\n public static void main(String args[]){\n Sample obj = new Sample();\n obj.Sample();\n }\n}"
},
{
"code": null,
"e": 1649,
"s": 1624,
"text": "This is a sample method\n"
}
] |
Ansible - Environment Setup
|
In this chapter, we will learn about the environment setup of Ansible.
Mainly, there are two types of machines when we talk about deployment −
Control machine − Machine from where we can manage other machines.
Control machine − Machine from where we can manage other machines.
Remote machine − Machines which are handled/controlled by control machine.
Remote machine − Machines which are handled/controlled by control machine.
There can be multiple remote machines which are handled by one control machine. So, for managing remote machines we have to install Ansible on control machine.
Ansible can be run from any machine with Python 2 (versions 2.6 or 2.7) or Python 3 (versions 3.5 and higher) installed.
Note − Windows does not support control machine.
By default, Ansible uses ssh to manage remote machine.
Ansible does not add any database. It does not require any daemons to start or keep it running. While managing remote machines, Ansible does not leave any software installed or running on them. Hence, there is no question of how to upgrade it when moving to a new version.
Ansible can be installed on control machine which have above mentioned requirements in different ways. You can install the latest release through Apt, yum, pkg, pip, OpenCSW, pacman, etc.
For installing Ansible you have to configure PPA on your machine. For this, you have to run the following line of code −
$ sudo apt-get update
$ sudo apt-get install software-properties-common
$ sudo apt-add-repository ppa:ansible/ansible $ sudo apt-get update
$ sudo apt-get install ansible
After running the above line of code, you are ready to manage remote machines through Ansible. Just run Ansible–version to check the version and just to check whether Ansible was installed properly or not.
41 Lectures
5 hours
AR Shankar
11 Lectures
58 mins
Musab Zayadneh
59 Lectures
15.5 hours
Narendra P
11 Lectures
1 hours
Sagar Mehta
39 Lectures
4 hours
Vikas Yadav
4 Lectures
3.5 hours
GreyCampus Inc.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1862,
"s": 1791,
"text": "In this chapter, we will learn about the environment setup of Ansible."
},
{
"code": null,
"e": 1934,
"s": 1862,
"text": "Mainly, there are two types of machines when we talk about deployment −"
},
{
"code": null,
"e": 2001,
"s": 1934,
"text": "Control machine − Machine from where we can manage other machines."
},
{
"code": null,
"e": 2068,
"s": 2001,
"text": "Control machine − Machine from where we can manage other machines."
},
{
"code": null,
"e": 2143,
"s": 2068,
"text": "Remote machine − Machines which are handled/controlled by control machine."
},
{
"code": null,
"e": 2218,
"s": 2143,
"text": "Remote machine − Machines which are handled/controlled by control machine."
},
{
"code": null,
"e": 2378,
"s": 2218,
"text": "There can be multiple remote machines which are handled by one control machine. So, for managing remote machines we have to install Ansible on control machine."
},
{
"code": null,
"e": 2499,
"s": 2378,
"text": "Ansible can be run from any machine with Python 2 (versions 2.6 or 2.7) or Python 3 (versions 3.5 and higher) installed."
},
{
"code": null,
"e": 2548,
"s": 2499,
"text": "Note − Windows does not support control machine."
},
{
"code": null,
"e": 2603,
"s": 2548,
"text": "By default, Ansible uses ssh to manage remote machine."
},
{
"code": null,
"e": 2876,
"s": 2603,
"text": "Ansible does not add any database. It does not require any daemons to start or keep it running. While managing remote machines, Ansible does not leave any software installed or running on them. Hence, there is no question of how to upgrade it when moving to a new version."
},
{
"code": null,
"e": 3064,
"s": 2876,
"text": "Ansible can be installed on control machine which have above mentioned requirements in different ways. You can install the latest release through Apt, yum, pkg, pip, OpenCSW, pacman, etc."
},
{
"code": null,
"e": 3185,
"s": 3064,
"text": "For installing Ansible you have to configure PPA on your machine. For this, you have to run the following line of code −"
},
{
"code": null,
"e": 3360,
"s": 3185,
"text": "$ sudo apt-get update \n$ sudo apt-get install software-properties-common \n$ sudo apt-add-repository ppa:ansible/ansible $ sudo apt-get update \n$ sudo apt-get install ansible\n"
},
{
"code": null,
"e": 3566,
"s": 3360,
"text": "After running the above line of code, you are ready to manage remote machines through Ansible. Just run Ansible–version to check the version and just to check whether Ansible was installed properly or not."
},
{
"code": null,
"e": 3599,
"s": 3566,
"text": "\n 41 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 3611,
"s": 3599,
"text": " AR Shankar"
},
{
"code": null,
"e": 3643,
"s": 3611,
"text": "\n 11 Lectures \n 58 mins\n"
},
{
"code": null,
"e": 3659,
"s": 3643,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 3695,
"s": 3659,
"text": "\n 59 Lectures \n 15.5 hours \n"
},
{
"code": null,
"e": 3707,
"s": 3695,
"text": " Narendra P"
},
{
"code": null,
"e": 3740,
"s": 3707,
"text": "\n 11 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3753,
"s": 3740,
"text": " Sagar Mehta"
},
{
"code": null,
"e": 3786,
"s": 3753,
"text": "\n 39 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3799,
"s": 3786,
"text": " Vikas Yadav"
},
{
"code": null,
"e": 3833,
"s": 3799,
"text": "\n 4 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3850,
"s": 3833,
"text": " GreyCampus Inc."
},
{
"code": null,
"e": 3857,
"s": 3850,
"text": " Print"
},
{
"code": null,
"e": 3868,
"s": 3857,
"text": " Add Notes"
}
] |
Generate Modern Stylish Wordcloud with stylecloud | by AbdulMajedRaja RS | Towards Data Science
|
Almost every Text Analytics Project with a need to find insights from Text Corpus would contain a word cloud. But as many of you remember, Wordclouds have got a very boring image and perception in the minds of a data scientist that we always try to beautify them — ultimately giving up in the process — except a few would choose some masking image and then try to get the wordcloud in that shape. That’s the maximum level where most of us would take our wordclouds.
But deep down, all of us have always wished for modern-stylish-beautiful wordclouds. That wish has become true with this new python package — stylecloud by Max Woolf (who’s famously known as minimaxir)
stylecloud is a Python package that leverages the popular word_cloud package, adding useful features to create truly unique word clouds that are stylistic including gradients and icon shapes.
stylecloud is just one pip away
pip3 install stylecloud
stylecloud offers two ways to generate a style-wordcloud:
stylecloud as a CLI command that could be invoked from your Terminal/Shell/Cmd Prompt to generate wordcloud (fast and stylish)
Typical pythonic way of importing the stylecloud package and creating the wordcloud using stylecloud() in the code
For this article, We’ll consider the iconic inaugural address of former US President Barack Obama in 2008 when he was elected as the POTUS.
Download the file — 2009–01–20-inaugural-address.txt— from here
Simply, open your Terminal or Command Prompt and try this below command stylecloud pointing to the file that we downloaded above
stylecloud --file_path 2009-01-20-inaugural-address.txt
This simple command from stylecloud results in this beautiful plot (automatically saved in the same current directory as stylecloud.png)
That’s simple, fast and beautiful isn’t it? ⚑
stylecloud in CLI is for normal humans, but we are coders who like to code in Python . So let’s build the same in Python with the following 2 lines of code.
import stylecloudstylecloud.gen_stylecloud(file_path = "2009-01-20-inaugural-address.txt")
Now, let’s say we don’t want it in the shape of a flag but in the form of twitter logo. After all, this is the age of internet, isn’t it? A little change in the code — just a new argument to give the specific fontawesome icon name would get us the twitter-shaped stylecloud of Mr. Obama’s speech.
stylecloud.gen_stylecloud(file_path = "2009-01-20-inaugural-address.txt", icon_name= "fab fa-twitter")
Now, Let’s change the color palette a bit and also a dark theme (which everyone’s fond of these days)
stylecloud.gen_stylecloud(file_path = "2009-01-20-inaugural-address.txt", icon_name= "fab fa-twitter", palette="cartocolors.diverging.TealRose_7", background_color="black")
That’s real Dark! And if you’re a fan of Linkedin (instead of Twitter), not to leave you behind — here’s your Linkedin Icon-shaped style-wordcloud
Thanks to Max Woolf , We’re gifted with this amazing library stylecloud. We just quickly learnt how to play with this modern-stylish wordcloud generator both as a CLI tool and in Python script. The PNG files and notebook can be found here.
|
[
{
"code": null,
"e": 637,
"s": 171,
"text": "Almost every Text Analytics Project with a need to find insights from Text Corpus would contain a word cloud. But as many of you remember, Wordclouds have got a very boring image and perception in the minds of a data scientist that we always try to beautify them — ultimately giving up in the process — except a few would choose some masking image and then try to get the wordcloud in that shape. That’s the maximum level where most of us would take our wordclouds."
},
{
"code": null,
"e": 839,
"s": 637,
"text": "But deep down, all of us have always wished for modern-stylish-beautiful wordclouds. That wish has become true with this new python package — stylecloud by Max Woolf (who’s famously known as minimaxir)"
},
{
"code": null,
"e": 1031,
"s": 839,
"text": "stylecloud is a Python package that leverages the popular word_cloud package, adding useful features to create truly unique word clouds that are stylistic including gradients and icon shapes."
},
{
"code": null,
"e": 1063,
"s": 1031,
"text": "stylecloud is just one pip away"
},
{
"code": null,
"e": 1087,
"s": 1063,
"text": "pip3 install stylecloud"
},
{
"code": null,
"e": 1145,
"s": 1087,
"text": "stylecloud offers two ways to generate a style-wordcloud:"
},
{
"code": null,
"e": 1272,
"s": 1145,
"text": "stylecloud as a CLI command that could be invoked from your Terminal/Shell/Cmd Prompt to generate wordcloud (fast and stylish)"
},
{
"code": null,
"e": 1387,
"s": 1272,
"text": "Typical pythonic way of importing the stylecloud package and creating the wordcloud using stylecloud() in the code"
},
{
"code": null,
"e": 1527,
"s": 1387,
"text": "For this article, We’ll consider the iconic inaugural address of former US President Barack Obama in 2008 when he was elected as the POTUS."
},
{
"code": null,
"e": 1591,
"s": 1527,
"text": "Download the file — 2009–01–20-inaugural-address.txt— from here"
},
{
"code": null,
"e": 1720,
"s": 1591,
"text": "Simply, open your Terminal or Command Prompt and try this below command stylecloud pointing to the file that we downloaded above"
},
{
"code": null,
"e": 1776,
"s": 1720,
"text": "stylecloud --file_path 2009-01-20-inaugural-address.txt"
},
{
"code": null,
"e": 1913,
"s": 1776,
"text": "This simple command from stylecloud results in this beautiful plot (automatically saved in the same current directory as stylecloud.png)"
},
{
"code": null,
"e": 1959,
"s": 1913,
"text": "That’s simple, fast and beautiful isn’t it? ⚑"
},
{
"code": null,
"e": 2116,
"s": 1959,
"text": "stylecloud in CLI is for normal humans, but we are coders who like to code in Python . So let’s build the same in Python with the following 2 lines of code."
},
{
"code": null,
"e": 2207,
"s": 2116,
"text": "import stylecloudstylecloud.gen_stylecloud(file_path = \"2009-01-20-inaugural-address.txt\")"
},
{
"code": null,
"e": 2504,
"s": 2207,
"text": "Now, let’s say we don’t want it in the shape of a flag but in the form of twitter logo. After all, this is the age of internet, isn’t it? A little change in the code — just a new argument to give the specific fontawesome icon name would get us the twitter-shaped stylecloud of Mr. Obama’s speech."
},
{
"code": null,
"e": 2607,
"s": 2504,
"text": "stylecloud.gen_stylecloud(file_path = \"2009-01-20-inaugural-address.txt\", icon_name= \"fab fa-twitter\")"
},
{
"code": null,
"e": 2709,
"s": 2607,
"text": "Now, Let’s change the color palette a bit and also a dark theme (which everyone’s fond of these days)"
},
{
"code": null,
"e": 2882,
"s": 2709,
"text": "stylecloud.gen_stylecloud(file_path = \"2009-01-20-inaugural-address.txt\", icon_name= \"fab fa-twitter\", palette=\"cartocolors.diverging.TealRose_7\", background_color=\"black\")"
},
{
"code": null,
"e": 3029,
"s": 2882,
"text": "That’s real Dark! And if you’re a fan of Linkedin (instead of Twitter), not to leave you behind — here’s your Linkedin Icon-shaped style-wordcloud"
}
] |
Count of numbers in the range [L, R] which satisfy the given conditions - GeeksforGeeks
|
19 Jan, 2022
Given a range [L, R], the task is to find the count of numbers from this range that satisfy the below conditions:
All the digit in the number are distinct.All the digits are less than or equal to 5.
All the digit in the number are distinct.
All the digits are less than or equal to 5.
Examples:
Input: L = 4, R = 13 Output: 5 4, 5, 10, 12 and 13 are the only valid numbers in the range [4, 13].Input: L = 100, R = 1000 Output: 100
Approach: The question seems simple if the range is small because in that case, all the numbers from the range can be iterated and checked whether they are valid or not. But since the range could be large, it can be observed all the digits of a valid number has to be distinct and from the range [0, 5] which suggests that the maximum number cannot exceed 543210.Now instead of checking for every number, the next valid number in the series can be generated from the previously generated numbers. The idea is similar to the approach discussed here.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Maximum possible valid number#define MAX 543210 // To store all the required number// from the range [1, MAX]vector<string> ans; // Function that returns true if x// satisfies the given conditionsbool isValidNum(string x){ // To store the digits of x map<int, int> mp; for (int i = 0; i < x.length(); i++) { // If current digit appears more than once if (mp.find(x[i] - '0') != mp.end()) { return false; } // If current digit is greater than 5 else if (x[i] - '0' > 5) { return false; } // Put the digit in the map else { mp[x[i] - '0'] = 1; } } return true;} // Function to generate all the required// numbers in the range [1, MAX]void generate(){ // Insert first 5 valid numbers queue<string> q; q.push("1"); q.push("2"); q.push("3"); q.push("4"); q.push("5"); bool flag = true; // Inserting 0 externally because 0 cannot // be the leading digit in any number ans.push_back("0"); while (!q.empty()) { string x = q.front(); q.pop(); // If x satisfies the given conditions if (isValidNum(x)) { ans.push_back(x); } // Cannot append anymore digit as // adding a digit will repeat one of // the already present digits if (x.length() == 6) continue; // Append all the valid digits one by // one and push the new generated // number to the queue for (int i = 0; i <= 5; i++) { string z = to_string(i); // Append the digit string temp = x + z; // Push the newly generated // number to the queue q.push(temp); } }} // Function to compare two strings// which represent a numerical valuebool comp(string a, string b){ if (a.size() == b.size()) return a < b; else return a.size() < b.size();} // Function to return the count of// valid numbers in the range [l, r]int findcount(string l, string r){ // Generate all the valid numbers // in the range [1, MAX] generate(); // To store the count of numbers // in the range [l, r] int count = 0; // For every valid number in // the range [1, MAX] for (int i = 0; i < ans.size(); i++) { string a = ans[i]; // If current number is within // the required range if (comp(l, a) && comp(a, r)) { count++; } // If number is equal to either l or r else if (a == l || a == r) { count++; } } return count;} // Driver codeint main(){ string l = "1", r = "1000"; cout << findcount(l, r); return 0;}
// Java implementation of the approachimport java.util.*; class GFG{ // Maximum possible valid numberstatic int MAX = 543210; // To store all the required number// from the range [1, MAX]static Vector<String> ans = new Vector<String>(); // Function that returns true if x// satisfies the given conditionsstatic boolean isValidNum(String x){ // To store the digits of x HashMap<Integer, Integer> mp = new HashMap<Integer, Integer>(); for (int i = 0; i < x.length(); i++) { // If current digit appears more than once if (mp.containsKey(x.charAt(i) - '0')) { return false; } // If current digit is greater than 5 else if (x.charAt(i) - '0' > 5) { return false; } // Put the digit in the map else { mp.put(x.charAt(i) - '0', 1); } } return true;} // Function to generate all the required// numbers in the range [1, MAX]static void generate(){ // Insert first 5 valid numbers Queue<String> q = new LinkedList<String>(); q.add("1"); q.add("2"); q.add("3"); q.add("4"); q.add("5"); boolean flag = true; // Inserting 0 externally because 0 cannot // be the leading digit in any number ans.add("0"); while (!q.isEmpty()) { String x = q.peek(); q.remove(); // If x satisfies the given conditions if (isValidNum(x)) { ans.add(x); } // Cannot append anymore digit as // adding a digit will repeat one of // the already present digits if (x.length() == 6) continue; // Append all the valid digits one by // one and push the new generated // number to the queue for (int i = 0; i <= 5; i++) { String z = String.valueOf(i); // Append the digit String temp = x + z; // Push the newly generated // number to the queue q.add(temp); } }} // Function to cpmpare two Strings// which represent a numerical valuestatic boolean comp(String a, String b){ if (a.length()== b.length()) { int i = a.compareTo(b); return i < 0 ? true : false; } else return a.length() < b.length();} // Function to return the count of// valid numbers in the range [l, r]static int findcount(String l, String r){ // Generate all the valid numbers // in the range [1, MAX] generate(); // To store the count of numbers // in the range [l, r] int count = 0; // For every valid number in // the range [1, MAX] for (int i = 0; i < ans.size(); i++) { String a = ans.get(i); // If current number is within // the required range if (comp(l, a) && comp(a, r)) { count++; } // If number is equal to either l or r else if (a == l || a == r) { count++; } } return count;} // Driver codepublic static void main (String[] args){ String l = "1", r = "1000"; System.out.println(findcount(l, r));}} // This code is contributed by PrinciRaj1992
# Python3 implementation of the approachfrom collections import deque # Maximum possible valid numberMAX = 543210 # To store all the required number# from the range [1, MAX]ans = [] # Function that returns true if x# satisfies the given conditionsdef isValidNum(x): # To store the digits of x mp = dict() for i in range(len(x)): # If current digit appears more than once if (ord(x[i]) - ord('0') in mp.keys()): return False # If current digit is greater than 5 elif (ord(x[i]) - ord('0') > 5): return False # Put the digit in the map else: mp[ord(x[i]) - ord('0')] = 1 return True # Function to generate all the required# numbers in the range [1, MAX]def generate(): # Insert first 5 valid numbers q = deque() q.append("1") q.append("2") q.append("3") q.append("4") q.append("5") flag = True # Inserting 0 externally because 0 cannot # be the leading digit in any number ans.append("0") while (len(q) > 0): x = q.popleft() # If x satisfies the given conditions if (isValidNum(x)): ans.append(x) # Cannot append anymore digit as # adding a digit will repeat one of # the already present digits if (len(x) == 6): continue # Append all the valid digits one by # one and append the new generated # number to the queue for i in range(6): z = str(i) # Append the digit temp = x + z # Push the newly generated # number to the queue q.append(temp) # Function to compare two strings# which represent a numerical valuedef comp(a, b): if (len(a) == len(b)): if a < b: return True else: return len(a) < len(b) # Function to return the count of# valid numbers in the range [l, r]def findcount(l, r): # Generate all the valid numbers # in the range [1, MAX] generate() # To store the count of numbers # in the range [l, r] count = 0 # For every valid number in # the range [1, MAX] for i in range(len(ans)): a = ans[i] # If current number is within # the required range if (comp(l, a) and comp(a, r)): count += 1 # If number is equal to either l or r elif (a == l or a == r): count += 1 return count # Driver codel = "1"r = "1000" print(findcount(l, r)) # This code is contributed by Mohit Kumar
// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Maximum possible valid numberstatic int MAX = 543210; // To store all the required number// from the range [1, MAX]static List<String> ans = new List<String>(); // Function that returns true if x// satisfies the given conditionsstatic bool isValidNum(String x){ // To store the digits of x Dictionary<int, int> mp = new Dictionary<int, int>(); for (int i = 0; i < x.Length; i++) { // If current digit appears more than once if (mp.ContainsKey(x[i] - '0')) { return false; } // If current digit is greater than 5 else if (x[i] - '0' > 5) { return false; } // Put the digit in the map else { mp.Add(x[i] - '0', 1); } } return true;} // Function to generate all the required// numbers in the range [1, MAX]static void generate(){ // Insert first 5 valid numbers Queue<String> q = new Queue<String>(); q.Enqueue("1"); q.Enqueue("2"); q.Enqueue("3"); q.Enqueue("4"); q.Enqueue("5"); bool flag = true; // Inserting 0 externally because 0 cannot // be the leading digit in any number ans.Add("0"); while (q.Count!=0) { String x = q.Peek(); q.Dequeue(); // If x satisfies the given conditions if (isValidNum(x)) { ans.Add(x); } // Cannot append anymore digit as // adding a digit will repeat one of // the already present digits if (x.Length == 6) continue; // Append all the valid digits one by // one and push the new generated // number to the queue for (int i = 0; i <= 5; i++) { String z = i.ToString(); // Append the digit String temp = x + z; // Push the newly generated // number to the queue q.Enqueue(temp); } }} // Function to compare two Strings// which represent a numerical valuestatic bool comp(String a, String b){ if (a.Length == b.Length) { int i = a.CompareTo(b); return i < 0 ? true : false; } else return a.Length < b.Length;} // Function to return the count of// valid numbers in the range [l, r]static int findcount(String l, String r){ // Generate all the valid numbers // in the range [1, MAX] generate(); // To store the count of numbers // in the range [l, r] int count = 0; // For every valid number in // the range [1, MAX] for (int i = 0; i < ans.Count; i++) { String a = ans[i]; // If current number is within // the required range if (comp(l, a) && comp(a, r)) { count++; } // If number is equal to either l or r else if (a == l || a == r) { count++; } } return count;} // Driver codepublic static void Main (String[] args){ String l = "1", r = "1000"; Console.WriteLine(findcount(l, r));}} // This code is contributed by Princi Singh
<script> // JavaScript implementation of the approach // Maximum possible valid numberlet MAX = 543210; // To store all the required number// from the range [1, MAX]let ans = []; // Function that returns true if x// satisfies the given conditionsfunction isValidNum(x){ // To store the digits of x let mp = new Map(); for (let i = 0; i < x.length; i++) { // If current digit appears more than once if (mp.has(x[i].charCodeAt(0) - '0'.charCodeAt(0))) { return false; } // If current digit is greater than 5 else if (x[i].charCodeAt(0) - '0'.charCodeAt(0) > 5) { return false; } // Put the digit in the map else { mp.set(x[i].charCodeAt(0) - '0'.charCodeAt(0), 1); } } return true;} // Function to generate all the required// numbers in the range [1, MAX]function generate(){ // Insert first 5 valid numbers let q = []; q.push("1"); q.push("2"); q.push("3"); q.push("4"); q.push("5"); let flag = true; // Inserting 0 externally because 0 cannot // be the leading digit in any number ans.push("0"); while (q.length!=0) { let x = q.shift(); // If x satisfies the given conditions if (isValidNum(x)) { ans.push(x); } // Cannot append anymore digit as // adding a digit will repeat one of // the already present digits if (x.length == 6) continue; // Append all the valid digits one by // one and push the new generated // number to the queue for (let i = 0; i <= 5; i++) { let z = (i).toString(); // Append the digit let temp = x + z; // Push the newly generated // number to the queue q.push(temp); } }} // Function to compare two Strings// which represent a numerical valuefunction comp(a,b){ if (a.length== b.length) { return a < b ? true : false; } else return a.length < b.length;} // Function to return the count of// valid numbers in the range [l, r]function findcount(l,r){ // Generate all the valid numbers // in the range [1, MAX] generate(); // To store the count of numbers // in the range [l, r] let count = 0; // For every valid number in // the range [1, MAX] for (let i = 0; i < ans.length; i++) { let a = ans[i]; // If current number is within // the required range if (comp(l, a) && comp(a, r)) { count++; } // If number is equal to either l or r else if (a == l || a == r) { count++; } } return count;} // Driver codelet l = "1", r = "1000"; document.write(findcount(l, r)); // This code is contributed by unknown2108 </script>
130
mohit kumar 29
princiraj1992
princi singh
unknown2108
varshagumber28
BFS
Greedy
Queue
Greedy
Queue
BFS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Huffman Coding | Greedy Algo-3
Activity Selection Problem | Greedy Algo-1
Fractional Knapsack Problem
Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)
Job Sequencing Problem
Breadth First Search or BFS for a Graph
Level Order Binary Tree Traversal
Queue Interface In Java
Queue in Python
Queue | Set 1 (Introduction and Array Implementation)
|
[
{
"code": null,
"e": 25791,
"s": 25763,
"text": "\n19 Jan, 2022"
},
{
"code": null,
"e": 25907,
"s": 25791,
"text": "Given a range [L, R], the task is to find the count of numbers from this range that satisfy the below conditions: "
},
{
"code": null,
"e": 25992,
"s": 25907,
"text": "All the digit in the number are distinct.All the digits are less than or equal to 5."
},
{
"code": null,
"e": 26034,
"s": 25992,
"text": "All the digit in the number are distinct."
},
{
"code": null,
"e": 26078,
"s": 26034,
"text": "All the digits are less than or equal to 5."
},
{
"code": null,
"e": 26090,
"s": 26078,
"text": "Examples: "
},
{
"code": null,
"e": 26228,
"s": 26090,
"text": "Input: L = 4, R = 13 Output: 5 4, 5, 10, 12 and 13 are the only valid numbers in the range [4, 13].Input: L = 100, R = 1000 Output: 100 "
},
{
"code": null,
"e": 26831,
"s": 26230,
"text": "Approach: The question seems simple if the range is small because in that case, all the numbers from the range can be iterated and checked whether they are valid or not. But since the range could be large, it can be observed all the digits of a valid number has to be distinct and from the range [0, 5] which suggests that the maximum number cannot exceed 543210.Now instead of checking for every number, the next valid number in the series can be generated from the previously generated numbers. The idea is similar to the approach discussed here.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26835,
"s": 26831,
"text": "C++"
},
{
"code": null,
"e": 26840,
"s": 26835,
"text": "Java"
},
{
"code": null,
"e": 26848,
"s": 26840,
"text": "Python3"
},
{
"code": null,
"e": 26851,
"s": 26848,
"text": "C#"
},
{
"code": null,
"e": 26862,
"s": 26851,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Maximum possible valid number#define MAX 543210 // To store all the required number// from the range [1, MAX]vector<string> ans; // Function that returns true if x// satisfies the given conditionsbool isValidNum(string x){ // To store the digits of x map<int, int> mp; for (int i = 0; i < x.length(); i++) { // If current digit appears more than once if (mp.find(x[i] - '0') != mp.end()) { return false; } // If current digit is greater than 5 else if (x[i] - '0' > 5) { return false; } // Put the digit in the map else { mp[x[i] - '0'] = 1; } } return true;} // Function to generate all the required// numbers in the range [1, MAX]void generate(){ // Insert first 5 valid numbers queue<string> q; q.push(\"1\"); q.push(\"2\"); q.push(\"3\"); q.push(\"4\"); q.push(\"5\"); bool flag = true; // Inserting 0 externally because 0 cannot // be the leading digit in any number ans.push_back(\"0\"); while (!q.empty()) { string x = q.front(); q.pop(); // If x satisfies the given conditions if (isValidNum(x)) { ans.push_back(x); } // Cannot append anymore digit as // adding a digit will repeat one of // the already present digits if (x.length() == 6) continue; // Append all the valid digits one by // one and push the new generated // number to the queue for (int i = 0; i <= 5; i++) { string z = to_string(i); // Append the digit string temp = x + z; // Push the newly generated // number to the queue q.push(temp); } }} // Function to compare two strings// which represent a numerical valuebool comp(string a, string b){ if (a.size() == b.size()) return a < b; else return a.size() < b.size();} // Function to return the count of// valid numbers in the range [l, r]int findcount(string l, string r){ // Generate all the valid numbers // in the range [1, MAX] generate(); // To store the count of numbers // in the range [l, r] int count = 0; // For every valid number in // the range [1, MAX] for (int i = 0; i < ans.size(); i++) { string a = ans[i]; // If current number is within // the required range if (comp(l, a) && comp(a, r)) { count++; } // If number is equal to either l or r else if (a == l || a == r) { count++; } } return count;} // Driver codeint main(){ string l = \"1\", r = \"1000\"; cout << findcount(l, r); return 0;}",
"e": 29668,
"s": 26862,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*; class GFG{ // Maximum possible valid numberstatic int MAX = 543210; // To store all the required number// from the range [1, MAX]static Vector<String> ans = new Vector<String>(); // Function that returns true if x// satisfies the given conditionsstatic boolean isValidNum(String x){ // To store the digits of x HashMap<Integer, Integer> mp = new HashMap<Integer, Integer>(); for (int i = 0; i < x.length(); i++) { // If current digit appears more than once if (mp.containsKey(x.charAt(i) - '0')) { return false; } // If current digit is greater than 5 else if (x.charAt(i) - '0' > 5) { return false; } // Put the digit in the map else { mp.put(x.charAt(i) - '0', 1); } } return true;} // Function to generate all the required// numbers in the range [1, MAX]static void generate(){ // Insert first 5 valid numbers Queue<String> q = new LinkedList<String>(); q.add(\"1\"); q.add(\"2\"); q.add(\"3\"); q.add(\"4\"); q.add(\"5\"); boolean flag = true; // Inserting 0 externally because 0 cannot // be the leading digit in any number ans.add(\"0\"); while (!q.isEmpty()) { String x = q.peek(); q.remove(); // If x satisfies the given conditions if (isValidNum(x)) { ans.add(x); } // Cannot append anymore digit as // adding a digit will repeat one of // the already present digits if (x.length() == 6) continue; // Append all the valid digits one by // one and push the new generated // number to the queue for (int i = 0; i <= 5; i++) { String z = String.valueOf(i); // Append the digit String temp = x + z; // Push the newly generated // number to the queue q.add(temp); } }} // Function to cpmpare two Strings// which represent a numerical valuestatic boolean comp(String a, String b){ if (a.length()== b.length()) { int i = a.compareTo(b); return i < 0 ? true : false; } else return a.length() < b.length();} // Function to return the count of// valid numbers in the range [l, r]static int findcount(String l, String r){ // Generate all the valid numbers // in the range [1, MAX] generate(); // To store the count of numbers // in the range [l, r] int count = 0; // For every valid number in // the range [1, MAX] for (int i = 0; i < ans.size(); i++) { String a = ans.get(i); // If current number is within // the required range if (comp(l, a) && comp(a, r)) { count++; } // If number is equal to either l or r else if (a == l || a == r) { count++; } } return count;} // Driver codepublic static void main (String[] args){ String l = \"1\", r = \"1000\"; System.out.println(findcount(l, r));}} // This code is contributed by PrinciRaj1992",
"e": 32866,
"s": 29668,
"text": null
},
{
"code": "# Python3 implementation of the approachfrom collections import deque # Maximum possible valid numberMAX = 543210 # To store all the required number# from the range [1, MAX]ans = [] # Function that returns true if x# satisfies the given conditionsdef isValidNum(x): # To store the digits of x mp = dict() for i in range(len(x)): # If current digit appears more than once if (ord(x[i]) - ord('0') in mp.keys()): return False # If current digit is greater than 5 elif (ord(x[i]) - ord('0') > 5): return False # Put the digit in the map else: mp[ord(x[i]) - ord('0')] = 1 return True # Function to generate all the required# numbers in the range [1, MAX]def generate(): # Insert first 5 valid numbers q = deque() q.append(\"1\") q.append(\"2\") q.append(\"3\") q.append(\"4\") q.append(\"5\") flag = True # Inserting 0 externally because 0 cannot # be the leading digit in any number ans.append(\"0\") while (len(q) > 0): x = q.popleft() # If x satisfies the given conditions if (isValidNum(x)): ans.append(x) # Cannot append anymore digit as # adding a digit will repeat one of # the already present digits if (len(x) == 6): continue # Append all the valid digits one by # one and append the new generated # number to the queue for i in range(6): z = str(i) # Append the digit temp = x + z # Push the newly generated # number to the queue q.append(temp) # Function to compare two strings# which represent a numerical valuedef comp(a, b): if (len(a) == len(b)): if a < b: return True else: return len(a) < len(b) # Function to return the count of# valid numbers in the range [l, r]def findcount(l, r): # Generate all the valid numbers # in the range [1, MAX] generate() # To store the count of numbers # in the range [l, r] count = 0 # For every valid number in # the range [1, MAX] for i in range(len(ans)): a = ans[i] # If current number is within # the required range if (comp(l, a) and comp(a, r)): count += 1 # If number is equal to either l or r elif (a == l or a == r): count += 1 return count # Driver codel = \"1\"r = \"1000\" print(findcount(l, r)) # This code is contributed by Mohit Kumar",
"e": 35383,
"s": 32866,
"text": null
},
{
"code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Maximum possible valid numberstatic int MAX = 543210; // To store all the required number// from the range [1, MAX]static List<String> ans = new List<String>(); // Function that returns true if x// satisfies the given conditionsstatic bool isValidNum(String x){ // To store the digits of x Dictionary<int, int> mp = new Dictionary<int, int>(); for (int i = 0; i < x.Length; i++) { // If current digit appears more than once if (mp.ContainsKey(x[i] - '0')) { return false; } // If current digit is greater than 5 else if (x[i] - '0' > 5) { return false; } // Put the digit in the map else { mp.Add(x[i] - '0', 1); } } return true;} // Function to generate all the required// numbers in the range [1, MAX]static void generate(){ // Insert first 5 valid numbers Queue<String> q = new Queue<String>(); q.Enqueue(\"1\"); q.Enqueue(\"2\"); q.Enqueue(\"3\"); q.Enqueue(\"4\"); q.Enqueue(\"5\"); bool flag = true; // Inserting 0 externally because 0 cannot // be the leading digit in any number ans.Add(\"0\"); while (q.Count!=0) { String x = q.Peek(); q.Dequeue(); // If x satisfies the given conditions if (isValidNum(x)) { ans.Add(x); } // Cannot append anymore digit as // adding a digit will repeat one of // the already present digits if (x.Length == 6) continue; // Append all the valid digits one by // one and push the new generated // number to the queue for (int i = 0; i <= 5; i++) { String z = i.ToString(); // Append the digit String temp = x + z; // Push the newly generated // number to the queue q.Enqueue(temp); } }} // Function to compare two Strings// which represent a numerical valuestatic bool comp(String a, String b){ if (a.Length == b.Length) { int i = a.CompareTo(b); return i < 0 ? true : false; } else return a.Length < b.Length;} // Function to return the count of// valid numbers in the range [l, r]static int findcount(String l, String r){ // Generate all the valid numbers // in the range [1, MAX] generate(); // To store the count of numbers // in the range [l, r] int count = 0; // For every valid number in // the range [1, MAX] for (int i = 0; i < ans.Count; i++) { String a = ans[i]; // If current number is within // the required range if (comp(l, a) && comp(a, r)) { count++; } // If number is equal to either l or r else if (a == l || a == r) { count++; } } return count;} // Driver codepublic static void Main (String[] args){ String l = \"1\", r = \"1000\"; Console.WriteLine(findcount(l, r));}} // This code is contributed by Princi Singh",
"e": 38517,
"s": 35383,
"text": null
},
{
"code": "<script> // JavaScript implementation of the approach // Maximum possible valid numberlet MAX = 543210; // To store all the required number// from the range [1, MAX]let ans = []; // Function that returns true if x// satisfies the given conditionsfunction isValidNum(x){ // To store the digits of x let mp = new Map(); for (let i = 0; i < x.length; i++) { // If current digit appears more than once if (mp.has(x[i].charCodeAt(0) - '0'.charCodeAt(0))) { return false; } // If current digit is greater than 5 else if (x[i].charCodeAt(0) - '0'.charCodeAt(0) > 5) { return false; } // Put the digit in the map else { mp.set(x[i].charCodeAt(0) - '0'.charCodeAt(0), 1); } } return true;} // Function to generate all the required// numbers in the range [1, MAX]function generate(){ // Insert first 5 valid numbers let q = []; q.push(\"1\"); q.push(\"2\"); q.push(\"3\"); q.push(\"4\"); q.push(\"5\"); let flag = true; // Inserting 0 externally because 0 cannot // be the leading digit in any number ans.push(\"0\"); while (q.length!=0) { let x = q.shift(); // If x satisfies the given conditions if (isValidNum(x)) { ans.push(x); } // Cannot append anymore digit as // adding a digit will repeat one of // the already present digits if (x.length == 6) continue; // Append all the valid digits one by // one and push the new generated // number to the queue for (let i = 0; i <= 5; i++) { let z = (i).toString(); // Append the digit let temp = x + z; // Push the newly generated // number to the queue q.push(temp); } }} // Function to compare two Strings// which represent a numerical valuefunction comp(a,b){ if (a.length== b.length) { return a < b ? true : false; } else return a.length < b.length;} // Function to return the count of// valid numbers in the range [l, r]function findcount(l,r){ // Generate all the valid numbers // in the range [1, MAX] generate(); // To store the count of numbers // in the range [l, r] let count = 0; // For every valid number in // the range [1, MAX] for (let i = 0; i < ans.length; i++) { let a = ans[i]; // If current number is within // the required range if (comp(l, a) && comp(a, r)) { count++; } // If number is equal to either l or r else if (a == l || a == r) { count++; } } return count;} // Driver codelet l = \"1\", r = \"1000\"; document.write(findcount(l, r)); // This code is contributed by unknown2108 </script>",
"e": 41462,
"s": 38517,
"text": null
},
{
"code": null,
"e": 41466,
"s": 41462,
"text": "130"
},
{
"code": null,
"e": 41483,
"s": 41468,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 41497,
"s": 41483,
"text": "princiraj1992"
},
{
"code": null,
"e": 41510,
"s": 41497,
"text": "princi singh"
},
{
"code": null,
"e": 41522,
"s": 41510,
"text": "unknown2108"
},
{
"code": null,
"e": 41537,
"s": 41522,
"text": "varshagumber28"
},
{
"code": null,
"e": 41541,
"s": 41537,
"text": "BFS"
},
{
"code": null,
"e": 41548,
"s": 41541,
"text": "Greedy"
},
{
"code": null,
"e": 41554,
"s": 41548,
"text": "Queue"
},
{
"code": null,
"e": 41561,
"s": 41554,
"text": "Greedy"
},
{
"code": null,
"e": 41567,
"s": 41561,
"text": "Queue"
},
{
"code": null,
"e": 41571,
"s": 41567,
"text": "BFS"
},
{
"code": null,
"e": 41669,
"s": 41571,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 41700,
"s": 41669,
"text": "Huffman Coding | Greedy Algo-3"
},
{
"code": null,
"e": 41743,
"s": 41700,
"text": "Activity Selection Problem | Greedy Algo-1"
},
{
"code": null,
"e": 41771,
"s": 41743,
"text": "Fractional Knapsack Problem"
},
{
"code": null,
"e": 41852,
"s": 41771,
"text": "Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)"
},
{
"code": null,
"e": 41875,
"s": 41852,
"text": "Job Sequencing Problem"
},
{
"code": null,
"e": 41915,
"s": 41875,
"text": "Breadth First Search or BFS for a Graph"
},
{
"code": null,
"e": 41949,
"s": 41915,
"text": "Level Order Binary Tree Traversal"
},
{
"code": null,
"e": 41973,
"s": 41949,
"text": "Queue Interface In Java"
},
{
"code": null,
"e": 41989,
"s": 41973,
"text": "Queue in Python"
}
] |
Tryit Editor v3.7
|
Tryit: Video autoplay
|
[] |
How to Add Fingerprint Authentication in Your Android App without Using any Library? - GeeksforGeeks
|
27 May, 2021
Biometric Fingerprint authentication is one method of protecting sensitive information or premium content of your app. Nowadays, all payment apps use this feature in their app. It is very easy to implement. A sample Video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using both Java and Kotlin language
Step 1: Create a new project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin/Java as the programming language
Step 2: Add Biometric permission in the manifest
Go to the AndroidMenifest.xml file and add the following permission there.
<uses-permission android:name=”android.permission.USE_BIOMETRIC”/>
Step 3: Working with the activity_main.xml file
Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file. It has only a Button on click of which will create the fingerprint Scanner dialog box.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:id="@+id/start_authentication" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Authenticate" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
Step 4: Working with the MainActivity file
Go to the MainActivity file and refer to the following code. Below is the code for the MainActivity file. Comments are added inside the code to understand the code in more detail.
Kotlin
Java
import android.app.KeyguardManagerimport android.content.Contextimport android.content.DialogInterfaceimport android.content.pm.PackageManagerimport android.hardware.biometrics.BiometricPromptimport android.os.Buildimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.os.CancellationSignalimport android.widget.Buttonimport android.widget.Toastimport androidx.annotation.RequiresApiimport androidx.core.app.ActivityCompat class MainActivity : AppCompatActivity() { // create a CancellationSignal variable and assign a value null to it private var cancellationSignal: CancellationSignal? = null // create an authenticationCallback private val authenticationCallback: BiometricPrompt.AuthenticationCallback get() = @RequiresApi(Build.VERSION_CODES.P) object : BiometricPrompt.AuthenticationCallback() { // here we need to implement two methods // onAuthenticationError and onAuthenticationSucceeded // If the fingerprint is not recognized by the app it will call // onAuthenticationError and show a toast override fun onAuthenticationError(errorCode: Int, errString: CharSequence?) { super.onAuthenticationError(errorCode, errString) notifyUser("Authentication Error : $errString") } // If the fingerprint is recognized by the app then it will call // onAuthenticationSucceeded and show a toast that Authentication has Succeed // Here you can also start a new activity after that override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult?) { super.onAuthenticationSucceeded(result) notifyUser("Authentication Succeeded") // or start a new Activity } } @RequiresApi(Build.VERSION_CODES.P) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) checkBiometricSupport() // create a biometric dialog on Click of button findViewById<Button>(R.id.start_authentication).setOnClickListener { // This creates a dialog of biometric auth and // it requires title , subtitle , // and description // In our case there is a cancel button by // clicking it, it will cancel the process of // fingerprint authentication val biometricPrompt = BiometricPrompt.Builder(this) .setTitle("Title of Prompt") .setSubtitle("Subtitle") .setDescription("Uses FP") .setNegativeButton("Cancel", this.mainExecutor, DialogInterface.OnClickListener { dialog, which -> notifyUser("Authentication Cancelled") }).build() // start the authenticationCallback in mainExecutor biometricPrompt.authenticate(getCancellationSignal(), mainExecutor, authenticationCallback) } } // it will be called when authentication is cancelled by the user private fun getCancellationSignal(): CancellationSignal { cancellationSignal = CancellationSignal() cancellationSignal?.setOnCancelListener { notifyUser("Authentication was Cancelled by the user") } return cancellationSignal as CancellationSignal } // it checks whether the app the app has fingerprint permission @RequiresApi(Build.VERSION_CODES.M) private fun checkBiometricSupport(): Boolean { val keyguardManager = getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager if (!keyguardManager.isDeviceSecure) { notifyUser("Fingerprint authentication has not been enabled in settings") return false } if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.USE_BIOMETRIC) != PackageManager.PERMISSION_GRANTED) { notifyUser("Fingerprint Authentication Permission is not enabled") return false } return if (packageManager.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)) { true } else true } // this is a toast method which is responsible for showing toast // it takes a string as parameter private fun notifyUser(message: String) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show() }}
import android.app.KeyguardManager;import android.content.Context;import android.content.DialogInterface;import android.content.pm.PackageManager;import android.hardware.biometrics.BiometricPrompt;import android.os.Build;import android.os.Bundle;import android.os.CancellationSignal;import android.view.View;import android.widget.Button;import android.widget.Toast;import androidx.annotation.Nullable;import androidx.annotation.RequiresApi;import androidx.appcompat.app.AppCompatActivity;import androidx.core.app.ActivityCompat; public class MainActivity extends AppCompatActivity { // create a CancellationSignal // variable and assign a // value null to it private CancellationSignal cancellationSignal = null; // create an authenticationCallback private BiometricPrompt.AuthenticationCallback authenticationCallback; @RequiresApi(api = Build.VERSION_CODES.P) @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); authenticationCallback = new BiometricPrompt.AuthenticationCallback() { // here we need to implement two methods // onAuthenticationError and // onAuthenticationSucceeded If the // fingerprint is not recognized by the // app it will call onAuthenticationError // and show a toast @Override public void onAuthenticationError( int errorCode, CharSequence errString) { super.onAuthenticationError(errorCode, errString); notifyUser("Authentication Error : " + errString); } // If the fingerprint is recognized by the // app then it will call // onAuthenticationSucceeded and show a // toast that Authentication has Succeed // Here you can also start a new activity // after that @Override public void onAuthenticationSucceeded(BiometricPrompt.AuthenticationResult result) { super.onAuthenticationSucceeded(result); notifyUser("Authentication Succeeded"); // or start a new Activity } }; checkBiometricSupport(); // create a biometric dialog on Click of button (Button) findViewById(R.id.start_authentication).setOnClickListener(new View.OnClickListener() { @RequiresApi(api = Build.VERSION_CODES.P) @Override public void onClick(View view) { // This creates a dialog of biometric // auth and it requires title , subtitle // , and description In our case there // is a cancel button by clicking it, it // will cancel the process of // fingerprint authentication BiometricPrompt biometricPrompt = new BiometricPrompt .Builder(getApplicationContext()) .setTitle("Title of Prompt") .setSubtitle("Subtitle") .setDescription("Uses FP") .setNegativeButton("Cancel", getMainExecutor(), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { notifyUser("Authentication Cancelled"); } }).build(); // start the authenticationCallback in // mainExecutor biometricPrompt.authenticate( getCancellationSignal(), getMainExecutor(), authenticationCallback); } }); } // it will be called when // authentication is cancelled by // the user private CancellationSignal getCancellationSignal() { cancellationSignal = new CancellationSignal(); cancellationSignal.setOnCancelListener( new CancellationSignal.OnCancelListener() { @Override public void onCancel() { notifyUser("Authentication was Cancelled by the user"); } }); return cancellationSignal; } // it checks whether the // app the app has fingerprint // permission @RequiresApi(Build.VERSION_CODES.M) private Boolean checkBiometricSupport() { KeyguardManager keyguardManager = (KeyguardManager)getSystemService(Context.KEYGUARD_SERVICE); if (!keyguardManager.isDeviceSecure()) { notifyUser("Fingerprint authentication has not been enabled in settings"); return false; } if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.USE_BIOMETRIC)!= PackageManager.PERMISSION_GRANTED) { notifyUser("Fingerprint Authentication Permission is not enabled"); return false; } if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)) { return true; } else return true; } // this is a toast method which is responsible for // showing toast it takes a string as parameter private void notifyUser(String message) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); }}
Output:
GitHub repo here.
raghav14
android
Technical Scripter 2020
Android
Kotlin
Technical Scripter
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Resource Raw Folder in Android Studio
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
How to Post Data to API using Retrofit in Android?
Retrofit with Kotlin Coroutine in Android
Android UI Layouts
Kotlin Array
Kotlin Setters and Getters
Retrofit with Kotlin Coroutine in Android
Kotlin when expression
|
[
{
"code": null,
"e": 25260,
"s": 25232,
"text": "\n27 May, 2021"
},
{
"code": null,
"e": 25645,
"s": 25260,
"text": "Biometric Fingerprint authentication is one method of protecting sensitive information or premium content of your app. Nowadays, all payment apps use this feature in their app. It is very easy to implement. A sample Video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using both Java and Kotlin language "
},
{
"code": null,
"e": 25674,
"s": 25645,
"text": "Step 1: Create a new project"
},
{
"code": null,
"e": 25842,
"s": 25674,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin/Java as the programming language"
},
{
"code": null,
"e": 25891,
"s": 25842,
"text": "Step 2: Add Biometric permission in the manifest"
},
{
"code": null,
"e": 25966,
"s": 25891,
"text": "Go to the AndroidMenifest.xml file and add the following permission there."
},
{
"code": null,
"e": 26035,
"s": 25966,
"text": " <uses-permission android:name=”android.permission.USE_BIOMETRIC”/>"
},
{
"code": null,
"e": 26083,
"s": 26035,
"text": "Step 3: Working with the activity_main.xml file"
},
{
"code": null,
"e": 26286,
"s": 26083,
"text": "Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file. It has only a Button on click of which will create the fingerprint Scanner dialog box."
},
{
"code": null,
"e": 26290,
"s": 26286,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <Button android:id=\"@+id/start_authentication\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Authenticate\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> </androidx.constraintlayout.widget.ConstraintLayout>",
"e": 27103,
"s": 26290,
"text": null
},
{
"code": null,
"e": 27147,
"s": 27103,
"text": "Step 4: Working with the MainActivity file "
},
{
"code": null,
"e": 27328,
"s": 27147,
"text": "Go to the MainActivity file and refer to the following code. Below is the code for the MainActivity file. Comments are added inside the code to understand the code in more detail. "
},
{
"code": null,
"e": 27335,
"s": 27328,
"text": "Kotlin"
},
{
"code": null,
"e": 27340,
"s": 27335,
"text": "Java"
},
{
"code": "import android.app.KeyguardManagerimport android.content.Contextimport android.content.DialogInterfaceimport android.content.pm.PackageManagerimport android.hardware.biometrics.BiometricPromptimport android.os.Buildimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.os.CancellationSignalimport android.widget.Buttonimport android.widget.Toastimport androidx.annotation.RequiresApiimport androidx.core.app.ActivityCompat class MainActivity : AppCompatActivity() { // create a CancellationSignal variable and assign a value null to it private var cancellationSignal: CancellationSignal? = null // create an authenticationCallback private val authenticationCallback: BiometricPrompt.AuthenticationCallback get() = @RequiresApi(Build.VERSION_CODES.P) object : BiometricPrompt.AuthenticationCallback() { // here we need to implement two methods // onAuthenticationError and onAuthenticationSucceeded // If the fingerprint is not recognized by the app it will call // onAuthenticationError and show a toast override fun onAuthenticationError(errorCode: Int, errString: CharSequence?) { super.onAuthenticationError(errorCode, errString) notifyUser(\"Authentication Error : $errString\") } // If the fingerprint is recognized by the app then it will call // onAuthenticationSucceeded and show a toast that Authentication has Succeed // Here you can also start a new activity after that override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult?) { super.onAuthenticationSucceeded(result) notifyUser(\"Authentication Succeeded\") // or start a new Activity } } @RequiresApi(Build.VERSION_CODES.P) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) checkBiometricSupport() // create a biometric dialog on Click of button findViewById<Button>(R.id.start_authentication).setOnClickListener { // This creates a dialog of biometric auth and // it requires title , subtitle , // and description // In our case there is a cancel button by // clicking it, it will cancel the process of // fingerprint authentication val biometricPrompt = BiometricPrompt.Builder(this) .setTitle(\"Title of Prompt\") .setSubtitle(\"Subtitle\") .setDescription(\"Uses FP\") .setNegativeButton(\"Cancel\", this.mainExecutor, DialogInterface.OnClickListener { dialog, which -> notifyUser(\"Authentication Cancelled\") }).build() // start the authenticationCallback in mainExecutor biometricPrompt.authenticate(getCancellationSignal(), mainExecutor, authenticationCallback) } } // it will be called when authentication is cancelled by the user private fun getCancellationSignal(): CancellationSignal { cancellationSignal = CancellationSignal() cancellationSignal?.setOnCancelListener { notifyUser(\"Authentication was Cancelled by the user\") } return cancellationSignal as CancellationSignal } // it checks whether the app the app has fingerprint permission @RequiresApi(Build.VERSION_CODES.M) private fun checkBiometricSupport(): Boolean { val keyguardManager = getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager if (!keyguardManager.isDeviceSecure) { notifyUser(\"Fingerprint authentication has not been enabled in settings\") return false } if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.USE_BIOMETRIC) != PackageManager.PERMISSION_GRANTED) { notifyUser(\"Fingerprint Authentication Permission is not enabled\") return false } return if (packageManager.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)) { true } else true } // this is a toast method which is responsible for showing toast // it takes a string as parameter private fun notifyUser(message: String) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show() }}",
"e": 31895,
"s": 27340,
"text": null
},
{
"code": "import android.app.KeyguardManager;import android.content.Context;import android.content.DialogInterface;import android.content.pm.PackageManager;import android.hardware.biometrics.BiometricPrompt;import android.os.Build;import android.os.Bundle;import android.os.CancellationSignal;import android.view.View;import android.widget.Button;import android.widget.Toast;import androidx.annotation.Nullable;import androidx.annotation.RequiresApi;import androidx.appcompat.app.AppCompatActivity;import androidx.core.app.ActivityCompat; public class MainActivity extends AppCompatActivity { // create a CancellationSignal // variable and assign a // value null to it private CancellationSignal cancellationSignal = null; // create an authenticationCallback private BiometricPrompt.AuthenticationCallback authenticationCallback; @RequiresApi(api = Build.VERSION_CODES.P) @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); authenticationCallback = new BiometricPrompt.AuthenticationCallback() { // here we need to implement two methods // onAuthenticationError and // onAuthenticationSucceeded If the // fingerprint is not recognized by the // app it will call onAuthenticationError // and show a toast @Override public void onAuthenticationError( int errorCode, CharSequence errString) { super.onAuthenticationError(errorCode, errString); notifyUser(\"Authentication Error : \" + errString); } // If the fingerprint is recognized by the // app then it will call // onAuthenticationSucceeded and show a // toast that Authentication has Succeed // Here you can also start a new activity // after that @Override public void onAuthenticationSucceeded(BiometricPrompt.AuthenticationResult result) { super.onAuthenticationSucceeded(result); notifyUser(\"Authentication Succeeded\"); // or start a new Activity } }; checkBiometricSupport(); // create a biometric dialog on Click of button (Button) findViewById(R.id.start_authentication).setOnClickListener(new View.OnClickListener() { @RequiresApi(api = Build.VERSION_CODES.P) @Override public void onClick(View view) { // This creates a dialog of biometric // auth and it requires title , subtitle // , and description In our case there // is a cancel button by clicking it, it // will cancel the process of // fingerprint authentication BiometricPrompt biometricPrompt = new BiometricPrompt .Builder(getApplicationContext()) .setTitle(\"Title of Prompt\") .setSubtitle(\"Subtitle\") .setDescription(\"Uses FP\") .setNegativeButton(\"Cancel\", getMainExecutor(), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { notifyUser(\"Authentication Cancelled\"); } }).build(); // start the authenticationCallback in // mainExecutor biometricPrompt.authenticate( getCancellationSignal(), getMainExecutor(), authenticationCallback); } }); } // it will be called when // authentication is cancelled by // the user private CancellationSignal getCancellationSignal() { cancellationSignal = new CancellationSignal(); cancellationSignal.setOnCancelListener( new CancellationSignal.OnCancelListener() { @Override public void onCancel() { notifyUser(\"Authentication was Cancelled by the user\"); } }); return cancellationSignal; } // it checks whether the // app the app has fingerprint // permission @RequiresApi(Build.VERSION_CODES.M) private Boolean checkBiometricSupport() { KeyguardManager keyguardManager = (KeyguardManager)getSystemService(Context.KEYGUARD_SERVICE); if (!keyguardManager.isDeviceSecure()) { notifyUser(\"Fingerprint authentication has not been enabled in settings\"); return false; } if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.USE_BIOMETRIC)!= PackageManager.PERMISSION_GRANTED) { notifyUser(\"Fingerprint Authentication Permission is not enabled\"); return false; } if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)) { return true; } else return true; } // this is a toast method which is responsible for // showing toast it takes a string as parameter private void notifyUser(String message) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); }}",
"e": 37732,
"s": 31895,
"text": null
},
{
"code": null,
"e": 37740,
"s": 37732,
"text": "Output:"
},
{
"code": null,
"e": 37758,
"s": 37740,
"text": "GitHub repo here."
},
{
"code": null,
"e": 37767,
"s": 37758,
"text": "raghav14"
},
{
"code": null,
"e": 37775,
"s": 37767,
"text": "android"
},
{
"code": null,
"e": 37799,
"s": 37775,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 37807,
"s": 37799,
"text": "Android"
},
{
"code": null,
"e": 37814,
"s": 37807,
"text": "Kotlin"
},
{
"code": null,
"e": 37833,
"s": 37814,
"text": "Technical Scripter"
},
{
"code": null,
"e": 37841,
"s": 37833,
"text": "Android"
},
{
"code": null,
"e": 37939,
"s": 37841,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37977,
"s": 37939,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 38016,
"s": 37977,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 38066,
"s": 38016,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 38117,
"s": 38066,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 38159,
"s": 38117,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 38178,
"s": 38159,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 38191,
"s": 38178,
"text": "Kotlin Array"
},
{
"code": null,
"e": 38218,
"s": 38191,
"text": "Kotlin Setters and Getters"
},
{
"code": null,
"e": 38260,
"s": 38218,
"text": "Retrofit with Kotlin Coroutine in Android"
}
] |
How to test and execute a regular expression in JavaScript?
|
Following is the code for testing and executing a regular expression 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,.sample {
font-size: 20px;
font-weight: 500;
}
</style>
</head>
<body>
<h1>Testing and executing regular expressions</h1>
<div class="sample"></div>
<div style="color: green;" class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>
Click on the above button to test and execute the regular expression
</h3>
<script>
let sampleEle=document.querySelector('.sample');
let resEle = document.querySelector('.result');
let str = 'Hello world. This is a beautiful world';
sampleEle.innerHTML =str;
let pattern = new RegExp("world");
document.querySelector(".Btn").addEventListener("click", () => {
resEle.innerHTML += 'pattern.test(str) = ' + pattern.test(str) + '<br>';
resEle.innerHTML += 'pattern.exec(str) = ' + pattern.exec(str) + '<br>';
});
</script>
</body>
</html>
The above code will produce the following output −
On clicking the ‘CLICK HERE’ button −
|
[
{
"code": null,
"e": 1147,
"s": 1062,
"text": "Following is the code for testing and executing a regular expression in JavaScript −"
},
{
"code": null,
"e": 1158,
"s": 1147,
"text": " Live Demo"
},
{
"code": null,
"e": 2249,
"s": 1158,
"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,.sample {\n font-size: 20px;\n font-weight: 500;\n }\n</style>\n</head>\n<body>\n<h1>Testing and executing regular expressions</h1>\n<div class=\"sample\"></div>\n<div style=\"color: green;\" class=\"result\"></div>\n<button class=\"Btn\">CLICK HERE</button>\n<h3>\nClick on the above button to test and execute the regular expression\n</h3>\n<script>\n let sampleEle=document.querySelector('.sample');\n let resEle = document.querySelector('.result');\n let str = 'Hello world. This is a beautiful world';\n sampleEle.innerHTML =str;\n let pattern = new RegExp(\"world\");\n document.querySelector(\".Btn\").addEventListener(\"click\", () => {\n resEle.innerHTML += 'pattern.test(str) = ' + pattern.test(str) + '<br>';\n resEle.innerHTML += 'pattern.exec(str) = ' + pattern.exec(str) + '<br>';\n });\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2300,
"s": 2249,
"text": "The above code will produce the following output −"
},
{
"code": null,
"e": 2338,
"s": 2300,
"text": "On clicking the ‘CLICK HERE’ button −"
}
] |
Crop Image with OpenCV-Python - GeeksforGeeks
|
10 Oct, 2021
Cropping an Image is one of the most basic image operations that we perform in our projects. In this article, w will discuss how to crop images using OpenCV in Python.
For this, we will take the image shown below.
cv2.imread() method loads an image from the specified file. If the image cannot be read (because of the missing file, improper permissions, unsupported or invalid format) then this method returns an empty matrix.
Note: When we load an image in OpenCV using cv2.imread(), we store it as a Numpy n-dimensional array.
Example: Python program to read the image
Python3
import cv2 # Read Input Imageimg = cv2.imread("test.jpeg") # Check the type of read imageprint(type(img)) # Display the imagecv2.imshow('image', img)cv2.waitKey(0)cv2.destroyAllWindows()
Output:
We can see the type of ‘img‘ as ‘numpy.ndarray‘. Now, we simply apply array slicing to our NumPy array and produce our cropped image, So we have to find the dimensions of the image. For this we will use the image.shape attribute.
Syntax:
image.shape
where image is the input image
Example: Python code to find the dimensions of the image,
Python3
import cv2 # read the imageimg = cv2.imread("test.jpeg")print(type(img)) # Check the shape of the input imageprint("Shape of the image", img.shape)
Output:
image shape
Now we can apply array slicing to produce our final result.
Syntax :
image[rows,columns]
where
rows are the row slicecolumns is the column slice
rows are the row slice
columns is the column slice
Example:
Python3
import cv2 img = cv2.imread("test.jpeg")print(type(img)) # Shape of the imageprint("Shape of the image", img.shape) # [rows, columns]crop = img[50:180, 100:300] cv2.imshow('original', img)cv2.imshow('cropped', crop)cv2.waitKey(0)cv2.destroyAllWindows()
Output:
Picked
Python-OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Bar Plot in Matplotlib
|
[
{
"code": null,
"e": 24212,
"s": 24184,
"text": "\n10 Oct, 2021"
},
{
"code": null,
"e": 24380,
"s": 24212,
"text": "Cropping an Image is one of the most basic image operations that we perform in our projects. In this article, w will discuss how to crop images using OpenCV in Python."
},
{
"code": null,
"e": 24427,
"s": 24380,
"text": "For this, we will take the image shown below. "
},
{
"code": null,
"e": 24640,
"s": 24427,
"text": "cv2.imread() method loads an image from the specified file. If the image cannot be read (because of the missing file, improper permissions, unsupported or invalid format) then this method returns an empty matrix."
},
{
"code": null,
"e": 24742,
"s": 24640,
"text": "Note: When we load an image in OpenCV using cv2.imread(), we store it as a Numpy n-dimensional array."
},
{
"code": null,
"e": 24784,
"s": 24742,
"text": "Example: Python program to read the image"
},
{
"code": null,
"e": 24792,
"s": 24784,
"text": "Python3"
},
{
"code": "import cv2 # Read Input Imageimg = cv2.imread(\"test.jpeg\") # Check the type of read imageprint(type(img)) # Display the imagecv2.imshow('image', img)cv2.waitKey(0)cv2.destroyAllWindows()",
"e": 24982,
"s": 24792,
"text": null
},
{
"code": null,
"e": 24991,
"s": 24982,
"text": "Output: "
},
{
"code": null,
"e": 25221,
"s": 24991,
"text": "We can see the type of ‘img‘ as ‘numpy.ndarray‘. Now, we simply apply array slicing to our NumPy array and produce our cropped image, So we have to find the dimensions of the image. For this we will use the image.shape attribute."
},
{
"code": null,
"e": 25229,
"s": 25221,
"text": "Syntax:"
},
{
"code": null,
"e": 25241,
"s": 25229,
"text": "image.shape"
},
{
"code": null,
"e": 25272,
"s": 25241,
"text": "where image is the input image"
},
{
"code": null,
"e": 25330,
"s": 25272,
"text": "Example: Python code to find the dimensions of the image,"
},
{
"code": null,
"e": 25338,
"s": 25330,
"text": "Python3"
},
{
"code": "import cv2 # read the imageimg = cv2.imread(\"test.jpeg\")print(type(img)) # Check the shape of the input imageprint(\"Shape of the image\", img.shape)",
"e": 25488,
"s": 25338,
"text": null
},
{
"code": null,
"e": 25497,
"s": 25488,
"text": "Output: "
},
{
"code": null,
"e": 25509,
"s": 25497,
"text": "image shape"
},
{
"code": null,
"e": 25569,
"s": 25509,
"text": "Now we can apply array slicing to produce our final result."
},
{
"code": null,
"e": 25578,
"s": 25569,
"text": "Syntax :"
},
{
"code": null,
"e": 25598,
"s": 25578,
"text": "image[rows,columns]"
},
{
"code": null,
"e": 25604,
"s": 25598,
"text": "where"
},
{
"code": null,
"e": 25654,
"s": 25604,
"text": "rows are the row slicecolumns is the column slice"
},
{
"code": null,
"e": 25677,
"s": 25654,
"text": "rows are the row slice"
},
{
"code": null,
"e": 25705,
"s": 25677,
"text": "columns is the column slice"
},
{
"code": null,
"e": 25714,
"s": 25705,
"text": "Example:"
},
{
"code": null,
"e": 25722,
"s": 25714,
"text": "Python3"
},
{
"code": "import cv2 img = cv2.imread(\"test.jpeg\")print(type(img)) # Shape of the imageprint(\"Shape of the image\", img.shape) # [rows, columns]crop = img[50:180, 100:300] cv2.imshow('original', img)cv2.imshow('cropped', crop)cv2.waitKey(0)cv2.destroyAllWindows()",
"e": 25981,
"s": 25722,
"text": null
},
{
"code": null,
"e": 25990,
"s": 25981,
"text": "Output: "
},
{
"code": null,
"e": 25997,
"s": 25990,
"text": "Picked"
},
{
"code": null,
"e": 26011,
"s": 25997,
"text": "Python-OpenCV"
},
{
"code": null,
"e": 26018,
"s": 26011,
"text": "Python"
},
{
"code": null,
"e": 26116,
"s": 26018,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26125,
"s": 26116,
"text": "Comments"
},
{
"code": null,
"e": 26138,
"s": 26125,
"text": "Old Comments"
},
{
"code": null,
"e": 26170,
"s": 26138,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26225,
"s": 26170,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 26281,
"s": 26225,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26320,
"s": 26281,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26362,
"s": 26320,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26404,
"s": 26362,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26426,
"s": 26404,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26457,
"s": 26426,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26486,
"s": 26457,
"text": "Create a directory in Python"
}
] |
Complex Numbers in Python?
|
A complex number is created from real numbers. Python complex number can be created either using direct assignment statement or by using complex () function.
Complex numbers which are mostly used where we are using two real numbers. For instance, an electric circuit which is defined by voltage(V) and current(C) are used in geometry, scientific calculations and calculus.
complex([real[, imag]])
>>> c = 3 +6j
>>> print(type(c))
<class 'complex'>
>>> print(c)
(3+6j)
>>>
>>> c1 = complex(3,6)
>>> print(type(c1))
<class 'complex'>
>>> print(c1)
(3+6j)
From above results, we can see python complex numbers are of type complex. Each complex number consist of one real part and one imaginary part.
>>> #Complex Number:
>>> c = (3 + 6j)
>>>
>>> #Real Part of complex number
>>> print('Complex Number: Real Part is = ', c. real)
Complex Number: Real Part is = 3.0
>>>
>>> #Imaginary Part of complex number
>>> print('Complex Number: Imaginary Part is = ', c. imag)
Complex Number: Imaginary Part is = 6.0
>>>
>>> #Conjugate of complex number
>>> print('Complex Number: conjugate Part = ', c. conjugate())
Complex Number: conjugate Part = (3-6j)
We can do simple mathematical calculations on complex numbers:
>>> #first complex number
>>> c1 = 3 + 6j
>>> #Second complex number
>>> c2 = 6 + 15j
>>>
>>> #Addition
>>> print("Addition of two complex number =", c1 + c2)
Addition of two complex number = (9+21j)
>>>
>>> #Subtraction
>>> print("Subtraction of two complex number =", c1 - c2)
Subtraction of two complex number = (-3-9j)
>>>
>>> #Multiplication
>>> print("Multiplication of two complex number =", c1 * c2)
Multiplication of two complex number = (-72+81j)
>>>
>>> #Division
>>> print("Division of two complex number =", c1 / c2)
Division of two complex number = (0.4137931034482759-0.03448275862068964j)
However, complex numbers don’t support comparison operators like <, >, <=, => and it will through TypeError message:
>>> c2 <= c2
Traceback (most recent call last):
File "<pyshell#40>", line 1, in <module>
c2 <= c2
TypeError: '<=' not supported between instances of 'complex' and 'complex'
Python cmath module provide access to mathematical functions for complex numbers. Let’s looks at some of the important features of complex numbers using math module function.
The phase of a complex number is the angle between the real axis and the vector representing the imaginary part.
The phase returned by math and cmath modules are in radians and we use the numpy.degrees() function to convert it to degrees.
import cmath, math, numpy
c = 4+ 4j
# phase
phase = cmath.phase(c)
print('4+ 4j Phase =', phase)
print('Phase in Degrees =', numpy.degrees(phase))
print('-4-4j Phase =', cmath.phase(-4-4j), 'radians. Degrees =', numpy.degrees(cmath.phase(-4-4j)))
# we can get phase using math.atan2() function too
print('Complex number phase using math.atan2() =', math.atan2(2, 1))
4+ 4j Phase = 0.7853981633974483
Phase in Degrees = 45.0
-4-4j Phase = -2.356194490192345 radians. Degrees = -135.0
Complex number phase using math.atan2() = 1.1071487177940904
There are a couple of constans available in cmath module that are used in the complex number calculations:
import cmath
print('π =', cmath.pi)
print('e =', cmath.e)
print('tau =', cmath.tau)
print('Positive infinity =', cmath.inf)
print('Positive Complex infinity =', cmath.infj)
print('NaN =', cmath.nan)
print('NaN Complex =', cmath.nanj)
π = 3.141592653589793
e = 2.718281828459045
tau = 6.283185307179586
Positive infinity = inf
Positive Complex infinity = infj
NaN = nan
NaN Complex = nanj
The cmath() module provides some useful functions for logarithmic and power operations:
import cmath
c = 1 + 2j
print('e^c =', cmath.exp(c))
print('log2(c) =', cmath.log(c, 2))
print('log10(c) =', cmath.log10(c))
print('sqrt(c) =', cmath.sqrt(c))
e^c = (-1.1312043837568135+2.4717266720048188j)
log2(c) = (1.1609640474436813+1.5972779646881088j)
log10(c) = (0.3494850021680094+0.480828578784234j)
sqrt(c) = (1.272019649514069+0.7861513777574233j)
import cmath
c = 2 + 4j
print('arc sine value:\n ', cmath.asin(c))
print('arc cosine value :\n', cmath.acos(c))
print('arc tangent value of complex number c :\n', cmath.atan(c))
print('sine value:\n', cmath.sin(c))
print('cosine value:\n', cmath.cos(c))
print('tangent value:\n', cmath.tan(c))
arc sine value:
(0.4538702099631225+2.198573027920936j)
arc cosine value :
(1.1169261168317741-2.198573027920936j)
arc tangent value of complex number c :
(1.4670482135772953+0.20058661813123432j)
sine value:
(24.83130584894638-11.356612711218174j)
cosine value:
(-11.36423470640106-24.814651485634187j)
tangent value:
(-0.0005079806234700387+1.0004385132020523j)
import cmath
c = 2 + 4j
print('Inverse hyperbolic sine value: \n', cmath.asinh(c))
print('Inverse hyperbolic cosine value: \n', cmath.acosh(c))
print('Inverse hyperbolic tangent value: \n', cmath.atanh(c))
print('Hyperbolic sine value: \n', cmath.sinh(c))
print('Hyperbolic cosine value: \n', cmath.cosh(c))
print('Hyperbolic tangent value: \n', cmath.tanh(c))
Inverse hyperbolic sine value:
(2.183585216564564+1.096921548830143j)
Inverse hyperbolic cosine value:
(2.198573027920936+1.1169261168317741j)
Inverse hyperbolic tangent value:
(0.09641562020299617+1.3715351039616865j)
Hyperbolic sine value:
(-2.370674169352002-2.8472390868488278j)
Hyperbolic cosine value:
(-2.4591352139173837-2.744817006792154j)
Hyperbolic tangent value:
(1.0046823121902348+0.03642336924740368j)
|
[
{
"code": null,
"e": 1220,
"s": 1062,
"text": "A complex number is created from real numbers. Python complex number can be created either using direct assignment statement or by using complex () function."
},
{
"code": null,
"e": 1435,
"s": 1220,
"text": "Complex numbers which are mostly used where we are using two real numbers. For instance, an electric circuit which is defined by voltage(V) and current(C) are used in geometry, scientific calculations and calculus."
},
{
"code": null,
"e": 1459,
"s": 1435,
"text": "complex([real[, imag]])"
},
{
"code": null,
"e": 1615,
"s": 1459,
"text": ">>> c = 3 +6j\n>>> print(type(c))\n<class 'complex'>\n>>> print(c)\n(3+6j)\n>>>\n>>> c1 = complex(3,6)\n>>> print(type(c1))\n<class 'complex'>\n>>> print(c1)\n(3+6j)"
},
{
"code": null,
"e": 1759,
"s": 1615,
"text": "From above results, we can see python complex numbers are of type complex. Each complex number consist of one real part and one imaginary part."
},
{
"code": null,
"e": 2204,
"s": 1759,
"text": ">>> #Complex Number:\n>>> c = (3 + 6j)\n>>>\n>>> #Real Part of complex number\n>>> print('Complex Number: Real Part is = ', c. real)\nComplex Number: Real Part is = 3.0\n>>>\n>>> #Imaginary Part of complex number\n>>> print('Complex Number: Imaginary Part is = ', c. imag)\nComplex Number: Imaginary Part is = 6.0\n>>>\n>>> #Conjugate of complex number\n>>> print('Complex Number: conjugate Part = ', c. conjugate())\nComplex Number: conjugate Part = (3-6j)"
},
{
"code": null,
"e": 2267,
"s": 2204,
"text": "We can do simple mathematical calculations on complex numbers:"
},
{
"code": null,
"e": 2872,
"s": 2267,
"text": ">>> #first complex number\n>>> c1 = 3 + 6j\n>>> #Second complex number\n>>> c2 = 6 + 15j\n>>>\n>>> #Addition\n>>> print(\"Addition of two complex number =\", c1 + c2)\nAddition of two complex number = (9+21j)\n>>>\n>>> #Subtraction\n>>> print(\"Subtraction of two complex number =\", c1 - c2)\nSubtraction of two complex number = (-3-9j)\n>>>\n>>> #Multiplication\n>>> print(\"Multiplication of two complex number =\", c1 * c2)\nMultiplication of two complex number = (-72+81j)\n>>>\n>>> #Division\n>>> print(\"Division of two complex number =\", c1 / c2)\nDivision of two complex number = (0.4137931034482759-0.03448275862068964j)"
},
{
"code": null,
"e": 2989,
"s": 2872,
"text": "However, complex numbers don’t support comparison operators like <, >, <=, => and it will through TypeError message:"
},
{
"code": null,
"e": 3162,
"s": 2989,
"text": ">>> c2 <= c2\nTraceback (most recent call last):\nFile \"<pyshell#40>\", line 1, in <module>\nc2 <= c2\nTypeError: '<=' not supported between instances of 'complex' and 'complex'"
},
{
"code": null,
"e": 3337,
"s": 3162,
"text": "Python cmath module provide access to mathematical functions for complex numbers. Let’s looks at some of the important features of complex numbers using math module function."
},
{
"code": null,
"e": 3450,
"s": 3337,
"text": "The phase of a complex number is the angle between the real axis and the vector representing the imaginary part."
},
{
"code": null,
"e": 3576,
"s": 3450,
"text": "The phase returned by math and cmath modules are in radians and we use the numpy.degrees() function to convert it to degrees."
},
{
"code": null,
"e": 3943,
"s": 3576,
"text": "import cmath, math, numpy\nc = 4+ 4j\n# phase\nphase = cmath.phase(c)\nprint('4+ 4j Phase =', phase)\nprint('Phase in Degrees =', numpy.degrees(phase))\nprint('-4-4j Phase =', cmath.phase(-4-4j), 'radians. Degrees =', numpy.degrees(cmath.phase(-4-4j)))\n# we can get phase using math.atan2() function too\nprint('Complex number phase using math.atan2() =', math.atan2(2, 1))"
},
{
"code": null,
"e": 4120,
"s": 3943,
"text": "4+ 4j Phase = 0.7853981633974483\nPhase in Degrees = 45.0\n-4-4j Phase = -2.356194490192345 radians. Degrees = -135.0\nComplex number phase using math.atan2() = 1.1071487177940904"
},
{
"code": null,
"e": 4227,
"s": 4120,
"text": "There are a couple of constans available in cmath module that are used in the complex number calculations:"
},
{
"code": null,
"e": 4461,
"s": 4227,
"text": "import cmath\nprint('π =', cmath.pi)\nprint('e =', cmath.e)\nprint('tau =', cmath.tau)\nprint('Positive infinity =', cmath.inf)\nprint('Positive Complex infinity =', cmath.infj)\nprint('NaN =', cmath.nan)\nprint('NaN Complex =', cmath.nanj)"
},
{
"code": null,
"e": 4615,
"s": 4461,
"text": "π = 3.141592653589793\ne = 2.718281828459045\ntau = 6.283185307179586\nPositive infinity = inf\nPositive Complex infinity = infj\nNaN = nan\nNaN Complex = nanj"
},
{
"code": null,
"e": 4703,
"s": 4615,
"text": "The cmath() module provides some useful functions for logarithmic and power operations:"
},
{
"code": null,
"e": 4862,
"s": 4703,
"text": "import cmath\nc = 1 + 2j\nprint('e^c =', cmath.exp(c))\nprint('log2(c) =', cmath.log(c, 2))\nprint('log10(c) =', cmath.log10(c))\nprint('sqrt(c) =', cmath.sqrt(c))"
},
{
"code": null,
"e": 5062,
"s": 4862,
"text": "e^c = (-1.1312043837568135+2.4717266720048188j)\nlog2(c) = (1.1609640474436813+1.5972779646881088j)\nlog10(c) = (0.3494850021680094+0.480828578784234j)\nsqrt(c) = (1.272019649514069+0.7861513777574233j)"
},
{
"code": null,
"e": 5356,
"s": 5062,
"text": "import cmath\nc = 2 + 4j\nprint('arc sine value:\\n ', cmath.asin(c))\nprint('arc cosine value :\\n', cmath.acos(c))\nprint('arc tangent value of complex number c :\\n', cmath.atan(c))\nprint('sine value:\\n', cmath.sin(c))\nprint('cosine value:\\n', cmath.cos(c))\nprint('tangent value:\\n', cmath.tan(c))"
},
{
"code": null,
"e": 5720,
"s": 5356,
"text": "arc sine value:\n(0.4538702099631225+2.198573027920936j)\narc cosine value :\n(1.1169261168317741-2.198573027920936j)\narc tangent value of complex number c :\n(1.4670482135772953+0.20058661813123432j)\nsine value:\n(24.83130584894638-11.356612711218174j)\ncosine value:\n(-11.36423470640106-24.814651485634187j)\ntangent value:\n(-0.0005079806234700387+1.0004385132020523j)"
},
{
"code": null,
"e": 6081,
"s": 5720,
"text": "import cmath\nc = 2 + 4j\nprint('Inverse hyperbolic sine value: \\n', cmath.asinh(c))\nprint('Inverse hyperbolic cosine value: \\n', cmath.acosh(c))\nprint('Inverse hyperbolic tangent value: \\n', cmath.atanh(c))\nprint('Hyperbolic sine value: \\n', cmath.sinh(c))\nprint('Hyperbolic cosine value: \\n', cmath.cosh(c))\nprint('Hyperbolic tangent value: \\n', cmath.tanh(c))"
},
{
"code": null,
"e": 6498,
"s": 6081,
"text": "Inverse hyperbolic sine value:\n(2.183585216564564+1.096921548830143j)\nInverse hyperbolic cosine value:\n(2.198573027920936+1.1169261168317741j)\nInverse hyperbolic tangent value:\n(0.09641562020299617+1.3715351039616865j)\nHyperbolic sine value:\n(-2.370674169352002-2.8472390868488278j)\nHyperbolic cosine value:\n(-2.4591352139173837-2.744817006792154j)\nHyperbolic tangent value:\n(1.0046823121902348+0.03642336924740368j)"
}
] |
C# | Math.Tanh() Method - GeeksforGeeks
|
13 Dec, 2021
Math.Tanh() is the inbuilt Math class method which returns the hyperbolic tan of a given double value argument. The result will be NaN if the given argument is NaN.Syntax:
public static double Tanh(double num)
Parameter:
num: It is the number whose hyperbolic tan is to be returned and type of this parameter is System.Double.
Return Value: The method returns the hyperbolic tan of num. of type System.Double. If num is equal to NegativeInfinity, this method returns -1. If num is equal to PositiveInfinity, this method returns 1. If num is equal to NaN, this method returns NaN.Examples :
Input : num = 60.0
Output : 1.0
Below programs illustrate the Math.Tanh() method:Program 1:
Csharp
// C# program to illustrate the// Math.Tanh()using System; class GFG { // Main Method public static void Main(String[] args) { double num1 = 60.0, num2 = 0.0, num3 = 1.0; // It returns the hyperbolic tan of // specified angle in radian double tanhvalue = Math.Tanh(num1); Console.WriteLine("The tanh of num1 = " + tanhvalue); tanhvalue = Math.Tanh(num2); Console.WriteLine("The tanh of num2 = " + tanhvalue); tanhvalue = Math.Tanh(num3); Console.WriteLine("The tanh of num3 = " + tanhvalue); }}
The tanh of num1 = 1
The tanh of num2 = 0
The tanh of num3 = 0.761594155955765
Program 2:
Csharp
// C# program to illustrate the// Math.Tanh() Methodusing System; class GFG { // Main Method public static void Main(String[] args) { double num1 = (30 * (Math.PI)) / 180, num2 = 11.0, num3 = 45.0; // It returns the hyperbolic tan of // angle in radian double tanhvalue = Math.Tanh(num1); Console.WriteLine("The tanh of num1 = " + tanhvalue); tanhvalue = Math.Tanh(num2); Console.WriteLine("The tanh of num2 = " + tanhvalue); tanhvalue = Math.Tanh(num3); Console.WriteLine("The tanh of num3 = " + tanhvalue); }}
The tanh of num1 = 0.480472778156452
The tanh of num2 = 0.999999999442106
The tanh of num3 = 1
ruhelaa48
CSharp-Math
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Delegates
C# | Method Overriding
C# | Abstract Classes
Difference between Ref and Out keywords in C#
Extension Method in C#
C# | Replace() Method
C# | Class and Object
C# | Constructors
Introduction to .NET Framework
|
[
{
"code": null,
"e": 25745,
"s": 25717,
"text": "\n13 Dec, 2021"
},
{
"code": null,
"e": 25917,
"s": 25745,
"text": "Math.Tanh() is the inbuilt Math class method which returns the hyperbolic tan of a given double value argument. The result will be NaN if the given argument is NaN.Syntax:"
},
{
"code": null,
"e": 25955,
"s": 25917,
"text": "public static double Tanh(double num)"
},
{
"code": null,
"e": 25967,
"s": 25955,
"text": "Parameter: "
},
{
"code": null,
"e": 26073,
"s": 25967,
"text": "num: It is the number whose hyperbolic tan is to be returned and type of this parameter is System.Double."
},
{
"code": null,
"e": 26337,
"s": 26073,
"text": "Return Value: The method returns the hyperbolic tan of num. of type System.Double. If num is equal to NegativeInfinity, this method returns -1. If num is equal to PositiveInfinity, this method returns 1. If num is equal to NaN, this method returns NaN.Examples : "
},
{
"code": null,
"e": 26370,
"s": 26337,
"text": "Input : num = 60.0\nOutput : 1.0"
},
{
"code": null,
"e": 26431,
"s": 26370,
"text": "Below programs illustrate the Math.Tanh() method:Program 1: "
},
{
"code": null,
"e": 26438,
"s": 26431,
"text": "Csharp"
},
{
"code": "// C# program to illustrate the// Math.Tanh()using System; class GFG { // Main Method public static void Main(String[] args) { double num1 = 60.0, num2 = 0.0, num3 = 1.0; // It returns the hyperbolic tan of // specified angle in radian double tanhvalue = Math.Tanh(num1); Console.WriteLine(\"The tanh of num1 = \" + tanhvalue); tanhvalue = Math.Tanh(num2); Console.WriteLine(\"The tanh of num2 = \" + tanhvalue); tanhvalue = Math.Tanh(num3); Console.WriteLine(\"The tanh of num3 = \" + tanhvalue); }}",
"e": 27014,
"s": 26438,
"text": null
},
{
"code": null,
"e": 27093,
"s": 27014,
"text": "The tanh of num1 = 1\nThe tanh of num2 = 0\nThe tanh of num3 = 0.761594155955765"
},
{
"code": null,
"e": 27108,
"s": 27095,
"text": "Program 2: "
},
{
"code": null,
"e": 27115,
"s": 27108,
"text": "Csharp"
},
{
"code": "// C# program to illustrate the// Math.Tanh() Methodusing System; class GFG { // Main Method public static void Main(String[] args) { double num1 = (30 * (Math.PI)) / 180, num2 = 11.0, num3 = 45.0; // It returns the hyperbolic tan of // angle in radian double tanhvalue = Math.Tanh(num1); Console.WriteLine(\"The tanh of num1 = \" + tanhvalue); tanhvalue = Math.Tanh(num2); Console.WriteLine(\"The tanh of num2 = \" + tanhvalue); tanhvalue = Math.Tanh(num3); Console.WriteLine(\"The tanh of num3 = \" + tanhvalue); }}",
"e": 27710,
"s": 27115,
"text": null
},
{
"code": null,
"e": 27805,
"s": 27710,
"text": "The tanh of num1 = 0.480472778156452\nThe tanh of num2 = 0.999999999442106\nThe tanh of num3 = 1"
},
{
"code": null,
"e": 27817,
"s": 27807,
"text": "ruhelaa48"
},
{
"code": null,
"e": 27829,
"s": 27817,
"text": "CSharp-Math"
},
{
"code": null,
"e": 27843,
"s": 27829,
"text": "CSharp-method"
},
{
"code": null,
"e": 27846,
"s": 27843,
"text": "C#"
},
{
"code": null,
"e": 27944,
"s": 27846,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27972,
"s": 27944,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 27987,
"s": 27972,
"text": "C# | Delegates"
},
{
"code": null,
"e": 28010,
"s": 27987,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 28032,
"s": 28010,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 28078,
"s": 28032,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 28101,
"s": 28078,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 28123,
"s": 28101,
"text": "C# | Replace() Method"
},
{
"code": null,
"e": 28145,
"s": 28123,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 28163,
"s": 28145,
"text": "C# | Constructors"
}
] |
C# | Remove elements from a HashSet with conditions defined by the predicate - GeeksforGeeks
|
01 Feb, 2019
A HashSet is an unordered collection of the unique elements. It comes under System.Collections.Generic namespace. It is used in a situation where we want to prevent duplicates from being inserted in the collection. As far as performance is concerned, it is better in comparison to the list.
HashSet<T>.RemoveWhere(Predicate<T>) method is used to remove all elements that match the conditions defined by the specified predicate from a HashSet<T> collection.
Syntax:
public int RemoveWhere (Predicate<T> match);
Return Value: This method returns the number of elements that were removed from the HashSet<T> collection.
Exception: This method will give the ArgumentNullException if the match is null.
Note: Calling this method is an O(n) operation, where n is Count i.e, the number of elements that are contained in the set.
Below are the programs to illustrate the use of HashSet<T>.RemoveWhere(Predicate<T>) Method:
Example 1:
// C# code to remove elements from a HashSet// with conditions defined by the predicateusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a HashSet of integers HashSet<int> mySet = new HashSet<int>(); // Inserting elements into HashSet for (int i = 0; i < 10; i++) { mySet.Add(i); } Console.WriteLine("The elements in HashSet are : "); // Displaying the elements in HashSet foreach(int i in mySet) { Console.WriteLine(i); } // Displaying the number of elements in HashSet Console.WriteLine("Number of elements are : " + mySet.Count); // Remove elements from a HashSet // with conditions defined by the predicate mySet.RemoveWhere(isEven); Console.WriteLine("The elements in HashSet are : "); // Displaying the elements in HashSet foreach(int i in mySet) { Console.WriteLine(i); } // Displaying the number of elements in HashSet Console.WriteLine("Number of elements are : " + mySet.Count); } // Helper function which tells // whether an element is even or not private static bool isEven(int i) { return ((i % 2) == 0); }}
The elements in HashSet are :
0
1
2
3
4
5
6
7
8
9
Number of elements are : 10
The elements in HashSet are :
1
3
5
7
9
Number of elements are : 5
Example 2:
// C# code to remove elements from a HashSet// with conditions defined by the predicateusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a HashSet of integers HashSet<int> mySet = new HashSet<int>(); // Inserting elements into HashSet for (int i = 0; i < 20; i++) { mySet.Add(i); } // Displaying the number of elements in HashSet Console.WriteLine("Number of elements are : " + mySet.Count); // Remove elements from a HashSet // with conditions defined by the predicate mySet.RemoveWhere(myFunc); // Displaying the number of elements in HashSet Console.WriteLine("Number of elements are : " + mySet.Count); } // Helper function which tells // whether an element is divisible // by both 2 and 3 private static bool myFunc(int i) { return ((i % 2) == 0 && (i % 3 == 0)); }}
Number of elements are : 20
Number of elements are : 16
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.hashset-1.removewhere?view=netframework-4.7.2
CSharp-Generic-HashSet
CSharp-Generic-Namespace
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# | Constructors
C# | Class and Object
Introduction to .NET Framework
Extension Method in C#
Difference between Ref and Out keywords in C#
C# | String.IndexOf( ) Method | Set - 1
C# | Delegates
C# | Data Types
C# | Abstract Classes
C# | Replace() Method
|
[
{
"code": null,
"e": 24736,
"s": 24708,
"text": "\n01 Feb, 2019"
},
{
"code": null,
"e": 25027,
"s": 24736,
"text": "A HashSet is an unordered collection of the unique elements. It comes under System.Collections.Generic namespace. It is used in a situation where we want to prevent duplicates from being inserted in the collection. As far as performance is concerned, it is better in comparison to the list."
},
{
"code": null,
"e": 25193,
"s": 25027,
"text": "HashSet<T>.RemoveWhere(Predicate<T>) method is used to remove all elements that match the conditions defined by the specified predicate from a HashSet<T> collection."
},
{
"code": null,
"e": 25201,
"s": 25193,
"text": "Syntax:"
},
{
"code": null,
"e": 25247,
"s": 25201,
"text": "public int RemoveWhere (Predicate<T> match);\n"
},
{
"code": null,
"e": 25354,
"s": 25247,
"text": "Return Value: This method returns the number of elements that were removed from the HashSet<T> collection."
},
{
"code": null,
"e": 25435,
"s": 25354,
"text": "Exception: This method will give the ArgumentNullException if the match is null."
},
{
"code": null,
"e": 25559,
"s": 25435,
"text": "Note: Calling this method is an O(n) operation, where n is Count i.e, the number of elements that are contained in the set."
},
{
"code": null,
"e": 25652,
"s": 25559,
"text": "Below are the programs to illustrate the use of HashSet<T>.RemoveWhere(Predicate<T>) Method:"
},
{
"code": null,
"e": 25663,
"s": 25652,
"text": "Example 1:"
},
{
"code": "// C# code to remove elements from a HashSet// with conditions defined by the predicateusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a HashSet of integers HashSet<int> mySet = new HashSet<int>(); // Inserting elements into HashSet for (int i = 0; i < 10; i++) { mySet.Add(i); } Console.WriteLine(\"The elements in HashSet are : \"); // Displaying the elements in HashSet foreach(int i in mySet) { Console.WriteLine(i); } // Displaying the number of elements in HashSet Console.WriteLine(\"Number of elements are : \" + mySet.Count); // Remove elements from a HashSet // with conditions defined by the predicate mySet.RemoveWhere(isEven); Console.WriteLine(\"The elements in HashSet are : \"); // Displaying the elements in HashSet foreach(int i in mySet) { Console.WriteLine(i); } // Displaying the number of elements in HashSet Console.WriteLine(\"Number of elements are : \" + mySet.Count); } // Helper function which tells // whether an element is even or not private static bool isEven(int i) { return ((i % 2) == 0); }}",
"e": 26992,
"s": 25663,
"text": null
},
{
"code": null,
"e": 27140,
"s": 26992,
"text": "The elements in HashSet are : \n0\n1\n2\n3\n4\n5\n6\n7\n8\n9\nNumber of elements are : 10\nThe elements in HashSet are : \n1\n3\n5\n7\n9\nNumber of elements are : 5\n"
},
{
"code": null,
"e": 27151,
"s": 27140,
"text": "Example 2:"
},
{
"code": "// C# code to remove elements from a HashSet// with conditions defined by the predicateusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a HashSet of integers HashSet<int> mySet = new HashSet<int>(); // Inserting elements into HashSet for (int i = 0; i < 20; i++) { mySet.Add(i); } // Displaying the number of elements in HashSet Console.WriteLine(\"Number of elements are : \" + mySet.Count); // Remove elements from a HashSet // with conditions defined by the predicate mySet.RemoveWhere(myFunc); // Displaying the number of elements in HashSet Console.WriteLine(\"Number of elements are : \" + mySet.Count); } // Helper function which tells // whether an element is divisible // by both 2 and 3 private static bool myFunc(int i) { return ((i % 2) == 0 && (i % 3 == 0)); }}",
"e": 28134,
"s": 27151,
"text": null
},
{
"code": null,
"e": 28191,
"s": 28134,
"text": "Number of elements are : 20\nNumber of elements are : 16\n"
},
{
"code": null,
"e": 28202,
"s": 28191,
"text": "Reference:"
},
{
"code": null,
"e": 28319,
"s": 28202,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.hashset-1.removewhere?view=netframework-4.7.2"
},
{
"code": null,
"e": 28342,
"s": 28319,
"text": "CSharp-Generic-HashSet"
},
{
"code": null,
"e": 28367,
"s": 28342,
"text": "CSharp-Generic-Namespace"
},
{
"code": null,
"e": 28381,
"s": 28367,
"text": "CSharp-method"
},
{
"code": null,
"e": 28384,
"s": 28381,
"text": "C#"
},
{
"code": null,
"e": 28482,
"s": 28384,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28491,
"s": 28482,
"text": "Comments"
},
{
"code": null,
"e": 28504,
"s": 28491,
"text": "Old Comments"
},
{
"code": null,
"e": 28522,
"s": 28504,
"text": "C# | Constructors"
},
{
"code": null,
"e": 28544,
"s": 28522,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 28575,
"s": 28544,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 28598,
"s": 28575,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 28644,
"s": 28598,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 28684,
"s": 28644,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 28699,
"s": 28684,
"text": "C# | Delegates"
},
{
"code": null,
"e": 28715,
"s": 28699,
"text": "C# | Data Types"
},
{
"code": null,
"e": 28737,
"s": 28715,
"text": "C# | Abstract Classes"
}
] |
Find the only repeating element in a sorted array of size n - GeeksforGeeks
|
24 Jan, 2022
Given a sorted array of n elements containing elements in range from 1 to n-1 i.e. one element occurs twice, the task is to find the repeating element in an array.Examples :
Input : arr[] = { 1, 2 , 3 , 4 , 4}
Output : 4
Input : arr[] = { 1 , 1 , 2 , 3 , 4}
Output : 1
A naive approach is to scan the whole array and check if an element occurs twice, then return. This approach takes O(n) time.An efficient method is to use Binary Search.
Observation: If an element ‘X’ is repeating, then it must be at index ‘X’ in the array. So the problem reduces to find any element whose value is same as its index.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find the only repeating element in an// array of size n and elements from range 1 to n-1.#include <bits/stdc++.h>using namespace std; // Returns index of second appearance of a repeating element// The function assumes that array elements are in range from// 1 to n-1.int FindRepeatingElement(int arr[], int size){ int lo = 0; int hi = size - 1; int mid; while(lo <= hi){ mid = (lo+hi)/2; if(arr[mid] <= mid){ hi = mid-1; } else{ lo = mid + 1; } } return lo;} // Driver codeint main(){ int arr[] = {1, 2, 3, 3, 4, 5}; int n = sizeof(arr) / sizeof(arr[0]); int index = findRepeatingElement(arr, n); if (index != -1) cout << arr[index]; return 0;}
// Java program to find the only repeating element in an// array of size n and elements from range 1 to n-1. class Test{ // Returns index of second appearance of a repeating element // The function assumes that array elements are in range from // 1 to n-1. static int findRepeatingElement(int arr[], int low, int high) { // low = 0 , high = n-1; if (low > high) return -1; int mid = (low + high) / 2; // Check if the mid element is the repeating one if (arr[mid] != mid + 1) { if (mid > 0 && arr[mid]==arr[mid-1]) return mid; // If mid element is not at its position that means // the repeated element is in left return findRepeatingElement(arr, low, mid-1); } // If mid is at proper position then repeated one is in // right. return findRepeatingElement(arr, mid+1, high); } // Driver method public static void main(String[] args) { int arr[] = {1, 2, 3, 3, 4, 5}; int index = findRepeatingElement(arr, 0, arr.length-1); if (index != -1) System.out.println(arr[index]); }}
# Python program to find the only repeating element in an# array of size n and elements from range 1 to n-1 # Returns index of second appearance of a repeating element# The function assumes that array elements are in range from# 1 to n-1.def findRepeatingElement(arr, low, high): # low = 0 , high = n-1 if low > high: return -1 mid = (low + high) // 2 # Check if the mid element is the repeating one if (arr[mid] != mid + 1): if (mid > 0 and arr[mid]==arr[mid-1]): return mid # If mid element is not at its position that means # the repeated element is in left return findRepeatingElement(arr, low, mid-1) # If mid is at proper position then repeated one is in # right. return findRepeatingElement(arr, mid+1, high) # Driver codearr = [1, 2, 3, 3, 4, 5]n = len(arr)index = findRepeatingElement(arr, 0, n-1)if (index is not -1): print (arr[index]) #This code is contributed by Afzal Ansari
// C# program to find the only repeating// element in an array of size n and// elements from range 1 to n-1.using System; class Test{ // Returns index of second appearance of a // repeating element. The function assumes that // array elements are in range from 1 to n-1. static int findRepeatingElement(int []arr, int low, int high) { // low = 0 , high = n-1; if (low > high) return -1; int mid = (low + high) / 2; // Check if the mid element // is the repeating one if (arr[mid] != mid + 1) { if (mid > 0 && arr[mid]==arr[mid-1]) return mid; // If mid element is not at its position // that means the repeated element is in left return findRepeatingElement(arr, low, mid-1); } // If mid is at proper position // then repeated one is in right. return findRepeatingElement(arr, mid+1, high); } // Driver method public static void Main() { int []arr = {1, 2, 3, 3, 4, 5}; int index = findRepeatingElement(arr, 0, arr.Length-1); if (index != -1) Console.Write(arr[index]); }} // This code is contributed by Nitin Mittal.
<?php// PHP program to find the only// repeating element in an array// of size n and elements from// range 1 to n-1. // Returns index of second// appearance of a repeating// element. The function assumes// that array elements are in// range from 1 to n-1.function findRepeatingElement($arr, $low, $high){ // low = 0 , high = n-1; if ($low > $high) return -1; $mid = floor(($low + $high) / 2); // Check if the mid element // is the repeating one if ($arr[$mid] != $mid + 1) { if ($mid > 0 && $arr[$mid] == $arr[$mid - 1]) return $mid; // If mid element is not at // its position that means // the repeated element is in left return findRepeatingElement($arr, $low, $mid - 1); } // If mid is at proper position // then repeated one is in right. return findRepeatingElement($arr, $mid + 1, $high);} // Driver code$arr = array(1, 2, 3, 3, 4, 5);$n = sizeof($arr);$index = findRepeatingElement($arr, 0, $n - 1);if ($index != -1)echo $arr[$index]; // This code is contributed// by nitin mittal.?>
<script> // JavaScript program to find the only repeating element in an // array of size n and elements from range 1 to n-1. // Returns index of second appearance of a repeating element // The function assumes that array elements are in range from // 1 to n-1. function findRepeatingElement(arr, low, high) { // low = 0 , high = n-1; if (low > high) return -1; var mid = parseInt((low + high) / 2); // Check if the mid element is the repeating one if (arr[mid] != mid + 1) { if (mid > 0 && arr[mid] == arr[mid - 1]) return mid; // If mid element is not at its position that means // the repeated element is in left return findRepeatingElement(arr, low, mid - 1); } // If mid is at proper position then repeated one is in // right. return findRepeatingElement(arr, mid + 1, high); } // Driver code var arr = [1, 2, 3, 3, 4, 5]; var n = arr.length; var index = findRepeatingElement(arr, 0, n - 1); if (index != -1) document.write(arr[index]); // This code is contributed by rdtank. </script>
Output :
3
Time Complexity : O(log n)This article is contributed by Sahil Chhabra (KILLER). 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
rdtank
satyaprakashbehera38
Arun KG
amartyaghoshgfg
Binary Search
Arrays
Divide and Conquer
Arrays
Divide and Conquer
Binary Search
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
Merge Sort
QuickSort
Binary Search
Maximum and minimum of an array using minimum number of comparisons
Program for Tower of Hanoi
|
[
{
"code": null,
"e": 26781,
"s": 26753,
"text": "\n24 Jan, 2022"
},
{
"code": null,
"e": 26957,
"s": 26781,
"text": "Given a sorted array of n elements containing elements in range from 1 to n-1 i.e. one element occurs twice, the task is to find the repeating element in an array.Examples : "
},
{
"code": null,
"e": 27057,
"s": 26957,
"text": "Input : arr[] = { 1, 2 , 3 , 4 , 4}\nOutput : 4\n\nInput : arr[] = { 1 , 1 , 2 , 3 , 4}\nOutput : 1"
},
{
"code": null,
"e": 27229,
"s": 27059,
"text": "A naive approach is to scan the whole array and check if an element occurs twice, then return. This approach takes O(n) time.An efficient method is to use Binary Search."
},
{
"code": null,
"e": 27394,
"s": 27229,
"text": "Observation: If an element ‘X’ is repeating, then it must be at index ‘X’ in the array. So the problem reduces to find any element whose value is same as its index."
},
{
"code": null,
"e": 27400,
"s": 27396,
"text": "C++"
},
{
"code": null,
"e": 27405,
"s": 27400,
"text": "Java"
},
{
"code": null,
"e": 27413,
"s": 27405,
"text": "Python3"
},
{
"code": null,
"e": 27416,
"s": 27413,
"text": "C#"
},
{
"code": null,
"e": 27420,
"s": 27416,
"text": "PHP"
},
{
"code": null,
"e": 27431,
"s": 27420,
"text": "Javascript"
},
{
"code": "// C++ program to find the only repeating element in an// array of size n and elements from range 1 to n-1.#include <bits/stdc++.h>using namespace std; // Returns index of second appearance of a repeating element// The function assumes that array elements are in range from// 1 to n-1.int FindRepeatingElement(int arr[], int size){ int lo = 0; int hi = size - 1; int mid; while(lo <= hi){ mid = (lo+hi)/2; if(arr[mid] <= mid){ hi = mid-1; } else{ lo = mid + 1; } } return lo;} // Driver codeint main(){ int arr[] = {1, 2, 3, 3, 4, 5}; int n = sizeof(arr) / sizeof(arr[0]); int index = findRepeatingElement(arr, n); if (index != -1) cout << arr[index]; return 0;}",
"e": 28211,
"s": 27431,
"text": null
},
{
"code": "// Java program to find the only repeating element in an// array of size n and elements from range 1 to n-1. class Test{ // Returns index of second appearance of a repeating element // The function assumes that array elements are in range from // 1 to n-1. static int findRepeatingElement(int arr[], int low, int high) { // low = 0 , high = n-1; if (low > high) return -1; int mid = (low + high) / 2; // Check if the mid element is the repeating one if (arr[mid] != mid + 1) { if (mid > 0 && arr[mid]==arr[mid-1]) return mid; // If mid element is not at its position that means // the repeated element is in left return findRepeatingElement(arr, low, mid-1); } // If mid is at proper position then repeated one is in // right. return findRepeatingElement(arr, mid+1, high); } // Driver method public static void main(String[] args) { int arr[] = {1, 2, 3, 3, 4, 5}; int index = findRepeatingElement(arr, 0, arr.length-1); if (index != -1) System.out.println(arr[index]); }}",
"e": 29418,
"s": 28211,
"text": null
},
{
"code": "# Python program to find the only repeating element in an# array of size n and elements from range 1 to n-1 # Returns index of second appearance of a repeating element# The function assumes that array elements are in range from# 1 to n-1.def findRepeatingElement(arr, low, high): # low = 0 , high = n-1 if low > high: return -1 mid = (low + high) // 2 # Check if the mid element is the repeating one if (arr[mid] != mid + 1): if (mid > 0 and arr[mid]==arr[mid-1]): return mid # If mid element is not at its position that means # the repeated element is in left return findRepeatingElement(arr, low, mid-1) # If mid is at proper position then repeated one is in # right. return findRepeatingElement(arr, mid+1, high) # Driver codearr = [1, 2, 3, 3, 4, 5]n = len(arr)index = findRepeatingElement(arr, 0, n-1)if (index is not -1): print (arr[index]) #This code is contributed by Afzal Ansari",
"e": 30391,
"s": 29418,
"text": null
},
{
"code": "// C# program to find the only repeating// element in an array of size n and// elements from range 1 to n-1.using System; class Test{ // Returns index of second appearance of a // repeating element. The function assumes that // array elements are in range from 1 to n-1. static int findRepeatingElement(int []arr, int low, int high) { // low = 0 , high = n-1; if (low > high) return -1; int mid = (low + high) / 2; // Check if the mid element // is the repeating one if (arr[mid] != mid + 1) { if (mid > 0 && arr[mid]==arr[mid-1]) return mid; // If mid element is not at its position // that means the repeated element is in left return findRepeatingElement(arr, low, mid-1); } // If mid is at proper position // then repeated one is in right. return findRepeatingElement(arr, mid+1, high); } // Driver method public static void Main() { int []arr = {1, 2, 3, 3, 4, 5}; int index = findRepeatingElement(arr, 0, arr.Length-1); if (index != -1) Console.Write(arr[index]); }} // This code is contributed by Nitin Mittal.",
"e": 31684,
"s": 30391,
"text": null
},
{
"code": "<?php// PHP program to find the only// repeating element in an array// of size n and elements from// range 1 to n-1. // Returns index of second// appearance of a repeating// element. The function assumes// that array elements are in// range from 1 to n-1.function findRepeatingElement($arr, $low, $high){ // low = 0 , high = n-1; if ($low > $high) return -1; $mid = floor(($low + $high) / 2); // Check if the mid element // is the repeating one if ($arr[$mid] != $mid + 1) { if ($mid > 0 && $arr[$mid] == $arr[$mid - 1]) return $mid; // If mid element is not at // its position that means // the repeated element is in left return findRepeatingElement($arr, $low, $mid - 1); } // If mid is at proper position // then repeated one is in right. return findRepeatingElement($arr, $mid + 1, $high);} // Driver code$arr = array(1, 2, 3, 3, 4, 5);$n = sizeof($arr);$index = findRepeatingElement($arr, 0, $n - 1);if ($index != -1)echo $arr[$index]; // This code is contributed// by nitin mittal.?>",
"e": 32949,
"s": 31684,
"text": null
},
{
"code": "<script> // JavaScript program to find the only repeating element in an // array of size n and elements from range 1 to n-1. // Returns index of second appearance of a repeating element // The function assumes that array elements are in range from // 1 to n-1. function findRepeatingElement(arr, low, high) { // low = 0 , high = n-1; if (low > high) return -1; var mid = parseInt((low + high) / 2); // Check if the mid element is the repeating one if (arr[mid] != mid + 1) { if (mid > 0 && arr[mid] == arr[mid - 1]) return mid; // If mid element is not at its position that means // the repeated element is in left return findRepeatingElement(arr, low, mid - 1); } // If mid is at proper position then repeated one is in // right. return findRepeatingElement(arr, mid + 1, high); } // Driver code var arr = [1, 2, 3, 3, 4, 5]; var n = arr.length; var index = findRepeatingElement(arr, 0, n - 1); if (index != -1) document.write(arr[index]); // This code is contributed by rdtank. </script>",
"e": 34138,
"s": 32949,
"text": null
},
{
"code": null,
"e": 34149,
"s": 34138,
"text": "Output : "
},
{
"code": null,
"e": 34151,
"s": 34149,
"text": "3"
},
{
"code": null,
"e": 34608,
"s": 34151,
"text": "Time Complexity : O(log n)This article is contributed by Sahil Chhabra (KILLER). 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": 34621,
"s": 34608,
"text": "nitin mittal"
},
{
"code": null,
"e": 34628,
"s": 34621,
"text": "rdtank"
},
{
"code": null,
"e": 34649,
"s": 34628,
"text": "satyaprakashbehera38"
},
{
"code": null,
"e": 34657,
"s": 34649,
"text": "Arun KG"
},
{
"code": null,
"e": 34673,
"s": 34657,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 34687,
"s": 34673,
"text": "Binary Search"
},
{
"code": null,
"e": 34694,
"s": 34687,
"text": "Arrays"
},
{
"code": null,
"e": 34713,
"s": 34694,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 34720,
"s": 34713,
"text": "Arrays"
},
{
"code": null,
"e": 34739,
"s": 34720,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 34753,
"s": 34739,
"text": "Binary Search"
},
{
"code": null,
"e": 34851,
"s": 34753,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34919,
"s": 34851,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 34963,
"s": 34919,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 35011,
"s": 34963,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 35034,
"s": 35011,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 35066,
"s": 35034,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 35077,
"s": 35066,
"text": "Merge Sort"
},
{
"code": null,
"e": 35087,
"s": 35077,
"text": "QuickSort"
},
{
"code": null,
"e": 35101,
"s": 35087,
"text": "Binary Search"
},
{
"code": null,
"e": 35169,
"s": 35101,
"text": "Maximum and minimum of an array using minimum number of comparisons"
}
] |
How to check the version of CodeIgniter framework ? - GeeksforGeeks
|
22 Oct, 2021
CodeIgniter is a powerful PHP framework used to create and design projects. The functionality and method calls are dependent on the CodeIgniter framework. The methods get deprecated based on the version of PHP and some of the functionality is specific to the browser. Therefore, it is important to check the version of CodeIgniter framework, which is possible using the following two methods :
Using system/core/CodeIgniter.php: The CodeIgniter framework provides a well structured framework to visualize the values for constants and sessions stored. It contains a directory within it named system folder which contains core database files like cache, driver, query builder etc. Within this folder is the core folder which contains the base class of your application. The version of CodeIgniter framework can be accessed using this file which has the version stored in the constant named CI_VERSION. The below screenshot indicates this:
Example: The below screenshot indicates that the version in use is 3.1.11.
Using php echo command: CI_VERSION is build in constant in CodeIgniter framework, which contains value of version of the framework that is currently being used. This displays the CodeIgniter framework version in which the project is being run on.
Example:
PHP
<?php echo CI_VERSION;?>
Output:
3.1.11
PHP-Questions
Picked
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to fetch data from localserver database and display on HTML table using PHP ?
How to pass form variables from one page to other page in PHP ?
Create a drop-down list that options fetched from a MySQL database in PHP
How to create admin login page using PHP?
Different ways for passing data to view in Laravel
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 24581,
"s": 24553,
"text": "\n22 Oct, 2021"
},
{
"code": null,
"e": 24976,
"s": 24581,
"text": "CodeIgniter is a powerful PHP framework used to create and design projects. The functionality and method calls are dependent on the CodeIgniter framework. The methods get deprecated based on the version of PHP and some of the functionality is specific to the browser. Therefore, it is important to check the version of CodeIgniter framework, which is possible using the following two methods : "
},
{
"code": null,
"e": 25520,
"s": 24976,
"text": "Using system/core/CodeIgniter.php: The CodeIgniter framework provides a well structured framework to visualize the values for constants and sessions stored. It contains a directory within it named system folder which contains core database files like cache, driver, query builder etc. Within this folder is the core folder which contains the base class of your application. The version of CodeIgniter framework can be accessed using this file which has the version stored in the constant named CI_VERSION. The below screenshot indicates this: "
},
{
"code": null,
"e": 25596,
"s": 25520,
"text": "Example: The below screenshot indicates that the version in use is 3.1.11. "
},
{
"code": null,
"e": 25844,
"s": 25596,
"text": "Using php echo command: CI_VERSION is build in constant in CodeIgniter framework, which contains value of version of the framework that is currently being used. This displays the CodeIgniter framework version in which the project is being run on. "
},
{
"code": null,
"e": 25853,
"s": 25844,
"text": "Example:"
},
{
"code": null,
"e": 25857,
"s": 25853,
"text": "PHP"
},
{
"code": "<?php echo CI_VERSION;?>",
"e": 25885,
"s": 25857,
"text": null
},
{
"code": null,
"e": 25893,
"s": 25885,
"text": "Output:"
},
{
"code": null,
"e": 25900,
"s": 25893,
"text": "3.1.11"
},
{
"code": null,
"e": 25914,
"s": 25900,
"text": "PHP-Questions"
},
{
"code": null,
"e": 25921,
"s": 25914,
"text": "Picked"
},
{
"code": null,
"e": 25925,
"s": 25921,
"text": "PHP"
},
{
"code": null,
"e": 25942,
"s": 25925,
"text": "Web Technologies"
},
{
"code": null,
"e": 25946,
"s": 25942,
"text": "PHP"
},
{
"code": null,
"e": 26044,
"s": 25946,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26053,
"s": 26044,
"text": "Comments"
},
{
"code": null,
"e": 26066,
"s": 26053,
"text": "Old Comments"
},
{
"code": null,
"e": 26148,
"s": 26066,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 26212,
"s": 26148,
"text": "How to pass form variables from one page to other page in PHP ?"
},
{
"code": null,
"e": 26286,
"s": 26212,
"text": "Create a drop-down list that options fetched from a MySQL database in PHP"
},
{
"code": null,
"e": 26328,
"s": 26286,
"text": "How to create admin login page using PHP?"
},
{
"code": null,
"e": 26379,
"s": 26328,
"text": "Different ways for passing data to view in Laravel"
},
{
"code": null,
"e": 26435,
"s": 26379,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 26468,
"s": 26435,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26530,
"s": 26468,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 26573,
"s": 26530,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Flatten binary tree to linked list | Practice | GeeksforGeeks
|
Given a binary tree, flatten it into linked list in-place. Usage of auxiliary data structure is not allowed. After flattening, left of each node should point to NULL and right should contain next node in preorder.
Example 1:
Input :
1
/ \
2 5
/ \ \
3 4 6
Output :
1 2 3 4 5 6
Explanation:
After flattening, the tree looks
like this
1
\
2
\
3
\
4
\
5
\
6
Here, left of each node points
to NULL and right contains the
next node in preorder.The inorder
traversal of this flattened tree
is 1 2 3 4 5 6.
Example 2:
Input :
1
/ \
3 4
/
2
\
5
Output :
1 3 4 2 5
Explanation :
After flattening, the tree looks
like this
1
\
3
\
4
\
2
\
5
Here, left of each node points
to NULL and right contains the
next node in preorder.The inorder
traversal of this flattened tree
is 1 3 4 2 5.
0
rohanmeher1642 weeks ago
// java solution
class Solution{ public static void flatten(Node root) { if(root==null) return; while(root!=null) { if(root.left!=null) { Node curr=root.left; while(curr.right!=null) curr=curr.right; curr.right=root.right; root.right=root.left; root.left=null; } root=root.right; } }}
0
vivekroxstar92 weeks ago
JavaScript Solution
class Solution {
constructor(){
this.prev=null;
}
flatten(root){
//code here
if(root===null)return;
this.flatten(root.right);
this.flatten(root.left);
root.right=this.prev;
root.left=null;
this.prev=root;
return root;
}
}
0
adarshgupta4013 weeks ago
Java-Most optimal and Easiest Approach-
class Solution
{
public static void flatten(Node root)
{
Node cur = root;
while (cur != null)
{
if(cur.left != null)
{
Node pre = cur.left;
while(pre.right != null)
{
pre = pre.right;
}
pre.right = cur.right;
cur.right = cur.left;
cur.left = null;
}
cur = cur.right;
}
}
}
0
singhashu19993 weeks ago
class Solution{ public: void flatten(Node *root) { //code here map<int,queue<Node*>> mp; vector<int> p; Node* temp = root; stack<Node*> st; st.push(root); while(st.empty() == false) { temp = st.top(); st.pop(); if(temp != root) { mp[temp->key].push(temp); } p.push_back(temp->key); if(temp->right) { st.push(temp->right); } if(temp->left) { st.push(temp->left); } } //cout << p.size() << endl; int i=0; temp = root; while(i < p.size()) { if(i == p.size() - 1) { temp->left = NULL; temp->right = NULL; break; } //cout << p[i+1] << endl; temp->left = NULL; temp->right = mp[p[i+1]].front(); mp[p[i+1]].pop(); temp = temp->right; i += 1; } }};
0
amishasahu3283 weeks ago
// Morris Traversal
// TC-> O(n) | SC->O(1)
void flatten(Node *root)
{
if(!root) return;
Node *curr = root;
while(curr)
{
if(curr->left != NULL)
{
Node *prev = curr->left;
while(prev->right)
prev = prev->right;
prev->right = curr->right;
curr->right = curr->left;
}
curr->left = NULL;
curr = curr->right;
}
}
0
ayushtiwari264023 weeks ago
class Solution{ public static void flatten(Node root) { if(root==null) return; if(root.left==null){ flatten(root.right); return; }else{ Node left = root.left; root.left=null; Node right = root.right; flatten(left); flatten(right); root.right = left; while(root.right!=null) root=root.right; root.right=right; return; } }}
0
dileeprajoriya20193 weeks ago
Simple Solution Using Morris Traversal--→(c++)
void flatten(Node *root) { Node *curr = root; while(curr) { if(curr->left) { Node *pred = curr->left; while(pred->right != NULL) { pred = pred->right; } pred->right = curr->right; curr->right = curr->left; curr->left = NULL; } curr = curr->right; } }
+1
akashmr10961 month ago
public static void flatten(Node root)
{
flattenUtil(root);
}
private static Node flattenUtil(Node root) {
if (root == null) {
return null;
}
Node n1 = flattenUtil(root.left);
Node rightHead = flattenUtil(root.right);
Node leftHead = n1;
root.left = null;
Node tail = root;
while(n1 != null) {
tail = n1;
n1 = n1.right;
}
if (tail != root) {
root.right = leftHead;
}
tail.right = rightHead;
return root;
}
0
mukulmishra24101 month ago
// USING MORRIS TRAVERSAL
void flatten(Node *root) {
// take a current on the root node Node* curr = root;
// run the loop till the current is not NULL while(curr != NULL){
// if current node does left exist if(curr -> left) {
// find the predecessor of current node Node* pred = curr -> left; while(pred -> right){ pred = pred -> right; }
// link the predecessor node with the current node's right pred -> right = curr -> right;
//link the current node's right with current node's left curr -> right = curr -> left;
// mark current node's left as NULL curr -> left = NULL; }
// if current node's left does not exist, point it to the current node's right curr = curr -> right; } }
0
vasukapoor07992 months ago
Java Solution
public static Node flat(Node node){ if(node == null) return null; // Returning the tails Node ltail = flat(node.left); Node rtail = flat(node.right); // Here we are checking if we have leftSubtree because if ltail is null then // No node is present in leftSubtree if(ltail != null){ ltail.right = node.right; node.right = node.left; node.left = null; } // Leaf Node if(rtail == null && ltail == null) return node; // if rightSubtree is not present then rtail = null have to return ltail return rtail != null? rtail: ltail; } public static void flatten(Node root) { flat(root); }
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": 452,
"s": 238,
"text": "Given a binary tree, flatten it into linked list in-place. Usage of auxiliary data structure is not allowed. After flattening, left of each node should point to NULL and right should contain next node in preorder."
},
{
"code": null,
"e": 463,
"s": 452,
"text": "Example 1:"
},
{
"code": null,
"e": 897,
"s": 463,
"text": "Input : \n 1\n / \\\n 2 5\n / \\ \\\n 3 4 6\nOutput :\n1 2 3 4 5 6 \nExplanation: \nAfter flattening, the tree looks \nlike this\n 1\n \\\n 2\n \\\n 3\n \\\n 4\n \\\n 5\n \\\n 6 \nHere, left of each node points \nto NULL and right contains the \nnext node in preorder.The inorder \ntraversal of this flattened tree \nis 1 2 3 4 5 6."
},
{
"code": null,
"e": 908,
"s": 897,
"text": "Example 2:"
},
{
"code": null,
"e": 1324,
"s": 908,
"text": "Input :\n 1\n / \\\n 3 4\n /\n 2\n \\\n 5 \nOutput : \n1 3 4 2 5 \nExplanation : \nAfter flattening, the tree looks \nlike this \n 1\n \\\n 3\n \\\n 4\n \\\n 2\n \\ \n 5 \nHere, left of each node points \nto NULL and right contains the \nnext node in preorder.The inorder \ntraversal of this flattened tree \nis 1 3 4 2 5."
},
{
"code": null,
"e": 1326,
"s": 1324,
"text": "0"
},
{
"code": null,
"e": 1351,
"s": 1326,
"text": "rohanmeher1642 weeks ago"
},
{
"code": null,
"e": 1368,
"s": 1351,
"text": "// java solution"
},
{
"code": null,
"e": 1756,
"s": 1370,
"text": "class Solution{ public static void flatten(Node root) { if(root==null) return; while(root!=null) { if(root.left!=null) { Node curr=root.left; while(curr.right!=null) curr=curr.right; curr.right=root.right; root.right=root.left; root.left=null; } root=root.right; } }}"
},
{
"code": null,
"e": 1758,
"s": 1756,
"text": "0"
},
{
"code": null,
"e": 1783,
"s": 1758,
"text": "vivekroxstar92 weeks ago"
},
{
"code": null,
"e": 2103,
"s": 1783,
"text": "JavaScript Solution\nclass Solution {\n constructor(){\n this.prev=null;\n }\n \tflatten(root){\n \t\t//code here\n \t\tif(root===null)return;\n this.flatten(root.right);\n this.flatten(root.left);\n root.right=this.prev;\n root.left=null;\n this.prev=root;\n return root;\n \t}\n}"
},
{
"code": null,
"e": 2105,
"s": 2103,
"text": "0"
},
{
"code": null,
"e": 2131,
"s": 2105,
"text": "adarshgupta4013 weeks ago"
},
{
"code": null,
"e": 2171,
"s": 2131,
"text": "Java-Most optimal and Easiest Approach-"
},
{
"code": null,
"e": 2516,
"s": 2171,
"text": "class Solution\n{\n public static void flatten(Node root)\n {\n Node cur = root;\n\t\twhile (cur != null)\n\t\t{\n\t\t\tif(cur.left != null)\n\t\t\t{\n\t\t\t\tNode pre = cur.left;\n\t\t\t\twhile(pre.right != null)\n\t\t\t\t{\n\t\t\t\t\tpre = pre.right;\n\t\t\t\t}\n\t\t\t\tpre.right = cur.right;\n\t\t\t\tcur.right = cur.left;\n\t\t\t\tcur.left = null;\n\t\t\t}\n\t\t\tcur = cur.right;\n\t\t}\n\n }\n}"
},
{
"code": null,
"e": 2518,
"s": 2516,
"text": "0"
},
{
"code": null,
"e": 2543,
"s": 2518,
"text": "singhashu19993 weeks ago"
},
{
"code": null,
"e": 3607,
"s": 2543,
"text": "class Solution{ public: void flatten(Node *root) { //code here map<int,queue<Node*>> mp; vector<int> p; Node* temp = root; stack<Node*> st; st.push(root); while(st.empty() == false) { temp = st.top(); st.pop(); if(temp != root) { mp[temp->key].push(temp); } p.push_back(temp->key); if(temp->right) { st.push(temp->right); } if(temp->left) { st.push(temp->left); } } //cout << p.size() << endl; int i=0; temp = root; while(i < p.size()) { if(i == p.size() - 1) { temp->left = NULL; temp->right = NULL; break; } //cout << p[i+1] << endl; temp->left = NULL; temp->right = mp[p[i+1]].front(); mp[p[i+1]].pop(); temp = temp->right; i += 1; } }};"
},
{
"code": null,
"e": 3609,
"s": 3607,
"text": "0"
},
{
"code": null,
"e": 3634,
"s": 3609,
"text": "amishasahu3283 weeks ago"
},
{
"code": null,
"e": 4165,
"s": 3634,
"text": "// Morris Traversal\n// TC-> O(n) | SC->O(1)\n void flatten(Node *root)\n {\n if(!root) return;\n Node *curr = root;\n while(curr)\n {\n if(curr->left != NULL)\n {\n Node *prev = curr->left;\n while(prev->right)\n prev = prev->right;\n \n prev->right = curr->right;\n curr->right = curr->left;\n }\n curr->left = NULL;\n curr = curr->right;\n \n }\n }"
},
{
"code": null,
"e": 4167,
"s": 4165,
"text": "0"
},
{
"code": null,
"e": 4195,
"s": 4167,
"text": "ayushtiwari264023 weeks ago"
},
{
"code": null,
"e": 4657,
"s": 4195,
"text": "class Solution{ public static void flatten(Node root) { if(root==null) return; if(root.left==null){ flatten(root.right); return; }else{ Node left = root.left; root.left=null; Node right = root.right; flatten(left); flatten(right); root.right = left; while(root.right!=null) root=root.right; root.right=right; return; } }}"
},
{
"code": null,
"e": 4659,
"s": 4657,
"text": "0"
},
{
"code": null,
"e": 4689,
"s": 4659,
"text": "dileeprajoriya20193 weeks ago"
},
{
"code": null,
"e": 4736,
"s": 4689,
"text": "Simple Solution Using Morris Traversal--→(c++)"
},
{
"code": null,
"e": 5236,
"s": 4738,
"text": "void flatten(Node *root) { Node *curr = root; while(curr) { if(curr->left) { Node *pred = curr->left; while(pred->right != NULL) { pred = pred->right; } pred->right = curr->right; curr->right = curr->left; curr->left = NULL; } curr = curr->right; } }"
},
{
"code": null,
"e": 5239,
"s": 5236,
"text": "+1"
},
{
"code": null,
"e": 5262,
"s": 5239,
"text": "akashmr10961 month ago"
},
{
"code": null,
"e": 5877,
"s": 5262,
"text": " public static void flatten(Node root)\n {\n flattenUtil(root);\n }\n \n private static Node flattenUtil(Node root) {\n if (root == null) {\n return null;\n }\n \n Node n1 = flattenUtil(root.left);\n Node rightHead = flattenUtil(root.right);\n Node leftHead = n1;\n root.left = null;\n \n Node tail = root;\n while(n1 != null) {\n tail = n1;\n n1 = n1.right;\n }\n \n if (tail != root) {\n root.right = leftHead;\n }\n tail.right = rightHead;\n return root;\n }"
},
{
"code": null,
"e": 5879,
"s": 5877,
"text": "0"
},
{
"code": null,
"e": 5906,
"s": 5879,
"text": "mukulmishra24101 month ago"
},
{
"code": null,
"e": 5933,
"s": 5906,
"text": "// USING MORRIS TRAVERSAL "
},
{
"code": null,
"e": 5964,
"s": 5935,
"text": "void flatten(Node *root) {"
},
{
"code": null,
"e": 6024,
"s": 5964,
"text": "// take a current on the root node Node* curr = root;"
},
{
"code": null,
"e": 6096,
"s": 6024,
"text": "// run the loop till the current is not NULL while(curr != NULL){"
},
{
"code": null,
"e": 6171,
"s": 6096,
"text": "// if current node does left exist if(curr -> left) {"
},
{
"code": null,
"e": 6344,
"s": 6171,
"text": "// find the predecessor of current node Node* pred = curr -> left; while(pred -> right){ pred = pred -> right; }"
},
{
"code": null,
"e": 6452,
"s": 6344,
"text": "// link the predecessor node with the current node's right pred -> right = curr -> right;"
},
{
"code": null,
"e": 6558,
"s": 6452,
"text": "//link the current node's right with current node's left curr -> right = curr -> left;"
},
{
"code": null,
"e": 6645,
"s": 6558,
"text": "// mark current node's left as NULL curr -> left = NULL; }"
},
{
"code": null,
"e": 6768,
"s": 6645,
"text": "// if current node's left does not exist, point it to the current node's right curr = curr -> right; } }"
},
{
"code": null,
"e": 6770,
"s": 6768,
"text": "0"
},
{
"code": null,
"e": 6797,
"s": 6770,
"text": "vasukapoor07992 months ago"
},
{
"code": null,
"e": 6811,
"s": 6797,
"text": "Java Solution"
},
{
"code": null,
"e": 7544,
"s": 6811,
"text": " public static Node flat(Node node){ if(node == null) return null; // Returning the tails Node ltail = flat(node.left); Node rtail = flat(node.right); // Here we are checking if we have leftSubtree because if ltail is null then // No node is present in leftSubtree if(ltail != null){ ltail.right = node.right; node.right = node.left; node.left = null; } // Leaf Node if(rtail == null && ltail == null) return node; // if rightSubtree is not present then rtail = null have to return ltail return rtail != null? rtail: ltail; } public static void flatten(Node root) { flat(root); }"
},
{
"code": null,
"e": 7690,
"s": 7544,
"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": 7726,
"s": 7690,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 7736,
"s": 7726,
"text": "\nProblem\n"
},
{
"code": null,
"e": 7746,
"s": 7736,
"text": "\nContest\n"
},
{
"code": null,
"e": 7809,
"s": 7746,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 7957,
"s": 7809,
"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": 8165,
"s": 7957,
"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": 8271,
"s": 8165,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
DateTime.ToUniversalTime() Method in C#
|
The DateTime.ToUniversalTime() method in C# is used to convert the value of the current DateTime object to Coordinated Universal Time (UTC).
Following is the syntax −
public DateTime ToUniversalTime ();
Let us now see an example to implement the DateTime.ToUniversalTime() method −
using System;
public class Demo {
public static void Main() {
DateTime d = new DateTime(2019, 12, 11, 7, 11, 25);
Console.WriteLine("Date = {0}", d);
DateTime res = d.ToUniversalTime();
Console.WriteLine("String representation = {0}", res);
}
}
This will produce the following output −
Date = 11/11/2019 7:11:25 AM
String representation = 11/11/2019 7:11:25 AM
Let us now see another example to implement the DateTime.ToUniversalTime() method −
using System;
public class Demo {
public static void Main() {
DateTime localDate, universalDate;
String str = "11/11/2019 4:10:55";
localDate = DateTime.Parse(str);
universalDate = localDate.ToUniversalTime();
Console.WriteLine("Local time = {0} ", localDate);
Console.WriteLine("Universal time = {0} ", universalDate);
}
}
This will produce the following output −
Local time = 11/11/2019 4:10:55 AM
Universal time = 11/11/2019 4:10:55 AM
|
[
{
"code": null,
"e": 1203,
"s": 1062,
"text": "The DateTime.ToUniversalTime() method in C# is used to convert the value of the current DateTime object to Coordinated Universal Time (UTC)."
},
{
"code": null,
"e": 1229,
"s": 1203,
"text": "Following is the syntax −"
},
{
"code": null,
"e": 1265,
"s": 1229,
"text": "public DateTime ToUniversalTime ();"
},
{
"code": null,
"e": 1344,
"s": 1265,
"text": "Let us now see an example to implement the DateTime.ToUniversalTime() method −"
},
{
"code": null,
"e": 1619,
"s": 1344,
"text": "using System;\npublic class Demo {\n public static void Main() {\n DateTime d = new DateTime(2019, 12, 11, 7, 11, 25);\n Console.WriteLine(\"Date = {0}\", d);\n DateTime res = d.ToUniversalTime();\n Console.WriteLine(\"String representation = {0}\", res);\n }\n}"
},
{
"code": null,
"e": 1660,
"s": 1619,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1735,
"s": 1660,
"text": "Date = 11/11/2019 7:11:25 AM\nString representation = 11/11/2019 7:11:25 AM"
},
{
"code": null,
"e": 1819,
"s": 1735,
"text": "Let us now see another example to implement the DateTime.ToUniversalTime() method −"
},
{
"code": null,
"e": 2185,
"s": 1819,
"text": "using System;\npublic class Demo {\n public static void Main() {\n DateTime localDate, universalDate;\n String str = \"11/11/2019 4:10:55\";\n localDate = DateTime.Parse(str);\n universalDate = localDate.ToUniversalTime();\n Console.WriteLine(\"Local time = {0} \", localDate);\n Console.WriteLine(\"Universal time = {0} \", universalDate);\n }\n}"
},
{
"code": null,
"e": 2226,
"s": 2185,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2300,
"s": 2226,
"text": "Local time = 11/11/2019 4:10:55 AM\nUniversal time = 11/11/2019 4:10:55 AM"
}
] |
Find Occurrence of Number More Than N/2 Times in a Sorted Array in Java - GeeksforGeeks
|
27 Jun, 2021
Given a Sorted Array of n integers, and an Integer X, the task is to find whether the given Integer X appears more than n/2 times in the array or not.
Input: arr[] = {1,1,2,3,3,3,3,3,3,3,3,3,4,5,6,6,7}, x=3
Output: 3 occurs 9 times which is more than 8 times
Input: arr[] = {1,1,2,3,3,3,3,3,3,3,3,3,4,5,6,6,7}, x=6
Output: 6 doesn't occur more than 8 times
Approach #1:
Maintain a count variable, initialize it with 0.
Iterate over the array and compare each element with x, if it is equal to x, then increment the count.
After iterating over the whole array check whether the value of the count variable is greater than n/2(half of the length of the array) or not.
If the value of the count variable is greater than n/2, print “true” else false.
Below is the implementation of the above approach:
Java
// Java Program to check whether element// x occurs more then n/2 times or not class GFG { static boolean isOccurMoreThenHalfTimes(int arr[], int x) { int len = arr.length; // initialize the count by 0 int count = 0; for (int i = 0; i < len; i++) { // if x is equal to arr[i],increment the count if (arr[i] == x) count++; } // checking the value of count variable if (count > len / 2) return true; else return false; } public static void main(String[] args) { // driver code int arr[] = { 1, 1, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 5, 6, 6, 7 }; int x = 3; // calling the function and storing // the returned result boolean answer = isOccurMoreThenHalfTimes(arr, x); if (answer) { System.out.println("true"); } else { System.out.println("false"); } }}
true
Time Complexity- 0(N)
Space Complexity: 0(1)
Approach #2:
Use a lower bound function for finding a lower bound index in a sorted array.Use an upper bound function for finding an upper bound index in a sorted array.Find the difference between the upper and lower bound index.If the difference is greater than N/2 then print occurs more than N/2.Else print doesn’t occur more than N/2 times.
Use a lower bound function for finding a lower bound index in a sorted array.
Use an upper bound function for finding an upper bound index in a sorted array.
Find the difference between the upper and lower bound index.
If the difference is greater than N/2 then print occurs more than N/2.
Else print doesn’t occur more than N/2 times.
Below is the implementation of the above approach:
Java
class Main { public static int lower_bound(int arr[], int low, int high, int X) { // Base Case if (low > high) { return low; } // Find the middle index int mid = low + (high - low) / 2; // If arr[mid] is greater than // or equal to X then search // in left subarray if (arr[mid] >= X) { return lower_bound(arr, low, mid - 1, X); } // If arr[mid] is less than X // then search in right subarray return lower_bound(arr, mid + 1, high, X); } // Recursive implementation of // upper_bound public static int upper_bound(int arr[], int low, int high, int X) { // Base Case if (low > high) return low; // Find the middle index int mid = low + (high - low) / 2; // If arr[mid] is less than // or equal to X search in // right subarray if (arr[mid] <= X) { return upper_bound(arr, mid + 1, high, X); } // If arr[mid] is greater than X // then search in left subarray return upper_bound(arr, low, mid - 1, X); } // Function to implement lower_bound // and upper_bound of X public static int printBound(int arr[], int N, int X) { int lower, upper; // If lower_bound doesn't exists if (arr[0] == X) { lower = 0; } else { // Find lower_bound lower = lower_bound(arr, 0, N, X); } // If upper_bound doesn't exists if (arr[N - 1] == X) { upper = N - 1; } else { // Find upper_bound upper = upper_bound(arr, 0, N, X); } return upper - lower; } public static void main(String[] args) { int X = 3; int arr[] = { 1, 1, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 5, 6, 6, 7 }; int occurrence = printBound(arr, arr.length, X); if (occurrence >= arr.length / 2) { System.out.println( X + " occurs " + occurrence + " times which is more than " + arr.length / 2 + " times"); } else { System.out.println(X + " doesn't occur more than " + arr.length / 2 + " times"); } }}
3 occurs 9 times which is more than 8 times
Time Complexity: O(log n)
sumitgumber28
gabaa406
Java-Array-Programs
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Functional Interfaces in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
|
[
{
"code": null,
"e": 23948,
"s": 23920,
"text": "\n27 Jun, 2021"
},
{
"code": null,
"e": 24099,
"s": 23948,
"text": "Given a Sorted Array of n integers, and an Integer X, the task is to find whether the given Integer X appears more than n/2 times in the array or not."
},
{
"code": null,
"e": 24306,
"s": 24099,
"text": "Input: arr[] = {1,1,2,3,3,3,3,3,3,3,3,3,4,5,6,6,7}, x=3\nOutput: 3 occurs 9 times which is more than 8 times\n\nInput: arr[] = {1,1,2,3,3,3,3,3,3,3,3,3,4,5,6,6,7}, x=6\nOutput: 6 doesn't occur more than 8 times"
},
{
"code": null,
"e": 24319,
"s": 24306,
"text": "Approach #1:"
},
{
"code": null,
"e": 24368,
"s": 24319,
"text": "Maintain a count variable, initialize it with 0."
},
{
"code": null,
"e": 24471,
"s": 24368,
"text": "Iterate over the array and compare each element with x, if it is equal to x, then increment the count."
},
{
"code": null,
"e": 24615,
"s": 24471,
"text": "After iterating over the whole array check whether the value of the count variable is greater than n/2(half of the length of the array) or not."
},
{
"code": null,
"e": 24696,
"s": 24615,
"text": "If the value of the count variable is greater than n/2, print “true” else false."
},
{
"code": null,
"e": 24747,
"s": 24696,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 24752,
"s": 24747,
"text": "Java"
},
{
"code": "// Java Program to check whether element// x occurs more then n/2 times or not class GFG { static boolean isOccurMoreThenHalfTimes(int arr[], int x) { int len = arr.length; // initialize the count by 0 int count = 0; for (int i = 0; i < len; i++) { // if x is equal to arr[i],increment the count if (arr[i] == x) count++; } // checking the value of count variable if (count > len / 2) return true; else return false; } public static void main(String[] args) { // driver code int arr[] = { 1, 1, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 5, 6, 6, 7 }; int x = 3; // calling the function and storing // the returned result boolean answer = isOccurMoreThenHalfTimes(arr, x); if (answer) { System.out.println(\"true\"); } else { System.out.println(\"false\"); } }}",
"e": 25790,
"s": 24752,
"text": null
},
{
"code": null,
"e": 25798,
"s": 25793,
"text": "true"
},
{
"code": null,
"e": 25822,
"s": 25800,
"text": "Time Complexity- 0(N)"
},
{
"code": null,
"e": 25845,
"s": 25822,
"text": "Space Complexity: 0(1)"
},
{
"code": null,
"e": 25860,
"s": 25847,
"text": "Approach #2:"
},
{
"code": null,
"e": 26194,
"s": 25862,
"text": "Use a lower bound function for finding a lower bound index in a sorted array.Use an upper bound function for finding an upper bound index in a sorted array.Find the difference between the upper and lower bound index.If the difference is greater than N/2 then print occurs more than N/2.Else print doesn’t occur more than N/2 times."
},
{
"code": null,
"e": 26272,
"s": 26194,
"text": "Use a lower bound function for finding a lower bound index in a sorted array."
},
{
"code": null,
"e": 26352,
"s": 26272,
"text": "Use an upper bound function for finding an upper bound index in a sorted array."
},
{
"code": null,
"e": 26413,
"s": 26352,
"text": "Find the difference between the upper and lower bound index."
},
{
"code": null,
"e": 26484,
"s": 26413,
"text": "If the difference is greater than N/2 then print occurs more than N/2."
},
{
"code": null,
"e": 26530,
"s": 26484,
"text": "Else print doesn’t occur more than N/2 times."
},
{
"code": null,
"e": 26583,
"s": 26532,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26590,
"s": 26585,
"text": "Java"
},
{
"code": "class Main { public static int lower_bound(int arr[], int low, int high, int X) { // Base Case if (low > high) { return low; } // Find the middle index int mid = low + (high - low) / 2; // If arr[mid] is greater than // or equal to X then search // in left subarray if (arr[mid] >= X) { return lower_bound(arr, low, mid - 1, X); } // If arr[mid] is less than X // then search in right subarray return lower_bound(arr, mid + 1, high, X); } // Recursive implementation of // upper_bound public static int upper_bound(int arr[], int low, int high, int X) { // Base Case if (low > high) return low; // Find the middle index int mid = low + (high - low) / 2; // If arr[mid] is less than // or equal to X search in // right subarray if (arr[mid] <= X) { return upper_bound(arr, mid + 1, high, X); } // If arr[mid] is greater than X // then search in left subarray return upper_bound(arr, low, mid - 1, X); } // Function to implement lower_bound // and upper_bound of X public static int printBound(int arr[], int N, int X) { int lower, upper; // If lower_bound doesn't exists if (arr[0] == X) { lower = 0; } else { // Find lower_bound lower = lower_bound(arr, 0, N, X); } // If upper_bound doesn't exists if (arr[N - 1] == X) { upper = N - 1; } else { // Find upper_bound upper = upper_bound(arr, 0, N, X); } return upper - lower; } public static void main(String[] args) { int X = 3; int arr[] = { 1, 1, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 5, 6, 6, 7 }; int occurrence = printBound(arr, arr.length, X); if (occurrence >= arr.length / 2) { System.out.println( X + \" occurs \" + occurrence + \" times which is more than \" + arr.length / 2 + \" times\"); } else { System.out.println(X + \" doesn't occur more than \" + arr.length / 2 + \" times\"); } }}",
"e": 29019,
"s": 26590,
"text": null
},
{
"code": null,
"e": 29066,
"s": 29022,
"text": "3 occurs 9 times which is more than 8 times"
},
{
"code": null,
"e": 29094,
"s": 29068,
"text": "Time Complexity: O(log n)"
},
{
"code": null,
"e": 29110,
"s": 29096,
"text": "sumitgumber28"
},
{
"code": null,
"e": 29119,
"s": 29110,
"text": "gabaa406"
},
{
"code": null,
"e": 29139,
"s": 29119,
"text": "Java-Array-Programs"
},
{
"code": null,
"e": 29146,
"s": 29139,
"text": "Picked"
},
{
"code": null,
"e": 29170,
"s": 29146,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 29175,
"s": 29170,
"text": "Java"
},
{
"code": null,
"e": 29189,
"s": 29175,
"text": "Java Programs"
},
{
"code": null,
"e": 29208,
"s": 29189,
"text": "Technical Scripter"
},
{
"code": null,
"e": 29213,
"s": 29208,
"text": "Java"
},
{
"code": null,
"e": 29311,
"s": 29213,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29326,
"s": 29311,
"text": "Stream In Java"
},
{
"code": null,
"e": 29347,
"s": 29326,
"text": "Constructors in Java"
},
{
"code": null,
"e": 29393,
"s": 29347,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 29412,
"s": 29393,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 29442,
"s": 29412,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 29486,
"s": 29442,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 29512,
"s": 29486,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 29546,
"s": 29512,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 29593,
"s": 29546,
"text": "Implementing a Linked List in Java using Class"
}
] |
NumPy — The King of Scientific Computing with Python | by Shubhanshu Singh | Towards Data Science
|
Python is one of my favourite programming languages ( I love cpp too ). It is super easy to learn because of its beginner-friendly syntax. What makes it stand apart from the other programming language is its awesome developers' community. It comes pre-loaded with so many tools & libraries. And it is one of the most preferred languages in the field of Data Science & Machine Learning.
In this article, I’m going to tell you about one such powerful library in Python known as NumPy.
Enjoy the ride !!
What is NumPy?NumPy vs ListInstallationLet’s get started with NumPy ArraysLet’s check out some built-in methods of NumPya) arangeb) Zeros and Onesc) linspaced) eyee) RandomArray Attributes and Methodsa) Reshapeb) max, min, argmax, argminc) Shaped) dtypeNumPy Indexing and SelectionBroadcastingIndexing a 2D array (matrices)SelectionNumPy Operationsa) Arithematicb) Universal Array FunctionsVectorizationConclusionGithub RepositoryReferencesSuggested Reading
What is NumPy?
NumPy vs List
Installation
Let’s get started with NumPy Arrays
Let’s check out some built-in methods of NumPya) arangeb) Zeros and Onesc) linspaced) eyee) Random
Array Attributes and Methodsa) Reshapeb) max, min, argmax, argminc) Shaped) dtype
NumPy Indexing and Selection
Broadcasting
Indexing a 2D array (matrices)
Selection
NumPy Operationsa) Arithematicb) Universal Array Functions
Vectorization
Conclusion
Github Repository
References
Suggested Reading
NumPy is a Linear Algebra Library for python.
It is the core library for scientific computation in python.It is super fast as it has bindings to C libraries.It provides a high-performance multidimensional array object and tools for working with these arrays.
It is the core library for scientific computation in python.
It is super fast as it has bindings to C libraries.
It provides a high-performance multidimensional array object and tools for working with these arrays.
Who is the winner?
Let’s see the difference
NumPy has a fixed type of nature. NumPy is used for creating homogeneous n-dimensional arrays. Lists can be heterogeneous in nature.
We don’t need to type check while iterating through NumPy arrays. On the other hand, Lists object can be of type int, boolean, string etc.
This code will give an error if we mention the dtype explicitly:
#heterogenous 1D array #gives an error in numpynp_arr = np.array([1,2,"a",3,"b"], dtype=np.int32)
This a valid code for python Lists:
#heterogenous 1D arrayarr = [1,2,"a",3,"b"]
Mathematical operations can’t be performed on heterogeneous data. That’s why it is recommended to have homogenous NumPy arrays
Let’s take one more example:
This code will give an error in python Lists:
x = [1,2,3]y = [4,5,6]#this will give an error,#not possible in Listsx*y
But this a valid code for NumPy:
x = np.array([1,2,3])y = np.array([4,5,6])x*y#Outputnp.array([4,10,18])
We’ll learn more about some awesome features in NumPy in the upcoming sections.
Suppose we have a matrix:
[[1,2,3], [4,5,6], [7,8,9]]
We’ll analyse for a number 7 in the matrix.
Computers read the information in binary.
By default Numpy stores 7 in total memory space of 4 bytes.
On the other hand in Lists, there is a lot of information that needs to be stored for integer 7.
Lists use a built-in int type for python.
The built-in int type consists of four different things:
Depicts the size of that particular integer value.
It tells how many times that particular integer (here 7) has been pointed at.
Every variable in Python is just a reference (a pointer) to an object. It is not the actual value itself.
So for keeping track of references, every object (even integer) has an extra field called reference count that is increased or decreased when a pointer to the object is created or deleted.
It tells whether the object is int, boolean, string etc.
It has its own binary representation
up to 64 bits........00000000 00000111 (8 bytes)
Like this we also have binary representation for size, reference count, object type.
So basically it’s faster to read less bytes of memory.
We can clearly see Numpy takes less memory than Lists for a single integer storage !!
Have look at this illustration
The data on our list will be scattered in the computer’s memory. It doesn't have contiguous blocks of memory. The list will contain just a pointer to those 8 blocks of memory.
On the other hand, NumPy array will have contiguous blocks of memory in the computer. All 8 blocks are right next to each other.
So the takeaway from above analysis is that Lists are very slow and NumPy is superfast !!
NumPy has the speed like cheetah ;)
I’ll recommend you to install Python using the Anaconda distribution to make sure all underlying dependencies (such as Linear Algebra libraries) sync up with the use of conda install.
Refer this link to know more about anaconda installation:
Installation — Anaconda Documentation
If you have Anaconda, install NumPy by going to your terminal or command prompt and start typing:
conda install numpy
If you don’t have Anaconda distribution, you can also use:
pip install numpy
We’ll talk about vectors & matrices.
Vectors are strictly 1-D arrays and Matrices are 2-D arrays
Note: Matrix can still have only one row or one column
First import Numpy
import numpy as np
Let’s create NumPy Arrays using python Lists
Code 1:
#definejust_a_list = [1,2,3]#showjust_a_list
Output:
[1, 2, 3]
Now we will convert the above code 1 snippet variable just_a_list to NumPy array.
Code 2:
np.array(just_a_list)
Output:
array([1, 2, 3])
Code 3:
#definejust_a_matrix = [[1,2,3],[4,5,6],[7,8,9]]#showjust_a_matrix
Output:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Now we will convert the above code 3 snippet variable just_a_matrix to NumPy 2d array
Code 4:
np.array(just_a_matrix)
Output:
array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
It returns evenly spaced values within a given interval.
This is very similar to Python’s own built-in range function.
The upper limit gets excluded in output.
Code 1:
np.arange(0,20)
Output:
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19])
Code 2:
#step size of 2np.arange(0,10,2)
Output:
array([0, 2, 4, 6, 8])
In the above code snippet, 2 is the step size. As you can see in the output, the series is incrementing by the difference of 2.
Code 1:
np.zeros(4)
Output:
array([0., 0., 0., 0.])
So basically np.zeros(4) returns a new array filled with 4 zeros.
Code 2:
np.zeros((3,3))
Output:
array([[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]])
np.zeros((3,3)) returns a matrix of shape (3,3) filled with zeros. Shape (3,3) refers to 3 rows & 3 columns.
Code 3:
np.ones(4)
Output:
array([1., 1., 1., 1.])
In the above code snippet, np.ones(4) returns a new array filled with 4 ones.
Code 4:
np.ones((3,3))
Output:
array([[ 1., 1., 1.], [ 1., 1., 1.], [ 1., 1., 1.]])
Return evenly spaced numbers over a specified interval.
Code 1:
#generates three numbers#between range 0 to 10np.linspace(0,10,3)
Output:
array([0., 5., 10.])
Code 2:
np.linspace(0,10,20)
Output:
array([ 0., 0.52631579, 1.05263158, 1.57894737, 2.10526316, 2.63157895, 3.15789474, 3.68421053, 4.21052632, 4.73684211, 5.26315789, 5.78947368, 6.31578947, 6.84210526, 7.36842105, 7.89473684, 8.42105263, 8.94736842, 9.47368421, 10. ])
Creates an identity matrix.
Code :
np.eye(3)
Output:
array([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]])
Numpy also has a lot of ways to create random number arrays
Creates an array of the given shape and populate it with random samples from a uniform distribution over [0, 1).
Code 1:
np.random.rand(2)
Output:
array([0.01231767, 0.24372946])
Code 2:
np.random.rand(3,3)
Output:
array([[0.75250092, 0.7582111 , 0.16155648], [0.11020177, 0.51819124, 0.29267394], [0.70052998, 0.58651773, 0.80589757]])
Return a sample (or samples) from the Standard Normal or Gaussian distribution. Unlike np.random.rand which returns a uniform distribution.
Code 1:
np.random.randn(2)
Output:
array([ 1.5868519 , -2.72817085])
Code 2:
np.random.randn(4,4)
Output:
array([[ 0.24602617, -2.39464955, -0.1382286 , 1.47872422], [ 0.70466341, -0.17408009, -2.22898345, 0.28018941], [ 0.57969196, 0.00664889, 1.20221044, 0.47452959], [ 0.93939176, -0.07719476, -0.08907384, 1.26465443]])
Return random integers from low (inclusive) to high (exclusive).
Code 1:
np.random.randint(1,100)
Output:
84
Code 2:
#generates 10 random #integers between 1 to 100np.random.randint(1,100,10)
Output:
array([85, 30, 2, 72, 40, 86, 18, 46, 3, 24])
One of the most useful methods you can use on an array is the reshape method.
It returns an array containing the same data with a new shape.
Code 1:
#definearr = np.arange(16)#showarr
Output:
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])
Now let’s reshape the above code 1 snippet variable arr
Code 2:
arr.reshape(4,4)
Output:
array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]])
These are useful methods for finding maximum or minimum values. We can also find their index locations using argmin or argmax !!
Let’s generate a random NumPy array of 10 integers
Code 1:
#definerandom_arr = np.random.randint(0,50,10)#showrandom_arr
Output:
array([16, 8, 40, 7, 15, 39, 0, 15, 20, 35])
Code 2:
random_arr.max()
Output:
40
Code 3:
random_arr.argmax()
Output:
2
Code 4:
random_arr.min()
Output:
0
Code 5:
random_arr.argmin()
Output:
6
Shape is an attribute that arrays have (not a method)
We have already defined the variable arr under the code 1 snippet of the Reshape Section.
Code 1:
arr.shape
Output:
(16,)
The above shape indicates that arr is just a one-dimensional vector of rank 1.
Code 2:
arr.reshape(1,16)
Output:
array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]])
Notice the two sets of brackets in the output. It indicates the 2-dimensional NumPy array.
Code 3:
arr.reshape(1,16).shape
Output:
(1, 16)
The reshaped arr contains 1 row & 16 columns.
Code 4:
arr.reshape(16,1)
Output:
array([[ 0], [ 1], [ 2], [ 3], [ 4], [ 5], [ 6], [ 7], [ 8], [ 9], [10], [11], [12], [13], [14], [15]])
Code 5:
arr.reshape(16,1).shape
Output:
(16, 1)
The reshaped arr contains 16 rows & 1 column.
Using dtype we can get the data type of the object in the array.
Code 1:
arr.dtype
Output:
dtype(‘int64’)
Now we will learn how to select elements or group of elements from an array. The simplest way of picking up one or more elements from an array looks very similar to python lists
We have already defined the variable arr under the code 1 snippet of the Reshape Section.
Code 1:
#Get a value #at an indexarr[5]
Output:
5
Code 2:
#Get values #in a rangearr[1:5]
Output:
array([1, 2, 3, 4])
The term broadcasting describes how Numpy treats array with different shapes during arithmetic operations.
Numpy arrays differ from a normal Python list because of their ability to broadcast.
Code 1:
#Setting a value with#index rangearr[0:5]=100#Showarr
Output:
array([100, 100, 100, 100, 100, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])
Code 2:
#Reset array, we'll #see the reason behind it soonarr = np.arange(0,11)#Showarr
Output:
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
Code 3:
slice_of_arr = arr[0:6]#Show sliceslice_of_arr
Output:
array([0, 1, 2, 3, 4, 5])
Code 4:
#Change Sliceslice_of_arr[:]=99#Show Slice againslice_of_arr
Output:
array([99, 99, 99, 99, 99, 99])
Code 5:
arr
Output:
array([99, 99, 99, 99, 99, 99, 6, 7, 8, 9, 10])
As you can see in the above output, the changes also occured in our original array !!
This happened because slice_of_arr is just a reference to the first five elements of arr . Assignment operation doesn’t make a separate copy of the data.
To Copy the data, we need to use the copy method !!
Code 6:
arr_copy = arr.copy()arr_copy
Output:
array([99, 99, 99, 99, 99, 99, 6, 7, 8, 9, 10])
Let’s see another example of broadcasting
Code 7:
a = [[1,2,3],[4,5,6]]#Converting to #numpy 2d arraynp_a = np.array(a)#shownp_a
Output:
array([[1, 2, 3], [4, 5, 6]])
Code 8:
#2 rows, 3 columnsnp_a.shape
Output:
(2, 3)
Code 9:
b = [100,200,300]#converting to #numpy arraynp_b = np.array(b)#shownp_b
Output:
array([100, 200, 300])
Code 10:
np_b.shape
Output:
(3,)
Code 11:
np_b_reshaped = np_b.reshape(1,3)#shownp_b_reshaped
Output:
array([[100, 200, 300]])
Code 12:
#1 row, 3 columnsnp_b_reshaped.shape
Output:
(1, 3)
See the magic of broadcasting
Code 13:
np_a + np_b_reshaped
Output:
array([[101, 202, 303], [104, 205, 306]])
So basically np_b_reshaped replicates itself for the second row & it’s shape becomes (2,3)
Code 14:
np.array([[100,200,300],[100,200,300]])
Output:
array([[100, 200, 300], [100, 200, 300]])
The general format is arr_2d[row][col] or arr_2d[row,col].
Code 1 :
arr_2d = np.array(([1,2,3],[4,5,6],[7,8,9]))#Showarr_2d
Output:
array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
Code 2:
#Indexing rowarr_2d[1]
Output:
array([4, 5, 6])
Code 3:
#Getting individual element valuearr_2d[1][0]
Output:
4
Code 4:
#another wayarr_2d[1,0]
Output:
4
Code 5:
#2D array slicing#Shape (2,2) from#top right cornerarr_2d[:2,1:]
Output:
array([[2, 3], [5, 6]])
Code 6:
#Shape of the #bottom rowarr_2d[2]
Output:
array([7, 8, 9])
Let’s briefly go over how to use brackets for selection based on comparison operators.
Code 1:
arr1 = np.arange(1,11)#showarr1
Output:
array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
Code 2:
arr1 > 5
Output:
array([False, False, False, False, False, True, True, True, True, True])
Code 3:
bool_arr = arr1 > 5#showbool_arr
Output:
array([False, False, False, False, False, True, True, True, True, True])
Code 4:
arr1[bool_arr]
Output:
array([ 6, 7, 8, 9, 10])
Code 5:
arr1[arr1 > 2]
Output:
array([ 3, 4, 5, 6, 7, 8, 9, 10])
You can easily perform array with array arithmetic, or scalar with array arithmetic. Let’s see some examples.
Code 1:
arr2 = np.arange(0,10)
Code 2:
arr2 + arr2
Output:
array([ 0, 2, 4, 6, 8, 10, 12, 14, 16, 18])
Code 3:
arr2 * arr2
Output:
array([ 0, 1, 4, 9, 16, 25, 36, 49, 64, 81])
Code 4:
arr2 - arr2
Output:
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
Warning on division by zero, but not an error!
Numpy will replace it with nan
Code 5:
arr2 / arr2
Output:
/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:3: RuntimeWarning: invalid value encountered in true_divide This is separate from the ipykernel package so we can avoid doing imports untilarray([nan, 1., 1., 1., 1., 1., 1., 1., 1., 1.])
Another warning, but not an error. Value will be replaced with infinity.
Code 6:
1 / arr2
Output:
/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:2: RuntimeWarning: divide by zero encountered in true_dividearray([inf, 1., 0.5, 0.33333333, 0.25, 0.2, 0.16666667, 0.14285714, 0.125, 0.11111111])
Cube of numbers
Code 7:
arr2 ** 3
Output:
array([0, 1, 8, 27, 64, 125, 216, 343, 512, 729])
Numpy comes preloaded with many universal array functions, which are essentially just mathematical operations you can use to perform the operation across the array. Let’s see some common ones.
Taking Square Roots
Code 1:
np.sqrt(arr2)
Output:
array([0. , 1., 1.41421356, 1.73205081, 2., 2.23606798, 2.44948974, 2.64575131, 2.82842712, 3.])
Calcualting exponential (e^x)
Code 2:
np.exp(arr2)
Output:
array([1.00000000e+00, 2.71828183e+00, 7.38905610e+00, 2.00855369e+01, 5.45981500e+01, 1.48413159e+02, 4.03428793e+02, 1.09663316e+03, 2.98095799e+03, 8.10308393e+03])
same as arr.max()
Code 3:
np.max(arr2)
Output:
9
Calculating sine value
Code 4:
np.sin(arr2)
Output:
array([ 0., 0.84147098, 0.90929743, 0.14112001, -0.7568025 , -0.95892427, -0.2794155 , 0.6569866 , 0.98935825, 0.41211849])
Calculating log
Code 5:
np.log(arr2)
Output:
usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:1: RuntimeWarning: divide by zero encountered in log """Entry point for launching an IPython kernel.array([ -inf, 0., 0.69314718, 1.09861229, 1.38629436, 1.60943791, 1.79175947, 1.94591015, 2.07944154, 2.19722458])
Vectorization is used to speed up the Python code without using a loop.
Various operations on vectors & matrices can be performed like the dot product, element-wise product etc.
Vectorized version of dot product
Code:
import timea = np.random.rand(1000000)b = np.random.rand(1000000)tic= time.time()c = np.dot(a,b) #dot product of two vectorstoc = time.time()print("Time taken in vectorized version: "+str(1000 * (toc - tic))+" ms")
Output:
Time taken in vectorized version: 1.483917236328125 ms
let’s check the for loop version of dot product
Code:
c = 0tic = time.time()for i in range(1000000): c += a[i] * b[i]toc = time.time()print("Time taken in for loop version: "+str(1000 *(toc - tic)) + " ms")
Output:
Time taken in for loop version: 579.4703960418701 ms
So basically the takeaway from the above analysis is that Vectorization is way more powerful and efficient than simple for loop. It takes very less time. So whenever possible avoid explicit for loops.
I have tried my best to give you a comprehensive introduction to NumPy.
Linear Algebra becomes a cakewalk with this package.
NumPy is a fundamental package for scientific computation & mathematical operations in python.
NumPy is way more powerful than Lists.
Go ahead and check out my GitHub repository for full code access.
Here is a link to my Medium Articles GitHub repository:
github.com
Here is a direct link to my NumPy Jupyter Notebook containing all the codes snippets used in this article :-
github.com
numpy.org
If you are interested in learning CS Fundamentals. If you are curious about learning Data Structures & Algorithms, then do check out my first blog on Heap Sort Algorithm.
medium.com
Thank you for reading this article.
Leave a comment below if you have any questions.
|
[
{
"code": null,
"e": 557,
"s": 171,
"text": "Python is one of my favourite programming languages ( I love cpp too ). It is super easy to learn because of its beginner-friendly syntax. What makes it stand apart from the other programming language is its awesome developers' community. It comes pre-loaded with so many tools & libraries. And it is one of the most preferred languages in the field of Data Science & Machine Learning."
},
{
"code": null,
"e": 654,
"s": 557,
"text": "In this article, I’m going to tell you about one such powerful library in Python known as NumPy."
},
{
"code": null,
"e": 672,
"s": 654,
"text": "Enjoy the ride !!"
},
{
"code": null,
"e": 1130,
"s": 672,
"text": "What is NumPy?NumPy vs ListInstallationLet’s get started with NumPy ArraysLet’s check out some built-in methods of NumPya) arangeb) Zeros and Onesc) linspaced) eyee) RandomArray Attributes and Methodsa) Reshapeb) max, min, argmax, argminc) Shaped) dtypeNumPy Indexing and SelectionBroadcastingIndexing a 2D array (matrices)SelectionNumPy Operationsa) Arithematicb) Universal Array FunctionsVectorizationConclusionGithub RepositoryReferencesSuggested Reading"
},
{
"code": null,
"e": 1145,
"s": 1130,
"text": "What is NumPy?"
},
{
"code": null,
"e": 1159,
"s": 1145,
"text": "NumPy vs List"
},
{
"code": null,
"e": 1172,
"s": 1159,
"text": "Installation"
},
{
"code": null,
"e": 1208,
"s": 1172,
"text": "Let’s get started with NumPy Arrays"
},
{
"code": null,
"e": 1307,
"s": 1208,
"text": "Let’s check out some built-in methods of NumPya) arangeb) Zeros and Onesc) linspaced) eyee) Random"
},
{
"code": null,
"e": 1389,
"s": 1307,
"text": "Array Attributes and Methodsa) Reshapeb) max, min, argmax, argminc) Shaped) dtype"
},
{
"code": null,
"e": 1418,
"s": 1389,
"text": "NumPy Indexing and Selection"
},
{
"code": null,
"e": 1431,
"s": 1418,
"text": "Broadcasting"
},
{
"code": null,
"e": 1462,
"s": 1431,
"text": "Indexing a 2D array (matrices)"
},
{
"code": null,
"e": 1472,
"s": 1462,
"text": "Selection"
},
{
"code": null,
"e": 1531,
"s": 1472,
"text": "NumPy Operationsa) Arithematicb) Universal Array Functions"
},
{
"code": null,
"e": 1545,
"s": 1531,
"text": "Vectorization"
},
{
"code": null,
"e": 1556,
"s": 1545,
"text": "Conclusion"
},
{
"code": null,
"e": 1574,
"s": 1556,
"text": "Github Repository"
},
{
"code": null,
"e": 1585,
"s": 1574,
"text": "References"
},
{
"code": null,
"e": 1603,
"s": 1585,
"text": "Suggested Reading"
},
{
"code": null,
"e": 1649,
"s": 1603,
"text": "NumPy is a Linear Algebra Library for python."
},
{
"code": null,
"e": 1862,
"s": 1649,
"text": "It is the core library for scientific computation in python.It is super fast as it has bindings to C libraries.It provides a high-performance multidimensional array object and tools for working with these arrays."
},
{
"code": null,
"e": 1923,
"s": 1862,
"text": "It is the core library for scientific computation in python."
},
{
"code": null,
"e": 1975,
"s": 1923,
"text": "It is super fast as it has bindings to C libraries."
},
{
"code": null,
"e": 2077,
"s": 1975,
"text": "It provides a high-performance multidimensional array object and tools for working with these arrays."
},
{
"code": null,
"e": 2096,
"s": 2077,
"text": "Who is the winner?"
},
{
"code": null,
"e": 2121,
"s": 2096,
"text": "Let’s see the difference"
},
{
"code": null,
"e": 2254,
"s": 2121,
"text": "NumPy has a fixed type of nature. NumPy is used for creating homogeneous n-dimensional arrays. Lists can be heterogeneous in nature."
},
{
"code": null,
"e": 2393,
"s": 2254,
"text": "We don’t need to type check while iterating through NumPy arrays. On the other hand, Lists object can be of type int, boolean, string etc."
},
{
"code": null,
"e": 2458,
"s": 2393,
"text": "This code will give an error if we mention the dtype explicitly:"
},
{
"code": null,
"e": 2556,
"s": 2458,
"text": "#heterogenous 1D array #gives an error in numpynp_arr = np.array([1,2,\"a\",3,\"b\"], dtype=np.int32)"
},
{
"code": null,
"e": 2592,
"s": 2556,
"text": "This a valid code for python Lists:"
},
{
"code": null,
"e": 2636,
"s": 2592,
"text": "#heterogenous 1D arrayarr = [1,2,\"a\",3,\"b\"]"
},
{
"code": null,
"e": 2763,
"s": 2636,
"text": "Mathematical operations can’t be performed on heterogeneous data. That’s why it is recommended to have homogenous NumPy arrays"
},
{
"code": null,
"e": 2792,
"s": 2763,
"text": "Let’s take one more example:"
},
{
"code": null,
"e": 2838,
"s": 2792,
"text": "This code will give an error in python Lists:"
},
{
"code": null,
"e": 2911,
"s": 2838,
"text": "x = [1,2,3]y = [4,5,6]#this will give an error,#not possible in Listsx*y"
},
{
"code": null,
"e": 2944,
"s": 2911,
"text": "But this a valid code for NumPy:"
},
{
"code": null,
"e": 3016,
"s": 2944,
"text": "x = np.array([1,2,3])y = np.array([4,5,6])x*y#Outputnp.array([4,10,18])"
},
{
"code": null,
"e": 3096,
"s": 3016,
"text": "We’ll learn more about some awesome features in NumPy in the upcoming sections."
},
{
"code": null,
"e": 3122,
"s": 3096,
"text": "Suppose we have a matrix:"
},
{
"code": null,
"e": 3150,
"s": 3122,
"text": "[[1,2,3], [4,5,6], [7,8,9]]"
},
{
"code": null,
"e": 3194,
"s": 3150,
"text": "We’ll analyse for a number 7 in the matrix."
},
{
"code": null,
"e": 3236,
"s": 3194,
"text": "Computers read the information in binary."
},
{
"code": null,
"e": 3296,
"s": 3236,
"text": "By default Numpy stores 7 in total memory space of 4 bytes."
},
{
"code": null,
"e": 3393,
"s": 3296,
"text": "On the other hand in Lists, there is a lot of information that needs to be stored for integer 7."
},
{
"code": null,
"e": 3435,
"s": 3393,
"text": "Lists use a built-in int type for python."
},
{
"code": null,
"e": 3492,
"s": 3435,
"text": "The built-in int type consists of four different things:"
},
{
"code": null,
"e": 3543,
"s": 3492,
"text": "Depicts the size of that particular integer value."
},
{
"code": null,
"e": 3621,
"s": 3543,
"text": "It tells how many times that particular integer (here 7) has been pointed at."
},
{
"code": null,
"e": 3727,
"s": 3621,
"text": "Every variable in Python is just a reference (a pointer) to an object. It is not the actual value itself."
},
{
"code": null,
"e": 3916,
"s": 3727,
"text": "So for keeping track of references, every object (even integer) has an extra field called reference count that is increased or decreased when a pointer to the object is created or deleted."
},
{
"code": null,
"e": 3973,
"s": 3916,
"text": "It tells whether the object is int, boolean, string etc."
},
{
"code": null,
"e": 4010,
"s": 3973,
"text": "It has its own binary representation"
},
{
"code": null,
"e": 4059,
"s": 4010,
"text": "up to 64 bits........00000000 00000111 (8 bytes)"
},
{
"code": null,
"e": 4144,
"s": 4059,
"text": "Like this we also have binary representation for size, reference count, object type."
},
{
"code": null,
"e": 4199,
"s": 4144,
"text": "So basically it’s faster to read less bytes of memory."
},
{
"code": null,
"e": 4285,
"s": 4199,
"text": "We can clearly see Numpy takes less memory than Lists for a single integer storage !!"
},
{
"code": null,
"e": 4316,
"s": 4285,
"text": "Have look at this illustration"
},
{
"code": null,
"e": 4492,
"s": 4316,
"text": "The data on our list will be scattered in the computer’s memory. It doesn't have contiguous blocks of memory. The list will contain just a pointer to those 8 blocks of memory."
},
{
"code": null,
"e": 4621,
"s": 4492,
"text": "On the other hand, NumPy array will have contiguous blocks of memory in the computer. All 8 blocks are right next to each other."
},
{
"code": null,
"e": 4711,
"s": 4621,
"text": "So the takeaway from above analysis is that Lists are very slow and NumPy is superfast !!"
},
{
"code": null,
"e": 4747,
"s": 4711,
"text": "NumPy has the speed like cheetah ;)"
},
{
"code": null,
"e": 4931,
"s": 4747,
"text": "I’ll recommend you to install Python using the Anaconda distribution to make sure all underlying dependencies (such as Linear Algebra libraries) sync up with the use of conda install."
},
{
"code": null,
"e": 4989,
"s": 4931,
"text": "Refer this link to know more about anaconda installation:"
},
{
"code": null,
"e": 5027,
"s": 4989,
"text": "Installation — Anaconda Documentation"
},
{
"code": null,
"e": 5125,
"s": 5027,
"text": "If you have Anaconda, install NumPy by going to your terminal or command prompt and start typing:"
},
{
"code": null,
"e": 5145,
"s": 5125,
"text": "conda install numpy"
},
{
"code": null,
"e": 5204,
"s": 5145,
"text": "If you don’t have Anaconda distribution, you can also use:"
},
{
"code": null,
"e": 5222,
"s": 5204,
"text": "pip install numpy"
},
{
"code": null,
"e": 5259,
"s": 5222,
"text": "We’ll talk about vectors & matrices."
},
{
"code": null,
"e": 5319,
"s": 5259,
"text": "Vectors are strictly 1-D arrays and Matrices are 2-D arrays"
},
{
"code": null,
"e": 5374,
"s": 5319,
"text": "Note: Matrix can still have only one row or one column"
},
{
"code": null,
"e": 5393,
"s": 5374,
"text": "First import Numpy"
},
{
"code": null,
"e": 5412,
"s": 5393,
"text": "import numpy as np"
},
{
"code": null,
"e": 5457,
"s": 5412,
"text": "Let’s create NumPy Arrays using python Lists"
},
{
"code": null,
"e": 5465,
"s": 5457,
"text": "Code 1:"
},
{
"code": null,
"e": 5510,
"s": 5465,
"text": "#definejust_a_list = [1,2,3]#showjust_a_list"
},
{
"code": null,
"e": 5518,
"s": 5510,
"text": "Output:"
},
{
"code": null,
"e": 5528,
"s": 5518,
"text": "[1, 2, 3]"
},
{
"code": null,
"e": 5610,
"s": 5528,
"text": "Now we will convert the above code 1 snippet variable just_a_list to NumPy array."
},
{
"code": null,
"e": 5618,
"s": 5610,
"text": "Code 2:"
},
{
"code": null,
"e": 5640,
"s": 5618,
"text": "np.array(just_a_list)"
},
{
"code": null,
"e": 5648,
"s": 5640,
"text": "Output:"
},
{
"code": null,
"e": 5665,
"s": 5648,
"text": "array([1, 2, 3])"
},
{
"code": null,
"e": 5673,
"s": 5665,
"text": "Code 3:"
},
{
"code": null,
"e": 5740,
"s": 5673,
"text": "#definejust_a_matrix = [[1,2,3],[4,5,6],[7,8,9]]#showjust_a_matrix"
},
{
"code": null,
"e": 5748,
"s": 5740,
"text": "Output:"
},
{
"code": null,
"e": 5782,
"s": 5748,
"text": "[[1, 2, 3], [4, 5, 6], [7, 8, 9]]"
},
{
"code": null,
"e": 5868,
"s": 5782,
"text": "Now we will convert the above code 3 snippet variable just_a_matrix to NumPy 2d array"
},
{
"code": null,
"e": 5876,
"s": 5868,
"text": "Code 4:"
},
{
"code": null,
"e": 5900,
"s": 5876,
"text": "np.array(just_a_matrix)"
},
{
"code": null,
"e": 5908,
"s": 5900,
"text": "Output:"
},
{
"code": null,
"e": 5961,
"s": 5908,
"text": "array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])"
},
{
"code": null,
"e": 6018,
"s": 5961,
"text": "It returns evenly spaced values within a given interval."
},
{
"code": null,
"e": 6080,
"s": 6018,
"text": "This is very similar to Python’s own built-in range function."
},
{
"code": null,
"e": 6121,
"s": 6080,
"text": "The upper limit gets excluded in output."
},
{
"code": null,
"e": 6129,
"s": 6121,
"text": "Code 1:"
},
{
"code": null,
"e": 6145,
"s": 6129,
"text": "np.arange(0,20)"
},
{
"code": null,
"e": 6153,
"s": 6145,
"text": "Output:"
},
{
"code": null,
"e": 6232,
"s": 6153,
"text": "array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19])"
},
{
"code": null,
"e": 6240,
"s": 6232,
"text": "Code 2:"
},
{
"code": null,
"e": 6273,
"s": 6240,
"text": "#step size of 2np.arange(0,10,2)"
},
{
"code": null,
"e": 6281,
"s": 6273,
"text": "Output:"
},
{
"code": null,
"e": 6304,
"s": 6281,
"text": "array([0, 2, 4, 6, 8])"
},
{
"code": null,
"e": 6432,
"s": 6304,
"text": "In the above code snippet, 2 is the step size. As you can see in the output, the series is incrementing by the difference of 2."
},
{
"code": null,
"e": 6440,
"s": 6432,
"text": "Code 1:"
},
{
"code": null,
"e": 6452,
"s": 6440,
"text": "np.zeros(4)"
},
{
"code": null,
"e": 6460,
"s": 6452,
"text": "Output:"
},
{
"code": null,
"e": 6484,
"s": 6460,
"text": "array([0., 0., 0., 0.])"
},
{
"code": null,
"e": 6550,
"s": 6484,
"text": "So basically np.zeros(4) returns a new array filled with 4 zeros."
},
{
"code": null,
"e": 6558,
"s": 6550,
"text": "Code 2:"
},
{
"code": null,
"e": 6574,
"s": 6558,
"text": "np.zeros((3,3))"
},
{
"code": null,
"e": 6582,
"s": 6574,
"text": "Output:"
},
{
"code": null,
"e": 6644,
"s": 6582,
"text": "array([[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]])"
},
{
"code": null,
"e": 6753,
"s": 6644,
"text": "np.zeros((3,3)) returns a matrix of shape (3,3) filled with zeros. Shape (3,3) refers to 3 rows & 3 columns."
},
{
"code": null,
"e": 6761,
"s": 6753,
"text": "Code 3:"
},
{
"code": null,
"e": 6772,
"s": 6761,
"text": "np.ones(4)"
},
{
"code": null,
"e": 6780,
"s": 6772,
"text": "Output:"
},
{
"code": null,
"e": 6804,
"s": 6780,
"text": "array([1., 1., 1., 1.])"
},
{
"code": null,
"e": 6882,
"s": 6804,
"text": "In the above code snippet, np.ones(4) returns a new array filled with 4 ones."
},
{
"code": null,
"e": 6890,
"s": 6882,
"text": "Code 4:"
},
{
"code": null,
"e": 6905,
"s": 6890,
"text": "np.ones((3,3))"
},
{
"code": null,
"e": 6913,
"s": 6905,
"text": "Output:"
},
{
"code": null,
"e": 6984,
"s": 6913,
"text": "array([[ 1., 1., 1.], [ 1., 1., 1.], [ 1., 1., 1.]])"
},
{
"code": null,
"e": 7040,
"s": 6984,
"text": "Return evenly spaced numbers over a specified interval."
},
{
"code": null,
"e": 7048,
"s": 7040,
"text": "Code 1:"
},
{
"code": null,
"e": 7114,
"s": 7048,
"text": "#generates three numbers#between range 0 to 10np.linspace(0,10,3)"
},
{
"code": null,
"e": 7122,
"s": 7114,
"text": "Output:"
},
{
"code": null,
"e": 7143,
"s": 7122,
"text": "array([0., 5., 10.])"
},
{
"code": null,
"e": 7151,
"s": 7143,
"text": "Code 2:"
},
{
"code": null,
"e": 7172,
"s": 7151,
"text": "np.linspace(0,10,20)"
},
{
"code": null,
"e": 7180,
"s": 7172,
"text": "Output:"
},
{
"code": null,
"e": 7462,
"s": 7180,
"text": "array([ 0., 0.52631579, 1.05263158, 1.57894737, 2.10526316, 2.63157895, 3.15789474, 3.68421053, 4.21052632, 4.73684211, 5.26315789, 5.78947368, 6.31578947, 6.84210526, 7.36842105, 7.89473684, 8.42105263, 8.94736842, 9.47368421, 10. ])"
},
{
"code": null,
"e": 7490,
"s": 7462,
"text": "Creates an identity matrix."
},
{
"code": null,
"e": 7497,
"s": 7490,
"text": "Code :"
},
{
"code": null,
"e": 7507,
"s": 7497,
"text": "np.eye(3)"
},
{
"code": null,
"e": 7515,
"s": 7507,
"text": "Output:"
},
{
"code": null,
"e": 7584,
"s": 7515,
"text": "array([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]])"
},
{
"code": null,
"e": 7644,
"s": 7584,
"text": "Numpy also has a lot of ways to create random number arrays"
},
{
"code": null,
"e": 7757,
"s": 7644,
"text": "Creates an array of the given shape and populate it with random samples from a uniform distribution over [0, 1)."
},
{
"code": null,
"e": 7765,
"s": 7757,
"text": "Code 1:"
},
{
"code": null,
"e": 7783,
"s": 7765,
"text": "np.random.rand(2)"
},
{
"code": null,
"e": 7791,
"s": 7783,
"text": "Output:"
},
{
"code": null,
"e": 7823,
"s": 7791,
"text": "array([0.01231767, 0.24372946])"
},
{
"code": null,
"e": 7831,
"s": 7823,
"text": "Code 2:"
},
{
"code": null,
"e": 7851,
"s": 7831,
"text": "np.random.rand(3,3)"
},
{
"code": null,
"e": 7859,
"s": 7851,
"text": "Output:"
},
{
"code": null,
"e": 8009,
"s": 7859,
"text": "array([[0.75250092, 0.7582111 , 0.16155648], [0.11020177, 0.51819124, 0.29267394], [0.70052998, 0.58651773, 0.80589757]])"
},
{
"code": null,
"e": 8149,
"s": 8009,
"text": "Return a sample (or samples) from the Standard Normal or Gaussian distribution. Unlike np.random.rand which returns a uniform distribution."
},
{
"code": null,
"e": 8157,
"s": 8149,
"text": "Code 1:"
},
{
"code": null,
"e": 8176,
"s": 8157,
"text": "np.random.randn(2)"
},
{
"code": null,
"e": 8184,
"s": 8176,
"text": "Output:"
},
{
"code": null,
"e": 8218,
"s": 8184,
"text": "array([ 1.5868519 , -2.72817085])"
},
{
"code": null,
"e": 8226,
"s": 8218,
"text": "Code 2:"
},
{
"code": null,
"e": 8247,
"s": 8226,
"text": "np.random.randn(4,4)"
},
{
"code": null,
"e": 8255,
"s": 8247,
"text": "Output:"
},
{
"code": null,
"e": 8517,
"s": 8255,
"text": "array([[ 0.24602617, -2.39464955, -0.1382286 , 1.47872422], [ 0.70466341, -0.17408009, -2.22898345, 0.28018941], [ 0.57969196, 0.00664889, 1.20221044, 0.47452959], [ 0.93939176, -0.07719476, -0.08907384, 1.26465443]])"
},
{
"code": null,
"e": 8582,
"s": 8517,
"text": "Return random integers from low (inclusive) to high (exclusive)."
},
{
"code": null,
"e": 8590,
"s": 8582,
"text": "Code 1:"
},
{
"code": null,
"e": 8615,
"s": 8590,
"text": "np.random.randint(1,100)"
},
{
"code": null,
"e": 8623,
"s": 8615,
"text": "Output:"
},
{
"code": null,
"e": 8626,
"s": 8623,
"text": "84"
},
{
"code": null,
"e": 8634,
"s": 8626,
"text": "Code 2:"
},
{
"code": null,
"e": 8709,
"s": 8634,
"text": "#generates 10 random #integers between 1 to 100np.random.randint(1,100,10)"
},
{
"code": null,
"e": 8717,
"s": 8709,
"text": "Output:"
},
{
"code": null,
"e": 8765,
"s": 8717,
"text": "array([85, 30, 2, 72, 40, 86, 18, 46, 3, 24])"
},
{
"code": null,
"e": 8843,
"s": 8765,
"text": "One of the most useful methods you can use on an array is the reshape method."
},
{
"code": null,
"e": 8906,
"s": 8843,
"text": "It returns an array containing the same data with a new shape."
},
{
"code": null,
"e": 8914,
"s": 8906,
"text": "Code 1:"
},
{
"code": null,
"e": 8949,
"s": 8914,
"text": "#definearr = np.arange(16)#showarr"
},
{
"code": null,
"e": 8957,
"s": 8949,
"text": "Output:"
},
{
"code": null,
"e": 9020,
"s": 8957,
"text": "array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])"
},
{
"code": null,
"e": 9076,
"s": 9020,
"text": "Now let’s reshape the above code 1 snippet variable arr"
},
{
"code": null,
"e": 9084,
"s": 9076,
"text": "Code 2:"
},
{
"code": null,
"e": 9101,
"s": 9084,
"text": "arr.reshape(4,4)"
},
{
"code": null,
"e": 9109,
"s": 9101,
"text": "Output:"
},
{
"code": null,
"e": 9231,
"s": 9109,
"text": "array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]])"
},
{
"code": null,
"e": 9360,
"s": 9231,
"text": "These are useful methods for finding maximum or minimum values. We can also find their index locations using argmin or argmax !!"
},
{
"code": null,
"e": 9411,
"s": 9360,
"text": "Let’s generate a random NumPy array of 10 integers"
},
{
"code": null,
"e": 9419,
"s": 9411,
"text": "Code 1:"
},
{
"code": null,
"e": 9481,
"s": 9419,
"text": "#definerandom_arr = np.random.randint(0,50,10)#showrandom_arr"
},
{
"code": null,
"e": 9489,
"s": 9481,
"text": "Output:"
},
{
"code": null,
"e": 9537,
"s": 9489,
"text": "array([16, 8, 40, 7, 15, 39, 0, 15, 20, 35])"
},
{
"code": null,
"e": 9545,
"s": 9537,
"text": "Code 2:"
},
{
"code": null,
"e": 9562,
"s": 9545,
"text": "random_arr.max()"
},
{
"code": null,
"e": 9570,
"s": 9562,
"text": "Output:"
},
{
"code": null,
"e": 9573,
"s": 9570,
"text": "40"
},
{
"code": null,
"e": 9581,
"s": 9573,
"text": "Code 3:"
},
{
"code": null,
"e": 9601,
"s": 9581,
"text": "random_arr.argmax()"
},
{
"code": null,
"e": 9609,
"s": 9601,
"text": "Output:"
},
{
"code": null,
"e": 9611,
"s": 9609,
"text": "2"
},
{
"code": null,
"e": 9619,
"s": 9611,
"text": "Code 4:"
},
{
"code": null,
"e": 9636,
"s": 9619,
"text": "random_arr.min()"
},
{
"code": null,
"e": 9644,
"s": 9636,
"text": "Output:"
},
{
"code": null,
"e": 9646,
"s": 9644,
"text": "0"
},
{
"code": null,
"e": 9654,
"s": 9646,
"text": "Code 5:"
},
{
"code": null,
"e": 9674,
"s": 9654,
"text": "random_arr.argmin()"
},
{
"code": null,
"e": 9682,
"s": 9674,
"text": "Output:"
},
{
"code": null,
"e": 9684,
"s": 9682,
"text": "6"
},
{
"code": null,
"e": 9738,
"s": 9684,
"text": "Shape is an attribute that arrays have (not a method)"
},
{
"code": null,
"e": 9828,
"s": 9738,
"text": "We have already defined the variable arr under the code 1 snippet of the Reshape Section."
},
{
"code": null,
"e": 9836,
"s": 9828,
"text": "Code 1:"
},
{
"code": null,
"e": 9846,
"s": 9836,
"text": "arr.shape"
},
{
"code": null,
"e": 9854,
"s": 9846,
"text": "Output:"
},
{
"code": null,
"e": 9860,
"s": 9854,
"text": "(16,)"
},
{
"code": null,
"e": 9939,
"s": 9860,
"text": "The above shape indicates that arr is just a one-dimensional vector of rank 1."
},
{
"code": null,
"e": 9947,
"s": 9939,
"text": "Code 2:"
},
{
"code": null,
"e": 9965,
"s": 9947,
"text": "arr.reshape(1,16)"
},
{
"code": null,
"e": 9973,
"s": 9965,
"text": "Output:"
},
{
"code": null,
"e": 10038,
"s": 9973,
"text": "array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]])"
},
{
"code": null,
"e": 10129,
"s": 10038,
"text": "Notice the two sets of brackets in the output. It indicates the 2-dimensional NumPy array."
},
{
"code": null,
"e": 10137,
"s": 10129,
"text": "Code 3:"
},
{
"code": null,
"e": 10161,
"s": 10137,
"text": "arr.reshape(1,16).shape"
},
{
"code": null,
"e": 10169,
"s": 10161,
"text": "Output:"
},
{
"code": null,
"e": 10177,
"s": 10169,
"text": "(1, 16)"
},
{
"code": null,
"e": 10223,
"s": 10177,
"text": "The reshaped arr contains 1 row & 16 columns."
},
{
"code": null,
"e": 10231,
"s": 10223,
"text": "Code 4:"
},
{
"code": null,
"e": 10249,
"s": 10231,
"text": "arr.reshape(16,1)"
},
{
"code": null,
"e": 10257,
"s": 10249,
"text": "Output:"
},
{
"code": null,
"e": 10466,
"s": 10257,
"text": "array([[ 0], [ 1], [ 2], [ 3], [ 4], [ 5], [ 6], [ 7], [ 8], [ 9], [10], [11], [12], [13], [14], [15]])"
},
{
"code": null,
"e": 10474,
"s": 10466,
"text": "Code 5:"
},
{
"code": null,
"e": 10498,
"s": 10474,
"text": "arr.reshape(16,1).shape"
},
{
"code": null,
"e": 10506,
"s": 10498,
"text": "Output:"
},
{
"code": null,
"e": 10514,
"s": 10506,
"text": "(16, 1)"
},
{
"code": null,
"e": 10560,
"s": 10514,
"text": "The reshaped arr contains 16 rows & 1 column."
},
{
"code": null,
"e": 10625,
"s": 10560,
"text": "Using dtype we can get the data type of the object in the array."
},
{
"code": null,
"e": 10633,
"s": 10625,
"text": "Code 1:"
},
{
"code": null,
"e": 10643,
"s": 10633,
"text": "arr.dtype"
},
{
"code": null,
"e": 10651,
"s": 10643,
"text": "Output:"
},
{
"code": null,
"e": 10666,
"s": 10651,
"text": "dtype(‘int64’)"
},
{
"code": null,
"e": 10844,
"s": 10666,
"text": "Now we will learn how to select elements or group of elements from an array. The simplest way of picking up one or more elements from an array looks very similar to python lists"
},
{
"code": null,
"e": 10934,
"s": 10844,
"text": "We have already defined the variable arr under the code 1 snippet of the Reshape Section."
},
{
"code": null,
"e": 10942,
"s": 10934,
"text": "Code 1:"
},
{
"code": null,
"e": 10974,
"s": 10942,
"text": "#Get a value #at an indexarr[5]"
},
{
"code": null,
"e": 10982,
"s": 10974,
"text": "Output:"
},
{
"code": null,
"e": 10984,
"s": 10982,
"text": "5"
},
{
"code": null,
"e": 10992,
"s": 10984,
"text": "Code 2:"
},
{
"code": null,
"e": 11024,
"s": 10992,
"text": "#Get values #in a rangearr[1:5]"
},
{
"code": null,
"e": 11032,
"s": 11024,
"text": "Output:"
},
{
"code": null,
"e": 11052,
"s": 11032,
"text": "array([1, 2, 3, 4])"
},
{
"code": null,
"e": 11159,
"s": 11052,
"text": "The term broadcasting describes how Numpy treats array with different shapes during arithmetic operations."
},
{
"code": null,
"e": 11244,
"s": 11159,
"text": "Numpy arrays differ from a normal Python list because of their ability to broadcast."
},
{
"code": null,
"e": 11252,
"s": 11244,
"text": "Code 1:"
},
{
"code": null,
"e": 11306,
"s": 11252,
"text": "#Setting a value with#index rangearr[0:5]=100#Showarr"
},
{
"code": null,
"e": 11314,
"s": 11306,
"text": "Output:"
},
{
"code": null,
"e": 11386,
"s": 11314,
"text": "array([100, 100, 100, 100, 100, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])"
},
{
"code": null,
"e": 11394,
"s": 11386,
"text": "Code 2:"
},
{
"code": null,
"e": 11474,
"s": 11394,
"text": "#Reset array, we'll #see the reason behind it soonarr = np.arange(0,11)#Showarr"
},
{
"code": null,
"e": 11482,
"s": 11474,
"text": "Output:"
},
{
"code": null,
"e": 11534,
"s": 11482,
"text": "array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])"
},
{
"code": null,
"e": 11542,
"s": 11534,
"text": "Code 3:"
},
{
"code": null,
"e": 11589,
"s": 11542,
"text": "slice_of_arr = arr[0:6]#Show sliceslice_of_arr"
},
{
"code": null,
"e": 11597,
"s": 11589,
"text": "Output:"
},
{
"code": null,
"e": 11623,
"s": 11597,
"text": "array([0, 1, 2, 3, 4, 5])"
},
{
"code": null,
"e": 11631,
"s": 11623,
"text": "Code 4:"
},
{
"code": null,
"e": 11692,
"s": 11631,
"text": "#Change Sliceslice_of_arr[:]=99#Show Slice againslice_of_arr"
},
{
"code": null,
"e": 11700,
"s": 11692,
"text": "Output:"
},
{
"code": null,
"e": 11732,
"s": 11700,
"text": "array([99, 99, 99, 99, 99, 99])"
},
{
"code": null,
"e": 11740,
"s": 11732,
"text": "Code 5:"
},
{
"code": null,
"e": 11744,
"s": 11740,
"text": "arr"
},
{
"code": null,
"e": 11752,
"s": 11744,
"text": "Output:"
},
{
"code": null,
"e": 11800,
"s": 11752,
"text": "array([99, 99, 99, 99, 99, 99, 6, 7, 8, 9, 10])"
},
{
"code": null,
"e": 11886,
"s": 11800,
"text": "As you can see in the above output, the changes also occured in our original array !!"
},
{
"code": null,
"e": 12040,
"s": 11886,
"text": "This happened because slice_of_arr is just a reference to the first five elements of arr . Assignment operation doesn’t make a separate copy of the data."
},
{
"code": null,
"e": 12092,
"s": 12040,
"text": "To Copy the data, we need to use the copy method !!"
},
{
"code": null,
"e": 12100,
"s": 12092,
"text": "Code 6:"
},
{
"code": null,
"e": 12130,
"s": 12100,
"text": "arr_copy = arr.copy()arr_copy"
},
{
"code": null,
"e": 12138,
"s": 12130,
"text": "Output:"
},
{
"code": null,
"e": 12190,
"s": 12138,
"text": "array([99, 99, 99, 99, 99, 99, 6, 7, 8, 9, 10])"
},
{
"code": null,
"e": 12232,
"s": 12190,
"text": "Let’s see another example of broadcasting"
},
{
"code": null,
"e": 12240,
"s": 12232,
"text": "Code 7:"
},
{
"code": null,
"e": 12319,
"s": 12240,
"text": "a = [[1,2,3],[4,5,6]]#Converting to #numpy 2d arraynp_a = np.array(a)#shownp_a"
},
{
"code": null,
"e": 12327,
"s": 12319,
"text": "Output:"
},
{
"code": null,
"e": 12371,
"s": 12327,
"text": "array([[1, 2, 3], [4, 5, 6]])"
},
{
"code": null,
"e": 12379,
"s": 12371,
"text": "Code 8:"
},
{
"code": null,
"e": 12408,
"s": 12379,
"text": "#2 rows, 3 columnsnp_a.shape"
},
{
"code": null,
"e": 12416,
"s": 12408,
"text": "Output:"
},
{
"code": null,
"e": 12423,
"s": 12416,
"text": "(2, 3)"
},
{
"code": null,
"e": 12431,
"s": 12423,
"text": "Code 9:"
},
{
"code": null,
"e": 12503,
"s": 12431,
"text": "b = [100,200,300]#converting to #numpy arraynp_b = np.array(b)#shownp_b"
},
{
"code": null,
"e": 12511,
"s": 12503,
"text": "Output:"
},
{
"code": null,
"e": 12534,
"s": 12511,
"text": "array([100, 200, 300])"
},
{
"code": null,
"e": 12543,
"s": 12534,
"text": "Code 10:"
},
{
"code": null,
"e": 12554,
"s": 12543,
"text": "np_b.shape"
},
{
"code": null,
"e": 12562,
"s": 12554,
"text": "Output:"
},
{
"code": null,
"e": 12567,
"s": 12562,
"text": "(3,)"
},
{
"code": null,
"e": 12576,
"s": 12567,
"text": "Code 11:"
},
{
"code": null,
"e": 12628,
"s": 12576,
"text": "np_b_reshaped = np_b.reshape(1,3)#shownp_b_reshaped"
},
{
"code": null,
"e": 12636,
"s": 12628,
"text": "Output:"
},
{
"code": null,
"e": 12661,
"s": 12636,
"text": "array([[100, 200, 300]])"
},
{
"code": null,
"e": 12670,
"s": 12661,
"text": "Code 12:"
},
{
"code": null,
"e": 12707,
"s": 12670,
"text": "#1 row, 3 columnsnp_b_reshaped.shape"
},
{
"code": null,
"e": 12715,
"s": 12707,
"text": "Output:"
},
{
"code": null,
"e": 12722,
"s": 12715,
"text": "(1, 3)"
},
{
"code": null,
"e": 12752,
"s": 12722,
"text": "See the magic of broadcasting"
},
{
"code": null,
"e": 12761,
"s": 12752,
"text": "Code 13:"
},
{
"code": null,
"e": 12782,
"s": 12761,
"text": "np_a + np_b_reshaped"
},
{
"code": null,
"e": 12790,
"s": 12782,
"text": "Output:"
},
{
"code": null,
"e": 12846,
"s": 12790,
"text": "array([[101, 202, 303], [104, 205, 306]])"
},
{
"code": null,
"e": 12937,
"s": 12846,
"text": "So basically np_b_reshaped replicates itself for the second row & it’s shape becomes (2,3)"
},
{
"code": null,
"e": 12946,
"s": 12937,
"text": "Code 14:"
},
{
"code": null,
"e": 12986,
"s": 12946,
"text": "np.array([[100,200,300],[100,200,300]])"
},
{
"code": null,
"e": 12994,
"s": 12986,
"text": "Output:"
},
{
"code": null,
"e": 13050,
"s": 12994,
"text": "array([[100, 200, 300], [100, 200, 300]])"
},
{
"code": null,
"e": 13109,
"s": 13050,
"text": "The general format is arr_2d[row][col] or arr_2d[row,col]."
},
{
"code": null,
"e": 13118,
"s": 13109,
"text": "Code 1 :"
},
{
"code": null,
"e": 13174,
"s": 13118,
"text": "arr_2d = np.array(([1,2,3],[4,5,6],[7,8,9]))#Showarr_2d"
},
{
"code": null,
"e": 13182,
"s": 13174,
"text": "Output:"
},
{
"code": null,
"e": 13251,
"s": 13182,
"text": "array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])"
},
{
"code": null,
"e": 13259,
"s": 13251,
"text": "Code 2:"
},
{
"code": null,
"e": 13282,
"s": 13259,
"text": "#Indexing rowarr_2d[1]"
},
{
"code": null,
"e": 13290,
"s": 13282,
"text": "Output:"
},
{
"code": null,
"e": 13307,
"s": 13290,
"text": "array([4, 5, 6])"
},
{
"code": null,
"e": 13315,
"s": 13307,
"text": "Code 3:"
},
{
"code": null,
"e": 13361,
"s": 13315,
"text": "#Getting individual element valuearr_2d[1][0]"
},
{
"code": null,
"e": 13369,
"s": 13361,
"text": "Output:"
},
{
"code": null,
"e": 13371,
"s": 13369,
"text": "4"
},
{
"code": null,
"e": 13379,
"s": 13371,
"text": "Code 4:"
},
{
"code": null,
"e": 13403,
"s": 13379,
"text": "#another wayarr_2d[1,0]"
},
{
"code": null,
"e": 13411,
"s": 13403,
"text": "Output:"
},
{
"code": null,
"e": 13413,
"s": 13411,
"text": "4"
},
{
"code": null,
"e": 13421,
"s": 13413,
"text": "Code 5:"
},
{
"code": null,
"e": 13486,
"s": 13421,
"text": "#2D array slicing#Shape (2,2) from#top right cornerarr_2d[:2,1:]"
},
{
"code": null,
"e": 13494,
"s": 13486,
"text": "Output:"
},
{
"code": null,
"e": 13532,
"s": 13494,
"text": "array([[2, 3], [5, 6]])"
},
{
"code": null,
"e": 13540,
"s": 13532,
"text": "Code 6:"
},
{
"code": null,
"e": 13575,
"s": 13540,
"text": "#Shape of the #bottom rowarr_2d[2]"
},
{
"code": null,
"e": 13583,
"s": 13575,
"text": "Output:"
},
{
"code": null,
"e": 13600,
"s": 13583,
"text": "array([7, 8, 9])"
},
{
"code": null,
"e": 13687,
"s": 13600,
"text": "Let’s briefly go over how to use brackets for selection based on comparison operators."
},
{
"code": null,
"e": 13695,
"s": 13687,
"text": "Code 1:"
},
{
"code": null,
"e": 13727,
"s": 13695,
"text": "arr1 = np.arange(1,11)#showarr1"
},
{
"code": null,
"e": 13735,
"s": 13727,
"text": "Output:"
},
{
"code": null,
"e": 13783,
"s": 13735,
"text": "array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])"
},
{
"code": null,
"e": 13791,
"s": 13783,
"text": "Code 2:"
},
{
"code": null,
"e": 13800,
"s": 13791,
"text": "arr1 > 5"
},
{
"code": null,
"e": 13808,
"s": 13800,
"text": "Output:"
},
{
"code": null,
"e": 13893,
"s": 13808,
"text": "array([False, False, False, False, False, True, True, True, True, True])"
},
{
"code": null,
"e": 13901,
"s": 13893,
"text": "Code 3:"
},
{
"code": null,
"e": 13934,
"s": 13901,
"text": "bool_arr = arr1 > 5#showbool_arr"
},
{
"code": null,
"e": 13942,
"s": 13934,
"text": "Output:"
},
{
"code": null,
"e": 14018,
"s": 13942,
"text": "array([False, False, False, False, False, True, True, True, True, True])"
},
{
"code": null,
"e": 14026,
"s": 14018,
"text": "Code 4:"
},
{
"code": null,
"e": 14041,
"s": 14026,
"text": "arr1[bool_arr]"
},
{
"code": null,
"e": 14049,
"s": 14041,
"text": "Output:"
},
{
"code": null,
"e": 14077,
"s": 14049,
"text": "array([ 6, 7, 8, 9, 10])"
},
{
"code": null,
"e": 14085,
"s": 14077,
"text": "Code 5:"
},
{
"code": null,
"e": 14100,
"s": 14085,
"text": "arr1[arr1 > 2]"
},
{
"code": null,
"e": 14108,
"s": 14100,
"text": "Output:"
},
{
"code": null,
"e": 14148,
"s": 14108,
"text": "array([ 3, 4, 5, 6, 7, 8, 9, 10])"
},
{
"code": null,
"e": 14258,
"s": 14148,
"text": "You can easily perform array with array arithmetic, or scalar with array arithmetic. Let’s see some examples."
},
{
"code": null,
"e": 14266,
"s": 14258,
"text": "Code 1:"
},
{
"code": null,
"e": 14289,
"s": 14266,
"text": "arr2 = np.arange(0,10)"
},
{
"code": null,
"e": 14297,
"s": 14289,
"text": "Code 2:"
},
{
"code": null,
"e": 14309,
"s": 14297,
"text": "arr2 + arr2"
},
{
"code": null,
"e": 14317,
"s": 14309,
"text": "Output:"
},
{
"code": null,
"e": 14365,
"s": 14317,
"text": "array([ 0, 2, 4, 6, 8, 10, 12, 14, 16, 18])"
},
{
"code": null,
"e": 14373,
"s": 14365,
"text": "Code 3:"
},
{
"code": null,
"e": 14385,
"s": 14373,
"text": "arr2 * arr2"
},
{
"code": null,
"e": 14393,
"s": 14385,
"text": "Output:"
},
{
"code": null,
"e": 14441,
"s": 14393,
"text": "array([ 0, 1, 4, 9, 16, 25, 36, 49, 64, 81])"
},
{
"code": null,
"e": 14449,
"s": 14441,
"text": "Code 4:"
},
{
"code": null,
"e": 14461,
"s": 14449,
"text": "arr2 - arr2"
},
{
"code": null,
"e": 14469,
"s": 14461,
"text": "Output:"
},
{
"code": null,
"e": 14507,
"s": 14469,
"text": "array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])"
},
{
"code": null,
"e": 14554,
"s": 14507,
"text": "Warning on division by zero, but not an error!"
},
{
"code": null,
"e": 14585,
"s": 14554,
"text": "Numpy will replace it with nan"
},
{
"code": null,
"e": 14593,
"s": 14585,
"text": "Code 5:"
},
{
"code": null,
"e": 14605,
"s": 14593,
"text": "arr2 / arr2"
},
{
"code": null,
"e": 14613,
"s": 14605,
"text": "Output:"
},
{
"code": null,
"e": 14872,
"s": 14613,
"text": "/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:3: RuntimeWarning: invalid value encountered in true_divide This is separate from the ipykernel package so we can avoid doing imports untilarray([nan, 1., 1., 1., 1., 1., 1., 1., 1., 1.])"
},
{
"code": null,
"e": 14945,
"s": 14872,
"text": "Another warning, but not an error. Value will be replaced with infinity."
},
{
"code": null,
"e": 14953,
"s": 14945,
"text": "Code 6:"
},
{
"code": null,
"e": 14962,
"s": 14953,
"text": "1 / arr2"
},
{
"code": null,
"e": 14970,
"s": 14962,
"text": "Output:"
},
{
"code": null,
"e": 15179,
"s": 14970,
"text": "/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:2: RuntimeWarning: divide by zero encountered in true_dividearray([inf, 1., 0.5, 0.33333333, 0.25, 0.2, 0.16666667, 0.14285714, 0.125, 0.11111111])"
},
{
"code": null,
"e": 15195,
"s": 15179,
"text": "Cube of numbers"
},
{
"code": null,
"e": 15203,
"s": 15195,
"text": "Code 7:"
},
{
"code": null,
"e": 15213,
"s": 15203,
"text": "arr2 ** 3"
},
{
"code": null,
"e": 15221,
"s": 15213,
"text": "Output:"
},
{
"code": null,
"e": 15271,
"s": 15221,
"text": "array([0, 1, 8, 27, 64, 125, 216, 343, 512, 729])"
},
{
"code": null,
"e": 15464,
"s": 15271,
"text": "Numpy comes preloaded with many universal array functions, which are essentially just mathematical operations you can use to perform the operation across the array. Let’s see some common ones."
},
{
"code": null,
"e": 15484,
"s": 15464,
"text": "Taking Square Roots"
},
{
"code": null,
"e": 15492,
"s": 15484,
"text": "Code 1:"
},
{
"code": null,
"e": 15506,
"s": 15492,
"text": "np.sqrt(arr2)"
},
{
"code": null,
"e": 15514,
"s": 15506,
"text": "Output:"
},
{
"code": null,
"e": 15611,
"s": 15514,
"text": "array([0. , 1., 1.41421356, 1.73205081, 2., 2.23606798, 2.44948974, 2.64575131, 2.82842712, 3.])"
},
{
"code": null,
"e": 15641,
"s": 15611,
"text": "Calcualting exponential (e^x)"
},
{
"code": null,
"e": 15649,
"s": 15641,
"text": "Code 2:"
},
{
"code": null,
"e": 15662,
"s": 15649,
"text": "np.exp(arr2)"
},
{
"code": null,
"e": 15670,
"s": 15662,
"text": "Output:"
},
{
"code": null,
"e": 15852,
"s": 15670,
"text": "array([1.00000000e+00, 2.71828183e+00, 7.38905610e+00, 2.00855369e+01, 5.45981500e+01, 1.48413159e+02, 4.03428793e+02, 1.09663316e+03, 2.98095799e+03, 8.10308393e+03])"
},
{
"code": null,
"e": 15870,
"s": 15852,
"text": "same as arr.max()"
},
{
"code": null,
"e": 15878,
"s": 15870,
"text": "Code 3:"
},
{
"code": null,
"e": 15891,
"s": 15878,
"text": "np.max(arr2)"
},
{
"code": null,
"e": 15899,
"s": 15891,
"text": "Output:"
},
{
"code": null,
"e": 15901,
"s": 15899,
"text": "9"
},
{
"code": null,
"e": 15924,
"s": 15901,
"text": "Calculating sine value"
},
{
"code": null,
"e": 15932,
"s": 15924,
"text": "Code 4:"
},
{
"code": null,
"e": 15945,
"s": 15932,
"text": "np.sin(arr2)"
},
{
"code": null,
"e": 15953,
"s": 15945,
"text": "Output:"
},
{
"code": null,
"e": 16090,
"s": 15953,
"text": "array([ 0., 0.84147098, 0.90929743, 0.14112001, -0.7568025 , -0.95892427, -0.2794155 , 0.6569866 , 0.98935825, 0.41211849])"
},
{
"code": null,
"e": 16106,
"s": 16090,
"text": "Calculating log"
},
{
"code": null,
"e": 16114,
"s": 16106,
"text": "Code 5:"
},
{
"code": null,
"e": 16127,
"s": 16114,
"text": "np.log(arr2)"
},
{
"code": null,
"e": 16135,
"s": 16127,
"text": "Output:"
},
{
"code": null,
"e": 16412,
"s": 16135,
"text": "usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:1: RuntimeWarning: divide by zero encountered in log \"\"\"Entry point for launching an IPython kernel.array([ -inf, 0., 0.69314718, 1.09861229, 1.38629436, 1.60943791, 1.79175947, 1.94591015, 2.07944154, 2.19722458])"
},
{
"code": null,
"e": 16484,
"s": 16412,
"text": "Vectorization is used to speed up the Python code without using a loop."
},
{
"code": null,
"e": 16590,
"s": 16484,
"text": "Various operations on vectors & matrices can be performed like the dot product, element-wise product etc."
},
{
"code": null,
"e": 16624,
"s": 16590,
"text": "Vectorized version of dot product"
},
{
"code": null,
"e": 16630,
"s": 16624,
"text": "Code:"
},
{
"code": null,
"e": 16845,
"s": 16630,
"text": "import timea = np.random.rand(1000000)b = np.random.rand(1000000)tic= time.time()c = np.dot(a,b) #dot product of two vectorstoc = time.time()print(\"Time taken in vectorized version: \"+str(1000 * (toc - tic))+\" ms\")"
},
{
"code": null,
"e": 16853,
"s": 16845,
"text": "Output:"
},
{
"code": null,
"e": 16908,
"s": 16853,
"text": "Time taken in vectorized version: 1.483917236328125 ms"
},
{
"code": null,
"e": 16956,
"s": 16908,
"text": "let’s check the for loop version of dot product"
},
{
"code": null,
"e": 16962,
"s": 16956,
"text": "Code:"
},
{
"code": null,
"e": 17116,
"s": 16962,
"text": "c = 0tic = time.time()for i in range(1000000): c += a[i] * b[i]toc = time.time()print(\"Time taken in for loop version: \"+str(1000 *(toc - tic)) + \" ms\")"
},
{
"code": null,
"e": 17124,
"s": 17116,
"text": "Output:"
},
{
"code": null,
"e": 17177,
"s": 17124,
"text": "Time taken in for loop version: 579.4703960418701 ms"
},
{
"code": null,
"e": 17378,
"s": 17177,
"text": "So basically the takeaway from the above analysis is that Vectorization is way more powerful and efficient than simple for loop. It takes very less time. So whenever possible avoid explicit for loops."
},
{
"code": null,
"e": 17450,
"s": 17378,
"text": "I have tried my best to give you a comprehensive introduction to NumPy."
},
{
"code": null,
"e": 17503,
"s": 17450,
"text": "Linear Algebra becomes a cakewalk with this package."
},
{
"code": null,
"e": 17598,
"s": 17503,
"text": "NumPy is a fundamental package for scientific computation & mathematical operations in python."
},
{
"code": null,
"e": 17637,
"s": 17598,
"text": "NumPy is way more powerful than Lists."
},
{
"code": null,
"e": 17703,
"s": 17637,
"text": "Go ahead and check out my GitHub repository for full code access."
},
{
"code": null,
"e": 17759,
"s": 17703,
"text": "Here is a link to my Medium Articles GitHub repository:"
},
{
"code": null,
"e": 17770,
"s": 17759,
"text": "github.com"
},
{
"code": null,
"e": 17879,
"s": 17770,
"text": "Here is a direct link to my NumPy Jupyter Notebook containing all the codes snippets used in this article :-"
},
{
"code": null,
"e": 17890,
"s": 17879,
"text": "github.com"
},
{
"code": null,
"e": 17900,
"s": 17890,
"text": "numpy.org"
},
{
"code": null,
"e": 18071,
"s": 17900,
"text": "If you are interested in learning CS Fundamentals. If you are curious about learning Data Structures & Algorithms, then do check out my first blog on Heap Sort Algorithm."
},
{
"code": null,
"e": 18082,
"s": 18071,
"text": "medium.com"
},
{
"code": null,
"e": 18118,
"s": 18082,
"text": "Thank you for reading this article."
}
] |
Static Blocks in Java - GeeksforGeeks
|
02 Dec, 2021
In simpler language whenever we do uses a static keyword and associate it to a block then that block is referred to as a static block. Unlike C++, Java supports a special block, called a static block (also called static clause) that can be used for static initialization of a class. This code inside the static block is executed only once: the first time the class is loaded into memory.
Calling of static block in java?
Now comes the point of how to call this static block. So in order to call any static block, there is no specified way as static block executes automatically when the class is loaded in memory. Refer to the below illustration for understanding how static block is called.
Illustration:
class GFG {
// Constructor of this class
GFG {}
// Method of this class
public static void print() { static{} }
public static void main(String[] args) {
// Calling of method insside main()
GFG geeks = new GFG();
// Calling of constructor inside main()
new GFG();
// Calling of static block
// Nothing to do here as it is called
// autimatically as class is loaded in memory
}
}
Note: From the above illustration we can perceive that static blocks are automatically called as soon as class is loaded in memory and there is nothing to do as we have to in case of calling methods and constructors inside main().
Can we print something on the console without creating main() method?
It is very important question from the interview’s perceptive point. The answer is yes we can print if we are using JDK version 1.6 or previous and if after that that it will throw an. error.
Example 1-A: Running on JDK version 1.6 of Previous
Java
// Java Program Running on JDK version 1.6 of Previous // Main classclass GFG { // Static block static { // Print statement System.out.print( "Static block can be printed without main method"); }}
Output:
Static block can be printed without main method
Example 1-B: Running on JDK version 1.6 and Later
Java
// Java Program Running on JDK version 1.6 and Later // Main classclass GFG { // Static block static { // Print statement System.out.print( "Static block can be printed without main method"); }}
Output:
Example 1:
Java
// Java Program to Illustrate How Static block is Called // Class 1// Helper classclass Test { // Case 1: Static variable static int i; // Case 2: non-static variables int j; // Case 3: Static block // Start of static block static { i = 10; System.out.println("static block called "); } // End of static block} // Class 2// Main classclass GFG { // Main driver method public static void main(String args[]) { // Although we don't have an object of Test, static // block is called because i is being accessed in // following statement. System.out.println(Test.i); }}
static block called
10
Remember: Static blocks can also be executed before constructors.
Example 2:
Java
// Java Program to Illustrate Execution of Static Block// Before Constructors // Class 1// Helper classclass Test { // Case 1: Static variable static int i; // Case 2: Non-static variable int j; // Case 3: Static blocks static { i = 10; System.out.println("static block called "); } // Constructor calling Test() { System.out.println("Constructor called"); }} // Class 2// Main classclass GFG { // Main driver method public static void main(String args[]) { // Although we have two objects, static block is // executed only once. Test t1 = new Test(); Test t2 = new Test(); }}
static block called
Constructor called
Constructor called
A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.
Note: We use Initializer Block in Java if we want to execute a fragment of code for every object which is seen widely in enterprising industries in development.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Object Oriented Programming (OOPs) Concept in Java
Split() String method in Java with examples
For-each loop in Java
Arrays.sort() in Java with examples
Reverse a string in Java
ArrayList in Java
HashMap in Java with Examples
Multidimensional Arrays in Java
Initialize an ArrayList in Java
|
[
{
"code": null,
"e": 19133,
"s": 19105,
"text": "\n02 Dec, 2021"
},
{
"code": null,
"e": 19522,
"s": 19133,
"text": "In simpler language whenever we do uses a static keyword and associate it to a block then that block is referred to as a static block. Unlike C++, Java supports a special block, called a static block (also called static clause) that can be used for static initialization of a class. This code inside the static block is executed only once: the first time the class is loaded into memory. "
},
{
"code": null,
"e": 19555,
"s": 19522,
"text": "Calling of static block in java?"
},
{
"code": null,
"e": 19826,
"s": 19555,
"text": "Now comes the point of how to call this static block. So in order to call any static block, there is no specified way as static block executes automatically when the class is loaded in memory. Refer to the below illustration for understanding how static block is called."
},
{
"code": null,
"e": 19840,
"s": 19826,
"text": "Illustration:"
},
{
"code": null,
"e": 20384,
"s": 19840,
"text": "class GFG {\n\n // Constructor of this class\n GFG {}\n // Method of this class\n public static void print() { static{} }\n\n public static void main(String[] args) {\n\n // Calling of method insside main()\n GFG geeks = new GFG();\n\n // Calling of constructor inside main()\n new GFG();\n\n // Calling of static block\n // Nothing to do here as it is called\n // autimatically as class is loaded in memory\n\n }\n}"
},
{
"code": null,
"e": 20616,
"s": 20384,
"text": "Note: From the above illustration we can perceive that static blocks are automatically called as soon as class is loaded in memory and there is nothing to do as we have to in case of calling methods and constructors inside main(). "
},
{
"code": null,
"e": 20686,
"s": 20616,
"text": "Can we print something on the console without creating main() method?"
},
{
"code": null,
"e": 20879,
"s": 20686,
"text": "It is very important question from the interview’s perceptive point. The answer is yes we can print if we are using JDK version 1.6 or previous and if after that that it will throw an. error. "
},
{
"code": null,
"e": 20932,
"s": 20879,
"text": "Example 1-A: Running on JDK version 1.6 of Previous"
},
{
"code": null,
"e": 20937,
"s": 20932,
"text": "Java"
},
{
"code": "// Java Program Running on JDK version 1.6 of Previous // Main classclass GFG { // Static block static { // Print statement System.out.print( \"Static block can be printed without main method\"); }}",
"e": 21174,
"s": 20937,
"text": null
},
{
"code": null,
"e": 21182,
"s": 21174,
"text": "Output:"
},
{
"code": null,
"e": 21230,
"s": 21182,
"text": "Static block can be printed without main method"
},
{
"code": null,
"e": 21280,
"s": 21230,
"text": "Example 1-B: Running on JDK version 1.6 and Later"
},
{
"code": null,
"e": 21285,
"s": 21280,
"text": "Java"
},
{
"code": "// Java Program Running on JDK version 1.6 and Later // Main classclass GFG { // Static block static { // Print statement System.out.print( \"Static block can be printed without main method\"); }}",
"e": 21520,
"s": 21285,
"text": null
},
{
"code": null,
"e": 21529,
"s": 21520,
"text": "Output: "
},
{
"code": null,
"e": 21540,
"s": 21529,
"text": "Example 1:"
},
{
"code": null,
"e": 21545,
"s": 21540,
"text": "Java"
},
{
"code": "// Java Program to Illustrate How Static block is Called // Class 1// Helper classclass Test { // Case 1: Static variable static int i; // Case 2: non-static variables int j; // Case 3: Static block // Start of static block static { i = 10; System.out.println(\"static block called \"); } // End of static block} // Class 2// Main classclass GFG { // Main driver method public static void main(String args[]) { // Although we don't have an object of Test, static // block is called because i is being accessed in // following statement. System.out.println(Test.i); }}",
"e": 22199,
"s": 21545,
"text": null
},
{
"code": null,
"e": 22223,
"s": 22199,
"text": "static block called \n10"
},
{
"code": null,
"e": 22289,
"s": 22223,
"text": "Remember: Static blocks can also be executed before constructors."
},
{
"code": null,
"e": 22300,
"s": 22289,
"text": "Example 2:"
},
{
"code": null,
"e": 22305,
"s": 22300,
"text": "Java"
},
{
"code": "// Java Program to Illustrate Execution of Static Block// Before Constructors // Class 1// Helper classclass Test { // Case 1: Static variable static int i; // Case 2: Non-static variable int j; // Case 3: Static blocks static { i = 10; System.out.println(\"static block called \"); } // Constructor calling Test() { System.out.println(\"Constructor called\"); }} // Class 2// Main classclass GFG { // Main driver method public static void main(String args[]) { // Although we have two objects, static block is // executed only once. Test t1 = new Test(); Test t2 = new Test(); }}",
"e": 22971,
"s": 22305,
"text": null
},
{
"code": null,
"e": 23030,
"s": 22971,
"text": "static block called \nConstructor called\nConstructor called"
},
{
"code": null,
"e": 23264,
"s": 23030,
"text": "A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code."
},
{
"code": null,
"e": 23426,
"s": 23264,
"text": "Note: We use Initializer Block in Java if we want to execute a fragment of code for every object which is seen widely in enterprising industries in development. "
},
{
"code": null,
"e": 23551,
"s": 23426,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 23556,
"s": 23551,
"text": "Java"
},
{
"code": null,
"e": 23561,
"s": 23556,
"text": "Java"
},
{
"code": null,
"e": 23659,
"s": 23561,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 23674,
"s": 23659,
"text": "Arrays in Java"
},
{
"code": null,
"e": 23725,
"s": 23674,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 23769,
"s": 23725,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 23791,
"s": 23769,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 23827,
"s": 23791,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 23852,
"s": 23827,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 23870,
"s": 23852,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 23900,
"s": 23870,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 23932,
"s": 23900,
"text": "Multidimensional Arrays in Java"
}
] |
Check if elements of array can be made equal by multiplying given prime numbers - GeeksforGeeks
|
24 Mar, 2021
Given an array of integers and an array of prime numbers. The task is to find if it is possible to make all the elements of integer array equal by multiplying one or more elements from prime given array of prime numbers.Examples:
Input : arr[] = {50, 200}
prime[] = {2, 3}
Output : Yes
We can multiply 50 with 2 two times
to make both elements of arr[] equal
Input : arr[] = {3, 4, 5, 6, 2}
prime[] = {2, 3}
Output : No
We find LCM of all array elements. All elements can be made equal only if it is possible to convert all numbers to LCM. So we find the multiplier for each element so that we can make that element equal to LCM by multiplying that number. After that we find if numbers from given primes can form given multiplier.Algorithm- Step 1: Find LCM of all numbers in the array O(n)Step 2 : For each number arr[i] ——– Divide LCM by arr[i] ——– Use each input prime number to divide the result to remove all factors of input prime numbers (can use modulo to check divisibility) ——– If left over number is not 1, return false; Step 3 : Return trueBelow is the implementation of above algorithm.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find if array elements can// be made same#include<bits/stdc++.h>using namespace std; // To calculate LCM of whole arrayint lcmOfArray(int arr[], int n){ int ans = arr[0]; for (int i=1; i<n; i++) ans = (arr[i]*ans)/__gcd(arr[i], ans); return ans;} // function to check possibility if we can make// all element same or notbool checkArray(int arr[], int prime[], int n, int m){ // Find LCM of whole array int lcm = lcmOfArray(arr,n); // One by one check if value of lcm / arr[i] // can be formed using prime numbers. for (int i=0; i<n; i++) { // divide each element of array by LCM int val = lcm/arr[i]; // Use each input prime number to divide // the result to remove all factors of // input prime numbers for (int j=0; j<m && val!=1; j++) while (val % prime[j] == 0) val = val/prime[j]; // If the remaining value is not 1, then // it is not possible to make all elements // same. if (val != 1) return false; } return true;} // Driver codeint main(){ int arr[] = {50, 200}; int prime[] = {2, 3}; int n = sizeof(arr)/sizeof(arr[0]); int m = sizeof(prime)/sizeof(prime[0]); checkArray(arr, prime, n, m)? cout << "Yes" : cout << "No"; return 0;}
// Java program to find if array// elements can be made same class GFG{ static int ___gcd(int a, int b) { // Everything divides 0 if (a == 0 || b == 0) return 0; // base case if (a == b) return a; // a is greater if (a > b) return ___gcd(a - b, b); return ___gcd(a, b - a); } // To calculate LCM of whole array static int lcmOfArray(int arr[], int n) { int ans = arr[0]; for (int i = 1; i < n; i++) ans = (arr[i] * ans)/ ___gcd(arr[i], ans); return ans; } // function to check possibility if we can make // all element same or not static boolean checkArray(int arr[], int prime[], int n, int m) { // Find LCM of whole array int lcm = lcmOfArray(arr,n); // One by one check if value of lcm / arr[i] // can be formed using prime numbers. for (int i = 0; i < n; i++) { // divide each element of array by LCM int val = lcm / arr[i]; // Use each input prime number to divide // the result to remove all factors of // input prime numbers for (int j = 0; j < m && val != 1; j++) while (val % prime[j] == 0) val = val / prime[j]; // If the remaining value is not 1, then // it is not possible to make all elements // same. if (val != 1) return false; } return true; } // Driver code public static void main (String[] args) { int arr[] = {50, 200}; int prime[] = {2, 3}; int n = arr.length; int m = prime.length; if(checkArray(arr, prime, n, m)) System.out.print("Yes"); else System.out.print("No"); }} // This code is contributed by Anant Agarwal.
# Python program to find# if array elements can# be made same def ___gcd(a,b): # Everything divides 0 if (a == 0 or b == 0): return 0 # base case if (a == b): return a # a is greater if (a > b): return ___gcd(a-b, b) return ___gcd(a, b-a) # To calculate LCM of whole arraydef lcmOfArray(arr,n): ans = arr[0] for i in range(1,n): ans = (arr[i]*ans)/___gcd(arr[i], ans) return ans # function to check possibility# if we can make# all element same or notdef checkArray(arr, prime, n, m): # Find LCM of whole array lcm = lcmOfArray(arr, n) # One by one check if # value of lcm / arr[i] # can be formed using prime numbers. for i in range(n): # divide each element # of array by LCM val = lcm/arr[i] # Use each input prime # number to divide # the result to remove # all factors of # input prime numbers for j in range(m and val!=1): while (val % prime[j] == 0): val = val/prime[j] # If the remaining value # is not 1, then # it is not possible to # make all elements # same. if (val != 1): return 0 return 1 # Driver codearr = [50, 200]prime = [2, 3]n = len(arr)m = len(prime) if(checkArray(arr, prime, n, m)): print("Yes")else: print("No") # This code is contributed# by Anant Agarwal.
// C# program to find if array// elements can be made sameusing System; class GFG { static int ___gcd(int a, int b) { // Everything divides 0 if (a == 0 || b == 0) return 0; // base case if (a == b) return a; // a is greater if (a > b) return ___gcd(a - b, b); return ___gcd(a, b - a); } // To calculate LCM of whole array static int lcmOfArray(int []arr, int n) { int ans = arr[0]; for (int i = 1; i < n; i++) ans = ((arr[i] * ans) / ___gcd(arr[i], ans)); return ans; } // function to check possibility if // we can make all element same or not static bool checkArray(int []arr, int []prime, int n, int m) { // Find LCM of whole array int lcm = lcmOfArray(arr, n); // One by one check if value of // lcm / arr[i] can be formed // using prime numbers. for (int i = 0; i < n; i++) { // divide each element of // array by LCM int val = lcm / arr[i]; // Use each input prime number // to divide the result to // remove all factors of // input prime numbers for (int j = 0; j < m && val != 1; j++) while (val % prime[j] == 0) val = val / prime[j]; // If the remaining value is not 1, // then it is not possible to make // all elements same. if (val != 1) return false; } return true; } // Driver code public static void Main () { int []arr = {50, 200}; int []prime = {2, 3}; int n = arr.Length; int m = prime.Length; if(checkArray(arr, prime, n, m)) Console.Write("Yes"); else Console.Write("No"); }} // This code is contributed by nitin mittal
<?php// PHP program to find if// array elements can be// made same function ___gcd($a, $b){ // Everything divides 0 if ($a == 0 || $b == 0) return 0; // base case if ($a == $b) return $a; // a is greater if ($a > $b) return ___gcd($a - $b, $b); return ___gcd($a, $b - $a);} // To calculate LCM// of whole arrayfunction lcmOfArray($arr, $n){ $ans = $arr[0]; for ($i = 1; $i < $n; $i++) $ans = (($arr[$i] * $ans) / ___gcd($arr[$i], $ans)); return $ans;} // function to check// possibility if we// can make all element// same or notfunction checkArray($arr, $prime, $n, $m){ // Find LCM of // whole array $lcm = lcmOfArray($arr, $n); // One by one check if // value of lcm / arr[i] // can be formed using // prime numbers. for ($i = 0; $i < $n; $i++) { // divide each element // of array by LCM $val = $lcm / $arr[$i]; // Use each input prime // number to divide the // result to remove all // factors of input prime // numbers for ($j = 0; $j < $m && $val != 1; $j++) while ($val % $prime[$j] == 0) $val = $val / $prime[$j]; // If the remaining value // is not 1, then it is // not possible to make // all elements same. if ($val != 1) return false; } return true;} // Driver code$arr = array(50, 200);$prime = array(2, 3);$n = sizeof($arr);$m = sizeof($prime); if(checkArray($arr, $prime, $n, $m)) echo "Yes";else echo "No"; // This code is contributed// by akt_mit?>
<script> // Javascript program to find if array// elements can be made same function ___gcd(a, b) { // Everything divides 0 if (a == 0 || b == 0) return 0; // base case if (a == b) return a; // a is greater if (a > b) return ___gcd(a - b, b); return ___gcd(a, b - a); } // To calculate LCM of whole array function lcmOfArray(arr, n) { let ans = arr[0]; for (let i = 1; i < n; i++) ans = (arr[i] * ans)/ ___gcd(arr[i], ans); return ans; } // function to check possibility if we can make // all element same or not function checkArray(arr, prime, n, m) { // Find LCM of whole array let lcm = lcmOfArray(arr,n); // One by one check if value of lcm / arr[i] // can be formed using prime numbers. for (let i = 0; i < n; i++) { // divide each element of array by LCM let val = lcm / arr[i]; // Use each input prime number to divide // the result to remove all factors of // input prime numbers for (let j = 0; j < m && val != 1; j++) while (val % prime[j] == 0) val = val / prime[j]; // If the remaining value is not 1, then // it is not possible to make all elements // same. if (val != 1) return false; } return true; } // Driver Code let arr = [50, 200]; let prime = [2, 3]; let n = arr.length; let m = prime.length; if(checkArray(arr, prime, n, m)) document.write("Yes"); else document.write("No"); </script>
Output:
Yes
This article is contributed by Niteesh kumar. 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.
nitin mittal
jit_t
nidhi_biet
souravghosh0416
GCD-LCM
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Program to find sum of elements in a given array
Program for factorial of a number
Operators in C / C++
Algorithm to solve Rubik's Cube
Minimum number of jumps to reach end
Print all possible combinations of r elements in a given array of size n
The Knight's tour problem | Backtracking-1
Find minimum number of coins that make a given value
|
[
{
"code": null,
"e": 24662,
"s": 24634,
"text": "\n24 Mar, 2021"
},
{
"code": null,
"e": 24894,
"s": 24662,
"text": "Given an array of integers and an array of prime numbers. The task is to find if it is possible to make all the elements of integer array equal by multiplying one or more elements from prime given array of prime numbers.Examples: "
},
{
"code": null,
"e": 25107,
"s": 24894,
"text": "Input : arr[] = {50, 200} \n prime[] = {2, 3}\nOutput : Yes\nWe can multiply 50 with 2 two times\nto make both elements of arr[] equal\n\nInput : arr[] = {3, 4, 5, 6, 2} \n prime[] = {2, 3}\nOutput : No"
},
{
"code": null,
"e": 25791,
"s": 25109,
"text": "We find LCM of all array elements. All elements can be made equal only if it is possible to convert all numbers to LCM. So we find the multiplier for each element so that we can make that element equal to LCM by multiplying that number. After that we find if numbers from given primes can form given multiplier.Algorithm- Step 1: Find LCM of all numbers in the array O(n)Step 2 : For each number arr[i] ——– Divide LCM by arr[i] ——– Use each input prime number to divide the result to remove all factors of input prime numbers (can use modulo to check divisibility) ——– If left over number is not 1, return false; Step 3 : Return trueBelow is the implementation of above algorithm. "
},
{
"code": null,
"e": 25795,
"s": 25791,
"text": "C++"
},
{
"code": null,
"e": 25800,
"s": 25795,
"text": "Java"
},
{
"code": null,
"e": 25808,
"s": 25800,
"text": "Python3"
},
{
"code": null,
"e": 25811,
"s": 25808,
"text": "C#"
},
{
"code": null,
"e": 25815,
"s": 25811,
"text": "PHP"
},
{
"code": null,
"e": 25826,
"s": 25815,
"text": "Javascript"
},
{
"code": "// C++ program to find if array elements can// be made same#include<bits/stdc++.h>using namespace std; // To calculate LCM of whole arrayint lcmOfArray(int arr[], int n){ int ans = arr[0]; for (int i=1; i<n; i++) ans = (arr[i]*ans)/__gcd(arr[i], ans); return ans;} // function to check possibility if we can make// all element same or notbool checkArray(int arr[], int prime[], int n, int m){ // Find LCM of whole array int lcm = lcmOfArray(arr,n); // One by one check if value of lcm / arr[i] // can be formed using prime numbers. for (int i=0; i<n; i++) { // divide each element of array by LCM int val = lcm/arr[i]; // Use each input prime number to divide // the result to remove all factors of // input prime numbers for (int j=0; j<m && val!=1; j++) while (val % prime[j] == 0) val = val/prime[j]; // If the remaining value is not 1, then // it is not possible to make all elements // same. if (val != 1) return false; } return true;} // Driver codeint main(){ int arr[] = {50, 200}; int prime[] = {2, 3}; int n = sizeof(arr)/sizeof(arr[0]); int m = sizeof(prime)/sizeof(prime[0]); checkArray(arr, prime, n, m)? cout << \"Yes\" : cout << \"No\"; return 0;}",
"e": 27186,
"s": 25826,
"text": null
},
{
"code": "// Java program to find if array// elements can be made same class GFG{ static int ___gcd(int a, int b) { // Everything divides 0 if (a == 0 || b == 0) return 0; // base case if (a == b) return a; // a is greater if (a > b) return ___gcd(a - b, b); return ___gcd(a, b - a); } // To calculate LCM of whole array static int lcmOfArray(int arr[], int n) { int ans = arr[0]; for (int i = 1; i < n; i++) ans = (arr[i] * ans)/ ___gcd(arr[i], ans); return ans; } // function to check possibility if we can make // all element same or not static boolean checkArray(int arr[], int prime[], int n, int m) { // Find LCM of whole array int lcm = lcmOfArray(arr,n); // One by one check if value of lcm / arr[i] // can be formed using prime numbers. for (int i = 0; i < n; i++) { // divide each element of array by LCM int val = lcm / arr[i]; // Use each input prime number to divide // the result to remove all factors of // input prime numbers for (int j = 0; j < m && val != 1; j++) while (val % prime[j] == 0) val = val / prime[j]; // If the remaining value is not 1, then // it is not possible to make all elements // same. if (val != 1) return false; } return true; } // Driver code public static void main (String[] args) { int arr[] = {50, 200}; int prime[] = {2, 3}; int n = arr.length; int m = prime.length; if(checkArray(arr, prime, n, m)) System.out.print(\"Yes\"); else System.out.print(\"No\"); }} // This code is contributed by Anant Agarwal.",
"e": 29142,
"s": 27186,
"text": null
},
{
"code": "# Python program to find# if array elements can# be made same def ___gcd(a,b): # Everything divides 0 if (a == 0 or b == 0): return 0 # base case if (a == b): return a # a is greater if (a > b): return ___gcd(a-b, b) return ___gcd(a, b-a) # To calculate LCM of whole arraydef lcmOfArray(arr,n): ans = arr[0] for i in range(1,n): ans = (arr[i]*ans)/___gcd(arr[i], ans) return ans # function to check possibility# if we can make# all element same or notdef checkArray(arr, prime, n, m): # Find LCM of whole array lcm = lcmOfArray(arr, n) # One by one check if # value of lcm / arr[i] # can be formed using prime numbers. for i in range(n): # divide each element # of array by LCM val = lcm/arr[i] # Use each input prime # number to divide # the result to remove # all factors of # input prime numbers for j in range(m and val!=1): while (val % prime[j] == 0): val = val/prime[j] # If the remaining value # is not 1, then # it is not possible to # make all elements # same. if (val != 1): return 0 return 1 # Driver codearr = [50, 200]prime = [2, 3]n = len(arr)m = len(prime) if(checkArray(arr, prime, n, m)): print(\"Yes\")else: print(\"No\") # This code is contributed# by Anant Agarwal.",
"e": 30580,
"s": 29142,
"text": null
},
{
"code": "// C# program to find if array// elements can be made sameusing System; class GFG { static int ___gcd(int a, int b) { // Everything divides 0 if (a == 0 || b == 0) return 0; // base case if (a == b) return a; // a is greater if (a > b) return ___gcd(a - b, b); return ___gcd(a, b - a); } // To calculate LCM of whole array static int lcmOfArray(int []arr, int n) { int ans = arr[0]; for (int i = 1; i < n; i++) ans = ((arr[i] * ans) / ___gcd(arr[i], ans)); return ans; } // function to check possibility if // we can make all element same or not static bool checkArray(int []arr, int []prime, int n, int m) { // Find LCM of whole array int lcm = lcmOfArray(arr, n); // One by one check if value of // lcm / arr[i] can be formed // using prime numbers. for (int i = 0; i < n; i++) { // divide each element of // array by LCM int val = lcm / arr[i]; // Use each input prime number // to divide the result to // remove all factors of // input prime numbers for (int j = 0; j < m && val != 1; j++) while (val % prime[j] == 0) val = val / prime[j]; // If the remaining value is not 1, // then it is not possible to make // all elements same. if (val != 1) return false; } return true; } // Driver code public static void Main () { int []arr = {50, 200}; int []prime = {2, 3}; int n = arr.Length; int m = prime.Length; if(checkArray(arr, prime, n, m)) Console.Write(\"Yes\"); else Console.Write(\"No\"); }} // This code is contributed by nitin mittal",
"e": 32668,
"s": 30580,
"text": null
},
{
"code": "<?php// PHP program to find if// array elements can be// made same function ___gcd($a, $b){ // Everything divides 0 if ($a == 0 || $b == 0) return 0; // base case if ($a == $b) return $a; // a is greater if ($a > $b) return ___gcd($a - $b, $b); return ___gcd($a, $b - $a);} // To calculate LCM// of whole arrayfunction lcmOfArray($arr, $n){ $ans = $arr[0]; for ($i = 1; $i < $n; $i++) $ans = (($arr[$i] * $ans) / ___gcd($arr[$i], $ans)); return $ans;} // function to check// possibility if we// can make all element// same or notfunction checkArray($arr, $prime, $n, $m){ // Find LCM of // whole array $lcm = lcmOfArray($arr, $n); // One by one check if // value of lcm / arr[i] // can be formed using // prime numbers. for ($i = 0; $i < $n; $i++) { // divide each element // of array by LCM $val = $lcm / $arr[$i]; // Use each input prime // number to divide the // result to remove all // factors of input prime // numbers for ($j = 0; $j < $m && $val != 1; $j++) while ($val % $prime[$j] == 0) $val = $val / $prime[$j]; // If the remaining value // is not 1, then it is // not possible to make // all elements same. if ($val != 1) return false; } return true;} // Driver code$arr = array(50, 200);$prime = array(2, 3);$n = sizeof($arr);$m = sizeof($prime); if(checkArray($arr, $prime, $n, $m)) echo \"Yes\";else echo \"No\"; // This code is contributed// by akt_mit?>",
"e": 34373,
"s": 32668,
"text": null
},
{
"code": "<script> // Javascript program to find if array// elements can be made same function ___gcd(a, b) { // Everything divides 0 if (a == 0 || b == 0) return 0; // base case if (a == b) return a; // a is greater if (a > b) return ___gcd(a - b, b); return ___gcd(a, b - a); } // To calculate LCM of whole array function lcmOfArray(arr, n) { let ans = arr[0]; for (let i = 1; i < n; i++) ans = (arr[i] * ans)/ ___gcd(arr[i], ans); return ans; } // function to check possibility if we can make // all element same or not function checkArray(arr, prime, n, m) { // Find LCM of whole array let lcm = lcmOfArray(arr,n); // One by one check if value of lcm / arr[i] // can be formed using prime numbers. for (let i = 0; i < n; i++) { // divide each element of array by LCM let val = lcm / arr[i]; // Use each input prime number to divide // the result to remove all factors of // input prime numbers for (let j = 0; j < m && val != 1; j++) while (val % prime[j] == 0) val = val / prime[j]; // If the remaining value is not 1, then // it is not possible to make all elements // same. if (val != 1) return false; } return true; } // Driver Code let arr = [50, 200]; let prime = [2, 3]; let n = arr.length; let m = prime.length; if(checkArray(arr, prime, n, m)) document.write(\"Yes\"); else document.write(\"No\"); </script>",
"e": 36172,
"s": 34373,
"text": null
},
{
"code": null,
"e": 36181,
"s": 36172,
"text": "Output: "
},
{
"code": null,
"e": 36185,
"s": 36181,
"text": "Yes"
},
{
"code": null,
"e": 36611,
"s": 36185,
"text": "This article is contributed by Niteesh kumar. 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. "
},
{
"code": null,
"e": 36624,
"s": 36611,
"text": "nitin mittal"
},
{
"code": null,
"e": 36630,
"s": 36624,
"text": "jit_t"
},
{
"code": null,
"e": 36641,
"s": 36630,
"text": "nidhi_biet"
},
{
"code": null,
"e": 36657,
"s": 36641,
"text": "souravghosh0416"
},
{
"code": null,
"e": 36665,
"s": 36657,
"text": "GCD-LCM"
},
{
"code": null,
"e": 36678,
"s": 36665,
"text": "Mathematical"
},
{
"code": null,
"e": 36691,
"s": 36678,
"text": "Mathematical"
},
{
"code": null,
"e": 36789,
"s": 36691,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36798,
"s": 36789,
"text": "Comments"
},
{
"code": null,
"e": 36811,
"s": 36798,
"text": "Old Comments"
},
{
"code": null,
"e": 36835,
"s": 36811,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 36878,
"s": 36835,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 36927,
"s": 36878,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 36961,
"s": 36927,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 36982,
"s": 36961,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 37014,
"s": 36982,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 37051,
"s": 37014,
"text": "Minimum number of jumps to reach end"
},
{
"code": null,
"e": 37124,
"s": 37051,
"text": "Print all possible combinations of r elements in a given array of size n"
},
{
"code": null,
"e": 37167,
"s": 37124,
"text": "The Knight's tour problem | Backtracking-1"
}
] |
Import Statement in Java
|
13 May, 2022
Import statement in Java is helpful to take a class or all classes visible for a program specified under a package, with the help of a single statement. It is pretty beneficial as the programmer do not require to write the entire class definition. Hence, it improves the readability of the program.
This article focuses on the import statements used in the Java programs and their alternatives.
Syntax 1:
import package1[.package2].(*);
Here,
package1: Top-level package
package2: Subordinate-level package under package1
*: To import all the classes
Syntax 2:
import package1[.package2].(myClass);
Here,
package1: Top-level package
package2: Subordinate-level package under the top-level package
myClass: Import only myClass
Note: Either we can import a class or we can import all classes specified under the package.
To understand why we do we need to bring a class or classes into visibility, let us consider a Java program without the use of an import statement:
Source Code:
Java
// Java program to demonstrate the// working of a program// without any import statement class GFG { // Main method public static void main(String[] args) { // Declaring an ArrayList of String type ArrayList<String> arrayList = new ArrayList<String>(); // Adding elements in the ArrayList arrayList.add("Geeks"); arrayList.add("For"); arrayList.add("Geeks"); // Print the ArrayList System.out.println("ArrayList: " + arrayList); }}
Let us compile the above program:
Compiler Verdict:
prog.java:11: error: cannot find symbol
ArrayList<String> arrayList
^
symbol: class ArrayList
location: class GFG
prog.java:12: error: cannot find symbol
= new ArrayList<String>();
^
symbol: class ArrayList
location: class GFG
2 errors
Compilation Description: We get the compile-time error. The Javac compiler couldn’t find the ArrayList class in the program. ArrayList class is a part of the java.util package. So we need to include the ArrayList class defined under Java.util package in our program.
Following are three ways to refer an external class or all external classes specified under a package:
The import statement is optional, and we can use the fully-qualified name of the class to refer to a class or package in the program. This method tells the compiler that the class is defined under a particular package, and we want to use that class or classes in our program. Each time we want to use a data member or member function defined in the class, we need to refer to it using a fully-qualified name. It increases the code size of our program and hence makes it less readable. This is the only disadvantage of this method.
Example: Below is the implementation using a fully-qualified name for the class ArrayList defined under Java.util package:
Java
// Java program to demonstrate the working of a program// using fully-qualified name or without the use of import// statement class GFG { // Main method public static void main(String[] args) { // Using fully-qualified name // Declaring an ArrayList of String type java.util.ArrayList<String> arrayList = new java.util.ArrayList<String>(); // Adding elements in the ArrayList arrayList.add("Geeks"); arrayList.add("For"); arrayList.add("Geeks"); // Print the ArrayList System.out.println("ArrayList: " + arrayList); }}
ArrayList: [Geeks, For, Geeks]
An import statement tells the compiler the path of a class or the entire package. It is unlike “#include” in C++, which includes the entire code in the program. Import statement tells the compiler that we want to use a class (or classes) that is defined under a package. It is pretty helpful and recommended over the “fully-qualified name” method as it reduces the overall code size and improves the source code’s readability.
Below is the implementation to illustrate how we can import a class into our program:
Java
// Java program to demonstrate the// working of import statement // Importing ArrayList class specified// under java.util packageimport java.util.ArrayList; class GFG { // Main method public static void main(String[] args) { // Declaring an ArrayList of String type ArrayList<String> arrayList = new ArrayList<String>(); // Adding elements in the ArrayList arrayList.add("Geeks"); arrayList.add("For"); arrayList.add("Geeks"); // Print the ArrayList System.out.println("ArrayList: " + arrayList); }}
ArrayList: [Geeks, For, Geeks]
Below is the implementation to illustrate how we can import all classes into our program:
Source Code:
Java
// Java program to demonstrate the// working of import statement // Importing all classes specified under java.util packageimport java.util.*; class GFG { // Static function to print array elements public static void print(int array[]) { System.out.print("Array: [ "); for (int i = 0; i < 5; i++) System.out.print(array[i] + " "); System.out.print("]"); } // main method public static void main(String[] args) { // Declaring an ArrayList of String type ArrayList<String> arrayList = new ArrayList<String>(); // Adding elements in the ArrayList arrayList.add("Geeks"); arrayList.add("For"); arrayList.add("Geeks"); // Declaring an array of integers int array[] = { 10, 3, 5, 11, 20 }; // sort function defined under Arrays class Arrays.sort(array); // Print the ArrayList System.out.println("ArrayList: " + arrayList); // Calling print() function print(array); }}
ArrayList: [Geeks, For, Geeks]
Array: [ 3 5 10 11 20 ]
Let us now see the working of the import statement by creating our custom package and a class inside it. We can include the following statement before all class definitions to bundle a program into a package.
package myPackage;
Here,
myPackage: Name of the package
Below is the implementation to illustrate how we can import a class by creating our custom package:
Java
// Statement to create a packagepackage CustomPackage; // Public classpublic class ComputerScienceDepartment { String name; int marks; // user defined constructor method public ComputerScienceDepartment(String studentName, int studentMarks) { // Assigning values to data // members with the help of // values passed to the constructor name = studentName; marks = studentMarks; } // Display method to display student's information public void display() { System.out.println("Name: " + name + '\n' + "Marks : " + marks + '\n' + "Department: " + "Computer Science" + '\n'); }}
We have created the above Java source file locally on our system and saved it as ComputerScienceDepartment.java:
Java Source Code file
Let us now compile the program using the javac compiler and bundle it as a package through command prompt,
javac ComputerScienceDepartment.java
javac -d . ComputerScienceDepartment.java
Compilation of the program
CustomPackage folder
Compilation Description: As you can see in the above picture, the CustomPackage folder is generated, which contains ComputerScienceDepartment.class byte code file. This file is later executed by a Java interpreter(JVM). Now the package is ready, and we can create another program and import this package into the program.
Below is the source code which includes/imports the ComputerScienceDepartment class defined under CustomPackage in the program:
Java
// Import the public class defined under// the created package (CustomPackage)import CustomPackage.ComputerScienceDepartment; class GeeksforGeeks { // main method public static void main(String args[]) { // Initializing a variable by passing name // and marks of the student as an argument to // the constructor ComputerScienceDepartment student1 = new ComputerScienceDepartment("Geeks", 97); // Using display() method defined under // ComputerScienceDepartment class to print sudent1 // information student1 .display(); // you may also call the display() // Initializing another variable by passing name // and marks of the student as an argument to // the constructor ComputerScienceDepartment student2 = new ComputerScienceDepartment("GeeksforGeeks", 100); // Using display() method defined under // ComputerScienceDepartment class to print sudent2 // information student2 .display(); // you may also call the display() }}
We have created the above Java source file locally on our system and saved it as GeeksforGeeks.java:
Java Source Code file that imports the class defined under the CustomPackage
Let us now compile the program using the javac compiler and run it through command prompt,
javac GeeksforGeeks.java
java GeeksforGeeks
Output:
Output
By using static import statements in Java, we can access data members or member functions of a class directly without the use of a fully-qualified name.
Below is the implementation in which we are accessing the abs() method under the Math class without any use of static import statement and by using fully-qualified name:
Java
// Java program to illustrate the working// of static import statement class GFG { // Main method public static void main(String[] args) { // Initializing two variables of integer type int number1 = 10; int number2 = 20; // Using fully-qualified name to access // abs() method - Math.abs() System.out.println( "Absolute difference of number1 and number2 is: " + Math.abs(number1 - number2)); }}
Absolute difference of number1 and number2 is: 10
Below is the implementation using a static import statement.
Java
// Java program to illustrate the working// of static import statement // Import static statementimport static java.lang.Math.*;class GFG { // Main method public static void main(String[] args) { // Initializing two variables of integer type int number1 = 10; int number2 = 20; // Directly accessing abs() method without using // fully-qualified name System.out.println( "Absolute difference of number1 and number2 is: " + abs(number1 - number2)); }}
Absolute difference of number1 and number2 is: 10
Import statements help in reducing the code size and hence save a lot of time.
It improves the readability of our code.
It is pretty useful while handling big projects.
They can be used to combine the functionality of several classes into one.
simmytarika5
sagartomar9927
Java-Packages
Picked
Java
Java
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": 28,
"s": 0,
"text": "\n13 May, 2022"
},
{
"code": null,
"e": 328,
"s": 28,
"text": "Import statement in Java is helpful to take a class or all classes visible for a program specified under a package, with the help of a single statement. It is pretty beneficial as the programmer do not require to write the entire class definition. Hence, it improves the readability of the program. "
},
{
"code": null,
"e": 424,
"s": 328,
"text": "This article focuses on the import statements used in the Java programs and their alternatives."
},
{
"code": null,
"e": 434,
"s": 424,
"text": "Syntax 1:"
},
{
"code": null,
"e": 466,
"s": 434,
"text": "import package1[.package2].(*);"
},
{
"code": null,
"e": 472,
"s": 466,
"text": "Here,"
},
{
"code": null,
"e": 500,
"s": 472,
"text": "package1: Top-level package"
},
{
"code": null,
"e": 551,
"s": 500,
"text": "package2: Subordinate-level package under package1"
},
{
"code": null,
"e": 580,
"s": 551,
"text": "*: To import all the classes"
},
{
"code": null,
"e": 590,
"s": 580,
"text": "Syntax 2:"
},
{
"code": null,
"e": 628,
"s": 590,
"text": "import package1[.package2].(myClass);"
},
{
"code": null,
"e": 634,
"s": 628,
"text": "Here,"
},
{
"code": null,
"e": 662,
"s": 634,
"text": "package1: Top-level package"
},
{
"code": null,
"e": 726,
"s": 662,
"text": "package2: Subordinate-level package under the top-level package"
},
{
"code": null,
"e": 756,
"s": 726,
"text": "myClass: Import only myClass "
},
{
"code": null,
"e": 849,
"s": 756,
"text": "Note: Either we can import a class or we can import all classes specified under the package."
},
{
"code": null,
"e": 997,
"s": 849,
"text": "To understand why we do we need to bring a class or classes into visibility, let us consider a Java program without the use of an import statement:"
},
{
"code": null,
"e": 1010,
"s": 997,
"text": "Source Code:"
},
{
"code": null,
"e": 1015,
"s": 1010,
"text": "Java"
},
{
"code": "// Java program to demonstrate the// working of a program// without any import statement class GFG { // Main method public static void main(String[] args) { // Declaring an ArrayList of String type ArrayList<String> arrayList = new ArrayList<String>(); // Adding elements in the ArrayList arrayList.add(\"Geeks\"); arrayList.add(\"For\"); arrayList.add(\"Geeks\"); // Print the ArrayList System.out.println(\"ArrayList: \" + arrayList); }}",
"e": 1529,
"s": 1015,
"text": null
},
{
"code": null,
"e": 1563,
"s": 1529,
"text": "Let us compile the above program:"
},
{
"code": null,
"e": 1581,
"s": 1563,
"text": "Compiler Verdict:"
},
{
"code": null,
"e": 1871,
"s": 1581,
"text": "prog.java:11: error: cannot find symbol\n ArrayList<String> arrayList\n ^\n symbol: class ArrayList\n location: class GFG\n \nprog.java:12: error: cannot find symbol\n = new ArrayList<String>();\n ^\n symbol: class ArrayList\n location: class GFG\n \n2 errors"
},
{
"code": null,
"e": 2139,
"s": 1871,
"text": "Compilation Description: We get the compile-time error. The Javac compiler couldn’t find the ArrayList class in the program. ArrayList class is a part of the java.util package. So we need to include the ArrayList class defined under Java.util package in our program."
},
{
"code": null,
"e": 2242,
"s": 2139,
"text": "Following are three ways to refer an external class or all external classes specified under a package:"
},
{
"code": null,
"e": 2774,
"s": 2242,
"text": "The import statement is optional, and we can use the fully-qualified name of the class to refer to a class or package in the program. This method tells the compiler that the class is defined under a particular package, and we want to use that class or classes in our program. Each time we want to use a data member or member function defined in the class, we need to refer to it using a fully-qualified name. It increases the code size of our program and hence makes it less readable. This is the only disadvantage of this method. "
},
{
"code": null,
"e": 2897,
"s": 2774,
"text": "Example: Below is the implementation using a fully-qualified name for the class ArrayList defined under Java.util package:"
},
{
"code": null,
"e": 2902,
"s": 2897,
"text": "Java"
},
{
"code": "// Java program to demonstrate the working of a program// using fully-qualified name or without the use of import// statement class GFG { // Main method public static void main(String[] args) { // Using fully-qualified name // Declaring an ArrayList of String type java.util.ArrayList<String> arrayList = new java.util.ArrayList<String>(); // Adding elements in the ArrayList arrayList.add(\"Geeks\"); arrayList.add(\"For\"); arrayList.add(\"Geeks\"); // Print the ArrayList System.out.println(\"ArrayList: \" + arrayList); }}",
"e": 3510,
"s": 2902,
"text": null
},
{
"code": null,
"e": 3541,
"s": 3510,
"text": "ArrayList: [Geeks, For, Geeks]"
},
{
"code": null,
"e": 3968,
"s": 3541,
"text": "An import statement tells the compiler the path of a class or the entire package. It is unlike “#include” in C++, which includes the entire code in the program. Import statement tells the compiler that we want to use a class (or classes) that is defined under a package. It is pretty helpful and recommended over the “fully-qualified name” method as it reduces the overall code size and improves the source code’s readability."
},
{
"code": null,
"e": 4054,
"s": 3968,
"text": "Below is the implementation to illustrate how we can import a class into our program:"
},
{
"code": null,
"e": 4059,
"s": 4054,
"text": "Java"
},
{
"code": "// Java program to demonstrate the// working of import statement // Importing ArrayList class specified// under java.util packageimport java.util.ArrayList; class GFG { // Main method public static void main(String[] args) { // Declaring an ArrayList of String type ArrayList<String> arrayList = new ArrayList<String>(); // Adding elements in the ArrayList arrayList.add(\"Geeks\"); arrayList.add(\"For\"); arrayList.add(\"Geeks\"); // Print the ArrayList System.out.println(\"ArrayList: \" + arrayList); }}",
"e": 4641,
"s": 4059,
"text": null
},
{
"code": null,
"e": 4672,
"s": 4641,
"text": "ArrayList: [Geeks, For, Geeks]"
},
{
"code": null,
"e": 4762,
"s": 4672,
"text": "Below is the implementation to illustrate how we can import all classes into our program:"
},
{
"code": null,
"e": 4775,
"s": 4762,
"text": "Source Code:"
},
{
"code": null,
"e": 4780,
"s": 4775,
"text": "Java"
},
{
"code": "// Java program to demonstrate the// working of import statement // Importing all classes specified under java.util packageimport java.util.*; class GFG { // Static function to print array elements public static void print(int array[]) { System.out.print(\"Array: [ \"); for (int i = 0; i < 5; i++) System.out.print(array[i] + \" \"); System.out.print(\"]\"); } // main method public static void main(String[] args) { // Declaring an ArrayList of String type ArrayList<String> arrayList = new ArrayList<String>(); // Adding elements in the ArrayList arrayList.add(\"Geeks\"); arrayList.add(\"For\"); arrayList.add(\"Geeks\"); // Declaring an array of integers int array[] = { 10, 3, 5, 11, 20 }; // sort function defined under Arrays class Arrays.sort(array); // Print the ArrayList System.out.println(\"ArrayList: \" + arrayList); // Calling print() function print(array); }}",
"e": 5820,
"s": 4780,
"text": null
},
{
"code": null,
"e": 5875,
"s": 5820,
"text": "ArrayList: [Geeks, For, Geeks]\nArray: [ 3 5 10 11 20 ]"
},
{
"code": null,
"e": 6084,
"s": 5875,
"text": "Let us now see the working of the import statement by creating our custom package and a class inside it. We can include the following statement before all class definitions to bundle a program into a package."
},
{
"code": null,
"e": 6103,
"s": 6084,
"text": "package myPackage;"
},
{
"code": null,
"e": 6110,
"s": 6103,
"text": "Here, "
},
{
"code": null,
"e": 6141,
"s": 6110,
"text": "myPackage: Name of the package"
},
{
"code": null,
"e": 6241,
"s": 6141,
"text": "Below is the implementation to illustrate how we can import a class by creating our custom package:"
},
{
"code": null,
"e": 6246,
"s": 6241,
"text": "Java"
},
{
"code": "// Statement to create a packagepackage CustomPackage; // Public classpublic class ComputerScienceDepartment { String name; int marks; // user defined constructor method public ComputerScienceDepartment(String studentName, int studentMarks) { // Assigning values to data // members with the help of // values passed to the constructor name = studentName; marks = studentMarks; } // Display method to display student's information public void display() { System.out.println(\"Name: \" + name + '\\n' + \"Marks : \" + marks + '\\n' + \"Department: \" + \"Computer Science\" + '\\n'); }}",
"e": 7008,
"s": 6246,
"text": null
},
{
"code": null,
"e": 7122,
"s": 7008,
"text": "We have created the above Java source file locally on our system and saved it as ComputerScienceDepartment.java: "
},
{
"code": null,
"e": 7144,
"s": 7122,
"text": "Java Source Code file"
},
{
"code": null,
"e": 7251,
"s": 7144,
"text": "Let us now compile the program using the javac compiler and bundle it as a package through command prompt,"
},
{
"code": null,
"e": 7331,
"s": 7251,
"text": "javac ComputerScienceDepartment.java \njavac -d . ComputerScienceDepartment.java"
},
{
"code": null,
"e": 7358,
"s": 7331,
"text": "Compilation of the program"
},
{
"code": null,
"e": 7379,
"s": 7358,
"text": "CustomPackage folder"
},
{
"code": null,
"e": 7701,
"s": 7379,
"text": "Compilation Description: As you can see in the above picture, the CustomPackage folder is generated, which contains ComputerScienceDepartment.class byte code file. This file is later executed by a Java interpreter(JVM). Now the package is ready, and we can create another program and import this package into the program."
},
{
"code": null,
"e": 7829,
"s": 7701,
"text": "Below is the source code which includes/imports the ComputerScienceDepartment class defined under CustomPackage in the program:"
},
{
"code": null,
"e": 7834,
"s": 7829,
"text": "Java"
},
{
"code": "// Import the public class defined under// the created package (CustomPackage)import CustomPackage.ComputerScienceDepartment; class GeeksforGeeks { // main method public static void main(String args[]) { // Initializing a variable by passing name // and marks of the student as an argument to // the constructor ComputerScienceDepartment student1 = new ComputerScienceDepartment(\"Geeks\", 97); // Using display() method defined under // ComputerScienceDepartment class to print sudent1 // information student1 .display(); // you may also call the display() // Initializing another variable by passing name // and marks of the student as an argument to // the constructor ComputerScienceDepartment student2 = new ComputerScienceDepartment(\"GeeksforGeeks\", 100); // Using display() method defined under // ComputerScienceDepartment class to print sudent2 // information student2 .display(); // you may also call the display() }}",
"e": 8974,
"s": 7834,
"text": null
},
{
"code": null,
"e": 9076,
"s": 8974,
"text": "We have created the above Java source file locally on our system and saved it as GeeksforGeeks.java: "
},
{
"code": null,
"e": 9153,
"s": 9076,
"text": "Java Source Code file that imports the class defined under the CustomPackage"
},
{
"code": null,
"e": 9244,
"s": 9153,
"text": "Let us now compile the program using the javac compiler and run it through command prompt,"
},
{
"code": null,
"e": 9289,
"s": 9244,
"text": "javac GeeksforGeeks.java \njava GeeksforGeeks"
},
{
"code": null,
"e": 9297,
"s": 9289,
"text": "Output:"
},
{
"code": null,
"e": 9304,
"s": 9297,
"text": "Output"
},
{
"code": null,
"e": 9457,
"s": 9304,
"text": "By using static import statements in Java, we can access data members or member functions of a class directly without the use of a fully-qualified name."
},
{
"code": null,
"e": 9627,
"s": 9457,
"text": "Below is the implementation in which we are accessing the abs() method under the Math class without any use of static import statement and by using fully-qualified name:"
},
{
"code": null,
"e": 9632,
"s": 9627,
"text": "Java"
},
{
"code": "// Java program to illustrate the working// of static import statement class GFG { // Main method public static void main(String[] args) { // Initializing two variables of integer type int number1 = 10; int number2 = 20; // Using fully-qualified name to access // abs() method - Math.abs() System.out.println( \"Absolute difference of number1 and number2 is: \" + Math.abs(number1 - number2)); }}",
"e": 10105,
"s": 9632,
"text": null
},
{
"code": null,
"e": 10155,
"s": 10105,
"text": "Absolute difference of number1 and number2 is: 10"
},
{
"code": null,
"e": 10216,
"s": 10155,
"text": "Below is the implementation using a static import statement."
},
{
"code": null,
"e": 10221,
"s": 10216,
"text": "Java"
},
{
"code": "// Java program to illustrate the working// of static import statement // Import static statementimport static java.lang.Math.*;class GFG { // Main method public static void main(String[] args) { // Initializing two variables of integer type int number1 = 10; int number2 = 20; // Directly accessing abs() method without using // fully-qualified name System.out.println( \"Absolute difference of number1 and number2 is: \" + abs(number1 - number2)); }}",
"e": 10752,
"s": 10221,
"text": null
},
{
"code": null,
"e": 10802,
"s": 10752,
"text": "Absolute difference of number1 and number2 is: 10"
},
{
"code": null,
"e": 10881,
"s": 10802,
"text": "Import statements help in reducing the code size and hence save a lot of time."
},
{
"code": null,
"e": 10922,
"s": 10881,
"text": "It improves the readability of our code."
},
{
"code": null,
"e": 10972,
"s": 10922,
"text": "It is pretty useful while handling big projects. "
},
{
"code": null,
"e": 11047,
"s": 10972,
"text": "They can be used to combine the functionality of several classes into one."
},
{
"code": null,
"e": 11060,
"s": 11047,
"text": "simmytarika5"
},
{
"code": null,
"e": 11075,
"s": 11060,
"text": "sagartomar9927"
},
{
"code": null,
"e": 11089,
"s": 11075,
"text": "Java-Packages"
},
{
"code": null,
"e": 11096,
"s": 11089,
"text": "Picked"
},
{
"code": null,
"e": 11101,
"s": 11096,
"text": "Java"
},
{
"code": null,
"e": 11106,
"s": 11101,
"text": "Java"
},
{
"code": null,
"e": 11204,
"s": 11106,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11219,
"s": 11204,
"text": "Stream In Java"
},
{
"code": null,
"e": 11240,
"s": 11219,
"text": "Introduction to Java"
},
{
"code": null,
"e": 11261,
"s": 11240,
"text": "Constructors in Java"
},
{
"code": null,
"e": 11280,
"s": 11261,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 11297,
"s": 11280,
"text": "Generics in Java"
},
{
"code": null,
"e": 11327,
"s": 11297,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 11353,
"s": 11327,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 11369,
"s": 11353,
"text": "Strings in Java"
},
{
"code": null,
"e": 11406,
"s": 11369,
"text": "Differences between JDK, JRE and JVM"
}
] |
Components of Data Communication System
|
25 Jun, 2020
Data Communication is defined as exchange of data between two devices via some form of transmission media such as a cable, wire or it can be air or vacuum also. For occurrence of data communication, communicating devices must be a part of communication system made up of a combination of hardware or software devices and programs.
Data Communication System Components :There are mainly five components of a data communication system:
1. Message
2. Sender
3. Receiver
4. Transmission Medium
5. Set of rules (Protocol)
All above mentioned elements are described below:
Message :This is most useful asset of a data communication system. The message simply refers to data or piece of information which is to be communicated. A message could be in any form, it may be in form of a text file, an audio file, a video file, etc.Sender :To transfer message from source to destination, someone must be there who will play role of a source. Sender plays part of a source in data communication system. It is simple a device that sends data message. The device could be in form of a computer, mobile, telephone, laptop, video camera, or a workstation, etc.Receiver :It is destination where finally message sent by source has arrived. It is a device that receives message. Same as sender, receiver can also be in form of a computer, telephone mobile, workstation, etc.Transmission Medium :In entire process of data communication, there must be something which could act as a bridge between sender and receiver, Transmission medium plays that part. It is physical path by which data or message travels from sender to receiver. Transmission medium could be guided (with wires) or unguided (without wires), for example, twisted pair cable, fiber optic cable, radio waves, microwaves, etc.Set of rules (Protocol) :To govern data communications, various sets of rules had been already designed by the designers of the communication systems, which represent a kind of agreement between communicating devices. These are defined as protocol. In simple terms, the protocol is a set of rules that govern data communication. If two different devices are connected but there is no protocol among them, there would not be any kind of communication between those two devices. Thus the protocol is necessary for data communication to take place.
Message :This is most useful asset of a data communication system. The message simply refers to data or piece of information which is to be communicated. A message could be in any form, it may be in form of a text file, an audio file, a video file, etc.
Sender :To transfer message from source to destination, someone must be there who will play role of a source. Sender plays part of a source in data communication system. It is simple a device that sends data message. The device could be in form of a computer, mobile, telephone, laptop, video camera, or a workstation, etc.
Receiver :It is destination where finally message sent by source has arrived. It is a device that receives message. Same as sender, receiver can also be in form of a computer, telephone mobile, workstation, etc.
Transmission Medium :In entire process of data communication, there must be something which could act as a bridge between sender and receiver, Transmission medium plays that part. It is physical path by which data or message travels from sender to receiver. Transmission medium could be guided (with wires) or unguided (without wires), for example, twisted pair cable, fiber optic cable, radio waves, microwaves, etc.
Set of rules (Protocol) :To govern data communications, various sets of rules had been already designed by the designers of the communication systems, which represent a kind of agreement between communicating devices. These are defined as protocol. In simple terms, the protocol is a set of rules that govern data communication. If two different devices are connected but there is no protocol among them, there would not be any kind of communication between those two devices. Thus the protocol is necessary for data communication to take place.
A typical example of a data communication system is sending an e-mail. The user which send email act as sender, message is data which user wants to send, receiver is one whom user wants to send message, there are many protocols involved in this entire process, one of them is Simple Mail Transfer Protocol (SMTP), both sender and receiver must have an internet connection which uses a wireless medium to send and receive email.
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Differences between TCP and UDP
RSA Algorithm in Cryptography
TCP Server-Client implementation in C
GSM in Wireless Communication
Socket Programming in Python
Differences between IPv4 and IPv6
Secure Socket Layer (SSL)
Wireless Application Protocol
Mobile Internet Protocol (or Mobile IP)
Data encryption standard (DES) | Set 1
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n25 Jun, 2020"
},
{
"code": null,
"e": 384,
"s": 53,
"text": "Data Communication is defined as exchange of data between two devices via some form of transmission media such as a cable, wire or it can be air or vacuum also. For occurrence of data communication, communicating devices must be a part of communication system made up of a combination of hardware or software devices and programs."
},
{
"code": null,
"e": 487,
"s": 384,
"text": "Data Communication System Components :There are mainly five components of a data communication system:"
},
{
"code": null,
"e": 571,
"s": 487,
"text": "1. Message\n2. Sender\n3. Receiver\n4. Transmission Medium\n5. Set of rules (Protocol) "
},
{
"code": null,
"e": 621,
"s": 571,
"text": "All above mentioned elements are described below:"
},
{
"code": null,
"e": 2371,
"s": 621,
"text": "Message :This is most useful asset of a data communication system. The message simply refers to data or piece of information which is to be communicated. A message could be in any form, it may be in form of a text file, an audio file, a video file, etc.Sender :To transfer message from source to destination, someone must be there who will play role of a source. Sender plays part of a source in data communication system. It is simple a device that sends data message. The device could be in form of a computer, mobile, telephone, laptop, video camera, or a workstation, etc.Receiver :It is destination where finally message sent by source has arrived. It is a device that receives message. Same as sender, receiver can also be in form of a computer, telephone mobile, workstation, etc.Transmission Medium :In entire process of data communication, there must be something which could act as a bridge between sender and receiver, Transmission medium plays that part. It is physical path by which data or message travels from sender to receiver. Transmission medium could be guided (with wires) or unguided (without wires), for example, twisted pair cable, fiber optic cable, radio waves, microwaves, etc.Set of rules (Protocol) :To govern data communications, various sets of rules had been already designed by the designers of the communication systems, which represent a kind of agreement between communicating devices. These are defined as protocol. In simple terms, the protocol is a set of rules that govern data communication. If two different devices are connected but there is no protocol among them, there would not be any kind of communication between those two devices. Thus the protocol is necessary for data communication to take place."
},
{
"code": null,
"e": 2625,
"s": 2371,
"text": "Message :This is most useful asset of a data communication system. The message simply refers to data or piece of information which is to be communicated. A message could be in any form, it may be in form of a text file, an audio file, a video file, etc."
},
{
"code": null,
"e": 2949,
"s": 2625,
"text": "Sender :To transfer message from source to destination, someone must be there who will play role of a source. Sender plays part of a source in data communication system. It is simple a device that sends data message. The device could be in form of a computer, mobile, telephone, laptop, video camera, or a workstation, etc."
},
{
"code": null,
"e": 3161,
"s": 2949,
"text": "Receiver :It is destination where finally message sent by source has arrived. It is a device that receives message. Same as sender, receiver can also be in form of a computer, telephone mobile, workstation, etc."
},
{
"code": null,
"e": 3579,
"s": 3161,
"text": "Transmission Medium :In entire process of data communication, there must be something which could act as a bridge between sender and receiver, Transmission medium plays that part. It is physical path by which data or message travels from sender to receiver. Transmission medium could be guided (with wires) or unguided (without wires), for example, twisted pair cable, fiber optic cable, radio waves, microwaves, etc."
},
{
"code": null,
"e": 4125,
"s": 3579,
"text": "Set of rules (Protocol) :To govern data communications, various sets of rules had been already designed by the designers of the communication systems, which represent a kind of agreement between communicating devices. These are defined as protocol. In simple terms, the protocol is a set of rules that govern data communication. If two different devices are connected but there is no protocol among them, there would not be any kind of communication between those two devices. Thus the protocol is necessary for data communication to take place."
},
{
"code": null,
"e": 4553,
"s": 4125,
"text": "A typical example of a data communication system is sending an e-mail. The user which send email act as sender, message is data which user wants to send, receiver is one whom user wants to send message, there are many protocols involved in this entire process, one of them is Simple Mail Transfer Protocol (SMTP), both sender and receiver must have an internet connection which uses a wireless medium to send and receive email."
},
{
"code": null,
"e": 4571,
"s": 4553,
"text": "Computer Networks"
},
{
"code": null,
"e": 4589,
"s": 4571,
"text": "Computer Networks"
},
{
"code": null,
"e": 4687,
"s": 4589,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4719,
"s": 4687,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 4749,
"s": 4719,
"text": "RSA Algorithm in Cryptography"
},
{
"code": null,
"e": 4787,
"s": 4749,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 4817,
"s": 4787,
"text": "GSM in Wireless Communication"
},
{
"code": null,
"e": 4846,
"s": 4817,
"text": "Socket Programming in Python"
},
{
"code": null,
"e": 4880,
"s": 4846,
"text": "Differences between IPv4 and IPv6"
},
{
"code": null,
"e": 4906,
"s": 4880,
"text": "Secure Socket Layer (SSL)"
},
{
"code": null,
"e": 4936,
"s": 4906,
"text": "Wireless Application Protocol"
},
{
"code": null,
"e": 4976,
"s": 4936,
"text": "Mobile Internet Protocol (or Mobile IP)"
}
] |
Chain Rules - Online Quiz
|
Following quiz provides Multiple Choice Questions (MCQs) related to Chain Rules. You will have to read all the given answers and click over the correct answer. If you are not sure about the answer then you can check the answer using Show Answer button. You can use Next Quiz button to check new set of questions in the quiz.
Q 1 - A worker makes a toy every 2/3 hour. If he works for 15/2 hours, then how many toys will he makes?
A - 45/4
B - 47/4
C - 53/4
D - 55/4
Let the required number of toys be x.
More time , more toys made (Direct)
2/3 : 15/2 :: 1:x ⇒ 2/3 * x = 15/2 *1 ⇒ x= (15/2 *3/2 ) = 45 /4 = 45/4.
Required number of toys = 45/4.
Q 2 - The Qutab minar casts a shadow 150m long at the same time when the vikes minar casts a shadow 120m long on the ground . If the height of the Vikes minar is 80m, what is the height of the Qutab Minar?
A - 100m
B - 120m
C - 150m
D - 180m
Let the height of the Qutab Minar be x metres.
Longer is the shadow , longer is the object (Direct)
120 : 150 :: 80 : x ⇒ 120 * x = (150 *80)⇒ x= (150 *80)/120=100m.
Height of Qutab Miinar = 100m.
Q 3 - 10 pipes of the same diameter can fill a tank in 24 minutes. If 2 pipes go out of order, how long will the remaining pipes takes to fill the tank?
A - 40 min
B - 45 min
C - 30 min
D - 96/5 min
Let the required time be x minutes.
Less pipes, more time (Indirect)
8: 10 ::24 : x ⇒ 8x = (10 * 24 ) ⇒ x= (10 * 24) /8 = 30min.
Q 4 - 8 men and 12 children can do a piece of work in 9 days . A child takes double the time to do a work than the men. In how many days 12 men can complete the work?
A - 21/2 days
B - 14 days
C - 18 days
D - 27/2 days
2 children = 1 men ⇒ (8 men + 12 children ) = 14 men.
Let the required number of days be x.
Less men , more day (Indirect )
12 : 14:: 9 : x ⇒ 12x = ( 14 * 90 ⇒ ( 14* 9 ) /12 = 21 /2 = 21/2 days.
Q 5 - In a barrack of soldiers there was stock of food for 190 days for 4000 soldiers.After 30 days , 800 soldiers left the barrack. For how many days shall the left over Food last for the remaining soldiers?
A - 175 days
B - 200 days
C - 225 days
D - 250 days
Remaining food was sufficient for 4000 soldiers for 160 days.
Remaining soldiers = ( 4000- 800) = 3200.
Let the required number of days be x .
Less soldiers, more days (Indirect)
3200 : 4000 :: 160 : x⇒ 3200 x = (4000 * 160 ) ⇒ x = (4000 * 160)/3200 = 200 days.
Q 6 - A contractor undertakes to build a wall in 50 days. He employs 50 people for the same . However, after 25 days , he finds that only 40 % of the work is complete , How many more men need to be employed to complete the work in time?
A - 20
B - 25
C - 30
D - 35
Work done = 40/100 = 2/5 , Remaining work = ( 1 - 2/5 ) = 3/5.
2/5 work is done in 25 days by 50 people.
3/5 work will be done in 25 days by (50 * 5/ 2 * 3/5) people = 75 people.
Required number of people = ( 75 ? 50 ) = 25.
Q 7 - 8 men working for 9 hours a day complete a piece of work in 20 days . In how many days can 7 men working for 10 hours a day complete the same piece of work?
A - 41/2 days
B - 103/5 days
C - 21 days
D - 144/7 days
Let the required number of days be x .
Less men , more days ( Indirect)
More working hours, less days (Indirect)
Men 7: 8
:: 20 : x
Working hrs 10 : 9
∴ ( 7 * 10 * x ) = ( 8 * 9 * 20) ⇒ x = 8 * 9 * 20 / 7 * 10 = 144/7 = 144/7.
Q 8 - If 3 persons weave 336 shawls in 14 days , how many shawls will 8 persons weave in 5 days?
A - 180
B - 210
C - 252
D - 320
Let the required number of shawls be x.
More persons, more shawls (Direct)
Less days, less shawls (Indirect)
Persons 3:8
:: 336 : x
Days 14: 5
∴ ( 3 * 14 * x ) = ( 8 * 5 * 336) ⇒ x = 8 * 5 * 336/ 3 * 14 = 320.
Q 9 - If 18 pumps can raise 2170 tonnes of water in 10 days , working 7 hours per day , in how many days will 16 pumps rise 1736 tonnes, working 9 hours per day?
A - 9 days
B - 8 days
C - 7 days
D - 6 days
Let the required number of days be x.
Less pumps, more days (Indirect)
Less water, less days (direct)
More working hrs, less days (Indirect)
Pumps 16:18
Water Qty. 2170 : 1736 :: 10 :x
Water hrs 9:7
∴ (16 * 2170 * 9 *x ) = ( 18 * 1736*7 *10)⇒ x=18 * 1736*7 *10/16*2170 * 9 = 7 days .
Q 10 - If x men working x hours per day can do x unit of work in x days , then y men working y hours per day would be able to do how much work in y days?
A - x2/y2 units
B - x3 / y2 unit
C - y2 / x3 unit
D - y3 / x2
More men , more work (Direct)
More working hrs , more work (Direct)
More days , more work (Direct)
Let the required work be z units. Then,
Men x:y
working hrs x:y :: x:z
days x:y
∴ x*x*x*z = y * y* y* x ⇒ z= y3 / x2 units.
|
[
{
"code": null,
"e": 4351,
"s": 4026,
"text": "Following quiz provides Multiple Choice Questions (MCQs) related to Chain Rules. You will have to read all the given answers and click over the correct answer. If you are not sure about the answer then you can check the answer using Show Answer button. You can use Next Quiz button to check new set of questions in the quiz."
},
{
"code": null,
"e": 4456,
"s": 4351,
"text": "Q 1 - A worker makes a toy every 2/3 hour. If he works for 15/2 hours, then how many toys will he makes?"
},
{
"code": null,
"e": 4465,
"s": 4456,
"text": "A - 45/4"
},
{
"code": null,
"e": 4474,
"s": 4465,
"text": "B - 47/4"
},
{
"code": null,
"e": 4483,
"s": 4474,
"text": "C - 53/4"
},
{
"code": null,
"e": 4492,
"s": 4483,
"text": "D - 55/4"
},
{
"code": null,
"e": 4673,
"s": 4492,
"text": "Let the required number of toys be x.\nMore time , more toys made (Direct)\n2/3 : 15/2 :: 1:x ⇒ 2/3 * x = 15/2 *1 ⇒ x= (15/2 *3/2 ) = 45 /4 = 45/4.\nRequired number of toys = 45/4."
},
{
"code": null,
"e": 4881,
"s": 4673,
"text": "Q 2 - The Qutab minar casts a shadow 150m long at the same time when the vikes minar casts a shadow 120m long on the ground . If the height of the Vikes minar is 80m, what is the height of the Qutab Minar?"
},
{
"code": null,
"e": 4890,
"s": 4881,
"text": "A - 100m"
},
{
"code": null,
"e": 4899,
"s": 4890,
"text": "B - 120m"
},
{
"code": null,
"e": 4908,
"s": 4899,
"text": "C - 150m"
},
{
"code": null,
"e": 4917,
"s": 4908,
"text": "D - 180m"
},
{
"code": null,
"e": 5118,
"s": 4917,
"text": "Let the height of the Qutab Minar be x metres.\nLonger is the shadow , longer is the object (Direct)\n120 : 150 :: 80 : x ⇒ 120 * x = (150 *80)⇒ x= (150 *80)/120=100m.\nHeight of Qutab Miinar = 100m."
},
{
"code": null,
"e": 5271,
"s": 5118,
"text": "Q 3 - 10 pipes of the same diameter can fill a tank in 24 minutes. If 2 pipes go out of order, how long will the remaining pipes takes to fill the tank?"
},
{
"code": null,
"e": 5282,
"s": 5271,
"text": "A - 40 min"
},
{
"code": null,
"e": 5293,
"s": 5282,
"text": "B - 45 min"
},
{
"code": null,
"e": 5304,
"s": 5293,
"text": "C - 30 min"
},
{
"code": null,
"e": 5317,
"s": 5304,
"text": "D - 96/5 min"
},
{
"code": null,
"e": 5450,
"s": 5317,
"text": "Let the required time be x minutes.\nLess pipes, more time (Indirect)\n8: 10 ::24 : x ⇒ 8x = (10 * 24 ) ⇒ x= (10 * 24) /8 = 30min."
},
{
"code": null,
"e": 5618,
"s": 5450,
"text": "Q 4 - 8 men and 12 children can do a piece of work in 9 days . A child takes double the time to do a work than the men. In how many days 12 men can complete the work?"
},
{
"code": null,
"e": 5632,
"s": 5618,
"text": "A - 21/2 days"
},
{
"code": null,
"e": 5644,
"s": 5632,
"text": "B - 14 days"
},
{
"code": null,
"e": 5656,
"s": 5644,
"text": "C - 18 days"
},
{
"code": null,
"e": 5670,
"s": 5656,
"text": "D - 27/2 days"
},
{
"code": null,
"e": 5872,
"s": 5670,
"text": "2 children = 1 men ⇒ (8 men + 12 children ) = 14 men.\nLet the required number of days be x. \nLess men , more day (Indirect )\n12 : 14:: 9 : x ⇒ 12x = ( 14 * 90 ⇒ ( 14* 9 ) /12 = 21 /2 = 21/2 days."
},
{
"code": null,
"e": 6082,
"s": 5872,
"text": "Q 5 - In a barrack of soldiers there was stock of food for 190 days for 4000 soldiers.After 30 days , 800 soldiers left the barrack. For how many days shall the left over Food last for the remaining soldiers?"
},
{
"code": null,
"e": 6095,
"s": 6082,
"text": "A - 175 days"
},
{
"code": null,
"e": 6108,
"s": 6095,
"text": "B - 200 days"
},
{
"code": null,
"e": 6121,
"s": 6108,
"text": "C - 225 days"
},
{
"code": null,
"e": 6134,
"s": 6121,
"text": "D - 250 days"
},
{
"code": null,
"e": 6403,
"s": 6134,
"text": "Remaining food was sufficient for 4000 soldiers for 160 days.\nRemaining soldiers = ( 4000- 800) = 3200.\nLet the required number of days be x .\nLess soldiers, more days (Indirect)\n3200 : 4000 :: 160 : x⇒ 3200 x = (4000 * 160 ) ⇒ x = (4000 * 160)/3200 = 200 days."
},
{
"code": null,
"e": 6642,
"s": 6403,
"text": "Q 6 - A contractor undertakes to build a wall in 50 days. He employs 50 people for the same . However, after 25 days , he finds that only 40 % of the work is complete , How many more men need to be employed to complete the work in time?"
},
{
"code": null,
"e": 6649,
"s": 6642,
"text": "A - 20"
},
{
"code": null,
"e": 6656,
"s": 6649,
"text": "B - 25"
},
{
"code": null,
"e": 6663,
"s": 6656,
"text": "C - 30"
},
{
"code": null,
"e": 6670,
"s": 6663,
"text": "D - 35"
},
{
"code": null,
"e": 6896,
"s": 6670,
"text": "Work done = 40/100 = 2/5 , Remaining work = ( 1 - 2/5 ) = 3/5.\n2/5 work is done in 25 days by 50 people.\n3/5 work will be done in 25 days by (50 * 5/ 2 * 3/5) people = 75 people.\nRequired number of people = ( 75 ? 50 ) = 25."
},
{
"code": null,
"e": 7059,
"s": 6896,
"text": "Q 7 - 8 men working for 9 hours a day complete a piece of work in 20 days . In how many days can 7 men working for 10 hours a day complete the same piece of work?"
},
{
"code": null,
"e": 7073,
"s": 7059,
"text": "A - 41/2 days"
},
{
"code": null,
"e": 7088,
"s": 7073,
"text": "B - 103/5 days"
},
{
"code": null,
"e": 7100,
"s": 7088,
"text": "C - 21 days"
},
{
"code": null,
"e": 7115,
"s": 7100,
"text": "D - 144/7 days"
},
{
"code": null,
"e": 7359,
"s": 7115,
"text": "Let the required number of days be x .\nLess men , more days ( Indirect)\nMore working hours, less days (Indirect)\nMen 7: 8\n:: 20 : x\nWorking hrs 10 : 9\n∴ ( 7 * 10 * x ) = ( 8 * 9 * 20) ⇒ x = 8 * 9 * 20 / 7 * 10 = 144/7 = 144/7."
},
{
"code": null,
"e": 7456,
"s": 7359,
"text": "Q 8 - If 3 persons weave 336 shawls in 14 days , how many shawls will 8 persons weave in 5 days?"
},
{
"code": null,
"e": 7464,
"s": 7456,
"text": "A - 180"
},
{
"code": null,
"e": 7472,
"s": 7464,
"text": "B - 210"
},
{
"code": null,
"e": 7480,
"s": 7472,
"text": "C - 252"
},
{
"code": null,
"e": 7488,
"s": 7480,
"text": "D - 320"
},
{
"code": null,
"e": 7720,
"s": 7488,
"text": "Let the required number of shawls be x.\nMore persons, more shawls (Direct)\nLess days, less shawls (Indirect)\nPersons 3:8\n:: 336 : x \nDays 14: 5 \n∴ ( 3 * 14 * x ) = ( 8 * 5 * 336) ⇒ x = 8 * 5 * 336/ 3 * 14 = 320."
},
{
"code": null,
"e": 7882,
"s": 7720,
"text": "Q 9 - If 18 pumps can raise 2170 tonnes of water in 10 days , working 7 hours per day , in how many days will 16 pumps rise 1736 tonnes, working 9 hours per day?"
},
{
"code": null,
"e": 7893,
"s": 7882,
"text": "A - 9 days"
},
{
"code": null,
"e": 7904,
"s": 7893,
"text": "B - 8 days"
},
{
"code": null,
"e": 7915,
"s": 7904,
"text": "C - 7 days"
},
{
"code": null,
"e": 7926,
"s": 7915,
"text": "D - 6 days"
},
{
"code": null,
"e": 8244,
"s": 7926,
"text": "Let the required number of days be x.\nLess pumps, more days (Indirect)\nLess water, less days (direct)\nMore working hrs, less days (Indirect)\nPumps 16:18\nWater Qty. 2170 : 1736 :: 10 :x\nWater hrs 9:7\n∴ (16 * 2170 * 9 *x ) = ( 18 * 1736*7 *10)⇒ x=18 * 1736*7 *10/16*2170 * 9 = 7 days ."
},
{
"code": null,
"e": 8398,
"s": 8244,
"text": "Q 10 - If x men working x hours per day can do x unit of work in x days , then y men working y hours per day would be able to do how much work in y days?"
},
{
"code": null,
"e": 8414,
"s": 8398,
"text": "A - x2/y2 units"
},
{
"code": null,
"e": 8432,
"s": 8414,
"text": "B - x3 / y2 unit"
},
{
"code": null,
"e": 8450,
"s": 8432,
"text": "C - y2 / x3 unit"
},
{
"code": null,
"e": 8462,
"s": 8450,
"text": "D - y3 / x2"
}
] |
What is an Expression and What are the types of Expressions?
|
02 Aug, 2019
Expression: An expression is a combination of operators, constants and variables. An expression may consist of one or more operands, and zero or more operators to produce a value.
Example:
a+b
c
s-1/7*f
.
.
etc
Types of Expressions:
Expressions may be of the following types:
Constant expressions: Constant Expressions consists of only constant values. A constant value is one that doesn’t change.Examples:5, 10 + 5 / 6.0, 'x’
5, 10 + 5 / 6.0, 'x’
Integral expressions: Integral Expressions are those which produce integer results after implementing all the automatic and explicit type conversions.Examples:x, x * y, x + int( 5.0)where x and y are integer variables.
x, x * y, x + int( 5.0)
where x and y are integer variables.
Floating expressions: Float Expressions are which produce floating point results after implementing all the automatic and explicit type conversions.Examples:x + y, 10.75where x and y are floating point variables.
x + y, 10.75
where x and y are floating point variables.
Relational expressions: Relational Expressions yield results of type bool which takes a value true or false. When arithmetic expressions are used on either side of a relational operator, they will be evaluated first and then the results compared. Relational expressions are also known as Boolean expressions.Examples:x <= y, x + y > 2
x <= y, x + y > 2
Logical expressions: Logical Expressions combine two or more relational expressions and produces bool type results.Examples: x > y && x == 10, x == 10 || y == 5
x > y && x == 10, x == 10 || y == 5
Pointer expressions: Pointer Expressions produce address values.Examples:&x, ptr, ptr++where x is a variable and ptr is a pointer.
&x, ptr, ptr++
where x is a variable and ptr is a pointer.
Bitwise expressions: Bitwise Expressions are used to manipulate data at bit level. They are basically used for testing or shifting bits.Examples:x << 3shifts three bit position to lefty >> 1shifts one bit position to right.Shift operators are often used for multiplication and division by powers of two.
x << 3
shifts three bit position to left
y >> 1
shifts one bit position to right.
Shift operators are often used for multiplication and division by powers of two.
Note: An expression may also use combinations of the above expressions. Such expressions are known as compound expressions.
expression-evaluation
Mathematical
School Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Prime Numbers
Sieve of Eratosthenes
Program to find GCD or HCF of two numbers
Python Dictionary
Reverse a string in Java
Arrays in C/C++
Introduction To PYTHON
Interfaces in Java
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n02 Aug, 2019"
},
{
"code": null,
"e": 234,
"s": 54,
"text": "Expression: An expression is a combination of operators, constants and variables. An expression may consist of one or more operands, and zero or more operators to produce a value."
},
{
"code": null,
"e": 243,
"s": 234,
"text": "Example:"
},
{
"code": null,
"e": 266,
"s": 243,
"text": "a+b\nc\ns-1/7*f\n.\n.\netc\n"
},
{
"code": null,
"e": 288,
"s": 266,
"text": "Types of Expressions:"
},
{
"code": null,
"e": 331,
"s": 288,
"text": "Expressions may be of the following types:"
},
{
"code": null,
"e": 482,
"s": 331,
"text": "Constant expressions: Constant Expressions consists of only constant values. A constant value is one that doesn’t change.Examples:5, 10 + 5 / 6.0, 'x’"
},
{
"code": null,
"e": 503,
"s": 482,
"text": "5, 10 + 5 / 6.0, 'x’"
},
{
"code": null,
"e": 722,
"s": 503,
"text": "Integral expressions: Integral Expressions are those which produce integer results after implementing all the automatic and explicit type conversions.Examples:x, x * y, x + int( 5.0)where x and y are integer variables."
},
{
"code": null,
"e": 746,
"s": 722,
"text": "x, x * y, x + int( 5.0)"
},
{
"code": null,
"e": 783,
"s": 746,
"text": "where x and y are integer variables."
},
{
"code": null,
"e": 996,
"s": 783,
"text": "Floating expressions: Float Expressions are which produce floating point results after implementing all the automatic and explicit type conversions.Examples:x + y, 10.75where x and y are floating point variables."
},
{
"code": null,
"e": 1009,
"s": 996,
"text": "x + y, 10.75"
},
{
"code": null,
"e": 1053,
"s": 1009,
"text": "where x and y are floating point variables."
},
{
"code": null,
"e": 1388,
"s": 1053,
"text": "Relational expressions: Relational Expressions yield results of type bool which takes a value true or false. When arithmetic expressions are used on either side of a relational operator, they will be evaluated first and then the results compared. Relational expressions are also known as Boolean expressions.Examples:x <= y, x + y > 2"
},
{
"code": null,
"e": 1406,
"s": 1388,
"text": "x <= y, x + y > 2"
},
{
"code": null,
"e": 1568,
"s": 1406,
"text": "Logical expressions: Logical Expressions combine two or more relational expressions and produces bool type results.Examples: x > y && x == 10, x == 10 || y == 5 "
},
{
"code": null,
"e": 1606,
"s": 1568,
"text": " x > y && x == 10, x == 10 || y == 5 "
},
{
"code": null,
"e": 1737,
"s": 1606,
"text": "Pointer expressions: Pointer Expressions produce address values.Examples:&x, ptr, ptr++where x is a variable and ptr is a pointer."
},
{
"code": null,
"e": 1752,
"s": 1737,
"text": "&x, ptr, ptr++"
},
{
"code": null,
"e": 1796,
"s": 1752,
"text": "where x is a variable and ptr is a pointer."
},
{
"code": null,
"e": 2100,
"s": 1796,
"text": "Bitwise expressions: Bitwise Expressions are used to manipulate data at bit level. They are basically used for testing or shifting bits.Examples:x << 3shifts three bit position to lefty >> 1shifts one bit position to right.Shift operators are often used for multiplication and division by powers of two."
},
{
"code": null,
"e": 2107,
"s": 2100,
"text": "x << 3"
},
{
"code": null,
"e": 2141,
"s": 2107,
"text": "shifts three bit position to left"
},
{
"code": null,
"e": 2148,
"s": 2141,
"text": "y >> 1"
},
{
"code": null,
"e": 2182,
"s": 2148,
"text": "shifts one bit position to right."
},
{
"code": null,
"e": 2263,
"s": 2182,
"text": "Shift operators are often used for multiplication and division by powers of two."
},
{
"code": null,
"e": 2387,
"s": 2263,
"text": "Note: An expression may also use combinations of the above expressions. Such expressions are known as compound expressions."
},
{
"code": null,
"e": 2409,
"s": 2387,
"text": "expression-evaluation"
},
{
"code": null,
"e": 2422,
"s": 2409,
"text": "Mathematical"
},
{
"code": null,
"e": 2441,
"s": 2422,
"text": "School Programming"
},
{
"code": null,
"e": 2454,
"s": 2441,
"text": "Mathematical"
},
{
"code": null,
"e": 2552,
"s": 2454,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2576,
"s": 2552,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 2597,
"s": 2576,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 2611,
"s": 2597,
"text": "Prime Numbers"
},
{
"code": null,
"e": 2633,
"s": 2611,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 2675,
"s": 2633,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 2693,
"s": 2675,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2718,
"s": 2693,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 2734,
"s": 2718,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 2757,
"s": 2734,
"text": "Introduction To PYTHON"
}
] |
Java - pow() Method
|
The method returns the value of the first argument raised to the power of the second argument.
double pow(double base, double exponent)
Here is the detail of parameters −
base − Any primitive data type.
base − Any primitive data type.
exponenet − Any primitive data type.
exponenet − Any primitive data type.
This method returns the value of the first argument raised to the power of the second argument.
This method returns the value of the first argument raised to the power of the second argument.
public class Test {
public static void main(String args[]) {
double x = 11.635;
double y = 2.76;
System.out.printf("The value of e is %.4f%n", Math.E);
System.out.printf("pow(%.3f, %.3f) is %.3f%n", x, y, Math.pow(x, y));
}
}
This will produce the following result −
The value of e is 2.7183
pow(11.635, 2.760) is 874.008
|
[
{
"code": null,
"e": 2606,
"s": 2511,
"text": "The method returns the value of the first argument raised to the power of the second argument."
},
{
"code": null,
"e": 2648,
"s": 2606,
"text": "double pow(double base, double exponent)\n"
},
{
"code": null,
"e": 2683,
"s": 2648,
"text": "Here is the detail of parameters −"
},
{
"code": null,
"e": 2715,
"s": 2683,
"text": "base − Any primitive data type."
},
{
"code": null,
"e": 2747,
"s": 2715,
"text": "base − Any primitive data type."
},
{
"code": null,
"e": 2784,
"s": 2747,
"text": "exponenet − Any primitive data type."
},
{
"code": null,
"e": 2821,
"s": 2784,
"text": "exponenet − Any primitive data type."
},
{
"code": null,
"e": 2917,
"s": 2821,
"text": "This method returns the value of the first argument raised to the power of the second argument."
},
{
"code": null,
"e": 3013,
"s": 2917,
"text": "This method returns the value of the first argument raised to the power of the second argument."
},
{
"code": null,
"e": 3272,
"s": 3013,
"text": "public class Test { \n\n public static void main(String args[]) {\n double x = 11.635;\n double y = 2.76;\n\n System.out.printf(\"The value of e is %.4f%n\", Math.E);\n System.out.printf(\"pow(%.3f, %.3f) is %.3f%n\", x, y, Math.pow(x, y));\n }\n}"
},
{
"code": null,
"e": 3313,
"s": 3272,
"text": "This will produce the following result −"
}
] |
Reference and Copy Variables in JavaScript
|
08 Jul, 2022
In this article, we will talk about pass-by-value and pass-by-reference in JavaScript.JavaScript always passes by value, but in an array or object, the value is a reference to it, so you can ‘change’ the data. JavaScript has 5 primitive data types that are passed by value, they are Boolean, NULL, undefined, String, and Number. It has 3 non-primitive data types that are passed by reference, they are Array, Function, and Object. In non-primitive data types, we have some challenges for copying data. As we know objects are created at some place in the computer’s memory. When we declare any property it creates a space in memory.
Example: The address is a data type that is passed by value just like a number, string, and address points to the location in memory.
Pass by value in case of number.
<script>let age = 100;let age2 = age;document.write(age, age2);document.write("<br>");age = 200;document.write(age, age2); </script>
Output:
100 100
200 100
Pass by value in case of string
<script>let name = 'sam';let name2 = name;document.write(name, name2); document.write("<br>");name = 'xyz';document.write(name, name2); </script>
Output:
sam sam
xyz sam
Pass by reference in case of array
<script>const players = ['Sam', 'Sarah', 'Ryan', 'Poppy'];const team = players;document.write(players, team);</script>
Output:
["Sam", "Sarah", "Ryan", "Poppy"]
["Sam", "Sarah", "Ryan", "Poppy"]
Now if you change the data from “team” array it also affects the “players” array
<script>const players = ['Sam', 'Sarah', 'Ryan', 'Poppy'];const team = players;team[3] = 'xyz';document.write(players, team);</script>
Output:
["Sam", "Sarah", "Ryan", "xyz"]
["Sam", "Sarah", "Ryan", "xyz"]
It’s an array reference, not an array copy. They both point to the same array.We have 4 ways to do it. By using these methods the primary array will not change.
By using slice() method:<script>const players = ['Sam', 'Sarah', 'Ryan', 'Poppy'];const playersCopy = players.slice();playersCopy[2]="west";console.log(players, palyersCopy);</script>Output:["Sam", "Sarah", "Ryan", "Poppy"]
["Sam", "Sarah", "west", "Poppy"]
By using concat() method: Create a new array variable and then concatenate the older one in the new array.<script> const players = ['Sam', 'Sarah', 'Ryan', 'Poppy']; const playersCopy2 = [].concat(players); playersCopy2[2]='hell'; document.write(players, playersCopy2);</script>Output:["Sam", "Sarah", "Ryan", "Poppy"]
["Sam", "Sarah", "hell", "Poppy"]
By using ES6 Spread operator:<script> const players = ['Sam', 'Sarah', 'Ryan', 'Poppy']; const playersCopy3 = [...players]; playersCopy3[3] = 'heeee hawww'; document.write(players, playersCopy3);</script>Output: ["Sam", "Sarah", "Ryan", "Poppy"]
["Sam", "Sarah", "Ryan", "heeee hawww"]
By using Array.from():<script> const players = ['Sam', 'Sarah', 'Ryan', 'Poppy']; const playersCopy4 = Array.from(players); playersCopy4[3]="kim"; document.write(players, playersCopy4);</script>Output:
["Sam", "Sarah", "Ryan", "Poppy"]
["Sam", "Sarah", "Ryan", "kim"]
By using slice() method:<script>const players = ['Sam', 'Sarah', 'Ryan', 'Poppy'];const playersCopy = players.slice();playersCopy[2]="west";console.log(players, palyersCopy);</script>Output:["Sam", "Sarah", "Ryan", "Poppy"]
["Sam", "Sarah", "west", "Poppy"]
<script>const players = ['Sam', 'Sarah', 'Ryan', 'Poppy'];const playersCopy = players.slice();playersCopy[2]="west";console.log(players, palyersCopy);</script>
Output:
["Sam", "Sarah", "Ryan", "Poppy"]
["Sam", "Sarah", "west", "Poppy"]
By using concat() method: Create a new array variable and then concatenate the older one in the new array.<script> const players = ['Sam', 'Sarah', 'Ryan', 'Poppy']; const playersCopy2 = [].concat(players); playersCopy2[2]='hell'; document.write(players, playersCopy2);</script>Output:["Sam", "Sarah", "Ryan", "Poppy"]
["Sam", "Sarah", "hell", "Poppy"]
<script> const players = ['Sam', 'Sarah', 'Ryan', 'Poppy']; const playersCopy2 = [].concat(players); playersCopy2[2]='hell'; document.write(players, playersCopy2);</script>
Output:
["Sam", "Sarah", "Ryan", "Poppy"]
["Sam", "Sarah", "hell", "Poppy"]
By using ES6 Spread operator:<script> const players = ['Sam', 'Sarah', 'Ryan', 'Poppy']; const playersCopy3 = [...players]; playersCopy3[3] = 'heeee hawww'; document.write(players, playersCopy3);</script>Output: ["Sam", "Sarah", "Ryan", "Poppy"]
["Sam", "Sarah", "Ryan", "heeee hawww"]
<script> const players = ['Sam', 'Sarah', 'Ryan', 'Poppy']; const playersCopy3 = [...players]; playersCopy3[3] = 'heeee hawww'; document.write(players, playersCopy3);</script>
Output:
["Sam", "Sarah", "Ryan", "Poppy"]
["Sam", "Sarah", "Ryan", "heeee hawww"]
By using Array.from():<script> const players = ['Sam', 'Sarah', 'Ryan', 'Poppy']; const playersCopy4 = Array.from(players); playersCopy4[3]="kim"; document.write(players, playersCopy4);</script>Output:
["Sam", "Sarah", "Ryan", "Poppy"]
["Sam", "Sarah", "Ryan", "kim"]
<script> const players = ['Sam', 'Sarah', 'Ryan', 'Poppy']; const playersCopy4 = Array.from(players); playersCopy4[3]="kim"; document.write(players, playersCopy4);</script>
Output:
["Sam", "Sarah", "Ryan", "Poppy"]
["Sam", "Sarah", "Ryan", "kim"]
Pass by reference in Object: The same point goes for objects, it also affects the original object.
const person = { name: 'loren isum', age: 80 };const captain = person;person.age = 25;console.log(captain, person);
Output:
{name: "loren isum", age: 25}
{name: "loren isum", age: 25}
There are two ways to do it.
By using the assign() method:<script>const personObject = { name: 'loren isum', age: 80 };const personCopy = Object.assign({}, personObject, { number: 99, age: 12 });personCopy.age = 78;console.log(personCopy, personObject);</script>Output:{name: "loren isum", age: 78, number: 99}
{name: "loren isum", age: 80}
By using the Spread operator:<script>const personData = { name: 'loren isum', age: 80 };const personCopy2 = {...personData };personCopy2.age = 78;console.log(personCopy2, personData );</script>Output:{name: "loren isum", age: 78}
{name: "loren isum", age: 80}
By using the assign() method:<script>const personObject = { name: 'loren isum', age: 80 };const personCopy = Object.assign({}, personObject, { number: 99, age: 12 });personCopy.age = 78;console.log(personCopy, personObject);</script>Output:{name: "loren isum", age: 78, number: 99}
{name: "loren isum", age: 80}
<script>const personObject = { name: 'loren isum', age: 80 };const personCopy = Object.assign({}, personObject, { number: 99, age: 12 });personCopy.age = 78;console.log(personCopy, personObject);</script>
Output:
{name: "loren isum", age: 78, number: 99}
{name: "loren isum", age: 80}
By using the Spread operator:<script>const personData = { name: 'loren isum', age: 80 };const personCopy2 = {...personData };personCopy2.age = 78;console.log(personCopy2, personData );</script>Output:{name: "loren isum", age: 78}
{name: "loren isum", age: 80}
<script>const personData = { name: 'loren isum', age: 80 };const personCopy2 = {...personData };personCopy2.age = 78;console.log(personCopy2, personData );</script>
Output:
{name: "loren isum", age: 78}
{name: "loren isum", age: 80}
One more thing you need to think about what will happen in the case of an equal and equality operator. When we use these operators on reference type variables they check the reference. If the property has a reference to the same item then the comparison will give output as “true”, otherwise it will return “false.”
<script> var arrayReference = ["Hi!"]; var arrayCopy = arrayReference; console.log(arrayCopy === arrayReference); </script>
Output:
true
<script>var array1 = ['Hi!'];var array2 = ['Hi!'];console.log(array1 === array2);</script>
Output:
false
This can be corrected by stringifying the array.
<script>var arr1str = JSON.stringify(array1);var arr2str = JSON.stringify(array2);console.log(arr1str === arr2str); // true</script>
Output:
true
We can change the name property of object person, but we are unable to reset the reference person since it has been marked as const.
<script> const person = { name: 'Tammy' }; // Name property changed person.name = 'abc'; // Objects are a reference type var val1 = { name: "Tom" }; var val2 = { name: "Tom" }; console.log(val1 == val2) </script>
Output:
false
But we can correct this thing by stringifying the array.
<script> var array1 = ['Hi!']; var array2 = ['Hi!']; var arr1str = JSON.stringify(array1); var arr2str = JSON.stringify(array2); console.log(arr1str === arr2str); </script>
Output:
true
Pass by reference in case of functions: If we pass the object in the function, it will change both the objects.
<script>function changevalue(person) { var newPersonObj = (person); newPersonObj.age = 25; return newPersonObj;}var alex = { name: 'xyz', age: 30};var alexChanged = changevalue(alex);console.log(alex); console.log(alexChanged); </script>
Output:
{ name: 'xyz', age: 25 }
{ name: 'xyz', age: 25 }
We can resolve this problem by parsing and stringifying the object.
<script>function changevalue(person) { var newPersonObj = JSON.parse(JSON.stringify(person)); newPersonObj.age = 25; return newPersonObj;}var alex = { name: 'xyz', age: 30};var alexChanged = changevalue(alex);console.log(alex); console.log(alexChanged); </script>
Output:
{ name: 'xyz', age: 30 }
{ name: 'xyz', age: 25 }
JavaScript-Misc
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Jul, 2022"
},
{
"code": null,
"e": 660,
"s": 28,
"text": "In this article, we will talk about pass-by-value and pass-by-reference in JavaScript.JavaScript always passes by value, but in an array or object, the value is a reference to it, so you can ‘change’ the data. JavaScript has 5 primitive data types that are passed by value, they are Boolean, NULL, undefined, String, and Number. It has 3 non-primitive data types that are passed by reference, they are Array, Function, and Object. In non-primitive data types, we have some challenges for copying data. As we know objects are created at some place in the computer’s memory. When we declare any property it creates a space in memory."
},
{
"code": null,
"e": 794,
"s": 660,
"text": "Example: The address is a data type that is passed by value just like a number, string, and address points to the location in memory."
},
{
"code": null,
"e": 827,
"s": 794,
"text": "Pass by value in case of number."
},
{
"code": "<script>let age = 100;let age2 = age;document.write(age, age2);document.write(\"<br>\");age = 200;document.write(age, age2); </script>",
"e": 960,
"s": 827,
"text": null
},
{
"code": null,
"e": 968,
"s": 960,
"text": "Output:"
},
{
"code": null,
"e": 985,
"s": 968,
"text": "100 100\n200 100\n"
},
{
"code": null,
"e": 1017,
"s": 985,
"text": "Pass by value in case of string"
},
{
"code": "<script>let name = 'sam';let name2 = name;document.write(name, name2); document.write(\"<br>\");name = 'xyz';document.write(name, name2); </script>",
"e": 1163,
"s": 1017,
"text": null
},
{
"code": null,
"e": 1171,
"s": 1163,
"text": "Output:"
},
{
"code": null,
"e": 1188,
"s": 1171,
"text": "sam sam\nxyz sam\n"
},
{
"code": null,
"e": 1223,
"s": 1188,
"text": "Pass by reference in case of array"
},
{
"code": "<script>const players = ['Sam', 'Sarah', 'Ryan', 'Poppy'];const team = players;document.write(players, team);</script>",
"e": 1342,
"s": 1223,
"text": null
},
{
"code": null,
"e": 1350,
"s": 1342,
"text": "Output:"
},
{
"code": null,
"e": 1419,
"s": 1350,
"text": "[\"Sam\", \"Sarah\", \"Ryan\", \"Poppy\"]\n[\"Sam\", \"Sarah\", \"Ryan\", \"Poppy\"]\n"
},
{
"code": null,
"e": 1500,
"s": 1419,
"text": "Now if you change the data from “team” array it also affects the “players” array"
},
{
"code": "<script>const players = ['Sam', 'Sarah', 'Ryan', 'Poppy'];const team = players;team[3] = 'xyz';document.write(players, team);</script>",
"e": 1635,
"s": 1500,
"text": null
},
{
"code": null,
"e": 1643,
"s": 1635,
"text": "Output:"
},
{
"code": null,
"e": 1708,
"s": 1643,
"text": "[\"Sam\", \"Sarah\", \"Ryan\", \"xyz\"]\n[\"Sam\", \"Sarah\", \"Ryan\", \"xyz\"]\n"
},
{
"code": null,
"e": 1869,
"s": 1708,
"text": "It’s an array reference, not an array copy. They both point to the same array.We have 4 ways to do it. By using these methods the primary array will not change."
},
{
"code": null,
"e": 3052,
"s": 1869,
"text": "By using slice() method:<script>const players = ['Sam', 'Sarah', 'Ryan', 'Poppy'];const playersCopy = players.slice();playersCopy[2]=\"west\";console.log(players, palyersCopy);</script>Output:[\"Sam\", \"Sarah\", \"Ryan\", \"Poppy\"]\n[\"Sam\", \"Sarah\", \"west\", \"Poppy\"]\nBy using concat() method: Create a new array variable and then concatenate the older one in the new array.<script> const players = ['Sam', 'Sarah', 'Ryan', 'Poppy']; const playersCopy2 = [].concat(players); playersCopy2[2]='hell'; document.write(players, playersCopy2);</script>Output:[\"Sam\", \"Sarah\", \"Ryan\", \"Poppy\"]\n[\"Sam\", \"Sarah\", \"hell\", \"Poppy\"]\nBy using ES6 Spread operator:<script> const players = ['Sam', 'Sarah', 'Ryan', 'Poppy']; const playersCopy3 = [...players]; playersCopy3[3] = 'heeee hawww'; document.write(players, playersCopy3);</script>Output: [\"Sam\", \"Sarah\", \"Ryan\", \"Poppy\"]\n [\"Sam\", \"Sarah\", \"Ryan\", \"heeee hawww\"]\nBy using Array.from():<script> const players = ['Sam', 'Sarah', 'Ryan', 'Poppy']; const playersCopy4 = Array.from(players); playersCopy4[3]=\"kim\"; document.write(players, playersCopy4);</script>Output: \n[\"Sam\", \"Sarah\", \"Ryan\", \"Poppy\"]\n[\"Sam\", \"Sarah\", \"Ryan\", \"kim\"]\n"
},
{
"code": null,
"e": 3311,
"s": 3052,
"text": "By using slice() method:<script>const players = ['Sam', 'Sarah', 'Ryan', 'Poppy'];const playersCopy = players.slice();playersCopy[2]=\"west\";console.log(players, palyersCopy);</script>Output:[\"Sam\", \"Sarah\", \"Ryan\", \"Poppy\"]\n[\"Sam\", \"Sarah\", \"west\", \"Poppy\"]\n"
},
{
"code": "<script>const players = ['Sam', 'Sarah', 'Ryan', 'Poppy'];const playersCopy = players.slice();playersCopy[2]=\"west\";console.log(players, palyersCopy);</script>",
"e": 3471,
"s": 3311,
"text": null
},
{
"code": null,
"e": 3479,
"s": 3471,
"text": "Output:"
},
{
"code": null,
"e": 3548,
"s": 3479,
"text": "[\"Sam\", \"Sarah\", \"Ryan\", \"Poppy\"]\n[\"Sam\", \"Sarah\", \"west\", \"Poppy\"]\n"
},
{
"code": null,
"e": 3906,
"s": 3548,
"text": "By using concat() method: Create a new array variable and then concatenate the older one in the new array.<script> const players = ['Sam', 'Sarah', 'Ryan', 'Poppy']; const playersCopy2 = [].concat(players); playersCopy2[2]='hell'; document.write(players, playersCopy2);</script>Output:[\"Sam\", \"Sarah\", \"Ryan\", \"Poppy\"]\n[\"Sam\", \"Sarah\", \"hell\", \"Poppy\"]\n"
},
{
"code": "<script> const players = ['Sam', 'Sarah', 'Ryan', 'Poppy']; const playersCopy2 = [].concat(players); playersCopy2[2]='hell'; document.write(players, playersCopy2);</script>",
"e": 4083,
"s": 3906,
"text": null
},
{
"code": null,
"e": 4091,
"s": 4083,
"text": "Output:"
},
{
"code": null,
"e": 4160,
"s": 4091,
"text": "[\"Sam\", \"Sarah\", \"Ryan\", \"Poppy\"]\n[\"Sam\", \"Sarah\", \"hell\", \"Poppy\"]\n"
},
{
"code": null,
"e": 4451,
"s": 4160,
"text": "By using ES6 Spread operator:<script> const players = ['Sam', 'Sarah', 'Ryan', 'Poppy']; const playersCopy3 = [...players]; playersCopy3[3] = 'heeee hawww'; document.write(players, playersCopy3);</script>Output: [\"Sam\", \"Sarah\", \"Ryan\", \"Poppy\"]\n [\"Sam\", \"Sarah\", \"Ryan\", \"heeee hawww\"]\n"
},
{
"code": "<script> const players = ['Sam', 'Sarah', 'Ryan', 'Poppy']; const playersCopy3 = [...players]; playersCopy3[3] = 'heeee hawww'; document.write(players, playersCopy3);</script>",
"e": 4628,
"s": 4451,
"text": null
},
{
"code": null,
"e": 4636,
"s": 4628,
"text": "Output:"
},
{
"code": null,
"e": 4715,
"s": 4636,
"text": " [\"Sam\", \"Sarah\", \"Ryan\", \"Poppy\"]\n [\"Sam\", \"Sarah\", \"Ryan\", \"heeee hawww\"]\n"
},
{
"code": null,
"e": 4993,
"s": 4715,
"text": "By using Array.from():<script> const players = ['Sam', 'Sarah', 'Ryan', 'Poppy']; const playersCopy4 = Array.from(players); playersCopy4[3]=\"kim\"; document.write(players, playersCopy4);</script>Output: \n[\"Sam\", \"Sarah\", \"Ryan\", \"Poppy\"]\n[\"Sam\", \"Sarah\", \"Ryan\", \"kim\"]\n"
},
{
"code": "<script> const players = ['Sam', 'Sarah', 'Ryan', 'Poppy']; const playersCopy4 = Array.from(players); playersCopy4[3]=\"kim\"; document.write(players, playersCopy4);</script>",
"e": 5172,
"s": 4993,
"text": null
},
{
"code": null,
"e": 5180,
"s": 5172,
"text": "Output:"
},
{
"code": null,
"e": 5251,
"s": 5180,
"text": " \n[\"Sam\", \"Sarah\", \"Ryan\", \"Poppy\"]\n[\"Sam\", \"Sarah\", \"Ryan\", \"kim\"]\n"
},
{
"code": null,
"e": 5350,
"s": 5251,
"text": "Pass by reference in Object: The same point goes for objects, it also affects the original object."
},
{
"code": "const person = { name: 'loren isum', age: 80 };const captain = person;person.age = 25;console.log(captain, person);",
"e": 5479,
"s": 5350,
"text": null
},
{
"code": null,
"e": 5487,
"s": 5479,
"text": "Output:"
},
{
"code": null,
"e": 5548,
"s": 5487,
"text": "{name: \"loren isum\", age: 25}\n{name: \"loren isum\", age: 25}\n"
},
{
"code": null,
"e": 5577,
"s": 5548,
"text": "There are two ways to do it."
},
{
"code": null,
"e": 6180,
"s": 5577,
"text": "By using the assign() method:<script>const personObject = { name: 'loren isum', age: 80 };const personCopy = Object.assign({}, personObject, { number: 99, age: 12 });personCopy.age = 78;console.log(personCopy, personObject);</script>Output:{name: \"loren isum\", age: 78, number: 99}\n{name: \"loren isum\", age: 80}\nBy using the Spread operator:<script>const personData = { name: 'loren isum', age: 80 };const personCopy2 = {...personData };personCopy2.age = 78;console.log(personCopy2, personData );</script>Output:{name: \"loren isum\", age: 78}\n{name: \"loren isum\", age: 80}\n"
},
{
"code": null,
"e": 6510,
"s": 6180,
"text": "By using the assign() method:<script>const personObject = { name: 'loren isum', age: 80 };const personCopy = Object.assign({}, personObject, { number: 99, age: 12 });personCopy.age = 78;console.log(personCopy, personObject);</script>Output:{name: \"loren isum\", age: 78, number: 99}\n{name: \"loren isum\", age: 80}\n"
},
{
"code": "<script>const personObject = { name: 'loren isum', age: 80 };const personCopy = Object.assign({}, personObject, { number: 99, age: 12 });personCopy.age = 78;console.log(personCopy, personObject);</script>",
"e": 6732,
"s": 6510,
"text": null
},
{
"code": null,
"e": 6740,
"s": 6732,
"text": "Output:"
},
{
"code": null,
"e": 6813,
"s": 6740,
"text": "{name: \"loren isum\", age: 78, number: 99}\n{name: \"loren isum\", age: 80}\n"
},
{
"code": null,
"e": 7087,
"s": 6813,
"text": "By using the Spread operator:<script>const personData = { name: 'loren isum', age: 80 };const personCopy2 = {...personData };personCopy2.age = 78;console.log(personCopy2, personData );</script>Output:{name: \"loren isum\", age: 78}\n{name: \"loren isum\", age: 80}\n"
},
{
"code": "<script>const personData = { name: 'loren isum', age: 80 };const personCopy2 = {...personData };personCopy2.age = 78;console.log(personCopy2, personData );</script>",
"e": 7265,
"s": 7087,
"text": null
},
{
"code": null,
"e": 7273,
"s": 7265,
"text": "Output:"
},
{
"code": null,
"e": 7334,
"s": 7273,
"text": "{name: \"loren isum\", age: 78}\n{name: \"loren isum\", age: 80}\n"
},
{
"code": null,
"e": 7650,
"s": 7334,
"text": "One more thing you need to think about what will happen in the case of an equal and equality operator. When we use these operators on reference type variables they check the reference. If the property has a reference to the same item then the comparison will give output as “true”, otherwise it will return “false.”"
},
{
"code": "<script> var arrayReference = [\"Hi!\"]; var arrayCopy = arrayReference; console.log(arrayCopy === arrayReference); </script>",
"e": 7774,
"s": 7650,
"text": null
},
{
"code": null,
"e": 7782,
"s": 7774,
"text": "Output:"
},
{
"code": null,
"e": 7789,
"s": 7782,
"text": " true\n"
},
{
"code": "<script>var array1 = ['Hi!'];var array2 = ['Hi!'];console.log(array1 === array2);</script>",
"e": 7880,
"s": 7789,
"text": null
},
{
"code": null,
"e": 7888,
"s": 7880,
"text": "Output:"
},
{
"code": null,
"e": 7895,
"s": 7888,
"text": "false\n"
},
{
"code": null,
"e": 7944,
"s": 7895,
"text": "This can be corrected by stringifying the array."
},
{
"code": "<script>var arr1str = JSON.stringify(array1);var arr2str = JSON.stringify(array2);console.log(arr1str === arr2str); // true</script>",
"e": 8077,
"s": 7944,
"text": null
},
{
"code": null,
"e": 8085,
"s": 8077,
"text": "Output:"
},
{
"code": null,
"e": 8093,
"s": 8085,
"text": " true\n"
},
{
"code": null,
"e": 8226,
"s": 8093,
"text": "We can change the name property of object person, but we are unable to reset the reference person since it has been marked as const."
},
{
"code": "<script> const person = { name: 'Tammy' }; // Name property changed person.name = 'abc'; // Objects are a reference type var val1 = { name: \"Tom\" }; var val2 = { name: \"Tom\" }; console.log(val1 == val2) </script>",
"e": 8452,
"s": 8226,
"text": null
},
{
"code": null,
"e": 8460,
"s": 8452,
"text": "Output:"
},
{
"code": null,
"e": 8468,
"s": 8460,
"text": " false\n"
},
{
"code": null,
"e": 8525,
"s": 8468,
"text": "But we can correct this thing by stringifying the array."
},
{
"code": "<script> var array1 = ['Hi!']; var array2 = ['Hi!']; var arr1str = JSON.stringify(array1); var arr2str = JSON.stringify(array2); console.log(arr1str === arr2str); </script>",
"e": 8698,
"s": 8525,
"text": null
},
{
"code": null,
"e": 8706,
"s": 8698,
"text": "Output:"
},
{
"code": null,
"e": 8714,
"s": 8706,
"text": " true\n"
},
{
"code": null,
"e": 8826,
"s": 8714,
"text": "Pass by reference in case of functions: If we pass the object in the function, it will change both the objects."
},
{
"code": "<script>function changevalue(person) { var newPersonObj = (person); newPersonObj.age = 25; return newPersonObj;}var alex = { name: 'xyz', age: 30};var alexChanged = changevalue(alex);console.log(alex); console.log(alexChanged); </script>",
"e": 9079,
"s": 8826,
"text": null
},
{
"code": null,
"e": 9087,
"s": 9079,
"text": "Output:"
},
{
"code": null,
"e": 9138,
"s": 9087,
"text": "{ name: 'xyz', age: 25 }\n{ name: 'xyz', age: 25 }\n"
},
{
"code": null,
"e": 9206,
"s": 9138,
"text": "We can resolve this problem by parsing and stringifying the object."
},
{
"code": "<script>function changevalue(person) { var newPersonObj = JSON.parse(JSON.stringify(person)); newPersonObj.age = 25; return newPersonObj;}var alex = { name: 'xyz', age: 30};var alexChanged = changevalue(alex);console.log(alex); console.log(alexChanged); </script>",
"e": 9486,
"s": 9206,
"text": null
},
{
"code": null,
"e": 9494,
"s": 9486,
"text": "Output:"
},
{
"code": null,
"e": 9549,
"s": 9494,
"text": " { name: 'xyz', age: 30 }\n { name: 'xyz', age: 25 }\n"
},
{
"code": null,
"e": 9565,
"s": 9549,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 9576,
"s": 9565,
"text": "JavaScript"
},
{
"code": null,
"e": 9593,
"s": 9576,
"text": "Web Technologies"
},
{
"code": null,
"e": 9691,
"s": 9593,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9752,
"s": 9691,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 9824,
"s": 9752,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 9864,
"s": 9824,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 9906,
"s": 9864,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 9947,
"s": 9906,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 9980,
"s": 9947,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 10042,
"s": 9980,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 10103,
"s": 10042,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 10153,
"s": 10103,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Replace all the NaN values with Zero’s in a column of a Pandas dataframe
|
25 Aug, 2021
Replacing the NaN or the null values in a dataframe can be easily performed using a single line DataFrame.fillna() and DataFrame.replace() method. We will discuss these methods along with an example demonstrating how to use it.
This method is used to fill null or null values with a specific value.
Syntax: DataFrame.fillna(self, value=None, method=None, axis=None, inplace=False, limit=None, downcast=None)
Parameters: This method will take following parameters:
value (scalar, dict, Series, or DataFrame): Specify the value to use to fill null values.
method([‘backfill’, ‘bfill’, ‘pad’, ‘ffill’, None], default None): Specify the method used to fill null values.
axis (0 or ‘index’, 1 or ‘columns’): Specify the axis along which to fill missing values.
inplace(bool, default False): If bool value is True, fill in-place which will modify any other views on this object.
limit(int, default None): Specify the maximum number of consecutive NaN values to forward/backward fill.
downcast(dict, default is None): A dict of item dtype of what to downcast if possible, or the string ‘infer’ which will try to downcast to an appropriate equal type (e.g. float64 to int64 if possible).
Returns: DataFrame or None. Object with null values filled or None if inplace=True.
Code: Create a Dataframe.
Python3
# Import Pandas Libraryimport pandas as pd # Import Numpy Libraryimport numpy as np # Create a DataFramedf = pd.DataFrame([[np.nan, 2, 3, np.nan], [3, 4, np.nan, 1], [1, np.nan, np.nan, 5], [np.nan, 3, np.nan, 4]]) # Show the DataFrameprint(df)
Output:
Code: Replace all the NaN values with Zero’s
Python3
# Filling null values# with 0df.fillna(value = 0, inplace = True) # Show the DataFrameprint(df)
Output:
This method is used to replace null or null values with a specific value.
Syntax: DataFrame.replace(self, to_replace=None, value=None, inplace=False, limit=None, regex=False, method=’pad’)
Parameters: This method will take following parameters:
to_replace(str, regex, list, dict, Series, int, float, None): Specify the values that will be replaced.
value(scalar, dict, list, str, regex, default value is None): Specify the value to replace any values matching to_replace with.
inplace(bool, default False): If a value is True, in place. Note: this will modify any other views on this object.
limit(int, default None): Specify the maximum size gap to forward or backward fill.
regex(bool or same types as to_replace, default False): If a value is True then to_replace must be a string. Alternatively, this could be a regular expression or a list, dict, or array of regular expressions in which case to_replace must be None.
method {‘pad’, ‘ffill’, ‘bfill’, None}: Specify the method to use when for replacement, when to_replace is a scalar, list or tuple and value is None.
Returns: DataFrame. Object after replacement.
Code: Create a Dataframe.
Python3
# Import Pandas Libraryimport pandas as pd # Import Numpy Libraryimport numpy as np # Create a DataFramedf = pd.DataFrame([[np.nan, 2, 3, np.nan], [3, 4, np.nan, 1], [1, np.nan, np.nan, 5], [np.nan, 3, np.nan, 4]]) # Show the DataFrameprint(df)
Output:
Code: Replace all the NaN values with Zero’s
Python3
# Filling null values with 0df = df.replace(np.nan, 0) # Show the DataFrameprint(df)
Output:
anikakapoor
Picked
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Aug, 2021"
},
{
"code": null,
"e": 257,
"s": 28,
"text": "Replacing the NaN or the null values in a dataframe can be easily performed using a single line DataFrame.fillna() and DataFrame.replace() method. We will discuss these methods along with an example demonstrating how to use it."
},
{
"code": null,
"e": 328,
"s": 257,
"text": "This method is used to fill null or null values with a specific value."
},
{
"code": null,
"e": 470,
"s": 328,
"text": "Syntax: DataFrame.fillna(self, value=None, method=None, axis=None, inplace=False, limit=None, downcast=None)"
},
{
"code": null,
"e": 526,
"s": 470,
"text": "Parameters: This method will take following parameters:"
},
{
"code": null,
"e": 617,
"s": 526,
"text": "value (scalar, dict, Series, or DataFrame): Specify the value to use to fill null values."
},
{
"code": null,
"e": 729,
"s": 617,
"text": "method([‘backfill’, ‘bfill’, ‘pad’, ‘ffill’, None], default None): Specify the method used to fill null values."
},
{
"code": null,
"e": 819,
"s": 729,
"text": "axis (0 or ‘index’, 1 or ‘columns’): Specify the axis along which to fill missing values."
},
{
"code": null,
"e": 936,
"s": 819,
"text": "inplace(bool, default False): If bool value is True, fill in-place which will modify any other views on this object."
},
{
"code": null,
"e": 1041,
"s": 936,
"text": "limit(int, default None): Specify the maximum number of consecutive NaN values to forward/backward fill."
},
{
"code": null,
"e": 1243,
"s": 1041,
"text": "downcast(dict, default is None): A dict of item dtype of what to downcast if possible, or the string ‘infer’ which will try to downcast to an appropriate equal type (e.g. float64 to int64 if possible)."
},
{
"code": null,
"e": 1327,
"s": 1243,
"text": "Returns: DataFrame or None. Object with null values filled or None if inplace=True."
},
{
"code": null,
"e": 1353,
"s": 1327,
"text": "Code: Create a Dataframe."
},
{
"code": null,
"e": 1361,
"s": 1353,
"text": "Python3"
},
{
"code": "# Import Pandas Libraryimport pandas as pd # Import Numpy Libraryimport numpy as np # Create a DataFramedf = pd.DataFrame([[np.nan, 2, 3, np.nan], [3, 4, np.nan, 1], [1, np.nan, np.nan, 5], [np.nan, 3, np.nan, 4]]) # Show the DataFrameprint(df)",
"e": 1660,
"s": 1361,
"text": null
},
{
"code": null,
"e": 1668,
"s": 1660,
"text": "Output:"
},
{
"code": null,
"e": 1713,
"s": 1668,
"text": "Code: Replace all the NaN values with Zero’s"
},
{
"code": null,
"e": 1721,
"s": 1713,
"text": "Python3"
},
{
"code": "# Filling null values# with 0df.fillna(value = 0, inplace = True) # Show the DataFrameprint(df)",
"e": 1826,
"s": 1721,
"text": null
},
{
"code": null,
"e": 1834,
"s": 1826,
"text": "Output:"
},
{
"code": null,
"e": 1908,
"s": 1834,
"text": "This method is used to replace null or null values with a specific value."
},
{
"code": null,
"e": 2047,
"s": 1908,
"text": "Syntax: DataFrame.replace(self, to_replace=None, value=None, inplace=False, limit=None, regex=False, method=’pad’)"
},
{
"code": null,
"e": 2103,
"s": 2047,
"text": "Parameters: This method will take following parameters:"
},
{
"code": null,
"e": 2207,
"s": 2103,
"text": "to_replace(str, regex, list, dict, Series, int, float, None): Specify the values that will be replaced."
},
{
"code": null,
"e": 2335,
"s": 2207,
"text": "value(scalar, dict, list, str, regex, default value is None): Specify the value to replace any values matching to_replace with."
},
{
"code": null,
"e": 2450,
"s": 2335,
"text": "inplace(bool, default False): If a value is True, in place. Note: this will modify any other views on this object."
},
{
"code": null,
"e": 2534,
"s": 2450,
"text": "limit(int, default None): Specify the maximum size gap to forward or backward fill."
},
{
"code": null,
"e": 2782,
"s": 2534,
"text": "regex(bool or same types as to_replace, default False): If a value is True then to_replace must be a string. Alternatively, this could be a regular expression or a list, dict, or array of regular expressions in which case to_replace must be None."
},
{
"code": null,
"e": 2932,
"s": 2782,
"text": "method {‘pad’, ‘ffill’, ‘bfill’, None}: Specify the method to use when for replacement, when to_replace is a scalar, list or tuple and value is None."
},
{
"code": null,
"e": 2978,
"s": 2932,
"text": "Returns: DataFrame. Object after replacement."
},
{
"code": null,
"e": 3004,
"s": 2978,
"text": "Code: Create a Dataframe."
},
{
"code": null,
"e": 3012,
"s": 3004,
"text": "Python3"
},
{
"code": "# Import Pandas Libraryimport pandas as pd # Import Numpy Libraryimport numpy as np # Create a DataFramedf = pd.DataFrame([[np.nan, 2, 3, np.nan], [3, 4, np.nan, 1], [1, np.nan, np.nan, 5], [np.nan, 3, np.nan, 4]]) # Show the DataFrameprint(df)",
"e": 3311,
"s": 3012,
"text": null
},
{
"code": null,
"e": 3319,
"s": 3311,
"text": "Output:"
},
{
"code": null,
"e": 3364,
"s": 3319,
"text": "Code: Replace all the NaN values with Zero’s"
},
{
"code": null,
"e": 3372,
"s": 3364,
"text": "Python3"
},
{
"code": "# Filling null values with 0df = df.replace(np.nan, 0) # Show the DataFrameprint(df)",
"e": 3457,
"s": 3372,
"text": null
},
{
"code": null,
"e": 3465,
"s": 3457,
"text": "Output:"
},
{
"code": null,
"e": 3477,
"s": 3465,
"text": "anikakapoor"
},
{
"code": null,
"e": 3484,
"s": 3477,
"text": "Picked"
},
{
"code": null,
"e": 3491,
"s": 3484,
"text": "Python"
},
{
"code": null,
"e": 3589,
"s": 3491,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3607,
"s": 3589,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3649,
"s": 3607,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3671,
"s": 3649,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3706,
"s": 3671,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 3732,
"s": 3706,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3764,
"s": 3732,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3793,
"s": 3764,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3823,
"s": 3793,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 3850,
"s": 3823,
"text": "Python Classes and Objects"
}
] |
Matplotlib.pyplot.ylabel() in Python
|
12 Apr, 2020
Matplotlib is a very powerful plotting library useful for those working with Python and NumPy. And for making statistical interference, it becomes very necessary to visualize our data and Matplotlib is the tool that can be very helpful for this purpose.
This function sets the label for the y-axis of the plot.
Syntax: matplotlib.pyplot.ylabel(ylabel, fontdict=None, labelpad=None)
Parameters:ylabel: The name of the labelfontdict: Adds the font styles to the labellabelpad: This helps us to set the spacing between label and the axis
Example #1:
import matplotlib.pyplot as plt # setting x valuesx =['Geeks', 'for', 'geeks', 'tutorials'] # Setting y values y =[1, 2, 3, 4] # Adding label on the y-axisplt.ylabel('Numbers label') # plotting the graphplt.plot(x, y)
Output:
Example #2:
import matplotlib.pyplot as plt x =['Geeks', 'for', 'geeks', 'tutorials']y =[1, 2, 3, 4] # Adding space between label and# axis by setting labelpadplt.ylabel('Numbers label', labelpad = 50) plt.plot(x, y)
Output:
Example #3:
import matplotlib.pyplot as plt x =['Geeks', 'for', 'geeks', 'tutorials']y =[1, 2, 3, 4] # Setting font dictionary font = {'family': 'Verdana', 'color': 'green', 'size': 20, } # Adding the font styles to the labelplt.ylabel('Numbers label', fontdict = font) plt.plot(x, y)
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Apr, 2020"
},
{
"code": null,
"e": 282,
"s": 28,
"text": "Matplotlib is a very powerful plotting library useful for those working with Python and NumPy. And for making statistical interference, it becomes very necessary to visualize our data and Matplotlib is the tool that can be very helpful for this purpose."
},
{
"code": null,
"e": 339,
"s": 282,
"text": "This function sets the label for the y-axis of the plot."
},
{
"code": null,
"e": 410,
"s": 339,
"text": "Syntax: matplotlib.pyplot.ylabel(ylabel, fontdict=None, labelpad=None)"
},
{
"code": null,
"e": 563,
"s": 410,
"text": "Parameters:ylabel: The name of the labelfontdict: Adds the font styles to the labellabelpad: This helps us to set the spacing between label and the axis"
},
{
"code": null,
"e": 575,
"s": 563,
"text": "Example #1:"
},
{
"code": "import matplotlib.pyplot as plt # setting x valuesx =['Geeks', 'for', 'geeks', 'tutorials'] # Setting y values y =[1, 2, 3, 4] # Adding label on the y-axisplt.ylabel('Numbers label') # plotting the graphplt.plot(x, y)",
"e": 797,
"s": 575,
"text": null
},
{
"code": null,
"e": 805,
"s": 797,
"text": "Output:"
},
{
"code": null,
"e": 817,
"s": 805,
"text": "Example #2:"
},
{
"code": "import matplotlib.pyplot as plt x =['Geeks', 'for', 'geeks', 'tutorials']y =[1, 2, 3, 4] # Adding space between label and# axis by setting labelpadplt.ylabel('Numbers label', labelpad = 50) plt.plot(x, y)",
"e": 1025,
"s": 817,
"text": null
},
{
"code": null,
"e": 1033,
"s": 1025,
"text": "Output:"
},
{
"code": null,
"e": 1045,
"s": 1033,
"text": "Example #3:"
},
{
"code": "import matplotlib.pyplot as plt x =['Geeks', 'for', 'geeks', 'tutorials']y =[1, 2, 3, 4] # Setting font dictionary font = {'family': 'Verdana', 'color': 'green', 'size': 20, } # Adding the font styles to the labelplt.ylabel('Numbers label', fontdict = font) plt.plot(x, y)",
"e": 1344,
"s": 1045,
"text": null
},
{
"code": null,
"e": 1352,
"s": 1344,
"text": "Output:"
},
{
"code": null,
"e": 1370,
"s": 1352,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 1377,
"s": 1370,
"text": "Python"
}
] |
Static methods vs Instance methods in Java
|
11 Feb, 2022
Instance Method
Instance method are methods which require an object of its class to be created before it can be called. To invoke a instance method, we have to create an Object of the class in which the method is defined.
public void geek(String name)
{
// code to be executed....
}
// Return type can be int, float String or user defined data type.
Memory allocation: These methods themselves are stored in Permanent Generation space of heap but the parameters (arguments passed to them) and their local variables and the value to be returned are allocated in stack. They can be called within the same class in which they reside or from the different classes defined either in the same package or other packages depend on the access type provided to the desired instance method.Important Points:
Instance method(s) belong to the Object of the class, not to the class i.e. they can be called after creating the Object of the class.
Instance methods are not stored on a per-instance basis, even with virtual methods. They’re stored in a single memory location, and they only “know” which object they belong to because this pointer is passed when you call them.
They can be overridden since they are resolved using dynamic binding at run time.
Below is the implementation of accessing the instance method:
Java
// Example to illustrate accessing the instance method .import java.io.*; class Foo { String name = ""; // Instance method to be called within the // same class or from a another class defined // in the same package or in different package. public void geek(String name) { this.name = name; }} class GFG { public static void main(String[] args) { // create an instance of the class. Foo ob = new Foo(); // calling an instance method in the class 'Foo'. ob.geek("GeeksforGeeks"); System.out.println(ob.name); }}
GeeksforGeeks
Static Method
Static methods are the methods in Java that can be called without creating an object of class. They are referenced by the class name itself or reference to the Object of that class.
public static void geek(String name)
{
// code to be executed....
}
// Must have static modifier in their declaration.
// Return type can be int, float, String or user defined data type.
Memory Allocation:
They are stored in the Permanent Generation space of heap as they are associated with the class in which they reside not to the objects of that class. But their local variables and the passed argument(s) to them are stored in the stack. Since they belong to the class, so they can be called to without creating the object of the class.
Important Points:
Static method(s) are associated with the class in which they reside i.e. they are called without creating an instance of the class i.e ClassName.methodName(args).
They are designed with the aim to be shared among all objects created from the same class.
Static methods can not be overridden, since they are resolved using static binding by the compiler at compile time. However, we can have the same name methods declared static in both superclass and subclass, but it will be called Method Hiding as the derived class method will hide the base class method.
Below is the illustration of accessing the static methods:
Java
// Example to illustrate Accessing// the Static method(s) of the class.import java.io.*; class Geek { public static String geekName = ""; public static void geek(String name) { geekName = name; }} class GFG { public static void main(String[] args) { // Accessing the static method geek() // and field by class name itself. Geek.geek("vaibhav"); System.out.println(Geek.geekName); // Accessing the static method geek() // by using Object's reference. Geek obj = new Geek(); obj.geek("mohit"); System.out.println(obj.geekName); }}
vaibhav
mohit
Note: Static variables and their values (primitives or references) defined in the class are stored in PermGen space of memory.
What if static variable refers to an Object?
static int i = 1;
static Object obj = new Object();
In the first line, the value 1 would be stored in PermGen section. In second line, the reference obj would be stored in PermGen section and the Object it refers to would be stored in heap section.
When to use static methods?
When you have code that can be shared across all instances of the same class, put that portion of code into static method.
They are basically used to access static field(s) of the class.
Instance method vs Static method
Instance method can access the instance methods and instance variables directly.
Instance method can access static variables and static methods directly.
Static methods can access the static variables and static methods directly.
Static methods can’t access instance methods and instance variables directly. They must use reference to object. And static method can’t use this keyword as there is no instance for ‘this’ to refer to.
References
https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
Stackoverflow
This article is contributed by Nitsdheerendra. 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.
temnur
tanyasingh27
email4shaun
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n11 Feb, 2022"
},
{
"code": null,
"e": 70,
"s": 54,
"text": "Instance Method"
},
{
"code": null,
"e": 277,
"s": 70,
"text": "Instance method are methods which require an object of its class to be created before it can be called. To invoke a instance method, we have to create an Object of the class in which the method is defined. "
},
{
"code": null,
"e": 406,
"s": 277,
"text": "public void geek(String name)\n{\n // code to be executed....\n}\n// Return type can be int, float String or user defined data type."
},
{
"code": null,
"e": 855,
"s": 406,
"text": "Memory allocation: These methods themselves are stored in Permanent Generation space of heap but the parameters (arguments passed to them) and their local variables and the value to be returned are allocated in stack. They can be called within the same class in which they reside or from the different classes defined either in the same package or other packages depend on the access type provided to the desired instance method.Important Points: "
},
{
"code": null,
"e": 990,
"s": 855,
"text": "Instance method(s) belong to the Object of the class, not to the class i.e. they can be called after creating the Object of the class."
},
{
"code": null,
"e": 1218,
"s": 990,
"text": "Instance methods are not stored on a per-instance basis, even with virtual methods. They’re stored in a single memory location, and they only “know” which object they belong to because this pointer is passed when you call them."
},
{
"code": null,
"e": 1300,
"s": 1218,
"text": "They can be overridden since they are resolved using dynamic binding at run time."
},
{
"code": null,
"e": 1362,
"s": 1300,
"text": "Below is the implementation of accessing the instance method:"
},
{
"code": null,
"e": 1367,
"s": 1362,
"text": "Java"
},
{
"code": "// Example to illustrate accessing the instance method .import java.io.*; class Foo { String name = \"\"; // Instance method to be called within the // same class or from a another class defined // in the same package or in different package. public void geek(String name) { this.name = name; }} class GFG { public static void main(String[] args) { // create an instance of the class. Foo ob = new Foo(); // calling an instance method in the class 'Foo'. ob.geek(\"GeeksforGeeks\"); System.out.println(ob.name); }}",
"e": 1941,
"s": 1367,
"text": null
},
{
"code": null,
"e": 1955,
"s": 1941,
"text": "GeeksforGeeks"
},
{
"code": null,
"e": 1971,
"s": 1957,
"text": "Static Method"
},
{
"code": null,
"e": 2155,
"s": 1971,
"text": "Static methods are the methods in Java that can be called without creating an object of class. They are referenced by the class name itself or reference to the Object of that class. "
},
{
"code": null,
"e": 2344,
"s": 2155,
"text": "public static void geek(String name)\n{\n // code to be executed....\n}\n\n// Must have static modifier in their declaration.\n// Return type can be int, float, String or user defined data type."
},
{
"code": null,
"e": 2364,
"s": 2344,
"text": "Memory Allocation: "
},
{
"code": null,
"e": 2700,
"s": 2364,
"text": "They are stored in the Permanent Generation space of heap as they are associated with the class in which they reside not to the objects of that class. But their local variables and the passed argument(s) to them are stored in the stack. Since they belong to the class, so they can be called to without creating the object of the class."
},
{
"code": null,
"e": 2720,
"s": 2700,
"text": "Important Points: "
},
{
"code": null,
"e": 2883,
"s": 2720,
"text": "Static method(s) are associated with the class in which they reside i.e. they are called without creating an instance of the class i.e ClassName.methodName(args)."
},
{
"code": null,
"e": 2974,
"s": 2883,
"text": "They are designed with the aim to be shared among all objects created from the same class."
},
{
"code": null,
"e": 3279,
"s": 2974,
"text": "Static methods can not be overridden, since they are resolved using static binding by the compiler at compile time. However, we can have the same name methods declared static in both superclass and subclass, but it will be called Method Hiding as the derived class method will hide the base class method."
},
{
"code": null,
"e": 3339,
"s": 3279,
"text": "Below is the illustration of accessing the static methods: "
},
{
"code": null,
"e": 3344,
"s": 3339,
"text": "Java"
},
{
"code": "// Example to illustrate Accessing// the Static method(s) of the class.import java.io.*; class Geek { public static String geekName = \"\"; public static void geek(String name) { geekName = name; }} class GFG { public static void main(String[] args) { // Accessing the static method geek() // and field by class name itself. Geek.geek(\"vaibhav\"); System.out.println(Geek.geekName); // Accessing the static method geek() // by using Object's reference. Geek obj = new Geek(); obj.geek(\"mohit\"); System.out.println(obj.geekName); }}",
"e": 3968,
"s": 3344,
"text": null
},
{
"code": null,
"e": 3982,
"s": 3968,
"text": "vaibhav\nmohit"
},
{
"code": null,
"e": 4111,
"s": 3982,
"text": "Note: Static variables and their values (primitives or references) defined in the class are stored in PermGen space of memory. "
},
{
"code": null,
"e": 4157,
"s": 4111,
"text": "What if static variable refers to an Object? "
},
{
"code": null,
"e": 4209,
"s": 4157,
"text": "static int i = 1;\nstatic Object obj = new Object();"
},
{
"code": null,
"e": 4406,
"s": 4209,
"text": "In the first line, the value 1 would be stored in PermGen section. In second line, the reference obj would be stored in PermGen section and the Object it refers to would be stored in heap section."
},
{
"code": null,
"e": 4435,
"s": 4406,
"text": "When to use static methods? "
},
{
"code": null,
"e": 4558,
"s": 4435,
"text": "When you have code that can be shared across all instances of the same class, put that portion of code into static method."
},
{
"code": null,
"e": 4622,
"s": 4558,
"text": "They are basically used to access static field(s) of the class."
},
{
"code": null,
"e": 4655,
"s": 4622,
"text": "Instance method vs Static method"
},
{
"code": null,
"e": 4736,
"s": 4655,
"text": "Instance method can access the instance methods and instance variables directly."
},
{
"code": null,
"e": 4809,
"s": 4736,
"text": "Instance method can access static variables and static methods directly."
},
{
"code": null,
"e": 4885,
"s": 4809,
"text": "Static methods can access the static variables and static methods directly."
},
{
"code": null,
"e": 5087,
"s": 4885,
"text": "Static methods can’t access instance methods and instance variables directly. They must use reference to object. And static method can’t use this keyword as there is no instance for ‘this’ to refer to."
},
{
"code": null,
"e": 5099,
"s": 5087,
"text": "References "
},
{
"code": null,
"e": 5166,
"s": 5099,
"text": "https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html"
},
{
"code": null,
"e": 5180,
"s": 5166,
"text": "Stackoverflow"
},
{
"code": null,
"e": 5603,
"s": 5180,
"text": "This article is contributed by Nitsdheerendra. 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": 5610,
"s": 5603,
"text": "temnur"
},
{
"code": null,
"e": 5623,
"s": 5610,
"text": "tanyasingh27"
},
{
"code": null,
"e": 5635,
"s": 5623,
"text": "email4shaun"
},
{
"code": null,
"e": 5640,
"s": 5635,
"text": "Java"
},
{
"code": null,
"e": 5645,
"s": 5640,
"text": "Java"
}
] |
Mathematics | Set Operations (Set theory)
|
05 Mar, 2021
Union of the sets A and B, denoted by A ∪ B, is the set of distinct elements that belong to set A or set B, or both.
Venn diagram of A ∪ B
Above is the Venn Diagram of A U B.
Example: Find the union of A = {2, 3, 4} and B = {3, 4, 5};
Solution : A ∪ B = {2, 3, 4, 5}.
The intersection of the sets A and B, denoted by A ∩ B, is the set of elements that belong to both A and B i.e. set of the common elements in A and B.
Venn diagram of A ∩ B
Above is the Venn Diagram of A ∩ B.
Example: Find the intersection of A = {2, 3, 4} and B = {3, 4, 5}
Solution : A ∩ B = {3, 4}.
Two sets are said to be disjoint if their intersection is the empty set. i.e, sets have no common elements.
Above is the Venn Diagram of A disjoint B.
Example: Let A = {1, 3, 5, 7, 9} and B = { 2, 4, 6, 8}
A and B are disjoint sets since both of them have no common elements.
The difference between sets is denoted by ‘A – B’, which is the set containing elements that are in A but not in B. i.e., all elements of A except the element of B.
Above is the Venn Diagram of A-B.
Example: If A = {1, 2, 3, 4, 5} and B = { 2, 4, 6, 8}, find A-B
Solution: A-B = {1, 3, 5}
The complement of a set A, denoted by AC is the set of all the elements except the elements in A. Complement of the set A is U – A.
Above is the Venn Diagram of Ac
Example: Let U = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} and A = {2, 4, 6, 8}.
Find AC
Solution: AC = U-A = {1, 3, 5, 7, 9, 10}
Addition of sets A and B, referred to as Minkowski addition, is the set in whose elements are the sum of each possible pair of elements from the 2 sets (that is one element is from set A and the other is from set B).Set subtraction follows the same rule, but with the subtraction operation on the elements. It is to be observed that these operations are operable only on numeric data types. Even if operated otherwise, it would only be a symbolic representation without any significance. Further, it can be seen easily that set addition is commutative, while subtraction is not.
For addition and consequently subtraction, please refer to this answer.
[Tex]A-B=A\cap \bar{B} [/Tex]
Associative Properties: A ∪ (B ∪ C) = (A ∪ B) ∪ C and A ∩ (B ∩ C) = (A ∩ B) ∩ CCommutative Properties: A ∪ B = B ∪ A and A ∩ B = B ∩ AIdentity Property for Union: A ∪ φ = AIntersection Property of the Empty Set: A ∩ φ = φDistributive Properties: A ∪ (B ∩ C) = (A ∪ B) ∩ (A ∪ C) similarly for intersection.
Associative Properties: A ∪ (B ∪ C) = (A ∪ B) ∪ C and A ∩ (B ∩ C) = (A ∩ B) ∩ C
Commutative Properties: A ∪ B = B ∪ A and A ∩ B = B ∩ A
Identity Property for Union: A ∪ φ = A
Intersection Property of the Empty Set: A ∩ φ = φ
Distributive Properties: A ∪ (B ∩ C) = (A ∪ B) ∩ (A ∪ C) similarly for intersection.
VaibhavRai3
PunitVerma
soumyasharma3
kaman7580
rohittopi474
animeshsingh70610
Engineering Mathematics
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inequalities in LaTeX
Difference between Propositional Logic and Predicate Logic
Arrow Symbols in LaTeX
Set Notations in LaTeX
Activation Functions
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Types of Operating Systems
Normal Forms in DBMS
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n05 Mar, 2021"
},
{
"code": null,
"e": 170,
"s": 52,
"text": "Union of the sets A and B, denoted by A ∪ B, is the set of distinct elements that belong to set A or set B, or both. "
},
{
"code": null,
"e": 192,
"s": 170,
"text": "Venn diagram of A ∪ B"
},
{
"code": null,
"e": 228,
"s": 192,
"text": "Above is the Venn Diagram of A U B."
},
{
"code": null,
"e": 322,
"s": 228,
"text": "Example: Find the union of A = {2, 3, 4} and B = {3, 4, 5}; \nSolution : A ∪ B = {2, 3, 4, 5}."
},
{
"code": null,
"e": 474,
"s": 322,
"text": "The intersection of the sets A and B, denoted by A ∩ B, is the set of elements that belong to both A and B i.e. set of the common elements in A and B. "
},
{
"code": null,
"e": 496,
"s": 474,
"text": "Venn diagram of A ∩ B"
},
{
"code": null,
"e": 532,
"s": 496,
"text": "Above is the Venn Diagram of A ∩ B."
},
{
"code": null,
"e": 626,
"s": 532,
"text": "Example: Find the intersection of A = {2, 3, 4} and B = {3, 4, 5} \nSolution : A ∩ B = {3, 4}."
},
{
"code": null,
"e": 735,
"s": 626,
"text": "Two sets are said to be disjoint if their intersection is the empty set. i.e, sets have no common elements. "
},
{
"code": null,
"e": 778,
"s": 735,
"text": "Above is the Venn Diagram of A disjoint B."
},
{
"code": null,
"e": 905,
"s": 778,
"text": "Example: Let A = {1, 3, 5, 7, 9} and B = { 2, 4, 6, 8} \nA and B are disjoint sets since both of them have no common elements."
},
{
"code": null,
"e": 1071,
"s": 905,
"text": "The difference between sets is denoted by ‘A – B’, which is the set containing elements that are in A but not in B. i.e., all elements of A except the element of B. "
},
{
"code": null,
"e": 1105,
"s": 1071,
"text": "Above is the Venn Diagram of A-B."
},
{
"code": null,
"e": 1195,
"s": 1105,
"text": "Example: If A = {1, 2, 3, 4, 5} and B = { 2, 4, 6, 8}, find A-B\nSolution: A-B = {1, 3, 5}"
},
{
"code": null,
"e": 1328,
"s": 1195,
"text": "The complement of a set A, denoted by AC is the set of all the elements except the elements in A. Complement of the set A is U – A. "
},
{
"code": null,
"e": 1360,
"s": 1328,
"text": "Above is the Venn Diagram of Ac"
},
{
"code": null,
"e": 1480,
"s": 1360,
"text": "Example: Let U = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} and A = {2, 4, 6, 8}.\nFind AC\nSolution: AC = U-A = {1, 3, 5, 7, 9, 10}"
},
{
"code": null,
"e": 2061,
"s": 1480,
"text": "Addition of sets A and B, referred to as Minkowski addition, is the set in whose elements are the sum of each possible pair of elements from the 2 sets (that is one element is from set A and the other is from set B).Set subtraction follows the same rule, but with the subtraction operation on the elements. It is to be observed that these operations are operable only on numeric data types. Even if operated otherwise, it would only be a symbolic representation without any significance. Further, it can be seen easily that set addition is commutative, while subtraction is not. "
},
{
"code": null,
"e": 2133,
"s": 2061,
"text": "For addition and consequently subtraction, please refer to this answer."
},
{
"code": null,
"e": 2166,
"s": 2133,
"text": "[Tex]A-B=A\\cap \\bar{B} [/Tex] "
},
{
"code": null,
"e": 2472,
"s": 2166,
"text": "Associative Properties: A ∪ (B ∪ C) = (A ∪ B) ∪ C and A ∩ (B ∩ C) = (A ∩ B) ∩ CCommutative Properties: A ∪ B = B ∪ A and A ∩ B = B ∩ AIdentity Property for Union: A ∪ φ = AIntersection Property of the Empty Set: A ∩ φ = φDistributive Properties: A ∪ (B ∩ C) = (A ∪ B) ∩ (A ∪ C) similarly for intersection."
},
{
"code": null,
"e": 2552,
"s": 2472,
"text": "Associative Properties: A ∪ (B ∪ C) = (A ∪ B) ∪ C and A ∩ (B ∩ C) = (A ∩ B) ∩ C"
},
{
"code": null,
"e": 2608,
"s": 2552,
"text": "Commutative Properties: A ∪ B = B ∪ A and A ∩ B = B ∩ A"
},
{
"code": null,
"e": 2647,
"s": 2608,
"text": "Identity Property for Union: A ∪ φ = A"
},
{
"code": null,
"e": 2697,
"s": 2647,
"text": "Intersection Property of the Empty Set: A ∩ φ = φ"
},
{
"code": null,
"e": 2782,
"s": 2697,
"text": "Distributive Properties: A ∪ (B ∩ C) = (A ∪ B) ∩ (A ∪ C) similarly for intersection."
},
{
"code": null,
"e": 2794,
"s": 2782,
"text": "VaibhavRai3"
},
{
"code": null,
"e": 2805,
"s": 2794,
"text": "PunitVerma"
},
{
"code": null,
"e": 2819,
"s": 2805,
"text": "soumyasharma3"
},
{
"code": null,
"e": 2829,
"s": 2819,
"text": "kaman7580"
},
{
"code": null,
"e": 2842,
"s": 2829,
"text": "rohittopi474"
},
{
"code": null,
"e": 2860,
"s": 2842,
"text": "animeshsingh70610"
},
{
"code": null,
"e": 2884,
"s": 2860,
"text": "Engineering Mathematics"
},
{
"code": null,
"e": 2892,
"s": 2884,
"text": "GATE CS"
},
{
"code": null,
"e": 2990,
"s": 2892,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3012,
"s": 2990,
"text": "Inequalities in LaTeX"
},
{
"code": null,
"e": 3071,
"s": 3012,
"text": "Difference between Propositional Logic and Predicate Logic"
},
{
"code": null,
"e": 3094,
"s": 3071,
"text": "Arrow Symbols in LaTeX"
},
{
"code": null,
"e": 3117,
"s": 3094,
"text": "Set Notations in LaTeX"
},
{
"code": null,
"e": 3138,
"s": 3117,
"text": "Activation Functions"
},
{
"code": null,
"e": 3158,
"s": 3138,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 3182,
"s": 3158,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 3195,
"s": 3182,
"text": "TCP/IP Model"
},
{
"code": null,
"e": 3222,
"s": 3195,
"text": "Types of Operating Systems"
}
] |
How to create Swipe Navigation in an Android App
|
01 Jun, 2020
When talking about Android Apps, the first thing that comes to mind is variety. There are so many varieties of Android apps providing the user with beautiful dynamic UI. One such feature is to navigate in our Android Apps using left and right swipes as opposed to clicking on buttons. Not only does it look more simple and elegant but also provides ease of access to the user. There are many apps which use this swipe feature to swipe through different activities in the app. For example, the popular chatting app, Snapchat, uses it to swipe through lenses, chats and stories. Here, we will learn how to implement swipe views in our own Android app.
We can implement this by use of two features:
Fragments A fragment is just a part of an activity. We can have a fragment that takes up part of a screen or a whole screen. Or we can show multiple fragments at the same time to make up a whole screen. Within an activity, we can also swap out different fragments with each other. ViewPager ViewPager is a class in Java which is used in conjunction with Fragments. It is mostly used for designing the UI of the app.
Fragments A fragment is just a part of an activity. We can have a fragment that takes up part of a screen or a whole screen. Or we can show multiple fragments at the same time to make up a whole screen. Within an activity, we can also swap out different fragments with each other.
ViewPager ViewPager is a class in Java which is used in conjunction with Fragments. It is mostly used for designing the UI of the app.
How does it work?First we need to set an adapter on the ViewPager using the setAdapter() method. The adapter which we set is called FragmentPagerAdapter which is an abstract class in Java. Hence, we create our own SampleFragmentPagerAdapter which extends from FragmentPagerAdapter and displays our Fragments on the screen. When we launch the app in our device, the ViewPager asks the SampleFragmentPagerAdapter how many pages are there to swipe through. The getCount() method of the adapter returns this answer to the ViewPager. Then the ViewPager asks for the Fragment which is at the 0th position and the adapter returns that particular fragment which is then displayed by ViewPager on our screen. When we swipe left, ViewPager asks adapter for the Fragment at 1st position and similarly, it is displayed on the screen and it continues so on.
Step by step implementation:We will be creating three fragments that is three screens that the user can swipe through. Then we will add these fragments to our FragmentPagerAdapter and finally set it on ViewPager. Note: To run these codes, you need to copy and paste them in Android Studio as it won’t run on the IDE!
Step1: Creating Fragments: To create a fragment, click on app > Java > com.example.android(Right Click) > New > Fragment > Fragment(Blank) We can create as many Fragments as we want but since we will be displaying only three screens, hence we will create three Fragments. Now we will open our Fragments and copy this code over there: JavaJavapackage com.example.android.gfg; import android.os.Bundle;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup; public class Fragment1 extends Fragment { @Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater .inflate( R.layout.fragment_1, container, false); }}Explanation: We are importing v4 Fragment with BuildTools version “23.0.2“ . If we get an error in our imports, we must make sure that our BuildTools and SDK version corresponds to the libraries which we import.We name our Fragment as Fragment1.Fragment1 displays the layout fragment_1.xml which we will make now.
Step1: Creating Fragments: To create a fragment, click on app > Java > com.example.android(Right Click) > New > Fragment > Fragment(Blank)
We can create as many Fragments as we want but since we will be displaying only three screens, hence we will create three Fragments. Now we will open our Fragments and copy this code over there:
Java
package com.example.android.gfg; import android.os.Bundle;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup; public class Fragment1 extends Fragment { @Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater .inflate( R.layout.fragment_1, container, false); }}
Explanation:
We are importing v4 Fragment with BuildTools version “23.0.2“ . If we get an error in our imports, we must make sure that our BuildTools and SDK version corresponds to the libraries which we import.
We name our Fragment as Fragment1.
Fragment1 displays the layout fragment_1.xml which we will make now.
Step 2: Creating layouts for Fragments: Each Fragment needs to display a layout. We can design this layout anyhow we want. Here is the code to how we would implement this layout as: XMLXML<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="16dp"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/gfg"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="With the idea of imparting programming knowledge, Mr. Sandeep Jain, an IIT Roorkee alumnus started a dream, GeeksforGeeks. Whether programming excites you or you feel stifled, wondering how to prepare for interview questions or how to ace data structures and algorithms, GeeksforGeeks is a one-stop solution. " android:textSize="20sp" android:textColor="#81c784"/></LinearLayout>This looks like: Similarly, we will create two more Fragments and a respective layout for each one of them.
Step 2: Creating layouts for Fragments: Each Fragment needs to display a layout. We can design this layout anyhow we want. Here is the code to how we would implement this layout as:
XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="16dp"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/gfg"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="With the idea of imparting programming knowledge, Mr. Sandeep Jain, an IIT Roorkee alumnus started a dream, GeeksforGeeks. Whether programming excites you or you feel stifled, wondering how to prepare for interview questions or how to ace data structures and algorithms, GeeksforGeeks is a one-stop solution. " android:textSize="20sp" android:textColor="#81c784"/></LinearLayout>
This looks like:
Similarly, we will create two more Fragments and a respective layout for each one of them.
Step 3: Creating our FragmentPageAdapter: Now that we have all our three Fragments and three layouts are associated with each one of them, we will now build our FragmentPageAdapter and call it SimpleFragmentPageAdapter. This can be done by first creating a new Java Class and naming it as SimpleFragmentPageAdapter. Here’s the code it will contain: JavaJavapackage com.example.android.gfg; import android.support.v4.app.Fragment;import android.support.v4.app.FragmentManager;import android.support.v4.app.FragmentPagerAdapter; public class SimpleFragmentPagerAdapter extends FragmentPagerAdapter { public SimpleFragmentPagerAdapter( FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { if (position == 0) { return new Fragment1(); } else if (position == 1) { return new Fragment2(); } else { return new Fragmnet3(); } } @Override public int getCount() { return 3; }}Explanation: The getItem() method returns the Fragment at specified position. So first will be Fragment1 and upon swiping left, we will get the other Fragments in the same order.The getCount() method returns the number of Fragments there are to be displayed, which, in this case is three.
Java
package com.example.android.gfg; import android.support.v4.app.Fragment;import android.support.v4.app.FragmentManager;import android.support.v4.app.FragmentPagerAdapter; public class SimpleFragmentPagerAdapter extends FragmentPagerAdapter { public SimpleFragmentPagerAdapter( FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { if (position == 0) { return new Fragment1(); } else if (position == 1) { return new Fragment2(); } else { return new Fragmnet3(); } } @Override public int getCount() { return 3; }}
Explanation:
The getItem() method returns the Fragment at specified position. So first will be Fragment1 and upon swiping left, we will get the other Fragments in the same order.
The getCount() method returns the number of Fragments there are to be displayed, which, in this case is three.
Step 3: Creating MainActivity.Java and activity_main.xml : Now that we have everything ready, the last step is just to make our MainActivity.Java and activity_main.xml files. They can vary largely depending on the app we are making but in this case, the files are pretty simple and looks like this: activity_main.xmlMainActivity.Javaactivity_main.xml<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.example.android.viewpager.MainActivity"> <android.support.v4.view.ViewPager android:id="@+id/viewpager" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout>MainActivity.Javapackage com.example.android.gfg; import android.os.Bundle;import android.support.v4.view.ViewPager;import android.support.v7.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Set the content of the activity // to use the activity_main.xml // layout file setContentView(R.layout.activity_main); // Find the view pager that will // allow the user to swipe // between fragments ViewPager viewPager = (ViewPager)findViewById( R.id.viewpager); // Create an adapter that // knows which fragment should // be shown on each page SimpleFragmentPagerAdapter adapter = new SimpleFragmentPagerAdapter( getSupportFragmentManager()); // Set the adapter onto // the view pager viewPager.setAdapter(adapter); }}Output:Video Playerhttps://media.geeksforgeeks.org/wp-content/uploads/20200516210454/15.mp400:0000:0000:11Use Up/Down Arrow keys to increase or decrease volume.My Personal Notes
arrow_drop_upSave
Step 3: Creating MainActivity.Java and activity_main.xml : Now that we have everything ready, the last step is just to make our MainActivity.Java and activity_main.xml files. They can vary largely depending on the app we are making but in this case, the files are pretty simple and looks like this:
activity_main.xml
MainActivity.Java
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.example.android.viewpager.MainActivity"> <android.support.v4.view.ViewPager android:id="@+id/viewpager" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout>
package com.example.android.gfg; import android.os.Bundle;import android.support.v4.view.ViewPager;import android.support.v7.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Set the content of the activity // to use the activity_main.xml // layout file setContentView(R.layout.activity_main); // Find the view pager that will // allow the user to swipe // between fragments ViewPager viewPager = (ViewPager)findViewById( R.id.viewpager); // Create an adapter that // knows which fragment should // be shown on each page SimpleFragmentPagerAdapter adapter = new SimpleFragmentPagerAdapter( getSupportFragmentManager()); // Set the adapter onto // the view pager viewPager.setAdapter(adapter); }}
Output:
android
Articles
How To
Java
Write From Home
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Jun, 2020"
},
{
"code": null,
"e": 678,
"s": 28,
"text": "When talking about Android Apps, the first thing that comes to mind is variety. There are so many varieties of Android apps providing the user with beautiful dynamic UI. One such feature is to navigate in our Android Apps using left and right swipes as opposed to clicking on buttons. Not only does it look more simple and elegant but also provides ease of access to the user. There are many apps which use this swipe feature to swipe through different activities in the app. For example, the popular chatting app, Snapchat, uses it to swipe through lenses, chats and stories. Here, we will learn how to implement swipe views in our own Android app."
},
{
"code": null,
"e": 724,
"s": 678,
"text": "We can implement this by use of two features:"
},
{
"code": null,
"e": 1140,
"s": 724,
"text": "Fragments A fragment is just a part of an activity. We can have a fragment that takes up part of a screen or a whole screen. Or we can show multiple fragments at the same time to make up a whole screen. Within an activity, we can also swap out different fragments with each other. ViewPager ViewPager is a class in Java which is used in conjunction with Fragments. It is mostly used for designing the UI of the app."
},
{
"code": null,
"e": 1422,
"s": 1140,
"text": "Fragments A fragment is just a part of an activity. We can have a fragment that takes up part of a screen or a whole screen. Or we can show multiple fragments at the same time to make up a whole screen. Within an activity, we can also swap out different fragments with each other. "
},
{
"code": null,
"e": 1557,
"s": 1422,
"text": "ViewPager ViewPager is a class in Java which is used in conjunction with Fragments. It is mostly used for designing the UI of the app."
},
{
"code": null,
"e": 2402,
"s": 1557,
"text": "How does it work?First we need to set an adapter on the ViewPager using the setAdapter() method. The adapter which we set is called FragmentPagerAdapter which is an abstract class in Java. Hence, we create our own SampleFragmentPagerAdapter which extends from FragmentPagerAdapter and displays our Fragments on the screen. When we launch the app in our device, the ViewPager asks the SampleFragmentPagerAdapter how many pages are there to swipe through. The getCount() method of the adapter returns this answer to the ViewPager. Then the ViewPager asks for the Fragment which is at the 0th position and the adapter returns that particular fragment which is then displayed by ViewPager on our screen. When we swipe left, ViewPager asks adapter for the Fragment at 1st position and similarly, it is displayed on the screen and it continues so on."
},
{
"code": null,
"e": 2719,
"s": 2402,
"text": "Step by step implementation:We will be creating three fragments that is three screens that the user can swipe through. Then we will add these fragments to our FragmentPagerAdapter and finally set it on ViewPager. Note: To run these codes, you need to copy and paste them in Android Studio as it won’t run on the IDE!"
},
{
"code": null,
"e": 3871,
"s": 2719,
"text": "Step1: Creating Fragments: To create a fragment, click on app > Java > com.example.android(Right Click) > New > Fragment > Fragment(Blank) We can create as many Fragments as we want but since we will be displaying only three screens, hence we will create three Fragments. Now we will open our Fragments and copy this code over there: JavaJavapackage com.example.android.gfg; import android.os.Bundle;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup; public class Fragment1 extends Fragment { @Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater .inflate( R.layout.fragment_1, container, false); }}Explanation: We are importing v4 Fragment with BuildTools version “23.0.2“ . If we get an error in our imports, we must make sure that our BuildTools and SDK version corresponds to the libraries which we import.We name our Fragment as Fragment1.Fragment1 displays the layout fragment_1.xml which we will make now."
},
{
"code": null,
"e": 4012,
"s": 3871,
"text": "Step1: Creating Fragments: To create a fragment, click on app > Java > com.example.android(Right Click) > New > Fragment > Fragment(Blank) "
},
{
"code": null,
"e": 4208,
"s": 4012,
"text": "We can create as many Fragments as we want but since we will be displaying only three screens, hence we will create three Fragments. Now we will open our Fragments and copy this code over there: "
},
{
"code": null,
"e": 4213,
"s": 4208,
"text": "Java"
},
{
"code": "package com.example.android.gfg; import android.os.Bundle;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup; public class Fragment1 extends Fragment { @Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater .inflate( R.layout.fragment_1, container, false); }}",
"e": 4708,
"s": 4213,
"text": null
},
{
"code": null,
"e": 4723,
"s": 4708,
"text": "Explanation: "
},
{
"code": null,
"e": 4922,
"s": 4723,
"text": "We are importing v4 Fragment with BuildTools version “23.0.2“ . If we get an error in our imports, we must make sure that our BuildTools and SDK version corresponds to the libraries which we import."
},
{
"code": null,
"e": 4957,
"s": 4922,
"text": "We name our Fragment as Fragment1."
},
{
"code": null,
"e": 5026,
"s": 4957,
"text": "Fragment1 displays the layout fragment_1.xml which we will make now."
},
{
"code": null,
"e": 6195,
"s": 5026,
"text": "Step 2: Creating layouts for Fragments: Each Fragment needs to display a layout. We can design this layout anyhow we want. Here is the code to how we would implement this layout as: XMLXML<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" android:padding=\"16dp\"> <ImageView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:src=\"@drawable/gfg\"/> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"With the idea of imparting programming knowledge, Mr. Sandeep Jain, an IIT Roorkee alumnus started a dream, GeeksforGeeks. Whether programming excites you or you feel stifled, wondering how to prepare for interview questions or how to ace data structures and algorithms, GeeksforGeeks is a one-stop solution. \" android:textSize=\"20sp\" android:textColor=\"#81c784\"/></LinearLayout>This looks like: Similarly, we will create two more Fragments and a respective layout for each one of them."
},
{
"code": null,
"e": 6378,
"s": 6195,
"text": "Step 2: Creating layouts for Fragments: Each Fragment needs to display a layout. We can design this layout anyhow we want. Here is the code to how we would implement this layout as: "
},
{
"code": null,
"e": 6382,
"s": 6378,
"text": "XML"
},
{
"code": "<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" android:padding=\"16dp\"> <ImageView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:src=\"@drawable/gfg\"/> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"With the idea of imparting programming knowledge, Mr. Sandeep Jain, an IIT Roorkee alumnus started a dream, GeeksforGeeks. Whether programming excites you or you feel stifled, wondering how to prepare for interview questions or how to ace data structures and algorithms, GeeksforGeeks is a one-stop solution. \" android:textSize=\"20sp\" android:textColor=\"#81c784\"/></LinearLayout>",
"e": 7255,
"s": 6382,
"text": null
},
{
"code": null,
"e": 7274,
"s": 7255,
"text": "This looks like: "
},
{
"code": null,
"e": 7365,
"s": 7274,
"text": "Similarly, we will create two more Fragments and a respective layout for each one of them."
},
{
"code": null,
"e": 8693,
"s": 7365,
"text": "Step 3: Creating our FragmentPageAdapter: Now that we have all our three Fragments and three layouts are associated with each one of them, we will now build our FragmentPageAdapter and call it SimpleFragmentPageAdapter. This can be done by first creating a new Java Class and naming it as SimpleFragmentPageAdapter. Here’s the code it will contain: JavaJavapackage com.example.android.gfg; import android.support.v4.app.Fragment;import android.support.v4.app.FragmentManager;import android.support.v4.app.FragmentPagerAdapter; public class SimpleFragmentPagerAdapter extends FragmentPagerAdapter { public SimpleFragmentPagerAdapter( FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { if (position == 0) { return new Fragment1(); } else if (position == 1) { return new Fragment2(); } else { return new Fragmnet3(); } } @Override public int getCount() { return 3; }}Explanation: The getItem() method returns the Fragment at specified position. So first will be Fragment1 and upon swiping left, we will get the other Fragments in the same order.The getCount() method returns the number of Fragments there are to be displayed, which, in this case is three."
},
{
"code": null,
"e": 8698,
"s": 8693,
"text": "Java"
},
{
"code": "package com.example.android.gfg; import android.support.v4.app.Fragment;import android.support.v4.app.FragmentManager;import android.support.v4.app.FragmentPagerAdapter; public class SimpleFragmentPagerAdapter extends FragmentPagerAdapter { public SimpleFragmentPagerAdapter( FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { if (position == 0) { return new Fragment1(); } else if (position == 1) { return new Fragment2(); } else { return new Fragmnet3(); } } @Override public int getCount() { return 3; }}",
"e": 9380,
"s": 8698,
"text": null
},
{
"code": null,
"e": 9395,
"s": 9380,
"text": "Explanation: "
},
{
"code": null,
"e": 9561,
"s": 9395,
"text": "The getItem() method returns the Fragment at specified position. So first will be Fragment1 and upon swiping left, we will get the other Fragments in the same order."
},
{
"code": null,
"e": 9672,
"s": 9561,
"text": "The getCount() method returns the number of Fragments there are to be displayed, which, in this case is three."
},
{
"code": null,
"e": 11792,
"s": 9672,
"text": "Step 3: Creating MainActivity.Java and activity_main.xml : Now that we have everything ready, the last step is just to make our MainActivity.Java and activity_main.xml files. They can vary largely depending on the app we are making but in this case, the files are pretty simple and looks like this: activity_main.xmlMainActivity.Javaactivity_main.xml<?xml version=\"1.0\" encoding=\"utf-8\"?> <LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\"com.example.android.viewpager.MainActivity\"> <android.support.v4.view.ViewPager android:id=\"@+id/viewpager\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" /> </LinearLayout>MainActivity.Javapackage com.example.android.gfg; import android.os.Bundle;import android.support.v4.view.ViewPager;import android.support.v7.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Set the content of the activity // to use the activity_main.xml // layout file setContentView(R.layout.activity_main); // Find the view pager that will // allow the user to swipe // between fragments ViewPager viewPager = (ViewPager)findViewById( R.id.viewpager); // Create an adapter that // knows which fragment should // be shown on each page SimpleFragmentPagerAdapter adapter = new SimpleFragmentPagerAdapter( getSupportFragmentManager()); // Set the adapter onto // the view pager viewPager.setAdapter(adapter); }}Output:Video Playerhttps://media.geeksforgeeks.org/wp-content/uploads/20200516210454/15.mp400:0000:0000:11Use Up/Down Arrow keys to increase or decrease volume.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 12092,
"s": 11792,
"text": "Step 3: Creating MainActivity.Java and activity_main.xml : Now that we have everything ready, the last step is just to make our MainActivity.Java and activity_main.xml files. They can vary largely depending on the app we are making but in this case, the files are pretty simple and looks like this: "
},
{
"code": null,
"e": 12110,
"s": 12092,
"text": "activity_main.xml"
},
{
"code": null,
"e": 12128,
"s": 12110,
"text": "MainActivity.Java"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?> <LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\"com.example.android.viewpager.MainActivity\"> <android.support.v4.view.ViewPager android:id=\"@+id/viewpager\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" /> </LinearLayout>",
"e": 12652,
"s": 12128,
"text": null
},
{
"code": "package com.example.android.gfg; import android.os.Bundle;import android.support.v4.view.ViewPager;import android.support.v7.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Set the content of the activity // to use the activity_main.xml // layout file setContentView(R.layout.activity_main); // Find the view pager that will // allow the user to swipe // between fragments ViewPager viewPager = (ViewPager)findViewById( R.id.viewpager); // Create an adapter that // knows which fragment should // be shown on each page SimpleFragmentPagerAdapter adapter = new SimpleFragmentPagerAdapter( getSupportFragmentManager()); // Set the adapter onto // the view pager viewPager.setAdapter(adapter); }}",
"e": 13687,
"s": 12652,
"text": null
},
{
"code": null,
"e": 13695,
"s": 13687,
"text": "Output:"
},
{
"code": null,
"e": 13703,
"s": 13695,
"text": "android"
},
{
"code": null,
"e": 13712,
"s": 13703,
"text": "Articles"
},
{
"code": null,
"e": 13719,
"s": 13712,
"text": "How To"
},
{
"code": null,
"e": 13724,
"s": 13719,
"text": "Java"
},
{
"code": null,
"e": 13740,
"s": 13724,
"text": "Write From Home"
},
{
"code": null,
"e": 13745,
"s": 13740,
"text": "Java"
}
] |
Training Neural Networks using Pytorch Lightning
|
26 Nov, 2020
Introduction:
PyTorch Lightning is a library that provides a high-level interface for PyTorch. Problem with PyTorch is that every time you start a project you have to rewrite those training and testing loop. PyTorch Lightning fixes the problem by not only reducing boilerplate code but also providing added functionality that might come handy while training your neural networks. One of the things I love about Lightning is that the code is very organized and reusable, and not only that but it reduces the training and testing loop while retain the flexibility that PyTorch is known for. And once you learn how to use it you’ll see how similar the code is to that of PyTorch.
Installing PyTorch Lightning:
Installing Lightning is same as that of any other library in python.
pip install pytorch-lightning
or if you want to install it in a conda environment you can use the following command:-
conda install -c conda-forge pytorch-lightning
PyTorch Lightning Model Format:
If you have ever used PyTorch you must know that defining PyTorch model follows the following format
from torch import nn
class model(nn.Module):
def __init__(self):
# Define Model Here
def forward(self, x):
# Define Forward Pass Here
That’s how we define a model in PyTorch now after defining loop we usually define loss, optimizer and training outside the class. In PyTorch Lightning, the way to define model is similar except for the fact that we add the loss, optimizer and training steps in the model itself. To define a lightning model we follow the following format:-
import pytorch-lightning as pl
class model(pl.LightningModule):
def __init__(self):
# Define Model Here
def forward(self, x):
# Define Forward Pass Here
def configure_optimizers(self):
# Define Optimizer Here
def training_step(self, train_batch, batch_idx):
# Define Training loop steps here
def validation_step(self, valid_batch, batch_idx):
# Define Validation loop steps here
Note: The names of the above functions should be exactly the same.
Training our Neural Network:
Loading Our Data:
For this tutorial we are going to be using MNIST dataset, so we’ll start by loading our data and defining the model afterwards. To load data for Lightning Model you can either define DataLoaders as you do in PyTorch and pass both train dataloader and validation dataloader in pl.Trainer() function or you can use LightingDataModule which does the same thing except now you do the steps in a python class. To create dataloaders we follow the following step:-
Loading Data by Creating DataLoaders:
from torchvision import datasets,transforms
from torch.utils.data import DataLoader
transform = transforms.Compose([
transforms.ToTensor()
])
train = datasets.MNIST('',train = True, download = True, transform=transform)
test = datasets.MNIST('',train = False, download = True, transform=transform)
trainloader = DataLoader(train, batch_size= 32, shuffle=True)
testloader = DataLoader(test, batch_size= 32, shuffle=True)
To creating LightningDataModule we follow the following steps:-
Loading Data by Creating LightningDataModule:
import pytorch-lightning as pl
from torchvision import datasets,transforms
from torch.utils.data import DataLoader
class Data(pl.LightningDataModule):
def prepare_data(self):
transform=transforms.Compose([
transforms.ToTensor()
])
self.train_data = datasets.MNIST('', train=True, download=True, transform=transform)
self.test_data = datasets.MNIST('', train=False, download=True, transform=transform)
def train_dataloader(self):
return DataLoader(self.train_data, batch_size= 32, shuffle=True)
def val_dataloader(self):
return DataLoader(self.test_data, batch_size= 32, shuffle=True)
Note: The names of the above functions should be exactly the same.
This is how you create Lightning Data Module. Creating dataloaders can get messy thats why its better to club the dataset in form of Data Module.
Defining Our Neural Network
Defining the model in PyTorch lighting is pretty much the same as that in PyTorch except now we are clubbing everything inside our model class.
from torch import nn
import pytorch_lightning as pl
import torch.nn.functional as F
from torch.optim import SGD
class model(pl.LightningModule):
def __init__(self):
super(model,self).__init__()
self.fc1 = nn.Linear(28*28,256)
self.fc2 = nn.Linear(256,128)
self.out = nn.Linear(128,10)
self.lr = 0.01
self.loss = nn.CrossEntropyLoss()
def forward(self,x):
batch_size, _, _, _ = x.size()
x = x.view(batch_size,-1)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
return self.out(x)
def configure_optimizers(self):
return SGD(self.parameters(),lr = self.lr)
def training_step(self, train_batch, batch_idx):
x, y = train_batch
logits = self.forward(x)
loss = self.loss(logits,y)
return loss
def validation_step(self, valid_batch, batch_idx):
x, y = valid_batch
logits = self.forward(x)
loss = self.loss(logits,y)
We’ll further discuss how training_step() differs from the steps in Training Loop in Pytorch and other difference between Lightning Model and Pytorch model.
Training Our Model
To training model in Pytorch, you first have to write the training loop but the Trainer class in Lightning makes the tasks easier. To Train model in Lightning:-
# Create Model Object
clf = model()
# Create Data Module Object
mnist = Data()
# Create Trainer Object
trainer = pl.Trainer(gpus=1,accelerator='dp',max_epochs=5)
trainer.fit(clf,mnist)
Note: `dp` is DataParallel (split batch among GPUs of same machine).
Note: If you have loaded data by creating dataloaders you can fit trainer by trainer.fit(clf,trainloader,testloader).
Difference Between PyTorch Model and Lightning Model:
As we can see the first difference between PyTorch and lightning model is the class that the model class inherits:-
class model(nn.Module):
class model(pl.LightningModule):
__init__() method
In both Pytorch and and Lightning Model we use the __init__() method to define our layers, since in lightning we club everything together we can also define other hyper parameters like learning rate for optimizer and the loss function.
def __init__(self):
super(model,self).__init__()
self.fc1 = nn.Linear(28*28,256)
self.fc2 = nn.Linear(256,128)
self.out = nn.Linear(128,10)
def __init__(self):
super(model,self).__init__()
self.fc1 = nn.Linear(28*28,256)
self.fc2 = nn.Linear(256,128)
self.out = nn.Linear(128,10)
self.lr = 0.01
self.loss = nn.CrossEntropyLoss()
forward() method:
In both Pytorch and Lightning Model we use the forward() method to define our forward pass, hence it is same for both.
def forward(self,x):
batch_size, _, _, _ = x.size()
x = x.view(batch_size,-1)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
return self.out(x)
Defining Optimizer:
In PyTorch, we usually define our optimizers by directly creating their object but in PyTorch-lightning we define our optimizers under configure_optimizers() method. Another thing to note is that in PyTorch we pass model object parameters as the arguments for optimizer but in lightning, we pass self.parameters() since the class is the model itself.
from torch.optim import SGD
clf = model() # Pytorch Model Object
optimizer = SGD(clf.parameters(),lr=0.01)
def configure_optimizers(self):
return SGD(self.parameters(),lr = self.lr)
Note: You can create multiple optimizers in lightning too.
Training Loop(Step):
It won’t be wrong to say that this is what makes Lightning stand out from PyTorch. In PyTorch we define the full training loop while in lightning we use the Trainer() to do the job. But we still define the steps that are going to be executed while training.
epochs = 5
for i in range(epochs):
train_loss = 0.0
for data,label in trainloader:
if is_gpu:
data, label = data.cuda(), label.cuda()
output = model(data)
optimizer.zero_grad()
loss = criterion(output,label)
loss.backward()
optimizer.step()
train_loss += loss.item() * data.size(0)
print(f'Epoch: {i+1} / {epochs} \t\t\t Training Loss:{train_loss/len(trainloader)}')
def training_step(self, train_batch, batch_idx):
x, y = train_batch
logits = self.forward(x)
loss = self.loss(logits,y)
return loss
See how in training steps we just write the steps necessary(bolded).
Code
Python3
import torchfrom torch import nnimport pytorch_lightning as plimport torch.nn.functional as Ffrom torchvision import datasets, transformsfrom torch.utils.data import DataLoaderfrom torch.optim import SGD class model(pl.LightningModule): def __init__(self): super(model, self).__init__() self.fc1 = nn.Linear(28*28, 256) self.fc2 = nn.Linear(256, 128) self.out = nn.Linear(128, 10) self.lr = 0.01 self.loss = nn.CrossEntropyLoss() def forward(self, x): batch_size, _, _, _ = x.size() x = x.view(batch_size, -1) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) return self.out(x) def configure_optimizers(self): return torch.optim.SGD(self.parameters(), lr=self.lr) def training_step(self, train_batch, batch_idx): x, y = train_batch logits = self.forward(x) loss = self.loss(logits, y) return loss def validation_step(self, valid_batch, batch_idx): x, y = valid_batch logits = self.forward(x) loss = self.loss(logits, y) class Data(pl.LightningDataModule): def prepare_data(self): transform = transforms.Compose([ transforms.ToTensor() ]) self.train_data = datasets.MNIST( '', train=True, download=True, transform=transform) self.test_data = datasets.MNIST( '', train=False, download=True, transform=transform) def train_dataloader(self): return DataLoader(self.train_data, batch_size=32, shuffle=True) def val_dataloader(self): return DataLoader(self.test_data, batch_size=32, shuffle=True) clf = model()mnist = Data()trainer = pl.Trainer(gpus=1, accelerator='dp', max_epochs=5)trainer.fit(clf, mnist)
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Recurrent Neural Network
Support Vector Machine Algorithm
ML | Monte Carlo Tree Search (MCTS)
Markov Decision Process
DBSCAN Clustering in ML | Density based clustering
Normalization vs Standardization
Bagging vs Boosting in Machine Learning
Principal Component Analysis with Python
Types of Environments in AI
An introduction to Machine Learning
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n26 Nov, 2020"
},
{
"code": null,
"e": 66,
"s": 52,
"text": "Introduction:"
},
{
"code": null,
"e": 729,
"s": 66,
"text": "PyTorch Lightning is a library that provides a high-level interface for PyTorch. Problem with PyTorch is that every time you start a project you have to rewrite those training and testing loop. PyTorch Lightning fixes the problem by not only reducing boilerplate code but also providing added functionality that might come handy while training your neural networks. One of the things I love about Lightning is that the code is very organized and reusable, and not only that but it reduces the training and testing loop while retain the flexibility that PyTorch is known for. And once you learn how to use it you’ll see how similar the code is to that of PyTorch."
},
{
"code": null,
"e": 759,
"s": 729,
"text": "Installing PyTorch Lightning:"
},
{
"code": null,
"e": 828,
"s": 759,
"text": "Installing Lightning is same as that of any other library in python."
},
{
"code": null,
"e": 859,
"s": 828,
"text": "pip install pytorch-lightning\n"
},
{
"code": null,
"e": 947,
"s": 859,
"text": "or if you want to install it in a conda environment you can use the following command:-"
},
{
"code": null,
"e": 995,
"s": 947,
"text": "conda install -c conda-forge pytorch-lightning\n"
},
{
"code": null,
"e": 1027,
"s": 995,
"text": "PyTorch Lightning Model Format:"
},
{
"code": null,
"e": 1128,
"s": 1027,
"text": "If you have ever used PyTorch you must know that defining PyTorch model follows the following format"
},
{
"code": null,
"e": 1297,
"s": 1128,
"text": "from torch import nn\n\nclass model(nn.Module):\n def __init__(self):\n # Define Model Here\n \n def forward(self, x):\n # Define Forward Pass Here\n"
},
{
"code": null,
"e": 1637,
"s": 1297,
"text": "That’s how we define a model in PyTorch now after defining loop we usually define loss, optimizer and training outside the class. In PyTorch Lightning, the way to define model is similar except for the fact that we add the loss, optimizer and training steps in the model itself. To define a lightning model we follow the following format:-"
},
{
"code": null,
"e": 2108,
"s": 1637,
"text": "import pytorch-lightning as pl\n\nclass model(pl.LightningModule):\n def __init__(self):\n # Define Model Here\n \n def forward(self, x):\n # Define Forward Pass Here\n \n def configure_optimizers(self):\n # Define Optimizer Here\n \n def training_step(self, train_batch, batch_idx):\n # Define Training loop steps here\n \n def validation_step(self, valid_batch, batch_idx):\n # Define Validation loop steps here\n"
},
{
"code": null,
"e": 2175,
"s": 2108,
"text": "Note: The names of the above functions should be exactly the same."
},
{
"code": null,
"e": 2204,
"s": 2175,
"text": "Training our Neural Network:"
},
{
"code": null,
"e": 2222,
"s": 2204,
"text": "Loading Our Data:"
},
{
"code": null,
"e": 2680,
"s": 2222,
"text": "For this tutorial we are going to be using MNIST dataset, so we’ll start by loading our data and defining the model afterwards. To load data for Lightning Model you can either define DataLoaders as you do in PyTorch and pass both train dataloader and validation dataloader in pl.Trainer() function or you can use LightingDataModule which does the same thing except now you do the steps in a python class. To create dataloaders we follow the following step:-"
},
{
"code": null,
"e": 2719,
"s": 2680,
"text": "Loading Data by Creating DataLoaders:"
},
{
"code": null,
"e": 3147,
"s": 2719,
"text": "from torchvision import datasets,transforms\nfrom torch.utils.data import DataLoader\n\ntransform = transforms.Compose([\n transforms.ToTensor()\n])\n\ntrain = datasets.MNIST('',train = True, download = True, transform=transform)\ntest = datasets.MNIST('',train = False, download = True, transform=transform)\n\ntrainloader = DataLoader(train, batch_size= 32, shuffle=True)\ntestloader = DataLoader(test, batch_size= 32, shuffle=True)\n"
},
{
"code": null,
"e": 3211,
"s": 3147,
"text": "To creating LightningDataModule we follow the following steps:-"
},
{
"code": null,
"e": 3257,
"s": 3211,
"text": "Loading Data by Creating LightningDataModule:"
},
{
"code": null,
"e": 3924,
"s": 3257,
"text": "import pytorch-lightning as pl\nfrom torchvision import datasets,transforms\nfrom torch.utils.data import DataLoader\n\nclass Data(pl.LightningDataModule):\n def prepare_data(self):\n transform=transforms.Compose([\n transforms.ToTensor()\n ])\n \n self.train_data = datasets.MNIST('', train=True, download=True, transform=transform)\n self.test_data = datasets.MNIST('', train=False, download=True, transform=transform)\n\n def train_dataloader(self):\n return DataLoader(self.train_data, batch_size= 32, shuffle=True)\n\n def val_dataloader(self):\n return DataLoader(self.test_data, batch_size= 32, shuffle=True)\n"
},
{
"code": null,
"e": 3991,
"s": 3924,
"text": "Note: The names of the above functions should be exactly the same."
},
{
"code": null,
"e": 4137,
"s": 3991,
"text": "This is how you create Lightning Data Module. Creating dataloaders can get messy thats why its better to club the dataset in form of Data Module."
},
{
"code": null,
"e": 4165,
"s": 4137,
"text": "Defining Our Neural Network"
},
{
"code": null,
"e": 4309,
"s": 4165,
"text": "Defining the model in PyTorch lighting is pretty much the same as that in PyTorch except now we are clubbing everything inside our model class."
},
{
"code": null,
"e": 5311,
"s": 4309,
"text": "from torch import nn\nimport pytorch_lightning as pl\nimport torch.nn.functional as F\nfrom torch.optim import SGD\n\nclass model(pl.LightningModule):\n def __init__(self):\n super(model,self).__init__()\n self.fc1 = nn.Linear(28*28,256)\n self.fc2 = nn.Linear(256,128)\n self.out = nn.Linear(128,10)\n self.lr = 0.01\n self.loss = nn.CrossEntropyLoss()\n \n def forward(self,x):\n batch_size, _, _, _ = x.size()\n x = x.view(batch_size,-1)\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n return self.out(x)\n \n def configure_optimizers(self):\n return SGD(self.parameters(),lr = self.lr)\n \n def training_step(self, train_batch, batch_idx):\n x, y = train_batch\n logits = self.forward(x)\n loss = self.loss(logits,y)\n return loss\n \n def validation_step(self, valid_batch, batch_idx):\n x, y = valid_batch\n logits = self.forward(x)\n loss = self.loss(logits,y)\n"
},
{
"code": null,
"e": 5468,
"s": 5311,
"text": "We’ll further discuss how training_step() differs from the steps in Training Loop in Pytorch and other difference between Lightning Model and Pytorch model."
},
{
"code": null,
"e": 5487,
"s": 5468,
"text": "Training Our Model"
},
{
"code": null,
"e": 5648,
"s": 5487,
"text": "To training model in Pytorch, you first have to write the training loop but the Trainer class in Lightning makes the tasks easier. To Train model in Lightning:-"
},
{
"code": null,
"e": 5834,
"s": 5648,
"text": "# Create Model Object\nclf = model()\n# Create Data Module Object\nmnist = Data()\n# Create Trainer Object\ntrainer = pl.Trainer(gpus=1,accelerator='dp',max_epochs=5)\ntrainer.fit(clf,mnist)\n"
},
{
"code": null,
"e": 5903,
"s": 5834,
"text": "Note: `dp` is DataParallel (split batch among GPUs of same machine)."
},
{
"code": null,
"e": 6021,
"s": 5903,
"text": "Note: If you have loaded data by creating dataloaders you can fit trainer by trainer.fit(clf,trainloader,testloader)."
},
{
"code": null,
"e": 6075,
"s": 6021,
"text": "Difference Between PyTorch Model and Lightning Model:"
},
{
"code": null,
"e": 6191,
"s": 6075,
"text": "As we can see the first difference between PyTorch and lightning model is the class that the model class inherits:-"
},
{
"code": null,
"e": 6216,
"s": 6191,
"text": "class model(nn.Module):\n"
},
{
"code": null,
"e": 6249,
"s": 6216,
"text": "class model(pl.LightningModule):"
},
{
"code": null,
"e": 6267,
"s": 6249,
"text": "__init__() method"
},
{
"code": null,
"e": 6503,
"s": 6267,
"text": "In both Pytorch and and Lightning Model we use the __init__() method to define our layers, since in lightning we club everything together we can also define other hyper parameters like learning rate for optimizer and the loss function."
},
{
"code": null,
"e": 6660,
"s": 6503,
"text": "def __init__(self):\n super(model,self).__init__()\n self.fc1 = nn.Linear(28*28,256)\n self.fc2 = nn.Linear(256,128)\n self.out = nn.Linear(128,10)\n"
},
{
"code": null,
"e": 6874,
"s": 6660,
"text": "def __init__(self):\n super(model,self).__init__()\n self.fc1 = nn.Linear(28*28,256)\n self.fc2 = nn.Linear(256,128)\n self.out = nn.Linear(128,10)\n self.lr = 0.01\n self.loss = nn.CrossEntropyLoss()\n"
},
{
"code": null,
"e": 6892,
"s": 6874,
"text": "forward() method:"
},
{
"code": null,
"e": 7011,
"s": 6892,
"text": "In both Pytorch and Lightning Model we use the forward() method to define our forward pass, hence it is same for both."
},
{
"code": null,
"e": 7177,
"s": 7011,
"text": "def forward(self,x):\n batch_size, _, _, _ = x.size()\n x = x.view(batch_size,-1)\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n return self.out(x)\n"
},
{
"code": null,
"e": 7197,
"s": 7177,
"text": "Defining Optimizer:"
},
{
"code": null,
"e": 7548,
"s": 7197,
"text": "In PyTorch, we usually define our optimizers by directly creating their object but in PyTorch-lightning we define our optimizers under configure_optimizers() method. Another thing to note is that in PyTorch we pass model object parameters as the arguments for optimizer but in lightning, we pass self.parameters() since the class is the model itself."
},
{
"code": null,
"e": 7659,
"s": 7548,
"text": "from torch.optim import SGD\nclf = model() # Pytorch Model Object\noptimizer = SGD(clf.parameters(),lr=0.01)\n"
},
{
"code": null,
"e": 7739,
"s": 7659,
"text": "def configure_optimizers(self):\n return SGD(self.parameters(),lr = self.lr)\n"
},
{
"code": null,
"e": 7798,
"s": 7739,
"text": "Note: You can create multiple optimizers in lightning too."
},
{
"code": null,
"e": 7819,
"s": 7798,
"text": "Training Loop(Step):"
},
{
"code": null,
"e": 8077,
"s": 7819,
"text": "It won’t be wrong to say that this is what makes Lightning stand out from PyTorch. In PyTorch we define the full training loop while in lightning we use the Trainer() to do the job. But we still define the steps that are going to be executed while training."
},
{
"code": null,
"e": 8535,
"s": 8077,
"text": "epochs = 5\n\nfor i in range(epochs):\n train_loss = 0.0\n for data,label in trainloader:\n if is_gpu:\n data, label = data.cuda(), label.cuda()\n output = model(data)\n optimizer.zero_grad()\n loss = criterion(output,label)\n loss.backward()\n optimizer.step()\n \n train_loss += loss.item() * data.size(0)\n print(f'Epoch: {i+1} / {epochs} \\t\\t\\t Training Loss:{train_loss/len(trainloader)}')\n"
},
{
"code": null,
"e": 8686,
"s": 8535,
"text": "def training_step(self, train_batch, batch_idx):\n x, y = train_batch\n logits = self.forward(x)\n loss = self.loss(logits,y)\n return loss\n\n\n"
},
{
"code": null,
"e": 8756,
"s": 8686,
"text": "See how in training steps we just write the steps necessary(bolded). "
},
{
"code": null,
"e": 8761,
"s": 8756,
"text": "Code"
},
{
"code": null,
"e": 8769,
"s": 8761,
"text": "Python3"
},
{
"code": "import torchfrom torch import nnimport pytorch_lightning as plimport torch.nn.functional as Ffrom torchvision import datasets, transformsfrom torch.utils.data import DataLoaderfrom torch.optim import SGD class model(pl.LightningModule): def __init__(self): super(model, self).__init__() self.fc1 = nn.Linear(28*28, 256) self.fc2 = nn.Linear(256, 128) self.out = nn.Linear(128, 10) self.lr = 0.01 self.loss = nn.CrossEntropyLoss() def forward(self, x): batch_size, _, _, _ = x.size() x = x.view(batch_size, -1) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) return self.out(x) def configure_optimizers(self): return torch.optim.SGD(self.parameters(), lr=self.lr) def training_step(self, train_batch, batch_idx): x, y = train_batch logits = self.forward(x) loss = self.loss(logits, y) return loss def validation_step(self, valid_batch, batch_idx): x, y = valid_batch logits = self.forward(x) loss = self.loss(logits, y) class Data(pl.LightningDataModule): def prepare_data(self): transform = transforms.Compose([ transforms.ToTensor() ]) self.train_data = datasets.MNIST( '', train=True, download=True, transform=transform) self.test_data = datasets.MNIST( '', train=False, download=True, transform=transform) def train_dataloader(self): return DataLoader(self.train_data, batch_size=32, shuffle=True) def val_dataloader(self): return DataLoader(self.test_data, batch_size=32, shuffle=True) clf = model()mnist = Data()trainer = pl.Trainer(gpus=1, accelerator='dp', max_epochs=5)trainer.fit(clf, mnist)",
"e": 10525,
"s": 8769,
"text": null
},
{
"code": null,
"e": 10542,
"s": 10525,
"text": "Machine Learning"
},
{
"code": null,
"e": 10559,
"s": 10542,
"text": "Machine Learning"
},
{
"code": null,
"e": 10657,
"s": 10559,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10698,
"s": 10657,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 10731,
"s": 10698,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 10767,
"s": 10731,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 10791,
"s": 10767,
"text": "Markov Decision Process"
},
{
"code": null,
"e": 10842,
"s": 10791,
"text": "DBSCAN Clustering in ML | Density based clustering"
},
{
"code": null,
"e": 10875,
"s": 10842,
"text": "Normalization vs Standardization"
},
{
"code": null,
"e": 10915,
"s": 10875,
"text": "Bagging vs Boosting in Machine Learning"
},
{
"code": null,
"e": 10956,
"s": 10915,
"text": "Principal Component Analysis with Python"
},
{
"code": null,
"e": 10984,
"s": 10956,
"text": "Types of Environments in AI"
}
] |
Python | Column Mean in tuple list - GeeksforGeeks
|
15 Jan, 2022
Sometimes, while working with records, we can have a problem in which we need to average all the columns of a container of lists which are tuples. This kind of application is common in web development domain. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using sum() + list comprehension + zip() This task can be performed using combination of above functions. In this, we cumulate the like index elements, i.e columns using zip(), and then iterate through them using list comprehension and perform summation using sum(). We divide the each result with No of rows for average computation.
Python3
# Python3 code to demonstrate working of# Column Mean in tuple list# using list comprehension + sum() + zip() # initialize listtest_list = [(1, 2, 3), (6, 7, 6), (1, 6, 8)] # printing original listprint("The original list : " + str(test_list)) # Column Mean in tuple list# using list comprehension + sum() + zip()res = [sum(ele) / len(test_list) for ele in zip(*test_list)] # printing resultprint("The Cumulative column mean is : " + str(res))
The original list : [(1, 2, 3), (6, 7, 6), (1, 6, 8)]
The Cumulative column mean is : [2.6666666666666665, 5.0, 5.666666666666667]
Method #2 : Using zip() + map() + sum() This method is similar to the above method. In this, the task performed by list comprehension is performed by map(), which extends the summation of columns to zipped elements. We divide the each result with No of rows for average computation.
Python3
# Python3 code to demonstrate working of# Column Mean in tuple list# using zip() + map() + sum() def avg(list): return sum(list)/len(list) # initialize listtest_list = [(1, 2, 3), (6, 7, 6), (1, 6, 8)] # printing original listprint("The original list : " + str(test_list)) # Column Mean in tuple list# using zip() + map() + sum()res = list(map(avg, zip(*test_list))) # printing resultprint("The Cumulative column mean is : " + str(res))
The original list : [(1, 2, 3), (6, 7, 6), (1, 6, 8)]
The Cumulative column mean is : [2.6666666666666665, 5.0, 5.666666666666667]
surindertarika1234
ruhelaa48
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Read a file line by line in Python
Enumerate() in Python
Iterate over a list in Python
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
|
[
{
"code": null,
"e": 24122,
"s": 24094,
"text": "\n15 Jan, 2022"
},
{
"code": null,
"e": 24395,
"s": 24122,
"text": "Sometimes, while working with records, we can have a problem in which we need to average all the columns of a container of lists which are tuples. This kind of application is common in web development domain. Let’s discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 24741,
"s": 24395,
"text": "Method #1 : Using sum() + list comprehension + zip() This task can be performed using combination of above functions. In this, we cumulate the like index elements, i.e columns using zip(), and then iterate through them using list comprehension and perform summation using sum(). We divide the each result with No of rows for average computation."
},
{
"code": null,
"e": 24749,
"s": 24741,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Column Mean in tuple list# using list comprehension + sum() + zip() # initialize listtest_list = [(1, 2, 3), (6, 7, 6), (1, 6, 8)] # printing original listprint(\"The original list : \" + str(test_list)) # Column Mean in tuple list# using list comprehension + sum() + zip()res = [sum(ele) / len(test_list) for ele in zip(*test_list)] # printing resultprint(\"The Cumulative column mean is : \" + str(res))",
"e": 25201,
"s": 24749,
"text": null
},
{
"code": null,
"e": 25332,
"s": 25201,
"text": "The original list : [(1, 2, 3), (6, 7, 6), (1, 6, 8)]\nThe Cumulative column mean is : [2.6666666666666665, 5.0, 5.666666666666667]"
},
{
"code": null,
"e": 25615,
"s": 25332,
"text": "Method #2 : Using zip() + map() + sum() This method is similar to the above method. In this, the task performed by list comprehension is performed by map(), which extends the summation of columns to zipped elements. We divide the each result with No of rows for average computation."
},
{
"code": null,
"e": 25623,
"s": 25615,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Column Mean in tuple list# using zip() + map() + sum() def avg(list): return sum(list)/len(list) # initialize listtest_list = [(1, 2, 3), (6, 7, 6), (1, 6, 8)] # printing original listprint(\"The original list : \" + str(test_list)) # Column Mean in tuple list# using zip() + map() + sum()res = list(map(avg, zip(*test_list))) # printing resultprint(\"The Cumulative column mean is : \" + str(res))",
"e": 26077,
"s": 25623,
"text": null
},
{
"code": null,
"e": 26208,
"s": 26077,
"text": "The original list : [(1, 2, 3), (6, 7, 6), (1, 6, 8)]\nThe Cumulative column mean is : [2.6666666666666665, 5.0, 5.666666666666667]"
},
{
"code": null,
"e": 26227,
"s": 26208,
"text": "surindertarika1234"
},
{
"code": null,
"e": 26237,
"s": 26227,
"text": "ruhelaa48"
},
{
"code": null,
"e": 26258,
"s": 26237,
"text": "Python list-programs"
},
{
"code": null,
"e": 26265,
"s": 26258,
"text": "Python"
},
{
"code": null,
"e": 26281,
"s": 26265,
"text": "Python Programs"
},
{
"code": null,
"e": 26379,
"s": 26281,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26388,
"s": 26379,
"text": "Comments"
},
{
"code": null,
"e": 26401,
"s": 26388,
"text": "Old Comments"
},
{
"code": null,
"e": 26419,
"s": 26401,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26451,
"s": 26419,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26486,
"s": 26451,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26508,
"s": 26486,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26538,
"s": 26508,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26581,
"s": 26538,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 26603,
"s": 26581,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26642,
"s": 26603,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 26688,
"s": 26642,
"text": "Python | Split string into list of characters"
}
] |
Data Structures & Algorithms in Python | by Papa Moryba Kouate | Towards Data Science
|
To develop a complete mind: Study the science of art; Study the art of science. Learn how to see. Realize that everything connects to everything else.
Leonardo da Vinci
The purpose of this article is to give you a panorama of data structures and algorithms in Python. This topic is very important for a Data Scientist in order to help him or her to design and solve machine learning models in a more effective way.
We will see together with practical examples the built-in data structures, the user-defined data structures, and last but not least I will introduce you to some algorithms like traversal algorithms, sorting algorithms, and searching algorithms.
So, let’s get started!
As the name suggests, data structures allow us to organize, store, and manage data for efficient access and modification.
In this part, we are going to take a look at built-in data structures. There are four types of built-in data structures in Python: list, tuple, set, and dictionary.
List
A list is defined using square brackets and holds data that is separated by commas. The list is mutable and ordered. It can contain a mix of different data types.
out:
january['january', 'february', 'march', 'april', 'may', 'june', 'july']['birthday', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december']
Below there are some useful functions for the list.
out:
Whatisyourfavouritepainting?Who-is-your-favourite-artist-?
out:
['Chagall', 'Kandinskij', 'Dalí', 'da Vinci', 'Picasso', 'Warhol', 'Basquiat']
Tuple
A tuple is another container. It is a data type for immutable ordered sequences of elements. Immutable because you can’t add and remove elements from tuples, or sort them in place.
out:
The dimensions are 7 x 3 x 1
Set
Set is a mutable and unordered collection of unique elements. It can permit us to remove duplicate quickly from a list.
out:
{1, 2, 3, 5, 6}FalseBasquiat
Dictionary
Dictionary is a mutable and unordered data structure. It permits storing a pair of items (i.e. keys and values).
As the example below shows, in the dictionary, it is possible to include containers into other containers to create compound data structures.
out:
In a Sentimental MoodLacrimosa
Now I will introduce you three user-defined data structures: ques, stack, and tree. I assume that you have a basic knowledge of classes and functions.
Stack using arrays
The stack is a linear data structure where elements are arranged sequentially. It follows the mechanism L.I.F.O which means last in first out. So, the last element inserted will be removed as the first. The operations are:
Push → inserting an element into the stack
Pop → deleting an element from the stack
The conditions to check:
overflow condition → this condition occurs when we try to put one more element into a stack that is already having maximum elements.
underflow condition →this condition occurs when we try to delete an element from an empty stack.
out:
5True[10, 23, 25, 27, 11]overflow1127252310underflow
Queue using arrays
The queue is a linear data structure where elements are in a sequential manner. It follows the F.I.F.O mechanism that means first in first out. Think when you go to the cinema with your friends, as you can imagine the first of you that give the ticket is also the first that step out of the line. The mechanism of the queue is the same.
Below the aspects that characterize a queue.
Two ends:
front → points to starting element
rear → points to the last element
There are two operations:
enqueue → inserting an element into the queue. It will be done at the rear.
dequeue → deleting an element from the queue. It will be done at the front.
There are two conditions:
overflow → insertion into a queue that is full
underflow → deletion from the empty queue
out:
[2, 3, 4, 5][3, 4, 5]
Tree (general tree)
Trees are used to define hierarchy. It starts with the root node and goes further down, the last nodes are called child nodes.
In this article, I focus on the binary tree. The binary tree is a tree data structure in which each node has at most two children, which are referred to as the left child and the right child. Below you can see a representation and an example of the binary tree with python where I constructed a class called Node and the objects that represent the different nodes( A, B, C, D, and E).
Anyway, there are other user-defined data structures like linked lists and graphs.
The concept of the algorithm has existed since antiquity. In fact, the ancient Egyptians used algorithms to solve their problems. Then they taught this approach to the Greeks.
The word algorithm derives itself from the 9th-century Persian mathematician Muḥammad ibn Mūsā al-Khwārizmī, whose name was Latinized as Algorithmi. Al-Khwārizmī was also an astronomer, geographer, and a scholar in the House of Wisdom in Baghdad.
As you already know algorithms are instructions that are formulated in a finite and sequential order to solve problems.
When we write an algorithm, we have to know what is the exact problem, determine where we need to start and stop and formulate the intermediate steps.
There are three main approaches to solve algorithms:
Divide et Impera (also known as divide and conquer) → it divides the problem into sub-parts and solves each one separately
Dynamic programming → it divides the problem into sub-parts remembers the results of the sub-parts and applies it to similar ones
Greedy algorithms → involve taking the easiest step while solving a problem without worrying about the complexity of the future steps
Tree Traversal Algorithm
Trees in python are non-linear data structures. They are characterized by roots and nodes. I take the class I constructed before for the binary tree.
Tree Traversal refers to visiting each node present in the tree exactly once, in order to update or check them.
There are three types of tree traversals:
In-order traversal → refers to visiting the left node, followed by the root and then the right nodes.
Here D is the leftmost node where the nearest root is B. The right of root B is E. Now the left sub-tree is completed, so I move towards the root node A and then to node C.
out:
DBEAC
Pre-order traversal → refers to visiting the root node followed by the left nodes and then the right nodes.
In this case, I move to the root node A and then to the left child node B and to the sub child node D. After that I can go to the nodes E and then C.
out:
ABDEC
Post-order traversal → refers to visiting the left nodes followed by the right nodes and then the root node
I go to the most left node which is D and then to the right node E. Then, I can go from the left node B to the right node C. Finally, I move towards the root node A.
out:
DEBCA
Sorting Algorithm
The sorting algorithm is used to sort data in some given order. It can be classified in Merge Sort and Bubble Sort.
Merge Sort → it follows the divide et Impera rule. The given list is first divided into smaller lists and compares adjacent lists and then, reorders them in the desired sequence. So, in summary from unordered elements as input, we need to have ordered elements as output. Below, the code with each step described.
out:
input - unordered elements: 15 1 19 93output - ordered elements: [1, 15, 19, 93]
Bubble Sort → it first compares and then sorts adjacent elements if they are not in the specified order.
out:
[1, 3, 9, 15]
Insertion Sort → it picks one item of a given list at the time and places it at the exact spot where it is to be placed.
out:
[1, 3, 9, 15]
There are other Sorting Algorithms like Selection Sort and Shell Sort.
Searching Algorithms
Searching algorithms are used to seek for some elements present in a given dataset. There are many types of search algorithms such as Linear Search, Binary Search, Exponential Search, Interpolation Search, and so on. In this section, we will see the Linear Search and Binary Search.
Linear Search → in a single-dimensional array we have to search a particular key element. The input is the group of elements and the key element that we want to find. So, we have to compare the key element with each element of the group. In the following code, I try to seek element 27 in our list.
out:
'not fund'
Binary Search → in this algorithm, we assume that the list is in ascending order. So, if the value of the search key is less than the element in the middle of the list, we narrow the interval to the lower half. Otherwise, we narrow to the upper half. We continue our check until the value is found or the list is empty.
out:
FalseTrue
Now you have an overview of data structures and algorithms. So, you can start going to a deeper understanding of algorithms.
The beautiful image of the Vitruvian Man I have chosen for this article is not casual. The drawing is based on the correlation of the ideal human body in relation to geometry. In fact, for this representation, Leonardo da Vinci was inspired by Vitruvius who described the man’s body as the ideal body to determine the correct proportion in architecture.
For what concerns algorithms, the Vitruvian Man hides a secret algorithm used by the artists for centuries to certify that their works were inspired by the divine proportion.
Sometimes I like to think that maybe Leonardo da Vinci, through his wonderful works, wanted to define the most important algorithm which is the algorithm of life.
Thanks for reading this. There are some other ways you can keep in touch with me and follow my work:
Subscribe to my newsletter.
You can also get in touch via my Telegram group, Data Science for Beginners.
|
[
{
"code": null,
"e": 323,
"s": 172,
"text": "To develop a complete mind: Study the science of art; Study the art of science. Learn how to see. Realize that everything connects to everything else."
},
{
"code": null,
"e": 341,
"s": 323,
"text": "Leonardo da Vinci"
},
{
"code": null,
"e": 587,
"s": 341,
"text": "The purpose of this article is to give you a panorama of data structures and algorithms in Python. This topic is very important for a Data Scientist in order to help him or her to design and solve machine learning models in a more effective way."
},
{
"code": null,
"e": 832,
"s": 587,
"text": "We will see together with practical examples the built-in data structures, the user-defined data structures, and last but not least I will introduce you to some algorithms like traversal algorithms, sorting algorithms, and searching algorithms."
},
{
"code": null,
"e": 855,
"s": 832,
"text": "So, let’s get started!"
},
{
"code": null,
"e": 977,
"s": 855,
"text": "As the name suggests, data structures allow us to organize, store, and manage data for efficient access and modification."
},
{
"code": null,
"e": 1142,
"s": 977,
"text": "In this part, we are going to take a look at built-in data structures. There are four types of built-in data structures in Python: list, tuple, set, and dictionary."
},
{
"code": null,
"e": 1147,
"s": 1142,
"text": "List"
},
{
"code": null,
"e": 1310,
"s": 1147,
"text": "A list is defined using square brackets and holds data that is separated by commas. The list is mutable and ordered. It can contain a mix of different data types."
},
{
"code": null,
"e": 1315,
"s": 1310,
"text": "out:"
},
{
"code": null,
"e": 1510,
"s": 1315,
"text": "january['january', 'february', 'march', 'april', 'may', 'june', 'july']['birthday', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december']"
},
{
"code": null,
"e": 1562,
"s": 1510,
"text": "Below there are some useful functions for the list."
},
{
"code": null,
"e": 1567,
"s": 1562,
"text": "out:"
},
{
"code": null,
"e": 1626,
"s": 1567,
"text": "Whatisyourfavouritepainting?Who-is-your-favourite-artist-?"
},
{
"code": null,
"e": 1631,
"s": 1626,
"text": "out:"
},
{
"code": null,
"e": 1711,
"s": 1631,
"text": "['Chagall', 'Kandinskij', 'Dalí', 'da Vinci', 'Picasso', 'Warhol', 'Basquiat']"
},
{
"code": null,
"e": 1717,
"s": 1711,
"text": "Tuple"
},
{
"code": null,
"e": 1898,
"s": 1717,
"text": "A tuple is another container. It is a data type for immutable ordered sequences of elements. Immutable because you can’t add and remove elements from tuples, or sort them in place."
},
{
"code": null,
"e": 1903,
"s": 1898,
"text": "out:"
},
{
"code": null,
"e": 1932,
"s": 1903,
"text": "The dimensions are 7 x 3 x 1"
},
{
"code": null,
"e": 1936,
"s": 1932,
"text": "Set"
},
{
"code": null,
"e": 2056,
"s": 1936,
"text": "Set is a mutable and unordered collection of unique elements. It can permit us to remove duplicate quickly from a list."
},
{
"code": null,
"e": 2061,
"s": 2056,
"text": "out:"
},
{
"code": null,
"e": 2090,
"s": 2061,
"text": "{1, 2, 3, 5, 6}FalseBasquiat"
},
{
"code": null,
"e": 2101,
"s": 2090,
"text": "Dictionary"
},
{
"code": null,
"e": 2214,
"s": 2101,
"text": "Dictionary is a mutable and unordered data structure. It permits storing a pair of items (i.e. keys and values)."
},
{
"code": null,
"e": 2356,
"s": 2214,
"text": "As the example below shows, in the dictionary, it is possible to include containers into other containers to create compound data structures."
},
{
"code": null,
"e": 2361,
"s": 2356,
"text": "out:"
},
{
"code": null,
"e": 2392,
"s": 2361,
"text": "In a Sentimental MoodLacrimosa"
},
{
"code": null,
"e": 2543,
"s": 2392,
"text": "Now I will introduce you three user-defined data structures: ques, stack, and tree. I assume that you have a basic knowledge of classes and functions."
},
{
"code": null,
"e": 2562,
"s": 2543,
"text": "Stack using arrays"
},
{
"code": null,
"e": 2785,
"s": 2562,
"text": "The stack is a linear data structure where elements are arranged sequentially. It follows the mechanism L.I.F.O which means last in first out. So, the last element inserted will be removed as the first. The operations are:"
},
{
"code": null,
"e": 2828,
"s": 2785,
"text": "Push → inserting an element into the stack"
},
{
"code": null,
"e": 2869,
"s": 2828,
"text": "Pop → deleting an element from the stack"
},
{
"code": null,
"e": 2894,
"s": 2869,
"text": "The conditions to check:"
},
{
"code": null,
"e": 3027,
"s": 2894,
"text": "overflow condition → this condition occurs when we try to put one more element into a stack that is already having maximum elements."
},
{
"code": null,
"e": 3124,
"s": 3027,
"text": "underflow condition →this condition occurs when we try to delete an element from an empty stack."
},
{
"code": null,
"e": 3129,
"s": 3124,
"text": "out:"
},
{
"code": null,
"e": 3182,
"s": 3129,
"text": "5True[10, 23, 25, 27, 11]overflow1127252310underflow"
},
{
"code": null,
"e": 3201,
"s": 3182,
"text": "Queue using arrays"
},
{
"code": null,
"e": 3538,
"s": 3201,
"text": "The queue is a linear data structure where elements are in a sequential manner. It follows the F.I.F.O mechanism that means first in first out. Think when you go to the cinema with your friends, as you can imagine the first of you that give the ticket is also the first that step out of the line. The mechanism of the queue is the same."
},
{
"code": null,
"e": 3583,
"s": 3538,
"text": "Below the aspects that characterize a queue."
},
{
"code": null,
"e": 3593,
"s": 3583,
"text": "Two ends:"
},
{
"code": null,
"e": 3628,
"s": 3593,
"text": "front → points to starting element"
},
{
"code": null,
"e": 3662,
"s": 3628,
"text": "rear → points to the last element"
},
{
"code": null,
"e": 3688,
"s": 3662,
"text": "There are two operations:"
},
{
"code": null,
"e": 3764,
"s": 3688,
"text": "enqueue → inserting an element into the queue. It will be done at the rear."
},
{
"code": null,
"e": 3840,
"s": 3764,
"text": "dequeue → deleting an element from the queue. It will be done at the front."
},
{
"code": null,
"e": 3866,
"s": 3840,
"text": "There are two conditions:"
},
{
"code": null,
"e": 3913,
"s": 3866,
"text": "overflow → insertion into a queue that is full"
},
{
"code": null,
"e": 3955,
"s": 3913,
"text": "underflow → deletion from the empty queue"
},
{
"code": null,
"e": 3960,
"s": 3955,
"text": "out:"
},
{
"code": null,
"e": 3982,
"s": 3960,
"text": "[2, 3, 4, 5][3, 4, 5]"
},
{
"code": null,
"e": 4002,
"s": 3982,
"text": "Tree (general tree)"
},
{
"code": null,
"e": 4129,
"s": 4002,
"text": "Trees are used to define hierarchy. It starts with the root node and goes further down, the last nodes are called child nodes."
},
{
"code": null,
"e": 4514,
"s": 4129,
"text": "In this article, I focus on the binary tree. The binary tree is a tree data structure in which each node has at most two children, which are referred to as the left child and the right child. Below you can see a representation and an example of the binary tree with python where I constructed a class called Node and the objects that represent the different nodes( A, B, C, D, and E)."
},
{
"code": null,
"e": 4597,
"s": 4514,
"text": "Anyway, there are other user-defined data structures like linked lists and graphs."
},
{
"code": null,
"e": 4773,
"s": 4597,
"text": "The concept of the algorithm has existed since antiquity. In fact, the ancient Egyptians used algorithms to solve their problems. Then they taught this approach to the Greeks."
},
{
"code": null,
"e": 5027,
"s": 4773,
"text": "The word algorithm derives itself from the 9th-century Persian mathematician Muḥammad ibn Mūsā al-Khwārizmī, whose name was Latinized as Algorithmi. Al-Khwārizmī was also an astronomer, geographer, and a scholar in the House of Wisdom in Baghdad."
},
{
"code": null,
"e": 5147,
"s": 5027,
"text": "As you already know algorithms are instructions that are formulated in a finite and sequential order to solve problems."
},
{
"code": null,
"e": 5298,
"s": 5147,
"text": "When we write an algorithm, we have to know what is the exact problem, determine where we need to start and stop and formulate the intermediate steps."
},
{
"code": null,
"e": 5351,
"s": 5298,
"text": "There are three main approaches to solve algorithms:"
},
{
"code": null,
"e": 5474,
"s": 5351,
"text": "Divide et Impera (also known as divide and conquer) → it divides the problem into sub-parts and solves each one separately"
},
{
"code": null,
"e": 5604,
"s": 5474,
"text": "Dynamic programming → it divides the problem into sub-parts remembers the results of the sub-parts and applies it to similar ones"
},
{
"code": null,
"e": 5738,
"s": 5604,
"text": "Greedy algorithms → involve taking the easiest step while solving a problem without worrying about the complexity of the future steps"
},
{
"code": null,
"e": 5763,
"s": 5738,
"text": "Tree Traversal Algorithm"
},
{
"code": null,
"e": 5913,
"s": 5763,
"text": "Trees in python are non-linear data structures. They are characterized by roots and nodes. I take the class I constructed before for the binary tree."
},
{
"code": null,
"e": 6025,
"s": 5913,
"text": "Tree Traversal refers to visiting each node present in the tree exactly once, in order to update or check them."
},
{
"code": null,
"e": 6067,
"s": 6025,
"text": "There are three types of tree traversals:"
},
{
"code": null,
"e": 6169,
"s": 6067,
"text": "In-order traversal → refers to visiting the left node, followed by the root and then the right nodes."
},
{
"code": null,
"e": 6342,
"s": 6169,
"text": "Here D is the leftmost node where the nearest root is B. The right of root B is E. Now the left sub-tree is completed, so I move towards the root node A and then to node C."
},
{
"code": null,
"e": 6347,
"s": 6342,
"text": "out:"
},
{
"code": null,
"e": 6353,
"s": 6347,
"text": "DBEAC"
},
{
"code": null,
"e": 6461,
"s": 6353,
"text": "Pre-order traversal → refers to visiting the root node followed by the left nodes and then the right nodes."
},
{
"code": null,
"e": 6611,
"s": 6461,
"text": "In this case, I move to the root node A and then to the left child node B and to the sub child node D. After that I can go to the nodes E and then C."
},
{
"code": null,
"e": 6616,
"s": 6611,
"text": "out:"
},
{
"code": null,
"e": 6622,
"s": 6616,
"text": "ABDEC"
},
{
"code": null,
"e": 6730,
"s": 6622,
"text": "Post-order traversal → refers to visiting the left nodes followed by the right nodes and then the root node"
},
{
"code": null,
"e": 6896,
"s": 6730,
"text": "I go to the most left node which is D and then to the right node E. Then, I can go from the left node B to the right node C. Finally, I move towards the root node A."
},
{
"code": null,
"e": 6901,
"s": 6896,
"text": "out:"
},
{
"code": null,
"e": 6907,
"s": 6901,
"text": "DEBCA"
},
{
"code": null,
"e": 6925,
"s": 6907,
"text": "Sorting Algorithm"
},
{
"code": null,
"e": 7041,
"s": 6925,
"text": "The sorting algorithm is used to sort data in some given order. It can be classified in Merge Sort and Bubble Sort."
},
{
"code": null,
"e": 7355,
"s": 7041,
"text": "Merge Sort → it follows the divide et Impera rule. The given list is first divided into smaller lists and compares adjacent lists and then, reorders them in the desired sequence. So, in summary from unordered elements as input, we need to have ordered elements as output. Below, the code with each step described."
},
{
"code": null,
"e": 7360,
"s": 7355,
"text": "out:"
},
{
"code": null,
"e": 7441,
"s": 7360,
"text": "input - unordered elements: 15 1 19 93output - ordered elements: [1, 15, 19, 93]"
},
{
"code": null,
"e": 7546,
"s": 7441,
"text": "Bubble Sort → it first compares and then sorts adjacent elements if they are not in the specified order."
},
{
"code": null,
"e": 7551,
"s": 7546,
"text": "out:"
},
{
"code": null,
"e": 7565,
"s": 7551,
"text": "[1, 3, 9, 15]"
},
{
"code": null,
"e": 7686,
"s": 7565,
"text": "Insertion Sort → it picks one item of a given list at the time and places it at the exact spot where it is to be placed."
},
{
"code": null,
"e": 7691,
"s": 7686,
"text": "out:"
},
{
"code": null,
"e": 7705,
"s": 7691,
"text": "[1, 3, 9, 15]"
},
{
"code": null,
"e": 7776,
"s": 7705,
"text": "There are other Sorting Algorithms like Selection Sort and Shell Sort."
},
{
"code": null,
"e": 7797,
"s": 7776,
"text": "Searching Algorithms"
},
{
"code": null,
"e": 8080,
"s": 7797,
"text": "Searching algorithms are used to seek for some elements present in a given dataset. There are many types of search algorithms such as Linear Search, Binary Search, Exponential Search, Interpolation Search, and so on. In this section, we will see the Linear Search and Binary Search."
},
{
"code": null,
"e": 8379,
"s": 8080,
"text": "Linear Search → in a single-dimensional array we have to search a particular key element. The input is the group of elements and the key element that we want to find. So, we have to compare the key element with each element of the group. In the following code, I try to seek element 27 in our list."
},
{
"code": null,
"e": 8384,
"s": 8379,
"text": "out:"
},
{
"code": null,
"e": 8395,
"s": 8384,
"text": "'not fund'"
},
{
"code": null,
"e": 8715,
"s": 8395,
"text": "Binary Search → in this algorithm, we assume that the list is in ascending order. So, if the value of the search key is less than the element in the middle of the list, we narrow the interval to the lower half. Otherwise, we narrow to the upper half. We continue our check until the value is found or the list is empty."
},
{
"code": null,
"e": 8720,
"s": 8715,
"text": "out:"
},
{
"code": null,
"e": 8730,
"s": 8720,
"text": "FalseTrue"
},
{
"code": null,
"e": 8855,
"s": 8730,
"text": "Now you have an overview of data structures and algorithms. So, you can start going to a deeper understanding of algorithms."
},
{
"code": null,
"e": 9209,
"s": 8855,
"text": "The beautiful image of the Vitruvian Man I have chosen for this article is not casual. The drawing is based on the correlation of the ideal human body in relation to geometry. In fact, for this representation, Leonardo da Vinci was inspired by Vitruvius who described the man’s body as the ideal body to determine the correct proportion in architecture."
},
{
"code": null,
"e": 9384,
"s": 9209,
"text": "For what concerns algorithms, the Vitruvian Man hides a secret algorithm used by the artists for centuries to certify that their works were inspired by the divine proportion."
},
{
"code": null,
"e": 9547,
"s": 9384,
"text": "Sometimes I like to think that maybe Leonardo da Vinci, through his wonderful works, wanted to define the most important algorithm which is the algorithm of life."
},
{
"code": null,
"e": 9648,
"s": 9547,
"text": "Thanks for reading this. There are some other ways you can keep in touch with me and follow my work:"
},
{
"code": null,
"e": 9676,
"s": 9648,
"text": "Subscribe to my newsletter."
}
] |
Java - URL Processing
|
URL stands for Uniform Resource Locator and represents a resource on the World Wide Web, such as a Web page or FTP directory.
This section shows you how to write Java programs that communicate with a URL. A URL can be broken down into parts, as follows −
protocol://host:port/path?query#ref
Examples of protocols include HTTP, HTTPS, FTP, and File. The path is also referred to as the filename, and the host is also called the authority.
The following is a URL to a web page whose protocol is HTTP −
https://www.amrood.com/index.htm?language=en#j2se
Notice that this URL does not specify a port, in which case the default port for the protocol is used. With HTTP, the default port is 80.
The java.net.URL class represents a URL and has a complete set of methods to manipulate URL in Java.
The URL class has several constructors for creating URLs, including the following −
public URL(String protocol, String host, int port, String file) throws MalformedURLException
Creates a URL by putting together the given parts.
public URL(String protocol, String host, String file) throws MalformedURLException
Identical to the previous constructor, except that the default port for the given protocol is used.
public URL(String url) throws MalformedURLException
Creates a URL from the given String.
public URL(URL context, String url) throws MalformedURLException
Creates a URL by parsing together the URL and String arguments.
The URL class contains many methods for accessing the various parts of the URL being represented. Some of the methods in the URL class include the following −
public String getPath()
Returns the path of the URL.
public String getQuery()
Returns the query part of the URL.
public String getAuthority()
Returns the authority of the URL.
public int getPort()
Returns the port of the URL.
public int getDefaultPort()
Returns the default port for the protocol of the URL.
public String getProtocol()
Returns the protocol of the URL.
public String getHost()
Returns the host of the URL.
public String getHost()
Returns the host of the URL.
public String getFile()
Returns the filename of the URL.
public String getRef()
Returns the reference part of the URL.
public URLConnection openConnection() throws IOException
Opens a connection to the URL, allowing a client to communicate with the resource.
The following URLDemo program demonstrates the various parts of a URL. A URL is entered on the command line, and the URLDemo program outputs each part of the given URL.
// File Name : URLDemo.java
import java.net.*;
import java.io.*;
public class URLDemo {
public static void main(String [] args) {
try {
URL url = new URL("https://www.amrood.com/index.htm?language=en#j2se");
System.out.println("URL is " + url.toString());
System.out.println("protocol is " + url.getProtocol());
System.out.println("authority is " + url.getAuthority());
System.out.println("file name is " + url.getFile());
System.out.println("host is " + url.getHost());
System.out.println("path is " + url.getPath());
System.out.println("port is " + url.getPort());
System.out.println("default port is " + url.getDefaultPort());
System.out.println("query is " + url.getQuery());
System.out.println("ref is " + url.getRef());
} catch (IOException e) {
e.printStackTrace();
}
}
}
A sample run of the this program will produce the following result −
URL is https://www.amrood.com/index.htm?language=en#j2se
protocol is http
authority is www.amrood.com
file name is /index.htm?language=en
host is www.amrood.com
path is /index.htm
port is -1
default port is 80
query is language=en
ref is j2se
The openConnection() method returns a java.net.URLConnection, an abstract class whose subclasses represent the various types of URL connections.
For example −
If you connect to a URL whose protocol is HTTP, the openConnection() method returns an HttpURLConnection object.
If you connect to a URL whose protocol is HTTP, the openConnection() method returns an HttpURLConnection object.
If you connect to a URL that represents a JAR file, the openConnection() method returns a JarURLConnection object, etc.
If you connect to a URL that represents a JAR file, the openConnection() method returns a JarURLConnection object, etc.
The URLConnection class has many methods for setting or determining information about the connection, including the following −
Object getContent()
Retrieves the contents of this URL connection.
Object getContent(Class[] classes)
Retrieves the contents of this URL connection.
String getContentEncoding()
Returns the value of the content-encoding header field.
int getContentLength()
Returns the value of the content-length header field.
String getContentType()
Returns the value of the content-type header field.
int getLastModified()
Returns the value of the last-modified header field.
long getExpiration()
Returns the value of the expired header field.
long getIfModifiedSince()
Returns the value of this object's ifModifiedSince field.
public void setDoInput(boolean input)
Passes in true to denote that the connection will be used for input. The default value is true because clients typically read from a URLConnection.
public void setDoOutput(boolean output)
Passes in true to denote that the connection will be used for output. The default value is false because many types of URLs do not support being written to.
public InputStream getInputStream() throws IOException
Returns the input stream of the URL connection for reading from the resource.
public OutputStream getOutputStream() throws IOException
Returns the output stream of the URL connection for writing to the resource.
public URL getURL()
Returns the URL that this URLConnection object is connected to.
The following URLConnectionDemo program connects to a URL entered from the command line.
If the URL represents an HTTP resource, the connection is cast to HttpURLConnection, and the data in the resource is read one line at a time.
// File Name : URLConnDemo.java
import java.net.*;
import java.io.*;
public class URLConnDemo {
public static void main(String [] args) {
try {
URL url = new URL("https://www.amrood.com");
URLConnection urlConnection = url.openConnection();
HttpURLConnection connection = null;
if(urlConnection instanceof HttpURLConnection) {
connection = (HttpURLConnection) urlConnection;
}else {
System.out.println("Please enter an HTTP URL.");
return;
}
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String urlString = "";
String current;
while((current = in.readLine()) != null) {
urlString += current;
}
System.out.println(urlString);
} catch (IOException e) {
e.printStackTrace();
}
}
}
A sample run of this program will produce the following result −
$ java URLConnDemo
.....a complete HTML content of home page of amrood.com.....
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": 2503,
"s": 2377,
"text": "URL stands for Uniform Resource Locator and represents a resource on the World Wide Web, such as a Web page or FTP directory."
},
{
"code": null,
"e": 2632,
"s": 2503,
"text": "This section shows you how to write Java programs that communicate with a URL. A URL can be broken down into parts, as follows −"
},
{
"code": null,
"e": 2669,
"s": 2632,
"text": "protocol://host:port/path?query#ref\n"
},
{
"code": null,
"e": 2816,
"s": 2669,
"text": "Examples of protocols include HTTP, HTTPS, FTP, and File. The path is also referred to as the filename, and the host is also called the authority."
},
{
"code": null,
"e": 2878,
"s": 2816,
"text": "The following is a URL to a web page whose protocol is HTTP −"
},
{
"code": null,
"e": 2929,
"s": 2878,
"text": "https://www.amrood.com/index.htm?language=en#j2se\n"
},
{
"code": null,
"e": 3067,
"s": 2929,
"text": "Notice that this URL does not specify a port, in which case the default port for the protocol is used. With HTTP, the default port is 80."
},
{
"code": null,
"e": 3168,
"s": 3067,
"text": "The java.net.URL class represents a URL and has a complete set of methods to manipulate URL in Java."
},
{
"code": null,
"e": 3252,
"s": 3168,
"text": "The URL class has several constructors for creating URLs, including the following −"
},
{
"code": null,
"e": 3345,
"s": 3252,
"text": "public URL(String protocol, String host, int port, String file) throws MalformedURLException"
},
{
"code": null,
"e": 3396,
"s": 3345,
"text": "Creates a URL by putting together the given parts."
},
{
"code": null,
"e": 3479,
"s": 3396,
"text": "public URL(String protocol, String host, String file) throws MalformedURLException"
},
{
"code": null,
"e": 3579,
"s": 3479,
"text": "Identical to the previous constructor, except that the default port for the given protocol is used."
},
{
"code": null,
"e": 3631,
"s": 3579,
"text": "public URL(String url) throws MalformedURLException"
},
{
"code": null,
"e": 3668,
"s": 3631,
"text": "Creates a URL from the given String."
},
{
"code": null,
"e": 3733,
"s": 3668,
"text": "public URL(URL context, String url) throws MalformedURLException"
},
{
"code": null,
"e": 3797,
"s": 3733,
"text": "Creates a URL by parsing together the URL and String arguments."
},
{
"code": null,
"e": 3956,
"s": 3797,
"text": "The URL class contains many methods for accessing the various parts of the URL being represented. Some of the methods in the URL class include the following −"
},
{
"code": null,
"e": 3980,
"s": 3956,
"text": "public String getPath()"
},
{
"code": null,
"e": 4009,
"s": 3980,
"text": "Returns the path of the URL."
},
{
"code": null,
"e": 4034,
"s": 4009,
"text": "public String getQuery()"
},
{
"code": null,
"e": 4069,
"s": 4034,
"text": "Returns the query part of the URL."
},
{
"code": null,
"e": 4098,
"s": 4069,
"text": "public String getAuthority()"
},
{
"code": null,
"e": 4132,
"s": 4098,
"text": "Returns the authority of the URL."
},
{
"code": null,
"e": 4153,
"s": 4132,
"text": "public int getPort()"
},
{
"code": null,
"e": 4182,
"s": 4153,
"text": "Returns the port of the URL."
},
{
"code": null,
"e": 4210,
"s": 4182,
"text": "public int getDefaultPort()"
},
{
"code": null,
"e": 4264,
"s": 4210,
"text": "Returns the default port for the protocol of the URL."
},
{
"code": null,
"e": 4292,
"s": 4264,
"text": "public String getProtocol()"
},
{
"code": null,
"e": 4325,
"s": 4292,
"text": "Returns the protocol of the URL."
},
{
"code": null,
"e": 4349,
"s": 4325,
"text": "public String getHost()"
},
{
"code": null,
"e": 4378,
"s": 4349,
"text": "Returns the host of the URL."
},
{
"code": null,
"e": 4402,
"s": 4378,
"text": "public String getHost()"
},
{
"code": null,
"e": 4431,
"s": 4402,
"text": "Returns the host of the URL."
},
{
"code": null,
"e": 4455,
"s": 4431,
"text": "public String getFile()"
},
{
"code": null,
"e": 4488,
"s": 4455,
"text": "Returns the filename of the URL."
},
{
"code": null,
"e": 4511,
"s": 4488,
"text": "public String getRef()"
},
{
"code": null,
"e": 4550,
"s": 4511,
"text": "Returns the reference part of the URL."
},
{
"code": null,
"e": 4607,
"s": 4550,
"text": "public URLConnection openConnection() throws IOException"
},
{
"code": null,
"e": 4690,
"s": 4607,
"text": "Opens a connection to the URL, allowing a client to communicate with the resource."
},
{
"code": null,
"e": 4859,
"s": 4690,
"text": "The following URLDemo program demonstrates the various parts of a URL. A URL is entered on the command line, and the URLDemo program outputs each part of the given URL."
},
{
"code": null,
"e": 5782,
"s": 4859,
"text": "// File Name : URLDemo.java\nimport java.net.*;\nimport java.io.*;\n\npublic class URLDemo {\n\n public static void main(String [] args) {\n try {\n URL url = new URL(\"https://www.amrood.com/index.htm?language=en#j2se\");\n \n System.out.println(\"URL is \" + url.toString());\n System.out.println(\"protocol is \" + url.getProtocol());\n System.out.println(\"authority is \" + url.getAuthority());\n System.out.println(\"file name is \" + url.getFile());\n System.out.println(\"host is \" + url.getHost());\n System.out.println(\"path is \" + url.getPath());\n System.out.println(\"port is \" + url.getPort());\n System.out.println(\"default port is \" + url.getDefaultPort());\n System.out.println(\"query is \" + url.getQuery());\n System.out.println(\"ref is \" + url.getRef());\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n}"
},
{
"code": null,
"e": 5851,
"s": 5782,
"text": "A sample run of the this program will produce the following result −"
},
{
"code": null,
"e": 6095,
"s": 5851,
"text": "URL is https://www.amrood.com/index.htm?language=en#j2se\nprotocol is http\nauthority is www.amrood.com\nfile name is /index.htm?language=en\nhost is www.amrood.com\npath is /index.htm\nport is -1\ndefault port is 80\nquery is language=en\nref is j2se\n"
},
{
"code": null,
"e": 6240,
"s": 6095,
"text": "The openConnection() method returns a java.net.URLConnection, an abstract class whose subclasses represent the various types of URL connections."
},
{
"code": null,
"e": 6254,
"s": 6240,
"text": "For example −"
},
{
"code": null,
"e": 6367,
"s": 6254,
"text": "If you connect to a URL whose protocol is HTTP, the openConnection() method returns an HttpURLConnection object."
},
{
"code": null,
"e": 6480,
"s": 6367,
"text": "If you connect to a URL whose protocol is HTTP, the openConnection() method returns an HttpURLConnection object."
},
{
"code": null,
"e": 6600,
"s": 6480,
"text": "If you connect to a URL that represents a JAR file, the openConnection() method returns a JarURLConnection object, etc."
},
{
"code": null,
"e": 6720,
"s": 6600,
"text": "If you connect to a URL that represents a JAR file, the openConnection() method returns a JarURLConnection object, etc."
},
{
"code": null,
"e": 6848,
"s": 6720,
"text": "The URLConnection class has many methods for setting or determining information about the connection, including the following −"
},
{
"code": null,
"e": 6868,
"s": 6848,
"text": "Object getContent()"
},
{
"code": null,
"e": 6915,
"s": 6868,
"text": "Retrieves the contents of this URL connection."
},
{
"code": null,
"e": 6950,
"s": 6915,
"text": "Object getContent(Class[] classes)"
},
{
"code": null,
"e": 6997,
"s": 6950,
"text": "Retrieves the contents of this URL connection."
},
{
"code": null,
"e": 7025,
"s": 6997,
"text": "String getContentEncoding()"
},
{
"code": null,
"e": 7081,
"s": 7025,
"text": "Returns the value of the content-encoding header field."
},
{
"code": null,
"e": 7104,
"s": 7081,
"text": "int getContentLength()"
},
{
"code": null,
"e": 7158,
"s": 7104,
"text": "Returns the value of the content-length header field."
},
{
"code": null,
"e": 7182,
"s": 7158,
"text": "String getContentType()"
},
{
"code": null,
"e": 7234,
"s": 7182,
"text": "Returns the value of the content-type header field."
},
{
"code": null,
"e": 7256,
"s": 7234,
"text": "int getLastModified()"
},
{
"code": null,
"e": 7309,
"s": 7256,
"text": "Returns the value of the last-modified header field."
},
{
"code": null,
"e": 7330,
"s": 7309,
"text": "long getExpiration()"
},
{
"code": null,
"e": 7377,
"s": 7330,
"text": "Returns the value of the expired header field."
},
{
"code": null,
"e": 7403,
"s": 7377,
"text": "long getIfModifiedSince()"
},
{
"code": null,
"e": 7461,
"s": 7403,
"text": "Returns the value of this object's ifModifiedSince field."
},
{
"code": null,
"e": 7499,
"s": 7461,
"text": "public void setDoInput(boolean input)"
},
{
"code": null,
"e": 7647,
"s": 7499,
"text": "Passes in true to denote that the connection will be used for input. The default value is true because clients typically read from a URLConnection."
},
{
"code": null,
"e": 7687,
"s": 7647,
"text": "public void setDoOutput(boolean output)"
},
{
"code": null,
"e": 7844,
"s": 7687,
"text": "Passes in true to denote that the connection will be used for output. The default value is false because many types of URLs do not support being written to."
},
{
"code": null,
"e": 7899,
"s": 7844,
"text": "public InputStream getInputStream() throws IOException"
},
{
"code": null,
"e": 7977,
"s": 7899,
"text": "Returns the input stream of the URL connection for reading from the resource."
},
{
"code": null,
"e": 8034,
"s": 7977,
"text": "public OutputStream getOutputStream() throws IOException"
},
{
"code": null,
"e": 8111,
"s": 8034,
"text": "Returns the output stream of the URL connection for writing to the resource."
},
{
"code": null,
"e": 8131,
"s": 8111,
"text": "public URL getURL()"
},
{
"code": null,
"e": 8195,
"s": 8131,
"text": "Returns the URL that this URLConnection object is connected to."
},
{
"code": null,
"e": 8284,
"s": 8195,
"text": "The following URLConnectionDemo program connects to a URL entered from the command line."
},
{
"code": null,
"e": 8426,
"s": 8284,
"text": "If the URL represents an HTTP resource, the connection is cast to HttpURLConnection, and the data in the resource is read one line at a time."
},
{
"code": null,
"e": 9374,
"s": 8426,
"text": "// File Name : URLConnDemo.java\nimport java.net.*;\nimport java.io.*;\n\npublic class URLConnDemo {\n\n public static void main(String [] args) {\n try {\n URL url = new URL(\"https://www.amrood.com\");\n URLConnection urlConnection = url.openConnection();\n HttpURLConnection connection = null;\n if(urlConnection instanceof HttpURLConnection) {\n connection = (HttpURLConnection) urlConnection;\n }else {\n System.out.println(\"Please enter an HTTP URL.\");\n return;\n }\n \n BufferedReader in = new BufferedReader(\n new InputStreamReader(connection.getInputStream()));\n String urlString = \"\";\n String current;\n \n while((current = in.readLine()) != null) {\n urlString += current;\n }\n System.out.println(urlString);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n}"
},
{
"code": null,
"e": 9439,
"s": 9374,
"text": "A sample run of this program will produce the following result −"
},
{
"code": null,
"e": 9521,
"s": 9439,
"text": "$ java URLConnDemo\n\n.....a complete HTML content of home page of amrood.com.....\n"
},
{
"code": null,
"e": 9554,
"s": 9521,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 9570,
"s": 9554,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 9603,
"s": 9570,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 9619,
"s": 9603,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 9654,
"s": 9619,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 9668,
"s": 9654,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 9702,
"s": 9668,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 9716,
"s": 9702,
"text": " Tushar Kale"
},
{
"code": null,
"e": 9753,
"s": 9716,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 9768,
"s": 9753,
"text": " Monica Mittal"
},
{
"code": null,
"e": 9801,
"s": 9768,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 9820,
"s": 9801,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 9827,
"s": 9820,
"text": " Print"
},
{
"code": null,
"e": 9838,
"s": 9827,
"text": " Add Notes"
}
] |
Program to find sum of the sum of all contiguous sublists in Python
|
Suppose we have a list of numbers called nums, now consider every contiguous subarray. Sum each of these subarray and return the sum of all these values. Finally, mod the result by 10 ** 9 + 7.
So, if the input is like nums = [3, 4, 6], then the output will be 43, as We have the following subarrays − [3] [4] [6] [3, 4] [4, 6] [3, 4, 6] The sum of all of these is 43.
To solve this, we will follow these steps −
N:= size of nums
ans:= 0
for i in range 0 to size of nums, don:= nums[i]ans := ans +(i+1) *(N-i) * n
n:= nums[i]
ans := ans +(i+1) *(N-i) * n
return (ans mod 1000000007)
Let us see the following implementation to get better understanding −
Live Demo
class Solution:
def solve(self, nums):
N=len(nums)
ans=0
for i in range(len(nums)):
n=nums[i]
ans += (i+1) * (N-i) * n
return ans%1000000007
ob = Solution()
print(ob.solve([3, 4, 6]))
[3, 4, 6]
43
|
[
{
"code": null,
"e": 1256,
"s": 1062,
"text": "Suppose we have a list of numbers called nums, now consider every contiguous subarray. Sum each of these subarray and return the sum of all these values. Finally, mod the result by 10 ** 9 + 7."
},
{
"code": null,
"e": 1431,
"s": 1256,
"text": "So, if the input is like nums = [3, 4, 6], then the output will be 43, as We have the following subarrays − [3] [4] [6] [3, 4] [4, 6] [3, 4, 6] The sum of all of these is 43."
},
{
"code": null,
"e": 1475,
"s": 1431,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1492,
"s": 1475,
"text": "N:= size of nums"
},
{
"code": null,
"e": 1500,
"s": 1492,
"text": "ans:= 0"
},
{
"code": null,
"e": 1576,
"s": 1500,
"text": "for i in range 0 to size of nums, don:= nums[i]ans := ans +(i+1) *(N-i) * n"
},
{
"code": null,
"e": 1588,
"s": 1576,
"text": "n:= nums[i]"
},
{
"code": null,
"e": 1617,
"s": 1588,
"text": "ans := ans +(i+1) *(N-i) * n"
},
{
"code": null,
"e": 1645,
"s": 1617,
"text": "return (ans mod 1000000007)"
},
{
"code": null,
"e": 1715,
"s": 1645,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 1726,
"s": 1715,
"text": " Live Demo"
},
{
"code": null,
"e": 1955,
"s": 1726,
"text": "class Solution:\n def solve(self, nums):\n N=len(nums)\n ans=0\n for i in range(len(nums)):\n n=nums[i]\n ans += (i+1) * (N-i) * n\n return ans%1000000007\nob = Solution()\nprint(ob.solve([3, 4, 6]))"
},
{
"code": null,
"e": 1965,
"s": 1955,
"text": "[3, 4, 6]"
},
{
"code": null,
"e": 1968,
"s": 1965,
"text": "43"
}
] |
Moving all special char to the end of the String using Java Regular Expression RegEx)
|
The following regular expression matches all the special characters i.e. all characters except English alphabet spaces and digits.
"[^a-zA-Z0-9\\s+]"
To move all the special characters to the end of the given line, match all the special characters using this regex concatenate them to an empty string and concatenate remaining characters to another string finally, concatenate these two strings.
public class RemovingSpecialCharacters {
public static void main(String args[]) {
String input = "sample # text * with & special@ characters";
String regex = "[^a-zA-Z0-9\\s+]";
String specialChars = "";
String inputData = "";
for(int i=0; i< input.length(); i++) {
char ch = input.charAt(i);
if(String.valueOf(ch).matches(regex)) {
specialChars = specialChars + ch;
} else {
inputData = inputData + ch;
}
}
System.out.println("Result: "+inputData+specialChars);
}
}
Result: sample text with special characters#*&@
Following is the Java program which moves the special characters of a string to its end using the methods of Regex package.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String args[]) {
String input = "sample # text * with & special@ characters";
String regex = "[^a-zA-Z0-9\\s+]";
String specialChars = "";
System.out.println("Input string: \n"+input);
//Creating a pattern object
Pattern pattern = Pattern.compile(regex);
//Matching the compiled pattern in the String
Matcher matcher = pattern.matcher(input);
//Creating an empty string buffer
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
specialChars = specialChars+matcher.group();
matcher.appendReplacement(sb, "");
}
matcher.appendTail(sb);
System.out.println("Result: \n"+ sb.toString()+specialChars );
}
}
Input string:
sample # text * with & special@ characters
Result:
sample text with special characters#*&@
|
[
{
"code": null,
"e": 1193,
"s": 1062,
"text": "The following regular expression matches all the special characters i.e. all characters except English alphabet spaces and digits."
},
{
"code": null,
"e": 1212,
"s": 1193,
"text": "\"[^a-zA-Z0-9\\\\s+]\""
},
{
"code": null,
"e": 1458,
"s": 1212,
"text": "To move all the special characters to the end of the given line, match all the special characters using this regex concatenate them to an empty string and concatenate remaining characters to another string finally, concatenate these two strings."
},
{
"code": null,
"e": 2033,
"s": 1458,
"text": "public class RemovingSpecialCharacters {\n public static void main(String args[]) {\n String input = \"sample # text * with & special@ characters\";\n String regex = \"[^a-zA-Z0-9\\\\s+]\";\n String specialChars = \"\";\n String inputData = \"\";\n for(int i=0; i< input.length(); i++) {\n char ch = input.charAt(i);\n if(String.valueOf(ch).matches(regex)) {\n specialChars = specialChars + ch;\n } else {\n inputData = inputData + ch;\n }\n }\n System.out.println(\"Result: \"+inputData+specialChars);\n }\n}"
},
{
"code": null,
"e": 2081,
"s": 2033,
"text": "Result: sample text with special characters#*&@"
},
{
"code": null,
"e": 2205,
"s": 2081,
"text": "Following is the Java program which moves the special characters of a string to its end using the methods of Regex package."
},
{
"code": null,
"e": 3034,
"s": 2205,
"text": "import java.util.regex.Matcher;\nimport java.util.regex.Pattern;\npublic class Test {\n public static void main(String args[]) {\n String input = \"sample # text * with & special@ characters\";\n String regex = \"[^a-zA-Z0-9\\\\s+]\";\n String specialChars = \"\";\n System.out.println(\"Input string: \\n\"+input);\n //Creating a pattern object\n Pattern pattern = Pattern.compile(regex);\n //Matching the compiled pattern in the String\n Matcher matcher = pattern.matcher(input);\n //Creating an empty string buffer\n StringBuffer sb = new StringBuffer();\n while (matcher.find()) {\n specialChars = specialChars+matcher.group();\n matcher.appendReplacement(sb, \"\");\n }\n matcher.appendTail(sb);\n System.out.println(\"Result: \\n\"+ sb.toString()+specialChars );\n }\n}"
},
{
"code": null,
"e": 3139,
"s": 3034,
"text": "Input string:\nsample # text * with & special@ characters\nResult:\nsample text with special characters#*&@"
}
] |
Angular 2 - Metadata
|
Metadata is used to decorate a class so that it can configure the expected behavior of the class. Following are the different parts for metadata.
Annotations − These are decorators at the class level. This is an array and an example having both the @Component and @Routes decorator.
Following is a sample code, which is present in the app.component.ts file.
@Component ({
selector: 'my-app',
templateUrl: 'app/app.component.html'
})
The component decorator is used to declare the class in the app.component.ts file as a component.
Design:paramtypes − These are only used for the constructors and applied only to Typescript.
Design:paramtypes − These are only used for the constructors and applied only to Typescript.
propMetadata − This is the metadata which is applied to the properties of the class.
propMetadata − This is the metadata which is applied to the properties of the class.
Following is an example code.
export class AppComponent {
@Environment(‘test’)
appTitle: string = 'Welcome';
}
Here, the @Environment is the metadata applied to the property appTitle and the value given is ‘test’.
Parameters − This is set by the decorators at the constructor level.
Following is an example code.
export class AppComponent {
constructor(@Environment(‘test’ private appTitle:string) { }
}
In the above example, metadata is applied to the parameters of the constructor.
16 Lectures
1.5 hours
Anadi Sharma
28 Lectures
2.5 hours
Anadi Sharma
11 Lectures
7.5 hours
SHIVPRASAD KOIRALA
16 Lectures
2.5 hours
Frahaan Hussain
69 Lectures
5 hours
Senol Atac
53 Lectures
3.5 hours
Senol Atac
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2443,
"s": 2297,
"text": "Metadata is used to decorate a class so that it can configure the expected behavior of the class. Following are the different parts for metadata."
},
{
"code": null,
"e": 2580,
"s": 2443,
"text": "Annotations − These are decorators at the class level. This is an array and an example having both the @Component and @Routes decorator."
},
{
"code": null,
"e": 2655,
"s": 2580,
"text": "Following is a sample code, which is present in the app.component.ts file."
},
{
"code": null,
"e": 2740,
"s": 2655,
"text": "@Component ({ \n selector: 'my-app', \n templateUrl: 'app/app.component.html' \n}) "
},
{
"code": null,
"e": 2838,
"s": 2740,
"text": "The component decorator is used to declare the class in the app.component.ts file as a component."
},
{
"code": null,
"e": 2931,
"s": 2838,
"text": "Design:paramtypes − These are only used for the constructors and applied only to Typescript."
},
{
"code": null,
"e": 3024,
"s": 2931,
"text": "Design:paramtypes − These are only used for the constructors and applied only to Typescript."
},
{
"code": null,
"e": 3109,
"s": 3024,
"text": "propMetadata − This is the metadata which is applied to the properties of the class."
},
{
"code": null,
"e": 3194,
"s": 3109,
"text": "propMetadata − This is the metadata which is applied to the properties of the class."
},
{
"code": null,
"e": 3224,
"s": 3194,
"text": "Following is an example code."
},
{
"code": null,
"e": 3311,
"s": 3224,
"text": "export class AppComponent {\n @Environment(‘test’)\n appTitle: string = 'Welcome';\n}"
},
{
"code": null,
"e": 3414,
"s": 3311,
"text": "Here, the @Environment is the metadata applied to the property appTitle and the value given is ‘test’."
},
{
"code": null,
"e": 3483,
"s": 3414,
"text": "Parameters − This is set by the decorators at the constructor level."
},
{
"code": null,
"e": 3513,
"s": 3483,
"text": "Following is an example code."
},
{
"code": null,
"e": 3607,
"s": 3513,
"text": "export class AppComponent {\n constructor(@Environment(‘test’ private appTitle:string) { }\n}"
},
{
"code": null,
"e": 3687,
"s": 3607,
"text": "In the above example, metadata is applied to the parameters of the constructor."
},
{
"code": null,
"e": 3722,
"s": 3687,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3736,
"s": 3722,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3771,
"s": 3736,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3785,
"s": 3771,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3820,
"s": 3785,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 3840,
"s": 3820,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 3875,
"s": 3840,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3892,
"s": 3875,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3925,
"s": 3892,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 3937,
"s": 3925,
"text": " Senol Atac"
},
{
"code": null,
"e": 3972,
"s": 3937,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3984,
"s": 3972,
"text": " Senol Atac"
},
{
"code": null,
"e": 3991,
"s": 3984,
"text": " Print"
},
{
"code": null,
"e": 4002,
"s": 3991,
"text": " Add Notes"
}
] |
D3.js - Array API
|
D3 contains a collection of modules. You can use each module independently or a collection of modules together to perform operations. This chapter explains about the Array API in detail.
An Array contains a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.
You can easily configure the API using the script below.
<script src = "https://d3js.org/d3-array.v1.min.js"></script>
<body>
<script>
</script>
</body>
Following are some of the most important array statistics API methods.
d3.min(array)
d3.max(array)
d3.extent(array)
d3.sum(array)
d3.mean(array)
d3.quantile(array)
d3.variance(array)
d3.deviation(array)
Let us discuss each of these in detail.
It returns the minimum value in the given array using natural order.
Example − Consider the following script.
<script>
var data = [20,40,60,80,100];
console.log(d3.min(data));
</script>
Result − The above script returns the minmum value in the array 20 in your console.
It returns the maximum value in a given array.
Example − Consider the following script.
<script>
var data = [20,40,60,80,100];
console.log(d3.max(data));
</script>
Result − The above script returns the maximum value in the array (100) in your console.
It returns the minimum and maximum value in the given array.
Example − Consider the following script.
<script>
var data = [20,40,60,80,100];
console.log(d3.extent(data));
</script>
Result − The above script returns an extent value [20,100].
It returns the sum of the given array of numbers. If the array is empty, it returns 0.
Example − Consider the following below.
<script>
var data = [20,40,60,80,100];
console.log(d3.sum(data));
</script>
Result − The above script returns the sum value is 300.
It returns the mean of the given array of numbers.
Example − Consider the following below.
<script>
var data = [20,40,60,80,100];
console.log(d3.mean(data));
</script>
Result − The above script returns the mean value as 60. Similarly, you can check the median value.
It returns the p-quantile of the given sorted array of numbers, where p is a number in the range[0, 1]. For example, the median can be computed using p = 0.5, the first quartile at p = 0.25, and the third quartile at p = 0.75. This implementation uses the R-7 method, default R programming language and Excel.
Example − Consider the following example.
var data = [20, 40, 60, 80, 100];
d3.quantile(data, 0); // output is 20
d3.quantile(data, 0.5); // output is 60
d3.quantile(data, 1); // output is 100
Similarly, you can check other values.
It returns the variance of the given array of numbers.
Example − Consider the following script.
<script>
var data = [20,40,60,80,100];
console.log(d3.variance(data));
</script>
Result − The above script returns the variance value as 1000.
It returns the standard deviation of the given array. If the array has fewer than two values, it returns as undefined.
Example − Consider the following below.
<script>
var data = [20,40,60,80,100];
console.log(d3.deviation(data));
</script>
Result − The above script returns the deviation value as 31.622776601683793.
Example − Let us perform all the Array API methods discussed above using the following script. Create a webpage “array.html” and add the following changes to it.
<html>
<head>
<script type = "text/javascript" src = "https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<h3>D3 array API</h3>
<script>
var data = [20,40,60,80,100];
console.log(d3.min(data));
console.log(d3.max(data));
console.log(d3.extent(data));
console.log(d3.sum(data));
console.log(d3.mean(data));
console.log(d3.quantile(data,0.5));
console.log(d3.variance(data));
console.log(d3.deviation(data));
</script>
</body>
</html>
Now, request the browser and we will see the following response.
Following are a couple of important Array search API methods.
d3.scan(array)
d3.ascending(a, b)
Let us understand both of these in detail.
This method is used to perform a linear scan of the specified array. It returns the index of the least element to the specified comparator. A simple example is defined below.
Example −
var array = [{one: 1}, {one: 10}];
console.log(d3.scan(array, function(a, b) { return a.one - b.one; })); // output is 0
console.log(d3.scan(array, function(a, b) { return b.one - a.one; })); // output is 1
This method is used to perform the comparator function. It can be implemented as −
function ascending(a, b) {
return a < b ? -1 : a > b ? 1 : a > = b ? 0 : NaN;
}
If no comparator function is specified to the built-in sort method, the default order is alphabetical. The above function returns -1, if a is less than b, or 1, if a is greater than b, or 0.
Similarly, you can perform descending(a, b) method. It returns -1, if a is greater than b, or 1, if a is less than b, or 0. This function performs reverse natural order.
Example −
Create a webpage array_search.html and add the following changes to it.
<html>
<head>
<script type = "text/javascript" src = "https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<h3>D3 array API</h3>
<script>
var array = [{one: 1}, {one: 10}];
console.log(d3.scan(array, function(a, b) { return a.one - b.one; })); // 0
console.log(d3.scan(array, function(a, b) { return b.one - a.one; })); // 1
</script>
</body>
</html>
Now, request the browser and we will see the following result.
Following are some of the most prominent array transformations API methods.
d3.cross(a, b[, reducer])
d3.merge(arrays)
d3.pairs(array[, reducer])
d3.permute(array, indexes)
d3.zip(arrays)
Let us understand each of these in detail.
This method is used to return the Cartesian product of the given two arrays a and b. A simple example is defined below.
d3.cross([10, 20], ["a", "b"]); // output is [[10, "a"], [10, "b"], [20, "a"], [20, "b"]]
This method is used to merge the arrays and it is defined below.
d3.merge([[10], [20]]); // output is [10, 20]
This method is used to pair array elements and is defined below.
d3.pairs([10, 20, 30, 40]); // output is [[10, 20], [20, 30], [30, 40]]
This method is used to perform the permutation from specified array and indexes. You can also perform the values from an object into an array. It is explained below.
var object = {fruit:"mango", color: "yellow"},
fields = ["fruit", "color"];
d3.permute(object, fields); // output is "mango" "yellow"
This method is used to return an array of arrays. If arrays contain only a single array, the returned array contains one-element arrays. If no argument is specified, then the returned array is empty. It is defined below.
d3.zip([10, 20], [30, 40]); // output is [[10, 30], [20, 40]]
Example − Create a webpage array_transform and add the following changes to it.
<html>
<head>
<script type = "text/javascript" src = "https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<h3>D3 array API</h3>
<script>
console.log(d3.cross([10, 20], ["a", "b"]));
console.log(d3.merge([[10], [30]]));
console.log(d3.pairs([10, 20, 30, 40]));
var object = {fruit:"mango", color: "yellow"},
fields = ["fruit", "color"];
console.log(d3.permute(object, fields));
console.log(d3.zip([10, 20], [30, 40]));
</script>
</body>
</html>
Now, request the browser and we will see the following response.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2317,
"s": 2130,
"text": "D3 contains a collection of modules. You can use each module independently or a collection of modules together to perform operations. This chapter explains about the Array API in detail."
},
{
"code": null,
"e": 2544,
"s": 2317,
"text": "An Array contains a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type."
},
{
"code": null,
"e": 2601,
"s": 2544,
"text": "You can easily configure the API using the script below."
},
{
"code": null,
"e": 2703,
"s": 2601,
"text": "<script src = \"https://d3js.org/d3-array.v1.min.js\"></script>\n<body>\n <script>\n </script>\n</body>"
},
{
"code": null,
"e": 2774,
"s": 2703,
"text": "Following are some of the most important array statistics API methods."
},
{
"code": null,
"e": 2788,
"s": 2774,
"text": "d3.min(array)"
},
{
"code": null,
"e": 2802,
"s": 2788,
"text": "d3.max(array)"
},
{
"code": null,
"e": 2819,
"s": 2802,
"text": "d3.extent(array)"
},
{
"code": null,
"e": 2833,
"s": 2819,
"text": "d3.sum(array)"
},
{
"code": null,
"e": 2848,
"s": 2833,
"text": "d3.mean(array)"
},
{
"code": null,
"e": 2867,
"s": 2848,
"text": "d3.quantile(array)"
},
{
"code": null,
"e": 2886,
"s": 2867,
"text": "d3.variance(array)"
},
{
"code": null,
"e": 2906,
"s": 2886,
"text": "d3.deviation(array)"
},
{
"code": null,
"e": 2946,
"s": 2906,
"text": "Let us discuss each of these in detail."
},
{
"code": null,
"e": 3015,
"s": 2946,
"text": "It returns the minimum value in the given array using natural order."
},
{
"code": null,
"e": 3056,
"s": 3015,
"text": "Example − Consider the following script."
},
{
"code": null,
"e": 3138,
"s": 3056,
"text": "<script>\n var data = [20,40,60,80,100];\n console.log(d3.min(data));\n</script>"
},
{
"code": null,
"e": 3222,
"s": 3138,
"text": "Result − The above script returns the minmum value in the array 20 in your console."
},
{
"code": null,
"e": 3269,
"s": 3222,
"text": "It returns the maximum value in a given array."
},
{
"code": null,
"e": 3310,
"s": 3269,
"text": "Example − Consider the following script."
},
{
"code": null,
"e": 3392,
"s": 3310,
"text": "<script>\n var data = [20,40,60,80,100];\n console.log(d3.max(data));\n</script>"
},
{
"code": null,
"e": 3480,
"s": 3392,
"text": "Result − The above script returns the maximum value in the array (100) in your console."
},
{
"code": null,
"e": 3541,
"s": 3480,
"text": "It returns the minimum and maximum value in the given array."
},
{
"code": null,
"e": 3582,
"s": 3541,
"text": "Example − Consider the following script."
},
{
"code": null,
"e": 3667,
"s": 3582,
"text": "<script>\n var data = [20,40,60,80,100];\n console.log(d3.extent(data));\n</script>"
},
{
"code": null,
"e": 3727,
"s": 3667,
"text": "Result − The above script returns an extent value [20,100]."
},
{
"code": null,
"e": 3814,
"s": 3727,
"text": "It returns the sum of the given array of numbers. If the array is empty, it returns 0."
},
{
"code": null,
"e": 3854,
"s": 3814,
"text": "Example − Consider the following below."
},
{
"code": null,
"e": 3936,
"s": 3854,
"text": "<script>\n var data = [20,40,60,80,100];\n console.log(d3.sum(data));\n</script>"
},
{
"code": null,
"e": 3992,
"s": 3936,
"text": "Result − The above script returns the sum value is 300."
},
{
"code": null,
"e": 4043,
"s": 3992,
"text": "It returns the mean of the given array of numbers."
},
{
"code": null,
"e": 4083,
"s": 4043,
"text": "Example − Consider the following below."
},
{
"code": null,
"e": 4166,
"s": 4083,
"text": "<script>\n var data = [20,40,60,80,100];\n console.log(d3.mean(data));\n</script>"
},
{
"code": null,
"e": 4265,
"s": 4166,
"text": "Result − The above script returns the mean value as 60. Similarly, you can check the median value."
},
{
"code": null,
"e": 4575,
"s": 4265,
"text": "It returns the p-quantile of the given sorted array of numbers, where p is a number in the range[0, 1]. For example, the median can be computed using p = 0.5, the first quartile at p = 0.25, and the third quartile at p = 0.75. This implementation uses the R-7 method, default R programming language and Excel."
},
{
"code": null,
"e": 4617,
"s": 4575,
"text": "Example − Consider the following example."
},
{
"code": null,
"e": 4768,
"s": 4617,
"text": "var data = [20, 40, 60, 80, 100];\nd3.quantile(data, 0); // output is 20\nd3.quantile(data, 0.5); // output is 60\nd3.quantile(data, 1); // output is 100"
},
{
"code": null,
"e": 4807,
"s": 4768,
"text": "Similarly, you can check other values."
},
{
"code": null,
"e": 4862,
"s": 4807,
"text": "It returns the variance of the given array of numbers."
},
{
"code": null,
"e": 4903,
"s": 4862,
"text": "Example − Consider the following script."
},
{
"code": null,
"e": 4990,
"s": 4903,
"text": "<script>\n var data = [20,40,60,80,100];\n console.log(d3.variance(data));\n</script>"
},
{
"code": null,
"e": 5052,
"s": 4990,
"text": "Result − The above script returns the variance value as 1000."
},
{
"code": null,
"e": 5171,
"s": 5052,
"text": "It returns the standard deviation of the given array. If the array has fewer than two values, it returns as undefined."
},
{
"code": null,
"e": 5211,
"s": 5171,
"text": "Example − Consider the following below."
},
{
"code": null,
"e": 5299,
"s": 5211,
"text": "<script>\n var data = [20,40,60,80,100];\n console.log(d3.deviation(data));\n</script>"
},
{
"code": null,
"e": 5376,
"s": 5299,
"text": "Result − The above script returns the deviation value as 31.622776601683793."
},
{
"code": null,
"e": 5538,
"s": 5376,
"text": "Example − Let us perform all the Array API methods discussed above using the following script. Create a webpage “array.html” and add the following changes to it."
},
{
"code": null,
"e": 6095,
"s": 5538,
"text": "<html>\n <head>\n <script type = \"text/javascript\" src = \"https://d3js.org/d3.v4.min.js\"></script>\n </head>\n\n <body>\n <h3>D3 array API</h3>\n <script>\n var data = [20,40,60,80,100];\n console.log(d3.min(data)); \n console.log(d3.max(data));\n console.log(d3.extent(data));\n console.log(d3.sum(data));\n console.log(d3.mean(data));\n console.log(d3.quantile(data,0.5));\n console.log(d3.variance(data));\n console.log(d3.deviation(data));\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 6160,
"s": 6095,
"text": "Now, request the browser and we will see the following response."
},
{
"code": null,
"e": 6222,
"s": 6160,
"text": "Following are a couple of important Array search API methods."
},
{
"code": null,
"e": 6237,
"s": 6222,
"text": "d3.scan(array)"
},
{
"code": null,
"e": 6256,
"s": 6237,
"text": "d3.ascending(a, b)"
},
{
"code": null,
"e": 6299,
"s": 6256,
"text": "Let us understand both of these in detail."
},
{
"code": null,
"e": 6474,
"s": 6299,
"text": "This method is used to perform a linear scan of the specified array. It returns the index of the least element to the specified comparator. A simple example is defined below."
},
{
"code": null,
"e": 6484,
"s": 6474,
"text": "Example −"
},
{
"code": null,
"e": 6691,
"s": 6484,
"text": "var array = [{one: 1}, {one: 10}];\nconsole.log(d3.scan(array, function(a, b) { return a.one - b.one; })); // output is 0\nconsole.log(d3.scan(array, function(a, b) { return b.one - a.one; })); // output is 1"
},
{
"code": null,
"e": 6774,
"s": 6691,
"text": "This method is used to perform the comparator function. It can be implemented as −"
},
{
"code": null,
"e": 6858,
"s": 6774,
"text": "function ascending(a, b) {\n return a < b ? -1 : a > b ? 1 : a > = b ? 0 : NaN;\n}"
},
{
"code": null,
"e": 7049,
"s": 6858,
"text": "If no comparator function is specified to the built-in sort method, the default order is alphabetical. The above function returns -1, if a is less than b, or 1, if a is greater than b, or 0."
},
{
"code": null,
"e": 7219,
"s": 7049,
"text": "Similarly, you can perform descending(a, b) method. It returns -1, if a is greater than b, or 1, if a is less than b, or 0. This function performs reverse natural order."
},
{
"code": null,
"e": 7229,
"s": 7219,
"text": "Example −"
},
{
"code": null,
"e": 7301,
"s": 7229,
"text": "Create a webpage array_search.html and add the following changes to it."
},
{
"code": null,
"e": 7719,
"s": 7301,
"text": "<html>\n <head>\n <script type = \"text/javascript\" src = \"https://d3js.org/d3.v4.min.js\"></script>\n </head>\n\n <body>\n <h3>D3 array API</h3>\n <script>\n var array = [{one: 1}, {one: 10}];\n console.log(d3.scan(array, function(a, b) { return a.one - b.one; })); // 0\n console.log(d3.scan(array, function(a, b) { return b.one - a.one; })); // 1\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 7782,
"s": 7719,
"text": "Now, request the browser and we will see the following result."
},
{
"code": null,
"e": 7858,
"s": 7782,
"text": "Following are some of the most prominent array transformations API methods."
},
{
"code": null,
"e": 7884,
"s": 7858,
"text": "d3.cross(a, b[, reducer])"
},
{
"code": null,
"e": 7901,
"s": 7884,
"text": "d3.merge(arrays)"
},
{
"code": null,
"e": 7928,
"s": 7901,
"text": "d3.pairs(array[, reducer])"
},
{
"code": null,
"e": 7955,
"s": 7928,
"text": "d3.permute(array, indexes)"
},
{
"code": null,
"e": 7970,
"s": 7955,
"text": "d3.zip(arrays)"
},
{
"code": null,
"e": 8013,
"s": 7970,
"text": "Let us understand each of these in detail."
},
{
"code": null,
"e": 8133,
"s": 8013,
"text": "This method is used to return the Cartesian product of the given two arrays a and b. A simple example is defined below."
},
{
"code": null,
"e": 8223,
"s": 8133,
"text": "d3.cross([10, 20], [\"a\", \"b\"]); // output is [[10, \"a\"], [10, \"b\"], [20, \"a\"], [20, \"b\"]]"
},
{
"code": null,
"e": 8288,
"s": 8223,
"text": "This method is used to merge the arrays and it is defined below."
},
{
"code": null,
"e": 8334,
"s": 8288,
"text": "d3.merge([[10], [20]]); // output is [10, 20]"
},
{
"code": null,
"e": 8399,
"s": 8334,
"text": "This method is used to pair array elements and is defined below."
},
{
"code": null,
"e": 8471,
"s": 8399,
"text": "d3.pairs([10, 20, 30, 40]); // output is [[10, 20], [20, 30], [30, 40]]"
},
{
"code": null,
"e": 8637,
"s": 8471,
"text": "This method is used to perform the permutation from specified array and indexes. You can also perform the values from an object into an array. It is explained below."
},
{
"code": null,
"e": 8774,
"s": 8637,
"text": "var object = {fruit:\"mango\", color: \"yellow\"},\n fields = [\"fruit\", \"color\"];\nd3.permute(object, fields); // output is \"mango\" \"yellow\""
},
{
"code": null,
"e": 8995,
"s": 8774,
"text": "This method is used to return an array of arrays. If arrays contain only a single array, the returned array contains one-element arrays. If no argument is specified, then the returned array is empty. It is defined below."
},
{
"code": null,
"e": 9057,
"s": 8995,
"text": "d3.zip([10, 20], [30, 40]); // output is [[10, 30], [20, 40]]"
},
{
"code": null,
"e": 9137,
"s": 9057,
"text": "Example − Create a webpage array_transform and add the following changes to it."
},
{
"code": null,
"e": 9686,
"s": 9137,
"text": "<html>\n <head>\n <script type = \"text/javascript\" src = \"https://d3js.org/d3.v4.min.js\"></script>\n </head>\n\n <body>\n <h3>D3 array API</h3>\n <script>\n console.log(d3.cross([10, 20], [\"a\", \"b\"]));\n console.log(d3.merge([[10], [30]]));\n console.log(d3.pairs([10, 20, 30, 40]));\n var object = {fruit:\"mango\", color: \"yellow\"},\n fields = [\"fruit\", \"color\"];\n console.log(d3.permute(object, fields)); \n console.log(d3.zip([10, 20], [30, 40]));\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 9751,
"s": 9686,
"text": "Now, request the browser and we will see the following response."
},
{
"code": null,
"e": 9758,
"s": 9751,
"text": " Print"
},
{
"code": null,
"e": 9769,
"s": 9758,
"text": " Add Notes"
}
] |
Creating a C++ reusable Header File and its Implementation Files - GeeksforGeeks
|
08 Oct, 2021
Reusability is one of the most important concepts of Software Engineering. Reusability means developing code that can be reused either in the same program or in different programs. C++ allows reusability through inheritance, containership, polymorphism, and genericity. But, there is another way to define independent building blocks. This can be achieved by creating header files and implementation files.
Header files are the files that include the class declaration. The name of the class is generally the same as that of the header file. (For example, a LinkedList class will be stored inside a LinkedList.h header file)
On the other hand, the implementation file consists of the function definition of the class which was defined inside the header file. Generally, the file name is the name of the class, with a .cpp extension. (For example, a LinkedList class’s function definition will be stored inside a LinkedList.cpp header file)
Now, to create an object of the class, defined in the above header file, there must be a main() function. But wait, where to define a main() function, particularly, which file?The main function is defined inside another file, known as the driver file, or, in some cases, the client file.
Example: Here, complexNum class is implemented. It is split up into two files. The header file has the extension.h and contains the class definitions.
Header File:
C++
// Header file complexNum.h#ifndef COMPLEXNUM_H#define COMPLEXNUM_H class complexNum {private: int real; int imaginary; public: // With default value, // default constructor complexNum(const int a = 0, const int b = 0); // setter function void setNum(const int a, const int b); // Prints the complex number // in the form real + i(imaginary), // i->iota void print() const; // An overloaded operator to compare // two complex number objects bool operator==(const complexNum&);};#endif
Implementation File:
C++
// Implementation file// complexNum.cpp#include "complexNum.h"#include <iostream>using namespace std; // A default constructorcomplexNum::complexNum(int a, int b){ real = a; imaginary = b;} // A function to set valuesvoid complexNum::setNum(const int a, const int b){ real = a; imaginary = b;} // A function to print the complex// number in the form real +// (imaginary)i, i->iotavoid complexNum::print() const{ cout << real << " + " << imaginary << "i" << endl;} // An overloaded operator to// compare two complex Number// objectsbool complexNum::operator==(const complexNum& obj){ if (this->real == obj.real && this->imaginary == obj.imaginary) { return true; } return false;}
Now to check for correctness and to implement the above complexNum class, there is a need for a driver file. Below is the driver file:
C++
// Driver file to illustrate// the implementation of// complexNum.cpp file#include "complexNum.h"#include <iostream>using namespace std; // Driver codeint main(){ // Defines a complex number // object (obj1 = 4 + 5i) complexNum obj1(4, 5); complexNum obj2; // Defines a complex number // object (obj2 = 3 + 4i) obj2.setNum(3, 4); // Prints the complex number obj1.print(); obj2.print(); // Checks, if two complex // number objects are equal or // not if (obj1 == obj2) { cout << "Both the numbers are equal" << endl; } else { cout << "Numbers are not equal" << endl; } return 0;}
Output:
Note:The header, implementation as well as driver files should be in the same folder. Otherwise, provide the link of the present working directory in the include statements.
Header files are already used by programmers, which are very useful, and become handy while implementing various data structures and algorithms. For example, dynamic arrays can be implemented using <vector> header file.
Advantages Of Storing Class Definition In Different Files:
Inheritance can be used to achieve code reusability, but the drawback of it is that a class has to be inherited from a class inside the same file. One cannot inherit a class from a different file.But, this issue is resolved by using the header and implementation files, hence making the class reusable.If the class implementation doesn’t change, then there is no need to recompile it.
Inheritance can be used to achieve code reusability, but the drawback of it is that a class has to be inherited from a class inside the same file. One cannot inherit a class from a different file.
But, this issue is resolved by using the header and implementation files, hence making the class reusable.
If the class implementation doesn’t change, then there is no need to recompile it.
singghakshay
CPP-Basics
C++
C++ Programs
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Sorting a vector in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
Header files in C/C++ and its uses
How to return multiple values from a function in C or C++?
C++ Program for QuickSort
Program to print ASCII Value of a character
Sorting a Map by value in C++ STL
|
[
{
"code": null,
"e": 24124,
"s": 24096,
"text": "\n08 Oct, 2021"
},
{
"code": null,
"e": 24532,
"s": 24124,
"text": "Reusability is one of the most important concepts of Software Engineering. Reusability means developing code that can be reused either in the same program or in different programs. C++ allows reusability through inheritance, containership, polymorphism, and genericity. But, there is another way to define independent building blocks. This can be achieved by creating header files and implementation files. "
},
{
"code": null,
"e": 24750,
"s": 24532,
"text": "Header files are the files that include the class declaration. The name of the class is generally the same as that of the header file. (For example, a LinkedList class will be stored inside a LinkedList.h header file)"
},
{
"code": null,
"e": 25065,
"s": 24750,
"text": "On the other hand, the implementation file consists of the function definition of the class which was defined inside the header file. Generally, the file name is the name of the class, with a .cpp extension. (For example, a LinkedList class’s function definition will be stored inside a LinkedList.cpp header file)"
},
{
"code": null,
"e": 25353,
"s": 25065,
"text": "Now, to create an object of the class, defined in the above header file, there must be a main() function. But wait, where to define a main() function, particularly, which file?The main function is defined inside another file, known as the driver file, or, in some cases, the client file."
},
{
"code": null,
"e": 25504,
"s": 25353,
"text": "Example: Here, complexNum class is implemented. It is split up into two files. The header file has the extension.h and contains the class definitions."
},
{
"code": null,
"e": 25517,
"s": 25504,
"text": "Header File:"
},
{
"code": null,
"e": 25521,
"s": 25517,
"text": "C++"
},
{
"code": "// Header file complexNum.h#ifndef COMPLEXNUM_H#define COMPLEXNUM_H class complexNum {private: int real; int imaginary; public: // With default value, // default constructor complexNum(const int a = 0, const int b = 0); // setter function void setNum(const int a, const int b); // Prints the complex number // in the form real + i(imaginary), // i->iota void print() const; // An overloaded operator to compare // two complex number objects bool operator==(const complexNum&);};#endif",
"e": 26080,
"s": 25521,
"text": null
},
{
"code": null,
"e": 26103,
"s": 26082,
"text": "Implementation File:"
},
{
"code": null,
"e": 26107,
"s": 26103,
"text": "C++"
},
{
"code": "// Implementation file// complexNum.cpp#include \"complexNum.h\"#include <iostream>using namespace std; // A default constructorcomplexNum::complexNum(int a, int b){ real = a; imaginary = b;} // A function to set valuesvoid complexNum::setNum(const int a, const int b){ real = a; imaginary = b;} // A function to print the complex// number in the form real +// (imaginary)i, i->iotavoid complexNum::print() const{ cout << real << \" + \" << imaginary << \"i\" << endl;} // An overloaded operator to// compare two complex Number// objectsbool complexNum::operator==(const complexNum& obj){ if (this->real == obj.real && this->imaginary == obj.imaginary) { return true; } return false;}",
"e": 26862,
"s": 26107,
"text": null
},
{
"code": null,
"e": 26997,
"s": 26862,
"text": "Now to check for correctness and to implement the above complexNum class, there is a need for a driver file. Below is the driver file:"
},
{
"code": null,
"e": 27001,
"s": 26997,
"text": "C++"
},
{
"code": "// Driver file to illustrate// the implementation of// complexNum.cpp file#include \"complexNum.h\"#include <iostream>using namespace std; // Driver codeint main(){ // Defines a complex number // object (obj1 = 4 + 5i) complexNum obj1(4, 5); complexNum obj2; // Defines a complex number // object (obj2 = 3 + 4i) obj2.setNum(3, 4); // Prints the complex number obj1.print(); obj2.print(); // Checks, if two complex // number objects are equal or // not if (obj1 == obj2) { cout << \"Both the numbers are equal\" << endl; } else { cout << \"Numbers are not equal\" << endl; } return 0;}",
"e": 27652,
"s": 27001,
"text": null
},
{
"code": null,
"e": 27661,
"s": 27652,
"text": "Output: "
},
{
"code": null,
"e": 27836,
"s": 27661,
"text": " Note:The header, implementation as well as driver files should be in the same folder. Otherwise, provide the link of the present working directory in the include statements."
},
{
"code": null,
"e": 28057,
"s": 27836,
"text": "Header files are already used by programmers, which are very useful, and become handy while implementing various data structures and algorithms. For example, dynamic arrays can be implemented using <vector> header file. "
},
{
"code": null,
"e": 28116,
"s": 28057,
"text": "Advantages Of Storing Class Definition In Different Files:"
},
{
"code": null,
"e": 28501,
"s": 28116,
"text": "Inheritance can be used to achieve code reusability, but the drawback of it is that a class has to be inherited from a class inside the same file. One cannot inherit a class from a different file.But, this issue is resolved by using the header and implementation files, hence making the class reusable.If the class implementation doesn’t change, then there is no need to recompile it."
},
{
"code": null,
"e": 28698,
"s": 28501,
"text": "Inheritance can be used to achieve code reusability, but the drawback of it is that a class has to be inherited from a class inside the same file. One cannot inherit a class from a different file."
},
{
"code": null,
"e": 28805,
"s": 28698,
"text": "But, this issue is resolved by using the header and implementation files, hence making the class reusable."
},
{
"code": null,
"e": 28888,
"s": 28805,
"text": "If the class implementation doesn’t change, then there is no need to recompile it."
},
{
"code": null,
"e": 28901,
"s": 28888,
"text": "singghakshay"
},
{
"code": null,
"e": 28912,
"s": 28901,
"text": "CPP-Basics"
},
{
"code": null,
"e": 28916,
"s": 28912,
"text": "C++"
},
{
"code": null,
"e": 28929,
"s": 28916,
"text": "C++ Programs"
},
{
"code": null,
"e": 28933,
"s": 28929,
"text": "CPP"
},
{
"code": null,
"e": 29031,
"s": 28933,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29059,
"s": 29031,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 29079,
"s": 29059,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 29103,
"s": 29079,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 29136,
"s": 29103,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 29180,
"s": 29136,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 29215,
"s": 29180,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 29274,
"s": 29215,
"text": "How to return multiple values from a function in C or C++?"
},
{
"code": null,
"e": 29300,
"s": 29274,
"text": "C++ Program for QuickSort"
},
{
"code": null,
"e": 29344,
"s": 29300,
"text": "Program to print ASCII Value of a character"
}
] |
How to get a list of installed Android applications in Kotlin?
|
This example demonstrates how to get a list of installed Android applications in Kotlin.
Step 1 − Create a new project in Android Studio, go to File ? New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="4dp"
tools:context=".MainActivity">
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.content.pm.ApplicationInfo
import android.os.Bundle
import android.util.Log
import android.widget.ArrayAdapter
import android.widget.ListView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
lateinit var listView: ListView
var arrayAdapter: ArrayAdapter<*>? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
listView = findViewById(R.id.listView)
installedApps()
}
private fun installedApps() {
val list = packageManager.getInstalledPackages(0)
for (i in list.indices) {
val packageInfo = list[i]
if (packageInfo!!.applicationInfo.flags and ApplicationInfo.FLAG_SYSTEM == 0) {
val appName = packageInfo.applicationInfo.loadLabel(packageManager).toString()
Log.e("App List$i", appName)
arrayAdapter = ArrayAdapter(this,
R.layout.support_simple_spinner_dropdown_item, list as List)
listView.adapter = arrayAdapter
}
}
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.myapplication">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the 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": 1151,
"s": 1062,
"text": "This example demonstrates how to get a list of installed Android applications in Kotlin."
},
{
"code": null,
"e": 1280,
"s": 1151,
"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": 1345,
"s": 1280,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1796,
"s": 1345,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"4dp\"\n tools:context=\".MainActivity\">\n <ListView\n android:id=\"@+id/listView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 1851,
"s": 1796,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 2985,
"s": 1851,
"text": "import android.content.pm.ApplicationInfo\nimport android.os.Bundle\nimport android.util.Log\nimport android.widget.ArrayAdapter\nimport android.widget.ListView\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n lateinit var listView: ListView\n var arrayAdapter: ArrayAdapter<*>? = null\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n listView = findViewById(R.id.listView)\n installedApps()\n }\n private fun installedApps() {\n val list = packageManager.getInstalledPackages(0)\n for (i in list.indices) {\n val packageInfo = list[i]\n if (packageInfo!!.applicationInfo.flags and ApplicationInfo.FLAG_SYSTEM == 0) {\n val appName = packageInfo.applicationInfo.loadLabel(packageManager).toString()\n Log.e(\"App List$i\", appName)\n arrayAdapter = ArrayAdapter(this,\n R.layout.support_simple_spinner_dropdown_item, list as List)\n listView.adapter = arrayAdapter\n }\n }\n }\n}"
},
{
"code": null,
"e": 3040,
"s": 2985,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3717,
"s": 3040,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.myapplication\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 4065,
"s": 3717,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen"
}
] |
execute_script driver method - Selenium Python - GeeksforGeeks
|
15 May, 2020
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python.Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc.
This article revolves around execute_script driver method in Selenium. execute_script method synchronously Executes JavaScript in the current window/frame. This is a big feature of selenium, because javascript can do everything with a website from hitting APIs to playing with live code.
Syntax –
execute_script(script, *args)
Args –
script: The JavaScript to execute.
*args: Any applicable arguments for your JavaScript.
Example –Now one can use execute_script method as a driver method as below –
diver.get("https://www.geeksforgeeks.org/")
driver.execute_script("alert("alert via selenium")")
To demonstrate, execute_script method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object.
Program –
# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # write scriptscript = "alert('Alert via selenium')" # generate a alert via javascriptdriver.execute_script(script)
Output –Browser generates alert as verified below –
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
|
[
{
"code": null,
"e": 24810,
"s": 24782,
"text": "\n15 May, 2020"
},
{
"code": null,
"e": 25548,
"s": 24810,
"text": "Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python.Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc."
},
{
"code": null,
"e": 25836,
"s": 25548,
"text": "This article revolves around execute_script driver method in Selenium. execute_script method synchronously Executes JavaScript in the current window/frame. This is a big feature of selenium, because javascript can do everything with a website from hitting APIs to playing with live code."
},
{
"code": null,
"e": 25845,
"s": 25836,
"text": "Syntax –"
},
{
"code": null,
"e": 25875,
"s": 25845,
"text": "execute_script(script, *args)"
},
{
"code": null,
"e": 25882,
"s": 25875,
"text": "Args –"
},
{
"code": null,
"e": 25917,
"s": 25882,
"text": "script: The JavaScript to execute."
},
{
"code": null,
"e": 25970,
"s": 25917,
"text": "*args: Any applicable arguments for your JavaScript."
},
{
"code": null,
"e": 26047,
"s": 25970,
"text": "Example –Now one can use execute_script method as a driver method as below –"
},
{
"code": null,
"e": 26145,
"s": 26047,
"text": "diver.get(\"https://www.geeksforgeeks.org/\")\ndriver.execute_script(\"alert(\"alert via selenium\")\")\n"
},
{
"code": null,
"e": 26290,
"s": 26145,
"text": "To demonstrate, execute_script method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object."
},
{
"code": null,
"e": 26300,
"s": 26290,
"text": "Program –"
},
{
"code": "# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # write scriptscript = \"alert('Alert via selenium')\" # generate a alert via javascriptdriver.execute_script(script)",
"e": 26591,
"s": 26300,
"text": null
},
{
"code": null,
"e": 26643,
"s": 26591,
"text": "Output –Browser generates alert as verified below –"
},
{
"code": null,
"e": 26659,
"s": 26643,
"text": "Python-selenium"
},
{
"code": null,
"e": 26668,
"s": 26659,
"text": "selenium"
},
{
"code": null,
"e": 26675,
"s": 26668,
"text": "Python"
},
{
"code": null,
"e": 26773,
"s": 26675,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26791,
"s": 26773,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26826,
"s": 26791,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26848,
"s": 26826,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26880,
"s": 26848,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26910,
"s": 26880,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26952,
"s": 26910,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26978,
"s": 26952,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27015,
"s": 26978,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 27058,
"s": 27015,
"text": "Python program to convert a list to string"
}
] |
Android - Theme Demo Example
|
Following example demonstrates how you can use a theme for an application. For demo purpose we will modify our default AppTheme wehere default text, its size, family, shadow etc will be changed. Let's start with creating a simple Android application as per the following steps −
Following is the content of the modified main activity file src/com.example.themedemo/MainActivity.java. This file can include each of the fundamental lifecycle methods.
package com.example.themedemo;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//--- find both the buttons---
Button sButton = (Button) findViewById(R.id.button_s);
Button lButton = (Button) findViewById(R.id.button_l);
// -- register click event with first button ---
sButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// --- find the text view --
TextView txtView = (TextView) findViewById(R.id.text_id);
// -- change text size --
txtView.setTextSize(20);
}
});
// -- register click event with second button ---
lButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// --- find the text view --
TextView txtView = (TextView) findViewById(R.id.text_id);
// -- change text size --
txtView.setTextSize(24);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Following will be the content of res/values/style.xml file which will have addition style CustomButtonStyle defined −
<resources>
<!--
Base application theme, dependent on API level. This theme is replaced
by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
-->
<style name="AppBaseTheme" parent="android:Theme.Light">
<!--
Theme customizations available in newer API levels can go in
res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.
-->
</style>
<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<!-- All customizations that are NOT specific to a particular API-level can go here. -->
<item name="android:capitalize">characters</item>
<item name="android:typeface">monospace</item>
<item name="android:shadowDx">1.2</item>
<item name="android:shadowDy">1.2</item>
<item name="android:shadowRadius">2</item>
<item name="android:textColor">#494948</item>/>
<item name="android:gravity" >center</item>
<item name="android:layout_margin" >3dp</item>
<item name="android:textSize" >5pt</item>
<item name="android:shadowColor" >#000000</item>
</style>
<!-- Custom Style defined for the buttons. -->
<style name="CustomButtonStyle">
<item name="android:layout_width">100dp</item>
<item name="android:layout_height">38dp</item>
</style>
</resources>
Following will be the content of res/layout/activity_main.xml file −
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/button_s"
style="@style/CustomButtonStyle"
android:text="@string/button_small"
android:onClick="doSmall"/>
<Button
android:id="@+id/button_l"
style="@style/CustomButtonStyle"
android:text="@string/button_large"
android:onClick="doLarge"/>
<TextView
android:id="@+id/text_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:capitalize="characters"
android:text="@string/hello_world" />
</LinearLayout>
Following will be the content of res/values/strings.xml to define two new constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">ThemeDemo</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="button_small">Small Font</string>
<string name="button_large">Large Font</string>
</resources>
Following is the default content of AndroidManifest.xml. Here we do not need to change anything because we kept out theme name unchanged. But if you define fresh new theme or inherit a default them with different name then you will have to replace AppTheme name with the new them name.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.guidemo"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.guidemo.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your ThemeDemo application. I assume you had created your AVD while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −
46 Lectures
7.5 hours
Aditya Dua
32 Lectures
3.5 hours
Sharad Kumar
9 Lectures
1 hours
Abhilash Nelson
14 Lectures
1.5 hours
Abhilash Nelson
15 Lectures
1.5 hours
Abhilash Nelson
10 Lectures
1 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3886,
"s": 3607,
"text": "Following example demonstrates how you can use a theme for an application. For demo purpose we will modify our default AppTheme wehere default text, its size, family, shadow etc will be changed. Let's start with creating a simple Android application as per the following steps −"
},
{
"code": null,
"e": 4056,
"s": 3886,
"text": "Following is the content of the modified main activity file src/com.example.themedemo/MainActivity.java. This file can include each of the fundamental lifecycle methods."
},
{
"code": null,
"e": 5544,
"s": 4056,
"text": "package com.example.themedemo;\n\nimport android.os.Bundle;\nimport android.app.Activity;\nimport android.view.Menu;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.TextView;\n\npublic class MainActivity extends Activity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n \n //--- find both the buttons---\n Button sButton = (Button) findViewById(R.id.button_s);\n Button lButton = (Button) findViewById(R.id.button_l);\n \n // -- register click event with first button ---\n sButton.setOnClickListener(new View.OnClickListener() {\n public void onClick(View v) {\n // --- find the text view --\n TextView txtView = (TextView) findViewById(R.id.text_id);\n \n // -- change text size --\n txtView.setTextSize(20);\n }\n });\n \n // -- register click event with second button ---\n lButton.setOnClickListener(new View.OnClickListener() {\n public void onClick(View v) {\n // --- find the text view --\n TextView txtView = (TextView) findViewById(R.id.text_id);\n \n // -- change text size --\n txtView.setTextSize(24);\n }\n });\n }\n \n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n getMenuInflater().inflate(R.menu.main, menu);\n return true;\n }\n}"
},
{
"code": null,
"e": 5662,
"s": 5544,
"text": "Following will be the content of res/values/style.xml file which will have addition style CustomButtonStyle defined −"
},
{
"code": null,
"e": 7039,
"s": 5662,
"text": "<resources>\n\n <!--\n Base application theme, dependent on API level. This theme is replaced\n by AppBaseTheme from res/values-vXX/styles.xml on newer devices.\n -->\n\t\n <style name=\"AppBaseTheme\" parent=\"android:Theme.Light\">\n <!--\n Theme customizations available in newer API levels can go in\n res/values-vXX/styles.xml, while customizations related to\n backward-compatibility can go here.\n -->\n </style>\n\n <!-- Application theme. -->\n <style name=\"AppTheme\" parent=\"AppBaseTheme\">\n <!-- All customizations that are NOT specific to a particular API-level can go here. -->\n <item name=\"android:capitalize\">characters</item>\n <item name=\"android:typeface\">monospace</item>\n <item name=\"android:shadowDx\">1.2</item>\n <item name=\"android:shadowDy\">1.2</item>\n <item name=\"android:shadowRadius\">2</item>\n <item name=\"android:textColor\">#494948</item>/> \n <item name=\"android:gravity\" >center</item>\n <item name=\"android:layout_margin\" >3dp</item>\n <item name=\"android:textSize\" >5pt</item>\n <item name=\"android:shadowColor\" >#000000</item>\n </style>\n \n <!-- Custom Style defined for the buttons. -->\n <style name=\"CustomButtonStyle\">\n <item name=\"android:layout_width\">100dp</item>\n <item name=\"android:layout_height\">38dp</item>\n </style>\n\n</resources>"
},
{
"code": null,
"e": 7108,
"s": 7039,
"text": "Following will be the content of res/layout/activity_main.xml file −"
},
{
"code": null,
"e": 7889,
"s": 7108,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"fill_parent\"\n android:layout_height=\"fill_parent\"\n android:orientation=\"vertical\" >\n\n <Button \n android:id=\"@+id/button_s\"\n style=\"@style/CustomButtonStyle\"\n android:text=\"@string/button_small\"\n android:onClick=\"doSmall\"/>\n \n <Button \n android:id=\"@+id/button_l\"\n style=\"@style/CustomButtonStyle\"\n android:text=\"@string/button_large\"\n android:onClick=\"doLarge\"/>\n\n <TextView\n android:id=\"@+id/text_id\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:capitalize=\"characters\"\n android:text=\"@string/hello_world\" />\n\n</LinearLayout>"
},
{
"code": null,
"e": 7975,
"s": 7889,
"text": "Following will be the content of res/values/strings.xml to define two new constants −"
},
{
"code": null,
"e": 8291,
"s": 7975,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n <string name=\"app_name\">ThemeDemo</string>\n <string name=\"action_settings\">Settings</string>\n <string name=\"hello_world\">Hello world!</string>\n <string name=\"button_small\">Small Font</string>\n <string name=\"button_large\">Large Font</string>\n</resources>"
},
{
"code": null,
"e": 8577,
"s": 8291,
"text": "Following is the default content of AndroidManifest.xml. Here we do not need to change anything because we kept out theme name unchanged. But if you define fresh new theme or inherit a default them with different name then you will have to replace AppTheme name with the new them name."
},
{
"code": null,
"e": 9433,
"s": 8577,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.guidemo\"\n android:versionCode=\"1\"\n android:versionName=\"1.0\" >\n \n <uses-sdk\n android:minSdkVersion=\"8\"\n android:targetSdkVersion=\"17\" />\n \n <application\n android:allowBackup=\"true\"\n android:icon=\"@drawable/ic_launcher\"\n android:label=\"@string/app_name\"\n android:theme=\"@style/AppTheme\" >\n \n <activity\n android:name=\"com.example.guidemo.MainActivity\"\n android:label=\"@string/app_name\" >\n \n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n \n </activity>\n \n </application>\n</manifest>"
},
{
"code": null,
"e": 9806,
"s": 9433,
"text": "Let's try to run your ThemeDemo application. I assume you had created your AVD while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −"
},
{
"code": null,
"e": 9841,
"s": 9806,
"text": "\n 46 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 9853,
"s": 9841,
"text": " Aditya Dua"
},
{
"code": null,
"e": 9888,
"s": 9853,
"text": "\n 32 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 9902,
"s": 9888,
"text": " Sharad Kumar"
},
{
"code": null,
"e": 9934,
"s": 9902,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 9951,
"s": 9934,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 9986,
"s": 9951,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 10003,
"s": 9986,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 10038,
"s": 10003,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 10055,
"s": 10038,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 10088,
"s": 10055,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 10105,
"s": 10088,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 10112,
"s": 10105,
"text": " Print"
},
{
"code": null,
"e": 10123,
"s": 10112,
"text": " Add Notes"
}
] |
[FIXED] Use -enable-preview to enable text blocks - onlinetutorialspoint
|
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
This article shows you how to enable preview feature in Java.
To enable the preview feature, make sure you are using java 12 or later version. Even if you are using Java 12 or above versions you might get “Use --enable-preview to enable text blocks” error because the text blocks and preview feature are disabled by default. We have to enable them manually.
In intellij goto File->Project Structure-> Project and makesure the below selected items
# compiling
javac --release 14 --enable-preview Demo.java // Enable all preview features of JDK 12
#Run
java --enable-preview Demo // Run with preview features of JDK 14
Add the below maven plugin in pom.xml to enable-preview
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<release>14</release>
<compilerArgs>
--enable-preview
</compilerArgs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M3</version>
<configuration>
<argLine>--enable-preview</argLine>
</configuration>
</plugin>
</plugins>
</build>
For gradle you need to configure the javaCompile task, so that Gradle passes this option to the Java compiler when compiling the java classes. Add the below code in build.gradle file
tasks.withType(JavaCompile).each {
it.options.compilerArgs.add('--enable-preview')
}
test {
jvmArgs(['--enable-preview'])
}
Preview Language
Java 13 Text Blocks
Happy Learning 🙂
Java 13 Text Blocks – Formatting String in Java 13
How to install Gradle on Windows 10
STS Gradle Setup Tutorials
Simple Spring Boot Example
How to read a text file in Python ?
Python Conditional Statements
JAXB XML to Java Object Conversion Example
JAXB Java Object to XML Conversion Example
Spring Boot Actuator Example
Spring Boot FileUpload Ajax Example
How to Configure Spring Profile in Tomcat ?
How to Enable Spring Boot CORS Example – @CrossOrigin
How to enable Swagger in Spring Boot Application
Step By Step Spring Boot Docker Deployment Example
How to add OJDBC jar to Maven Repository
Java 13 Text Blocks – Formatting String in Java 13
How to install Gradle on Windows 10
STS Gradle Setup Tutorials
Simple Spring Boot Example
How to read a text file in Python ?
Python Conditional Statements
JAXB XML to Java Object Conversion Example
JAXB Java Object to XML Conversion Example
Spring Boot Actuator Example
Spring Boot FileUpload Ajax Example
How to Configure Spring Profile in Tomcat ?
How to Enable Spring Boot CORS Example – @CrossOrigin
How to enable Swagger in Spring Boot Application
Step By Step Spring Boot Docker Deployment Example
How to add OJDBC jar to Maven Repository
Δ
Install Java on Mac OS
Install AWS CLI on Windows
Install Minikube on Windows
Install Docker Toolbox on Windows
Install SOAPUI on Windows
Install Gradle on Windows
Install RabbitMQ on Windows
Install PuTTY on windows
Install Mysql on Windows
Install Hibernate Tools in Eclipse
Install Elasticsearch on Windows
Install Maven on Windows
Install Maven on Ubuntu
Install Maven on Windows Command
Add OJDBC jar to Maven Repository
Install Ant on Windows
Install RabbitMQ on Windows
Install Apache Kafka on Ubuntu
Install Apache Kafka on Windows
Java8 – Install Windows
Java8 – foreach
Java8 – forEach with index
Java8 – Stream Filter Objects
Java8 – Comparator Userdefined
Java8 – GroupingBy
Java8 – SummingInt
Java8 – walk ReadFiles
Java8 – JAVA_HOME on Windows
Howto – Install Java on Mac OS
Howto – Convert Iterable to Stream
Howto – Get common elements from two Lists
Howto – Convert List to String
Howto – Concatenate Arrays using Stream
Howto – Remove duplicates from List
Howto – Filter null values from Stream
Howto – Convert List to Map
Howto – Convert Stream to List
Howto – Sort a Map
Howto – Filter a Map
Howto – Get Current UTC Time
Howto – Verify an Array contains a specific value
Howto – Convert ArrayList to Array
Howto – Read File Line By Line
Howto – Convert Date to LocalDate
Howto – Merge Streams
Howto – Resolve NullPointerException in toMap
Howto -Get Stream count
Howto – Get Min and Max values in a Stream
Howto – Convert InputStream to String
|
[
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
"text": "C Tutorials"
},
{
"code": null,
"e": 199,
"s": 195,
"text": "aws"
},
{
"code": null,
"e": 234,
"s": 199,
"text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "EXCEPTIONS"
},
{
"code": null,
"e": 257,
"s": 245,
"text": "COLLECTIONS"
},
{
"code": null,
"e": 263,
"s": 257,
"text": "SWING"
},
{
"code": null,
"e": 268,
"s": 263,
"text": "JDBC"
},
{
"code": null,
"e": 275,
"s": 268,
"text": "JAVA 8"
},
{
"code": null,
"e": 282,
"s": 275,
"text": "SPRING"
},
{
"code": null,
"e": 294,
"s": 282,
"text": "SPRING BOOT"
},
{
"code": null,
"e": 304,
"s": 294,
"text": "HIBERNATE"
},
{
"code": null,
"e": 311,
"s": 304,
"text": "PYTHON"
},
{
"code": null,
"e": 315,
"s": 311,
"text": "PHP"
},
{
"code": null,
"e": 322,
"s": 315,
"text": "JQUERY"
},
{
"code": null,
"e": 357,
"s": 322,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 371,
"s": 357,
"text": "Java Examples"
},
{
"code": null,
"e": 382,
"s": 371,
"text": "C Examples"
},
{
"code": null,
"e": 394,
"s": 382,
"text": "C Tutorials"
},
{
"code": null,
"e": 398,
"s": 394,
"text": "aws"
},
{
"code": null,
"e": 460,
"s": 398,
"text": "This article shows you how to enable preview feature in Java."
},
{
"code": null,
"e": 756,
"s": 460,
"text": "To enable the preview feature, make sure you are using java 12 or later version. Even if you are using Java 12 or above versions you might get “Use --enable-preview to enable text blocks” error because the text blocks and preview feature are disabled by default. We have to enable them manually."
},
{
"code": null,
"e": 845,
"s": 756,
"text": "In intellij goto File->Project Structure-> Project and makesure the below selected items"
},
{
"code": null,
"e": 1022,
"s": 845,
"text": "# compiling\njavac --release 14 --enable-preview Demo.java // Enable all preview features of JDK 12\n\n#Run\njava --enable-preview Demo // Run with preview features of JDK 14"
},
{
"code": null,
"e": 1078,
"s": 1022,
"text": "Add the below maven plugin in pom.xml to enable-preview"
},
{
"code": null,
"e": 1683,
"s": 1078,
"text": "<build>\n <plugins>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-compiler-plugin</artifactId>\n <version>3.8.0</version>\n <configuration>\n <release>14</release>\n <compilerArgs>\n --enable-preview\n </compilerArgs>\n </configuration>\n </plugin>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-surefire-plugin</artifactId>\n <version>3.0.0-M3</version>\n <configuration>\n <argLine>--enable-preview</argLine>\n </configuration>\n </plugin>\n </plugins>\n</build>"
},
{
"code": null,
"e": 1866,
"s": 1683,
"text": "For gradle you need to configure the javaCompile task, so that Gradle passes this option to the Java compiler when compiling the java classes. Add the below code in build.gradle file"
},
{
"code": null,
"e": 1998,
"s": 1866,
"text": "tasks.withType(JavaCompile).each {\n it.options.compilerArgs.add('--enable-preview')\n}\ntest {\n jvmArgs(['--enable-preview'])\n}"
},
{
"code": null,
"e": 2015,
"s": 1998,
"text": "Preview Language"
},
{
"code": null,
"e": 2035,
"s": 2015,
"text": "Java 13 Text Blocks"
},
{
"code": null,
"e": 2052,
"s": 2035,
"text": "Happy Learning 🙂"
},
{
"code": null,
"e": 2651,
"s": 2052,
"text": "\nJava 13 Text Blocks – Formatting String in Java 13\nHow to install Gradle on Windows 10\nSTS Gradle Setup Tutorials\nSimple Spring Boot Example\nHow to read a text file in Python ?\nPython Conditional Statements\nJAXB XML to Java Object Conversion Example\nJAXB Java Object to XML Conversion Example\nSpring Boot Actuator Example\nSpring Boot FileUpload Ajax Example\nHow to Configure Spring Profile in Tomcat ?\nHow to Enable Spring Boot CORS Example – @CrossOrigin\nHow to enable Swagger in Spring Boot Application\nStep By Step Spring Boot Docker Deployment Example\nHow to add OJDBC jar to Maven Repository\n"
},
{
"code": null,
"e": 2702,
"s": 2651,
"text": "Java 13 Text Blocks – Formatting String in Java 13"
},
{
"code": null,
"e": 2738,
"s": 2702,
"text": "How to install Gradle on Windows 10"
},
{
"code": null,
"e": 2765,
"s": 2738,
"text": "STS Gradle Setup Tutorials"
},
{
"code": null,
"e": 2792,
"s": 2765,
"text": "Simple Spring Boot Example"
},
{
"code": null,
"e": 2828,
"s": 2792,
"text": "How to read a text file in Python ?"
},
{
"code": null,
"e": 2858,
"s": 2828,
"text": "Python Conditional Statements"
},
{
"code": null,
"e": 2901,
"s": 2858,
"text": "JAXB XML to Java Object Conversion Example"
},
{
"code": null,
"e": 2944,
"s": 2901,
"text": "JAXB Java Object to XML Conversion Example"
},
{
"code": null,
"e": 2973,
"s": 2944,
"text": "Spring Boot Actuator Example"
},
{
"code": null,
"e": 3009,
"s": 2973,
"text": "Spring Boot FileUpload Ajax Example"
},
{
"code": null,
"e": 3053,
"s": 3009,
"text": "How to Configure Spring Profile in Tomcat ?"
},
{
"code": null,
"e": 3107,
"s": 3053,
"text": "How to Enable Spring Boot CORS Example – @CrossOrigin"
},
{
"code": null,
"e": 3156,
"s": 3107,
"text": "How to enable Swagger in Spring Boot Application"
},
{
"code": null,
"e": 3207,
"s": 3156,
"text": "Step By Step Spring Boot Docker Deployment Example"
},
{
"code": null,
"e": 3248,
"s": 3207,
"text": "How to add OJDBC jar to Maven Repository"
},
{
"code": null,
"e": 3254,
"s": 3252,
"text": "Δ"
},
{
"code": null,
"e": 3278,
"s": 3254,
"text": " Install Java on Mac OS"
},
{
"code": null,
"e": 3306,
"s": 3278,
"text": " Install AWS CLI on Windows"
},
{
"code": null,
"e": 3335,
"s": 3306,
"text": " Install Minikube on Windows"
},
{
"code": null,
"e": 3370,
"s": 3335,
"text": " Install Docker Toolbox on Windows"
},
{
"code": null,
"e": 3397,
"s": 3370,
"text": " Install SOAPUI on Windows"
},
{
"code": null,
"e": 3424,
"s": 3397,
"text": " Install Gradle on Windows"
},
{
"code": null,
"e": 3453,
"s": 3424,
"text": " Install RabbitMQ on Windows"
},
{
"code": null,
"e": 3479,
"s": 3453,
"text": " Install PuTTY on windows"
},
{
"code": null,
"e": 3505,
"s": 3479,
"text": " Install Mysql on Windows"
},
{
"code": null,
"e": 3541,
"s": 3505,
"text": " Install Hibernate Tools in Eclipse"
},
{
"code": null,
"e": 3575,
"s": 3541,
"text": " Install Elasticsearch on Windows"
},
{
"code": null,
"e": 3601,
"s": 3575,
"text": " Install Maven on Windows"
},
{
"code": null,
"e": 3626,
"s": 3601,
"text": " Install Maven on Ubuntu"
},
{
"code": null,
"e": 3660,
"s": 3626,
"text": " Install Maven on Windows Command"
},
{
"code": null,
"e": 3695,
"s": 3660,
"text": " Add OJDBC jar to Maven Repository"
},
{
"code": null,
"e": 3719,
"s": 3695,
"text": " Install Ant on Windows"
},
{
"code": null,
"e": 3748,
"s": 3719,
"text": " Install RabbitMQ on Windows"
},
{
"code": null,
"e": 3780,
"s": 3748,
"text": " Install Apache Kafka on Ubuntu"
},
{
"code": null,
"e": 3813,
"s": 3780,
"text": " Install Apache Kafka on Windows"
},
{
"code": null,
"e": 3838,
"s": 3813,
"text": " Java8 – Install Windows"
},
{
"code": null,
"e": 3855,
"s": 3838,
"text": " Java8 – foreach"
},
{
"code": null,
"e": 3883,
"s": 3855,
"text": " Java8 – forEach with index"
},
{
"code": null,
"e": 3914,
"s": 3883,
"text": " Java8 – Stream Filter Objects"
},
{
"code": null,
"e": 3946,
"s": 3914,
"text": " Java8 – Comparator Userdefined"
},
{
"code": null,
"e": 3966,
"s": 3946,
"text": " Java8 – GroupingBy"
},
{
"code": null,
"e": 3986,
"s": 3966,
"text": " Java8 – SummingInt"
},
{
"code": null,
"e": 4010,
"s": 3986,
"text": " Java8 – walk ReadFiles"
},
{
"code": null,
"e": 4040,
"s": 4010,
"text": " Java8 – JAVA_HOME on Windows"
},
{
"code": null,
"e": 4072,
"s": 4040,
"text": " Howto – Install Java on Mac OS"
},
{
"code": null,
"e": 4108,
"s": 4072,
"text": " Howto – Convert Iterable to Stream"
},
{
"code": null,
"e": 4152,
"s": 4108,
"text": " Howto – Get common elements from two Lists"
},
{
"code": null,
"e": 4184,
"s": 4152,
"text": " Howto – Convert List to String"
},
{
"code": null,
"e": 4225,
"s": 4184,
"text": " Howto – Concatenate Arrays using Stream"
},
{
"code": null,
"e": 4262,
"s": 4225,
"text": " Howto – Remove duplicates from List"
},
{
"code": null,
"e": 4302,
"s": 4262,
"text": " Howto – Filter null values from Stream"
},
{
"code": null,
"e": 4331,
"s": 4302,
"text": " Howto – Convert List to Map"
},
{
"code": null,
"e": 4363,
"s": 4331,
"text": " Howto – Convert Stream to List"
},
{
"code": null,
"e": 4383,
"s": 4363,
"text": " Howto – Sort a Map"
},
{
"code": null,
"e": 4405,
"s": 4383,
"text": " Howto – Filter a Map"
},
{
"code": null,
"e": 4435,
"s": 4405,
"text": " Howto – Get Current UTC Time"
},
{
"code": null,
"e": 4486,
"s": 4435,
"text": " Howto – Verify an Array contains a specific value"
},
{
"code": null,
"e": 4522,
"s": 4486,
"text": " Howto – Convert ArrayList to Array"
},
{
"code": null,
"e": 4554,
"s": 4522,
"text": " Howto – Read File Line By Line"
},
{
"code": null,
"e": 4589,
"s": 4554,
"text": " Howto – Convert Date to LocalDate"
},
{
"code": null,
"e": 4612,
"s": 4589,
"text": " Howto – Merge Streams"
},
{
"code": null,
"e": 4659,
"s": 4612,
"text": " Howto – Resolve NullPointerException in toMap"
},
{
"code": null,
"e": 4684,
"s": 4659,
"text": " Howto -Get Stream count"
},
{
"code": null,
"e": 4728,
"s": 4684,
"text": " Howto – Get Min and Max values in a Stream"
}
] |
AutoML for Time Series Forecasting | by Denis Vorotyntsev | Towards Data Science
|
Although I’m not a fan of nowadays AutoML, I enjoy participating in AutoML competitions. I believe that such competitions are a great learning opportunity and could give strong pipelines for future projects. AutoML competitions are something in between Kaggle-like competitions and LeetCode tasks: your code should give high scores, and it should be steady and fast.
Recently I took part in AutoSeries — AutoML competition on time-series data, in which I managed to get the first place among 40 competitors (15 in the finals). This post is an overview of my solution.
AutoSeries is one of the competitions of the Web Search and Data Mining (WSDM) conference. The competition is the 10th AutoML competition organized by 4Paradigm and ChaLearn. The previous ones were aimed to provide automated machine learning solutions for tabular data, computer vision, natural language processing, and speech recognition tasks. The full list of past challenges could be found on the official website of AutoML challenges.
This challenge aims at proposing automated solutions for the time series regression task. AutoSeries is restricted to multivariate regression problems, which come from different time series domains, including air quality, sales, work presence, city traffic, and other. Each dataset in the challenge is a tabular data whose features are of three main types: Id (could be multiple features or none), timestamp (each dataset has only one timestamp), other features (either numerical or categorical), and target to predict. The combination of Id features identifies a variable (a time series).
Participants have to submit code, which will be run in Docker container (CPU: 4 cores, 16 Gb RAM, no GPU). At first, the model is trained on full data, but during inference, it could be updated or retrained. The public leaderboard is calculated on five datasets, private — 5 new datasets without human intervention. The results of the private datasets determine the final ranking.
This section is devoted to the main parts of the final solution. The code of it is published here:
github.com
The solution consists of several steps. At first, common features are generated for time-series tasks. The number and types of these features are hyperparameters of the pipeline, which should be optimized for each task separately, but due to lack of computational time, I decided to generate the same features for all tasks and remove useless ones during the features selection stage.
The first batch of features are features based on the most critical numerical features. Numerical operations (addition, subtraction, multiplication, and division) of pairs of numerical features always improve the score of tree-based models because new features might reveal some hidden relations in the data.
Let’s take, for example, predicting the price of the apartment. The known information on the apartment’s floor (ap_floor) and the total number of floors (total_floors) in the building might be enriched by adding a new feature — relative_floor — which shows the relative position of the apartment’s floor in the building:
rel_floor = ap_floor / total_floors
This feature might help the model to understand that the third floor in row house (rel_floor is closer to 1) is not the same as the third in a skyscraper (rel_floor is closer to 0).
However, there are two significant problems with such features engineering strategy, if we perform numerical operations of all possible pairs: overfitting, which is especially vital in time-series tasks, and memory issues (16 RAM docker was used). To reduce the negative effect, a small subset of features is selected and used for pairs. It is done by fitting the whole dataset to a shallow LigtGBM model (10 trees). All used features are sorted by “gain” importance, i.e. a total sum of gains of splits that use the feature. Then top-n most important numerical features are selected for pairs.
The next batch of features is based on the time-series nature of the data: previous values and differences. I calculate the lagged values of target, most important numerical and categorical features, the difference between last value of the target (lag = 1), and lagged value of the target (lag > 1). These new features were among the most important ones.
The last batch is time-series features: year, month, day of the week, day of the year, and hour. I could add many more time-based features, such as a minute of the day, quartal of the year, and so on, but decided not to do that, so my solution would be universal. Treating these new features as categories sometimes improved scores, but in other cases, it significantly reduced it. I didn’t have enough computational time during inference for optimizing this hyperparameter (i.e., treating as numerical or categorical), so all of them are treated as numerical.
After generating new features, the baseline model is trained. The baseline model uses all initial and created features. It encodes categories with a CatBoost encoder and uses the target as-is. The model is trained in two steps:
At first, the data is split into the train and validation parts. Commonly, you want your train/validation/test split to emulate the usage of model in “production settings”. In the case of time series, that means that the model won’t be updated frequently, and you take 20–30% of data in the validation part (or use rolling window with the same proportions). In this competition, frequent updating of the model was possible, and thus, the validation part should be smaller: the validation part is 10% of the full training data. It is used for early stopping, i.e., to optimize the number of trees in boosting ensemble. After this step, the model could start making predictions, and all following steps are optional (bt crucial for a high score).The model is refit on full data using the optimal number of trees.
At first, the data is split into the train and validation parts. Commonly, you want your train/validation/test split to emulate the usage of model in “production settings”. In the case of time series, that means that the model won’t be updated frequently, and you take 20–30% of data in the validation part (or use rolling window with the same proportions). In this competition, frequent updating of the model was possible, and thus, the validation part should be smaller: the validation part is 10% of the full training data. It is used for early stopping, i.e., to optimize the number of trees in boosting ensemble. After this step, the model could start making predictions, and all following steps are optional (bt crucial for a high score).
The model is refit on full data using the optimal number of trees.
I used the solo LigthGBM model for making predictions. I tested CatBoost (too slow without GPU) and LinearModels (not accurate enough). I also tested bagging and training with different seeds to reduce the variance of the predictions, but these approaches took a lot of time and didn’t improve the scores enough to be included in the final solution.
I had too little time during inference for hyperparameters optimization, so I decided to narrow all possible hyperparameters combinations to the most promising ones, namely:
Treating categorical variables: treat categorical features as pandas category type and leave the headache to LightGBM or encode each category with CatBoost encoding (check my previous article on the encoding categories, if you haven’t’ read it yet).Target preprocessing: use target as is or calculate a new target for regression by differentiating: new_target(t)=target(t)-target(t-1). Differencing could help to overcome non-stationarity time series data. I also tested power transformation (taking root of target and Box-Cox) to reduce stationarity, but it didn’t improve the score enough to be included in the final solution.
Treating categorical variables: treat categorical features as pandas category type and leave the headache to LightGBM or encode each category with CatBoost encoding (check my previous article on the encoding categories, if you haven’t’ read it yet).
Target preprocessing: use target as is or calculate a new target for regression by differentiating: new_target(t)=target(t)-target(t-1). Differencing could help to overcome non-stationarity time series data. I also tested power transformation (taking root of target and Box-Cox) to reduce stationarity, but it didn’t improve the score enough to be included in the final solution.
towardsdatascience.com
Each set of parameters is first validated, and, if the new validation score is better — refit model. After selecting the best set of pipeline hyperparameters, the model starts feature selection: the model is refit using the top 5, 10, 20, etc. percents of the most important features (“gain” importance). If the scores improve — a new set of features is used for the final optional step — optimizing hyperparameters (RandomGrid).
Updating is simple: refit optimal model with full data (training data plus new train data). Yet frequent updating was crucial for a high score.
I put a lot of effort into this project, and the struggle paid off. I got third place in public leaderboard and a first place in the private leaderboard.
During the competition, I faced a lot of bugs, which cost me time and submissions. Bugs are inevitable, but there are notes, which helped me a lot if I used them from the start:
Log as much useful information as possible: columns in the data frame (columns order in train and test data might be different), data types(data types in train and test data frames might be different), time per training, time left for training, etc. It will help a lot to understand why submission failed or got a low score. For example, models in some of my submissions were not updated due to a silly bug, and I haven’t noticed that. Thus, my scores were much lower than they should be. A simple message print(“Model is updated!”) saved the day and helped me found the bug.The testing on unseen data is essential in AutoML. You may easily overfit your solution for a public part, and it could crash on the unseen data. That was my case — my submission failed on the first task. Try to collect more data at the beginning of the competition. New datasets should be diverse, for example, have missing values or strings in categories and other factors, which might crash your code. Test them with different time budgets: try to output even poor model when you’re tight on time.Organize your code in the “plug and play” manner: each part of the pipeline should not rely on the other parts. For example, I want to fit Linear Regression instead of LightGBM, would it be easy to do? If your code is well-organized, it will be. During this competition, I’ve made a great step towards a more clean, organized code. Yet sometimes I think it is still garbage, I see the progress.Do not use inplace operations in pandas because it is buggy. Simply don’t use it when possible.
Log as much useful information as possible: columns in the data frame (columns order in train and test data might be different), data types(data types in train and test data frames might be different), time per training, time left for training, etc. It will help a lot to understand why submission failed or got a low score. For example, models in some of my submissions were not updated due to a silly bug, and I haven’t noticed that. Thus, my scores were much lower than they should be. A simple message print(“Model is updated!”) saved the day and helped me found the bug.
The testing on unseen data is essential in AutoML. You may easily overfit your solution for a public part, and it could crash on the unseen data. That was my case — my submission failed on the first task. Try to collect more data at the beginning of the competition. New datasets should be diverse, for example, have missing values or strings in categories and other factors, which might crash your code. Test them with different time budgets: try to output even poor model when you’re tight on time.
Organize your code in the “plug and play” manner: each part of the pipeline should not rely on the other parts. For example, I want to fit Linear Regression instead of LightGBM, would it be easy to do? If your code is well-organized, it will be. During this competition, I’ve made a great step towards a more clean, organized code. Yet sometimes I think it is still garbage, I see the progress.
Do not use inplace operations in pandas because it is buggy. Simply don’t use it when possible.
I would like to thank organizers of the AutoSeries competition — 4Paradigm and ChaLearn teams. They did a great job: collected the data, prepared submissions scoring engine, wrote a robust baseline solution and answered the arising questions on the forum and in emails. Thank you for your work!
|
[
{
"code": null,
"e": 538,
"s": 171,
"text": "Although I’m not a fan of nowadays AutoML, I enjoy participating in AutoML competitions. I believe that such competitions are a great learning opportunity and could give strong pipelines for future projects. AutoML competitions are something in between Kaggle-like competitions and LeetCode tasks: your code should give high scores, and it should be steady and fast."
},
{
"code": null,
"e": 739,
"s": 538,
"text": "Recently I took part in AutoSeries — AutoML competition on time-series data, in which I managed to get the first place among 40 competitors (15 in the finals). This post is an overview of my solution."
},
{
"code": null,
"e": 1179,
"s": 739,
"text": "AutoSeries is one of the competitions of the Web Search and Data Mining (WSDM) conference. The competition is the 10th AutoML competition organized by 4Paradigm and ChaLearn. The previous ones were aimed to provide automated machine learning solutions for tabular data, computer vision, natural language processing, and speech recognition tasks. The full list of past challenges could be found on the official website of AutoML challenges."
},
{
"code": null,
"e": 1769,
"s": 1179,
"text": "This challenge aims at proposing automated solutions for the time series regression task. AutoSeries is restricted to multivariate regression problems, which come from different time series domains, including air quality, sales, work presence, city traffic, and other. Each dataset in the challenge is a tabular data whose features are of three main types: Id (could be multiple features or none), timestamp (each dataset has only one timestamp), other features (either numerical or categorical), and target to predict. The combination of Id features identifies a variable (a time series)."
},
{
"code": null,
"e": 2150,
"s": 1769,
"text": "Participants have to submit code, which will be run in Docker container (CPU: 4 cores, 16 Gb RAM, no GPU). At first, the model is trained on full data, but during inference, it could be updated or retrained. The public leaderboard is calculated on five datasets, private — 5 new datasets without human intervention. The results of the private datasets determine the final ranking."
},
{
"code": null,
"e": 2249,
"s": 2150,
"text": "This section is devoted to the main parts of the final solution. The code of it is published here:"
},
{
"code": null,
"e": 2260,
"s": 2249,
"text": "github.com"
},
{
"code": null,
"e": 2645,
"s": 2260,
"text": "The solution consists of several steps. At first, common features are generated for time-series tasks. The number and types of these features are hyperparameters of the pipeline, which should be optimized for each task separately, but due to lack of computational time, I decided to generate the same features for all tasks and remove useless ones during the features selection stage."
},
{
"code": null,
"e": 2954,
"s": 2645,
"text": "The first batch of features are features based on the most critical numerical features. Numerical operations (addition, subtraction, multiplication, and division) of pairs of numerical features always improve the score of tree-based models because new features might reveal some hidden relations in the data."
},
{
"code": null,
"e": 3275,
"s": 2954,
"text": "Let’s take, for example, predicting the price of the apartment. The known information on the apartment’s floor (ap_floor) and the total number of floors (total_floors) in the building might be enriched by adding a new feature — relative_floor — which shows the relative position of the apartment’s floor in the building:"
},
{
"code": null,
"e": 3311,
"s": 3275,
"text": "rel_floor = ap_floor / total_floors"
},
{
"code": null,
"e": 3493,
"s": 3311,
"text": "This feature might help the model to understand that the third floor in row house (rel_floor is closer to 1) is not the same as the third in a skyscraper (rel_floor is closer to 0)."
},
{
"code": null,
"e": 4088,
"s": 3493,
"text": "However, there are two significant problems with such features engineering strategy, if we perform numerical operations of all possible pairs: overfitting, which is especially vital in time-series tasks, and memory issues (16 RAM docker was used). To reduce the negative effect, a small subset of features is selected and used for pairs. It is done by fitting the whole dataset to a shallow LigtGBM model (10 trees). All used features are sorted by “gain” importance, i.e. a total sum of gains of splits that use the feature. Then top-n most important numerical features are selected for pairs."
},
{
"code": null,
"e": 4444,
"s": 4088,
"text": "The next batch of features is based on the time-series nature of the data: previous values and differences. I calculate the lagged values of target, most important numerical and categorical features, the difference between last value of the target (lag = 1), and lagged value of the target (lag > 1). These new features were among the most important ones."
},
{
"code": null,
"e": 5005,
"s": 4444,
"text": "The last batch is time-series features: year, month, day of the week, day of the year, and hour. I could add many more time-based features, such as a minute of the day, quartal of the year, and so on, but decided not to do that, so my solution would be universal. Treating these new features as categories sometimes improved scores, but in other cases, it significantly reduced it. I didn’t have enough computational time during inference for optimizing this hyperparameter (i.e., treating as numerical or categorical), so all of them are treated as numerical."
},
{
"code": null,
"e": 5233,
"s": 5005,
"text": "After generating new features, the baseline model is trained. The baseline model uses all initial and created features. It encodes categories with a CatBoost encoder and uses the target as-is. The model is trained in two steps:"
},
{
"code": null,
"e": 6044,
"s": 5233,
"text": "At first, the data is split into the train and validation parts. Commonly, you want your train/validation/test split to emulate the usage of model in “production settings”. In the case of time series, that means that the model won’t be updated frequently, and you take 20–30% of data in the validation part (or use rolling window with the same proportions). In this competition, frequent updating of the model was possible, and thus, the validation part should be smaller: the validation part is 10% of the full training data. It is used for early stopping, i.e., to optimize the number of trees in boosting ensemble. After this step, the model could start making predictions, and all following steps are optional (bt crucial for a high score).The model is refit on full data using the optimal number of trees."
},
{
"code": null,
"e": 6789,
"s": 6044,
"text": "At first, the data is split into the train and validation parts. Commonly, you want your train/validation/test split to emulate the usage of model in “production settings”. In the case of time series, that means that the model won’t be updated frequently, and you take 20–30% of data in the validation part (or use rolling window with the same proportions). In this competition, frequent updating of the model was possible, and thus, the validation part should be smaller: the validation part is 10% of the full training data. It is used for early stopping, i.e., to optimize the number of trees in boosting ensemble. After this step, the model could start making predictions, and all following steps are optional (bt crucial for a high score)."
},
{
"code": null,
"e": 6856,
"s": 6789,
"text": "The model is refit on full data using the optimal number of trees."
},
{
"code": null,
"e": 7206,
"s": 6856,
"text": "I used the solo LigthGBM model for making predictions. I tested CatBoost (too slow without GPU) and LinearModels (not accurate enough). I also tested bagging and training with different seeds to reduce the variance of the predictions, but these approaches took a lot of time and didn’t improve the scores enough to be included in the final solution."
},
{
"code": null,
"e": 7380,
"s": 7206,
"text": "I had too little time during inference for hyperparameters optimization, so I decided to narrow all possible hyperparameters combinations to the most promising ones, namely:"
},
{
"code": null,
"e": 8009,
"s": 7380,
"text": "Treating categorical variables: treat categorical features as pandas category type and leave the headache to LightGBM or encode each category with CatBoost encoding (check my previous article on the encoding categories, if you haven’t’ read it yet).Target preprocessing: use target as is or calculate a new target for regression by differentiating: new_target(t)=target(t)-target(t-1). Differencing could help to overcome non-stationarity time series data. I also tested power transformation (taking root of target and Box-Cox) to reduce stationarity, but it didn’t improve the score enough to be included in the final solution."
},
{
"code": null,
"e": 8259,
"s": 8009,
"text": "Treating categorical variables: treat categorical features as pandas category type and leave the headache to LightGBM or encode each category with CatBoost encoding (check my previous article on the encoding categories, if you haven’t’ read it yet)."
},
{
"code": null,
"e": 8639,
"s": 8259,
"text": "Target preprocessing: use target as is or calculate a new target for regression by differentiating: new_target(t)=target(t)-target(t-1). Differencing could help to overcome non-stationarity time series data. I also tested power transformation (taking root of target and Box-Cox) to reduce stationarity, but it didn’t improve the score enough to be included in the final solution."
},
{
"code": null,
"e": 8662,
"s": 8639,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 9092,
"s": 8662,
"text": "Each set of parameters is first validated, and, if the new validation score is better — refit model. After selecting the best set of pipeline hyperparameters, the model starts feature selection: the model is refit using the top 5, 10, 20, etc. percents of the most important features (“gain” importance). If the scores improve — a new set of features is used for the final optional step — optimizing hyperparameters (RandomGrid)."
},
{
"code": null,
"e": 9236,
"s": 9092,
"text": "Updating is simple: refit optimal model with full data (training data plus new train data). Yet frequent updating was crucial for a high score."
},
{
"code": null,
"e": 9390,
"s": 9236,
"text": "I put a lot of effort into this project, and the struggle paid off. I got third place in public leaderboard and a first place in the private leaderboard."
},
{
"code": null,
"e": 9568,
"s": 9390,
"text": "During the competition, I faced a lot of bugs, which cost me time and submissions. Bugs are inevitable, but there are notes, which helped me a lot if I used them from the start:"
},
{
"code": null,
"e": 11133,
"s": 9568,
"text": "Log as much useful information as possible: columns in the data frame (columns order in train and test data might be different), data types(data types in train and test data frames might be different), time per training, time left for training, etc. It will help a lot to understand why submission failed or got a low score. For example, models in some of my submissions were not updated due to a silly bug, and I haven’t noticed that. Thus, my scores were much lower than they should be. A simple message print(“Model is updated!”) saved the day and helped me found the bug.The testing on unseen data is essential in AutoML. You may easily overfit your solution for a public part, and it could crash on the unseen data. That was my case — my submission failed on the first task. Try to collect more data at the beginning of the competition. New datasets should be diverse, for example, have missing values or strings in categories and other factors, which might crash your code. Test them with different time budgets: try to output even poor model when you’re tight on time.Organize your code in the “plug and play” manner: each part of the pipeline should not rely on the other parts. For example, I want to fit Linear Regression instead of LightGBM, would it be easy to do? If your code is well-organized, it will be. During this competition, I’ve made a great step towards a more clean, organized code. Yet sometimes I think it is still garbage, I see the progress.Do not use inplace operations in pandas because it is buggy. Simply don’t use it when possible."
},
{
"code": null,
"e": 11709,
"s": 11133,
"text": "Log as much useful information as possible: columns in the data frame (columns order in train and test data might be different), data types(data types in train and test data frames might be different), time per training, time left for training, etc. It will help a lot to understand why submission failed or got a low score. For example, models in some of my submissions were not updated due to a silly bug, and I haven’t noticed that. Thus, my scores were much lower than they should be. A simple message print(“Model is updated!”) saved the day and helped me found the bug."
},
{
"code": null,
"e": 12210,
"s": 11709,
"text": "The testing on unseen data is essential in AutoML. You may easily overfit your solution for a public part, and it could crash on the unseen data. That was my case — my submission failed on the first task. Try to collect more data at the beginning of the competition. New datasets should be diverse, for example, have missing values or strings in categories and other factors, which might crash your code. Test them with different time budgets: try to output even poor model when you’re tight on time."
},
{
"code": null,
"e": 12605,
"s": 12210,
"text": "Organize your code in the “plug and play” manner: each part of the pipeline should not rely on the other parts. For example, I want to fit Linear Regression instead of LightGBM, would it be easy to do? If your code is well-organized, it will be. During this competition, I’ve made a great step towards a more clean, organized code. Yet sometimes I think it is still garbage, I see the progress."
},
{
"code": null,
"e": 12701,
"s": 12605,
"text": "Do not use inplace operations in pandas because it is buggy. Simply don’t use it when possible."
}
] |
Simulating stock prices in Python using Geometric Brownian Motion | by Umut Yildiz | Towards Data Science
|
It would be great if we can precisely predict how stock prices will change in near or far future. We would be rich, but it is almost impossible to create exact predictions. There are so many factors involved in the movement of stock prices that are hard to model. Human psychology is one of them. Investors, for sure, make their decisions based on empirical evidence and stock market indicators. However, they are still humans. Different people can interpret data differently, both because of their risk appetite and their mood at the moment. While a piece of breaking news in the country causes an investor to buy a stock, it causes another one to sell that same stock. Therefore, predicting stock prices is a difficult job, but we still have valuable tools which can help us to understand the stock price movement up to some point.
In this article, we discuss how to construct a Geometric Brownian Motion(GBM) simulation using Python. While building the script, we also explore the intuition behind the GBM model. I will not be getting into the theoretical background of its derivation. It’s beyond the scope of this article. I care more about giving a high-level understanding of what GBM needs as parameters, what its components are and how it creates predictions. I will try to have a bottom-up approach and build up the logic of GBM starting from its components. The simulation model we develop here is a discrete-time model. Therefore, all mathematics discussed here is the discrete-time analogy of Geometric Brownian Motion for continuous stochastic processes. At the end of this article, we learn how to create simulations using GBM and you will have a full code.
What GBM doesWhat input parameters we need for GBM simulationThe components of GBM: Drift and DiffusionBuilding the discrete-time GBM modelMaking predictions
What GBM does
What input parameters we need for GBM simulation
The components of GBM: Drift and Diffusion
Building the discrete-time GBM model
Making predictions
I use E.ON’s stock prices as an example throughout the article when explaining the related concepts. E.ON is an electric utility company based in Germany and it is one of the biggest in Europe. I retrieve its stock prices(in Euros) from Xetra Exchange through Python package of Quandl. Here is a link where you can display the stock prices: Investing.com Link
To be able to use Quandl, you need to sign up and get an authorization token from its website and also you need to install “quandl” Python package. Assuming that you completed these steps, you can just use the code below to extract stock price data.
Geometric Brownian Motion is widely used to model stock prices in finance and there is a reason why people choose it. In the line plot below, the x-axis indicates the days between 1 Jan 2019–31 Jul 2019 and the y-axis indicates the stock price in Euros. I want you to focus only on major, longer duration trends in the plot, disregarding the small fluctuations. You would realize that the stock price follows a wavy path. It increases from January to April, then it decreases until mid-May, followed by another increase series until mid-June and finally decreasing until the end of July. Now, I want you to focus on shorter-term fluctuations. Let’s investigate July. You can say that the general trend is downward, but the stock price doesn’t just fall smoothly. During its journey to the end of July, it goes up and down continuously which indicates that there is not an interpretable pattern in this movement.
So, we have already identified the two components of stock price movement. In July,
E.ON’s stock price tends to fall, andThere are random shocks each day to the falling stock price that result in an irregular line plot.
E.ON’s stock price tends to fall, and
There are random shocks each day to the falling stock price that result in an irregular line plot.
As a result, we need a suitable model that takes into account both types of movements in the stock price. This is where Geometric Brownian Motion comes into play. GBM has two components that do this job. One component incorporates the long-term trend while the other component applies random shocks. We will talk about these in later sections.
Below are the input parameters that our GBM simulation model will take. We will discuss each of them one by one in detail. For the sake of this article, I will use E.ON’s stock prices of July to make predictions for August. Also, you should note that I talk about trading days when I explain things using dates. We assume that a week is composed of only the weekdays, meaning that what comes after Friday is Monday. So, I want you to keep these in mind while reading about the input parameters.
We retrieve historical stock prices between start_date and end_date. Then using our GBM model, we will get our simulations until pred_end_date. We can play with these variables and create different settings.
Date Close 0 2019-07-01 9.612 1 2019-07-02 9.761 2 2019-07-03 9.856 3 2019-07-04 9.800 4 2019-07-05 9.664Date Close 18 2019-07-25 9.517 19 2019-07-26 9.460 20 2019-07-29 9.488 21 2019-07-30 9.226 22 2019-07-31 9.054
Note that, stock prices for only the trading days are retrieved, as you can realize from the data above.
1. So
This is the initial stock price. Forward stock price simulations take their roots from this initial stock price value. We will multiply this initial value with some expressions to get predictions for each of the trading days in August. In our case, So is the closing stock price on July 31, 2019.
9.054
2. dt
This is the time increment in our model. It means the time unit that we assume. Remember that we have the closing prices of E.ON stocks for each trading day, then the time increment in our model is 1 day. Please note that dt follows from the time steps in historical data. If the stock price data is published every 7.2 hours, then dt would be 0.3 since it corresponds to 7.2 hours(= 0.3 days).
1
3. T
T denotes the length of our prediction time horizon. We should be careful and consistent when specifying values for T and dt. For example, in our case, T should be 22 days since we want predictions for 22 trading days of August and when assigning a value to dt, following from our declaration of T, we should remember that dt must be represented in terms of days. The time unit for these two parameters has to be the same. Now, looking at a different example, suppose we have two stock price values for each trading day in our data and we know that we will make predictions for the 22 trading days in August. Under this setting, our time increment would be 0.5 days and we would assign 0.5 to dt. So, we would have 44 predictions after applying GBM, two predictions for each trading day in August.
Remember the example in the previous part where we supposed stock price data is published every 7.2 hours. If we want our prediction time horizon to be 72 hours(T = 72), then the appropriate dt would be 7.2 hours itself, without needing to convert it to 0.3 days. So, in the end, we would have 72 / 7.2 = 10 predictions with 7.2 hours between each of them.
If you follow this idea when building and using a GBM model, it becomes a lot easier to use your model for different equities under different settings. This feels confusing to many people and that’s why I try to standardize it like this here :) The ultimate point we are trying to reach is calculating N(explained in the next part) correctly. It is the number of time points within our prediction time horizon which should be consistent with our historical data in terms of time increment magnitude. I know it’s a simple thing, but building a line of reasoning is always a good idea to prevent potential confusions in different applications of our code in the future.
We can infer the number of trading days in August, using the pred_end_date variable we declared at the beginning of this section. Using the code below, we can extract the number of trading days our model will predict stock prices for, by counting the weekdays between (end_date + 1 day) and pred_end_date. What we need in our case is the number of trading days between 1 Aug 2019 and 31 Aug 2019.
22
4. N
This parameter comes automatically after assignment of dt and T. It is the number of time points in the prediction time horizon. In our case, our time increment is 1 day and we will get predictions for 22 trading days. This means, we have 22 different time points(days) and we will have 22 predictions at the end.
22.0
5. t
This is an array where we show the time progression in our model. It is like a time ticker where we measure time by counting the number of time points elapsed. Building array t follows from the calculation of N. Remember we have 22 time points(days) to make predictions for. That’s why array t starts from 1 and goes up to 22. When we use an element from array t, it means, that much time point elapsed in the model. As our predictions get far away from the date of So(starting day), they will fluctuate more due to this array t with more time points getting elapsed. In our case, t would be the array below for our model.
[ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22]
Some other examples:
i. If dt is 0.5 days (two stock prices for each day) and T is 22 days, then t:
[1 2 3 4 5 6 7 8 9 10 ... 44]
ii. If dt is 7.2 hours and T is 72 hours, then t:
[1 2 3 4 5 6 7 8 9 10]
The reason why we can use array t as a sequence of positive integers up to N is that we treat historical stock price data and our predictions in the same way in terms of their time-scaling. I mean, 1 day in the historical data is the same 1 day for our predictions. In some other articles on the Internet, you may come across with such cases where array t is scaled-down and goes up to 1. In those cases, the meaning of 1 day changes for the prediction time horizon and our input parameters mu, sigma, and array b have to be scaled to account for the time-scale difference. In this article, we use the same time-scale both for the historical data and the predictions in order to make the GBM model more interpretable.
6. mu
This is the mean return of the stock prices within the historical date range selected. In our case, we pick trading days of July as the historical data and we should calculate mu using stock prices of July. Before calculating mu, we should calculate the return for each trading day. The calculation is below.
[0.015501456512692377, 0.00973260936379476, -0.005681818181818097, -0.013877551020408265, -0.0032077814569537026, 0.00384096335513348, -0.013340227507755901, -0.005554973273241884, -0.008326306913996506, -0.0004251248804337693, -0.0005316321105793732, -0.0013829787234042447, 0.0030893789283050936, 0.0036108751062020944, 0.0010582010582012237, 0.0052854122621563355, 0.002944269190326022, -0.0022017194380374075, -0.0059892823368707165, 0.0029598308668074727, -0.0276138279932545, -0.018642965532191694]
After calculating returns for all of the days in July, we need to calculate the arithmetic average using those returns to obtain mu. We will then use mu in our drift component calculation. It will have an effect on the long-term movement of the stock price. Also, as you can see below, mu is ~ -0.3 % which indicates that there is a negative return on average during the month July and we should take into this account when calculating forward predictions for August.
-0.0026705996693330543
One important thing to note is that we don’t need to multiply mean return with a number for adjustment. We stay loyal to the time increment magnitude of our historical data and we create prediction series in the same way the historical data exists. We already discussed this issue above, but to elaborate more, suppose we are retrieving stock price data every 7.2 hours and we have the data for the last 72 hours. Also, we want to make predictions for the following 36 hours. When we calculate mean return from the historical data, that mean return accounts for the associated time step length of 7.2 hours(There are 7.2 hours between two data points). When making predictions, obeying our consistency rule for history and future time-scales, we assign 7.2 hours to dt. This results in 5 time points(36/7.2) with 7.2 hours between them and our array t becomes [1 2 3 4 5]. This means we can use mean return as mu in our model without needing to adjust it.
7. sigma
This is the standard deviation of returns of the stock prices in July. sigma is important, because, it will be helpful to incorporate random shocks to our predictions. Remember from the line plot of E.ON stock prices above, the stock price continuously goes up and down one day to another. Also, the magnitude and direction of this small movement seem to be random. Here, sigma will help us in determining the magnitude of the movement. sigma, by itself, doesn’t add the randomness we need to the model. We will use the standard normal random variable when picking up random values. sigma will contribute by scaling the magnitude of random shock so that the small fluctuations occur in accordance with the historical volatility of the stock prices. We don’t want any irrelevant random values coming from the standard normal distribution. Below, you can see how sigma is calculated.
0.009362443851856311
Remember we said that we don’t multiply mu with any number for adjustment, because we stay loyal to the length of time steps in the historical data when making predictions. The same logic applies here and we don’t need to adjust sigma either.
8. b
This array is the array where we add randomness to our model. The important thing here is the scen_size variable. Since this is a simulation model, we want to have many hypothetical paths for the stock price within the prediction time horizon. Assigning 2 to scen_size means, in the end, we will have 2 different stock price series. The logic for each scenario is the same as the other. So, I will discuss as if we are creating only 1 prediction series. Remember from the discussion of t, we declared an array for time progression which counts elapsed time points. Here array b, for each corresponding prediction time point, stores a random number coming from the standard normal distribution. These random numbers will add the random shocks, that we have been talking since the beginning of the article, to the model. That’s why we will use numpy.random.normal() to generate random values from the standard normal distribution. Again, we don’t multiply this random value with any number for adjustment, following the same reasoning with mu and sigma.
In the example above, we assume our historical stock price data is daily and that’s why we assign 1 to dt. Also, We want predictions for 5 days, which means the value of T is 5. Following these, N is calculated as 5 time points(5 1-day periods). So, for each of these time points, we generated a random number coming from the standard normal distribution(mean=0, std=1) using numpy.random.normal() method. These random values composed our array b at the end.
In our case, T should be 22 days. Below is the code where we create 2 arrays of random values with length 22 for 2 different scenarios.
{'1': array([ 1.37139893, -1.60468185, 0.84629302, 0.84599139, 0.1392499 , -0.23658454, 0.66158754, 1.44276449, 0.25582332, -0.00432083, 1.39636253, 0.21584903, 0.15232219, 1.41902316, 0.15672926, -0.76728718, 0.26303217, 1.61346848, 0.16319213, 1.08515534, -1.43681955, -1.89643601]),'2': array([-1.19967538, -0.66905682, -1.31963702, -0.04374916, 1.36622513, 0.39133558, -0.05713623, -1.16944076, 0.51635002, -0.53486539, 1.864583 , -1.2722681 , 0.06091857, -0.86510476, 0.1338046 , 0.76766205, -0.00538846, 0.92632565, -0.13265282, -0.12242566, 0.4031829 , 0.74874924])}
9. W
W is the Brownian path and it determines how the stock prices fluctuate from beginning time point(So) to some other time point t. You should distinguish between b and W. In the next section, the difference between them will be a lot clearer, but still, I want to mention briefly here. b is the random shock being applied to the stock price at a time point when predicting the stock price of the NEXT time point. So, suppose, at time point 3, the stock price is S_3. When predicting time point 4, b(4) is applied to S_3 as the random shock. W, on the other hand, is THE PATH. It means that it includes the effects of all the random shocks since the beginning of the prediction time horizon. It is the total effect of randomness incorporated into So(initial stock price) until the specific time point we are concerned with. So, suppose, we are predicting time point 4. We need to apply all the random shocks up-to and including time point 4 to So. Therefore, instead of b(4), we use W(4) which is the cumulative sum of array b elements with index less than or equal to 4. Below is the continuation of the example in the previous part where we discussed array b.
{'1': array([ 1.37139893, -0.23328292, 0.6130101 , 1.45900149, 1.59825139, 1.36166685, 2.02325439, 3.46601888, 3.72184221, 3.71752138, 5.11388391, 5.32973294, 5.48205514, 6.9010783 , 7.05780756, 6.29052038, 6.55355255, 8.16702103, 8.33021316, 9.4153685 , 7.97854894, 6.08211294]),'2': array([-1.19967538, -1.8687322 , -3.18836922, -3.23211838, -1.86589325, -1.47455767, -1.5316939 , -2.70113466, -2.18478464, -2.71965004, -0.85506704, -2.12733514, -2.06641657, -2.93152133, -2.79771673, -2.03005468, -2.03544314, -1.10911749, -1.24177031, -1.36419597, -0.96101307, -0.21226383])}
Above is the code for our case. Following from array b calculation in the previous part, we take the cumulative sums according to W(k) expression above and create array W.
This concludes our discussion of input parameters to the GBM model. We understood the reasoning behind each of them with examples and in the next sections, we will build the GBM model from its components. It will make the input parameters in this section more meaningful to you.
Remember from Section 1, we already identified the two components of Geometric Brownian Motion. One is the longer-term trend in the stock prices, and another one is the shorter-term random fluctuations. Now, we will give them names. We will call longer-term trends as Drift and we will call shorter-term fluctuations as Diffusion. In this section, I want you to suppose that we are at a specific time point (k-1) and we are going to predict the time point (k). However, the same assumptions we talked in the previous section are still valid. Just as a reminder:
Assumption 1: length of the time period between (k-1) and (k), which is dt, is in line with the historical data frequency.
Assumption 2: the time in our simulation progresses through counting time periods.
These assumptions make us ignore multiplying mu, sigma, and z(k) with a time-length value for adjustment and we can form our array t as a time point counter [1 2 3 ...].
Let’s move on. We are at a time point (k-1). The stock price at this time point needs to obey the longer-term trend in the stock prices while getting exposed to a random shock when we use it to create a prediction for the time point (k). So, we need to apply the two components of GBM to this stock price.
Let’s see what these components are in mathematical terms:
1. Drift
drift reflects the longer-term trend in stock prices. As you can recall from the previous section, we already know mu and sigma. They are constant values calculated from the historical stock price data in July. So, our drift is a constant value and if we suppose there is no random shock, we can apply it to the stock price at the time point (k-1) as you can see in the above expression. If we keep applying the drift without any random shock, stock prices smoothly go up if drift is positive or goes down if drift is negative. You should notice that the stock prices can never become 0 since drift is applied through the exponential function. This is the story of drift. Now, let’s move with the diffusion.
2. Diffusion
diffusion reflects shorter-term fluctuations. As you can recall from Section 2, array b stores the random shock information we need and it retrieves random shock information from standard normal random variable z. When calculating the diffusion component, we multiply the random value z(k) with sigma. Here, you can notice how the randomness is incorporated into the GBM model. Also, the diffusion component makes it possible to create different stock price prediction scenarios. The drift component is constant. We can’t create different scenarios out of it, but the diffusion component helps us create as many scenarios as we want since it involves Wiener process(It creates independent, stationary and normally distributed random shocks).
So, when making a prediction for the time point (k) considering the stock price at the time point (k-1), we need to add the effects of both of the components. The total combined effect gives us the prediction for the time point (k). If there would only be the drift component, we would always know what the stock price will become in the next time point, but the diffusion component disturbs this smoothness by introducing random shock. So, we don’t observe a monotonous increase or decrease trend for the stock prices. Below is how the total combined effect is applied to the stock price at the time point (k-1).
Up to now, we learned why we need GBM, what the parameters of a discrete-time GBM model are and how to make a prediction for 1 time point ahead. Now, we build the generic closed-form equation of the Geometric Brownian Motion adjusted for discrete-time context. In the previous section, we showed how to predict S(k) by multiplying S(k-1) with exp(drift + diffusion). As the continuation of this, we will try to predict S(k) using So(the initial stock price which is known).
To do that, we first replace S(k-1) with
S(k-2)exp(drift(k-1) + diffusion(k-1)).
Then we replace S(k-2) with
S(k-3)exp(drift(k-2) + diffusion(k-2)).
If we continue doing this, in the end, we will have So multiplied by many exponential terms. You can see what we obtain at the end of this procedure below.
After that, we extend the equation above, expressing drift and diffusion terms separately this time.
Above is the penultimate equation for S(k). It means, we can predict S(k) from So by adding the combined effect of k many drifts and the cumulative diffusion up to k. From So to S(k), there are k many time points which we call as the path. Remember from the previous section, drift doesn’t change from one time point to another. That’s why, to predict k time points ahead, we just add the drift k many times. This is different for diffusion. In Section 2, when discussing W, we learned that it is the Brownian path. You can recall that part. Based on that discussion, to predict k time points, we should consider the total effect of all the random shocks encountered on the path. In the last step of building the equation, we modify the equation just above by making below replacements.
Then, it gives us the final form of the equation with parameters that are all familiar to us and I hope all the discussions we made in Section 2 now help you to understand why we created those parameters in the way we did.
We know So, we know mu, we know sigma, we know array t and we know array W. We can easily create predictions for all the time points in our prediction time horizon at a single step. We will do this in the next section.
This is the last section of our article and it is the most fun part. We can now create the predictions. The first thing to do is calculating the drift for all the time points in the prediction time horizon. You already remember array t. We just multiply it with drift and we get an array of drifts. This drift array contains the total drift for all the time points in the prediction time horizon.
About diffusion, we will have a diffusion array for each of the scenarios. Remember, we control how many scenarios we want using the scen_size variable. Now, for this problem, we only have 2 scenarios. You can go up as much as you want. That’s why you see 2 different diffusion arrays labeled with ‘1’ and ‘2’, respectively. But, it is the same logic for each of them. We multiply the Brownian path(array W) with sigma.
drift:[-0.00271443 -0.00542885 -0.00814328 -0.01085771 -0.01357214 -0.01628656 -0.01900099 -0.02171542 -0.02442985 -0.02714427 -0.0298587 -0.03257313 -0.03528756 -0.03800198 -0.04071641 -0.04343084 -0.04614526 -0.04885969 -0.05157412 -0.05428855 -0.05700297 -0.0597174 ]diffusion: {'1': array([ 0.01283965, -0.0021841 , 0.00573927, 0.01365982, 0.01496354, 0.01274853, 0.01894261, 0.03245041, 0.03484554, 0.03480509, 0.04787845, 0.04989933, 0.05132543, 0.06461096, 0.06607833, 0.05889464, 0.06135727, 0.07646328, 0.07799115, 0.08815086, 0.07469872, 0.05694344]),'2': array([-0.01123189, -0.0174959 , -0.02985093, -0.03026053, -0.01746932, -0.01380546, -0.0143404 , -0.02528922, -0.02045492, -0.02546257, -0.00800552, -0.01991706, -0.01934671, -0.0274462 , -0.02619347, -0.01900627, -0.01905672, -0.01038405, -0.011626 , -0.01277221, -0.00899743, -0.00198731])}
Below are the predictions. Since we have 2 scenarios, we will have two stock price prediction series as a result of the operation below. The first line of code is just the final GBM equation we derived in the previous section. The second line just adds So to the prediction series, since it is the starting point and we may want to see it in our plots.
[[9.054 9.1461394 8.98533403 9.03226024 9.07940588 9.06660652 9.02202324 9.05347139 9.15171815 9.14879651 9.12362735 9.21862966 9.21223827 9.2003776 9.29815157 9.28656346 9.19509744 9.19278238 9.30740419 9.29636703 9.36583938 9.21564323 9.02891936][9.054 8.92860643 8.84880033 8.71645344 8.6892655 8.77726795 8.78560531 8.75710402 8.63826721 8.65659865 8.59000918 8.71758658 8.59101135 8.57261126 8.48040716 8.46802049 8.50598079 8.48249529 8.53318693 8.49949308 8.46674294 8.47572541 8.51221286]]
As the last thing to do, we now create the plot of our predictions. As you can see below, we have 2 stock price prediction scenarios. One goes up and the other one goes down. The drift in our problem is negative as you can observe from the drift array. This means the longer-term trend is downward for the stock prices(Remember we are only considering July as the historical data. I am talking based on this!). However, in spite of a negative drift, we have a prediction that is going up. This is due to random shocks. Remember, we create them using the standard normal random variable. In the scenario where prices are going up, it is clear that these random shocks exceeded the drift effect and it resulted in such a series.
In this article, we learned how to build a simulation model for stock prices using Geometric Brownian Motion in discrete-time context. Below is the full code. When you put your authorization token taken from Quandl after your registration and install the required Python packages, you can use the code right away. In each run, you will get different stock price scenarios. It is because we use np.random.normal() without setting seed. Each time we run the model, we will have a different array W and it will result in different predictions.
Geometric Brownian Motion helps us to see what paths stock prices may follow and lets us be prepared for what is coming. Of course, it is never possible to predict the exact future, but these statistical methods give us the chance of creating sound trading and hedging strategies that we can rely on.
|
[
{
"code": null,
"e": 1006,
"s": 172,
"text": "It would be great if we can precisely predict how stock prices will change in near or far future. We would be rich, but it is almost impossible to create exact predictions. There are so many factors involved in the movement of stock prices that are hard to model. Human psychology is one of them. Investors, for sure, make their decisions based on empirical evidence and stock market indicators. However, they are still humans. Different people can interpret data differently, both because of their risk appetite and their mood at the moment. While a piece of breaking news in the country causes an investor to buy a stock, it causes another one to sell that same stock. Therefore, predicting stock prices is a difficult job, but we still have valuable tools which can help us to understand the stock price movement up to some point."
},
{
"code": null,
"e": 1845,
"s": 1006,
"text": "In this article, we discuss how to construct a Geometric Brownian Motion(GBM) simulation using Python. While building the script, we also explore the intuition behind the GBM model. I will not be getting into the theoretical background of its derivation. It’s beyond the scope of this article. I care more about giving a high-level understanding of what GBM needs as parameters, what its components are and how it creates predictions. I will try to have a bottom-up approach and build up the logic of GBM starting from its components. The simulation model we develop here is a discrete-time model. Therefore, all mathematics discussed here is the discrete-time analogy of Geometric Brownian Motion for continuous stochastic processes. At the end of this article, we learn how to create simulations using GBM and you will have a full code."
},
{
"code": null,
"e": 2003,
"s": 1845,
"text": "What GBM doesWhat input parameters we need for GBM simulationThe components of GBM: Drift and DiffusionBuilding the discrete-time GBM modelMaking predictions"
},
{
"code": null,
"e": 2017,
"s": 2003,
"text": "What GBM does"
},
{
"code": null,
"e": 2066,
"s": 2017,
"text": "What input parameters we need for GBM simulation"
},
{
"code": null,
"e": 2109,
"s": 2066,
"text": "The components of GBM: Drift and Diffusion"
},
{
"code": null,
"e": 2146,
"s": 2109,
"text": "Building the discrete-time GBM model"
},
{
"code": null,
"e": 2165,
"s": 2146,
"text": "Making predictions"
},
{
"code": null,
"e": 2525,
"s": 2165,
"text": "I use E.ON’s stock prices as an example throughout the article when explaining the related concepts. E.ON is an electric utility company based in Germany and it is one of the biggest in Europe. I retrieve its stock prices(in Euros) from Xetra Exchange through Python package of Quandl. Here is a link where you can display the stock prices: Investing.com Link"
},
{
"code": null,
"e": 2775,
"s": 2525,
"text": "To be able to use Quandl, you need to sign up and get an authorization token from its website and also you need to install “quandl” Python package. Assuming that you completed these steps, you can just use the code below to extract stock price data."
},
{
"code": null,
"e": 3687,
"s": 2775,
"text": "Geometric Brownian Motion is widely used to model stock prices in finance and there is a reason why people choose it. In the line plot below, the x-axis indicates the days between 1 Jan 2019–31 Jul 2019 and the y-axis indicates the stock price in Euros. I want you to focus only on major, longer duration trends in the plot, disregarding the small fluctuations. You would realize that the stock price follows a wavy path. It increases from January to April, then it decreases until mid-May, followed by another increase series until mid-June and finally decreasing until the end of July. Now, I want you to focus on shorter-term fluctuations. Let’s investigate July. You can say that the general trend is downward, but the stock price doesn’t just fall smoothly. During its journey to the end of July, it goes up and down continuously which indicates that there is not an interpretable pattern in this movement."
},
{
"code": null,
"e": 3771,
"s": 3687,
"text": "So, we have already identified the two components of stock price movement. In July,"
},
{
"code": null,
"e": 3907,
"s": 3771,
"text": "E.ON’s stock price tends to fall, andThere are random shocks each day to the falling stock price that result in an irregular line plot."
},
{
"code": null,
"e": 3945,
"s": 3907,
"text": "E.ON’s stock price tends to fall, and"
},
{
"code": null,
"e": 4044,
"s": 3945,
"text": "There are random shocks each day to the falling stock price that result in an irregular line plot."
},
{
"code": null,
"e": 4388,
"s": 4044,
"text": "As a result, we need a suitable model that takes into account both types of movements in the stock price. This is where Geometric Brownian Motion comes into play. GBM has two components that do this job. One component incorporates the long-term trend while the other component applies random shocks. We will talk about these in later sections."
},
{
"code": null,
"e": 4883,
"s": 4388,
"text": "Below are the input parameters that our GBM simulation model will take. We will discuss each of them one by one in detail. For the sake of this article, I will use E.ON’s stock prices of July to make predictions for August. Also, you should note that I talk about trading days when I explain things using dates. We assume that a week is composed of only the weekdays, meaning that what comes after Friday is Monday. So, I want you to keep these in mind while reading about the input parameters."
},
{
"code": null,
"e": 5091,
"s": 4883,
"text": "We retrieve historical stock prices between start_date and end_date. Then using our GBM model, we will get our simulations until pred_end_date. We can play with these variables and create different settings."
},
{
"code": null,
"e": 5331,
"s": 5091,
"text": "Date Close 0 2019-07-01 9.612 1 2019-07-02 9.761 2 2019-07-03 9.856 3 2019-07-04 9.800 4 2019-07-05 9.664Date Close 18 2019-07-25 9.517 19 2019-07-26 9.460 20 2019-07-29 9.488 21 2019-07-30 9.226 22 2019-07-31 9.054"
},
{
"code": null,
"e": 5436,
"s": 5331,
"text": "Note that, stock prices for only the trading days are retrieved, as you can realize from the data above."
},
{
"code": null,
"e": 5442,
"s": 5436,
"text": "1. So"
},
{
"code": null,
"e": 5739,
"s": 5442,
"text": "This is the initial stock price. Forward stock price simulations take their roots from this initial stock price value. We will multiply this initial value with some expressions to get predictions for each of the trading days in August. In our case, So is the closing stock price on July 31, 2019."
},
{
"code": null,
"e": 5745,
"s": 5739,
"text": "9.054"
},
{
"code": null,
"e": 5751,
"s": 5745,
"text": "2. dt"
},
{
"code": null,
"e": 6146,
"s": 5751,
"text": "This is the time increment in our model. It means the time unit that we assume. Remember that we have the closing prices of E.ON stocks for each trading day, then the time increment in our model is 1 day. Please note that dt follows from the time steps in historical data. If the stock price data is published every 7.2 hours, then dt would be 0.3 since it corresponds to 7.2 hours(= 0.3 days)."
},
{
"code": null,
"e": 6148,
"s": 6146,
"text": "1"
},
{
"code": null,
"e": 6153,
"s": 6148,
"text": "3. T"
},
{
"code": null,
"e": 6951,
"s": 6153,
"text": "T denotes the length of our prediction time horizon. We should be careful and consistent when specifying values for T and dt. For example, in our case, T should be 22 days since we want predictions for 22 trading days of August and when assigning a value to dt, following from our declaration of T, we should remember that dt must be represented in terms of days. The time unit for these two parameters has to be the same. Now, looking at a different example, suppose we have two stock price values for each trading day in our data and we know that we will make predictions for the 22 trading days in August. Under this setting, our time increment would be 0.5 days and we would assign 0.5 to dt. So, we would have 44 predictions after applying GBM, two predictions for each trading day in August."
},
{
"code": null,
"e": 7308,
"s": 6951,
"text": "Remember the example in the previous part where we supposed stock price data is published every 7.2 hours. If we want our prediction time horizon to be 72 hours(T = 72), then the appropriate dt would be 7.2 hours itself, without needing to convert it to 0.3 days. So, in the end, we would have 72 / 7.2 = 10 predictions with 7.2 hours between each of them."
},
{
"code": null,
"e": 7976,
"s": 7308,
"text": "If you follow this idea when building and using a GBM model, it becomes a lot easier to use your model for different equities under different settings. This feels confusing to many people and that’s why I try to standardize it like this here :) The ultimate point we are trying to reach is calculating N(explained in the next part) correctly. It is the number of time points within our prediction time horizon which should be consistent with our historical data in terms of time increment magnitude. I know it’s a simple thing, but building a line of reasoning is always a good idea to prevent potential confusions in different applications of our code in the future."
},
{
"code": null,
"e": 8373,
"s": 7976,
"text": "We can infer the number of trading days in August, using the pred_end_date variable we declared at the beginning of this section. Using the code below, we can extract the number of trading days our model will predict stock prices for, by counting the weekdays between (end_date + 1 day) and pred_end_date. What we need in our case is the number of trading days between 1 Aug 2019 and 31 Aug 2019."
},
{
"code": null,
"e": 8376,
"s": 8373,
"text": "22"
},
{
"code": null,
"e": 8381,
"s": 8376,
"text": "4. N"
},
{
"code": null,
"e": 8695,
"s": 8381,
"text": "This parameter comes automatically after assignment of dt and T. It is the number of time points in the prediction time horizon. In our case, our time increment is 1 day and we will get predictions for 22 trading days. This means, we have 22 different time points(days) and we will have 22 predictions at the end."
},
{
"code": null,
"e": 8700,
"s": 8695,
"text": "22.0"
},
{
"code": null,
"e": 8705,
"s": 8700,
"text": "5. t"
},
{
"code": null,
"e": 9328,
"s": 8705,
"text": "This is an array where we show the time progression in our model. It is like a time ticker where we measure time by counting the number of time points elapsed. Building array t follows from the calculation of N. Remember we have 22 time points(days) to make predictions for. That’s why array t starts from 1 and goes up to 22. When we use an element from array t, it means, that much time point elapsed in the model. As our predictions get far away from the date of So(starting day), they will fluctuate more due to this array t with more time points getting elapsed. In our case, t would be the array below for our model."
},
{
"code": null,
"e": 9388,
"s": 9328,
"text": "[ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22]"
},
{
"code": null,
"e": 9409,
"s": 9388,
"text": "Some other examples:"
},
{
"code": null,
"e": 9488,
"s": 9409,
"text": "i. If dt is 0.5 days (two stock prices for each day) and T is 22 days, then t:"
},
{
"code": null,
"e": 9518,
"s": 9488,
"text": "[1 2 3 4 5 6 7 8 9 10 ... 44]"
},
{
"code": null,
"e": 9568,
"s": 9518,
"text": "ii. If dt is 7.2 hours and T is 72 hours, then t:"
},
{
"code": null,
"e": 9591,
"s": 9568,
"text": "[1 2 3 4 5 6 7 8 9 10]"
},
{
"code": null,
"e": 10309,
"s": 9591,
"text": "The reason why we can use array t as a sequence of positive integers up to N is that we treat historical stock price data and our predictions in the same way in terms of their time-scaling. I mean, 1 day in the historical data is the same 1 day for our predictions. In some other articles on the Internet, you may come across with such cases where array t is scaled-down and goes up to 1. In those cases, the meaning of 1 day changes for the prediction time horizon and our input parameters mu, sigma, and array b have to be scaled to account for the time-scale difference. In this article, we use the same time-scale both for the historical data and the predictions in order to make the GBM model more interpretable."
},
{
"code": null,
"e": 10315,
"s": 10309,
"text": "6. mu"
},
{
"code": null,
"e": 10624,
"s": 10315,
"text": "This is the mean return of the stock prices within the historical date range selected. In our case, we pick trading days of July as the historical data and we should calculate mu using stock prices of July. Before calculating mu, we should calculate the return for each trading day. The calculation is below."
},
{
"code": null,
"e": 11129,
"s": 10624,
"text": "[0.015501456512692377, 0.00973260936379476, -0.005681818181818097, -0.013877551020408265, -0.0032077814569537026, 0.00384096335513348, -0.013340227507755901, -0.005554973273241884, -0.008326306913996506, -0.0004251248804337693, -0.0005316321105793732, -0.0013829787234042447, 0.0030893789283050936, 0.0036108751062020944, 0.0010582010582012237, 0.0052854122621563355, 0.002944269190326022, -0.0022017194380374075, -0.0059892823368707165, 0.0029598308668074727, -0.0276138279932545, -0.018642965532191694]"
},
{
"code": null,
"e": 11597,
"s": 11129,
"text": "After calculating returns for all of the days in July, we need to calculate the arithmetic average using those returns to obtain mu. We will then use mu in our drift component calculation. It will have an effect on the long-term movement of the stock price. Also, as you can see below, mu is ~ -0.3 % which indicates that there is a negative return on average during the month July and we should take into this account when calculating forward predictions for August."
},
{
"code": null,
"e": 11620,
"s": 11597,
"text": "-0.0026705996693330543"
},
{
"code": null,
"e": 12576,
"s": 11620,
"text": "One important thing to note is that we don’t need to multiply mean return with a number for adjustment. We stay loyal to the time increment magnitude of our historical data and we create prediction series in the same way the historical data exists. We already discussed this issue above, but to elaborate more, suppose we are retrieving stock price data every 7.2 hours and we have the data for the last 72 hours. Also, we want to make predictions for the following 36 hours. When we calculate mean return from the historical data, that mean return accounts for the associated time step length of 7.2 hours(There are 7.2 hours between two data points). When making predictions, obeying our consistency rule for history and future time-scales, we assign 7.2 hours to dt. This results in 5 time points(36/7.2) with 7.2 hours between them and our array t becomes [1 2 3 4 5]. This means we can use mean return as mu in our model without needing to adjust it."
},
{
"code": null,
"e": 12585,
"s": 12576,
"text": "7. sigma"
},
{
"code": null,
"e": 13467,
"s": 12585,
"text": "This is the standard deviation of returns of the stock prices in July. sigma is important, because, it will be helpful to incorporate random shocks to our predictions. Remember from the line plot of E.ON stock prices above, the stock price continuously goes up and down one day to another. Also, the magnitude and direction of this small movement seem to be random. Here, sigma will help us in determining the magnitude of the movement. sigma, by itself, doesn’t add the randomness we need to the model. We will use the standard normal random variable when picking up random values. sigma will contribute by scaling the magnitude of random shock so that the small fluctuations occur in accordance with the historical volatility of the stock prices. We don’t want any irrelevant random values coming from the standard normal distribution. Below, you can see how sigma is calculated."
},
{
"code": null,
"e": 13488,
"s": 13467,
"text": "0.009362443851856311"
},
{
"code": null,
"e": 13731,
"s": 13488,
"text": "Remember we said that we don’t multiply mu with any number for adjustment, because we stay loyal to the length of time steps in the historical data when making predictions. The same logic applies here and we don’t need to adjust sigma either."
},
{
"code": null,
"e": 13736,
"s": 13731,
"text": "8. b"
},
{
"code": null,
"e": 14788,
"s": 13736,
"text": "This array is the array where we add randomness to our model. The important thing here is the scen_size variable. Since this is a simulation model, we want to have many hypothetical paths for the stock price within the prediction time horizon. Assigning 2 to scen_size means, in the end, we will have 2 different stock price series. The logic for each scenario is the same as the other. So, I will discuss as if we are creating only 1 prediction series. Remember from the discussion of t, we declared an array for time progression which counts elapsed time points. Here array b, for each corresponding prediction time point, stores a random number coming from the standard normal distribution. These random numbers will add the random shocks, that we have been talking since the beginning of the article, to the model. That’s why we will use numpy.random.normal() to generate random values from the standard normal distribution. Again, we don’t multiply this random value with any number for adjustment, following the same reasoning with mu and sigma."
},
{
"code": null,
"e": 15247,
"s": 14788,
"text": "In the example above, we assume our historical stock price data is daily and that’s why we assign 1 to dt. Also, We want predictions for 5 days, which means the value of T is 5. Following these, N is calculated as 5 time points(5 1-day periods). So, for each of these time points, we generated a random number coming from the standard normal distribution(mean=0, std=1) using numpy.random.normal() method. These random values composed our array b at the end."
},
{
"code": null,
"e": 15383,
"s": 15247,
"text": "In our case, T should be 22 days. Below is the code where we create 2 arrays of random values with length 22 for 2 different scenarios."
},
{
"code": null,
"e": 16039,
"s": 15383,
"text": "{'1': array([ 1.37139893, -1.60468185, 0.84629302, 0.84599139, 0.1392499 , -0.23658454, 0.66158754, 1.44276449, 0.25582332, -0.00432083, 1.39636253, 0.21584903, 0.15232219, 1.41902316, 0.15672926, -0.76728718, 0.26303217, 1.61346848, 0.16319213, 1.08515534, -1.43681955, -1.89643601]),'2': array([-1.19967538, -0.66905682, -1.31963702, -0.04374916, 1.36622513, 0.39133558, -0.05713623, -1.16944076, 0.51635002, -0.53486539, 1.864583 , -1.2722681 , 0.06091857, -0.86510476, 0.1338046 , 0.76766205, -0.00538846, 0.92632565, -0.13265282, -0.12242566, 0.4031829 , 0.74874924])}"
},
{
"code": null,
"e": 16044,
"s": 16039,
"text": "9. W"
},
{
"code": null,
"e": 17204,
"s": 16044,
"text": "W is the Brownian path and it determines how the stock prices fluctuate from beginning time point(So) to some other time point t. You should distinguish between b and W. In the next section, the difference between them will be a lot clearer, but still, I want to mention briefly here. b is the random shock being applied to the stock price at a time point when predicting the stock price of the NEXT time point. So, suppose, at time point 3, the stock price is S_3. When predicting time point 4, b(4) is applied to S_3 as the random shock. W, on the other hand, is THE PATH. It means that it includes the effects of all the random shocks since the beginning of the prediction time horizon. It is the total effect of randomness incorporated into So(initial stock price) until the specific time point we are concerned with. So, suppose, we are predicting time point 4. We need to apply all the random shocks up-to and including time point 4 to So. Therefore, instead of b(4), we use W(4) which is the cumulative sum of array b elements with index less than or equal to 4. Below is the continuation of the example in the previous part where we discussed array b."
},
{
"code": null,
"e": 17860,
"s": 17204,
"text": "{'1': array([ 1.37139893, -0.23328292, 0.6130101 , 1.45900149, 1.59825139, 1.36166685, 2.02325439, 3.46601888, 3.72184221, 3.71752138, 5.11388391, 5.32973294, 5.48205514, 6.9010783 , 7.05780756, 6.29052038, 6.55355255, 8.16702103, 8.33021316, 9.4153685 , 7.97854894, 6.08211294]),'2': array([-1.19967538, -1.8687322 , -3.18836922, -3.23211838, -1.86589325, -1.47455767, -1.5316939 , -2.70113466, -2.18478464, -2.71965004, -0.85506704, -2.12733514, -2.06641657, -2.93152133, -2.79771673, -2.03005468, -2.03544314, -1.10911749, -1.24177031, -1.36419597, -0.96101307, -0.21226383])}"
},
{
"code": null,
"e": 18032,
"s": 17860,
"text": "Above is the code for our case. Following from array b calculation in the previous part, we take the cumulative sums according to W(k) expression above and create array W."
},
{
"code": null,
"e": 18311,
"s": 18032,
"text": "This concludes our discussion of input parameters to the GBM model. We understood the reasoning behind each of them with examples and in the next sections, we will build the GBM model from its components. It will make the input parameters in this section more meaningful to you."
},
{
"code": null,
"e": 18873,
"s": 18311,
"text": "Remember from Section 1, we already identified the two components of Geometric Brownian Motion. One is the longer-term trend in the stock prices, and another one is the shorter-term random fluctuations. Now, we will give them names. We will call longer-term trends as Drift and we will call shorter-term fluctuations as Diffusion. In this section, I want you to suppose that we are at a specific time point (k-1) and we are going to predict the time point (k). However, the same assumptions we talked in the previous section are still valid. Just as a reminder:"
},
{
"code": null,
"e": 18996,
"s": 18873,
"text": "Assumption 1: length of the time period between (k-1) and (k), which is dt, is in line with the historical data frequency."
},
{
"code": null,
"e": 19079,
"s": 18996,
"text": "Assumption 2: the time in our simulation progresses through counting time periods."
},
{
"code": null,
"e": 19249,
"s": 19079,
"text": "These assumptions make us ignore multiplying mu, sigma, and z(k) with a time-length value for adjustment and we can form our array t as a time point counter [1 2 3 ...]."
},
{
"code": null,
"e": 19555,
"s": 19249,
"text": "Let’s move on. We are at a time point (k-1). The stock price at this time point needs to obey the longer-term trend in the stock prices while getting exposed to a random shock when we use it to create a prediction for the time point (k). So, we need to apply the two components of GBM to this stock price."
},
{
"code": null,
"e": 19614,
"s": 19555,
"text": "Let’s see what these components are in mathematical terms:"
},
{
"code": null,
"e": 19623,
"s": 19614,
"text": "1. Drift"
},
{
"code": null,
"e": 20331,
"s": 19623,
"text": "drift reflects the longer-term trend in stock prices. As you can recall from the previous section, we already know mu and sigma. They are constant values calculated from the historical stock price data in July. So, our drift is a constant value and if we suppose there is no random shock, we can apply it to the stock price at the time point (k-1) as you can see in the above expression. If we keep applying the drift without any random shock, stock prices smoothly go up if drift is positive or goes down if drift is negative. You should notice that the stock prices can never become 0 since drift is applied through the exponential function. This is the story of drift. Now, let’s move with the diffusion."
},
{
"code": null,
"e": 20344,
"s": 20331,
"text": "2. Diffusion"
},
{
"code": null,
"e": 21086,
"s": 20344,
"text": "diffusion reflects shorter-term fluctuations. As you can recall from Section 2, array b stores the random shock information we need and it retrieves random shock information from standard normal random variable z. When calculating the diffusion component, we multiply the random value z(k) with sigma. Here, you can notice how the randomness is incorporated into the GBM model. Also, the diffusion component makes it possible to create different stock price prediction scenarios. The drift component is constant. We can’t create different scenarios out of it, but the diffusion component helps us create as many scenarios as we want since it involves Wiener process(It creates independent, stationary and normally distributed random shocks)."
},
{
"code": null,
"e": 21700,
"s": 21086,
"text": "So, when making a prediction for the time point (k) considering the stock price at the time point (k-1), we need to add the effects of both of the components. The total combined effect gives us the prediction for the time point (k). If there would only be the drift component, we would always know what the stock price will become in the next time point, but the diffusion component disturbs this smoothness by introducing random shock. So, we don’t observe a monotonous increase or decrease trend for the stock prices. Below is how the total combined effect is applied to the stock price at the time point (k-1)."
},
{
"code": null,
"e": 22174,
"s": 21700,
"text": "Up to now, we learned why we need GBM, what the parameters of a discrete-time GBM model are and how to make a prediction for 1 time point ahead. Now, we build the generic closed-form equation of the Geometric Brownian Motion adjusted for discrete-time context. In the previous section, we showed how to predict S(k) by multiplying S(k-1) with exp(drift + diffusion). As the continuation of this, we will try to predict S(k) using So(the initial stock price which is known)."
},
{
"code": null,
"e": 22215,
"s": 22174,
"text": "To do that, we first replace S(k-1) with"
},
{
"code": null,
"e": 22255,
"s": 22215,
"text": "S(k-2)exp(drift(k-1) + diffusion(k-1))."
},
{
"code": null,
"e": 22283,
"s": 22255,
"text": "Then we replace S(k-2) with"
},
{
"code": null,
"e": 22323,
"s": 22283,
"text": "S(k-3)exp(drift(k-2) + diffusion(k-2))."
},
{
"code": null,
"e": 22479,
"s": 22323,
"text": "If we continue doing this, in the end, we will have So multiplied by many exponential terms. You can see what we obtain at the end of this procedure below."
},
{
"code": null,
"e": 22580,
"s": 22479,
"text": "After that, we extend the equation above, expressing drift and diffusion terms separately this time."
},
{
"code": null,
"e": 23367,
"s": 22580,
"text": "Above is the penultimate equation for S(k). It means, we can predict S(k) from So by adding the combined effect of k many drifts and the cumulative diffusion up to k. From So to S(k), there are k many time points which we call as the path. Remember from the previous section, drift doesn’t change from one time point to another. That’s why, to predict k time points ahead, we just add the drift k many times. This is different for diffusion. In Section 2, when discussing W, we learned that it is the Brownian path. You can recall that part. Based on that discussion, to predict k time points, we should consider the total effect of all the random shocks encountered on the path. In the last step of building the equation, we modify the equation just above by making below replacements."
},
{
"code": null,
"e": 23590,
"s": 23367,
"text": "Then, it gives us the final form of the equation with parameters that are all familiar to us and I hope all the discussions we made in Section 2 now help you to understand why we created those parameters in the way we did."
},
{
"code": null,
"e": 23809,
"s": 23590,
"text": "We know So, we know mu, we know sigma, we know array t and we know array W. We can easily create predictions for all the time points in our prediction time horizon at a single step. We will do this in the next section."
},
{
"code": null,
"e": 24206,
"s": 23809,
"text": "This is the last section of our article and it is the most fun part. We can now create the predictions. The first thing to do is calculating the drift for all the time points in the prediction time horizon. You already remember array t. We just multiply it with drift and we get an array of drifts. This drift array contains the total drift for all the time points in the prediction time horizon."
},
{
"code": null,
"e": 24626,
"s": 24206,
"text": "About diffusion, we will have a diffusion array for each of the scenarios. Remember, we control how many scenarios we want using the scen_size variable. Now, for this problem, we only have 2 scenarios. You can go up as much as you want. That’s why you see 2 different diffusion arrays labeled with ‘1’ and ‘2’, respectively. But, it is the same logic for each of them. We multiply the Brownian path(array W) with sigma."
},
{
"code": null,
"e": 25567,
"s": 24626,
"text": "drift:[-0.00271443 -0.00542885 -0.00814328 -0.01085771 -0.01357214 -0.01628656 -0.01900099 -0.02171542 -0.02442985 -0.02714427 -0.0298587 -0.03257313 -0.03528756 -0.03800198 -0.04071641 -0.04343084 -0.04614526 -0.04885969 -0.05157412 -0.05428855 -0.05700297 -0.0597174 ]diffusion: {'1': array([ 0.01283965, -0.0021841 , 0.00573927, 0.01365982, 0.01496354, 0.01274853, 0.01894261, 0.03245041, 0.03484554, 0.03480509, 0.04787845, 0.04989933, 0.05132543, 0.06461096, 0.06607833, 0.05889464, 0.06135727, 0.07646328, 0.07799115, 0.08815086, 0.07469872, 0.05694344]),'2': array([-0.01123189, -0.0174959 , -0.02985093, -0.03026053, -0.01746932, -0.01380546, -0.0143404 , -0.02528922, -0.02045492, -0.02546257, -0.00800552, -0.01991706, -0.01934671, -0.0274462 , -0.02619347, -0.01900627, -0.01905672, -0.01038405, -0.011626 , -0.01277221, -0.00899743, -0.00198731])}"
},
{
"code": null,
"e": 25920,
"s": 25567,
"text": "Below are the predictions. Since we have 2 scenarios, we will have two stock price prediction series as a result of the operation below. The first line of code is just the final GBM equation we derived in the previous section. The second line just adds So to the prediction series, since it is the starting point and we may want to see it in our plots."
},
{
"code": null,
"e": 26443,
"s": 25920,
"text": "[[9.054 9.1461394 8.98533403 9.03226024 9.07940588 9.06660652 9.02202324 9.05347139 9.15171815 9.14879651 9.12362735 9.21862966 9.21223827 9.2003776 9.29815157 9.28656346 9.19509744 9.19278238 9.30740419 9.29636703 9.36583938 9.21564323 9.02891936][9.054 8.92860643 8.84880033 8.71645344 8.6892655 8.77726795 8.78560531 8.75710402 8.63826721 8.65659865 8.59000918 8.71758658 8.59101135 8.57261126 8.48040716 8.46802049 8.50598079 8.48249529 8.53318693 8.49949308 8.46674294 8.47572541 8.51221286]]"
},
{
"code": null,
"e": 27170,
"s": 26443,
"text": "As the last thing to do, we now create the plot of our predictions. As you can see below, we have 2 stock price prediction scenarios. One goes up and the other one goes down. The drift in our problem is negative as you can observe from the drift array. This means the longer-term trend is downward for the stock prices(Remember we are only considering July as the historical data. I am talking based on this!). However, in spite of a negative drift, we have a prediction that is going up. This is due to random shocks. Remember, we create them using the standard normal random variable. In the scenario where prices are going up, it is clear that these random shocks exceeded the drift effect and it resulted in such a series."
},
{
"code": null,
"e": 27711,
"s": 27170,
"text": "In this article, we learned how to build a simulation model for stock prices using Geometric Brownian Motion in discrete-time context. Below is the full code. When you put your authorization token taken from Quandl after your registration and install the required Python packages, you can use the code right away. In each run, you will get different stock price scenarios. It is because we use np.random.normal() without setting seed. Each time we run the model, we will have a different array W and it will result in different predictions."
}
] |
Maximum size square Sub-Matrix with sum less than or equals to K - GeeksforGeeks
|
19 Jul, 2021
Given a Matrix arr[][] of size M x N having positive integers and a number K, the task is to find the size of the largest square sub-matrix whose sum of elements is less than or equals to K.
Example:
Input:
arr[][] = { { 1, 1, 3, 2, 4, 3, 2 },
{ 1, 1, 3, 2, 4, 3, 2 },
{ 1, 1, 3, 2, 4, 3, 2 } },
K = 4
Output:
2
Explanation:
Maximum size square Sub-Matrix
with sum less than or equals to 4
1 1
1 1
Size is 2.
Input:
arr[][] = { { 1, 1, 3, 2, 4, 3, 2 },
{ 1, 1, 3, 2, 4, 3, 2 },
{ 1, 1, 3, 2, 4, 3, 2 } },
K = 22
Output:
3
Explanation:
Maximum size square Sub-Matrix
with sum less than or equals to 22
1 1 3
1 1 3
1 1 3
Size is 3.
Approach:
For the given matrix arr[][] create a prefix sum matrix(say sum[][]) such that sum[i][j] stores the sum of all the elements of the matrix of size i x j.For each row in prefix sum matrix sum[][] using Binary Search do the following: Perform Binary search with the lower limit as 0 end the upper limit as to maximum size of square matrix.Find the middle index (say mid).If the sum of elements of all possible square matrix of size mid is less than or equals to K, then update the lower limit as mid + 1 to find the maximum sum with size greater than mid.Else Update the upper limit as mid – 1 to find the maximum sum with size less than mid.Keep updating the maximum size of square matrix in each iteration for the given valid condition above.
For the given matrix arr[][] create a prefix sum matrix(say sum[][]) such that sum[i][j] stores the sum of all the elements of the matrix of size i x j.
For each row in prefix sum matrix sum[][] using Binary Search do the following: Perform Binary search with the lower limit as 0 end the upper limit as to maximum size of square matrix.Find the middle index (say mid).If the sum of elements of all possible square matrix of size mid is less than or equals to K, then update the lower limit as mid + 1 to find the maximum sum with size greater than mid.Else Update the upper limit as mid – 1 to find the maximum sum with size less than mid.
Perform Binary search with the lower limit as 0 end the upper limit as to maximum size of square matrix.
Find the middle index (say mid).
If the sum of elements of all possible square matrix of size mid is less than or equals to K, then update the lower limit as mid + 1 to find the maximum sum with size greater than mid.
Else Update the upper limit as mid – 1 to find the maximum sum with size less than mid.
Keep updating the maximum size of square matrix in each iteration for the given valid condition above.
Below is the implementation of the above approach:
Java
Python3
C#
Javascript
C++
// Java program for the above approachimport java.util.*; class GFG { // Function to find the maximum size // of matrix with sum <= K static void findMaxMatrixSize(int[][] arr, int K) { int i, j; // N size of rows and M size of cols int n = arr.length; int m = arr[0].length; // To store the prefix sum of matrix int[][] sum = new int[n + 1][m + 1]; // Create prefix sum for (i = 0; i <= n; i++) { // Traverse each rows for (j = 0; j <= m; j++) { if (i == 0 || j == 0) { sum[i][j] = 0; continue; } // Update the prefix sum // till index i x j sum[i][j] = arr[i - 1][j - 1] + sum[i - 1][j] + sum[i][j - 1] - sum[i - 1][j - 1]; } } // To store the maximum size of // matrix with sum <= K int ans = 0; // Traverse the sum matrix for (i = 1; i <= n; i++) { for (j = 1; j <= m; j++) { // Index out of bound if (i + ans - 1 > n || j + ans - 1 > m) break; int mid, lo = ans; // Maximum possible size // of matrix int hi = Math.min(n - i + 1, m - j + 1); // Binary Search while (lo < hi) { // Find middle index mid = (hi + lo + 1) / 2; // Check whether sum <= K // or not // If Yes check for other // half of the search if (sum[i + mid - 1][j + mid - 1] + sum[i - 1][j - 1] - sum[i + mid - 1][j - 1] - sum[i - 1][j + mid - 1] <= K) { lo = mid; } // Else check it in first // half else { hi = mid - 1; } } // Update the maximum size matrix ans = Math.max(ans, lo); } } // Print the final answer System.out.print(ans + "\n"); } // Driver Code public static void main(String[] args) { int[][] arr = { { 1, 1, 3, 2, 4, 3, 2 }, { 1, 1, 3, 2, 4, 3, 2 }, { 1, 1, 3, 2, 4, 3, 2 } }; // Given target sum int K = 4; // Function Call findMaxMatrixSize(arr, K); }} // This code is contributed by 29AjayKumar
# Python3 program for the above approach # Function to find the maximum size# of matrix with sum <= K def findMaxMatrixSize(arr, K): # N size of rows and M size of cols n = len(arr) m = len(arr[0]) # To store the prefix sum of matrix sum = [[0 for i in range(m + 1)] for j in range(n + 1)] # Create Prefix Sum for i in range(n + 1): # Traverse each rows for j in range(m+1): if (i == 0 or j == 0): sum[i][j] = 0 continue # Update the prefix sum # till index i x j sum[i][j] = arr[i - 1][j - 1] + sum[i - 1][j] + \ sum[i][j - 1]-sum[i - 1][j - 1] # To store the maximum size of # matrix with sum <= K ans = 0 # Traverse the sum matrix for i in range(1, n + 1): for j in range(1, m + 1): # Index out of bound if (i + ans - 1 > n or j + ans - 1 > m): break mid = ans lo = ans # Maximum possible size # of matrix hi = min(n - i + 1, m - j + 1) # Binary Search while (lo < hi): # Find middle index mid = (hi + lo + 1) // 2 # Check whether sum <= K # or not # If Yes check for other # half of the search if (sum[i + mid - 1][j + mid - 1] + sum[i - 1][j - 1] - sum[i + mid - 1][j - 1] - sum[i - 1][j + mid - 1] <= K): lo = mid # Else check it in first # half else: hi = mid - 1 # Update the maximum size matrix ans = max(ans, lo) # Print the final answer print(ans) # Driver Codeif __name__ == '__main__': arr = [[1, 1, 3, 2, 4, 3, 2], [1, 1, 3, 2, 4, 3, 2], [1, 1, 3, 2, 4, 3, 2]] # Given target sum K = 4 # Function Call findMaxMatrixSize(arr, K) # This code is contributed by Surendra_Gangwar
// C# program for the above approachusing System; class GFG { // Function to find the maximum size // of matrix with sum <= K static void findMaxMatrixSize(int[, ] arr, int K) { int i, j; // N size of rows and M size of cols int n = arr.GetLength(0); int m = arr.GetLength(1); // To store the prefix sum of matrix int[, ] sum = new int[n + 1, m + 1]; // Create prefix sum for (i = 0; i <= n; i++) { // Traverse each rows for (j = 0; j <= m; j++) { if (i == 0 || j == 0) { sum[i, j] = 0; continue; } // Update the prefix sum // till index i x j sum[i, j] = arr[i - 1, j - 1] + sum[i - 1, j] + sum[i, j - 1] - sum[i - 1, j - 1]; } } // To store the maximum size // of matrix with sum <= K int ans = 0; // Traverse the sum matrix for (i = 1; i <= n; i++) { for (j = 1; j <= m; j++) { // Index out of bound if (i + ans - 1 > n || j + ans - 1 > m) break; int mid, lo = ans; // Maximum possible size // of matrix int hi = Math.Min(n - i + 1, m - j + 1); // Binary Search while (lo < hi) { // Find middle index mid = (hi + lo + 1) / 2; // Check whether sum <= K // or not // If Yes check for other // half of the search if (sum[i + mid - 1, j + mid - 1] + sum[i - 1, j - 1] - sum[i + mid - 1, j - 1] - sum[i - 1, j + mid - 1] <= K) { lo = mid; } // Else check it in first // half else { hi = mid - 1; } } // Update the maximum size matrix ans = Math.Max(ans, lo); } } // Print the readonly answer Console.Write(ans + "\n"); } // Driver Code public static void Main(String[] args) { int[, ] arr = { { 1, 1, 3, 2, 4, 3, 2 }, { 1, 1, 3, 2, 4, 3, 2 }, { 1, 1, 3, 2, 4, 3, 2 } }; // Given target sum int K = 4; // Function Call findMaxMatrixSize(arr, K); }} // This code is contributed by Amit Katiyar
<script>// js program for the above approach // Function to find the maximum size// of matrix with sum <= Kfunction findMaxMatrixSize(arr, K){ let i, j; // N size of rows and M size of cols let n = arr.length; let m = arr[0].length; // To store the prefix sum of matrix let sum=[]; for(i =0;i<n+1;i++){ sum[i] = []; for(j =0;j<m+1;j++){ sum[i][j] = 0; } } // Create Prefix Sum for ( i = 0; i <= n; i++) { // Traverse each rows for (j = 0; j <= m; j++) { if (i == 0 || j == 0) { sum[i][j] = 0; continue; } // Update the prefix sum // till index i x j sum[i][j] = arr[i - 1][j - 1] + sum[i - 1][j] + sum[i][j - 1] - sum[i - 1][j - 1]; } } // To store the maximum size of // matrix with sum <= K let ans = 0; // Traverse the sum matrix for (i = 1; i <= n; i++) { for (j = 1; j <= m; j++) { // Index out of bound if (i + ans - 1 > n || j + ans - 1 > m) break; let mid, lo = ans; // Maximum possible size // of matrix let hi = Math.min(n - i + 1, m - j + 1); // Binary Search while (lo < hi) { // Find middle index mid = Math.floor((hi + lo + 1) / 2); // Check whether sum <= K // or not // If Yes check for other // half of the search if (sum[i + mid - 1][j + mid - 1] + sum[i - 1][j - 1] - sum[i + mid - 1][j - 1] - sum[i - 1][j + mid - 1] <= K) { lo = mid; } // Else check it in first // half else { hi = mid - 1; } } // Update the maximum size matrix ans = Math.max(ans, lo); } } // Print the final answer document.write(ans ,'<br>');} // Driver Code let arr = [[ 1, 1, 3, 2, 4, 3, 2 ], [ 1, 1, 3, 2, 4, 3, 2 ], [ 1, 1, 3, 2, 4, 3, 2 ]]; // Given target sum let K = 4; // Function Call findMaxMatrixSize(arr, K);</script>
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the maximum size// of matrix with sum <= Kvoid findMaxMatrixSize(vector<vector<int> > arr, int K){ int i, j; // N size of rows and M size of cols int n = arr.size(); int m = arr[0].size(); // To store the prefix sum of matrix int sum[n + 1][m + 1]; // Create Prefix Sum for (int i = 0; i <= n; i++) { // Traverse each rows for (int j = 0; j <= m; j++) { if (i == 0 || j == 0) { sum[i][j] = 0; continue; } // Update the prefix sum // till index i x j sum[i][j] = arr[i - 1][j - 1] + sum[i - 1][j] + sum[i][j - 1] - sum[i - 1][j - 1]; } } // To store the maximum size of // matrix with sum <= K int ans = 0; // Traverse the sum matrix for (i = 1; i <= n; i++) { for (j = 1; j <= m; j++) { // Index out of bound if (i + ans - 1 > n || j + ans - 1 > m) break; int mid, lo = ans; // Maximum possible size // of matrix int hi = min(n - i + 1, m - j + 1); // Binary Search while (lo < hi) { // Find middle index mid = (hi + lo + 1) / 2; // Check whether sum <= K // or not // If Yes check for other // half of the search if (sum[i + mid - 1][j + mid - 1] + sum[i - 1][j - 1] - sum[i + mid - 1][j - 1] - sum[i - 1][j + mid - 1] <= K) { lo = mid; } // Else check it in first // half else { hi = mid - 1; } } // Update the maximum size matrix ans = max(ans, lo); } } // Print the final answer cout << ans << endl;} // Driver Codeint main(){ vector<vector<int> > arr; arr = { { 1, 1, 3, 2, 4, 3, 2 }, { 1, 1, 3, 2, 4, 3, 2 }, { 1, 1, 3, 2, 4, 3, 2 } }; // Given target sum int K = 4; // Function Call findMaxMatrixSize(arr, K); return 0;}
2
Time Complexity: O(N*N*log(N)) Auxiliary Space: O(M*N)
SURENDRA_GANGWAR
29AjayKumar
amit143katiyar
bodhwani
roger2001
rohitsingh07052
harshitkap00r
submatrix
Algorithms
Matrix
Searching
Searching
Matrix
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
Introduction to Algorithms
Playfair Cipher with Examples
How to write a Pseudo Code?
Matrix Chain Multiplication | DP-8
Program to find largest element in an array
Print a given matrix in spiral form
Sudoku | Backtracking-7
Rat in a Maze | Backtracking-2
|
[
{
"code": null,
"e": 25288,
"s": 25260,
"text": "\n19 Jul, 2021"
},
{
"code": null,
"e": 25480,
"s": 25288,
"text": "Given a Matrix arr[][] of size M x N having positive integers and a number K, the task is to find the size of the largest square sub-matrix whose sum of elements is less than or equals to K. "
},
{
"code": null,
"e": 25490,
"s": 25480,
"text": "Example: "
},
{
"code": null,
"e": 26007,
"s": 25490,
"text": "Input: \narr[][] = { { 1, 1, 3, 2, 4, 3, 2 },\n { 1, 1, 3, 2, 4, 3, 2 },\n { 1, 1, 3, 2, 4, 3, 2 } },\nK = 4\nOutput: \n2\nExplanation:\nMaximum size square Sub-Matrix \nwith sum less than or equals to 4\n 1 1\n 1 1\nSize is 2.\n\nInput: \narr[][] = { { 1, 1, 3, 2, 4, 3, 2 },\n { 1, 1, 3, 2, 4, 3, 2 },\n { 1, 1, 3, 2, 4, 3, 2 } }, \nK = 22\nOutput: \n3\nExplanation:\nMaximum size square Sub-Matrix \nwith sum less than or equals to 22\n 1 1 3\n 1 1 3\n 1 1 3\nSize is 3. "
},
{
"code": null,
"e": 26019,
"s": 26007,
"text": "Approach: "
},
{
"code": null,
"e": 26761,
"s": 26019,
"text": "For the given matrix arr[][] create a prefix sum matrix(say sum[][]) such that sum[i][j] stores the sum of all the elements of the matrix of size i x j.For each row in prefix sum matrix sum[][] using Binary Search do the following: Perform Binary search with the lower limit as 0 end the upper limit as to maximum size of square matrix.Find the middle index (say mid).If the sum of elements of all possible square matrix of size mid is less than or equals to K, then update the lower limit as mid + 1 to find the maximum sum with size greater than mid.Else Update the upper limit as mid – 1 to find the maximum sum with size less than mid.Keep updating the maximum size of square matrix in each iteration for the given valid condition above."
},
{
"code": null,
"e": 26914,
"s": 26761,
"text": "For the given matrix arr[][] create a prefix sum matrix(say sum[][]) such that sum[i][j] stores the sum of all the elements of the matrix of size i x j."
},
{
"code": null,
"e": 27402,
"s": 26914,
"text": "For each row in prefix sum matrix sum[][] using Binary Search do the following: Perform Binary search with the lower limit as 0 end the upper limit as to maximum size of square matrix.Find the middle index (say mid).If the sum of elements of all possible square matrix of size mid is less than or equals to K, then update the lower limit as mid + 1 to find the maximum sum with size greater than mid.Else Update the upper limit as mid – 1 to find the maximum sum with size less than mid."
},
{
"code": null,
"e": 27507,
"s": 27402,
"text": "Perform Binary search with the lower limit as 0 end the upper limit as to maximum size of square matrix."
},
{
"code": null,
"e": 27540,
"s": 27507,
"text": "Find the middle index (say mid)."
},
{
"code": null,
"e": 27725,
"s": 27540,
"text": "If the sum of elements of all possible square matrix of size mid is less than or equals to K, then update the lower limit as mid + 1 to find the maximum sum with size greater than mid."
},
{
"code": null,
"e": 27813,
"s": 27725,
"text": "Else Update the upper limit as mid – 1 to find the maximum sum with size less than mid."
},
{
"code": null,
"e": 27916,
"s": 27813,
"text": "Keep updating the maximum size of square matrix in each iteration for the given valid condition above."
},
{
"code": null,
"e": 27969,
"s": 27916,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27974,
"s": 27969,
"text": "Java"
},
{
"code": null,
"e": 27982,
"s": 27974,
"text": "Python3"
},
{
"code": null,
"e": 27985,
"s": 27982,
"text": "C#"
},
{
"code": null,
"e": 27996,
"s": 27985,
"text": "Javascript"
},
{
"code": null,
"e": 28000,
"s": 27996,
"text": "C++"
},
{
"code": "// Java program for the above approachimport java.util.*; class GFG { // Function to find the maximum size // of matrix with sum <= K static void findMaxMatrixSize(int[][] arr, int K) { int i, j; // N size of rows and M size of cols int n = arr.length; int m = arr[0].length; // To store the prefix sum of matrix int[][] sum = new int[n + 1][m + 1]; // Create prefix sum for (i = 0; i <= n; i++) { // Traverse each rows for (j = 0; j <= m; j++) { if (i == 0 || j == 0) { sum[i][j] = 0; continue; } // Update the prefix sum // till index i x j sum[i][j] = arr[i - 1][j - 1] + sum[i - 1][j] + sum[i][j - 1] - sum[i - 1][j - 1]; } } // To store the maximum size of // matrix with sum <= K int ans = 0; // Traverse the sum matrix for (i = 1; i <= n; i++) { for (j = 1; j <= m; j++) { // Index out of bound if (i + ans - 1 > n || j + ans - 1 > m) break; int mid, lo = ans; // Maximum possible size // of matrix int hi = Math.min(n - i + 1, m - j + 1); // Binary Search while (lo < hi) { // Find middle index mid = (hi + lo + 1) / 2; // Check whether sum <= K // or not // If Yes check for other // half of the search if (sum[i + mid - 1][j + mid - 1] + sum[i - 1][j - 1] - sum[i + mid - 1][j - 1] - sum[i - 1][j + mid - 1] <= K) { lo = mid; } // Else check it in first // half else { hi = mid - 1; } } // Update the maximum size matrix ans = Math.max(ans, lo); } } // Print the final answer System.out.print(ans + \"\\n\"); } // Driver Code public static void main(String[] args) { int[][] arr = { { 1, 1, 3, 2, 4, 3, 2 }, { 1, 1, 3, 2, 4, 3, 2 }, { 1, 1, 3, 2, 4, 3, 2 } }; // Given target sum int K = 4; // Function Call findMaxMatrixSize(arr, K); }} // This code is contributed by 29AjayKumar",
"e": 30719,
"s": 28000,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to find the maximum size# of matrix with sum <= K def findMaxMatrixSize(arr, K): # N size of rows and M size of cols n = len(arr) m = len(arr[0]) # To store the prefix sum of matrix sum = [[0 for i in range(m + 1)] for j in range(n + 1)] # Create Prefix Sum for i in range(n + 1): # Traverse each rows for j in range(m+1): if (i == 0 or j == 0): sum[i][j] = 0 continue # Update the prefix sum # till index i x j sum[i][j] = arr[i - 1][j - 1] + sum[i - 1][j] + \\ sum[i][j - 1]-sum[i - 1][j - 1] # To store the maximum size of # matrix with sum <= K ans = 0 # Traverse the sum matrix for i in range(1, n + 1): for j in range(1, m + 1): # Index out of bound if (i + ans - 1 > n or j + ans - 1 > m): break mid = ans lo = ans # Maximum possible size # of matrix hi = min(n - i + 1, m - j + 1) # Binary Search while (lo < hi): # Find middle index mid = (hi + lo + 1) // 2 # Check whether sum <= K # or not # If Yes check for other # half of the search if (sum[i + mid - 1][j + mid - 1] + sum[i - 1][j - 1] - sum[i + mid - 1][j - 1] - sum[i - 1][j + mid - 1] <= K): lo = mid # Else check it in first # half else: hi = mid - 1 # Update the maximum size matrix ans = max(ans, lo) # Print the final answer print(ans) # Driver Codeif __name__ == '__main__': arr = [[1, 1, 3, 2, 4, 3, 2], [1, 1, 3, 2, 4, 3, 2], [1, 1, 3, 2, 4, 3, 2]] # Given target sum K = 4 # Function Call findMaxMatrixSize(arr, K) # This code is contributed by Surendra_Gangwar",
"e": 32800,
"s": 30719,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG { // Function to find the maximum size // of matrix with sum <= K static void findMaxMatrixSize(int[, ] arr, int K) { int i, j; // N size of rows and M size of cols int n = arr.GetLength(0); int m = arr.GetLength(1); // To store the prefix sum of matrix int[, ] sum = new int[n + 1, m + 1]; // Create prefix sum for (i = 0; i <= n; i++) { // Traverse each rows for (j = 0; j <= m; j++) { if (i == 0 || j == 0) { sum[i, j] = 0; continue; } // Update the prefix sum // till index i x j sum[i, j] = arr[i - 1, j - 1] + sum[i - 1, j] + sum[i, j - 1] - sum[i - 1, j - 1]; } } // To store the maximum size // of matrix with sum <= K int ans = 0; // Traverse the sum matrix for (i = 1; i <= n; i++) { for (j = 1; j <= m; j++) { // Index out of bound if (i + ans - 1 > n || j + ans - 1 > m) break; int mid, lo = ans; // Maximum possible size // of matrix int hi = Math.Min(n - i + 1, m - j + 1); // Binary Search while (lo < hi) { // Find middle index mid = (hi + lo + 1) / 2; // Check whether sum <= K // or not // If Yes check for other // half of the search if (sum[i + mid - 1, j + mid - 1] + sum[i - 1, j - 1] - sum[i + mid - 1, j - 1] - sum[i - 1, j + mid - 1] <= K) { lo = mid; } // Else check it in first // half else { hi = mid - 1; } } // Update the maximum size matrix ans = Math.Max(ans, lo); } } // Print the readonly answer Console.Write(ans + \"\\n\"); } // Driver Code public static void Main(String[] args) { int[, ] arr = { { 1, 1, 3, 2, 4, 3, 2 }, { 1, 1, 3, 2, 4, 3, 2 }, { 1, 1, 3, 2, 4, 3, 2 } }; // Given target sum int K = 4; // Function Call findMaxMatrixSize(arr, K); }} // This code is contributed by Amit Katiyar",
"e": 35521,
"s": 32800,
"text": null
},
{
"code": "<script>// js program for the above approach // Function to find the maximum size// of matrix with sum <= Kfunction findMaxMatrixSize(arr, K){ let i, j; // N size of rows and M size of cols let n = arr.length; let m = arr[0].length; // To store the prefix sum of matrix let sum=[]; for(i =0;i<n+1;i++){ sum[i] = []; for(j =0;j<m+1;j++){ sum[i][j] = 0; } } // Create Prefix Sum for ( i = 0; i <= n; i++) { // Traverse each rows for (j = 0; j <= m; j++) { if (i == 0 || j == 0) { sum[i][j] = 0; continue; } // Update the prefix sum // till index i x j sum[i][j] = arr[i - 1][j - 1] + sum[i - 1][j] + sum[i][j - 1] - sum[i - 1][j - 1]; } } // To store the maximum size of // matrix with sum <= K let ans = 0; // Traverse the sum matrix for (i = 1; i <= n; i++) { for (j = 1; j <= m; j++) { // Index out of bound if (i + ans - 1 > n || j + ans - 1 > m) break; let mid, lo = ans; // Maximum possible size // of matrix let hi = Math.min(n - i + 1, m - j + 1); // Binary Search while (lo < hi) { // Find middle index mid = Math.floor((hi + lo + 1) / 2); // Check whether sum <= K // or not // If Yes check for other // half of the search if (sum[i + mid - 1][j + mid - 1] + sum[i - 1][j - 1] - sum[i + mid - 1][j - 1] - sum[i - 1][j + mid - 1] <= K) { lo = mid; } // Else check it in first // half else { hi = mid - 1; } } // Update the maximum size matrix ans = Math.max(ans, lo); } } // Print the final answer document.write(ans ,'<br>');} // Driver Code let arr = [[ 1, 1, 3, 2, 4, 3, 2 ], [ 1, 1, 3, 2, 4, 3, 2 ], [ 1, 1, 3, 2, 4, 3, 2 ]]; // Given target sum let K = 4; // Function Call findMaxMatrixSize(arr, K);</script>",
"e": 37870,
"s": 35521,
"text": null
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the maximum size// of matrix with sum <= Kvoid findMaxMatrixSize(vector<vector<int> > arr, int K){ int i, j; // N size of rows and M size of cols int n = arr.size(); int m = arr[0].size(); // To store the prefix sum of matrix int sum[n + 1][m + 1]; // Create Prefix Sum for (int i = 0; i <= n; i++) { // Traverse each rows for (int j = 0; j <= m; j++) { if (i == 0 || j == 0) { sum[i][j] = 0; continue; } // Update the prefix sum // till index i x j sum[i][j] = arr[i - 1][j - 1] + sum[i - 1][j] + sum[i][j - 1] - sum[i - 1][j - 1]; } } // To store the maximum size of // matrix with sum <= K int ans = 0; // Traverse the sum matrix for (i = 1; i <= n; i++) { for (j = 1; j <= m; j++) { // Index out of bound if (i + ans - 1 > n || j + ans - 1 > m) break; int mid, lo = ans; // Maximum possible size // of matrix int hi = min(n - i + 1, m - j + 1); // Binary Search while (lo < hi) { // Find middle index mid = (hi + lo + 1) / 2; // Check whether sum <= K // or not // If Yes check for other // half of the search if (sum[i + mid - 1][j + mid - 1] + sum[i - 1][j - 1] - sum[i + mid - 1][j - 1] - sum[i - 1][j + mid - 1] <= K) { lo = mid; } // Else check it in first // half else { hi = mid - 1; } } // Update the maximum size matrix ans = max(ans, lo); } } // Print the final answer cout << ans << endl;} // Driver Codeint main(){ vector<vector<int> > arr; arr = { { 1, 1, 3, 2, 4, 3, 2 }, { 1, 1, 3, 2, 4, 3, 2 }, { 1, 1, 3, 2, 4, 3, 2 } }; // Given target sum int K = 4; // Function Call findMaxMatrixSize(arr, K); return 0;}",
"e": 40202,
"s": 37870,
"text": null
},
{
"code": null,
"e": 40204,
"s": 40202,
"text": "2"
},
{
"code": null,
"e": 40259,
"s": 40204,
"text": "Time Complexity: O(N*N*log(N)) Auxiliary Space: O(M*N)"
},
{
"code": null,
"e": 40276,
"s": 40259,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 40288,
"s": 40276,
"text": "29AjayKumar"
},
{
"code": null,
"e": 40303,
"s": 40288,
"text": "amit143katiyar"
},
{
"code": null,
"e": 40312,
"s": 40303,
"text": "bodhwani"
},
{
"code": null,
"e": 40322,
"s": 40312,
"text": "roger2001"
},
{
"code": null,
"e": 40338,
"s": 40322,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 40352,
"s": 40338,
"text": "harshitkap00r"
},
{
"code": null,
"e": 40362,
"s": 40352,
"text": "submatrix"
},
{
"code": null,
"e": 40373,
"s": 40362,
"text": "Algorithms"
},
{
"code": null,
"e": 40380,
"s": 40373,
"text": "Matrix"
},
{
"code": null,
"e": 40390,
"s": 40380,
"text": "Searching"
},
{
"code": null,
"e": 40400,
"s": 40390,
"text": "Searching"
},
{
"code": null,
"e": 40407,
"s": 40400,
"text": "Matrix"
},
{
"code": null,
"e": 40418,
"s": 40407,
"text": "Algorithms"
},
{
"code": null,
"e": 40516,
"s": 40418,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40525,
"s": 40516,
"text": "Comments"
},
{
"code": null,
"e": 40538,
"s": 40525,
"text": "Old Comments"
},
{
"code": null,
"e": 40587,
"s": 40538,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 40612,
"s": 40587,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 40639,
"s": 40612,
"text": "Introduction to Algorithms"
},
{
"code": null,
"e": 40669,
"s": 40639,
"text": "Playfair Cipher with Examples"
},
{
"code": null,
"e": 40697,
"s": 40669,
"text": "How to write a Pseudo Code?"
},
{
"code": null,
"e": 40732,
"s": 40697,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 40776,
"s": 40732,
"text": "Program to find largest element in an array"
},
{
"code": null,
"e": 40812,
"s": 40776,
"text": "Print a given matrix in spiral form"
},
{
"code": null,
"e": 40836,
"s": 40812,
"text": "Sudoku | Backtracking-7"
}
] |
Check if the given graph represents a Bus Topology - GeeksforGeeks
|
21 Feb, 2022
Given a graph G, check if it represents a Bus Topology.A Bus Topology is the one shown in the image below:
Examples:
Input:
Output: YES
Input:
Output: NO
A graph of V vertices represents a bus topology if it satisfies the following two conditions:
Each node except the starting end ending ones has degree 2 while the starting and ending have degree 1.No of edges = No of Vertices – 1.
Each node except the starting end ending ones has degree 2 while the starting and ending have degree 1.
No of edges = No of Vertices – 1.
The idea is to traverse the graph and check if it satisfies the above two conditions. If yes, then it represents a Bus Topology.Below is the implementation of the above approach:
CPP
Java
Python3
C#
Javascript
// CPP program to check if the given graph// represents a bus topology#include <bits/stdc++.h>using namespace std; // A utility function to add an edge in an// undirected graph.void addEdge(vector<int> adj[], int u, int v){ adj[u].push_back(v); adj[v].push_back(u);} // A utility function to print the adjacency list// representation of graphvoid printGraph(vector<int> adj[], int V){ for (int v = 0; v < V; ++v) { cout << "\n Adjacency list of vertex " << v << "\n head "; for (auto x : adj[v]) cout << "-> " << x; printf("\n"); }} /* Function to return true if the graph represented by the adjacency list represents a bus topology else return false */bool checkBusTopologyUtil(vector<int> adj[], int V, int E){ // Number of edges should be equal // to (Number of vertices - 1) if (E != (V - 1)) return false; // a single node is termed as a bus topology if (V == 1) return true; int* vertexDegree = new int[V + 1]; memset(vertexDegree, 0, sizeof vertexDegree); // calculate the degree of each vertex for (int i = 1; i <= V; i++) { for (auto v : adj[i]) { vertexDegree[v]++; } } // countDegree2 - number of vertices with degree 2 // countDegree1 - number of vertices with degree 1 int countDegree2 = 0, countDegree1 = 0; for (int i = 1; i <= V; i++) { if (vertexDegree[i] == 2) { countDegree2++; } else if (vertexDegree[i] == 1) { countDegree1++; } else { // if any node has degree other // than 1 or 2, it is // NOT a bus topology return false; } } // if both necessary conditions as discussed, // satisfy return true if (countDegree1 == 2 && countDegree2 == (V - 2)) { return true; } return false;} // Function to check if the graph represents a bus topologyvoid checkBusTopology(vector<int> adj[], int V, int E){ bool isBus = checkBusTopologyUtil(adj, V, E); if (isBus) { cout << "YES" << endl; } else { cout << "NO" << endl; }} // Driver codeint main(){ // Graph 1 int V = 5, E = 4; vector<int> adj1[V + 1]; addEdge(adj1, 1, 2); addEdge(adj1, 1, 3); addEdge(adj1, 3, 4); addEdge(adj1, 4, 5); checkBusTopology(adj1, V, E); // Graph 2 V = 4, E = 4; vector<int> adj2[V + 1]; addEdge(adj2, 1, 2); addEdge(adj2, 1, 3); addEdge(adj2, 3, 4); addEdge(adj2, 4, 2); checkBusTopology(adj2, V, E); return 0;}
// java program to check if the given graph// represents a bus topologyimport java.io.*;import java.util.*; class GFG{ // A utility function to add an edge in an // undirected graph. static void addEdge(ArrayList<ArrayList<Integer>> adj, int u, int v) { adj.get(u).add(v); adj.get(v).add(u); } // A utility function to print the adjacency list // representation of graph static void printGraph(ArrayList<ArrayList<Integer>> adj, int V) { for (int v = 0; v < V; ++v) { System.out.print("\n Adjacency list of vertex " + v + "\n head "); for (int x : adj.get(v)) { System.out.print( "-> " + x); } System.out.println(); } } /* Function to return true if the graph represented by the adjacency list represents a bus topology else return false */ static boolean checkBusTopologyUtil(ArrayList<ArrayList<Integer>> adj, int V, int E) { // Number of edges should be equal // to (Number of vertices - 1) if (E != (V - 1)) { return false; } // a single node is termed as a bus topology if (V == 1) { return true; } int[] vertexDegree = new int[V + 1]; // calculate the degree of each vertex for (int i = 1; i <= V; i++) { for (int v : adj.get(i)) { vertexDegree[v]++; } } // countDegree2 - number of vertices with degree 2 // countDegree1 - number of vertices with degree 1 int countDegree2 = 0, countDegree1 = 0; for (int i = 1; i <= V; i++) { if (vertexDegree[i] == 2) { countDegree2++; } else if (vertexDegree[i] == 1) { countDegree1++; } else { // if any node has degree other // than 1 or 2, it is // NOT a bus topology return false; } } // if both necessary conditions as discussed, // satisfy return true if (countDegree1 == 2 && countDegree2 == (V - 2)) { return true; } return false; } // Function to check if the graph represents a bus topology static void checkBusTopology(ArrayList<ArrayList<Integer>> adj, int V, int E) { boolean isBus = checkBusTopologyUtil(adj, V, E); if (isBus) { System.out.println("YES"); } else { System.out.println("NO"); } } // Driver code public static void main (String[] args) { // Graph 1 int V = 5, E = 4; ArrayList<ArrayList<Integer>> adj1= new ArrayList<ArrayList<Integer>>(); for(int i = 0; i < V + 1; i++) { adj1.add(new ArrayList<Integer>()); } addEdge(adj1, 1, 2); addEdge(adj1, 1, 3); addEdge(adj1, 3, 4); addEdge(adj1, 4, 5); checkBusTopology(adj1, V, E); // Graph 2 V = 4; E = 4; ArrayList<ArrayList<Integer>> adj2 = new ArrayList<ArrayList<Integer>>(); for(int i = 0; i < (V + 1); i++) { adj2.add(new ArrayList<Integer>()); } addEdge(adj2, 1, 2); addEdge(adj2, 1, 3); addEdge(adj2, 3, 4); addEdge(adj2, 4, 2); checkBusTopology(adj2, V, E); }} // This code is contributed by rag2127
# Python3 program to check if the given graph# represents a bus topology # A utility function to add an edge in an# undirected graph.def addEdge(adj, u, v): adj[u].append(v) adj[v].append(u) # A utility function to print the adjacency list# representation of graphdef printGraph(adj, V): for v in range(V): print("Adjacency list of vertex ",v,"\n head ") for x in adj[v]: print("-> ",x,end=" ") printf() # /* Function to return true if the graph represented# by the adjacency list represents a bus topology# else return false */def checkBusTopologyUtil(adj, V, E): # Number of edges should be equal # to (Number of vertices - 1) if (E != (V - 1)): return False # a single node is termed as a bus topology if (V == 1): return True vertexDegree = [0]*(V + 1) # calculate the degree of each vertex for i in range(V + 1): for v in adj[i]: vertexDegree[v] += 1 # countDegree2 - number of vertices with degree 2 # countDegree1 - number of vertices with degree 1 countDegree2,countDegree1 = 0,0 for i in range(1, V + 1): if (vertexDegree[i] == 2): countDegree2 += 1 elif (vertexDegree[i] == 1): countDegree1 += 1 else: # if any node has degree other # than 1 or 2, it is # NOT a bus topology return False # if both necessary conditions as discussed, # satisfy return true if (countDegree1 == 2 and countDegree2 == (V - 2)): return True return False # Function to check if the graph represents a bus topologydef checkBusTopology(adj, V, E): isBus = checkBusTopologyUtil(adj, V, E) if (isBus): print("YES") else: print("NO" ) # Driver code # Graph 1V, E = 5, 4adj1 = [[] for i in range(V + 1)]addEdge(adj1, 1, 2)addEdge(adj1, 1, 3)addEdge(adj1, 3, 4)addEdge(adj1, 4, 5)checkBusTopology(adj1, V, E) # Graph 2V, E = 4, 4adj2 = [[] for i in range(V + 1)]addEdge(adj2, 1, 2)addEdge(adj2, 1, 3)addEdge(adj2, 3, 4)addEdge(adj2, 4, 2)checkBusTopology(adj2, V, E) # This code is contributed by mohit kumar 29
// C# program to check if the given graph// represents a bus topologyusing System;using System.Collections.Generic; public class GFG{ // A utility function to add an edge in an // undirected graph. static void addEdge(List<List<int>> adj, int u, int v) { adj[u].Add(v); adj[v].Add(u); } // A utility function to print the adjacency list // representation of graph static void printGraph(List<List<int>> adj, int V) { for (int v = 0; v < V; ++v) { Console.WriteLine("\n Adjacency list of vertex " + v + "\n head "); foreach (int x in adj[v]) { Console.Write( "-> " + x); } Console.WriteLine(); } } /* Function to return true if the graph represented by the adjacency list represents a bus topology else return false */ static bool checkBusTopologyUtil(List<List<int>> adj, int V, int E) { // Number of edges should be equal // to (Number of vertices - 1) if (E != (V - 1)) { return false; } // a single node is termed as a bus topology if (V == 1) { return true; } int[] vertexDegree = new int[V + 1]; // calculate the degree of each vertex for (int i = 1; i <= V; i++) { foreach (int v in adj[i]) { vertexDegree[v]++; } } // countDegree2 - number of vertices with degree 2 // countDegree1 - number of vertices with degree 1 int countDegree2 = 0, countDegree1 = 0; for (int i = 1; i <= V; i++) { if (vertexDegree[i] == 2) { countDegree2++; } else if (vertexDegree[i] == 1) { countDegree1++; } else { // if any node has degree other // than 1 or 2, it is // NOT a bus topology return false; } } // if both necessary conditions as discussed, // satisfy return true if (countDegree1 == 2 && countDegree2 == (V - 2)) { return true; } return false; } // Function to check if the graph represents a bus topology static void checkBusTopology(List<List<int>> adj, int V, int E) { bool isBus = checkBusTopologyUtil(adj, V, E); if (isBus) { Console.WriteLine("YES"); } else { Console.WriteLine("NO"); } } // Driver code static public void Main () { // Graph 1 int V = 5, E = 4; List<List<int>> adj1 = new List<List<int>>(); for(int i = 0; i < V + 1; i++) { adj1.Add(new List<int>()); } addEdge(adj1, 1, 2); addEdge(adj1, 1, 3); addEdge(adj1, 3, 4); addEdge(adj1, 4, 5); checkBusTopology(adj1, V, E); // Graph 2 V = 4; E = 4; List<List<int>> adj2 = new List<List<int>>(); for(int i = 0; i < V + 1; i++) { adj2.Add(new List<int>()); } addEdge(adj2, 1, 2); addEdge(adj2, 1, 3); addEdge(adj2, 3, 4); addEdge(adj2, 4, 2); checkBusTopology(adj2, V, E); }} // This code is contributed by avanitrachhadiya2155
<script> // JavaScript program to check if the given graph// represents a bus topology // A utility function to add an edge in an // undirected graph.function addEdge(adj,u,v){ adj[u].push(v); adj[v].push(u);} // A utility function to print the adjacency list // representation of graphfunction printGraph(adj,V){ for (let v = 0; v < V; ++v) { document.write("\n Adjacency list of vertex " + v + "\n head "); for (let x=0;x<adj[v].length;x++) { document.write( "-> " + adj[v][x]); } document.write("<br>"); }} /* Function to return true if the graph represented by the adjacency list represents a bus topology else return false */function checkBusTopologyUtil(adj,V,E){ // Number of edges should be equal // to (Number of vertices - 1) if (E != (V - 1)) { return false; } // a single node is termed as a bus topology if (V == 1) { return true; } let vertexDegree = new Array(V + 1); for(let i=0;i<vertexDegree.length;i++) { vertexDegree[i]=0; } // calculate the degree of each vertex for (let i = 1; i <= V; i++) { for (let v=0;v<adj[i].length;v++) { vertexDegree[adj[i][v]]++; } } // countDegree2 - number of vertices with degree 2 // countDegree1 - number of vertices with degree 1 let countDegree2 = 0, countDegree1 = 0; for (let i = 1; i <= V; i++) { if (vertexDegree[i] == 2) { countDegree2++; } else if (vertexDegree[i] == 1) { countDegree1++; } else { // if any node has degree other // than 1 or 2, it is // NOT a bus topology return false; } } // if both necessary conditions as discussed, // satisfy return true if (countDegree1 == 2 && countDegree2 == (V - 2)) { return true; } return false;} // Function to check if the graph represents a bus topologyfunction checkBusTopology(adj,V,E){ let isBus = checkBusTopologyUtil(adj, V, E); if (isBus) { document.write("YES<br>"); } else { document.write("NO<br>"); }} // Driver code // Graph 1 let V = 5, E = 4; let adj1=[]; for(let i = 0; i < V + 1; i++) { adj1.push([]); } addEdge(adj1, 1, 2); addEdge(adj1, 1, 3); addEdge(adj1, 3, 4); addEdge(adj1, 4, 5); checkBusTopology(adj1, V, E); // Graph 2 V = 4; E = 4; let adj2 = []; for(let i = 0; i < (V + 1); i++) { adj2.push([]); } addEdge(adj2, 1, 2); addEdge(adj2, 1, 3); addEdge(adj2, 3, 4); addEdge(adj2, 4, 2); checkBusTopology(adj2, V, E); // This code is contributed by patel2127 </script>
YES
NO
Time Complexity : O(E), where E is the number of Edges in the graph.Auxiliary Space: O(1).
mohit kumar 29
Code_Mech
rag2127
avanitrachhadiya2155
patel2127
pankajsharmagfg
varshagumber28
graph-connectivity
Competitive Programming
Data Structures
Graph
Data Structures
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ordered Set and GNU C++ PBDS
Bits manipulation (Important tactics)
What is Competitive Programming and How to Prepare for It?
7 Best Coding Challenge Websites in 2020
Formatted output in Java
SDE SHEET - A Complete Guide for SDE Preparation
Top 50 Array Coding Problems for Interviews
DSA Sheet by Love Babbar
Doubly Linked List | Set 1 (Introduction and Insertion)
How to Start Learning DSA?
|
[
{
"code": null,
"e": 26761,
"s": 26733,
"text": "\n21 Feb, 2022"
},
{
"code": null,
"e": 26870,
"s": 26761,
"text": "Given a graph G, check if it represents a Bus Topology.A Bus Topology is the one shown in the image below: "
},
{
"code": null,
"e": 26882,
"s": 26870,
"text": "Examples: "
},
{
"code": null,
"e": 26890,
"s": 26882,
"text": "Input: "
},
{
"code": null,
"e": 26912,
"s": 26890,
"text": "Output: YES\n\nInput: "
},
{
"code": null,
"e": 26924,
"s": 26912,
"text": "Output: NO"
},
{
"code": null,
"e": 27020,
"s": 26924,
"text": "A graph of V vertices represents a bus topology if it satisfies the following two conditions: "
},
{
"code": null,
"e": 27157,
"s": 27020,
"text": "Each node except the starting end ending ones has degree 2 while the starting and ending have degree 1.No of edges = No of Vertices – 1."
},
{
"code": null,
"e": 27261,
"s": 27157,
"text": "Each node except the starting end ending ones has degree 2 while the starting and ending have degree 1."
},
{
"code": null,
"e": 27295,
"s": 27261,
"text": "No of edges = No of Vertices – 1."
},
{
"code": null,
"e": 27476,
"s": 27295,
"text": "The idea is to traverse the graph and check if it satisfies the above two conditions. If yes, then it represents a Bus Topology.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27480,
"s": 27476,
"text": "CPP"
},
{
"code": null,
"e": 27485,
"s": 27480,
"text": "Java"
},
{
"code": null,
"e": 27493,
"s": 27485,
"text": "Python3"
},
{
"code": null,
"e": 27496,
"s": 27493,
"text": "C#"
},
{
"code": null,
"e": 27507,
"s": 27496,
"text": "Javascript"
},
{
"code": "// CPP program to check if the given graph// represents a bus topology#include <bits/stdc++.h>using namespace std; // A utility function to add an edge in an// undirected graph.void addEdge(vector<int> adj[], int u, int v){ adj[u].push_back(v); adj[v].push_back(u);} // A utility function to print the adjacency list// representation of graphvoid printGraph(vector<int> adj[], int V){ for (int v = 0; v < V; ++v) { cout << \"\\n Adjacency list of vertex \" << v << \"\\n head \"; for (auto x : adj[v]) cout << \"-> \" << x; printf(\"\\n\"); }} /* Function to return true if the graph represented by the adjacency list represents a bus topology else return false */bool checkBusTopologyUtil(vector<int> adj[], int V, int E){ // Number of edges should be equal // to (Number of vertices - 1) if (E != (V - 1)) return false; // a single node is termed as a bus topology if (V == 1) return true; int* vertexDegree = new int[V + 1]; memset(vertexDegree, 0, sizeof vertexDegree); // calculate the degree of each vertex for (int i = 1; i <= V; i++) { for (auto v : adj[i]) { vertexDegree[v]++; } } // countDegree2 - number of vertices with degree 2 // countDegree1 - number of vertices with degree 1 int countDegree2 = 0, countDegree1 = 0; for (int i = 1; i <= V; i++) { if (vertexDegree[i] == 2) { countDegree2++; } else if (vertexDegree[i] == 1) { countDegree1++; } else { // if any node has degree other // than 1 or 2, it is // NOT a bus topology return false; } } // if both necessary conditions as discussed, // satisfy return true if (countDegree1 == 2 && countDegree2 == (V - 2)) { return true; } return false;} // Function to check if the graph represents a bus topologyvoid checkBusTopology(vector<int> adj[], int V, int E){ bool isBus = checkBusTopologyUtil(adj, V, E); if (isBus) { cout << \"YES\" << endl; } else { cout << \"NO\" << endl; }} // Driver codeint main(){ // Graph 1 int V = 5, E = 4; vector<int> adj1[V + 1]; addEdge(adj1, 1, 2); addEdge(adj1, 1, 3); addEdge(adj1, 3, 4); addEdge(adj1, 4, 5); checkBusTopology(adj1, V, E); // Graph 2 V = 4, E = 4; vector<int> adj2[V + 1]; addEdge(adj2, 1, 2); addEdge(adj2, 1, 3); addEdge(adj2, 3, 4); addEdge(adj2, 4, 2); checkBusTopology(adj2, V, E); return 0;}",
"e": 30071,
"s": 27507,
"text": null
},
{
"code": "// java program to check if the given graph// represents a bus topologyimport java.io.*;import java.util.*; class GFG{ // A utility function to add an edge in an // undirected graph. static void addEdge(ArrayList<ArrayList<Integer>> adj, int u, int v) { adj.get(u).add(v); adj.get(v).add(u); } // A utility function to print the adjacency list // representation of graph static void printGraph(ArrayList<ArrayList<Integer>> adj, int V) { for (int v = 0; v < V; ++v) { System.out.print(\"\\n Adjacency list of vertex \" + v + \"\\n head \"); for (int x : adj.get(v)) { System.out.print( \"-> \" + x); } System.out.println(); } } /* Function to return true if the graph represented by the adjacency list represents a bus topology else return false */ static boolean checkBusTopologyUtil(ArrayList<ArrayList<Integer>> adj, int V, int E) { // Number of edges should be equal // to (Number of vertices - 1) if (E != (V - 1)) { return false; } // a single node is termed as a bus topology if (V == 1) { return true; } int[] vertexDegree = new int[V + 1]; // calculate the degree of each vertex for (int i = 1; i <= V; i++) { for (int v : adj.get(i)) { vertexDegree[v]++; } } // countDegree2 - number of vertices with degree 2 // countDegree1 - number of vertices with degree 1 int countDegree2 = 0, countDegree1 = 0; for (int i = 1; i <= V; i++) { if (vertexDegree[i] == 2) { countDegree2++; } else if (vertexDegree[i] == 1) { countDegree1++; } else { // if any node has degree other // than 1 or 2, it is // NOT a bus topology return false; } } // if both necessary conditions as discussed, // satisfy return true if (countDegree1 == 2 && countDegree2 == (V - 2)) { return true; } return false; } // Function to check if the graph represents a bus topology static void checkBusTopology(ArrayList<ArrayList<Integer>> adj, int V, int E) { boolean isBus = checkBusTopologyUtil(adj, V, E); if (isBus) { System.out.println(\"YES\"); } else { System.out.println(\"NO\"); } } // Driver code public static void main (String[] args) { // Graph 1 int V = 5, E = 4; ArrayList<ArrayList<Integer>> adj1= new ArrayList<ArrayList<Integer>>(); for(int i = 0; i < V + 1; i++) { adj1.add(new ArrayList<Integer>()); } addEdge(adj1, 1, 2); addEdge(adj1, 1, 3); addEdge(adj1, 3, 4); addEdge(adj1, 4, 5); checkBusTopology(adj1, V, E); // Graph 2 V = 4; E = 4; ArrayList<ArrayList<Integer>> adj2 = new ArrayList<ArrayList<Integer>>(); for(int i = 0; i < (V + 1); i++) { adj2.add(new ArrayList<Integer>()); } addEdge(adj2, 1, 2); addEdge(adj2, 1, 3); addEdge(adj2, 3, 4); addEdge(adj2, 4, 2); checkBusTopology(adj2, V, E); }} // This code is contributed by rag2127",
"e": 33105,
"s": 30071,
"text": null
},
{
"code": "# Python3 program to check if the given graph# represents a bus topology # A utility function to add an edge in an# undirected graph.def addEdge(adj, u, v): adj[u].append(v) adj[v].append(u) # A utility function to print the adjacency list# representation of graphdef printGraph(adj, V): for v in range(V): print(\"Adjacency list of vertex \",v,\"\\n head \") for x in adj[v]: print(\"-> \",x,end=\" \") printf() # /* Function to return true if the graph represented# by the adjacency list represents a bus topology# else return false */def checkBusTopologyUtil(adj, V, E): # Number of edges should be equal # to (Number of vertices - 1) if (E != (V - 1)): return False # a single node is termed as a bus topology if (V == 1): return True vertexDegree = [0]*(V + 1) # calculate the degree of each vertex for i in range(V + 1): for v in adj[i]: vertexDegree[v] += 1 # countDegree2 - number of vertices with degree 2 # countDegree1 - number of vertices with degree 1 countDegree2,countDegree1 = 0,0 for i in range(1, V + 1): if (vertexDegree[i] == 2): countDegree2 += 1 elif (vertexDegree[i] == 1): countDegree1 += 1 else: # if any node has degree other # than 1 or 2, it is # NOT a bus topology return False # if both necessary conditions as discussed, # satisfy return true if (countDegree1 == 2 and countDegree2 == (V - 2)): return True return False # Function to check if the graph represents a bus topologydef checkBusTopology(adj, V, E): isBus = checkBusTopologyUtil(adj, V, E) if (isBus): print(\"YES\") else: print(\"NO\" ) # Driver code # Graph 1V, E = 5, 4adj1 = [[] for i in range(V + 1)]addEdge(adj1, 1, 2)addEdge(adj1, 1, 3)addEdge(adj1, 3, 4)addEdge(adj1, 4, 5)checkBusTopology(adj1, V, E) # Graph 2V, E = 4, 4adj2 = [[] for i in range(V + 1)]addEdge(adj2, 1, 2)addEdge(adj2, 1, 3)addEdge(adj2, 3, 4)addEdge(adj2, 4, 2)checkBusTopology(adj2, V, E) # This code is contributed by mohit kumar 29",
"e": 35247,
"s": 33105,
"text": null
},
{
"code": "// C# program to check if the given graph// represents a bus topologyusing System;using System.Collections.Generic; public class GFG{ // A utility function to add an edge in an // undirected graph. static void addEdge(List<List<int>> adj, int u, int v) { adj[u].Add(v); adj[v].Add(u); } // A utility function to print the adjacency list // representation of graph static void printGraph(List<List<int>> adj, int V) { for (int v = 0; v < V; ++v) { Console.WriteLine(\"\\n Adjacency list of vertex \" + v + \"\\n head \"); foreach (int x in adj[v]) { Console.Write( \"-> \" + x); } Console.WriteLine(); } } /* Function to return true if the graph represented by the adjacency list represents a bus topology else return false */ static bool checkBusTopologyUtil(List<List<int>> adj, int V, int E) { // Number of edges should be equal // to (Number of vertices - 1) if (E != (V - 1)) { return false; } // a single node is termed as a bus topology if (V == 1) { return true; } int[] vertexDegree = new int[V + 1]; // calculate the degree of each vertex for (int i = 1; i <= V; i++) { foreach (int v in adj[i]) { vertexDegree[v]++; } } // countDegree2 - number of vertices with degree 2 // countDegree1 - number of vertices with degree 1 int countDegree2 = 0, countDegree1 = 0; for (int i = 1; i <= V; i++) { if (vertexDegree[i] == 2) { countDegree2++; } else if (vertexDegree[i] == 1) { countDegree1++; } else { // if any node has degree other // than 1 or 2, it is // NOT a bus topology return false; } } // if both necessary conditions as discussed, // satisfy return true if (countDegree1 == 2 && countDegree2 == (V - 2)) { return true; } return false; } // Function to check if the graph represents a bus topology static void checkBusTopology(List<List<int>> adj, int V, int E) { bool isBus = checkBusTopologyUtil(adj, V, E); if (isBus) { Console.WriteLine(\"YES\"); } else { Console.WriteLine(\"NO\"); } } // Driver code static public void Main () { // Graph 1 int V = 5, E = 4; List<List<int>> adj1 = new List<List<int>>(); for(int i = 0; i < V + 1; i++) { adj1.Add(new List<int>()); } addEdge(adj1, 1, 2); addEdge(adj1, 1, 3); addEdge(adj1, 3, 4); addEdge(adj1, 4, 5); checkBusTopology(adj1, V, E); // Graph 2 V = 4; E = 4; List<List<int>> adj2 = new List<List<int>>(); for(int i = 0; i < V + 1; i++) { adj2.Add(new List<int>()); } addEdge(adj2, 1, 2); addEdge(adj2, 1, 3); addEdge(adj2, 3, 4); addEdge(adj2, 4, 2); checkBusTopology(adj2, V, E); }} // This code is contributed by avanitrachhadiya2155",
"e": 38354,
"s": 35247,
"text": null
},
{
"code": "<script> // JavaScript program to check if the given graph// represents a bus topology // A utility function to add an edge in an // undirected graph.function addEdge(adj,u,v){ adj[u].push(v); adj[v].push(u);} // A utility function to print the adjacency list // representation of graphfunction printGraph(adj,V){ for (let v = 0; v < V; ++v) { document.write(\"\\n Adjacency list of vertex \" + v + \"\\n head \"); for (let x=0;x<adj[v].length;x++) { document.write( \"-> \" + adj[v][x]); } document.write(\"<br>\"); }} /* Function to return true if the graph represented by the adjacency list represents a bus topology else return false */function checkBusTopologyUtil(adj,V,E){ // Number of edges should be equal // to (Number of vertices - 1) if (E != (V - 1)) { return false; } // a single node is termed as a bus topology if (V == 1) { return true; } let vertexDegree = new Array(V + 1); for(let i=0;i<vertexDegree.length;i++) { vertexDegree[i]=0; } // calculate the degree of each vertex for (let i = 1; i <= V; i++) { for (let v=0;v<adj[i].length;v++) { vertexDegree[adj[i][v]]++; } } // countDegree2 - number of vertices with degree 2 // countDegree1 - number of vertices with degree 1 let countDegree2 = 0, countDegree1 = 0; for (let i = 1; i <= V; i++) { if (vertexDegree[i] == 2) { countDegree2++; } else if (vertexDegree[i] == 1) { countDegree1++; } else { // if any node has degree other // than 1 or 2, it is // NOT a bus topology return false; } } // if both necessary conditions as discussed, // satisfy return true if (countDegree1 == 2 && countDegree2 == (V - 2)) { return true; } return false;} // Function to check if the graph represents a bus topologyfunction checkBusTopology(adj,V,E){ let isBus = checkBusTopologyUtil(adj, V, E); if (isBus) { document.write(\"YES<br>\"); } else { document.write(\"NO<br>\"); }} // Driver code // Graph 1 let V = 5, E = 4; let adj1=[]; for(let i = 0; i < V + 1; i++) { adj1.push([]); } addEdge(adj1, 1, 2); addEdge(adj1, 1, 3); addEdge(adj1, 3, 4); addEdge(adj1, 4, 5); checkBusTopology(adj1, V, E); // Graph 2 V = 4; E = 4; let adj2 = []; for(let i = 0; i < (V + 1); i++) { adj2.push([]); } addEdge(adj2, 1, 2); addEdge(adj2, 1, 3); addEdge(adj2, 3, 4); addEdge(adj2, 4, 2); checkBusTopology(adj2, V, E); // This code is contributed by patel2127 </script>",
"e": 41055,
"s": 38354,
"text": null
},
{
"code": null,
"e": 41062,
"s": 41055,
"text": "YES\nNO"
},
{
"code": null,
"e": 41158,
"s": 41064,
"text": "Time Complexity : O(E), where E is the number of Edges in the graph.Auxiliary Space: O(1). "
},
{
"code": null,
"e": 41173,
"s": 41158,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 41183,
"s": 41173,
"text": "Code_Mech"
},
{
"code": null,
"e": 41191,
"s": 41183,
"text": "rag2127"
},
{
"code": null,
"e": 41212,
"s": 41191,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 41222,
"s": 41212,
"text": "patel2127"
},
{
"code": null,
"e": 41238,
"s": 41222,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 41253,
"s": 41238,
"text": "varshagumber28"
},
{
"code": null,
"e": 41272,
"s": 41253,
"text": "graph-connectivity"
},
{
"code": null,
"e": 41296,
"s": 41272,
"text": "Competitive Programming"
},
{
"code": null,
"e": 41312,
"s": 41296,
"text": "Data Structures"
},
{
"code": null,
"e": 41318,
"s": 41312,
"text": "Graph"
},
{
"code": null,
"e": 41334,
"s": 41318,
"text": "Data Structures"
},
{
"code": null,
"e": 41340,
"s": 41334,
"text": "Graph"
},
{
"code": null,
"e": 41438,
"s": 41340,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 41467,
"s": 41438,
"text": "Ordered Set and GNU C++ PBDS"
},
{
"code": null,
"e": 41505,
"s": 41467,
"text": "Bits manipulation (Important tactics)"
},
{
"code": null,
"e": 41564,
"s": 41505,
"text": "What is Competitive Programming and How to Prepare for It?"
},
{
"code": null,
"e": 41605,
"s": 41564,
"text": "7 Best Coding Challenge Websites in 2020"
},
{
"code": null,
"e": 41630,
"s": 41605,
"text": "Formatted output in Java"
},
{
"code": null,
"e": 41679,
"s": 41630,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 41723,
"s": 41679,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 41748,
"s": 41723,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 41804,
"s": 41748,
"text": "Doubly Linked List | Set 1 (Introduction and Insertion)"
}
] |
PYGLET – Loading 3-D Model - GeeksforGeeks
|
06 Sep, 2021
In this article, we will see how we can load a 3-D model in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia, etc. A window is a “heavyweight” object occupying operating system resources. Windows may appear as floating regions or can be set to fill an entire screen (fullscreen). In order to load a file i.e resource we use resource module of pyglet. This module allows applications to specify a search path for resources. Relative paths are taken to be relative to the application’s __main__ module. A 3D file format is used for storing information about 3D models. You may have heard of the most popular formats STL, OBJ, FBX, COLLADA, etc. They are widely used in 3D printing, video games, movies, architecture, academia, medicine, engineering, and earth sciences.
We can create a window object with the help of command given below
# creating a window
window = pyglet.window.Window(width, height, title)
In order to do this we use model method with the pyglet.resourceSyntax : resource.model(file_name)Argument : It takes string i.e file name as argumentReturn : It returns Model object
Below is the implementation
Python3
# importing pyglet moduleimport pygletimport pyglet.window.key as key # width of windowwidth = 500 # height of windowheight = 500 # caption i.e title of the windowtitle = "Geeksforgeeks" # creating a windowwindow = pyglet.window.Window(width, height, title) # text text = "Welcome to GeeksforGeeks" # creating label with following properties# font = cooper# position = 250, 150# anchor position = centerlabel = pyglet.text.Label(text, font_name ='Cooper', font_size = 16, x = 250, y = 150, anchor_x ='center', anchor_y ='center') # creating a batchbatch = pyglet.graphics.Batch() # loading geeksforgeeks imageimage = pyglet.image.load('gfg.png') # creating sprite object# it is instance of an image displayed on-screensprite = pyglet.sprite.Sprite(image, x = 200, y = 230) # on draw event@window.eventdef on_draw(): # clear the window window.clear() # draw the label label.draw() # draw the image on screen sprite.draw() # key press event @window.eventdef on_key_press(symbol, modifier): # key "C" get press if symbol == key.C: # printing the message print("Key : C is pressed") # image for iconimg = image = pyglet.resource.image("gfg.png") # setting image as iconwindow.set_icon(img) # loading3-model filevalue = pyglet.resource.model("model.stl") # setting text of labellabel.text = str(value) # start running the applicationpyglet.app.run()
Output :
anikakapoor
singghakshay
Python-gui
Python-Pyglet
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Bar Plot in Matplotlib
|
[
{
"code": null,
"e": 24212,
"s": 24184,
"text": "\n06 Sep, 2021"
},
{
"code": null,
"e": 25068,
"s": 24212,
"text": "In this article, we will see how we can load a 3-D model in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia, etc. A window is a “heavyweight” object occupying operating system resources. Windows may appear as floating regions or can be set to fill an entire screen (fullscreen). In order to load a file i.e resource we use resource module of pyglet. This module allows applications to specify a search path for resources. Relative paths are taken to be relative to the application’s __main__ module. A 3D file format is used for storing information about 3D models. You may have heard of the most popular formats STL, OBJ, FBX, COLLADA, etc. They are widely used in 3D printing, video games, movies, architecture, academia, medicine, engineering, and earth sciences."
},
{
"code": null,
"e": 25136,
"s": 25068,
"text": "We can create a window object with the help of command given below "
},
{
"code": null,
"e": 25208,
"s": 25136,
"text": "# creating a window\nwindow = pyglet.window.Window(width, height, title)"
},
{
"code": null,
"e": 25393,
"s": 25208,
"text": "In order to do this we use model method with the pyglet.resourceSyntax : resource.model(file_name)Argument : It takes string i.e file name as argumentReturn : It returns Model object "
},
{
"code": null,
"e": 25423,
"s": 25393,
"text": "Below is the implementation "
},
{
"code": null,
"e": 25431,
"s": 25423,
"text": "Python3"
},
{
"code": "# importing pyglet moduleimport pygletimport pyglet.window.key as key # width of windowwidth = 500 # height of windowheight = 500 # caption i.e title of the windowtitle = \"Geeksforgeeks\" # creating a windowwindow = pyglet.window.Window(width, height, title) # text text = \"Welcome to GeeksforGeeks\" # creating label with following properties# font = cooper# position = 250, 150# anchor position = centerlabel = pyglet.text.Label(text, font_name ='Cooper', font_size = 16, x = 250, y = 150, anchor_x ='center', anchor_y ='center') # creating a batchbatch = pyglet.graphics.Batch() # loading geeksforgeeks imageimage = pyglet.image.load('gfg.png') # creating sprite object# it is instance of an image displayed on-screensprite = pyglet.sprite.Sprite(image, x = 200, y = 230) # on draw event@window.eventdef on_draw(): # clear the window window.clear() # draw the label label.draw() # draw the image on screen sprite.draw() # key press event @window.eventdef on_key_press(symbol, modifier): # key \"C\" get press if symbol == key.C: # printing the message print(\"Key : C is pressed\") # image for iconimg = image = pyglet.resource.image(\"gfg.png\") # setting image as iconwindow.set_icon(img) # loading3-model filevalue = pyglet.resource.model(\"model.stl\") # setting text of labellabel.text = str(value) # start running the applicationpyglet.app.run()",
"e": 27030,
"s": 25431,
"text": null
},
{
"code": null,
"e": 27040,
"s": 27030,
"text": "Output : "
},
{
"code": null,
"e": 27054,
"s": 27042,
"text": "anikakapoor"
},
{
"code": null,
"e": 27067,
"s": 27054,
"text": "singghakshay"
},
{
"code": null,
"e": 27078,
"s": 27067,
"text": "Python-gui"
},
{
"code": null,
"e": 27092,
"s": 27078,
"text": "Python-Pyglet"
},
{
"code": null,
"e": 27099,
"s": 27092,
"text": "Python"
},
{
"code": null,
"e": 27197,
"s": 27099,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27206,
"s": 27197,
"text": "Comments"
},
{
"code": null,
"e": 27219,
"s": 27206,
"text": "Old Comments"
},
{
"code": null,
"e": 27251,
"s": 27219,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27306,
"s": 27251,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 27362,
"s": 27306,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27401,
"s": 27362,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27443,
"s": 27401,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27485,
"s": 27443,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27507,
"s": 27485,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27538,
"s": 27507,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27567,
"s": 27538,
"text": "Create a directory in Python"
}
] |
C# | Gets an ICollection containing the values in the Hashtable - GeeksforGeeks
|
01 Feb, 2019
Hashtable.Values Property is used to get an ICollection containing the values in the Hashtable.
Syntax:
public virtual System.Collections.ICollection Values { get; }
Return Value: This property returns an ICollection containing the values in the Hashtable.
Note:
The order of values in the ICollection is unspecified.
Retrieving the value of this property is an O(1) operation.
Below programs illustrate the use of above-discussed property:
Example 1:
// C# code to get an ICollection containing// the values in the Hashtable.using System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Hashtable Hashtable myTable = new Hashtable(); // Adding elements in Hashtable myTable.Add("g", "geeks"); myTable.Add("c", "c++"); myTable.Add("d", "data structures"); myTable.Add("q", "quiz"); // Get a collection of the values ICollection c = myTable.Values; // Displaying the contents foreach(string str in c) Console.WriteLine(str + myTable[str]); }}
data structures
c++
quiz
geeks
Example 2:
// C# code to get an ICollection containing// the values in the Hashtable.using System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Hashtable Hashtable myTable = new Hashtable(); // Adding elements in Hashtable myTable.Add("India", "Country"); myTable.Add("Chandigarh", "City"); myTable.Add("Mars", "Planet"); myTable.Add("China", "Country"); // Get a collection of the values ICollection c = myTable.Values; // Displaying the contents foreach(string str in c) Console.WriteLine(str + myTable[str]); }}
City
Country
Country
Planet
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.hashtable.values?view=netframework-4.7.2
CSharp-Collections-Hashtable
CSharp-Collections-Namespace
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Extension Method in C#
Top 50 C# Interview Questions & Answers
HashSet in C# with Examples
C# | How to insert an element in an Array?
Partial Classes in C#
C# | Inheritance
C# | List Class
Lambda Expressions in C#
Difference between Hashtable and Dictionary in C#
Convert String to Character Array in C#
|
[
{
"code": null,
"e": 24302,
"s": 24274,
"text": "\n01 Feb, 2019"
},
{
"code": null,
"e": 24398,
"s": 24302,
"text": "Hashtable.Values Property is used to get an ICollection containing the values in the Hashtable."
},
{
"code": null,
"e": 24406,
"s": 24398,
"text": "Syntax:"
},
{
"code": null,
"e": 24468,
"s": 24406,
"text": "public virtual System.Collections.ICollection Values { get; }"
},
{
"code": null,
"e": 24559,
"s": 24468,
"text": "Return Value: This property returns an ICollection containing the values in the Hashtable."
},
{
"code": null,
"e": 24565,
"s": 24559,
"text": "Note:"
},
{
"code": null,
"e": 24620,
"s": 24565,
"text": "The order of values in the ICollection is unspecified."
},
{
"code": null,
"e": 24680,
"s": 24620,
"text": "Retrieving the value of this property is an O(1) operation."
},
{
"code": null,
"e": 24743,
"s": 24680,
"text": "Below programs illustrate the use of above-discussed property:"
},
{
"code": null,
"e": 24754,
"s": 24743,
"text": "Example 1:"
},
{
"code": "// C# code to get an ICollection containing// the values in the Hashtable.using System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Hashtable Hashtable myTable = new Hashtable(); // Adding elements in Hashtable myTable.Add(\"g\", \"geeks\"); myTable.Add(\"c\", \"c++\"); myTable.Add(\"d\", \"data structures\"); myTable.Add(\"q\", \"quiz\"); // Get a collection of the values ICollection c = myTable.Values; // Displaying the contents foreach(string str in c) Console.WriteLine(str + myTable[str]); }}",
"e": 25401,
"s": 24754,
"text": null
},
{
"code": null,
"e": 25433,
"s": 25401,
"text": "data structures\nc++\nquiz\ngeeks\n"
},
{
"code": null,
"e": 25444,
"s": 25433,
"text": "Example 2:"
},
{
"code": "// C# code to get an ICollection containing// the values in the Hashtable.using System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Hashtable Hashtable myTable = new Hashtable(); // Adding elements in Hashtable myTable.Add(\"India\", \"Country\"); myTable.Add(\"Chandigarh\", \"City\"); myTable.Add(\"Mars\", \"Planet\"); myTable.Add(\"China\", \"Country\"); // Get a collection of the values ICollection c = myTable.Values; // Displaying the contents foreach(string str in c) Console.WriteLine(str + myTable[str]); }}",
"e": 26108,
"s": 25444,
"text": null
},
{
"code": null,
"e": 26137,
"s": 26108,
"text": "City\nCountry\nCountry\nPlanet\n"
},
{
"code": null,
"e": 26148,
"s": 26137,
"text": "Reference:"
},
{
"code": null,
"e": 26252,
"s": 26148,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.hashtable.values?view=netframework-4.7.2"
},
{
"code": null,
"e": 26281,
"s": 26252,
"text": "CSharp-Collections-Hashtable"
},
{
"code": null,
"e": 26310,
"s": 26281,
"text": "CSharp-Collections-Namespace"
},
{
"code": null,
"e": 26313,
"s": 26310,
"text": "C#"
},
{
"code": null,
"e": 26411,
"s": 26313,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26420,
"s": 26411,
"text": "Comments"
},
{
"code": null,
"e": 26433,
"s": 26420,
"text": "Old Comments"
},
{
"code": null,
"e": 26456,
"s": 26433,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 26496,
"s": 26456,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 26524,
"s": 26496,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 26567,
"s": 26524,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 26589,
"s": 26567,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 26606,
"s": 26589,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 26622,
"s": 26606,
"text": "C# | List Class"
},
{
"code": null,
"e": 26647,
"s": 26622,
"text": "Lambda Expressions in C#"
},
{
"code": null,
"e": 26697,
"s": 26647,
"text": "Difference between Hashtable and Dictionary in C#"
}
] |
Input Pipeline for Images using Keras and TensorFlow | by Renu Khandelwal | Towards Data Science
|
Second, in the series to learn how to create an input pipeline to load and create image train and test dataset from custom data using Kera Preprocessing, Tensorflow, and tf.data.
The dataset used here is Intel Image Classification from Kaggle, and all the code in the article works in Tensorflow 2.0.
Intel Image classification dataset is split into Train, Test, and Val. We will only use the training dataset to learn how to load the dataset using different libraries.
The ImageDataGenerator class generates batches of tensors for the image data and scale down the pixel values from 0 to 255 to a value between 0 and 1.
We can apply different real-time data augmentation to the train image dataset like rotating the image, zooming the image, horizontal flip or vertical flip, etc. Data augmentation is not applied to the validation or test dataset.
import pandas as pdimport numpy as npimport osfrom tensorflow.keras.preprocessing.image import ImageDataGenerator, img_to_array, load_img, array_to_imgimport tensorflow as tfIMG_WIDTH=200IMG_HEIGHT=200batch_size=4train_dir = r'\CV\Intel_Images\seg_train\seg_train'test_dir = r'\CV\Intel_Images\seg_pred\seg_pred'val_dir = r'\CV\Intel_Images\seg_test\seg_test'image_gen_train = ImageDataGenerator(rescale=1./255, zoom_range=0.2, rotation_range=65, shear_range=0.09, horizontal_flip=True, vertical_flip=True)image_gen_val = ImageDataGenerator(rescale=1./255)
Once the instance of ImageDatagenerator is created, use the flow_from_directory() to read the image files from the directory.
flow_from_directory() expects the image data in a specific structure as shown below where each class has a folder, and images for that class are contained within the class folder.
train_data_gen = image_gen_train.flow_from_directory(batch_size=batch_size,directory=train_dir,shuffle=True, target_size=(IMG_HEIGHT, IMG_WIDTH,3), class_mode='sparse')val_data_gen = image_gen_val.flow_from_directory(batch_size=batch_size,directory=val_dir, target_size=(IMG_HEIGHT, IMG_WIDTH,3), class_mode='sparse')
class_indices.keys() will extract the class names from the dataset in a dictionary
train_data_gen.class_indices.keys()
Creating a simple Deep Learning model, compiling it, and training the model using the dataset generated using Keras preprocessing
model=tf.keras.Sequential( [ tf.keras.layers.InputLayer(input_shape=(200, 200, 3)), tf.keras.layers.Conv2D(filters=32, kernel_size=3, strides=(2, 2), activation='relu'), tf.keras.layers.Conv2D(filters=64, kernel_size=3, strides=(2, 2), activation='relu'), tf.keras.layers.Flatten(), tf.keras.layers.Dense(6) ])#Compile the modelmodel.compile(optimizer='rmsprop', loss='sparse_categorical_crossentropy',metrics=['accuracy'])#Fitting the modelhistory = model.fit(train_data_gen,steps_per_epoch=len(train_data_gen)//batch_size, validation_data=val_data_gen, epochs=2)
Input pipeline using Tensorflow will create tensors as an input to the model.
Open the image file using tensorflow.io.read_file()Decode the format of the file. Here we have a JPEG file, so we use decode_jpeg() with three color channels.Resize the image to match the input size for the Input layer of the Deep Learning model.Convert the image to float datatype using TensorFlow and then normalize the values between 0 and 1 from 0 to 255.tf.stack() creates a stacked tensor as rows of data
Open the image file using tensorflow.io.read_file()
Decode the format of the file. Here we have a JPEG file, so we use decode_jpeg() with three color channels.
Resize the image to match the input size for the Input layer of the Deep Learning model.
Convert the image to float datatype using TensorFlow and then normalize the values between 0 and 1 from 0 to 255.
tf.stack() creates a stacked tensor as rows of data
def create_dataset_tf(img_folder): class_name=[] tf_img_data_array=[] for dir1 in os.listdir(img_folder): for file in os.listdir(os.path.join(img_folder, dir1)): image= os.path.join(img_folder,dir1, file) image = tf.io.read_file(image) image = tf.io.decode_jpeg(image, channels=3) image = tf.image.resize(image, (200,200)) image = tf.cast(image / 255., tf.float32) tf_img_data_array.append(image) class_name.append(dir1) return tf.stack(tf_img_data_array, axis=0),class_nameimg_folder=r'CV\Intel_Images\seg_train\seg_train'tf_img_data, class_name=create_dataset_tf(img_folder)
Converting text labels to numeric codes
Create a dictionary for all unique values for the classes
target_dict={k: v for v, k in enumerate(np.unique(class_name))}target_dict
Convert the class_names to their respective numeric value based on the dictionary
target_val= [target_dict[class_name[i]] for i in range(len(class_name))]
Creating a simple Deep Learning model, compiling it, and training the model.
It is the same model that we created earlier when suing Keras.preprocessing(). The only change here is the input image data and class names, which are a list of Tensors values to fit the model.
model=tf.keras.Sequential( [ tf.keras.layers.InputLayer(input_shape=(200, 200, 3)), tf.keras.layers.Conv2D(filters=32, kernel_size=3, strides=(2, 2), activation='relu'), tf.keras.layers.Conv2D(filters=64, kernel_size=3, strides=(2, 2), activation='relu'), tf.keras.layers.Flatten(), tf.keras.layers.Dense(6) ])#Compile the modelmodel.compile(optimizer='rmsprop', loss='sparse_categorical_crossentropy',metrics=['accuracy'])#Fitting the modelhistory = model.fit(x=tf_img_data, y=tf.cast(list(map(int,target_val)),tf.int32), epochs=2)
tf.data API allows us to build complex input pipelines while reading large amounts of data available in different formats and then apply transformations.
In tf.data for image processing pipeline, an element is a single training example, having a pair of tensors to represent the image and its corresponding label.
Importing libraries and setting basic parameters
import numpy as npimport osimport tensorflow as tfdata_dir=r'\CV\Intel_Images\seg_train\seg_train'batch_size = 32img_height = 200img_width = 200
tf.data.Dataset.list_files() creates a dataset from a directory list of files using a matching pattern.
list_ds = tf.data.Dataset.list_files(str(data_dir + '\\*\\*'), shuffle=False)# get the count of image files in the train directoryimage_count=0for dir1 in os.listdir(data_dir): for files in os.listdir(os.path.join(data_dir, dir1)): image_count+=1list_ds = list_ds.shuffle(image_count, reshuffle_each_iteration=False)
Creating class labels from the directory name
class_names = np.array(sorted([dir1 for dir1 in os.listdir(data_dir)]))
Splitting the dataset into train, and Val.
The validation dataset is 20% of the total dataset, and train dataset is 80% of the entire dataset.
val_size = int(image_count * 0.2)train_ds = list_ds.skip(val_size)val_ds = list_ds.take(val_size)
Creating input pipeline components for a single training/validation example representing a pair of tensors to represent the image and its corresponding label.
#To process the labeldef get_label(file_path): # convert the path to a list of path components separated by sep parts = tf.strings.split(file_path, os.path.sep) # The second to last is the class-directory one_hot = parts[-2] == class_names# Integer encode the label return tf.argmax(tf.cast(one_hot, tf.int32))# To process the imagedef decode_img(img): # convert the compressed string to a 3D uint8 tensor img = tf.image.decode_jpeg(img, channels=3) # resize the image to the desired size return tf.image.resize(img, [img_height, img_width])# To create the single training of validation example with image and its corresponding labeldef process_path(file_path): label = get_label(file_path)# load the raw data from the file as a string img = tf.io.read_file(file_path) img = decode_img(img) return img, label
Set the AUTOTUNE; this will help to delegate the decision on the level of parallelism to use to the tf.data at runtime to optimize the CPU/GPU utilization.
AUTOTUNE = tf.data.experimental.AUTOTUNE# Set `num_parallel_calls` so multiple images are loaded/processed in parallel.train_ds = train_ds.map(process_path, num_parallel_calls=AUTOTUNE)val_ds = val_ds.map(process_path, num_parallel_calls=AUTOTUNE)
Configure data source for Performance
To configure the data source for performance, use prefetching.
Prefetching in tf.data allows the preprocessing of the data and model execution of a training step to overlap.
While the model is executing a training step 100, the input pipeline is reading the data for step 101.
def configure_for_performance(ds): ds = ds.cache() ds = ds.shuffle(buffer_size=1000) ds = ds.batch(batch_size) ds = ds.prefetch(buffer_size=AUTOTUNE) return dstrain_ds = configure_for_performance(train_ds)val_ds = configure_for_performance(val_ds)
Creating a simple Deep Learning model
The input to the model is tf.data.Dataset
model=tf.keras.Sequential( [ tf.keras.layers.InputLayer(input_shape=(200, 200, 3)), tf.keras.layers.Conv2D(filters=32, kernel_size=3, strides=(2, 2), activation='relu'), tf.keras.layers.Conv2D(filters=64, kernel_size=3, strides=(2, 2), activation='relu'), tf.keras.layers.Flatten(), tf.keras.layers.Dense(6) ])#Compile the modelmodel.compile(optimizer='rmsprop', loss='sparse_categorical_crossentropy',metrics=['accuracy'])#Fitting the modelhistory = model.fit(train_ds,validation_data=val_ds,epochs=3)
The best training time I got was using tf.data as there is prefetching, which is using AUTOTUNE to delegate the decision on the level of parallelism.
|
[
{
"code": null,
"e": 351,
"s": 172,
"text": "Second, in the series to learn how to create an input pipeline to load and create image train and test dataset from custom data using Kera Preprocessing, Tensorflow, and tf.data."
},
{
"code": null,
"e": 473,
"s": 351,
"text": "The dataset used here is Intel Image Classification from Kaggle, and all the code in the article works in Tensorflow 2.0."
},
{
"code": null,
"e": 642,
"s": 473,
"text": "Intel Image classification dataset is split into Train, Test, and Val. We will only use the training dataset to learn how to load the dataset using different libraries."
},
{
"code": null,
"e": 793,
"s": 642,
"text": "The ImageDataGenerator class generates batches of tensors for the image data and scale down the pixel values from 0 to 255 to a value between 0 and 1."
},
{
"code": null,
"e": 1022,
"s": 793,
"text": "We can apply different real-time data augmentation to the train image dataset like rotating the image, zooming the image, horizontal flip or vertical flip, etc. Data augmentation is not applied to the validation or test dataset."
},
{
"code": null,
"e": 1764,
"s": 1022,
"text": "import pandas as pdimport numpy as npimport osfrom tensorflow.keras.preprocessing.image import ImageDataGenerator, img_to_array, load_img, array_to_imgimport tensorflow as tfIMG_WIDTH=200IMG_HEIGHT=200batch_size=4train_dir = r'\\CV\\Intel_Images\\seg_train\\seg_train'test_dir = r'\\CV\\Intel_Images\\seg_pred\\seg_pred'val_dir = r'\\CV\\Intel_Images\\seg_test\\seg_test'image_gen_train = ImageDataGenerator(rescale=1./255, zoom_range=0.2, rotation_range=65, shear_range=0.09, horizontal_flip=True, vertical_flip=True)image_gen_val = ImageDataGenerator(rescale=1./255)"
},
{
"code": null,
"e": 1890,
"s": 1764,
"text": "Once the instance of ImageDatagenerator is created, use the flow_from_directory() to read the image files from the directory."
},
{
"code": null,
"e": 2070,
"s": 1890,
"text": "flow_from_directory() expects the image data in a specific structure as shown below where each class has a folder, and images for that class are contained within the class folder."
},
{
"code": null,
"e": 2588,
"s": 2070,
"text": "train_data_gen = image_gen_train.flow_from_directory(batch_size=batch_size,directory=train_dir,shuffle=True, target_size=(IMG_HEIGHT, IMG_WIDTH,3), class_mode='sparse')val_data_gen = image_gen_val.flow_from_directory(batch_size=batch_size,directory=val_dir, target_size=(IMG_HEIGHT, IMG_WIDTH,3), class_mode='sparse')"
},
{
"code": null,
"e": 2671,
"s": 2588,
"text": "class_indices.keys() will extract the class names from the dataset in a dictionary"
},
{
"code": null,
"e": 2707,
"s": 2671,
"text": "train_data_gen.class_indices.keys()"
},
{
"code": null,
"e": 2837,
"s": 2707,
"text": "Creating a simple Deep Learning model, compiling it, and training the model using the dataset generated using Keras preprocessing"
},
{
"code": null,
"e": 3472,
"s": 2837,
"text": "model=tf.keras.Sequential( [ tf.keras.layers.InputLayer(input_shape=(200, 200, 3)), tf.keras.layers.Conv2D(filters=32, kernel_size=3, strides=(2, 2), activation='relu'), tf.keras.layers.Conv2D(filters=64, kernel_size=3, strides=(2, 2), activation='relu'), tf.keras.layers.Flatten(), tf.keras.layers.Dense(6) ])#Compile the modelmodel.compile(optimizer='rmsprop', loss='sparse_categorical_crossentropy',metrics=['accuracy'])#Fitting the modelhistory = model.fit(train_data_gen,steps_per_epoch=len(train_data_gen)//batch_size, validation_data=val_data_gen, epochs=2)"
},
{
"code": null,
"e": 3550,
"s": 3472,
"text": "Input pipeline using Tensorflow will create tensors as an input to the model."
},
{
"code": null,
"e": 3961,
"s": 3550,
"text": "Open the image file using tensorflow.io.read_file()Decode the format of the file. Here we have a JPEG file, so we use decode_jpeg() with three color channels.Resize the image to match the input size for the Input layer of the Deep Learning model.Convert the image to float datatype using TensorFlow and then normalize the values between 0 and 1 from 0 to 255.tf.stack() creates a stacked tensor as rows of data"
},
{
"code": null,
"e": 4013,
"s": 3961,
"text": "Open the image file using tensorflow.io.read_file()"
},
{
"code": null,
"e": 4121,
"s": 4013,
"text": "Decode the format of the file. Here we have a JPEG file, so we use decode_jpeg() with three color channels."
},
{
"code": null,
"e": 4210,
"s": 4121,
"text": "Resize the image to match the input size for the Input layer of the Deep Learning model."
},
{
"code": null,
"e": 4324,
"s": 4210,
"text": "Convert the image to float datatype using TensorFlow and then normalize the values between 0 and 1 from 0 to 255."
},
{
"code": null,
"e": 4376,
"s": 4324,
"text": "tf.stack() creates a stacked tensor as rows of data"
},
{
"code": null,
"e": 5075,
"s": 4376,
"text": "def create_dataset_tf(img_folder): class_name=[] tf_img_data_array=[] for dir1 in os.listdir(img_folder): for file in os.listdir(os.path.join(img_folder, dir1)): image= os.path.join(img_folder,dir1, file) image = tf.io.read_file(image) image = tf.io.decode_jpeg(image, channels=3) image = tf.image.resize(image, (200,200)) image = tf.cast(image / 255., tf.float32) tf_img_data_array.append(image) class_name.append(dir1) return tf.stack(tf_img_data_array, axis=0),class_nameimg_folder=r'CV\\Intel_Images\\seg_train\\seg_train'tf_img_data, class_name=create_dataset_tf(img_folder)"
},
{
"code": null,
"e": 5115,
"s": 5075,
"text": "Converting text labels to numeric codes"
},
{
"code": null,
"e": 5173,
"s": 5115,
"text": "Create a dictionary for all unique values for the classes"
},
{
"code": null,
"e": 5248,
"s": 5173,
"text": "target_dict={k: v for v, k in enumerate(np.unique(class_name))}target_dict"
},
{
"code": null,
"e": 5330,
"s": 5248,
"text": "Convert the class_names to their respective numeric value based on the dictionary"
},
{
"code": null,
"e": 5404,
"s": 5330,
"text": "target_val= [target_dict[class_name[i]] for i in range(len(class_name))]"
},
{
"code": null,
"e": 5481,
"s": 5404,
"text": "Creating a simple Deep Learning model, compiling it, and training the model."
},
{
"code": null,
"e": 5675,
"s": 5481,
"text": "It is the same model that we created earlier when suing Keras.preprocessing(). The only change here is the input image data and class names, which are a list of Tensors values to fit the model."
},
{
"code": null,
"e": 6278,
"s": 5675,
"text": "model=tf.keras.Sequential( [ tf.keras.layers.InputLayer(input_shape=(200, 200, 3)), tf.keras.layers.Conv2D(filters=32, kernel_size=3, strides=(2, 2), activation='relu'), tf.keras.layers.Conv2D(filters=64, kernel_size=3, strides=(2, 2), activation='relu'), tf.keras.layers.Flatten(), tf.keras.layers.Dense(6) ])#Compile the modelmodel.compile(optimizer='rmsprop', loss='sparse_categorical_crossentropy',metrics=['accuracy'])#Fitting the modelhistory = model.fit(x=tf_img_data, y=tf.cast(list(map(int,target_val)),tf.int32), epochs=2)"
},
{
"code": null,
"e": 6432,
"s": 6278,
"text": "tf.data API allows us to build complex input pipelines while reading large amounts of data available in different formats and then apply transformations."
},
{
"code": null,
"e": 6592,
"s": 6432,
"text": "In tf.data for image processing pipeline, an element is a single training example, having a pair of tensors to represent the image and its corresponding label."
},
{
"code": null,
"e": 6641,
"s": 6592,
"text": "Importing libraries and setting basic parameters"
},
{
"code": null,
"e": 6786,
"s": 6641,
"text": "import numpy as npimport osimport tensorflow as tfdata_dir=r'\\CV\\Intel_Images\\seg_train\\seg_train'batch_size = 32img_height = 200img_width = 200"
},
{
"code": null,
"e": 6890,
"s": 6786,
"text": "tf.data.Dataset.list_files() creates a dataset from a directory list of files using a matching pattern."
},
{
"code": null,
"e": 7217,
"s": 6890,
"text": "list_ds = tf.data.Dataset.list_files(str(data_dir + '\\\\*\\\\*'), shuffle=False)# get the count of image files in the train directoryimage_count=0for dir1 in os.listdir(data_dir): for files in os.listdir(os.path.join(data_dir, dir1)): image_count+=1list_ds = list_ds.shuffle(image_count, reshuffle_each_iteration=False)"
},
{
"code": null,
"e": 7263,
"s": 7217,
"text": "Creating class labels from the directory name"
},
{
"code": null,
"e": 7335,
"s": 7263,
"text": "class_names = np.array(sorted([dir1 for dir1 in os.listdir(data_dir)]))"
},
{
"code": null,
"e": 7378,
"s": 7335,
"text": "Splitting the dataset into train, and Val."
},
{
"code": null,
"e": 7478,
"s": 7378,
"text": "The validation dataset is 20% of the total dataset, and train dataset is 80% of the entire dataset."
},
{
"code": null,
"e": 7576,
"s": 7478,
"text": "val_size = int(image_count * 0.2)train_ds = list_ds.skip(val_size)val_ds = list_ds.take(val_size)"
},
{
"code": null,
"e": 7735,
"s": 7576,
"text": "Creating input pipeline components for a single training/validation example representing a pair of tensors to represent the image and its corresponding label."
},
{
"code": null,
"e": 8561,
"s": 7735,
"text": "#To process the labeldef get_label(file_path): # convert the path to a list of path components separated by sep parts = tf.strings.split(file_path, os.path.sep) # The second to last is the class-directory one_hot = parts[-2] == class_names# Integer encode the label return tf.argmax(tf.cast(one_hot, tf.int32))# To process the imagedef decode_img(img): # convert the compressed string to a 3D uint8 tensor img = tf.image.decode_jpeg(img, channels=3) # resize the image to the desired size return tf.image.resize(img, [img_height, img_width])# To create the single training of validation example with image and its corresponding labeldef process_path(file_path): label = get_label(file_path)# load the raw data from the file as a string img = tf.io.read_file(file_path) img = decode_img(img) return img, label"
},
{
"code": null,
"e": 8717,
"s": 8561,
"text": "Set the AUTOTUNE; this will help to delegate the decision on the level of parallelism to use to the tf.data at runtime to optimize the CPU/GPU utilization."
},
{
"code": null,
"e": 8965,
"s": 8717,
"text": "AUTOTUNE = tf.data.experimental.AUTOTUNE# Set `num_parallel_calls` so multiple images are loaded/processed in parallel.train_ds = train_ds.map(process_path, num_parallel_calls=AUTOTUNE)val_ds = val_ds.map(process_path, num_parallel_calls=AUTOTUNE)"
},
{
"code": null,
"e": 9003,
"s": 8965,
"text": "Configure data source for Performance"
},
{
"code": null,
"e": 9066,
"s": 9003,
"text": "To configure the data source for performance, use prefetching."
},
{
"code": null,
"e": 9177,
"s": 9066,
"text": "Prefetching in tf.data allows the preprocessing of the data and model execution of a training step to overlap."
},
{
"code": null,
"e": 9280,
"s": 9177,
"text": "While the model is executing a training step 100, the input pipeline is reading the data for step 101."
},
{
"code": null,
"e": 9533,
"s": 9280,
"text": "def configure_for_performance(ds): ds = ds.cache() ds = ds.shuffle(buffer_size=1000) ds = ds.batch(batch_size) ds = ds.prefetch(buffer_size=AUTOTUNE) return dstrain_ds = configure_for_performance(train_ds)val_ds = configure_for_performance(val_ds)"
},
{
"code": null,
"e": 9571,
"s": 9533,
"text": "Creating a simple Deep Learning model"
},
{
"code": null,
"e": 9613,
"s": 9571,
"text": "The input to the model is tf.data.Dataset"
},
{
"code": null,
"e": 10186,
"s": 9613,
"text": "model=tf.keras.Sequential( [ tf.keras.layers.InputLayer(input_shape=(200, 200, 3)), tf.keras.layers.Conv2D(filters=32, kernel_size=3, strides=(2, 2), activation='relu'), tf.keras.layers.Conv2D(filters=64, kernel_size=3, strides=(2, 2), activation='relu'), tf.keras.layers.Flatten(), tf.keras.layers.Dense(6) ])#Compile the modelmodel.compile(optimizer='rmsprop', loss='sparse_categorical_crossentropy',metrics=['accuracy'])#Fitting the modelhistory = model.fit(train_ds,validation_data=val_ds,epochs=3)"
}
] |
Deep Learning meets Physics: Restricted Boltzmann Machines Part II | by Artem Oppermann | Towards Data Science
|
This article is the sequel of the first part where I introduced the theory behind Restricted Boltzmann Machines. This second part consists in a step by step guide through a practical implementation of a Restricted Boltzmann Machine which serves as a Recommender System and can predict whether a user would like a movie or not based on the users taste.
(1) In this article I wont cover the theory behind the steps I make, I will only explain the practical parts. Make sure to renew your theoretical knowledge by reviewing the first part of this series.
(2) The code I present in this article is from my project repository on GitHub. Since I focus only on the implementation of the model I skip some preprocessing steps like, splitting the data into training/test sets and building the input pipeline. These steps can be examined in the repository.
Python 3.6
TensorFlow 1.5 or higher
NumPy 1.11 or higher
We are using the MovieLens 1M Dataset. This set contains 1 million ratings of approximately 4000 movies made by approximately 6000 users. The model will be trained on this dataset and will learn to make predictions whether a user would like a random movie or not. The dataset requires some reprocessing steps. Because an usual Restricted Boltzmann Machine accepts only binary values it is necessary to give ratings 1–2 a value of 0 — hence the user does not like the movie. Accordingly the ratings 3–5 receive a value of 1. The movies that are not rated yet receive a value of -1.
In the next step the transformed original data is divided into two separate training and test datasets. It is necessary two have exactly the same users in both datasets but different movie ratings. Fig. 1 shows a simple example for the partitioning of the original dataset into the training and test data. In this example the first 5 ratings are put into the training set, while the rest is masked with -1 as not rated yet. Accordingly the test set receives the remaining 5 ratings.
During the training time the Restricted Boltzmann Machine learns on the first 5 movie ratings of each user, while during the inference time the model tries to predict the ratings for the last 5 movies. These predicted ratings are then compared with the actual ratings which were put into the test set.
Both datasets are saved in a binary TFRecords format that enables a very efficient data input pipeline.
The model is implemented in an object oriented manner. The Restricted Boltzmann Machine is a class with all necessary operations like training, loss, accuracy, inference etc. inside of it. Some helper functions are outsourced into a separate script.
The constructor sets the kernel initializers for the weights and biases. In the next step all weights and biases in the network get initialized. The weights are normal distributed with a mean of 0.0 and a variance of 0.02, while the biases are all set to 0.0 in the beginning. It can be noticed that the network consists only out of one hidden layer. As a result only one weight matrix is needed.
Giving the binary input v the following function _sample_h(self) obtains the probabilities that a hidden neuron is activated (Eq.1). This is achieved by multiplying the input v by the weight matrix, adding a bias and applying a sigmoidal activation . The obtained probabilities are used to sample from Bernoulli distribution. The sampled values which are either 1.0 or 0.0 are the states of the hidden neurons.
Given the hidden states h we can use these to obtain the probabilities that a visible neuron is active (Eq.2) as well as the corresponding state values. This is implemented in _sample_v(self) .
The first part of the training consists in an operation that is called Gibbs Sampling. Briefly speaking we take an input vector v_0 and use it to predict the values of the hidden state h_0. The hidden state are used on the other hand to predict new input state v. This procedure is repeated k times. This procedure is illustrated in Fig. 2.
Gibbs Sampling is implemented in the code snipped below. The iteration is happening in the while loop body. An important step in the body is Vk=tf.where(tf.less(V,0),V,Vk). This operations makes sure that the ratings in v which are -1 (meaning movies that have not been seen yet) remain -1 for every v_k in every iteration. After k iteration we obtain v_k and corresponding probabilities p(h_k|v_k). Together with v_0 and h_0 these values can be used to compute the gradient matrix in the next training step.
The values obtained in the previous step can be used to compute the gradient matrix and the gradient vectors. The computation of gradients according to Eq. 3 are straight forward. Please notice that the symbols a and b in this equations stand for hidden respectively visible biases in contrasts to different symbols I used in my code.
The only tricky part is that TensorFlow 1.5 does not support outer products. But this issue can be solved by temporary reshaping and applying usual point wise multiplication.
Notice that the computation of the gradients is happening in while loop. This is only due to the fact that the training is happening in mini-batches. Meaning the loop computes for each data sample in the mini-batch the gradients and adds them to the previously defined gradient placeholders. In the end the sum of gradients is divided by the size of the mini-batch.
After the gradients are computed all weights and biases can be updated through gradient ascent according to eq. 4. For this procedure we must create an assign operation in _update_parameter(self).
The whole training operation is computed in optimize(self) method under the name scope “operation”. Below that the more complicated accuracy operation of the training is implemented. Basically this operation subtracts the original input values v_0 from v_k that are obtained during Gibbs Sampling. The subtraction is only happening for v_0 ≥ 0. After that the summed subtractions are divided by the number of all ratings ≥ 0. The accuracy gives the ratio of correctly predicted binary movie ratings during training.
During inference time the method inference(self) receives the input v. That input is one training sample of a specific user that is used to activate the hidden neurons (the underlying features of users movie taste). The hidden neurons are used again to predict a new input v. In the best scenario this new input consists of the recreation of already present ratings as well as ratings of movies that were not rated yet.
The made prediction are compared outside the TensorFlow Session with the according test data for validation purposes.
The Network Graph
To outline the previous steps here is the definition of the main network graph and the start of the session where the training and inference steps are executed.
During the training process we can examine the progress of the accuracy on training and test sets. The accuracy gives the ratio of correctly predicted binary movie ratings. It can be seen that after 6 epochs the model predicts 78% of the time correctly if a user would like a random movie or not.
epoch_nr: 0, batch: 50/188, acc_train: 0.721, acc_test: 0.709epoch_nr: 1, batch: 50/188, acc_train: 0.767, acc_test: 0.764epoch_nr: 2, batch: 50/188, acc_train: 0.772, acc_test: 0.773epoch_nr: 3, batch: 50/188, acc_train: 0.767, acc_test: 0.725epoch_nr: 4, batch: 50/188, acc_train: 0.768, acc_test: 0.717epoch_nr: 5, batch: 50/188, acc_train: 0.772, acc_test: 0.769epoch_nr: 6, batch: 50/188, acc_train: 0.774, acc_test: 0.771epoch_nr: 7, batch: 50/188, acc_train: 0.779, acc_test: 0.780
|
[
{
"code": null,
"e": 524,
"s": 172,
"text": "This article is the sequel of the first part where I introduced the theory behind Restricted Boltzmann Machines. This second part consists in a step by step guide through a practical implementation of a Restricted Boltzmann Machine which serves as a Recommender System and can predict whether a user would like a movie or not based on the users taste."
},
{
"code": null,
"e": 724,
"s": 524,
"text": "(1) In this article I wont cover the theory behind the steps I make, I will only explain the practical parts. Make sure to renew your theoretical knowledge by reviewing the first part of this series."
},
{
"code": null,
"e": 1019,
"s": 724,
"text": "(2) The code I present in this article is from my project repository on GitHub. Since I focus only on the implementation of the model I skip some preprocessing steps like, splitting the data into training/test sets and building the input pipeline. These steps can be examined in the repository."
},
{
"code": null,
"e": 1030,
"s": 1019,
"text": "Python 3.6"
},
{
"code": null,
"e": 1055,
"s": 1030,
"text": "TensorFlow 1.5 or higher"
},
{
"code": null,
"e": 1076,
"s": 1055,
"text": "NumPy 1.11 or higher"
},
{
"code": null,
"e": 1657,
"s": 1076,
"text": "We are using the MovieLens 1M Dataset. This set contains 1 million ratings of approximately 4000 movies made by approximately 6000 users. The model will be trained on this dataset and will learn to make predictions whether a user would like a random movie or not. The dataset requires some reprocessing steps. Because an usual Restricted Boltzmann Machine accepts only binary values it is necessary to give ratings 1–2 a value of 0 — hence the user does not like the movie. Accordingly the ratings 3–5 receive a value of 1. The movies that are not rated yet receive a value of -1."
},
{
"code": null,
"e": 2140,
"s": 1657,
"text": "In the next step the transformed original data is divided into two separate training and test datasets. It is necessary two have exactly the same users in both datasets but different movie ratings. Fig. 1 shows a simple example for the partitioning of the original dataset into the training and test data. In this example the first 5 ratings are put into the training set, while the rest is masked with -1 as not rated yet. Accordingly the test set receives the remaining 5 ratings."
},
{
"code": null,
"e": 2442,
"s": 2140,
"text": "During the training time the Restricted Boltzmann Machine learns on the first 5 movie ratings of each user, while during the inference time the model tries to predict the ratings for the last 5 movies. These predicted ratings are then compared with the actual ratings which were put into the test set."
},
{
"code": null,
"e": 2546,
"s": 2442,
"text": "Both datasets are saved in a binary TFRecords format that enables a very efficient data input pipeline."
},
{
"code": null,
"e": 2796,
"s": 2546,
"text": "The model is implemented in an object oriented manner. The Restricted Boltzmann Machine is a class with all necessary operations like training, loss, accuracy, inference etc. inside of it. Some helper functions are outsourced into a separate script."
},
{
"code": null,
"e": 3193,
"s": 2796,
"text": "The constructor sets the kernel initializers for the weights and biases. In the next step all weights and biases in the network get initialized. The weights are normal distributed with a mean of 0.0 and a variance of 0.02, while the biases are all set to 0.0 in the beginning. It can be noticed that the network consists only out of one hidden layer. As a result only one weight matrix is needed."
},
{
"code": null,
"e": 3604,
"s": 3193,
"text": "Giving the binary input v the following function _sample_h(self) obtains the probabilities that a hidden neuron is activated (Eq.1). This is achieved by multiplying the input v by the weight matrix, adding a bias and applying a sigmoidal activation . The obtained probabilities are used to sample from Bernoulli distribution. The sampled values which are either 1.0 or 0.0 are the states of the hidden neurons."
},
{
"code": null,
"e": 3798,
"s": 3604,
"text": "Given the hidden states h we can use these to obtain the probabilities that a visible neuron is active (Eq.2) as well as the corresponding state values. This is implemented in _sample_v(self) ."
},
{
"code": null,
"e": 4139,
"s": 3798,
"text": "The first part of the training consists in an operation that is called Gibbs Sampling. Briefly speaking we take an input vector v_0 and use it to predict the values of the hidden state h_0. The hidden state are used on the other hand to predict new input state v. This procedure is repeated k times. This procedure is illustrated in Fig. 2."
},
{
"code": null,
"e": 4648,
"s": 4139,
"text": "Gibbs Sampling is implemented in the code snipped below. The iteration is happening in the while loop body. An important step in the body is Vk=tf.where(tf.less(V,0),V,Vk). This operations makes sure that the ratings in v which are -1 (meaning movies that have not been seen yet) remain -1 for every v_k in every iteration. After k iteration we obtain v_k and corresponding probabilities p(h_k|v_k). Together with v_0 and h_0 these values can be used to compute the gradient matrix in the next training step."
},
{
"code": null,
"e": 4983,
"s": 4648,
"text": "The values obtained in the previous step can be used to compute the gradient matrix and the gradient vectors. The computation of gradients according to Eq. 3 are straight forward. Please notice that the symbols a and b in this equations stand for hidden respectively visible biases in contrasts to different symbols I used in my code."
},
{
"code": null,
"e": 5158,
"s": 4983,
"text": "The only tricky part is that TensorFlow 1.5 does not support outer products. But this issue can be solved by temporary reshaping and applying usual point wise multiplication."
},
{
"code": null,
"e": 5524,
"s": 5158,
"text": "Notice that the computation of the gradients is happening in while loop. This is only due to the fact that the training is happening in mini-batches. Meaning the loop computes for each data sample in the mini-batch the gradients and adds them to the previously defined gradient placeholders. In the end the sum of gradients is divided by the size of the mini-batch."
},
{
"code": null,
"e": 5721,
"s": 5524,
"text": "After the gradients are computed all weights and biases can be updated through gradient ascent according to eq. 4. For this procedure we must create an assign operation in _update_parameter(self)."
},
{
"code": null,
"e": 6237,
"s": 5721,
"text": "The whole training operation is computed in optimize(self) method under the name scope “operation”. Below that the more complicated accuracy operation of the training is implemented. Basically this operation subtracts the original input values v_0 from v_k that are obtained during Gibbs Sampling. The subtraction is only happening for v_0 ≥ 0. After that the summed subtractions are divided by the number of all ratings ≥ 0. The accuracy gives the ratio of correctly predicted binary movie ratings during training."
},
{
"code": null,
"e": 6657,
"s": 6237,
"text": "During inference time the method inference(self) receives the input v. That input is one training sample of a specific user that is used to activate the hidden neurons (the underlying features of users movie taste). The hidden neurons are used again to predict a new input v. In the best scenario this new input consists of the recreation of already present ratings as well as ratings of movies that were not rated yet."
},
{
"code": null,
"e": 6775,
"s": 6657,
"text": "The made prediction are compared outside the TensorFlow Session with the according test data for validation purposes."
},
{
"code": null,
"e": 6793,
"s": 6775,
"text": "The Network Graph"
},
{
"code": null,
"e": 6954,
"s": 6793,
"text": "To outline the previous steps here is the definition of the main network graph and the start of the session where the training and inference steps are executed."
},
{
"code": null,
"e": 7251,
"s": 6954,
"text": "During the training process we can examine the progress of the accuracy on training and test sets. The accuracy gives the ratio of correctly predicted binary movie ratings. It can be seen that after 6 epochs the model predicts 78% of the time correctly if a user would like a random movie or not."
}
] |
Jupyter notebook on AWS EC2 Instance | by Sanjay Singh | Towards Data Science
|
Jupyter is the most used development tool by data science and machine learning professionals. Considering most of the data science and machine learning projects involve working with data on the cloud, it makes sense to use the Jupyter notebook on the cloud. The flexibility of Jupyter on a ubiquitous cloud instance is a win-win combination.
In this article, I will take you through the steps to install and run a Jupyter notebook from a Linux instance on AWS EC2 instance.
Prerequisite Tools
I am assuming that you already have an AWS EC2 instance and know how to access it through Putty.
Make sure you have configured X11 forwarding in Putty.
Xming: For launching the Jupyter notebook on AWS instance and accessing it on your computer, you will also need the Xming tool. Xming can be downloaded from the below link
sourceforge.net
After downloading and installing Xming you should see two icons Xming and XLaunch on your computer. Click on Xming and it will launch the Xming server.
Click on XLaunch and go through the below screen.
This is the first screen you will see. No action required, click on Next.
No changes required on this screen. Click on the Next button.
No changes required on this screen. Click on the Next button.
No changes required on this screen. Click on the Finish button.
Xming is good to go.
Anaconda: Instead of installing Python and Jupyter separately in AWS instance, I suggest to install Anaconda. I am using a Redhat Linux machine on AWS EC2. By default, it doesn’t come with the Anaconda repository. So, the first step is getting Anaconda through the wget command.
a. First, check if wget is installed in your instance. If not, run install it through yum install as shown below.
sudo yum install wget
b. Chek if bzip2 is installed. If not, install it through yum
sudo yum install bzip2
c. Check if firefox installed. If not, install it through yum
sudo yum install firefox
d. Check if xorg-x11 drivers are installed. If not, install it through yum
sudo yum install xorg-x11*
e. Open /etc/ssh/ssh_config file and make sure the ForwardX11 option is uncommented and set as yes.
f. Download Anaconda3 through wget
sudo wget http://repo.continuum.io/archive/Anaconda3-4.3.0-Linux-x86_64.sh
This will create file Anaconda3–4.3.0-Linux-x86_64.sh in the directory.
g. Run the below command to install Anaconda 3.
bash Anaconda3-4.3.0-Linux-x86_64.sh
Click on Enter and go through terms and conditions. Once you get the below message write yes.
Mention the location where you want to install anaconda3
Wait for Anaconda3 installation to finish.
h. Add Anacond3 binary and DISPLAY variable in bashrc file. I am using vi editor, you can use nano or something else.
sudo vi ~/.bashrc
Add below in this file
export PATH=/u01/anaconda3/bin:$PATHexport DISPLAY=localhost:10.0
i. Close the instance and re-login through Putty.
j. Make sure Xming and XLaunch are on. Xming icon should show in task view.
k. Let’s confirm it got successfully installed. Check the versions of Anaconda, Python, and Jupyter.
Congratulations! You have completed the required setups and ready to launch the Jupyter notebook.
Run the below command to launch the jupyter notebook
jupyter notebook
Jupyter notebook will open on Mozilla Browser in the X11 window.
Congratulations! Now you know how to launch a Jupyter notebook on AWS EC2 instance!
I and my students have gone through these steps several times and have been able to successfully run the Jupyter notebook on AWS instance. Nevertheless, if you encounter any issue at any step please feel free to write and I will respond promptly.
Looking forward to your feedback.
|
[
{
"code": null,
"e": 514,
"s": 172,
"text": "Jupyter is the most used development tool by data science and machine learning professionals. Considering most of the data science and machine learning projects involve working with data on the cloud, it makes sense to use the Jupyter notebook on the cloud. The flexibility of Jupyter on a ubiquitous cloud instance is a win-win combination."
},
{
"code": null,
"e": 646,
"s": 514,
"text": "In this article, I will take you through the steps to install and run a Jupyter notebook from a Linux instance on AWS EC2 instance."
},
{
"code": null,
"e": 665,
"s": 646,
"text": "Prerequisite Tools"
},
{
"code": null,
"e": 762,
"s": 665,
"text": "I am assuming that you already have an AWS EC2 instance and know how to access it through Putty."
},
{
"code": null,
"e": 817,
"s": 762,
"text": "Make sure you have configured X11 forwarding in Putty."
},
{
"code": null,
"e": 989,
"s": 817,
"text": "Xming: For launching the Jupyter notebook on AWS instance and accessing it on your computer, you will also need the Xming tool. Xming can be downloaded from the below link"
},
{
"code": null,
"e": 1005,
"s": 989,
"text": "sourceforge.net"
},
{
"code": null,
"e": 1157,
"s": 1005,
"text": "After downloading and installing Xming you should see two icons Xming and XLaunch on your computer. Click on Xming and it will launch the Xming server."
},
{
"code": null,
"e": 1207,
"s": 1157,
"text": "Click on XLaunch and go through the below screen."
},
{
"code": null,
"e": 1281,
"s": 1207,
"text": "This is the first screen you will see. No action required, click on Next."
},
{
"code": null,
"e": 1343,
"s": 1281,
"text": "No changes required on this screen. Click on the Next button."
},
{
"code": null,
"e": 1405,
"s": 1343,
"text": "No changes required on this screen. Click on the Next button."
},
{
"code": null,
"e": 1469,
"s": 1405,
"text": "No changes required on this screen. Click on the Finish button."
},
{
"code": null,
"e": 1490,
"s": 1469,
"text": "Xming is good to go."
},
{
"code": null,
"e": 1769,
"s": 1490,
"text": "Anaconda: Instead of installing Python and Jupyter separately in AWS instance, I suggest to install Anaconda. I am using a Redhat Linux machine on AWS EC2. By default, it doesn’t come with the Anaconda repository. So, the first step is getting Anaconda through the wget command."
},
{
"code": null,
"e": 1883,
"s": 1769,
"text": "a. First, check if wget is installed in your instance. If not, run install it through yum install as shown below."
},
{
"code": null,
"e": 1905,
"s": 1883,
"text": "sudo yum install wget"
},
{
"code": null,
"e": 1967,
"s": 1905,
"text": "b. Chek if bzip2 is installed. If not, install it through yum"
},
{
"code": null,
"e": 1990,
"s": 1967,
"text": "sudo yum install bzip2"
},
{
"code": null,
"e": 2052,
"s": 1990,
"text": "c. Check if firefox installed. If not, install it through yum"
},
{
"code": null,
"e": 2077,
"s": 2052,
"text": "sudo yum install firefox"
},
{
"code": null,
"e": 2152,
"s": 2077,
"text": "d. Check if xorg-x11 drivers are installed. If not, install it through yum"
},
{
"code": null,
"e": 2179,
"s": 2152,
"text": "sudo yum install xorg-x11*"
},
{
"code": null,
"e": 2279,
"s": 2179,
"text": "e. Open /etc/ssh/ssh_config file and make sure the ForwardX11 option is uncommented and set as yes."
},
{
"code": null,
"e": 2314,
"s": 2279,
"text": "f. Download Anaconda3 through wget"
},
{
"code": null,
"e": 2389,
"s": 2314,
"text": "sudo wget http://repo.continuum.io/archive/Anaconda3-4.3.0-Linux-x86_64.sh"
},
{
"code": null,
"e": 2461,
"s": 2389,
"text": "This will create file Anaconda3–4.3.0-Linux-x86_64.sh in the directory."
},
{
"code": null,
"e": 2509,
"s": 2461,
"text": "g. Run the below command to install Anaconda 3."
},
{
"code": null,
"e": 2546,
"s": 2509,
"text": "bash Anaconda3-4.3.0-Linux-x86_64.sh"
},
{
"code": null,
"e": 2640,
"s": 2546,
"text": "Click on Enter and go through terms and conditions. Once you get the below message write yes."
},
{
"code": null,
"e": 2697,
"s": 2640,
"text": "Mention the location where you want to install anaconda3"
},
{
"code": null,
"e": 2740,
"s": 2697,
"text": "Wait for Anaconda3 installation to finish."
},
{
"code": null,
"e": 2858,
"s": 2740,
"text": "h. Add Anacond3 binary and DISPLAY variable in bashrc file. I am using vi editor, you can use nano or something else."
},
{
"code": null,
"e": 2876,
"s": 2858,
"text": "sudo vi ~/.bashrc"
},
{
"code": null,
"e": 2899,
"s": 2876,
"text": "Add below in this file"
},
{
"code": null,
"e": 2965,
"s": 2899,
"text": "export PATH=/u01/anaconda3/bin:$PATHexport DISPLAY=localhost:10.0"
},
{
"code": null,
"e": 3015,
"s": 2965,
"text": "i. Close the instance and re-login through Putty."
},
{
"code": null,
"e": 3091,
"s": 3015,
"text": "j. Make sure Xming and XLaunch are on. Xming icon should show in task view."
},
{
"code": null,
"e": 3192,
"s": 3091,
"text": "k. Let’s confirm it got successfully installed. Check the versions of Anaconda, Python, and Jupyter."
},
{
"code": null,
"e": 3290,
"s": 3192,
"text": "Congratulations! You have completed the required setups and ready to launch the Jupyter notebook."
},
{
"code": null,
"e": 3343,
"s": 3290,
"text": "Run the below command to launch the jupyter notebook"
},
{
"code": null,
"e": 3360,
"s": 3343,
"text": "jupyter notebook"
},
{
"code": null,
"e": 3425,
"s": 3360,
"text": "Jupyter notebook will open on Mozilla Browser in the X11 window."
},
{
"code": null,
"e": 3509,
"s": 3425,
"text": "Congratulations! Now you know how to launch a Jupyter notebook on AWS EC2 instance!"
},
{
"code": null,
"e": 3756,
"s": 3509,
"text": "I and my students have gone through these steps several times and have been able to successfully run the Jupyter notebook on AWS instance. Nevertheless, if you encounter any issue at any step please feel free to write and I will respond promptly."
}
] |
Compute the Sum of Rows of a Matrix or Array in R Programming - rowSums Function - GeeksforGeeks
|
03 Jun, 2020
rowSums() function in R Language is used to compute the sum of rows of a matrix or an array.
Syntax: rowSums(x, na.rm = FALSE, dims = 1)
Parameters:x: array or matrixdims: Integer: Dimensions are regarded as ‘rows’ to sum over. It is over dimensions dims+1, ....
Example 1:
# R program to illustrate# rowSums() function # Initializing a matrix x <- matrix(rep(2:10), 3, 3) # Printing Matrixprint(x) # Calling the rowSums() functionrowSums(x)
Output:
[, 1] [, 2] [, 3]
[1, ] 2 5 8
[2, ] 3 6 9
[3, ] 4 7 10
[1] 15 18 21
Example 2:
# R program to illustrate# rowSums function # Initializing a 3D arrayx <- array(1:8, c(2, 2, 2)) # Printing the arrayprint(x) # Calling the rowSums() functionrowSums(x, dims = 1)
Output:
,, 1
[, 1] [, 2]
[1, ] 1 3
[2, ] 2 4,, 2
[, 1] [, 2]
[1, ] 5 7
[2, ] 6 8
[1] 16 20
R Matrix-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Replace specific values in column in R DataFrame ?
How to change Row Names of DataFrame in R ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
Printing Output of an R Program
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
K-Means Clustering in R Programming
|
[
{
"code": null,
"e": 24843,
"s": 24815,
"text": "\n03 Jun, 2020"
},
{
"code": null,
"e": 24936,
"s": 24843,
"text": "rowSums() function in R Language is used to compute the sum of rows of a matrix or an array."
},
{
"code": null,
"e": 24980,
"s": 24936,
"text": "Syntax: rowSums(x, na.rm = FALSE, dims = 1)"
},
{
"code": null,
"e": 25106,
"s": 24980,
"text": "Parameters:x: array or matrixdims: Integer: Dimensions are regarded as ‘rows’ to sum over. It is over dimensions dims+1, ...."
},
{
"code": null,
"e": 25117,
"s": 25106,
"text": "Example 1:"
},
{
"code": "# R program to illustrate# rowSums() function # Initializing a matrix x <- matrix(rep(2:10), 3, 3) # Printing Matrixprint(x) # Calling the rowSums() functionrowSums(x)",
"e": 25288,
"s": 25117,
"text": null
},
{
"code": null,
"e": 25296,
"s": 25288,
"text": "Output:"
},
{
"code": null,
"e": 25396,
"s": 25296,
"text": " [, 1] [, 2] [, 3]\n[1, ] 2 5 8\n[2, ] 3 6 9\n[3, ] 4 7 10\n[1] 15 18 21\n"
},
{
"code": null,
"e": 25407,
"s": 25396,
"text": "Example 2:"
},
{
"code": "# R program to illustrate# rowSums function # Initializing a 3D arrayx <- array(1:8, c(2, 2, 2)) # Printing the arrayprint(x) # Calling the rowSums() functionrowSums(x, dims = 1)",
"e": 25589,
"s": 25407,
"text": null
},
{
"code": null,
"e": 25597,
"s": 25589,
"text": "Output:"
},
{
"code": null,
"e": 25718,
"s": 25597,
"text": ",, 1\n\n [, 1] [, 2]\n[1, ] 1 3\n[2, ] 2 4,, 2\n\n [, 1] [, 2]\n[1, ] 5 7\n[2, ] 6 8\n\n[1] 16 20\n"
},
{
"code": null,
"e": 25736,
"s": 25718,
"text": "R Matrix-Function"
},
{
"code": null,
"e": 25747,
"s": 25736,
"text": "R Language"
},
{
"code": null,
"e": 25845,
"s": 25747,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25854,
"s": 25845,
"text": "Comments"
},
{
"code": null,
"e": 25867,
"s": 25854,
"text": "Old Comments"
},
{
"code": null,
"e": 25925,
"s": 25867,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 25969,
"s": 25925,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 26021,
"s": 25969,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 26053,
"s": 26021,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 26105,
"s": 26053,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 26137,
"s": 26105,
"text": "Printing Output of an R Program"
},
{
"code": null,
"e": 26175,
"s": 26137,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 26210,
"s": 26175,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 26268,
"s": 26210,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
}
] |
Working with Python dictionaries: a cheat sheet | by Mahbubul Alam | Towards Data Science
|
Dictionaries in Python are a collection of key-value pairs — meaning every item in the dictionary has a key and an associated value.
If we want to write down prices of some items in a grocery store, normally we will note them on a piece of paper like this:
eggs - 4.99banana - 1.49cheese- 4.5eggplant - 2.5bread - 3.99
In Python dictionary lingo, the name of each item is “key” and the associated price is “value” and they appear in pairs. We can represent the same in a Python dictionary data structure as follows:
{"eggs": 4.99,"banana": 1.49,"cheese": 4.5,"eggplant": 2.5,"bread": 3.99}
Notice the differences. In the dictionary
each key is within quotation marks because they are strings
the associated values are not quoted because they are numeric
keys and values are separated by a colon (:)
the items are comma-separated
Now, in the first items we have {"eggs”: 4.99} but in reality, eggs can have several values — one for brown eggs, one for white eggs and one for organic eggs — and python dictionaries allows for adding more than one value in the dictionary such that {“eggs”: [3.99, 4.99, 5.50]}.
Let’s give this dictionary a name and play with it:
grocery_items = {"eggs": [3.99, 4.99, 5.50],"banana": 1.49,"cheese": 4.5,"eggplant": 2.5,"bread": 3.99}
You can open your IDE/text editor and follow along with the codes below to work with this dictionary we just created.
We’ve built our initial dictionary with 5 items but we can grow it by adding more items:
grocery_items["onion"] = 3.50Out: {"eggs": [3.99, 4.99, 5.50], "banana": 1.49, "cheese": 4.5, "eggplant": 2.5, "bread": 3.99, "onion": 3.50}
You can add multiple items in a similar fashion.
We can also do the opposite — remove one or more items from this list. There are a couple of ways to do that:
Remove the last item using popitem() method:
grocery_items.popitem()Out: {"eggs": [3.99, 4.99, 5.50], "banana": 1.49, "cheese": 4.5, "eggplant": 2.5, "bread": 3.99}
Or remove an item by its key name using just pop() method:
grocery_items.pop("banana")Out: {"eggs": [3.99, 4.99, 5.50], "cheese": 4.5, "eggplant": 2.5, "bread": 3.99}
And finally, you can clear the whole dictionary (i.e. making it empty) with clear() method and delete the entire dictionary with del keyword (just be careful if you ever have to use it).
You may be wondering where someone can find all those methods? Just hit the “tab” key on the keyboard and all methods will pop up.
It’s often necessary to get a list of keys or values in the dictionary for further analysis (we’ll see later why).
To access all the keys:
grocery_items.keys()Out: dict_keys(['eggs', 'banana', 'cheese', 'eggplant', 'bread'])
To access all values instead:
grocery_items.values()Out: dict_values([[3.99, 4.99, 5.5], 1.49, 4.5, 2.5, 3.99])
We can also query the dictionary to access the value of a specific key (e.g. the price of bananas). There are a couple of ways to do that:
# access values by keygrocery_items["banana"]# or grocery_items.get("banana")Out: 1.49
But what about eggs? We have three different prices for eggs. We can choose to access all prices:
grocery_items.get("eggs")Out: [3.99, 4.99, 5.5]
We can also choose to access just the first one from the list by index position:
grocery_items.get("eggs")[0]Out: 3.99
In fact, we can access more complex nested dictionary items/keys/values in a similar fashion.
Besides the methods the above, which are most frequently used with a dictionary, there are a few methods and functions which can come in handy in data analysis:
To get the number of items in the dictionary:
len(grocery_items)Out: 5
To change the value of a key:
grocery_items.update({"banana": 0.85})
To cast the keys as a list:
list(grocery_items)Out: ['eggs', 'banana', 'cheese', 'eggplant', 'bread']
If the dictionary is really large, we can check whether a key exists:
"potato" in grocery_itemsOut: False
And finally, for returning the string representation of a dictionary:
str(grocery_items)Out: "{'apple': 2.5, 'orange': 4.99, 'banana': 0.59}"
It is often necessary to change dictionary elements or extract specific values or keys based on certain conditions. Since dictionaries are iterable objects, for loops are often used for such operations. Here are a couple of examples:
A simple loop to print all the keys:
for i in grocery_items: print(i)Out:eggsbananacheeseeggplantbread
Or a for loop for conditional filtering of dictionary keys:
for i in grocery_items.keys(): if i.startswith("e"): print(i)Out:eggseggplant
Like list comprehensions, Python also supports dictionary comprehensions to perform different kinds of operations. The for loops we created above could also be expressed in dictionary comprehension syntax.
For example, to print the values of a dictionary:
[x for x in grocery_items.values()]Out:[[3.99, 4.99, 5.5], 1.49, 4.5, 2.5, 3.99]
To summarise, we have covered in this article:
Python dictionaries are iterable objects with key-value pairs
dictionaries can be edited to add, remove and update values
dictionary elements can be accessed with methods such as .keys(), .values() and .items()
dictionaries are iterable objects, so Python allows for loops or dictionary comprehensions.
I left many other methods and functionalities out, but I hope this gives a head start to build a cheat sheet to work with Python dictionary objects.
If you have comments feel free to write them down below or connect with me via Medium, Twitter or LinkedIn.
|
[
{
"code": null,
"e": 305,
"s": 172,
"text": "Dictionaries in Python are a collection of key-value pairs — meaning every item in the dictionary has a key and an associated value."
},
{
"code": null,
"e": 429,
"s": 305,
"text": "If we want to write down prices of some items in a grocery store, normally we will note them on a piece of paper like this:"
},
{
"code": null,
"e": 491,
"s": 429,
"text": "eggs - 4.99banana - 1.49cheese- 4.5eggplant - 2.5bread - 3.99"
},
{
"code": null,
"e": 688,
"s": 491,
"text": "In Python dictionary lingo, the name of each item is “key” and the associated price is “value” and they appear in pairs. We can represent the same in a Python dictionary data structure as follows:"
},
{
"code": null,
"e": 762,
"s": 688,
"text": "{\"eggs\": 4.99,\"banana\": 1.49,\"cheese\": 4.5,\"eggplant\": 2.5,\"bread\": 3.99}"
},
{
"code": null,
"e": 804,
"s": 762,
"text": "Notice the differences. In the dictionary"
},
{
"code": null,
"e": 864,
"s": 804,
"text": "each key is within quotation marks because they are strings"
},
{
"code": null,
"e": 926,
"s": 864,
"text": "the associated values are not quoted because they are numeric"
},
{
"code": null,
"e": 971,
"s": 926,
"text": "keys and values are separated by a colon (:)"
},
{
"code": null,
"e": 1001,
"s": 971,
"text": "the items are comma-separated"
},
{
"code": null,
"e": 1281,
"s": 1001,
"text": "Now, in the first items we have {\"eggs”: 4.99} but in reality, eggs can have several values — one for brown eggs, one for white eggs and one for organic eggs — and python dictionaries allows for adding more than one value in the dictionary such that {“eggs”: [3.99, 4.99, 5.50]}."
},
{
"code": null,
"e": 1333,
"s": 1281,
"text": "Let’s give this dictionary a name and play with it:"
},
{
"code": null,
"e": 1437,
"s": 1333,
"text": "grocery_items = {\"eggs\": [3.99, 4.99, 5.50],\"banana\": 1.49,\"cheese\": 4.5,\"eggplant\": 2.5,\"bread\": 3.99}"
},
{
"code": null,
"e": 1555,
"s": 1437,
"text": "You can open your IDE/text editor and follow along with the codes below to work with this dictionary we just created."
},
{
"code": null,
"e": 1644,
"s": 1555,
"text": "We’ve built our initial dictionary with 5 items but we can grow it by adding more items:"
},
{
"code": null,
"e": 1785,
"s": 1644,
"text": "grocery_items[\"onion\"] = 3.50Out: {\"eggs\": [3.99, 4.99, 5.50], \"banana\": 1.49, \"cheese\": 4.5, \"eggplant\": 2.5, \"bread\": 3.99, \"onion\": 3.50}"
},
{
"code": null,
"e": 1834,
"s": 1785,
"text": "You can add multiple items in a similar fashion."
},
{
"code": null,
"e": 1944,
"s": 1834,
"text": "We can also do the opposite — remove one or more items from this list. There are a couple of ways to do that:"
},
{
"code": null,
"e": 1989,
"s": 1944,
"text": "Remove the last item using popitem() method:"
},
{
"code": null,
"e": 2109,
"s": 1989,
"text": "grocery_items.popitem()Out: {\"eggs\": [3.99, 4.99, 5.50], \"banana\": 1.49, \"cheese\": 4.5, \"eggplant\": 2.5, \"bread\": 3.99}"
},
{
"code": null,
"e": 2168,
"s": 2109,
"text": "Or remove an item by its key name using just pop() method:"
},
{
"code": null,
"e": 2276,
"s": 2168,
"text": "grocery_items.pop(\"banana\")Out: {\"eggs\": [3.99, 4.99, 5.50], \"cheese\": 4.5, \"eggplant\": 2.5, \"bread\": 3.99}"
},
{
"code": null,
"e": 2463,
"s": 2276,
"text": "And finally, you can clear the whole dictionary (i.e. making it empty) with clear() method and delete the entire dictionary with del keyword (just be careful if you ever have to use it)."
},
{
"code": null,
"e": 2594,
"s": 2463,
"text": "You may be wondering where someone can find all those methods? Just hit the “tab” key on the keyboard and all methods will pop up."
},
{
"code": null,
"e": 2709,
"s": 2594,
"text": "It’s often necessary to get a list of keys or values in the dictionary for further analysis (we’ll see later why)."
},
{
"code": null,
"e": 2733,
"s": 2709,
"text": "To access all the keys:"
},
{
"code": null,
"e": 2819,
"s": 2733,
"text": "grocery_items.keys()Out: dict_keys(['eggs', 'banana', 'cheese', 'eggplant', 'bread'])"
},
{
"code": null,
"e": 2849,
"s": 2819,
"text": "To access all values instead:"
},
{
"code": null,
"e": 2931,
"s": 2849,
"text": "grocery_items.values()Out: dict_values([[3.99, 4.99, 5.5], 1.49, 4.5, 2.5, 3.99])"
},
{
"code": null,
"e": 3070,
"s": 2931,
"text": "We can also query the dictionary to access the value of a specific key (e.g. the price of bananas). There are a couple of ways to do that:"
},
{
"code": null,
"e": 3157,
"s": 3070,
"text": "# access values by keygrocery_items[\"banana\"]# or grocery_items.get(\"banana\")Out: 1.49"
},
{
"code": null,
"e": 3255,
"s": 3157,
"text": "But what about eggs? We have three different prices for eggs. We can choose to access all prices:"
},
{
"code": null,
"e": 3303,
"s": 3255,
"text": "grocery_items.get(\"eggs\")Out: [3.99, 4.99, 5.5]"
},
{
"code": null,
"e": 3384,
"s": 3303,
"text": "We can also choose to access just the first one from the list by index position:"
},
{
"code": null,
"e": 3422,
"s": 3384,
"text": "grocery_items.get(\"eggs\")[0]Out: 3.99"
},
{
"code": null,
"e": 3516,
"s": 3422,
"text": "In fact, we can access more complex nested dictionary items/keys/values in a similar fashion."
},
{
"code": null,
"e": 3677,
"s": 3516,
"text": "Besides the methods the above, which are most frequently used with a dictionary, there are a few methods and functions which can come in handy in data analysis:"
},
{
"code": null,
"e": 3723,
"s": 3677,
"text": "To get the number of items in the dictionary:"
},
{
"code": null,
"e": 3748,
"s": 3723,
"text": "len(grocery_items)Out: 5"
},
{
"code": null,
"e": 3778,
"s": 3748,
"text": "To change the value of a key:"
},
{
"code": null,
"e": 3817,
"s": 3778,
"text": "grocery_items.update({\"banana\": 0.85})"
},
{
"code": null,
"e": 3845,
"s": 3817,
"text": "To cast the keys as a list:"
},
{
"code": null,
"e": 3919,
"s": 3845,
"text": "list(grocery_items)Out: ['eggs', 'banana', 'cheese', 'eggplant', 'bread']"
},
{
"code": null,
"e": 3989,
"s": 3919,
"text": "If the dictionary is really large, we can check whether a key exists:"
},
{
"code": null,
"e": 4025,
"s": 3989,
"text": "\"potato\" in grocery_itemsOut: False"
},
{
"code": null,
"e": 4095,
"s": 4025,
"text": "And finally, for returning the string representation of a dictionary:"
},
{
"code": null,
"e": 4167,
"s": 4095,
"text": "str(grocery_items)Out: \"{'apple': 2.5, 'orange': 4.99, 'banana': 0.59}\""
},
{
"code": null,
"e": 4401,
"s": 4167,
"text": "It is often necessary to change dictionary elements or extract specific values or keys based on certain conditions. Since dictionaries are iterable objects, for loops are often used for such operations. Here are a couple of examples:"
},
{
"code": null,
"e": 4438,
"s": 4401,
"text": "A simple loop to print all the keys:"
},
{
"code": null,
"e": 4507,
"s": 4438,
"text": "for i in grocery_items: print(i)Out:eggsbananacheeseeggplantbread"
},
{
"code": null,
"e": 4567,
"s": 4507,
"text": "Or a for loop for conditional filtering of dictionary keys:"
},
{
"code": null,
"e": 4655,
"s": 4567,
"text": "for i in grocery_items.keys(): if i.startswith(\"e\"): print(i)Out:eggseggplant"
},
{
"code": null,
"e": 4861,
"s": 4655,
"text": "Like list comprehensions, Python also supports dictionary comprehensions to perform different kinds of operations. The for loops we created above could also be expressed in dictionary comprehension syntax."
},
{
"code": null,
"e": 4911,
"s": 4861,
"text": "For example, to print the values of a dictionary:"
},
{
"code": null,
"e": 4992,
"s": 4911,
"text": "[x for x in grocery_items.values()]Out:[[3.99, 4.99, 5.5], 1.49, 4.5, 2.5, 3.99]"
},
{
"code": null,
"e": 5039,
"s": 4992,
"text": "To summarise, we have covered in this article:"
},
{
"code": null,
"e": 5101,
"s": 5039,
"text": "Python dictionaries are iterable objects with key-value pairs"
},
{
"code": null,
"e": 5161,
"s": 5101,
"text": "dictionaries can be edited to add, remove and update values"
},
{
"code": null,
"e": 5250,
"s": 5161,
"text": "dictionary elements can be accessed with methods such as .keys(), .values() and .items()"
},
{
"code": null,
"e": 5342,
"s": 5250,
"text": "dictionaries are iterable objects, so Python allows for loops or dictionary comprehensions."
},
{
"code": null,
"e": 5491,
"s": 5342,
"text": "I left many other methods and functionalities out, but I hope this gives a head start to build a cheat sheet to work with Python dictionary objects."
}
] |
Distinct permutations of a number - GeeksforGeeks
|
08 Jun, 2021
Given an integer N, the task is to print all distinct permutations of the number N.
Examples:
Input: N = 133Output: 133 313 331Explanation:There are a total of 6 permutations, which are [133, 313, 331, 133, 313, 331].Out of all these permutations, distinct permutations are [133, 313, 331].
Input: N = 7668Output: 7668 7686 7866 6768 6786 6678 6687 6876 6867 8766 8676 8667
Approach: Follow the steps below to solve the problem:
Initialize an empty string to store the equivalent string representation of N.
Initialize a Map to convert each character of the string to an integer and store it as a list.
Permute this list using built-in python functions itertools. permutations().
Initialize another list, say newList.
Traverse the permutations of the list and if the permutation(list) is not in newList then append this list to newList.
Initialize an empty string, s = “” and another empty list say permuteList.
Traverse the list newlist and for each list, perform the following operations:Traverse the list and add each element to the string s.After traversing, convert the string to an integer.Append this integer to permuteList.
Traverse the list and add each element to the string s.
After traversing, convert the string to an integer.
Append this integer to permuteList.
Print the values of permuteList as the possible distinct permutations.
Below is the implementation of the above approach:
Python3
# Python3 program for the above approach from itertools import permutations # Utility function to print# all distinct permutationsdef uniquePermutationsUtil(permute): p = [] # Traverse the list permute[] for i in permute: # Convert this permutation to list permutelist = list(i) # Append this list to p p.append(permutelist) # Stores unique permutations newlist = [] # Traverse list p[] for i in p: # If permutation is # not in newlist if i not in newlist: newlist.append(i) # Initialize empty list permutelist = [] # Traverse the list newlist[] for i in newlist: # Initialize empty string s = "" # Traversing in element list for j in i: # Convert each # element to string s = s + str(j) # Convert string to integer s = int(s) # Append the unique # permutation to permutelist permutelist.append(s) # Print all distinct permutations print(*permutelist) # Function to print all# distinct permutationsdef uniquePermutations(N): # Stores equivalent string # representation of N num = str(N) # Convert each character to # integer and store in the list lis = list(map(int, num)) # Built in method to store all # permutations of the list permute = permutations(lis) # Print unique permutations uniquePermutationsUtil(permute) # Driver Code # Given value of NN = 7668 # Function call to find all# distinct permutations of NuniquePermutations(N)
7668 7686 7866 6768 6786 6678 6687 6876 6867 8766 8676 8667
Time Complexity: O(N * N!)Auxiliary Space: O(N * N!)
ruhelaa48
number-digits
permutation
Combinatorial
Mathematical
Mathematical
permutation
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Find the Number of Permutations that satisfy the given condition in an array
Split array into subarrays at minimum cost by minimizing count of repeating elements in each subarray
Ways to sum to N using Natural Numbers up to K with repetitions allowed
Number of Simple Graph with N Vertices and M Edges
Largest substring with same Characters
Program for Fibonacci numbers
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
Merge two sorted arrays
|
[
{
"code": null,
"e": 25061,
"s": 25033,
"text": "\n08 Jun, 2021"
},
{
"code": null,
"e": 25145,
"s": 25061,
"text": "Given an integer N, the task is to print all distinct permutations of the number N."
},
{
"code": null,
"e": 25155,
"s": 25145,
"text": "Examples:"
},
{
"code": null,
"e": 25352,
"s": 25155,
"text": "Input: N = 133Output: 133 313 331Explanation:There are a total of 6 permutations, which are [133, 313, 331, 133, 313, 331].Out of all these permutations, distinct permutations are [133, 313, 331]."
},
{
"code": null,
"e": 25435,
"s": 25352,
"text": "Input: N = 7668Output: 7668 7686 7866 6768 6786 6678 6687 6876 6867 8766 8676 8667"
},
{
"code": null,
"e": 25490,
"s": 25435,
"text": "Approach: Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 25569,
"s": 25490,
"text": "Initialize an empty string to store the equivalent string representation of N."
},
{
"code": null,
"e": 25664,
"s": 25569,
"text": "Initialize a Map to convert each character of the string to an integer and store it as a list."
},
{
"code": null,
"e": 25741,
"s": 25664,
"text": "Permute this list using built-in python functions itertools. permutations()."
},
{
"code": null,
"e": 25779,
"s": 25741,
"text": "Initialize another list, say newList."
},
{
"code": null,
"e": 25898,
"s": 25779,
"text": "Traverse the permutations of the list and if the permutation(list) is not in newList then append this list to newList."
},
{
"code": null,
"e": 25973,
"s": 25898,
"text": "Initialize an empty string, s = “” and another empty list say permuteList."
},
{
"code": null,
"e": 26193,
"s": 25973,
"text": "Traverse the list newlist and for each list, perform the following operations:Traverse the list and add each element to the string s.After traversing, convert the string to an integer.Append this integer to permuteList."
},
{
"code": null,
"e": 26249,
"s": 26193,
"text": "Traverse the list and add each element to the string s."
},
{
"code": null,
"e": 26301,
"s": 26249,
"text": "After traversing, convert the string to an integer."
},
{
"code": null,
"e": 26337,
"s": 26301,
"text": "Append this integer to permuteList."
},
{
"code": null,
"e": 26408,
"s": 26337,
"text": "Print the values of permuteList as the possible distinct permutations."
},
{
"code": null,
"e": 26459,
"s": 26408,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26467,
"s": 26459,
"text": "Python3"
},
{
"code": "# Python3 program for the above approach from itertools import permutations # Utility function to print# all distinct permutationsdef uniquePermutationsUtil(permute): p = [] # Traverse the list permute[] for i in permute: # Convert this permutation to list permutelist = list(i) # Append this list to p p.append(permutelist) # Stores unique permutations newlist = [] # Traverse list p[] for i in p: # If permutation is # not in newlist if i not in newlist: newlist.append(i) # Initialize empty list permutelist = [] # Traverse the list newlist[] for i in newlist: # Initialize empty string s = \"\" # Traversing in element list for j in i: # Convert each # element to string s = s + str(j) # Convert string to integer s = int(s) # Append the unique # permutation to permutelist permutelist.append(s) # Print all distinct permutations print(*permutelist) # Function to print all# distinct permutationsdef uniquePermutations(N): # Stores equivalent string # representation of N num = str(N) # Convert each character to # integer and store in the list lis = list(map(int, num)) # Built in method to store all # permutations of the list permute = permutations(lis) # Print unique permutations uniquePermutationsUtil(permute) # Driver Code # Given value of NN = 7668 # Function call to find all# distinct permutations of NuniquePermutations(N)",
"e": 28151,
"s": 26467,
"text": null
},
{
"code": null,
"e": 28211,
"s": 28151,
"text": "7668 7686 7866 6768 6786 6678 6687 6876 6867 8766 8676 8667"
},
{
"code": null,
"e": 28266,
"s": 28213,
"text": "Time Complexity: O(N * N!)Auxiliary Space: O(N * N!)"
},
{
"code": null,
"e": 28276,
"s": 28266,
"text": "ruhelaa48"
},
{
"code": null,
"e": 28290,
"s": 28276,
"text": "number-digits"
},
{
"code": null,
"e": 28302,
"s": 28290,
"text": "permutation"
},
{
"code": null,
"e": 28316,
"s": 28302,
"text": "Combinatorial"
},
{
"code": null,
"e": 28329,
"s": 28316,
"text": "Mathematical"
},
{
"code": null,
"e": 28342,
"s": 28329,
"text": "Mathematical"
},
{
"code": null,
"e": 28354,
"s": 28342,
"text": "permutation"
},
{
"code": null,
"e": 28368,
"s": 28354,
"text": "Combinatorial"
},
{
"code": null,
"e": 28466,
"s": 28368,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28475,
"s": 28466,
"text": "Comments"
},
{
"code": null,
"e": 28488,
"s": 28475,
"text": "Old Comments"
},
{
"code": null,
"e": 28565,
"s": 28488,
"text": "Find the Number of Permutations that satisfy the given condition in an array"
},
{
"code": null,
"e": 28667,
"s": 28565,
"text": "Split array into subarrays at minimum cost by minimizing count of repeating elements in each subarray"
},
{
"code": null,
"e": 28739,
"s": 28667,
"text": "Ways to sum to N using Natural Numbers up to K with repetitions allowed"
},
{
"code": null,
"e": 28790,
"s": 28739,
"text": "Number of Simple Graph with N Vertices and M Edges"
},
{
"code": null,
"e": 28829,
"s": 28790,
"text": "Largest substring with same Characters"
},
{
"code": null,
"e": 28859,
"s": 28829,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 28874,
"s": 28859,
"text": "C++ Data Types"
},
{
"code": null,
"e": 28917,
"s": 28874,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 28936,
"s": 28917,
"text": "Coin Change | DP-7"
}
] |
Python PostgreSQL - Insert Data
|
You can insert record into an existing table in PostgreSQL using the INSERT INTO statement. While executing this, you need to specify the name of the table, and values for the columns in it.
Following is the recommended syntax of the INSERT statement −
INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)
VALUES (value1, value2, value3,...valueN);
Where, column1, column2, column3,.. are the names of the columns of a table, and value1, value2, value3,... are the values you need to insert into the table.
Assume we have created a table with name CRICKETERS using the CREATE TABLE statement as shown below −
postgres=# CREATE TABLE CRICKETERS (
First_Name VARCHAR(255),
Last_Name VARCHAR(255),
Age INT,
Place_Of_Birth VARCHAR(255),
Country VARCHAR(255)
);
CREATE TABLE
postgres=#
Following PostgreSQL statement inserts a row in the above created table −
postgres=# insert into CRICKETERS (
First_Name, Last_Name, Age, Place_Of_Birth, Country)
values('Shikhar', 'Dhawan', 33, 'Delhi', 'India');
INSERT 0 1
postgres=#
While inserting records using the INSERT INTO statement, if you skip any columns names Record will be inserted leaving empty spaces at columns which you have skipped.
postgres=# insert into CRICKETERS (First_Name, Last_Name, Country)
values('Jonathan', 'Trott', 'SouthAfrica');
INSERT 0 1
You can also insert records into a table without specifying the column names, if the order of values you pass is same as their respective column names in the table.
postgres=# insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka');
INSERT 0 1
postgres=# insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India');
INSERT 0 1
postgres=# insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India');
INSERT 0 1
postgres=#
After inserting the records into a table you can verify its contents using the SELECT statement as shown below −
postgres=# SELECT * from CRICKETERS;
first_name | last_name | age | place_of_birth | country
------------+------------+-----+----------------+-------------
Shikhar | Dhawan | 33 | Delhi | India
Jonathan | Trott | | | SouthAfrica
Kumara | Sangakkara | 41 | Matale | Srilanka
Virat | Kohli | 30 | Delhi | India
Rohit | Sharma | 32 | Nagpur | India
(5 rows)
The cursor class of psycopg2 provides a method with name execute() method. This method accepts the query as a parameter and executes it.
Therefore, to insert data into a table in PostgreSQL using python −
Import psycopg2 package.
Import psycopg2 package.
Create a connection object using the connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it.
Create a connection object using the connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it.
Turn off the auto-commit mode by setting false as value to the attribute autocommit.
Turn off the auto-commit mode by setting false as value to the attribute autocommit.
The cursor() method of the Connection class of the psycopg2 library returns a cursor object. Create a cursor object using this method.
The cursor() method of the Connection class of the psycopg2 library returns a cursor object. Create a cursor object using this method.
Then, execute the INSERT statement(s) by passing it/them as a parameter to the execute() method.
Then, execute the INSERT statement(s) by passing it/them as a parameter to the execute() method.
Following Python program creates a table with name EMPLOYEE in PostgreSQL database and inserts records into it using the execute() method −
import psycopg2
#Establishing the connection
conn = psycopg2.connect(
database="mydb", user='postgres', password='password', host='127.0.0.1', port= '5432'
)
#Setting auto commit false
conn.autocommit = True
#Creating a cursor object using the cursor() method
cursor = conn.cursor()
# Preparing SQL queries to INSERT a record into the database.
cursor.execute('''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX,
INCOME) VALUES ('Ramya', 'Rama priya', 27, 'F', 9000)''')
cursor.execute('''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX,
INCOME) VALUES ('Vinay', 'Battacharya', 20, 'M', 6000)''')
cursor.execute('''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX,
INCOME) VALUES ('Sharukh', 'Sheik', 25, 'M', 8300)''')
cursor.execute('''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX,
INCOME) VALUES ('Sarmista', 'Sharma', 26, 'F', 10000)''')
cursor.execute('''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX,
INCOME) VALUES ('Tripthi', 'Mishra', 24, 'F', 6000)''')
# Commit your changes in the database
conn.commit()
print("Records inserted........")
# Closing the connection
conn.close()
Records inserted........
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3396,
"s": 3205,
"text": "You can insert record into an existing table in PostgreSQL using the INSERT INTO statement. While executing this, you need to specify the name of the table, and values for the columns in it."
},
{
"code": null,
"e": 3458,
"s": 3396,
"text": "Following is the recommended syntax of the INSERT statement −"
},
{
"code": null,
"e": 3564,
"s": 3458,
"text": "INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)\nVALUES (value1, value2, value3,...valueN);\n"
},
{
"code": null,
"e": 3722,
"s": 3564,
"text": "Where, column1, column2, column3,.. are the names of the columns of a table, and value1, value2, value3,... are the values you need to insert into the table."
},
{
"code": null,
"e": 3824,
"s": 3722,
"text": "Assume we have created a table with name CRICKETERS using the CREATE TABLE statement as shown below −"
},
{
"code": null,
"e": 4011,
"s": 3824,
"text": "postgres=# CREATE TABLE CRICKETERS (\n First_Name VARCHAR(255),\n Last_Name VARCHAR(255),\n Age INT,\n Place_Of_Birth VARCHAR(255),\n Country VARCHAR(255)\n);\nCREATE TABLE\npostgres=#"
},
{
"code": null,
"e": 4085,
"s": 4011,
"text": "Following PostgreSQL statement inserts a row in the above created table −"
},
{
"code": null,
"e": 4255,
"s": 4085,
"text": "postgres=# insert into CRICKETERS (\n First_Name, Last_Name, Age, Place_Of_Birth, Country) \n values('Shikhar', 'Dhawan', 33, 'Delhi', 'India');\nINSERT 0 1\npostgres=#\n"
},
{
"code": null,
"e": 4422,
"s": 4255,
"text": "While inserting records using the INSERT INTO statement, if you skip any columns names Record will be inserted leaving empty spaces at columns which you have skipped."
},
{
"code": null,
"e": 4549,
"s": 4422,
"text": "postgres=# insert into CRICKETERS (First_Name, Last_Name, Country) \n values('Jonathan', 'Trott', 'SouthAfrica');\nINSERT 0 1\n"
},
{
"code": null,
"e": 4714,
"s": 4549,
"text": "You can also insert records into a table without specifying the column names, if the order of values you pass is same as their respective column names in the table."
},
{
"code": null,
"e": 5016,
"s": 4714,
"text": "postgres=# insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka');\nINSERT 0 1\npostgres=# insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India');\nINSERT 0 1\npostgres=# insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India');\nINSERT 0 1\npostgres=#"
},
{
"code": null,
"e": 5129,
"s": 5016,
"text": "After inserting the records into a table you can verify its contents using the SELECT statement as shown below −"
},
{
"code": null,
"e": 5586,
"s": 5129,
"text": "postgres=# SELECT * from CRICKETERS;\nfirst_name | last_name | age | place_of_birth | country\n------------+------------+-----+----------------+-------------\nShikhar | Dhawan | 33 | Delhi | India\nJonathan | Trott | | | SouthAfrica\nKumara | Sangakkara | 41 | Matale | Srilanka\nVirat | Kohli | 30 | Delhi | India\nRohit | Sharma | 32 | Nagpur | India\n(5 rows)\n"
},
{
"code": null,
"e": 5723,
"s": 5586,
"text": "The cursor class of psycopg2 provides a method with name execute() method. This method accepts the query as a parameter and executes it."
},
{
"code": null,
"e": 5791,
"s": 5723,
"text": "Therefore, to insert data into a table in PostgreSQL using python −"
},
{
"code": null,
"e": 5816,
"s": 5791,
"text": "Import psycopg2 package."
},
{
"code": null,
"e": 5841,
"s": 5816,
"text": "Import psycopg2 package."
},
{
"code": null,
"e": 6013,
"s": 5841,
"text": "Create a connection object using the connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it."
},
{
"code": null,
"e": 6185,
"s": 6013,
"text": "Create a connection object using the connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it."
},
{
"code": null,
"e": 6270,
"s": 6185,
"text": "Turn off the auto-commit mode by setting false as value to the attribute autocommit."
},
{
"code": null,
"e": 6355,
"s": 6270,
"text": "Turn off the auto-commit mode by setting false as value to the attribute autocommit."
},
{
"code": null,
"e": 6490,
"s": 6355,
"text": "The cursor() method of the Connection class of the psycopg2 library returns a cursor object. Create a cursor object using this method."
},
{
"code": null,
"e": 6625,
"s": 6490,
"text": "The cursor() method of the Connection class of the psycopg2 library returns a cursor object. Create a cursor object using this method."
},
{
"code": null,
"e": 6722,
"s": 6625,
"text": "Then, execute the INSERT statement(s) by passing it/them as a parameter to the execute() method."
},
{
"code": null,
"e": 6819,
"s": 6722,
"text": "Then, execute the INSERT statement(s) by passing it/them as a parameter to the execute() method."
},
{
"code": null,
"e": 6959,
"s": 6819,
"text": "Following Python program creates a table with name EMPLOYEE in PostgreSQL database and inserts records into it using the execute() method −"
},
{
"code": null,
"e": 8097,
"s": 6959,
"text": "import psycopg2\n\n#Establishing the connection\nconn = psycopg2.connect(\n database=\"mydb\", user='postgres', password='password', host='127.0.0.1', port= '5432'\n)\n#Setting auto commit false\nconn.autocommit = True\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n# Preparing SQL queries to INSERT a record into the database.\ncursor.execute('''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX,\n INCOME) VALUES ('Ramya', 'Rama priya', 27, 'F', 9000)''')\ncursor.execute('''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX,\n INCOME) VALUES ('Vinay', 'Battacharya', 20, 'M', 6000)''')\ncursor.execute('''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX,\n INCOME) VALUES ('Sharukh', 'Sheik', 25, 'M', 8300)''')\ncursor.execute('''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX,\n INCOME) VALUES ('Sarmista', 'Sharma', 26, 'F', 10000)''')\ncursor.execute('''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX,\n INCOME) VALUES ('Tripthi', 'Mishra', 24, 'F', 6000)''')\n\n# Commit your changes in the database\nconn.commit()\nprint(\"Records inserted........\")\n\n# Closing the connection\nconn.close()"
},
{
"code": null,
"e": 8123,
"s": 8097,
"text": "Records inserted........\n"
},
{
"code": null,
"e": 8160,
"s": 8123,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 8176,
"s": 8160,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 8209,
"s": 8176,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 8228,
"s": 8209,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 8263,
"s": 8228,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 8285,
"s": 8263,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 8319,
"s": 8285,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 8347,
"s": 8319,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 8382,
"s": 8347,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 8396,
"s": 8382,
"text": " Lets Kode It"
},
{
"code": null,
"e": 8429,
"s": 8396,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 8446,
"s": 8429,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 8453,
"s": 8446,
"text": " Print"
},
{
"code": null,
"e": 8464,
"s": 8453,
"text": " Add Notes"
}
] |
C program to remove extra spaces using string concepts.
|
Remove all the extra spaces from an entered string at runtime with the help of while loop by checking the spaces at each index of a character.
Consider an example given below −
It removes all the spaces from a given string. The given string is Tutorials Point C Programming. The result after removing spaces is TutorialsPointCProgramming.
An array of characters is called a string.
Given below is the declaration of a string −
char stringname [size];
For example, char string[50]; string of length 50 characters.
Using single character constant.
char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’}
Using string constants.
char string[10] = “Hello”:;
There is a control string “%s” used for accessing the string till it encounters ‘\0’.
The logic we used to remove extra spaces between strings is as follows −
len = strlen(string);
for(i=0; i<len; i++){
if(string[0]==' '){
for(i=0; i<(len-1); i++)
string[i] = string[i+1];
string[i] = '\0';
len--;
i = -1;
continue;
}
if(string[i]==' ' && string[i+1]==' '){
for(j=i; j<(len-1); j++){
string[j] = string[j+1];
}
string[j] = '\0';
len--;
i--;
}
}
Following is the C program to remove all the extra spaces in a sentence by using the string concepts −
#include<stdio.h>
int main() {
char string[200];
int i, j, len;
printf("Enter a statement: ");
gets(string);
len = strlen(string);
for(i=0; i<len; i++) {
if(string[0]==' ') {
for(i=0; i<(len-1); i++)
string[i] = string[i+1];
string[i] = '\0';
len--;
i = -1;
continue;
}
if(string[i]==' ' && string[i+1]==' ') {
for(j=i; j<(len-1); j++) {
string[j] = string[j+1];
}
string[j] = '\0';
len--;
i--;
}
}
printf("\nNew String after removing extra spaces is = %s", string);
getch();
return 0;
}
When the above program is executed, it produces the following output −
Enter a statement: Welcome to The world of C programming
New String after removing extra spaces is = Welcome to The world of C programming
|
[
{
"code": null,
"e": 1205,
"s": 1062,
"text": "Remove all the extra spaces from an entered string at runtime with the help of while loop by checking the spaces at each index of a character."
},
{
"code": null,
"e": 1239,
"s": 1205,
"text": "Consider an example given below −"
},
{
"code": null,
"e": 1401,
"s": 1239,
"text": "It removes all the spaces from a given string. The given string is Tutorials Point C Programming. The result after removing spaces is TutorialsPointCProgramming."
},
{
"code": null,
"e": 1444,
"s": 1401,
"text": "An array of characters is called a string."
},
{
"code": null,
"e": 1489,
"s": 1444,
"text": "Given below is the declaration of a string −"
},
{
"code": null,
"e": 1513,
"s": 1489,
"text": "char stringname [size];"
},
{
"code": null,
"e": 1575,
"s": 1513,
"text": "For example, char string[50]; string of length 50 characters."
},
{
"code": null,
"e": 1608,
"s": 1575,
"text": "Using single character constant."
},
{
"code": null,
"e": 1659,
"s": 1608,
"text": "char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\\0’}"
},
{
"code": null,
"e": 1683,
"s": 1659,
"text": "Using string constants."
},
{
"code": null,
"e": 1711,
"s": 1683,
"text": "char string[10] = “Hello”:;"
},
{
"code": null,
"e": 1797,
"s": 1711,
"text": "There is a control string “%s” used for accessing the string till it encounters ‘\\0’."
},
{
"code": null,
"e": 1870,
"s": 1797,
"text": "The logic we used to remove extra spaces between strings is as follows −"
},
{
"code": null,
"e": 2243,
"s": 1870,
"text": "len = strlen(string);\nfor(i=0; i<len; i++){\n if(string[0]==' '){\n for(i=0; i<(len-1); i++)\n string[i] = string[i+1];\n string[i] = '\\0';\n len--;\n i = -1;\n continue;\n }\n if(string[i]==' ' && string[i+1]==' '){\n for(j=i; j<(len-1); j++){\n string[j] = string[j+1];\n }\n string[j] = '\\0';\n len--;\n i--;\n }\n}"
},
{
"code": null,
"e": 2346,
"s": 2243,
"text": "Following is the C program to remove all the extra spaces in a sentence by using the string concepts −"
},
{
"code": null,
"e": 2999,
"s": 2346,
"text": "#include<stdio.h>\nint main() {\n char string[200];\n int i, j, len;\n printf(\"Enter a statement: \");\n gets(string);\n len = strlen(string);\n for(i=0; i<len; i++) {\n if(string[0]==' ') {\n for(i=0; i<(len-1); i++)\n string[i] = string[i+1];\n string[i] = '\\0';\n len--;\n i = -1;\n continue;\n }\n if(string[i]==' ' && string[i+1]==' ') {\n for(j=i; j<(len-1); j++) {\n string[j] = string[j+1];\n }\n string[j] = '\\0';\n len--;\n i--;\n }\n }\n printf(\"\\nNew String after removing extra spaces is = %s\", string);\n getch();\n return 0;\n}"
},
{
"code": null,
"e": 3070,
"s": 2999,
"text": "When the above program is executed, it produces the following output −"
},
{
"code": null,
"e": 3209,
"s": 3070,
"text": "Enter a statement: Welcome to The world of C programming\nNew String after removing extra spaces is = Welcome to The world of C programming"
}
] |
Hibernate - Many-to-One Mappings
|
A many-to-one association is the most common kind of association where an Object can be associated with multiple objects. For example, the same address object can be associated with multiple employee objects.
Consider a situation where we need to store our employee records in EMPLOYEE table, which will have the following structure −
create table EMPLOYEE (
id INT NOT NULL auto_increment,
first_name VARCHAR(20) default NULL,
last_name VARCHAR(20) default NULL,
salary INT default NULL,
address INT NOT NULL,
PRIMARY KEY (id)
);
Further, many employee can have same address, so this association can be presented using many-to-one association. We will store address related information in a separate table having the following structure −
create table ADDRESS (
id INT NOT NULL auto_increment,
street_name VARCHAR(40) default NULL,
city_name VARCHAR(40) default NULL,
state_name VARCHAR(40) default NULL,
zipcode VARCHAR(10) default NULL,
PRIMARY KEY (id)
);
Create both the RBDMS tables and keep them ready for the next implementation.
Let us implement a POJO class Employee, which will be used to persist the objects related to EMPLOYEE table and having a variable of Address type.
import java.util.*;
public class Employee{
private int id;
private String firstName;
private String lastName;
private int salary;
private Address address;
public Employee() {}
public Employee(String fname, String lname, int salary, Address address ) {
this.firstName = fname;
this.lastName = lname;
this.salary = salary;
this.address = address;
}
public int getId() {
return id;
}
public void setId( int id ) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName( String first_name ) {
this.firstName = first_name;
}
public String getLastName() {
return lastName;
}
public void setLastName( String last_name ) {
this.lastName = last_name;
}
public int getSalary() {
return salary;
}
public void setSalary( int salary ) {
this.salary = salary;
}
public Address getAddress() {
return address;
}
public void setAddress( Address address ) {
this.address = address;
}
}
We need to define another POJO class corresponding to ADDRESS table so that address objects can be stored and retrieved into the ADDRESS table.
import java.util.*;
public class Address{
private int id;
private String street;
private String city;
private String state;
private String zipcode;
public Address() {}
public Address(String street, String city, String state, String zipcode) {
this.street = street;
this.city = city;
this.state = state;
this.zipcode = zipcode;
}
public int getId() {
return id;
}
public void setId( int id ) {
this.id = id;
}
public String getStreet() {
return street;
}
public void setStreet( String street ) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity( String city ) {
this.city = city;
}
public String getState() {
return state;
}
public void setState( String state ) {
this.state = state;
}
public String getZipcode() {
return zipcode;
}
public void setZipcode( String zipcode ) {
this.zipcode = zipcode;
}
}
Let us develop our mapping files, which instructs Hibernate how to map the defined classes to the database tables. The <many-to-one> element will be used to define the rule to establish a many-to-one relationship between EMPLOYEE and ADDRESS entities.
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name = "Employee" table = "EMPLOYEE">
<meta attribute = "class-description">
This class contains the employee detail.
</meta>
<id name = "id" type = "int" column = "id">
<generator class="native"/>
</id>
<property name = "firstName" column = "first_name" type = "string"/>
<property name = "lastName" column = "last_name" type = "string"/>
<property name = "salary" column = "salary" type = "int"/>
<many-to-one name = "address" column = "address"
class="Address" not-null="true"/>
</class>
<class name = "Address" table="ADDRESS">
<meta attribute = "class-description">
This class contains the address detail.
</meta>
<id name = "id" type = "int" column = "id">
<generator class="native"/>
</id>
<property name = "street" column = "street_name" type = "string"/>
<property name = "city" column = "city_name" type = "string"/>
<property name = "state" column = "state_name" type = "string"/>
<property name = "zipcode" column = "zipcode" type = "string"/>
</class>
</hibernate-mapping>
You should save the mapping document in a file with the format <classname>.hbm.xml. We saved our mapping document in the file Employee.hbm.xml. You are already familiar with most of the mapping detail, but let us see all the elements of mapping file once again −
The mapping document is an XML document having <hibernate-mapping> as the root element which contains two <class> elements corresponding to each class.
The mapping document is an XML document having <hibernate-mapping> as the root element which contains two <class> elements corresponding to each class.
The <class> elements are used to define specific mappings from a Java classes to the database tables. The Java class name is specified using the name attribute of the class element and the database table name is specified using the table attribute.
The <class> elements are used to define specific mappings from a Java classes to the database tables. The Java class name is specified using the name attribute of the class element and the database table name is specified using the table attribute.
The <meta> element is optional element and can be used to create the class description.
The <meta> element is optional element and can be used to create the class description.
The <id> element maps the unique ID attribute in class to the primary key of the database table. The name attribute of the id element refers to the property in the class and the column attribute refers to the column in the database table. The type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type.
The <id> element maps the unique ID attribute in class to the primary key of the database table. The name attribute of the id element refers to the property in the class and the column attribute refers to the column in the database table. The type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type.
The <generator> element within the id element is used to generate the primary key values automatically. The class attribute of the generator element is set to native to let hibernate pick up either identity, sequence or hilo algorithm to create primary key depending upon the capabilities of the underlying database.
The <generator> element within the id element is used to generate the primary key values automatically. The class attribute of the generator element is set to native to let hibernate pick up either identity, sequence or hilo algorithm to create primary key depending upon the capabilities of the underlying database.
The <property> element is used to map a Java class property to a column in the database table. The name attribute of the element refers to the property in the class and the column attribute refers to the column in the database table. The type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type.
The <property> element is used to map a Java class property to a column in the database table. The name attribute of the element refers to the property in the class and the column attribute refers to the column in the database table. The type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type.
The <many-to-one> element is used to set the relationship between EMPLOYEE and ADDRESS entities. The name attribute is set to the defined variable in the parent class, in our case it is address. The column attribute is used to set the column name in the parent table EMPLOYEE.
The <many-to-one> element is used to set the relationship between EMPLOYEE and ADDRESS entities. The name attribute is set to the defined variable in the parent class, in our case it is address. The column attribute is used to set the column name in the parent table EMPLOYEE.
Finally, we will create our application class with the main() method to run the application. We will use this application to save few Employee's records along with their addresses and then we will apply CRUD operations on those records.
import java.util.*;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class ManageEmployee {
private static SessionFactory factory;
public static void main(String[] args) {
try {
factory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
ManageEmployee ME = new ManageEmployee();
/* Let us have one address object */
Address address = ME.addAddress("Kondapur","Hyderabad","AP","532");
/* Add employee records in the database */
Integer empID1 = ME.addEmployee("Manoj", "Kumar", 4000, address);
/* Add another employee record in the database */
Integer empID2 = ME.addEmployee("Dilip", "Kumar", 3000, address);
/* List down all the employees */
ME.listEmployees();
/* Update employee's salary records */
ME.updateEmployee(empID1, 5000);
/* Delete an employee from the database */
ME.deleteEmployee(empID2);
/* List down all the employees */
ME.listEmployees();
}
/* Method to add an address record in the database */
public Address addAddress(String street, String city, String state, String zipcode) {
Session session = factory.openSession();
Transaction tx = null;
Integer addressID = null;
Address address = null;
try {
tx = session.beginTransaction();
address = new Address(street, city, state, zipcode);
addressID = (Integer) session.save(address);
tx.commit();
} catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
return address;
}
/* Method to add an employee record in the database */
public Integer addEmployee(String fname, String lname, int salary, Address address){
Session session = factory.openSession();
Transaction tx = null;
Integer employeeID = null;
try {
tx = session.beginTransaction();
Employee employee = new Employee(fname, lname, salary, address);
employeeID = (Integer) session.save(employee);
tx.commit();
} catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
return employeeID;
}
/* Method to list all the employees detail */
public void listEmployees( ){
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
List employees = session.createQuery("FROM Employee").list();
for (Iterator iterator = employees.iterator(); iterator.hasNext();){
Employee employee = (Employee) iterator.next();
System.out.print("First Name: " + employee.getFirstName());
System.out.print(" Last Name: " + employee.getLastName());
System.out.println(" Salary: " + employee.getSalary());
Address add = employee.getAddress();
System.out.println("Address ");
System.out.println("\tStreet: " + add.getStreet());
System.out.println("\tCity: " + add.getCity());
System.out.println("\tState: " + add.getState());
System.out.println("\tZipcode: " + add.getZipcode());
}
tx.commit();
} catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
/* Method to update salary for an employee */
public void updateEmployee(Integer EmployeeID, int salary ){
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Employee employee = (Employee)session.get(Employee.class, EmployeeID);
employee.setSalary( salary );
session.update(employee);
tx.commit();
} catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
/* Method to delete an employee from the records */
public void deleteEmployee(Integer EmployeeID){
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Employee employee = (Employee)session.get(Employee.class, EmployeeID);
session.delete(employee);
tx.commit();
} catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
}
Here are the steps to compile and run the above mentioned application. Make sure you have set PATH and CLASSPATH appropriately before proceeding for the compilation and execution.
Create hibernate.cfg.xml configuration file as explained in configuration chapter.
Create hibernate.cfg.xml configuration file as explained in configuration chapter.
Create Employee.hbm.xml mapping file as shown above.
Create Employee.hbm.xml mapping file as shown above.
Create Employee.java source file as shown above and compile it.
Create Employee.java source file as shown above and compile it.
Create Address.java source file as shown above and compile it.
Create Address.java source file as shown above and compile it.
Create ManageEmployee.java source file as shown above and compile it.
Create ManageEmployee.java source file as shown above and compile it.
Execute ManageEmployee binary to run the program.
Execute ManageEmployee binary to run the program.
You would get the following result on the screen, and same time records would be created in EMPLOYEE and ADDRESS tables.
$java ManageEmployee
.......VARIOUS LOG MESSAGES WILL DISPLAY HERE........
First Name: Manoj Last Name: Kumar Salary: 4000
Address
Street: Kondapur
City: Hyderabad
State: AP
Zipcode: 532
First Name: Dilip Last Name: Kumar Salary: 3000
Address
Street: Kondapur
City: Hyderabad
State: AP
Zipcode: 532
First Name: Manoj Last Name: Kumar Salary: 5000
Address
Street: Kondapur
City: Hyderabad
State: AP
Zipcode: 532
If you check your EMPLOYEE and ADDRESS tables, they should have the following records −
mysql> select * from EMPLOYEE;
+----+------------+-----------+--------+---------+
| id | first_name | last_name | salary | address |
+----+------------+-----------+--------+---------+
| 1 | Manoj | Kumar | 5000 | 5 |
+----+------------+-----------+--------+---------+
1 row in set (0.00 sec)
mysql> select * from ADDRESS;
+----+-------------+-----------+------------+---------+
| id | street_name | city_name | state_name | zipcode |
+----+-------------+-----------+------------+---------+
| 1 | Kondapur | Hyderabad | AP | 532 |
+----+-------------+-----------+------------+---------+
1 row in set (0.00 sec)
mysql>
108 Lectures
11 hours
Chaand Sheikh
65 Lectures
5 hours
Karthikeya T
39 Lectures
4.5 hours
TELCOMA Global
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2272,
"s": 2063,
"text": "A many-to-one association is the most common kind of association where an Object can be associated with multiple objects. For example, the same address object can be associated with multiple employee objects."
},
{
"code": null,
"e": 2398,
"s": 2272,
"text": "Consider a situation where we need to store our employee records in EMPLOYEE table, which will have the following structure −"
},
{
"code": null,
"e": 2621,
"s": 2398,
"text": "create table EMPLOYEE (\n id INT NOT NULL auto_increment,\n first_name VARCHAR(20) default NULL,\n last_name VARCHAR(20) default NULL,\n salary INT default NULL,\n address INT NOT NULL,\n PRIMARY KEY (id)\n);"
},
{
"code": null,
"e": 2830,
"s": 2621,
"text": "Further, many employee can have same address, so this association can be presented using many-to-one association. We will store address related information in a separate table having the following structure −"
},
{
"code": null,
"e": 3068,
"s": 2830,
"text": "create table ADDRESS (\n id INT NOT NULL auto_increment,\n street_name VARCHAR(40) default NULL,\n city_name VARCHAR(40) default NULL,\n state_name VARCHAR(40) default NULL,\n zipcode VARCHAR(10) default NULL,\n PRIMARY KEY (id)\n);"
},
{
"code": null,
"e": 3146,
"s": 3068,
"text": "Create both the RBDMS tables and keep them ready for the next implementation."
},
{
"code": null,
"e": 3293,
"s": 3146,
"text": "Let us implement a POJO class Employee, which will be used to persist the objects related to EMPLOYEE table and having a variable of Address type."
},
{
"code": null,
"e": 4413,
"s": 3293,
"text": "import java.util.*;\n\npublic class Employee{\n private int id;\n private String firstName; \n private String lastName; \n private int salary;\n private Address address;\n\n public Employee() {}\n \n public Employee(String fname, String lname, int salary, Address address ) {\n this.firstName = fname;\n this.lastName = lname;\n this.salary = salary;\n this.address = address;\n }\n \n public int getId() {\n return id;\n }\n \n public void setId( int id ) {\n this.id = id;\n }\n \n public String getFirstName() {\n return firstName;\n }\n \n public void setFirstName( String first_name ) {\n this.firstName = first_name;\n }\n \n public String getLastName() {\n return lastName;\n }\n \n public void setLastName( String last_name ) {\n this.lastName = last_name;\n }\n \n public int getSalary() {\n return salary;\n }\n \n public void setSalary( int salary ) {\n this.salary = salary;\n }\n\n public Address getAddress() {\n return address;\n }\n \n public void setAddress( Address address ) {\n this.address = address;\n }\n}"
},
{
"code": null,
"e": 4557,
"s": 4413,
"text": "We need to define another POJO class corresponding to ADDRESS table so that address objects can be stored and retrieved into the ADDRESS table."
},
{
"code": null,
"e": 5633,
"s": 4557,
"text": "import java.util.*;\n\npublic class Address{\n private int id;\n private String street; \n private String city; \n private String state; \n private String zipcode; \n\n public Address() {}\n \n public Address(String street, String city, String state, String zipcode) {\n this.street = street; \n this.city = city; \n this.state = state; \n this.zipcode = zipcode; \n }\n \n public int getId() {\n return id;\n }\n \n public void setId( int id ) {\n this.id = id;\n }\n \n public String getStreet() {\n return street;\n }\n \n public void setStreet( String street ) {\n this.street = street;\n }\n \n public String getCity() {\n return city;\n }\n \n public void setCity( String city ) {\n this.city = city;\n }\n \n public String getState() {\n return state;\n }\n \n public void setState( String state ) {\n this.state = state;\n }\n \n public String getZipcode() {\n return zipcode;\n }\n \n public void setZipcode( String zipcode ) {\n this.zipcode = zipcode;\n }\n \n}"
},
{
"code": null,
"e": 5885,
"s": 5633,
"text": "Let us develop our mapping files, which instructs Hibernate how to map the defined classes to the database tables. The <many-to-one> element will be used to define the rule to establish a many-to-one relationship between EMPLOYEE and ADDRESS entities."
},
{
"code": null,
"e": 7295,
"s": 5885,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<!DOCTYPE hibernate-mapping PUBLIC \n\"-//Hibernate/Hibernate Mapping DTD//EN\"\n\"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd\"> \n\n<hibernate-mapping>\n <class name = \"Employee\" table = \"EMPLOYEE\">\n \n <meta attribute = \"class-description\">\n This class contains the employee detail. \n </meta>\n \n <id name = \"id\" type = \"int\" column = \"id\">\n <generator class=\"native\"/>\n </id>\n \n <property name = \"firstName\" column = \"first_name\" type = \"string\"/>\n <property name = \"lastName\" column = \"last_name\" type = \"string\"/>\n <property name = \"salary\" column = \"salary\" type = \"int\"/>\n <many-to-one name = \"address\" column = \"address\" \n class=\"Address\" not-null=\"true\"/>\n \n </class>\n\n <class name = \"Address\" table=\"ADDRESS\">\n \n <meta attribute = \"class-description\">\n This class contains the address detail. \n </meta>\n \n <id name = \"id\" type = \"int\" column = \"id\">\n <generator class=\"native\"/>\n </id>\n \n <property name = \"street\" column = \"street_name\" type = \"string\"/>\n <property name = \"city\" column = \"city_name\" type = \"string\"/>\n <property name = \"state\" column = \"state_name\" type = \"string\"/>\n <property name = \"zipcode\" column = \"zipcode\" type = \"string\"/>\n \n </class>\n\n</hibernate-mapping>"
},
{
"code": null,
"e": 7558,
"s": 7295,
"text": "You should save the mapping document in a file with the format <classname>.hbm.xml. We saved our mapping document in the file Employee.hbm.xml. You are already familiar with most of the mapping detail, but let us see all the elements of mapping file once again −"
},
{
"code": null,
"e": 7710,
"s": 7558,
"text": "The mapping document is an XML document having <hibernate-mapping> as the root element which contains two <class> elements corresponding to each class."
},
{
"code": null,
"e": 7862,
"s": 7710,
"text": "The mapping document is an XML document having <hibernate-mapping> as the root element which contains two <class> elements corresponding to each class."
},
{
"code": null,
"e": 8111,
"s": 7862,
"text": "The <class> elements are used to define specific mappings from a Java classes to the database tables. The Java class name is specified using the name attribute of the class element and the database table name is specified using the table attribute."
},
{
"code": null,
"e": 8360,
"s": 8111,
"text": "The <class> elements are used to define specific mappings from a Java classes to the database tables. The Java class name is specified using the name attribute of the class element and the database table name is specified using the table attribute."
},
{
"code": null,
"e": 8448,
"s": 8360,
"text": "The <meta> element is optional element and can be used to create the class description."
},
{
"code": null,
"e": 8536,
"s": 8448,
"text": "The <meta> element is optional element and can be used to create the class description."
},
{
"code": null,
"e": 8888,
"s": 8536,
"text": "The <id> element maps the unique ID attribute in class to the primary key of the database table. The name attribute of the id element refers to the property in the class and the column attribute refers to the column in the database table. The type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type."
},
{
"code": null,
"e": 9240,
"s": 8888,
"text": "The <id> element maps the unique ID attribute in class to the primary key of the database table. The name attribute of the id element refers to the property in the class and the column attribute refers to the column in the database table. The type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type."
},
{
"code": null,
"e": 9558,
"s": 9240,
"text": "The <generator> element within the id element is used to generate the primary key values automatically. The class attribute of the generator element is set to native to let hibernate pick up either identity, sequence or hilo algorithm to create primary key depending upon the capabilities of the underlying database."
},
{
"code": null,
"e": 9876,
"s": 9558,
"text": "The <generator> element within the id element is used to generate the primary key values automatically. The class attribute of the generator element is set to native to let hibernate pick up either identity, sequence or hilo algorithm to create primary key depending upon the capabilities of the underlying database."
},
{
"code": null,
"e": 10223,
"s": 9876,
"text": "The <property> element is used to map a Java class property to a column in the database table. The name attribute of the element refers to the property in the class and the column attribute refers to the column in the database table. The type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type."
},
{
"code": null,
"e": 10570,
"s": 10223,
"text": "The <property> element is used to map a Java class property to a column in the database table. The name attribute of the element refers to the property in the class and the column attribute refers to the column in the database table. The type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type."
},
{
"code": null,
"e": 10847,
"s": 10570,
"text": "The <many-to-one> element is used to set the relationship between EMPLOYEE and ADDRESS entities. The name attribute is set to the defined variable in the parent class, in our case it is address. The column attribute is used to set the column name in the parent table EMPLOYEE."
},
{
"code": null,
"e": 11124,
"s": 10847,
"text": "The <many-to-one> element is used to set the relationship between EMPLOYEE and ADDRESS entities. The name attribute is set to the defined variable in the parent class, in our case it is address. The column attribute is used to set the column name in the parent table EMPLOYEE."
},
{
"code": null,
"e": 11361,
"s": 11124,
"text": "Finally, we will create our application class with the main() method to run the application. We will use this application to save few Employee's records along with their addresses and then we will apply CRUD operations on those records."
},
{
"code": null,
"e": 16356,
"s": 11361,
"text": "import java.util.*;\n \nimport org.hibernate.HibernateException; \nimport org.hibernate.Session; \nimport org.hibernate.Transaction;\nimport org.hibernate.SessionFactory;\nimport org.hibernate.cfg.Configuration;\n\npublic class ManageEmployee {\n private static SessionFactory factory; \n public static void main(String[] args) {\n \n try {\n factory = new Configuration().configure().buildSessionFactory();\n } catch (Throwable ex) { \n System.err.println(\"Failed to create sessionFactory object.\" + ex);\n throw new ExceptionInInitializerError(ex); \n }\n \n ManageEmployee ME = new ManageEmployee();\n\n /* Let us have one address object */\n Address address = ME.addAddress(\"Kondapur\",\"Hyderabad\",\"AP\",\"532\");\n\n /* Add employee records in the database */\n Integer empID1 = ME.addEmployee(\"Manoj\", \"Kumar\", 4000, address);\n\n /* Add another employee record in the database */\n Integer empID2 = ME.addEmployee(\"Dilip\", \"Kumar\", 3000, address);\n\n /* List down all the employees */\n ME.listEmployees();\n\n /* Update employee's salary records */\n ME.updateEmployee(empID1, 5000);\n\n /* Delete an employee from the database */\n ME.deleteEmployee(empID2);\n\n /* List down all the employees */\n ME.listEmployees();\n\n }\n\n /* Method to add an address record in the database */\n public Address addAddress(String street, String city, String state, String zipcode) {\n Session session = factory.openSession();\n Transaction tx = null;\n Integer addressID = null;\n Address address = null;\n \n try {\n tx = session.beginTransaction();\n address = new Address(street, city, state, zipcode);\n addressID = (Integer) session.save(address); \n tx.commit();\n } catch (HibernateException e) {\n if (tx!=null) tx.rollback();\n e.printStackTrace(); \n } finally {\n session.close(); \n }\n return address;\n }\n\n /* Method to add an employee record in the database */\n public Integer addEmployee(String fname, String lname, int salary, Address address){\n Session session = factory.openSession();\n Transaction tx = null;\n Integer employeeID = null;\n \n try {\n tx = session.beginTransaction();\n Employee employee = new Employee(fname, lname, salary, address);\n employeeID = (Integer) session.save(employee); \n tx.commit();\n } catch (HibernateException e) {\n if (tx!=null) tx.rollback();\n e.printStackTrace(); \n } finally {\n session.close(); \n }\n return employeeID;\n }\n\n /* Method to list all the employees detail */\n public void listEmployees( ){\n Session session = factory.openSession();\n Transaction tx = null;\n \n try {\n tx = session.beginTransaction();\n List employees = session.createQuery(\"FROM Employee\").list(); \n for (Iterator iterator = employees.iterator(); iterator.hasNext();){\n Employee employee = (Employee) iterator.next(); \n System.out.print(\"First Name: \" + employee.getFirstName()); \n System.out.print(\" Last Name: \" + employee.getLastName()); \n System.out.println(\" Salary: \" + employee.getSalary());\n Address add = employee.getAddress();\n System.out.println(\"Address \");\n System.out.println(\"\\tStreet: \" + add.getStreet());\n System.out.println(\"\\tCity: \" + add.getCity());\n System.out.println(\"\\tState: \" + add.getState());\n System.out.println(\"\\tZipcode: \" + add.getZipcode());\n }\n tx.commit();\n } catch (HibernateException e) {\n if (tx!=null) tx.rollback();\n e.printStackTrace(); \n } finally {\n session.close(); \n }\n }\n \n /* Method to update salary for an employee */\n public void updateEmployee(Integer EmployeeID, int salary ){\n Session session = factory.openSession();\n Transaction tx = null;\n \n try {\n tx = session.beginTransaction();\n Employee employee = (Employee)session.get(Employee.class, EmployeeID); \n employee.setSalary( salary );\n session.update(employee);\n tx.commit();\n } catch (HibernateException e) {\n if (tx!=null) tx.rollback();\n e.printStackTrace(); \n } finally {\n session.close(); \n }\n }\n \n /* Method to delete an employee from the records */\n public void deleteEmployee(Integer EmployeeID){\n Session session = factory.openSession();\n Transaction tx = null;\n \n try {\n tx = session.beginTransaction();\n Employee employee = (Employee)session.get(Employee.class, EmployeeID); \n session.delete(employee); \n tx.commit();\n } catch (HibernateException e) {\n if (tx!=null) tx.rollback();\n e.printStackTrace(); \n } finally {\n session.close(); \n }\n }\n}"
},
{
"code": null,
"e": 16536,
"s": 16356,
"text": "Here are the steps to compile and run the above mentioned application. Make sure you have set PATH and CLASSPATH appropriately before proceeding for the compilation and execution."
},
{
"code": null,
"e": 16619,
"s": 16536,
"text": "Create hibernate.cfg.xml configuration file as explained in configuration chapter."
},
{
"code": null,
"e": 16702,
"s": 16619,
"text": "Create hibernate.cfg.xml configuration file as explained in configuration chapter."
},
{
"code": null,
"e": 16755,
"s": 16702,
"text": "Create Employee.hbm.xml mapping file as shown above."
},
{
"code": null,
"e": 16808,
"s": 16755,
"text": "Create Employee.hbm.xml mapping file as shown above."
},
{
"code": null,
"e": 16872,
"s": 16808,
"text": "Create Employee.java source file as shown above and compile it."
},
{
"code": null,
"e": 16936,
"s": 16872,
"text": "Create Employee.java source file as shown above and compile it."
},
{
"code": null,
"e": 16999,
"s": 16936,
"text": "Create Address.java source file as shown above and compile it."
},
{
"code": null,
"e": 17062,
"s": 16999,
"text": "Create Address.java source file as shown above and compile it."
},
{
"code": null,
"e": 17132,
"s": 17062,
"text": "Create ManageEmployee.java source file as shown above and compile it."
},
{
"code": null,
"e": 17202,
"s": 17132,
"text": "Create ManageEmployee.java source file as shown above and compile it."
},
{
"code": null,
"e": 17252,
"s": 17202,
"text": "Execute ManageEmployee binary to run the program."
},
{
"code": null,
"e": 17302,
"s": 17252,
"text": "Execute ManageEmployee binary to run the program."
},
{
"code": null,
"e": 17423,
"s": 17302,
"text": "You would get the following result on the screen, and same time records would be created in EMPLOYEE and ADDRESS tables."
},
{
"code": null,
"e": 17937,
"s": 17423,
"text": "$java ManageEmployee\n.......VARIOUS LOG MESSAGES WILL DISPLAY HERE........\n\nFirst Name: Manoj Last Name: Kumar Salary: 4000\nAddress\n Street: Kondapur\n City: Hyderabad\n State: AP\n Zipcode: 532\nFirst Name: Dilip Last Name: Kumar Salary: 3000\nAddress\n Street: Kondapur\n City: Hyderabad\n State: AP\n Zipcode: 532\nFirst Name: Manoj Last Name: Kumar Salary: 5000\nAddress\n Street: Kondapur\n City: Hyderabad\n State: AP\n Zipcode: 532"
},
{
"code": null,
"e": 18025,
"s": 17937,
"text": "If you check your EMPLOYEE and ADDRESS tables, they should have the following records −"
},
{
"code": null,
"e": 18678,
"s": 18025,
"text": "mysql> select * from EMPLOYEE;\n+----+------------+-----------+--------+---------+\n| id | first_name | last_name | salary | address |\n+----+------------+-----------+--------+---------+\n| 1 | Manoj | Kumar | 5000 | 5 |\n+----+------------+-----------+--------+---------+\n1 row in set (0.00 sec)\n\nmysql> select * from ADDRESS;\n+----+-------------+-----------+------------+---------+\n| id | street_name | city_name | state_name | zipcode |\n+----+-------------+-----------+------------+---------+\n| 1 | Kondapur | Hyderabad | AP | 532 |\n+----+-------------+-----------+------------+---------+\n1 row in set (0.00 sec)\n\nmysql>"
},
{
"code": null,
"e": 18713,
"s": 18678,
"text": "\n 108 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 18728,
"s": 18713,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 18761,
"s": 18728,
"text": "\n 65 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 18775,
"s": 18761,
"text": " Karthikeya T"
},
{
"code": null,
"e": 18810,
"s": 18775,
"text": "\n 39 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 18826,
"s": 18810,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 18833,
"s": 18826,
"text": " Print"
},
{
"code": null,
"e": 18844,
"s": 18833,
"text": " Add Notes"
}
] |
Python | How to dynamically change text of Checkbutton - GeeksforGeeks
|
02 Apr, 2019
Tkinter is a GUI (Graphical User interface) module which is used to create various types of applications. It comes along with the Python and consists of various types of widgets which can be used to make GUI more attractive and user-friendly. Checkbutton is one of the widgets which is used to select multiple options.
Checkbutton can be created as follows:
chkbtn = ttk.Checkbutton(parent, value = options, ...)
Code #1:
# This will import tkinter and ttkfrom tkinter import * from tkinter import ttk root = Tk() # This will set the geometry to 200x100root.geometry('200x100') text1 = StringVar()text2 = StringVar() # These text are used to set initial# values of Checkbutton to offtext1.set('OFF')text2.set('OFF') chkbtn1 = ttk.Checkbutton(root, textvariable = text1, variable = text1, offvalue = 'GFG Not Selected', onvalue = 'GFG Selected') chkbtn1.pack(side = TOP, pady = 10)chkbtn2 = ttk.Checkbutton(root, textvariable = text2, variable = text2, offvalue = 'GFG Average', onvalue = 'GFG Good')chkbtn2.pack(side = TOP, pady = 10) root.mainloop()
Output #1: When you run application you see the initial states of Checkbutton as shown in output.
Output #2: As soon as you select the Checkbutton you’ll see that text has been changed as in output.
Output #3: When you deselect the Checkbutton you’ll again observe following changes.
Code #2: Commands can be integrate with the Checkbutton which can be execute when checkbutton is selected or deselected depending upon conditions.
# Importing tkinter, ttk and# _show method to display# pop-up message windowfrom tkinter import * from tkinter import ttkfrom tkinter.messagebox import _show root = Tk()root.geometry('200x100') text1 = StringVar()text1.set('OFF') # This function is used to display# the pop-up messagedef show(event): string = event.get() _show('Message', 'You selected ' + string) chkbtn1 = ttk.Checkbutton(root, textvariable = text1, variable = text1, offvalue = 'GFG Good', onvalue = 'GFG Great', command = lambda : show(text1))chkbtn1.pack(side = TOP, pady = 10) root.mainloop()
Output:Note: In above code offvalue and onvalue are used to set the values of Checkbutton of non-selected state and selected state respectively.
Python-gui
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
Check if element exists in list in Python
Python | os.path.join() method
Defaultdict in Python
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n02 Apr, 2019"
},
{
"code": null,
"e": 24611,
"s": 24292,
"text": "Tkinter is a GUI (Graphical User interface) module which is used to create various types of applications. It comes along with the Python and consists of various types of widgets which can be used to make GUI more attractive and user-friendly. Checkbutton is one of the widgets which is used to select multiple options."
},
{
"code": null,
"e": 24650,
"s": 24611,
"text": "Checkbutton can be created as follows:"
},
{
"code": null,
"e": 24705,
"s": 24650,
"text": "chkbtn = ttk.Checkbutton(parent, value = options, ...)"
},
{
"code": null,
"e": 24714,
"s": 24705,
"text": "Code #1:"
},
{
"code": "# This will import tkinter and ttkfrom tkinter import * from tkinter import ttk root = Tk() # This will set the geometry to 200x100root.geometry('200x100') text1 = StringVar()text2 = StringVar() # These text are used to set initial# values of Checkbutton to offtext1.set('OFF')text2.set('OFF') chkbtn1 = ttk.Checkbutton(root, textvariable = text1, variable = text1, offvalue = 'GFG Not Selected', onvalue = 'GFG Selected') chkbtn1.pack(side = TOP, pady = 10)chkbtn2 = ttk.Checkbutton(root, textvariable = text2, variable = text2, offvalue = 'GFG Average', onvalue = 'GFG Good')chkbtn2.pack(side = TOP, pady = 10) root.mainloop()",
"e": 25450,
"s": 24714,
"text": null
},
{
"code": null,
"e": 25548,
"s": 25450,
"text": "Output #1: When you run application you see the initial states of Checkbutton as shown in output."
},
{
"code": null,
"e": 25649,
"s": 25548,
"text": "Output #2: As soon as you select the Checkbutton you’ll see that text has been changed as in output."
},
{
"code": null,
"e": 25734,
"s": 25649,
"text": "Output #3: When you deselect the Checkbutton you’ll again observe following changes."
},
{
"code": null,
"e": 25881,
"s": 25734,
"text": "Code #2: Commands can be integrate with the Checkbutton which can be execute when checkbutton is selected or deselected depending upon conditions."
},
{
"code": "# Importing tkinter, ttk and# _show method to display# pop-up message windowfrom tkinter import * from tkinter import ttkfrom tkinter.messagebox import _show root = Tk()root.geometry('200x100') text1 = StringVar()text1.set('OFF') # This function is used to display# the pop-up messagedef show(event): string = event.get() _show('Message', 'You selected ' + string) chkbtn1 = ttk.Checkbutton(root, textvariable = text1, variable = text1, offvalue = 'GFG Good', onvalue = 'GFG Great', command = lambda : show(text1))chkbtn1.pack(side = TOP, pady = 10) root.mainloop()",
"e": 26533,
"s": 25881,
"text": null
},
{
"code": null,
"e": 26678,
"s": 26533,
"text": "Output:Note: In above code offvalue and onvalue are used to set the values of Checkbutton of non-selected state and selected state respectively."
},
{
"code": null,
"e": 26689,
"s": 26678,
"text": "Python-gui"
},
{
"code": null,
"e": 26704,
"s": 26689,
"text": "Python-tkinter"
},
{
"code": null,
"e": 26711,
"s": 26704,
"text": "Python"
},
{
"code": null,
"e": 26809,
"s": 26711,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26841,
"s": 26809,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26883,
"s": 26841,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26939,
"s": 26883,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26994,
"s": 26939,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 27036,
"s": 26994,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27067,
"s": 27036,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27089,
"s": 27067,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27128,
"s": 27089,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27157,
"s": 27128,
"text": "Create a directory in Python"
}
] |
Behave - Scenario Outlines
|
A Scenario Outline is used if we have a group of similar criteria and the results are to be passed in a Scenario. A Scenario Outline is accompanied with an Examples table. A Scenario Outline can have multiple Examples tables.
The tests get executed once for every row found (after the header row) within the Examples table. The values to be tested are represented by their names enclosed in brackets<>. These names should match with the Examples table header.
It helps to reduce the lines of code (eliminates repeating steps) and orders our tests.
Feature File
The feature file for scenario outline is as follows −
Feature − User information
Scenario Outline: Check login functionality
Given user enters "<name>" and "<password>"
Then user should be logged in
Examples: Credentials
| name | password |
| user1 | pwd1 |
| user2 | pwd2 |
Please Note: We have kept the name and password parameters enclosed in "<>". These parameters are column headers provided below the Examples section. In the step implementation, we shall pass the parameters enclosed in "{}".
Also, these parameters need to be passed as arguments to the implementation method.
Corresponding Step Implementation File
The corresponding step implementation file is as follows −
from behave import *
@given('user enters "{name}" and "{password}"')
def step_implpy(context, name, password):
print("Username for login: {}".format(name))
print("Password for login: {}".format(password))
@then('user should be logged in')
def step_implpy(context):
pass
Output
The output is obtained after running the feature file and the command used is behave --no-capture -f plain.
The output shows Username for login: user1, Password for login: pwd1 and Username for login: user2, Password for login: pwd2 printed. Here, the two data sets were passed from the Examples.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2522,
"s": 2296,
"text": "A Scenario Outline is used if we have a group of similar criteria and the results are to be passed in a Scenario. A Scenario Outline is accompanied with an Examples table. A Scenario Outline can have multiple Examples tables."
},
{
"code": null,
"e": 2756,
"s": 2522,
"text": "The tests get executed once for every row found (after the header row) within the Examples table. The values to be tested are represented by their names enclosed in brackets<>. These names should match with the Examples table header."
},
{
"code": null,
"e": 2844,
"s": 2756,
"text": "It helps to reduce the lines of code (eliminates repeating steps) and orders our tests."
},
{
"code": null,
"e": 2857,
"s": 2844,
"text": "Feature File"
},
{
"code": null,
"e": 2911,
"s": 2857,
"text": "The feature file for scenario outline is as follows −"
},
{
"code": null,
"e": 3172,
"s": 2911,
"text": "Feature − User information\nScenario Outline: Check login functionality\n Given user enters \"<name>\" and \"<password>\"\n Then user should be logged in\n Examples: Credentials\n | name | password |\n | user1 | pwd1 |\n | user2 | pwd2 |\n"
},
{
"code": null,
"e": 3397,
"s": 3172,
"text": "Please Note: We have kept the name and password parameters enclosed in \"<>\". These parameters are column headers provided below the Examples section. In the step implementation, we shall pass the parameters enclosed in \"{}\"."
},
{
"code": null,
"e": 3481,
"s": 3397,
"text": "Also, these parameters need to be passed as arguments to the implementation method."
},
{
"code": null,
"e": 3520,
"s": 3481,
"text": "Corresponding Step Implementation File"
},
{
"code": null,
"e": 3579,
"s": 3520,
"text": "The corresponding step implementation file is as follows −"
},
{
"code": null,
"e": 3870,
"s": 3579,
"text": "from behave import *\n@given('user enters \"{name}\" and \"{password}\"')\ndef step_implpy(context, name, password):\n print(\"Username for login: {}\".format(name))\n print(\"Password for login: {}\".format(password))\n@then('user should be logged in')\ndef step_implpy(context):\n pass"
},
{
"code": null,
"e": 3877,
"s": 3870,
"text": "Output"
},
{
"code": null,
"e": 3985,
"s": 3877,
"text": "The output is obtained after running the feature file and the command used is behave --no-capture -f plain."
},
{
"code": null,
"e": 4174,
"s": 3985,
"text": "The output shows Username for login: user1, Password for login: pwd1 and Username for login: user2, Password for login: pwd2 printed. Here, the two data sets were passed from the Examples."
},
{
"code": null,
"e": 4181,
"s": 4174,
"text": " Print"
},
{
"code": null,
"e": 4192,
"s": 4181,
"text": " Add Notes"
}
] |
NumPy Array Slicing
|
Slicing in python means taking elements from one given index to another given
index.
We pass slice instead of index like this: [start:end].
We can also define the step, like this: [start:end:step].
If we don't pass start its considered 0
If we don't pass end its considered length of array in that dimension
If we don't pass step its considered 1
Slice elements from index 1 to index 5 from the following array:
Note: The result includes the start index, but excludes the end index.
Slice elements from index 4 to the end of the array:
Slice elements from the beginning to index 4 (not included):
Use the minus operator to refer to an index from the end:
Slice from the index 3 from the end to index 1 from the end:
Use the step value to determine the step of the slicing:
Return every other element from index 1 to index 5:
Return every other element from the entire array:
From the second element, slice elements from index 1 to index 4 (not included):
Note: Remember that second element has index 1.
From both elements, return index 2:
From both elements, slice index 1 to index 4 (not included), this will return a 2-D array:
Insert the correct slicing syntax to print the following selection of the array:
Everything from (including) the second item to (not including) the fifth item.
arr = np.array([10, 15, 20, 25, 30, 35, 40])
print(arr)
Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 86,
"s": 0,
"text": "Slicing in python means taking elements from one given index to another given \nindex."
},
{
"code": null,
"e": 141,
"s": 86,
"text": "We pass slice instead of index like this: [start:end]."
},
{
"code": null,
"e": 199,
"s": 141,
"text": "We can also define the step, like this: [start:end:step]."
},
{
"code": null,
"e": 239,
"s": 199,
"text": "If we don't pass start its considered 0"
},
{
"code": null,
"e": 309,
"s": 239,
"text": "If we don't pass end its considered length of array in that dimension"
},
{
"code": null,
"e": 348,
"s": 309,
"text": "If we don't pass step its considered 1"
},
{
"code": null,
"e": 413,
"s": 348,
"text": "Slice elements from index 1 to index 5 from the following array:"
},
{
"code": null,
"e": 484,
"s": 413,
"text": "Note: The result includes the start index, but excludes the end index."
},
{
"code": null,
"e": 537,
"s": 484,
"text": "Slice elements from index 4 to the end of the array:"
},
{
"code": null,
"e": 598,
"s": 537,
"text": "Slice elements from the beginning to index 4 (not included):"
},
{
"code": null,
"e": 656,
"s": 598,
"text": "Use the minus operator to refer to an index from the end:"
},
{
"code": null,
"e": 717,
"s": 656,
"text": "Slice from the index 3 from the end to index 1 from the end:"
},
{
"code": null,
"e": 774,
"s": 717,
"text": "Use the step value to determine the step of the slicing:"
},
{
"code": null,
"e": 826,
"s": 774,
"text": "Return every other element from index 1 to index 5:"
},
{
"code": null,
"e": 876,
"s": 826,
"text": "Return every other element from the entire array:"
},
{
"code": null,
"e": 956,
"s": 876,
"text": "From the second element, slice elements from index 1 to index 4 (not included):"
},
{
"code": null,
"e": 1004,
"s": 956,
"text": "Note: Remember that second element has index 1."
},
{
"code": null,
"e": 1040,
"s": 1004,
"text": "From both elements, return index 2:"
},
{
"code": null,
"e": 1131,
"s": 1040,
"text": "From both elements, slice index 1 to index 4 (not included), this will return a 2-D array:"
},
{
"code": null,
"e": 1212,
"s": 1131,
"text": "Insert the correct slicing syntax to print the following selection of the array:"
},
{
"code": null,
"e": 1291,
"s": 1212,
"text": "Everything from (including) the second item to (not including) the fifth item."
},
{
"code": null,
"e": 1349,
"s": 1291,
"text": "arr = np.array([10, 15, 20, 25, 30, 35, 40])\n\nprint(arr)\n"
},
{
"code": null,
"e": 1368,
"s": 1349,
"text": "Start the Exercise"
},
{
"code": null,
"e": 1401,
"s": 1368,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 1443,
"s": 1401,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 1550,
"s": 1443,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 1569,
"s": 1550,
"text": "help@w3schools.com"
}
] |
Print concentric rectangular pattern in a 2d matrix in C++
|
In this problem, we have to print a rectangular pattern in a 2D matrix in such a way that they are concentric to each other.
Let’s take an example to understand this problem better,
For n=4 is :
4 4 4 4 4 4 4
4 3 3 3 3 3 4
4 3 2 2 2 3 4
4 3 2 1 2 3 4
4 3 2 2 2 3 4
4 3 3 3 3 3 4
4 4 4 4 4 4 4
Here, we have to print the pattern as above taking n, integer value and print concentric rectangles as −
n n n n n
n n-1 n-1 n-1 n
n n-1 n-2 n-1 n
n n-1 n-1 n-1 n
n n n n n
Now, in this problem, as we can see there are (2n-1) columns and rows in the 2D matrix in total. This 2D matrix is printed in two parts. The upper one will be from 0 to (2n-1)/2 and the lower half will be from ((2n-1)/2+1) to 2n-2.
Now, each row will go on decreasing value by 1 until the number reaches the number of rows i.e. 1 to i (no. of rows). Then it increases the number back to n.
Using this logic lets create a program to solve the problem,
Live Demo
#include <bits/stdc++.h>
using namespace std;
void print2Dsequence(int n){
int s = 2 * n - 1;
for (int i = 0; i < (s / 2) + 1; i++) {
int m = n;
for (int j = 0; j < i; j++) {
cout << m << " ";
m--;
}
for (int k = 0; k < s - 2 * i; k++) {
cout << n - i << " ";
}
m = n - i + 1;
for (int l = 0; l < i; l++) {
cout << m << " ";
m++;
}
cout << endl;
}
for (int i = s / 2 - 1; i >= 0; i--) {
int m = n;
for (int j = 0; j < i; j++) {
cout << m << " ";
m--;
}
for (int k = 0; k < s - 2 * i; k++) {
cout << n - i << " ";
}
m = n - i + 1;
for (int l = 0; l < i; l++) {
cout << m << " ";
m++;
}
cout << endl;
}
}
int main(){
int n = 4;
cout<<"The sequence of concurrent rectangle of 4 is : \n";
print2Dsequence(n);
return 0;
}
The sequence of the concurrent rectangle of 4 is −
4 4 4 4 4 4 4
4 3 3 3 3 3 4
4 3 2 2 2 3 4
4 3 2 1 2 3 4
4 3 2 2 2 3 4
4 3 3 3 3 3 4
4 4 4 4 4 4 4
|
[
{
"code": null,
"e": 1187,
"s": 1062,
"text": "In this problem, we have to print a rectangular pattern in a 2D matrix in such a way that they are concentric to each other."
},
{
"code": null,
"e": 1244,
"s": 1187,
"text": "Let’s take an example to understand this problem better,"
},
{
"code": null,
"e": 1376,
"s": 1244,
"text": "For n=4 is :\n 4 4 4 4 4 4 4\n 4 3 3 3 3 3 4\n 4 3 2 2 2 3 4\n 4 3 2 1 2 3 4\n 4 3 2 2 2 3 4\n 4 3 3 3 3 3 4\n 4 4 4 4 4 4 4"
},
{
"code": null,
"e": 1481,
"s": 1376,
"text": "Here, we have to print the pattern as above taking n, integer value and print concentric rectangles as −"
},
{
"code": null,
"e": 1561,
"s": 1481,
"text": "n n n n n\nn n-1 n-1 n-1 n\nn n-1 n-2 n-1 n\nn n-1 n-1 n-1 n\nn n n n n"
},
{
"code": null,
"e": 1793,
"s": 1561,
"text": "Now, in this problem, as we can see there are (2n-1) columns and rows in the 2D matrix in total. This 2D matrix is printed in two parts. The upper one will be from 0 to (2n-1)/2 and the lower half will be from ((2n-1)/2+1) to 2n-2."
},
{
"code": null,
"e": 1951,
"s": 1793,
"text": "Now, each row will go on decreasing value by 1 until the number reaches the number of rows i.e. 1 to i (no. of rows). Then it increases the number back to n."
},
{
"code": null,
"e": 2012,
"s": 1951,
"text": "Using this logic lets create a program to solve the problem,"
},
{
"code": null,
"e": 2023,
"s": 2012,
"text": " Live Demo"
},
{
"code": null,
"e": 2965,
"s": 2023,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nvoid print2Dsequence(int n){\n int s = 2 * n - 1;\n for (int i = 0; i < (s / 2) + 1; i++) {\n int m = n;\n for (int j = 0; j < i; j++) {\n cout << m << \" \";\n m--;\n }\n for (int k = 0; k < s - 2 * i; k++) {\n cout << n - i << \" \";\n }\n m = n - i + 1;\n for (int l = 0; l < i; l++) {\n cout << m << \" \";\n m++;\n }\n cout << endl;\n }\n for (int i = s / 2 - 1; i >= 0; i--) {\n int m = n;\n for (int j = 0; j < i; j++) {\n cout << m << \" \";\n m--;\n }\n for (int k = 0; k < s - 2 * i; k++) {\n cout << n - i << \" \";\n }\n m = n - i + 1;\n for (int l = 0; l < i; l++) {\n cout << m << \" \";\n m++;\n }\n cout << endl;\n }\n}\nint main(){\n int n = 4;\n cout<<\"The sequence of concurrent rectangle of 4 is : \\n\";\n print2Dsequence(n);\n return 0;\n}"
},
{
"code": null,
"e": 3016,
"s": 2965,
"text": "The sequence of the concurrent rectangle of 4 is −"
},
{
"code": null,
"e": 3114,
"s": 3016,
"text": "4 4 4 4 4 4 4\n4 3 3 3 3 3 4\n4 3 2 2 2 3 4\n4 3 2 1 2 3 4\n4 3 2 2 2 3 4\n4 3 3 3 3 3 4\n4 4 4 4 4 4 4"
}
] |
How to Querying Two Tables For Duplicate Values in SQL?
|
16 Nov, 2021
In this article, we will see how to write SQL queries to get duplicate values from two tables.
We can perform the given task using two methods:
Using INNER JOIN.Using WHERE clause
Using INNER JOIN.
Using WHERE clause
Now, for the demonstration follow the below steps:
Step 1: Create a database
we can use the following command to create a database called geeks.
Query:
CREATE DATABASE geeks;
Step 2: Use database
Use the below SQL statement to switch the database context to geeks:
Query:
USE geeks;
Step 3: Table definition
We have two tables named ‘demo_table1’ and ‘demo_table2’ in our geek’s database.
Query(demo_table1):
CREATE TABLE demo_table1(
ID int,
NAME VARCHAR(20),
AGE INT,
CITY VARCHAR(20) );
Query(demo_table2):
CREATE TABLE demo_table2(
ID int,
NAME VARCHAR(20),
AGE int);
Step 4: Insert data into a table
Query(demo_table1):
INSERT INTO demo_table1 VALUES
(11,'Romy',23,'Delhi'),
(23,'Rahul',23,'Delhi'),
(31,'Nikhil',24,'Punjab'),
(46,'Ranvir',23,'Punjab'),
(52,'Samiksha',23,'Banglore'),
(61,'Ashtha',24,'Banglore'),
(77,'Tannu',30,'Patna'),
(89,'Girish',30,'Patna');
Query(demo_table2):
INSERT INTO demo_table2 VALUES
(31,'Fanny',25 ),
(77,'Prem', 30),
(15,'Preeti',21),
(46,'Samita',32),
(09,'Rajan',45);
Step 5: View the content
Execute the below query to see the content of the table
Query(demo_table1):
SELECT * FROM demo_table1;
Output:
Query(demo_table2):
SELECT * FROM demo_table2;
Output:
STEP 6: SQL query to get duplicates from two tables
Method 1:
INNER JOIN: It is a keyword used for querying two tables to get the records having matching values in both the table.
Syntax:
SELECT Column_name
FROM table1 INNER JOIN
table2 ON condition;
For demonstration, we will write SQL query that will return duplicate ID values from both the tables
Query:
SELECT demo_table1.ID
FROM demo_table1
INNER JOIN demo_table2
ON demo_table1.ID=demo_table2.ID;
If two tables have the same column name, the table name should be used before the name of column name like table_name.column_name to differentiate the column of both the tables.
Output:
Method 2: By using where clause to compare column values
Syntax:
SELECT column_name from table_name WHERE condition;
Query:
SELECT demo_table1.ID
FROM demo_table1, demo_table2
WHERE demo_table1.ID=demo_table2.ID;
Output:
Picked
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n16 Nov, 2021"
},
{
"code": null,
"e": 149,
"s": 54,
"text": "In this article, we will see how to write SQL queries to get duplicate values from two tables."
},
{
"code": null,
"e": 198,
"s": 149,
"text": "We can perform the given task using two methods:"
},
{
"code": null,
"e": 234,
"s": 198,
"text": "Using INNER JOIN.Using WHERE clause"
},
{
"code": null,
"e": 252,
"s": 234,
"text": "Using INNER JOIN."
},
{
"code": null,
"e": 271,
"s": 252,
"text": "Using WHERE clause"
},
{
"code": null,
"e": 322,
"s": 271,
"text": "Now, for the demonstration follow the below steps:"
},
{
"code": null,
"e": 348,
"s": 322,
"text": "Step 1: Create a database"
},
{
"code": null,
"e": 416,
"s": 348,
"text": "we can use the following command to create a database called geeks."
},
{
"code": null,
"e": 423,
"s": 416,
"text": "Query:"
},
{
"code": null,
"e": 446,
"s": 423,
"text": "CREATE DATABASE geeks;"
},
{
"code": null,
"e": 467,
"s": 446,
"text": "Step 2: Use database"
},
{
"code": null,
"e": 536,
"s": 467,
"text": "Use the below SQL statement to switch the database context to geeks:"
},
{
"code": null,
"e": 543,
"s": 536,
"text": "Query:"
},
{
"code": null,
"e": 554,
"s": 543,
"text": "USE geeks;"
},
{
"code": null,
"e": 579,
"s": 554,
"text": "Step 3: Table definition"
},
{
"code": null,
"e": 660,
"s": 579,
"text": "We have two tables named ‘demo_table1’ and ‘demo_table2’ in our geek’s database."
},
{
"code": null,
"e": 680,
"s": 660,
"text": "Query(demo_table1):"
},
{
"code": null,
"e": 761,
"s": 680,
"text": "CREATE TABLE demo_table1(\nID int,\nNAME VARCHAR(20),\nAGE INT,\nCITY VARCHAR(20) );"
},
{
"code": null,
"e": 781,
"s": 761,
"text": "Query(demo_table2):"
},
{
"code": null,
"e": 843,
"s": 781,
"text": "CREATE TABLE demo_table2(\nID int,\nNAME VARCHAR(20),\nAGE int);"
},
{
"code": null,
"e": 876,
"s": 843,
"text": "Step 4: Insert data into a table"
},
{
"code": null,
"e": 896,
"s": 876,
"text": "Query(demo_table1):"
},
{
"code": null,
"e": 1141,
"s": 896,
"text": "INSERT INTO demo_table1 VALUES\n(11,'Romy',23,'Delhi'),\n(23,'Rahul',23,'Delhi'),\n(31,'Nikhil',24,'Punjab'),\n(46,'Ranvir',23,'Punjab'),\n(52,'Samiksha',23,'Banglore'),\n(61,'Ashtha',24,'Banglore'),\n(77,'Tannu',30,'Patna'),\n(89,'Girish',30,'Patna');"
},
{
"code": null,
"e": 1161,
"s": 1141,
"text": "Query(demo_table2):"
},
{
"code": null,
"e": 1280,
"s": 1161,
"text": "INSERT INTO demo_table2 VALUES\n(31,'Fanny',25 ),\n(77,'Prem', 30),\n(15,'Preeti',21),\n(46,'Samita',32),\n(09,'Rajan',45);"
},
{
"code": null,
"e": 1305,
"s": 1280,
"text": "Step 5: View the content"
},
{
"code": null,
"e": 1361,
"s": 1305,
"text": "Execute the below query to see the content of the table"
},
{
"code": null,
"e": 1381,
"s": 1361,
"text": "Query(demo_table1):"
},
{
"code": null,
"e": 1408,
"s": 1381,
"text": "SELECT * FROM demo_table1;"
},
{
"code": null,
"e": 1416,
"s": 1408,
"text": "Output:"
},
{
"code": null,
"e": 1436,
"s": 1416,
"text": "Query(demo_table2):"
},
{
"code": null,
"e": 1463,
"s": 1436,
"text": "SELECT * FROM demo_table2;"
},
{
"code": null,
"e": 1471,
"s": 1463,
"text": "Output:"
},
{
"code": null,
"e": 1523,
"s": 1471,
"text": "STEP 6: SQL query to get duplicates from two tables"
},
{
"code": null,
"e": 1533,
"s": 1523,
"text": "Method 1:"
},
{
"code": null,
"e": 1651,
"s": 1533,
"text": "INNER JOIN: It is a keyword used for querying two tables to get the records having matching values in both the table."
},
{
"code": null,
"e": 1659,
"s": 1651,
"text": "Syntax:"
},
{
"code": null,
"e": 1722,
"s": 1659,
"text": "SELECT Column_name\nFROM table1 INNER JOIN\ntable2 ON condition;"
},
{
"code": null,
"e": 1823,
"s": 1722,
"text": "For demonstration, we will write SQL query that will return duplicate ID values from both the tables"
},
{
"code": null,
"e": 1830,
"s": 1823,
"text": "Query:"
},
{
"code": null,
"e": 1926,
"s": 1830,
"text": "SELECT demo_table1.ID\nFROM demo_table1\nINNER JOIN demo_table2\nON demo_table1.ID=demo_table2.ID;"
},
{
"code": null,
"e": 2104,
"s": 1926,
"text": "If two tables have the same column name, the table name should be used before the name of column name like table_name.column_name to differentiate the column of both the tables."
},
{
"code": null,
"e": 2112,
"s": 2104,
"text": "Output:"
},
{
"code": null,
"e": 2169,
"s": 2112,
"text": "Method 2: By using where clause to compare column values"
},
{
"code": null,
"e": 2177,
"s": 2169,
"text": "Syntax:"
},
{
"code": null,
"e": 2229,
"s": 2177,
"text": "SELECT column_name from table_name WHERE condition;"
},
{
"code": null,
"e": 2236,
"s": 2229,
"text": "Query:"
},
{
"code": null,
"e": 2325,
"s": 2236,
"text": "SELECT demo_table1.ID\nFROM demo_table1, demo_table2\nWHERE demo_table1.ID=demo_table2.ID;"
},
{
"code": null,
"e": 2333,
"s": 2325,
"text": "Output:"
},
{
"code": null,
"e": 2340,
"s": 2333,
"text": "Picked"
},
{
"code": null,
"e": 2351,
"s": 2340,
"text": "SQL-Server"
},
{
"code": null,
"e": 2355,
"s": 2351,
"text": "SQL"
},
{
"code": null,
"e": 2359,
"s": 2355,
"text": "SQL"
}
] |
Remove all duplicates from a given string | Practice | GeeksforGeeks
|
Given a string Str which may contains lowercase and uppercase chracters. The task is to remove all duplicate characters from the string and find the resultant string. The order of remaining characters in the output should be same as in the original string.
Example 1:
Input:
Str = geeksforgeeks
Output: geksfor
Explanation: After removing duplicate
characters such as e, k, g, s, we have
string as "geksfor".
Example 2:
Input:
Str = HappyNewYear
Output: HapyNewYr
Explanation: After removing duplicate
characters such as p, e, a, we have
string as "HapyNewYr".
Your Task:
Complete the function removeDuplicates() which takes a string str, as input parameters and returns a string denoting the answer. You don't to print answer or take inputs.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(N)
Constraints:
1 ≤ N ≤ 105
String contains uppercase and lowercase english letters.
0
hrishikeshwagh2001in 5 hours
string removeDuplicates(string str) { string res = ""; unordered_map<char,int>mp; for(int i=0;i<str.length();i++){ if(mp[str[i]]>0) continue; res.push_back(str[i]); mp[str[i]]++; } return res;}
0
dilipchoudhary7272 hours ago
class Solution {
String removeDuplicates(String str)
{
String ans="";
for(int i=0;i<str.length();i++)
{
if(!ans.contains(String.valueOf(str.charAt(i))))
{
ans+=str.charAt(i);
}
}
return ans;
}
}
0
satyammauryaksm7112 days ago
string removeDuplicates(string str) { string result=""; int hash[256]={0}; for(int i=0;i<str.length();i++){ if(hash[str[i]]==0){ hash[str[i]]=1; result = result + str[i]; } } return result;}
0
sabtharishiPremium4 days ago
PYTHON USING HASH MAPS.
class Solution:
def removeDuplicates(self,str):
hashdict = {}
result = ""
for ch in str:
if ch not in hashdict.keys():
hashdict[ch]=1
result+=ch
else:
pass
return result
0
sabtharishi
This comment was deleted.
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": 483,
"s": 226,
"text": "Given a string Str which may contains lowercase and uppercase chracters. The task is to remove all duplicate characters from the string and find the resultant string. The order of remaining characters in the output should be same as in the original string."
},
{
"code": null,
"e": 494,
"s": 483,
"text": "Example 1:"
},
{
"code": null,
"e": 636,
"s": 494,
"text": "Input:\nStr = geeksforgeeks\nOutput: geksfor\nExplanation: After removing duplicate\ncharacters such as e, k, g, s, we have\nstring as \"geksfor\".\n"
},
{
"code": null,
"e": 647,
"s": 636,
"text": "Example 2:"
},
{
"code": null,
"e": 789,
"s": 647,
"text": "Input:\nStr = HappyNewYear\nOutput: HapyNewYr\nExplanation: After removing duplicate\ncharacters such as p, e, a, we have\nstring as \"HapyNewYr\".\n"
},
{
"code": null,
"e": 971,
"s": 789,
"text": "Your Task:\nComplete the function removeDuplicates() which takes a string str, as input parameters and returns a string denoting the answer. You don't to print answer or take inputs."
},
{
"code": null,
"e": 1033,
"s": 971,
"text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)"
},
{
"code": null,
"e": 1115,
"s": 1033,
"text": "Constraints:\n1 ≤ N ≤ 105\nString contains uppercase and lowercase english letters."
},
{
"code": null,
"e": 1119,
"s": 1117,
"text": "0"
},
{
"code": null,
"e": 1148,
"s": 1119,
"text": "hrishikeshwagh2001in 5 hours"
},
{
"code": null,
"e": 1398,
"s": 1148,
"text": " string removeDuplicates(string str) { string res = \"\"; unordered_map<char,int>mp; for(int i=0;i<str.length();i++){ if(mp[str[i]]>0) continue; res.push_back(str[i]); mp[str[i]]++; } return res;}"
},
{
"code": null,
"e": 1400,
"s": 1398,
"text": "0"
},
{
"code": null,
"e": 1429,
"s": 1400,
"text": "dilipchoudhary7272 hours ago"
},
{
"code": null,
"e": 1722,
"s": 1429,
"text": "class Solution {\n String removeDuplicates(String str) \n {\n String ans=\"\";\n for(int i=0;i<str.length();i++)\n {\n if(!ans.contains(String.valueOf(str.charAt(i))))\n {\n ans+=str.charAt(i);\n }\n }\n return ans;\n }\n}\n"
},
{
"code": null,
"e": 1724,
"s": 1722,
"text": "0"
},
{
"code": null,
"e": 1753,
"s": 1724,
"text": "satyammauryaksm7112 days ago"
},
{
"code": null,
"e": 2000,
"s": 1753,
"text": " string removeDuplicates(string str) { string result=\"\"; int hash[256]={0}; for(int i=0;i<str.length();i++){ if(hash[str[i]]==0){ hash[str[i]]=1; result = result + str[i]; } } return result;}"
},
{
"code": null,
"e": 2002,
"s": 2000,
"text": "0"
},
{
"code": null,
"e": 2031,
"s": 2002,
"text": "sabtharishiPremium4 days ago"
},
{
"code": null,
"e": 2057,
"s": 2033,
"text": "PYTHON USING HASH MAPS."
},
{
"code": null,
"e": 2307,
"s": 2059,
"text": "class Solution:\n\tdef removeDuplicates(self,str):\n\t hashdict = {}\n\t result = \"\"\n\t for ch in str:\n\t if ch not in hashdict.keys():\n\t hashdict[ch]=1\n\t result+=ch\n\t else:\n\t pass\n\t return result"
},
{
"code": null,
"e": 2309,
"s": 2307,
"text": "0"
},
{
"code": null,
"e": 2321,
"s": 2309,
"text": "sabtharishi"
},
{
"code": null,
"e": 2347,
"s": 2321,
"text": "This comment was deleted."
},
{
"code": null,
"e": 2493,
"s": 2347,
"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": 2529,
"s": 2493,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 2539,
"s": 2529,
"text": "\nProblem\n"
},
{
"code": null,
"e": 2549,
"s": 2539,
"text": "\nContest\n"
},
{
"code": null,
"e": 2612,
"s": 2549,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 2797,
"s": 2612,
"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": 3081,
"s": 2797,
"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": 3227,
"s": 3081,
"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": 3304,
"s": 3227,
"text": "You can view the solutions submitted by other users from the submission tab."
},
{
"code": null,
"e": 3345,
"s": 3304,
"text": "Make sure you are not using ad-blockers."
},
{
"code": null,
"e": 3373,
"s": 3345,
"text": "Disable browser extensions."
},
{
"code": null,
"e": 3444,
"s": 3373,
"text": "We recommend using latest version of your browser for best experience."
},
{
"code": null,
"e": 3631,
"s": 3444,
"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."
}
] |
How to import a module in Typescript ?
|
19 Oct, 2021
Before starting with importing modules, first of all, we need to know the basics of modules in TypeScript.
We know that JavaScript has come with the concept of modules from the ES6 version in 2015 and by 2020 had broad support in most web browsers and JavaScript runtimes. TypeScript also shares the same concept of a module. Any file which contains a top-level import or export is considered a module.
The module is designed to arrange a code written in TypeScript and used as a local scope. Modules are basically scripts written in separate files. Import allows you to reference their source location in an existing file. Now we will understand different ways to import external models, and know how to use that module in the desired location.
Approach: Before importing any module we need to export it from another file. We can create a module by using the export keyword and can use it in other modules by using the import keyword. We can export both class-based modules and function-based modules. as shown below.
Syntax for export class-based module:
export class CLASS_NAME {
constructor(para1 , para2) {}
Method() {
console.log("This is class-based Module export" );
}
}
Syntax for export function-based module:
export function FUNCTION_NAME {
console.log("This is function-based Module export");
}
Ways to Import External Modules: In TypeScript, we use the keyword import and from to import a particular module or a named parameter. Let’s see the different ways we can use the import operation.
1. Import Default Export: In order to import the default export from a file, we can use the from location of the file and use the keyword import before it, or we could give a specific name i.e. MODULE_NAME to the import which makes the syntax as the following.
import MODULE_NAME from './MODULE_LOCATION'
2. Import Named Values: It is not necessary that every file exports default modules, they can have a number of named parameters and in case we need to import one we should use the syntax as follows.
import { MODULE_NAME } from './MODULE_LOCATION'
And similarly, for multiple modules imports, we can use a comma ( , ) separator to separate two-parameter names within the curly braces { }. As shown below.
import { MODULE_NAME1, MODULE_NAME2, ... ,
MODULE_NAMEn } from ./MODULE_LOCATION'
3. Importing a combination of Default Exports and Named Values: The title makes it clear what we need to see is that the syntax of the same. In order to import a combination, we should use the following syntax.
import DEFAULT_EXPORT, { MODULE_NAME1,
MODULE_NAME2, ... , MODULE_NAMEn }
from './MODULE_LOCATION'
4. Import everything from the Module: Sometimes you need to import every module from the specific file, then you can use ( * ) asterisk to import all modules and assign them to an object ( OBJ_NAME ) as shown below
import * as OBJ_NAME from './MODULE_LOCATION'
Or you can use:
import MODULE = require('LOCATION')
Now we implement what we learn above using the following examples:
Example 1: Import a default export module from a file to another file.
Module1.ts
// Exporting the Default export module// which is used in another file// export default keyword used to // Export the moduleexport default function GFG() { return "GeeksforGeeks";}
Module2.ts
// Importing the default export module // from the location of the file.import GFG from "./MODULE1"; // Creating an object of the// class which is importedlet msg = GFG(); console.log("This is MSG from "); console.log(msg);
Steps to print output: First, convert the TypeScript file into JavaScript for that you need to run the following command on your respective terminal.
> tsc MODULE2.ts
After that, you need to run a JavaScript file using the Node module. as shown below.
> node MODULE2.js
Output:
Example 2: Import a class from a file to another file.
Module1.ts
// Exporting the class which used in another file// export keyword used to Export the moduleexport class GFG { StringConcat(banner) { return "Welcome to " + banner; }}
Module2.ts
// Importing the module// from the location of the file.import { GFG } from "./Module1"; let obj1 = new GFG(); console.log(obj1.StringConcat("GeeksforGeeks"));
Steps to print output:
> tsc MODULE2.ts
> node MODULE2.js
Output:
Example 3: Import all modules from a file to another file.
Module1.ts
// Export all the classes functions export function Welcome(str: string) { return "Hello " + str + "..!";} export class Geeks { msg(str1: string) { return "Welcome to " + str1; }}
Module2.ts
// Importing everything from the MODULE1.ts // using 'import *' and 'as' keyword import * as AllImports from "./MODULE1"; // Variables createdlet str = "Geeks";let str1 = "GeeksforGeeks"; // Calling function using common import// name i.e. AllImportconsole.log(AllImports.Welcome(str)); // Object of imported class is createdlet obj = new AllImports.Geeks(); // Calling the import class function// using object nameconsole.log(obj.msg(str1));
Steps to print output:
> tsc MODULE2.ts
> node MODULE2.js
Output:
rs1686740
JavaScript-Questions
Picked
TypeScript
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n19 Oct, 2021"
},
{
"code": null,
"e": 161,
"s": 54,
"text": "Before starting with importing modules, first of all, we need to know the basics of modules in TypeScript."
},
{
"code": null,
"e": 457,
"s": 161,
"text": "We know that JavaScript has come with the concept of modules from the ES6 version in 2015 and by 2020 had broad support in most web browsers and JavaScript runtimes. TypeScript also shares the same concept of a module. Any file which contains a top-level import or export is considered a module."
},
{
"code": null,
"e": 800,
"s": 457,
"text": "The module is designed to arrange a code written in TypeScript and used as a local scope. Modules are basically scripts written in separate files. Import allows you to reference their source location in an existing file. Now we will understand different ways to import external models, and know how to use that module in the desired location."
},
{
"code": null,
"e": 1073,
"s": 800,
"text": "Approach: Before importing any module we need to export it from another file. We can create a module by using the export keyword and can use it in other modules by using the import keyword. We can export both class-based modules and function-based modules. as shown below."
},
{
"code": null,
"e": 1112,
"s": 1073,
"text": "Syntax for export class-based module: "
},
{
"code": null,
"e": 1244,
"s": 1112,
"text": "export class CLASS_NAME {\n constructor(para1 , para2) {}\n Method() {\n console.log(\"This is class-based Module export\" );\n }\n}"
},
{
"code": null,
"e": 1285,
"s": 1244,
"text": "Syntax for export function-based module:"
},
{
"code": null,
"e": 1376,
"s": 1285,
"text": "export function FUNCTION_NAME {\n console.log(\"This is function-based Module export\");\n}"
},
{
"code": null,
"e": 1573,
"s": 1376,
"text": "Ways to Import External Modules: In TypeScript, we use the keyword import and from to import a particular module or a named parameter. Let’s see the different ways we can use the import operation."
},
{
"code": null,
"e": 1835,
"s": 1573,
"text": "1. Import Default Export: In order to import the default export from a file, we can use the from location of the file and use the keyword import before it, or we could give a specific name i.e. MODULE_NAME to the import which makes the syntax as the following."
},
{
"code": null,
"e": 1879,
"s": 1835,
"text": "import MODULE_NAME from './MODULE_LOCATION'"
},
{
"code": null,
"e": 2078,
"s": 1879,
"text": "2. Import Named Values: It is not necessary that every file exports default modules, they can have a number of named parameters and in case we need to import one we should use the syntax as follows."
},
{
"code": null,
"e": 2126,
"s": 2078,
"text": "import { MODULE_NAME } from './MODULE_LOCATION'"
},
{
"code": null,
"e": 2283,
"s": 2126,
"text": "And similarly, for multiple modules imports, we can use a comma ( , ) separator to separate two-parameter names within the curly braces { }. As shown below."
},
{
"code": null,
"e": 2370,
"s": 2283,
"text": "import { MODULE_NAME1, MODULE_NAME2, ... , \n MODULE_NAMEn } from ./MODULE_LOCATION'"
},
{
"code": null,
"e": 2583,
"s": 2370,
"text": "3. Importing a combination of Default Exports and Named Values: The title makes it clear what we need to see is that the syntax of the same. In order to import a combination, we should use the following syntax. "
},
{
"code": null,
"e": 2692,
"s": 2583,
"text": "import DEFAULT_EXPORT, { MODULE_NAME1, \n MODULE_NAME2, ... , MODULE_NAMEn } \n from './MODULE_LOCATION'"
},
{
"code": null,
"e": 2907,
"s": 2692,
"text": "4. Import everything from the Module: Sometimes you need to import every module from the specific file, then you can use ( * ) asterisk to import all modules and assign them to an object ( OBJ_NAME ) as shown below"
},
{
"code": null,
"e": 2953,
"s": 2907,
"text": "import * as OBJ_NAME from './MODULE_LOCATION'"
},
{
"code": null,
"e": 2969,
"s": 2953,
"text": "Or you can use:"
},
{
"code": null,
"e": 3005,
"s": 2969,
"text": "import MODULE = require('LOCATION')"
},
{
"code": null,
"e": 3072,
"s": 3005,
"text": "Now we implement what we learn above using the following examples:"
},
{
"code": null,
"e": 3143,
"s": 3072,
"text": "Example 1: Import a default export module from a file to another file."
},
{
"code": null,
"e": 3154,
"s": 3143,
"text": "Module1.ts"
},
{
"code": "// Exporting the Default export module// which is used in another file// export default keyword used to // Export the moduleexport default function GFG() { return \"GeeksforGeeks\";}",
"e": 3338,
"s": 3154,
"text": null
},
{
"code": null,
"e": 3349,
"s": 3338,
"text": "Module2.ts"
},
{
"code": "// Importing the default export module // from the location of the file.import GFG from \"./MODULE1\"; // Creating an object of the// class which is importedlet msg = GFG(); console.log(\"This is MSG from \"); console.log(msg);",
"e": 3576,
"s": 3349,
"text": null
},
{
"code": null,
"e": 3726,
"s": 3576,
"text": "Steps to print output: First, convert the TypeScript file into JavaScript for that you need to run the following command on your respective terminal."
},
{
"code": null,
"e": 3743,
"s": 3726,
"text": "> tsc MODULE2.ts"
},
{
"code": null,
"e": 3828,
"s": 3743,
"text": "After that, you need to run a JavaScript file using the Node module. as shown below."
},
{
"code": null,
"e": 3846,
"s": 3828,
"text": "> node MODULE2.js"
},
{
"code": null,
"e": 3854,
"s": 3846,
"text": "Output:"
},
{
"code": null,
"e": 3909,
"s": 3854,
"text": "Example 2: Import a class from a file to another file."
},
{
"code": null,
"e": 3920,
"s": 3909,
"text": "Module1.ts"
},
{
"code": "// Exporting the class which used in another file// export keyword used to Export the moduleexport class GFG { StringConcat(banner) { return \"Welcome to \" + banner; }}",
"e": 4105,
"s": 3920,
"text": null
},
{
"code": null,
"e": 4116,
"s": 4105,
"text": "Module2.ts"
},
{
"code": "// Importing the module// from the location of the file.import { GFG } from \"./Module1\"; let obj1 = new GFG(); console.log(obj1.StringConcat(\"GeeksforGeeks\"));",
"e": 4278,
"s": 4116,
"text": null
},
{
"code": null,
"e": 4301,
"s": 4278,
"text": "Steps to print output:"
},
{
"code": null,
"e": 4336,
"s": 4301,
"text": "> tsc MODULE2.ts\n> node MODULE2.js"
},
{
"code": null,
"e": 4344,
"s": 4336,
"text": "Output:"
},
{
"code": null,
"e": 4403,
"s": 4344,
"text": "Example 3: Import all modules from a file to another file."
},
{
"code": null,
"e": 4414,
"s": 4403,
"text": "Module1.ts"
},
{
"code": "// Export all the classes functions export function Welcome(str: string) { return \"Hello \" + str + \"..!\";} export class Geeks { msg(str1: string) { return \"Welcome to \" + str1; }}",
"e": 4602,
"s": 4414,
"text": null
},
{
"code": null,
"e": 4613,
"s": 4602,
"text": "Module2.ts"
},
{
"code": "// Importing everything from the MODULE1.ts // using 'import *' and 'as' keyword import * as AllImports from \"./MODULE1\"; // Variables createdlet str = \"Geeks\";let str1 = \"GeeksforGeeks\"; // Calling function using common import// name i.e. AllImportconsole.log(AllImports.Welcome(str)); // Object of imported class is createdlet obj = new AllImports.Geeks(); // Calling the import class function// using object nameconsole.log(obj.msg(str1));",
"e": 5061,
"s": 4613,
"text": null
},
{
"code": null,
"e": 5084,
"s": 5061,
"text": "Steps to print output:"
},
{
"code": null,
"e": 5119,
"s": 5084,
"text": "> tsc MODULE2.ts\n> node MODULE2.js"
},
{
"code": null,
"e": 5127,
"s": 5119,
"text": "Output:"
},
{
"code": null,
"e": 5137,
"s": 5127,
"text": "rs1686740"
},
{
"code": null,
"e": 5158,
"s": 5137,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 5165,
"s": 5158,
"text": "Picked"
},
{
"code": null,
"e": 5176,
"s": 5165,
"text": "TypeScript"
},
{
"code": null,
"e": 5187,
"s": 5176,
"text": "JavaScript"
},
{
"code": null,
"e": 5204,
"s": 5187,
"text": "Web Technologies"
}
] |
PyQtGraph – Enable Mouse on Plot Window
|
01 Jun, 2021
In this article we will see how we can enable mouse on the plot window in the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) and second is to provide tools to aid in rapid application development (for example, property trees such as used in Qt Designer).Plot windows consist of two main parts: the Plot Panel containing the actual plotted graphics and the Control Panel. When mouse is enable user can use the mouse to interact with the plot like changing size and moving the graph.
In order to do this we use enableMouse method with the plot window objectSyntax : window.enableMouse(True)Argument : It takes bool as argumentReturn : It returns None
Below is the implementation
Python3
# importing pyqtgraph as pgimport pyqtgraph as pg # importing QtCore and QtGui from the pyqtgraph modulefrom pyqtgraph.Qt import QtCore, QtGui # importing numpy as npimport numpy as np # define the datatitle = "GeeksforGeeks PyQtGraph" # y values to plot by line 1y = [2, 8, 6, 8, 6, 11, 14, 13, 18, 19] # y values to plot by line 2y2 = [3, 1, 5, 8, 9, 11, 16, 17, 14, 16]x = range(0, 10) # create plot window objectplt = pg.plot() # showing x and y gridsplt.showGrid(x = True, y = True) # adding legendplt.addLegend() # set properties of the label for y axisplt.setLabel('left', 'Vertical Values', units ='y') # set properties of the label for x axisplt.setLabel('bottom', 'Horizontal Values', units ='s') # setting horizontal rangeplt.setXRange(0, 10) # setting vertical rangeplt.setYRange(0, 20) # setting window titleplt.setWindowTitle(title) # ploting line in green colorline1 = plt.plot(x, y, pen ='g', symbol ='x', symbolPen ='g', symbolBrush = 0.2, name ='green') # ploting line2 with blue colorline2 = plt.plot(x, y2, pen ='b', symbol ='o', symbolPen ='b', symbolBrush = 0.2, name ='blue') # main methodif __name__ == '__main__': # importing system import sys # Start Qt event loop unless running in interactive mode or using if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'): QtGui.QApplication.instance().exec_()
Output :
surinderdawra388
Python-gui
Python-PyQtGraph
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
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Jun, 2021"
},
{
"code": null,
"e": 730,
"s": 28,
"text": "In this article we will see how we can enable mouse on the plot window in the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) and second is to provide tools to aid in rapid application development (for example, property trees such as used in Qt Designer).Plot windows consist of two main parts: the Plot Panel containing the actual plotted graphics and the Control Panel. When mouse is enable user can use the mouse to interact with the plot like changing size and moving the graph. "
},
{
"code": null,
"e": 899,
"s": 730,
"text": "In order to do this we use enableMouse method with the plot window objectSyntax : window.enableMouse(True)Argument : It takes bool as argumentReturn : It returns None "
},
{
"code": null,
"e": 929,
"s": 899,
"text": "Below is the implementation "
},
{
"code": null,
"e": 937,
"s": 929,
"text": "Python3"
},
{
"code": "# importing pyqtgraph as pgimport pyqtgraph as pg # importing QtCore and QtGui from the pyqtgraph modulefrom pyqtgraph.Qt import QtCore, QtGui # importing numpy as npimport numpy as np # define the datatitle = \"GeeksforGeeks PyQtGraph\" # y values to plot by line 1y = [2, 8, 6, 8, 6, 11, 14, 13, 18, 19] # y values to plot by line 2y2 = [3, 1, 5, 8, 9, 11, 16, 17, 14, 16]x = range(0, 10) # create plot window objectplt = pg.plot() # showing x and y gridsplt.showGrid(x = True, y = True) # adding legendplt.addLegend() # set properties of the label for y axisplt.setLabel('left', 'Vertical Values', units ='y') # set properties of the label for x axisplt.setLabel('bottom', 'Horizontal Values', units ='s') # setting horizontal rangeplt.setXRange(0, 10) # setting vertical rangeplt.setYRange(0, 20) # setting window titleplt.setWindowTitle(title) # ploting line in green colorline1 = plt.plot(x, y, pen ='g', symbol ='x', symbolPen ='g', symbolBrush = 0.2, name ='green') # ploting line2 with blue colorline2 = plt.plot(x, y2, pen ='b', symbol ='o', symbolPen ='b', symbolBrush = 0.2, name ='blue') # main methodif __name__ == '__main__': # importing system import sys # Start Qt event loop unless running in interactive mode or using if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'): QtGui.QApplication.instance().exec_()",
"e": 2311,
"s": 937,
"text": null
},
{
"code": null,
"e": 2322,
"s": 2311,
"text": "Output : "
},
{
"code": null,
"e": 2341,
"s": 2324,
"text": "surinderdawra388"
},
{
"code": null,
"e": 2352,
"s": 2341,
"text": "Python-gui"
},
{
"code": null,
"e": 2369,
"s": 2352,
"text": "Python-PyQtGraph"
},
{
"code": null,
"e": 2376,
"s": 2369,
"text": "Python"
},
{
"code": null,
"e": 2474,
"s": 2376,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2506,
"s": 2474,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2533,
"s": 2506,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2554,
"s": 2533,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2577,
"s": 2554,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2608,
"s": 2577,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2664,
"s": 2608,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2706,
"s": 2664,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2748,
"s": 2706,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2787,
"s": 2748,
"text": "Python | Get unique values from a list"
}
] |
Magical Indices in an array
|
03 Jun, 2021
Given an array A of integers. Index i of A is said to be connected to index j if j = (i + A[i]) % n + 1 (Assume 1-based indexing). Start traversing array from index i and jump to its next connected index. If on traversing array in the described order, index i is again visited then index i is a magical index. Count the number of magical indexes in the array. Assume that array A consists of non-negative integers.
Examples :
Input : A = {1, 1, 1, 1}
Output : 4
Possible traversals:
1 -> 3 -> 1
2 -> 4 -> 2
3 -> 1 -> 3
4 -> 2 -> 4
Clearly all the indices are magical
Input : A = {0, 0, 0, 2}
Output : 2
Possible traversals:
1 -> 2 -> 3 -> 4 -> 3...
2 -> 3 -> 4 -> 3...
3 -> 4 -> 3
4 -> 3 ->4
Magical indices = 3, 4
Approach: The problem is of counting number of nodes in all the cycles present in the graph. Each index represents a single node of the graph. Each node has a single directed edge as described in the problem statement. This graph has a special property: On starting a traversal from any vertex, a cycle is always detected. This property will be helpful in reducing the time complexity of the solution.
Read this post on how to detect cycle in a directed graph: Detect Cycle in directed graphLet the traversal begins from node i. Node i will be called parent node of this traversal and this parent node will be assigned to all the nodes visited during traversal. While traversing the graph if we discover a node that is already visited and parent node of that visited node is same as parent node of the traversal then a new cycle is detected. To count number of nodes in this cycle, start another dfs from this node until this same node is not visited again. This procedure is repeated for every node i of the graph. In worst case every node will be traversed at most 3 times. Hence solution has linear time complexity.
The stepwise algorithm is:
1. For each node in the graph:
if node i is not visited then:
for every adjacent node j:
if node j is not visited:
par[j] = i
else:
if par[j]==i
cycle detected
count nodes in cycle
2. return count
Implementation:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find number of magical// indices in the given array.#include <bits/stdc++.h>using namespace std; #define mp make_pair#define pb push_back#define mod 1000000007 // Function to count number of magical indices.int solve(int A[], int n){ int i, cnt = 0, j; // Array to store parent node of traversal. int parent[n + 1]; // Array to determine whether current node // is already counted in the cycle. int vis[n + 1]; // Initialize the arrays. memset(parent, -1, sizeof(parent)); memset(vis, 0, sizeof(vis)); for (i = 0; i < n; i++) { j = i; // Check if current node is already // traversed or not. If node is not // traversed yet then parent value // will be -1. if (parent[j] == -1) { // Traverse the graph until an // already visited node is not // found. while (parent[j] == -1) { parent[j] = i; j = (j + A[j] + 1) % n; } // Check parent value to ensure // a cycle is present. if (parent[j] == i) { // Count number of nodes in // the cycle. while (!vis[j]) { vis[j] = 1; cnt++; j = (j + A[j] + 1) % n; } } } } return cnt;} int main(){ int A[] = { 0, 0, 0, 2 }; int n = sizeof(A) / sizeof(A[0]); cout << solve(A, n); return 0;}
// Java program to find number of magical// indices in the given array.import java.io.*;import java.util.*; public class GFG { // Function to count number of magical // indices. static int solve(int []A, int n) { int i, cnt = 0, j; // Array to store parent node of // traversal. int []parent = new int[n + 1]; // Array to determine whether current node // is already counted in the cycle. int []vis = new int[n + 1]; // Initialize the arrays. for (i = 0; i < n+1; i++) { parent[i] = -1; vis[i] = 0; } for (i = 0; i < n; i++) { j = i; // Check if current node is already // traversed or not. If node is not // traversed yet then parent value // will be -1. if (parent[j] == -1) { // Traverse the graph until an // already visited node is not // found. while (parent[j] == -1) { parent[j] = i; j = (j + A[j] + 1) % n; } // Check parent value to ensure // a cycle is present. if (parent[j] == i) { // Count number of nodes in // the cycle. while (vis[j]==0) { vis[j] = 1; cnt++; j = (j + A[j] + 1) % n; } } } } return cnt; } // Driver code public static void main(String args[]) { int []A = { 0, 0, 0, 2 }; int n = A.length; System.out.print(solve(A, n)); }} // This code is contributed by Manish Shaw// (manishshaw1)
# Python3 program to find number of magical# indices in the given array. # Function to count number of magical# indices.def solve(A, n) : cnt = 0 # Array to store parent node of # traversal. parent = [None] * (n + 1) # Array to determine whether current node # is already counted in the cycle. vis = [None] * (n + 1) # Initialize the arrays. for i in range(0, n+1): parent[i] = -1 vis[i] = 0 for i in range(0, n): j = i # Check if current node is already # traversed or not. If node is not # traversed yet then parent value # will be -1. if (parent[j] == -1) : # Traverse the graph until an # already visited node is not # found. while (parent[j] == -1) : parent[j] = i j = (j + A[j] + 1) % n # Check parent value to ensure # a cycle is present. if (parent[j] == i) : # Count number of nodes in # the cycle. while (vis[j]==0) : vis[j] = 1 cnt = cnt + 1 j = (j + A[j] + 1) % n return cnt # Driver code A = [ 0, 0, 0, 2 ]n = len(A)print (solve(A, n)) # This code is contributed by Manish Shaw# (manishshaw1)
// C# program to find number of magical// indices in the given array.using System;using System.Collections.Generic;using System.Linq; class GFG { // Function to count number of magical // indices. static int solve(int []A, int n) { int i, cnt = 0, j; // Array to store parent node of // traversal. int []parent = new int[n + 1]; // Array to determine whether current node // is already counted in the cycle. int []vis = new int[n + 1]; // Initialize the arrays. for (i = 0; i < n+1; i++) { parent[i] = -1; vis[i] = 0; } for (i = 0; i < n; i++) { j = i; // Check if current node is already // traversed or not. If node is not // traversed yet then parent value // will be -1. if (parent[j] == -1) { // Traverse the graph until an // already visited node is not // found. while (parent[j] == -1) { parent[j] = i; j = (j + A[j] + 1) % n; } // Check parent value to ensure // a cycle is present. if (parent[j] == i) { // Count number of nodes in // the cycle. while (vis[j]==0) { vis[j] = 1; cnt++; j = (j + A[j] + 1) % n; } } } } return cnt; } // Driver code public static void Main() { int []A = { 0, 0, 0, 2 }; int n = A.Length; Console.WriteLine(solve(A, n)); }} // This code is contributed by Manish Shaw// (manishshaw1)
<?php// PHP program to find// number of magical// indices in the given// array. // Function to count number// of magical indices.function solve($A, $n){ $i = 0; $cnt = 0; $j = 0; // Array to store parent // node of traversal. $parent = array(); // Array to determine // whether current node // is already counted // in the cycle. $vis = array(); // Initialize the arrays. for ($i = 0; $i < $n + 1; $i++) { $parent[$i] = -1; $vis[$i] = 0; } for ($i = 0; $i < $n; $i++) { $j = $i; // Check if current node is // already traversed or not. // If node is not traversed // yet then parent value will // be -1. if ($parent[$j] == -1) { // Traverse the graph until // an already visited node // is not found. while ($parent[$j] == -1) { $parent[$j] = $i; $j = ($j + $A[$j] + 1) % $n; } // Check parent value to ensure // a cycle is present. if ($parent[$j] == $i) { // Count number of // nodes in the cycle. while ($vis[$j] == 0) { $vis[$j] = 1; $cnt++; $j = ($j + $A[$j] + 1) % $n; } } } } return $cnt;} // Driver code $A = array( 0, 0, 0, 2 );$n = count($A);echo (solve($A, $n)); // This code is contributed by// Manish Shaw (manishshaw1)?>
<script> // Javascript program to find number of magical// indices in the given array.mod = 1000000007 // Function to count number of magical indices.function solve(A, n){ var i, cnt = 0, j; // Array to store parent node of traversal. var parent = new Array(n + 1); // Array to determine whether current node // is already counted in the cycle. var vis = new Array(n + 1); // Initialize the arrays. parent.fill(-1); vis.fill(0); for(i = 0; i < n; i++) { j = i; // Check if current node is already // traversed or not. If node is not // traversed yet then parent value // will be -1. if (parent[j] == -1) { // Traverse the graph until an // already visited node is not // found. while (parent[j] == -1) { parent[j] = i; j = (j + A[j] + 1) % n; } // Check parent value to ensure // a cycle is present. if (parent[j] == i) { // Count number of nodes in // the cycle. while (!vis[j]) { vis[j] = 1; cnt++; j = (j + A[j] + 1) % n; } } } } return cnt;} // Driver codevar A = [ 0, 0, 0, 2 ];var n = A.length; document.write(solve(A, n)); // This code is contributed by SoumikMondal </script>
2
Time Complexity: O(n) Space Complexity: O(n)
manishshaw1
SoumikMondal
DFS
graph-cycle
Arrays
Graph
Arrays
DFS
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n03 Jun, 2021"
},
{
"code": null,
"e": 469,
"s": 54,
"text": "Given an array A of integers. Index i of A is said to be connected to index j if j = (i + A[i]) % n + 1 (Assume 1-based indexing). Start traversing array from index i and jump to its next connected index. If on traversing array in the described order, index i is again visited then index i is a magical index. Count the number of magical indexes in the array. Assume that array A consists of non-negative integers."
},
{
"code": null,
"e": 481,
"s": 469,
"text": "Examples : "
},
{
"code": null,
"e": 771,
"s": 481,
"text": "Input : A = {1, 1, 1, 1}\nOutput : 4\nPossible traversals:\n1 -> 3 -> 1\n2 -> 4 -> 2\n3 -> 1 -> 3\n4 -> 2 -> 4\nClearly all the indices are magical\n\nInput : A = {0, 0, 0, 2}\nOutput : 2\nPossible traversals:\n1 -> 2 -> 3 -> 4 -> 3...\n2 -> 3 -> 4 -> 3...\n3 -> 4 -> 3\n4 -> 3 ->4\nMagical indices = 3, 4"
},
{
"code": null,
"e": 1173,
"s": 771,
"text": "Approach: The problem is of counting number of nodes in all the cycles present in the graph. Each index represents a single node of the graph. Each node has a single directed edge as described in the problem statement. This graph has a special property: On starting a traversal from any vertex, a cycle is always detected. This property will be helpful in reducing the time complexity of the solution."
},
{
"code": null,
"e": 1890,
"s": 1173,
"text": "Read this post on how to detect cycle in a directed graph: Detect Cycle in directed graphLet the traversal begins from node i. Node i will be called parent node of this traversal and this parent node will be assigned to all the nodes visited during traversal. While traversing the graph if we discover a node that is already visited and parent node of that visited node is same as parent node of the traversal then a new cycle is detected. To count number of nodes in this cycle, start another dfs from this node until this same node is not visited again. This procedure is repeated for every node i of the graph. In worst case every node will be traversed at most 3 times. Hence solution has linear time complexity."
},
{
"code": null,
"e": 1919,
"s": 1890,
"text": "The stepwise algorithm is: "
},
{
"code": null,
"e": 2202,
"s": 1919,
"text": "1. For each node in the graph:\n if node i is not visited then:\n for every adjacent node j:\n if node j is not visited:\n par[j] = i\n else:\n if par[j]==i\n cycle detected\n count nodes in cycle\n2. return count "
},
{
"code": null,
"e": 2219,
"s": 2202,
"text": "Implementation: "
},
{
"code": null,
"e": 2223,
"s": 2219,
"text": "C++"
},
{
"code": null,
"e": 2228,
"s": 2223,
"text": "Java"
},
{
"code": null,
"e": 2236,
"s": 2228,
"text": "Python3"
},
{
"code": null,
"e": 2239,
"s": 2236,
"text": "C#"
},
{
"code": null,
"e": 2243,
"s": 2239,
"text": "PHP"
},
{
"code": null,
"e": 2254,
"s": 2243,
"text": "Javascript"
},
{
"code": "// C++ program to find number of magical// indices in the given array.#include <bits/stdc++.h>using namespace std; #define mp make_pair#define pb push_back#define mod 1000000007 // Function to count number of magical indices.int solve(int A[], int n){ int i, cnt = 0, j; // Array to store parent node of traversal. int parent[n + 1]; // Array to determine whether current node // is already counted in the cycle. int vis[n + 1]; // Initialize the arrays. memset(parent, -1, sizeof(parent)); memset(vis, 0, sizeof(vis)); for (i = 0; i < n; i++) { j = i; // Check if current node is already // traversed or not. If node is not // traversed yet then parent value // will be -1. if (parent[j] == -1) { // Traverse the graph until an // already visited node is not // found. while (parent[j] == -1) { parent[j] = i; j = (j + A[j] + 1) % n; } // Check parent value to ensure // a cycle is present. if (parent[j] == i) { // Count number of nodes in // the cycle. while (!vis[j]) { vis[j] = 1; cnt++; j = (j + A[j] + 1) % n; } } } } return cnt;} int main(){ int A[] = { 0, 0, 0, 2 }; int n = sizeof(A) / sizeof(A[0]); cout << solve(A, n); return 0;}",
"e": 3748,
"s": 2254,
"text": null
},
{
"code": "// Java program to find number of magical// indices in the given array.import java.io.*;import java.util.*; public class GFG { // Function to count number of magical // indices. static int solve(int []A, int n) { int i, cnt = 0, j; // Array to store parent node of // traversal. int []parent = new int[n + 1]; // Array to determine whether current node // is already counted in the cycle. int []vis = new int[n + 1]; // Initialize the arrays. for (i = 0; i < n+1; i++) { parent[i] = -1; vis[i] = 0; } for (i = 0; i < n; i++) { j = i; // Check if current node is already // traversed or not. If node is not // traversed yet then parent value // will be -1. if (parent[j] == -1) { // Traverse the graph until an // already visited node is not // found. while (parent[j] == -1) { parent[j] = i; j = (j + A[j] + 1) % n; } // Check parent value to ensure // a cycle is present. if (parent[j] == i) { // Count number of nodes in // the cycle. while (vis[j]==0) { vis[j] = 1; cnt++; j = (j + A[j] + 1) % n; } } } } return cnt; } // Driver code public static void main(String args[]) { int []A = { 0, 0, 0, 2 }; int n = A.length; System.out.print(solve(A, n)); }} // This code is contributed by Manish Shaw// (manishshaw1)",
"e": 5609,
"s": 3748,
"text": null
},
{
"code": "# Python3 program to find number of magical# indices in the given array. # Function to count number of magical# indices.def solve(A, n) : cnt = 0 # Array to store parent node of # traversal. parent = [None] * (n + 1) # Array to determine whether current node # is already counted in the cycle. vis = [None] * (n + 1) # Initialize the arrays. for i in range(0, n+1): parent[i] = -1 vis[i] = 0 for i in range(0, n): j = i # Check if current node is already # traversed or not. If node is not # traversed yet then parent value # will be -1. if (parent[j] == -1) : # Traverse the graph until an # already visited node is not # found. while (parent[j] == -1) : parent[j] = i j = (j + A[j] + 1) % n # Check parent value to ensure # a cycle is present. if (parent[j] == i) : # Count number of nodes in # the cycle. while (vis[j]==0) : vis[j] = 1 cnt = cnt + 1 j = (j + A[j] + 1) % n return cnt # Driver code A = [ 0, 0, 0, 2 ]n = len(A)print (solve(A, n)) # This code is contributed by Manish Shaw# (manishshaw1)",
"e": 6964,
"s": 5609,
"text": null
},
{
"code": "// C# program to find number of magical// indices in the given array.using System;using System.Collections.Generic;using System.Linq; class GFG { // Function to count number of magical // indices. static int solve(int []A, int n) { int i, cnt = 0, j; // Array to store parent node of // traversal. int []parent = new int[n + 1]; // Array to determine whether current node // is already counted in the cycle. int []vis = new int[n + 1]; // Initialize the arrays. for (i = 0; i < n+1; i++) { parent[i] = -1; vis[i] = 0; } for (i = 0; i < n; i++) { j = i; // Check if current node is already // traversed or not. If node is not // traversed yet then parent value // will be -1. if (parent[j] == -1) { // Traverse the graph until an // already visited node is not // found. while (parent[j] == -1) { parent[j] = i; j = (j + A[j] + 1) % n; } // Check parent value to ensure // a cycle is present. if (parent[j] == i) { // Count number of nodes in // the cycle. while (vis[j]==0) { vis[j] = 1; cnt++; j = (j + A[j] + 1) % n; } } } } return cnt; } // Driver code public static void Main() { int []A = { 0, 0, 0, 2 }; int n = A.Length; Console.WriteLine(solve(A, n)); }} // This code is contributed by Manish Shaw// (manishshaw1)",
"e": 8819,
"s": 6964,
"text": null
},
{
"code": "<?php// PHP program to find// number of magical// indices in the given// array. // Function to count number// of magical indices.function solve($A, $n){ $i = 0; $cnt = 0; $j = 0; // Array to store parent // node of traversal. $parent = array(); // Array to determine // whether current node // is already counted // in the cycle. $vis = array(); // Initialize the arrays. for ($i = 0; $i < $n + 1; $i++) { $parent[$i] = -1; $vis[$i] = 0; } for ($i = 0; $i < $n; $i++) { $j = $i; // Check if current node is // already traversed or not. // If node is not traversed // yet then parent value will // be -1. if ($parent[$j] == -1) { // Traverse the graph until // an already visited node // is not found. while ($parent[$j] == -1) { $parent[$j] = $i; $j = ($j + $A[$j] + 1) % $n; } // Check parent value to ensure // a cycle is present. if ($parent[$j] == $i) { // Count number of // nodes in the cycle. while ($vis[$j] == 0) { $vis[$j] = 1; $cnt++; $j = ($j + $A[$j] + 1) % $n; } } } } return $cnt;} // Driver code $A = array( 0, 0, 0, 2 );$n = count($A);echo (solve($A, $n)); // This code is contributed by// Manish Shaw (manishshaw1)?>",
"e": 10429,
"s": 8819,
"text": null
},
{
"code": "<script> // Javascript program to find number of magical// indices in the given array.mod = 1000000007 // Function to count number of magical indices.function solve(A, n){ var i, cnt = 0, j; // Array to store parent node of traversal. var parent = new Array(n + 1); // Array to determine whether current node // is already counted in the cycle. var vis = new Array(n + 1); // Initialize the arrays. parent.fill(-1); vis.fill(0); for(i = 0; i < n; i++) { j = i; // Check if current node is already // traversed or not. If node is not // traversed yet then parent value // will be -1. if (parent[j] == -1) { // Traverse the graph until an // already visited node is not // found. while (parent[j] == -1) { parent[j] = i; j = (j + A[j] + 1) % n; } // Check parent value to ensure // a cycle is present. if (parent[j] == i) { // Count number of nodes in // the cycle. while (!vis[j]) { vis[j] = 1; cnt++; j = (j + A[j] + 1) % n; } } } } return cnt;} // Driver codevar A = [ 0, 0, 0, 2 ];var n = A.length; document.write(solve(A, n)); // This code is contributed by SoumikMondal </script>",
"e": 11929,
"s": 10429,
"text": null
},
{
"code": null,
"e": 11931,
"s": 11929,
"text": "2"
},
{
"code": null,
"e": 11979,
"s": 11933,
"text": "Time Complexity: O(n) Space Complexity: O(n) "
},
{
"code": null,
"e": 11991,
"s": 11979,
"text": "manishshaw1"
},
{
"code": null,
"e": 12004,
"s": 11991,
"text": "SoumikMondal"
},
{
"code": null,
"e": 12008,
"s": 12004,
"text": "DFS"
},
{
"code": null,
"e": 12020,
"s": 12008,
"text": "graph-cycle"
},
{
"code": null,
"e": 12027,
"s": 12020,
"text": "Arrays"
},
{
"code": null,
"e": 12033,
"s": 12027,
"text": "Graph"
},
{
"code": null,
"e": 12040,
"s": 12033,
"text": "Arrays"
},
{
"code": null,
"e": 12044,
"s": 12040,
"text": "DFS"
},
{
"code": null,
"e": 12050,
"s": 12044,
"text": "Graph"
}
] |
SQL Query to Find the Average Value in a Column
|
24 Mar, 2022
In this article, we are going to see how to find the average value in a column in SQL. A column in the SQL table is the vertical catalog structure. In this article, we will be using the Microsoft SQL Server as our database.
For the purpose of example, we will be creating a sample table and performing the same operations on it.
We have the following car table in our database :
CREATE TABLE car (
companyid integer ,
companyname varchar(20) ,
totalmodels integer )
The above query creates a car table for us.
To insert values into the table we need to use the insert statement. Use the below statement to add data to the car table:
INSERT INTO car values(1,'maruti suzuki',10);
INSERT INTO car values(2,'tata',12);
INSERT INTO car values(3,'volkswagen',8);
The above query will add the data to the car table.
Note: We have to insert values according to the table created. For example, we created a car table with companyid as integer, companyname as varchar, and totalmodels as an integer. So, we need to insert an integer, a character, and an integer else we may get an error.
To verify the contents of the table use the below statement:
SELECT * FROM car;
This will show us our created table as shown below:
For this, we need to use avg() function. We have to pass the column name as a parameter. The avg() function has the following syntax:
SELECT AVG( column_name ) FROM table_name;
The avg() function can be used with the SELECT query for retrieving data from a table.
The below query can be used to find the average of the totalmodels column of our cars table:
SELECT AVG(totalmodels) FROM car;
Output :
Let’s verify the output. The average of 10, 12, and 18 is 10. Hence, we have successfully found out the average of all values n a column of a table.
surinderdawra388
SQL-Query
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 | Sub queries in From Clause
Window functions in SQL
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
SQL Query to Convert VARCHAR to INT
RANK() Function in SQL Server
How to Import JSON Data into SQL Server?
SQL Query to Compare Two Dates
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n24 Mar, 2022"
},
{
"code": null,
"e": 278,
"s": 53,
"text": "In this article, we are going to see how to find the average value in a column in SQL. A column in the SQL table is the vertical catalog structure. In this article, we will be using the Microsoft SQL Server as our database."
},
{
"code": null,
"e": 383,
"s": 278,
"text": "For the purpose of example, we will be creating a sample table and performing the same operations on it."
},
{
"code": null,
"e": 433,
"s": 383,
"text": "We have the following car table in our database :"
},
{
"code": null,
"e": 520,
"s": 433,
"text": "CREATE TABLE car (\ncompanyid integer ,\ncompanyname varchar(20) ,\ntotalmodels integer )"
},
{
"code": null,
"e": 564,
"s": 520,
"text": "The above query creates a car table for us."
},
{
"code": null,
"e": 687,
"s": 564,
"text": "To insert values into the table we need to use the insert statement. Use the below statement to add data to the car table:"
},
{
"code": null,
"e": 813,
"s": 687,
"text": "INSERT INTO car values(1,'maruti suzuki',10);\nINSERT INTO car values(2,'tata',12);\nINSERT INTO car values(3,'volkswagen',8);"
},
{
"code": null,
"e": 865,
"s": 813,
"text": "The above query will add the data to the car table."
},
{
"code": null,
"e": 1134,
"s": 865,
"text": "Note: We have to insert values according to the table created. For example, we created a car table with companyid as integer, companyname as varchar, and totalmodels as an integer. So, we need to insert an integer, a character, and an integer else we may get an error."
},
{
"code": null,
"e": 1195,
"s": 1134,
"text": "To verify the contents of the table use the below statement:"
},
{
"code": null,
"e": 1214,
"s": 1195,
"text": "SELECT * FROM car;"
},
{
"code": null,
"e": 1266,
"s": 1214,
"text": "This will show us our created table as shown below:"
},
{
"code": null,
"e": 1400,
"s": 1266,
"text": "For this, we need to use avg() function. We have to pass the column name as a parameter. The avg() function has the following syntax:"
},
{
"code": null,
"e": 1443,
"s": 1400,
"text": "SELECT AVG( column_name ) FROM table_name;"
},
{
"code": null,
"e": 1530,
"s": 1443,
"text": "The avg() function can be used with the SELECT query for retrieving data from a table."
},
{
"code": null,
"e": 1623,
"s": 1530,
"text": "The below query can be used to find the average of the totalmodels column of our cars table:"
},
{
"code": null,
"e": 1657,
"s": 1623,
"text": "SELECT AVG(totalmodels) FROM car;"
},
{
"code": null,
"e": 1666,
"s": 1657,
"text": "Output :"
},
{
"code": null,
"e": 1816,
"s": 1666,
"text": "Let’s verify the output. The average of 10, 12, and 18 is 10. Hence, we have successfully found out the average of all values n a column of a table."
},
{
"code": null,
"e": 1833,
"s": 1816,
"text": "surinderdawra388"
},
{
"code": null,
"e": 1843,
"s": 1833,
"text": "SQL-Query"
},
{
"code": null,
"e": 1847,
"s": 1843,
"text": "SQL"
},
{
"code": null,
"e": 1851,
"s": 1847,
"text": "SQL"
},
{
"code": null,
"e": 1949,
"s": 1851,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2015,
"s": 1949,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 2048,
"s": 2015,
"text": "SQL | Sub queries in From Clause"
},
{
"code": null,
"e": 2072,
"s": 2048,
"text": "Window functions in SQL"
},
{
"code": null,
"e": 2104,
"s": 2072,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 2182,
"s": 2104,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 2199,
"s": 2182,
"text": "SQL using Python"
},
{
"code": null,
"e": 2235,
"s": 2199,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 2265,
"s": 2235,
"text": "RANK() Function in SQL Server"
},
{
"code": null,
"e": 2306,
"s": 2265,
"text": "How to Import JSON Data into SQL Server?"
}
] |
Node.js fs.opendir() Method
|
08 Oct, 2021
The fs.opendir() method is used to asynchronously open a directory in the file system. It creates an fs.Dir object that is used to represent the directory. This object contains various methods that can be used to accessing the directory.
Syntax:
fs.opendir( path[, options], callback )
Parameters: This method accepts three parameters as mentioned above and described below:
path: It is a String, Buffer or URL that denotes the path of the directory that has to be opened.
options: It is an String or an object that can be used to specify optional parameters that will affect the output. It has two optional parameters:encoding: It is a string that specifies the encoding for the path when opening the directory and for subsequent read operations. The default value is ‘utf8’.bufferSize: It is a number that specifies the number of directory entries that are buffered internally when the directory is being read. A higher value means more performance but leads to higher memory usage. The default value is ’32’.
encoding: It is a string that specifies the encoding for the path when opening the directory and for subsequent read operations. The default value is ‘utf8’.
bufferSize: It is a number that specifies the number of directory entries that are buffered internally when the directory is being read. A higher value means more performance but leads to higher memory usage. The default value is ’32’.
callback: It is a function that would be called when the method is executed.err: It is an error that would be thrown if the method fails.dir: It is an fs.Dir object created by the method that represents the directory.
err: It is an error that would be thrown if the method fails.
dir: It is an fs.Dir object created by the method that represents the directory.
Below examples illustrate the fs.opendir() method in Node.js:
Example 1:
// Node.js program to demonstrate the// fs.opendir() method // Import the filesystem moduleconst fs = require('fs'); // Open the directoryconsole.log("Opening the directory");fs.opendir( // Path of the directory "example_dir", // Options for modifying the operation { encoding: "utf8", bufferSize: 64 }, // Callback with the error and returned // directory (err, dir) => { if (err) console.log("Error:", err); else { // Print the pathname of the directory console.log("Path of the directory:", dir.path); // Close the directory console.log("Closing the directory"); dir.closeSync(); } });
Output:
Opening the directory
Path of the directory: example_dir
Closing the directory
Example 2:
// Node.js program to demonstrate the// fs.opendir() method // Import the filesystem moduleconst fs = require('fs'); // Function to get current filenames// in directoryfilenames = fs.readdirSync("example_dir"); console.log("\nCurrent filenames in directory:");filenames.forEach((file) => { console.log(file);}); // Open the directoryfs.opendir("example_dir", (err, dir) => { if (err) console.log("Error:", err); else { // Print the pathname of the directory console.log("\nPath of the directory:", dir.path); // Read the files in the directory // as fs.Dirent objects console.log("First Dirent:", dir.readSync()); console.log("Next Dirent:", dir.readSync()); console.log("Next Dirent:", dir.readSync()); }});
Output:
Current filenames in directory:
file_a.txt
file_b.txt
Path of the directory: example_dir
First Dirent: Dirent { name: 'file_a.txt', [Symbol(type)]: 1 }
Next Dirent: Dirent { name: 'file_b.txt', [Symbol(type)]: 1 }
Next Dirent: null
Reference: https://nodejs.org/api/fs.html#fs_fs_opendir_path_options_callback
Node.js-fs-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Oct, 2021"
},
{
"code": null,
"e": 266,
"s": 28,
"text": "The fs.opendir() method is used to asynchronously open a directory in the file system. It creates an fs.Dir object that is used to represent the directory. This object contains various methods that can be used to accessing the directory."
},
{
"code": null,
"e": 274,
"s": 266,
"text": "Syntax:"
},
{
"code": null,
"e": 314,
"s": 274,
"text": "fs.opendir( path[, options], callback )"
},
{
"code": null,
"e": 403,
"s": 314,
"text": "Parameters: This method accepts three parameters as mentioned above and described below:"
},
{
"code": null,
"e": 501,
"s": 403,
"text": "path: It is a String, Buffer or URL that denotes the path of the directory that has to be opened."
},
{
"code": null,
"e": 1040,
"s": 501,
"text": "options: It is an String or an object that can be used to specify optional parameters that will affect the output. It has two optional parameters:encoding: It is a string that specifies the encoding for the path when opening the directory and for subsequent read operations. The default value is ‘utf8’.bufferSize: It is a number that specifies the number of directory entries that are buffered internally when the directory is being read. A higher value means more performance but leads to higher memory usage. The default value is ’32’."
},
{
"code": null,
"e": 1198,
"s": 1040,
"text": "encoding: It is a string that specifies the encoding for the path when opening the directory and for subsequent read operations. The default value is ‘utf8’."
},
{
"code": null,
"e": 1434,
"s": 1198,
"text": "bufferSize: It is a number that specifies the number of directory entries that are buffered internally when the directory is being read. A higher value means more performance but leads to higher memory usage. The default value is ’32’."
},
{
"code": null,
"e": 1652,
"s": 1434,
"text": "callback: It is a function that would be called when the method is executed.err: It is an error that would be thrown if the method fails.dir: It is an fs.Dir object created by the method that represents the directory."
},
{
"code": null,
"e": 1714,
"s": 1652,
"text": "err: It is an error that would be thrown if the method fails."
},
{
"code": null,
"e": 1795,
"s": 1714,
"text": "dir: It is an fs.Dir object created by the method that represents the directory."
},
{
"code": null,
"e": 1857,
"s": 1795,
"text": "Below examples illustrate the fs.opendir() method in Node.js:"
},
{
"code": null,
"e": 1868,
"s": 1857,
"text": "Example 1:"
},
{
"code": "// Node.js program to demonstrate the// fs.opendir() method // Import the filesystem moduleconst fs = require('fs'); // Open the directoryconsole.log(\"Opening the directory\");fs.opendir( // Path of the directory \"example_dir\", // Options for modifying the operation { encoding: \"utf8\", bufferSize: 64 }, // Callback with the error and returned // directory (err, dir) => { if (err) console.log(\"Error:\", err); else { // Print the pathname of the directory console.log(\"Path of the directory:\", dir.path); // Close the directory console.log(\"Closing the directory\"); dir.closeSync(); } });",
"e": 2511,
"s": 1868,
"text": null
},
{
"code": null,
"e": 2519,
"s": 2511,
"text": "Output:"
},
{
"code": null,
"e": 2599,
"s": 2519,
"text": "Opening the directory\nPath of the directory: example_dir\nClosing the directory\n"
},
{
"code": null,
"e": 2610,
"s": 2599,
"text": "Example 2:"
},
{
"code": "// Node.js program to demonstrate the// fs.opendir() method // Import the filesystem moduleconst fs = require('fs'); // Function to get current filenames// in directoryfilenames = fs.readdirSync(\"example_dir\"); console.log(\"\\nCurrent filenames in directory:\");filenames.forEach((file) => { console.log(file);}); // Open the directoryfs.opendir(\"example_dir\", (err, dir) => { if (err) console.log(\"Error:\", err); else { // Print the pathname of the directory console.log(\"\\nPath of the directory:\", dir.path); // Read the files in the directory // as fs.Dirent objects console.log(\"First Dirent:\", dir.readSync()); console.log(\"Next Dirent:\", dir.readSync()); console.log(\"Next Dirent:\", dir.readSync()); }});",
"e": 3350,
"s": 2610,
"text": null
},
{
"code": null,
"e": 3358,
"s": 3350,
"text": "Output:"
},
{
"code": null,
"e": 3592,
"s": 3358,
"text": "Current filenames in directory:\nfile_a.txt\nfile_b.txt\n\nPath of the directory: example_dir\nFirst Dirent: Dirent { name: 'file_a.txt', [Symbol(type)]: 1 }\nNext Dirent: Dirent { name: 'file_b.txt', [Symbol(type)]: 1 }\nNext Dirent: null\n"
},
{
"code": null,
"e": 3670,
"s": 3592,
"text": "Reference: https://nodejs.org/api/fs.html#fs_fs_opendir_path_options_callback"
},
{
"code": null,
"e": 3688,
"s": 3670,
"text": "Node.js-fs-module"
},
{
"code": null,
"e": 3696,
"s": 3688,
"text": "Node.js"
},
{
"code": null,
"e": 3713,
"s": 3696,
"text": "Web Technologies"
}
] |
PostgreSQL – Reset Password For Postgres
|
22 Apr, 2022
In this article, we will look into the step-by-step process of resetting the Postgres user password in case the user forgets it.
PostgreSQL uses the pg_hba.conf configuration file stored in the database data directory (e.g., C:\Program Files\PostgreSQL\12\data on Windows) and is used to handle user authentication. The hba in pg_hba.conf means host-based authentication.
As resetting the password requires modification in the pg_hba.conf file, you will need to login to the Postgres role without any password.
Follow the below steps to reset a password for the postgres user:
Step 1: Create a backup of the pg_hba.conf file by copying it to a different location or just rename it to pg_hba.conf.bk
Step 2: Now change the pg_hba.conf file by making all local connections from md5 to trust. This will help you to log in to the PostgreSQL database server without using a password.
# TYPE DATABASE USER ADDRESS METHOD
# IPv4 local connections:
host all all 127.0.0.1/32 trust
# IPv6 local connections:
host all all ::1/128 trust
# Allow replication connections from localhost, by a user with the
# replication privilege.
host replication all 127.0.0.1/32 trust
host replication all ::1/128 trust
Step 3: Now restart the PostgreSQL server. On a Windows machine, you can restart the PostgreSQL from Services.
Or use the below command from the window terminal:
pg_ctl -D "C:\Program Files\PostgreSQL\12\data" restart
The “C:\Program Files\PostgreSQL\12\data” is the data directory.
Step 4: Finally connect to the PostgreSQL database server using any tool such as psql or pgAdmin(In pgAdmin, press ok while it prompts you to enter the password without entering anything in the field.):
psql -U postgres
At this stage, you will not be asked for any authentication.
Step 5: Use the below command to set a new password for the postgres user.
ALTER USER postgres WITH PASSWORD 'new_password';
This will change the user’s password as shown below:
Step 6:Now restart the PostgreSQL database server. At this stage, you can connect to the PostgreSQL database server with the new password.
Follow the above steps to successfully reset the Postgres password and do not forget to restore the pg_hba.conf file after the reset to successfully store the credentials for future verification.
arjun8991
postgreSQL-administration
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Apr, 2022"
},
{
"code": null,
"e": 157,
"s": 28,
"text": "In this article, we will look into the step-by-step process of resetting the Postgres user password in case the user forgets it."
},
{
"code": null,
"e": 400,
"s": 157,
"text": "PostgreSQL uses the pg_hba.conf configuration file stored in the database data directory (e.g., C:\\Program Files\\PostgreSQL\\12\\data on Windows) and is used to handle user authentication. The hba in pg_hba.conf means host-based authentication."
},
{
"code": null,
"e": 539,
"s": 400,
"text": "As resetting the password requires modification in the pg_hba.conf file, you will need to login to the Postgres role without any password."
},
{
"code": null,
"e": 605,
"s": 539,
"text": "Follow the below steps to reset a password for the postgres user:"
},
{
"code": null,
"e": 727,
"s": 605,
"text": "Step 1: Create a backup of the pg_hba.conf file by copying it to a different location or just rename it to pg_hba.conf.bk"
},
{
"code": null,
"e": 907,
"s": 727,
"text": "Step 2: Now change the pg_hba.conf file by making all local connections from md5 to trust. This will help you to log in to the PostgreSQL database server without using a password."
},
{
"code": null,
"e": 1403,
"s": 907,
"text": "# TYPE DATABASE USER ADDRESS METHOD\n\n# IPv4 local connections:\nhost all all 127.0.0.1/32 trust\n# IPv6 local connections:\nhost all all ::1/128 trust\n# Allow replication connections from localhost, by a user with the\n# replication privilege.\nhost replication all 127.0.0.1/32 trust\nhost replication all ::1/128 trust"
},
{
"code": null,
"e": 1514,
"s": 1403,
"text": "Step 3: Now restart the PostgreSQL server. On a Windows machine, you can restart the PostgreSQL from Services."
},
{
"code": null,
"e": 1575,
"s": 1514,
"text": " Or use the below command from the window terminal:"
},
{
"code": null,
"e": 1631,
"s": 1575,
"text": "pg_ctl -D \"C:\\Program Files\\PostgreSQL\\12\\data\" restart"
},
{
"code": null,
"e": 1696,
"s": 1631,
"text": "The “C:\\Program Files\\PostgreSQL\\12\\data” is the data directory."
},
{
"code": null,
"e": 1899,
"s": 1696,
"text": "Step 4: Finally connect to the PostgreSQL database server using any tool such as psql or pgAdmin(In pgAdmin, press ok while it prompts you to enter the password without entering anything in the field.):"
},
{
"code": null,
"e": 1916,
"s": 1899,
"text": "psql -U postgres"
},
{
"code": null,
"e": 1977,
"s": 1916,
"text": "At this stage, you will not be asked for any authentication."
},
{
"code": null,
"e": 2052,
"s": 1977,
"text": "Step 5: Use the below command to set a new password for the postgres user."
},
{
"code": null,
"e": 2102,
"s": 2052,
"text": "ALTER USER postgres WITH PASSWORD 'new_password';"
},
{
"code": null,
"e": 2155,
"s": 2102,
"text": "This will change the user’s password as shown below:"
},
{
"code": null,
"e": 2294,
"s": 2155,
"text": "Step 6:Now restart the PostgreSQL database server. At this stage, you can connect to the PostgreSQL database server with the new password."
},
{
"code": null,
"e": 2490,
"s": 2294,
"text": "Follow the above steps to successfully reset the Postgres password and do not forget to restore the pg_hba.conf file after the reset to successfully store the credentials for future verification."
},
{
"code": null,
"e": 2500,
"s": 2490,
"text": "arjun8991"
},
{
"code": null,
"e": 2526,
"s": 2500,
"text": "postgreSQL-administration"
},
{
"code": null,
"e": 2537,
"s": 2526,
"text": "PostgreSQL"
}
] |
PyQt5 – Move the Label Position within the window using Arrow Keys
|
12 Jun, 2020
In this article we will see how we can move the label within the window using arrow keys i.e when ever the arrow key(direction key) get pressed it moves towards that direction. For example when user press the Up arrow key the label will move upward similarly for other arrow keys label will change its position as well.
Concept : We can change the position of the label by incrementing/decrementing the co-ordinate values of the label but do not increment or decrement if it reaches the any end of the side below is the data given to do when each arrow key is pressed.
When Up arrow key is pressed : X Co-ordinate remain same, decrement the Y Co-ordinate
When Down arrow key is pressed : X Co-ordinate remain same, increment the Y Co-ordinate
When Left arrow key is pressed : Decrement X Co-ordinate, Y Co-ordinate remain same
When Right arrow key is pressed : Increment X Co-ordinate, Y Co-ordinate remain same
Below is the edges restriction data so that label should remain in the window
For top edge the y- co-ordinate should be always greater than 0For bottom edge the y- co-ordinate should be always less than height of window – height of labelFor left edge the x- co-ordinate should be always greater than 0For right edge the x- co-ordinate should be always less than width of window – width of label
Implementation Steps :1. Create a Main window2. Create a label inside the main window3. Add style sheet geometry to the label4. Create a speed variable5. Override the key press event6. Inside the key press event get the current x and y co-ordinates of the label7. And check which key key is pressed and check if side end is not reached then update the x and y co-ordinates with the help of move method by incrementing/decrementing speed value from them
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # width of window self.w_width = 500 # height of window self.w_height = 500 # setting geometry self.setGeometry(100, 100, self.w_width, self.w_height) # calling method self.UiComponents() # showing all the widgets self.show() # speed variable self.speed = 15 # method for components def UiComponents(self): # creating a label self.label = QLabel(self) # label width self.l_width = 40 # label height self.l_height = 40 # setting geometry to the label self.label.setGeometry(200, 200, self.l_width, self.l_height) # setting stylesheet to the label self.label.setStyleSheet("QLabel" "{" "border : 4px solid darkgreen;" "background : lightgreen;" "}") # override the key press event def keyPressEvent(self, event): # get the current co-ordinates of the label # X Co-ordinate x = self.label.x() # Y Co-ordinate y = self.label.y() # if up arrow key is pressed if event.key() == Qt.Key_Up: # if top position is attained if y > 0: self.label.move(x, y - self.speed) # if down arrow key is pressed elif event.key() == Qt.Key_Down: # if bottom position is attained # for bottom point, bottom co-ordinate will be # height of window - height of label if y < self.w_height - self.l_height: self.label.move(x, y + self.speed) # if left arrow key is pressed elif event.key() == Qt.Key_Left: # if left end position is attained if x > 0: self.label.move(x - self.speed, y) # if down arrow key is pressed elif event.key() == Qt.Key_Right: # if right end position is attained # for right end point, right co-ordinate will be # width of window - width of label if x < self.w_width - self.l_width: self.label.move(x + self.speed, y) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
PyQt-exercise
Python-gui
Python-PyQt
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 | os.path.join() method
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Jun, 2020"
},
{
"code": null,
"e": 348,
"s": 28,
"text": "In this article we will see how we can move the label within the window using arrow keys i.e when ever the arrow key(direction key) get pressed it moves towards that direction. For example when user press the Up arrow key the label will move upward similarly for other arrow keys label will change its position as well."
},
{
"code": null,
"e": 597,
"s": 348,
"text": "Concept : We can change the position of the label by incrementing/decrementing the co-ordinate values of the label but do not increment or decrement if it reaches the any end of the side below is the data given to do when each arrow key is pressed."
},
{
"code": null,
"e": 943,
"s": 597,
"text": "When Up arrow key is pressed : X Co-ordinate remain same, decrement the Y Co-ordinate \nWhen Down arrow key is pressed : X Co-ordinate remain same, increment the Y Co-ordinate \nWhen Left arrow key is pressed : Decrement X Co-ordinate, Y Co-ordinate remain same\nWhen Right arrow key is pressed : Increment X Co-ordinate, Y Co-ordinate remain same\n"
},
{
"code": null,
"e": 1021,
"s": 943,
"text": "Below is the edges restriction data so that label should remain in the window"
},
{
"code": null,
"e": 1338,
"s": 1021,
"text": "For top edge the y- co-ordinate should be always greater than 0For bottom edge the y- co-ordinate should be always less than height of window – height of labelFor left edge the x- co-ordinate should be always greater than 0For right edge the x- co-ordinate should be always less than width of window – width of label"
},
{
"code": null,
"e": 1791,
"s": 1338,
"text": "Implementation Steps :1. Create a Main window2. Create a label inside the main window3. Add style sheet geometry to the label4. Create a speed variable5. Override the key press event6. Inside the key press event get the current x and y co-ordinates of the label7. And check which key key is pressed and check if side end is not reached then update the x and y co-ordinates with the help of move method by incrementing/decrementing speed value from them"
},
{
"code": null,
"e": 1819,
"s": 1791,
"text": "Below is the implementation"
},
{
"code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # width of window self.w_width = 500 # height of window self.w_height = 500 # setting geometry self.setGeometry(100, 100, self.w_width, self.w_height) # calling method self.UiComponents() # showing all the widgets self.show() # speed variable self.speed = 15 # method for components def UiComponents(self): # creating a label self.label = QLabel(self) # label width self.l_width = 40 # label height self.l_height = 40 # setting geometry to the label self.label.setGeometry(200, 200, self.l_width, self.l_height) # setting stylesheet to the label self.label.setStyleSheet(\"QLabel\" \"{\" \"border : 4px solid darkgreen;\" \"background : lightgreen;\" \"}\") # override the key press event def keyPressEvent(self, event): # get the current co-ordinates of the label # X Co-ordinate x = self.label.x() # Y Co-ordinate y = self.label.y() # if up arrow key is pressed if event.key() == Qt.Key_Up: # if top position is attained if y > 0: self.label.move(x, y - self.speed) # if down arrow key is pressed elif event.key() == Qt.Key_Down: # if bottom position is attained # for bottom point, bottom co-ordinate will be # height of window - height of label if y < self.w_height - self.l_height: self.label.move(x, y + self.speed) # if left arrow key is pressed elif event.key() == Qt.Key_Left: # if left end position is attained if x > 0: self.label.move(x - self.speed, y) # if down arrow key is pressed elif event.key() == Qt.Key_Right: # if right end position is attained # for right end point, right co-ordinate will be # width of window - width of label if x < self.w_width - self.l_width: self.label.move(x + self.speed, y) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 4495,
"s": 1819,
"text": null
},
{
"code": null,
"e": 4504,
"s": 4495,
"text": "Output :"
},
{
"code": null,
"e": 4518,
"s": 4504,
"text": "PyQt-exercise"
},
{
"code": null,
"e": 4529,
"s": 4518,
"text": "Python-gui"
},
{
"code": null,
"e": 4541,
"s": 4529,
"text": "Python-PyQt"
},
{
"code": null,
"e": 4548,
"s": 4541,
"text": "Python"
},
{
"code": null,
"e": 4646,
"s": 4548,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4678,
"s": 4646,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4705,
"s": 4678,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4736,
"s": 4705,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 4757,
"s": 4736,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 4780,
"s": 4757,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 4836,
"s": 4780,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 4878,
"s": 4836,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 4920,
"s": 4878,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 4959,
"s": 4920,
"text": "Python | Get unique values from a list"
}
] |
D3.js selection.each() Function
|
18 Aug, 2020
The selection.each() function in D3.js is used to call the particular function for each selected HTML elements. In function datum(d) and index(i) are given as the parameters. By using this method one can access parent and child data simultaneously.
Syntax:
selection.each(callback);
Parameters: This function accepts a single parameter as mentioned above and described below.
callback: This is the function that is invoked by each selected element.
Return Values: This function does not return anything.
Below given are a few examples of the function given above.
Example1:
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" path1tent="width=device-width, initial-scale=1.0"/> <title> D3.js selection.each() Function</title> </head> <style> .div { width: 200px; height: 200px; background-color: green; overflow: hidden; } div { background-color: red; width: 10px; height: 10px; } </style> <body> <ul> <li>Geeks for geeks</li> <li>Some text</li> </ul> <ul> <li>List tag</li> <li>each function</li> </ul> <button>Click me</button> <script src="https://d3js.org/d3.v4.min.js"> </script> <script src="https://d3js.org/d3-selection.v1.min.js"> </script> <script> let btn = document.querySelector("button"); let func = () => { let p = d3.selectAll("ul"); p.each(function (p, j) { d3.select(this) .selectAll("li") .text(function (d, i) { return "child are edited."; }); }); }; btn.addEventListener("click", func); </script> </body></html>
Output:
Before clicking the button:
After clicking the button:
Example 2:
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" path1tent="width=device-width, initial-scale=1.0"/> <title>D3.js selection.each() Function</title> </head> <style> div { background-color: green; margin-bottom: 5px; padding: 10px; width: fit-content; } </style> <body> <div>Some text</div> <div>Geeks</div> <div>Geeks for geeks</div> <div>Some text</div> <button>Click me</button> <script src="https://d3js.org/d3.v4.min.js"> </script> <script src="https://d3js.org/d3-selection.v1.min.js"> </script> <script> let btn = document.querySelector("button"); let func = () => { let p = d3.selectAll("div"); console.log(p); p.each(function (p, j) { console.log("p: " + p, "j: " + j); d3.select(this).text(function (d, i) { return "DIVs are edited."; }); }); }; btn.addEventListener("click", func); </script> </body></html>
Output:
Before clicking the button:
After clicking the button:
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Aug, 2020"
},
{
"code": null,
"e": 277,
"s": 28,
"text": "The selection.each() function in D3.js is used to call the particular function for each selected HTML elements. In function datum(d) and index(i) are given as the parameters. By using this method one can access parent and child data simultaneously."
},
{
"code": null,
"e": 285,
"s": 277,
"text": "Syntax:"
},
{
"code": null,
"e": 312,
"s": 285,
"text": "selection.each(callback);\n"
},
{
"code": null,
"e": 405,
"s": 312,
"text": "Parameters: This function accepts a single parameter as mentioned above and described below."
},
{
"code": null,
"e": 478,
"s": 405,
"text": "callback: This is the function that is invoked by each selected element."
},
{
"code": null,
"e": 533,
"s": 478,
"text": "Return Values: This function does not return anything."
},
{
"code": null,
"e": 593,
"s": 533,
"text": "Below given are a few examples of the function given above."
},
{
"code": null,
"e": 603,
"s": 593,
"text": "Example1:"
},
{
"code": null,
"e": 608,
"s": 603,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" path1tent=\"width=device-width, initial-scale=1.0\"/> <title> D3.js selection.each() Function</title> </head> <style> .div { width: 200px; height: 200px; background-color: green; overflow: hidden; } div { background-color: red; width: 10px; height: 10px; } </style> <body> <ul> <li>Geeks for geeks</li> <li>Some text</li> </ul> <ul> <li>List tag</li> <li>each function</li> </ul> <button>Click me</button> <script src=\"https://d3js.org/d3.v4.min.js\"> </script> <script src=\"https://d3js.org/d3-selection.v1.min.js\"> </script> <script> let btn = document.querySelector(\"button\"); let func = () => { let p = d3.selectAll(\"ul\"); p.each(function (p, j) { d3.select(this) .selectAll(\"li\") .text(function (d, i) { return \"child are edited.\"; }); }); }; btn.addEventListener(\"click\", func); </script> </body></html>",
"e": 2016,
"s": 608,
"text": null
},
{
"code": null,
"e": 2024,
"s": 2016,
"text": "Output:"
},
{
"code": null,
"e": 2052,
"s": 2024,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 2079,
"s": 2052,
"text": "After clicking the button:"
},
{
"code": null,
"e": 2090,
"s": 2079,
"text": "Example 2:"
},
{
"code": null,
"e": 2095,
"s": 2090,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" path1tent=\"width=device-width, initial-scale=1.0\"/> <title>D3.js selection.each() Function</title> </head> <style> div { background-color: green; margin-bottom: 5px; padding: 10px; width: fit-content; } </style> <body> <div>Some text</div> <div>Geeks</div> <div>Geeks for geeks</div> <div>Some text</div> <button>Click me</button> <script src=\"https://d3js.org/d3.v4.min.js\"> </script> <script src=\"https://d3js.org/d3-selection.v1.min.js\"> </script> <script> let btn = document.querySelector(\"button\"); let func = () => { let p = d3.selectAll(\"div\"); console.log(p); p.each(function (p, j) { console.log(\"p: \" + p, \"j: \" + j); d3.select(this).text(function (d, i) { return \"DIVs are edited.\"; }); }); }; btn.addEventListener(\"click\", func); </script> </body></html>",
"e": 3351,
"s": 2095,
"text": null
},
{
"code": null,
"e": 3359,
"s": 3351,
"text": "Output:"
},
{
"code": null,
"e": 3387,
"s": 3359,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 3415,
"s": 3387,
"text": "After clicking the button: "
},
{
"code": null,
"e": 3421,
"s": 3415,
"text": "D3.js"
},
{
"code": null,
"e": 3432,
"s": 3421,
"text": "JavaScript"
},
{
"code": null,
"e": 3449,
"s": 3432,
"text": "Web Technologies"
}
] |
Serialize and Deserialize JSON using GSON Library in Android
|
06 Dec, 2021
When we need to send some data from one activity to another, we can use intents with putExtra() function. But we putExtra supports primitive data types. So if we need to pass and the user defines the object, we need to serialize it first, then send it to the destination. While receiving the data we need to deserialize it. We will serialize and deserialize objects to JSON using the Gson library.
Step 1: Create a new project in android studio using kotlin.
Step 2: Create a user-defined data class
Kotlin
package com.ayush.serialize_deserialize data class StudentInfo(val id: Int, val Name :String, val RollNo : Int)
Step 3: Create a new activity where we will send the data
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:gravity="center" android:orientation="vertical" android:layout_height="match_parent" tools:context=".SecondActivity"> <TextView android:id="@+id/tvId" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="ID" android:textStyle="bold" android:textColor="#7CB342" android:textSize="22sp"/> <TextView android:id="@+id/tvName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="NAME" android:textStyle="bold" android:textColor="#7CB342" android:layout_margin="4dp" android:textSize="22sp"/> <TextView android:id="@+id/tvRoll" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="ROLL" android:textStyle="bold" android:textColor="#7CB342" android:textSize="22sp"/></LinearLayout>
Step 4: Now we will create an object of user define class, and convert it into JSON data using Gson().toJson() function and send it to the intent.
Kotlin
package com.ayush.serialize_deserialize import android.content.Intentimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport com.google.gson.Gson class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val stu01 = StudentInfo(1,"AMAN",10) val json = Gson().toJson(stu01) val intent = Intent(this,SecondActivity::class.java) intent.putExtra("data",json) startActivity(intent) }}
Step 5: We will extract data from intent using getExtra() method and deserialize it using Gson().fromJson().
Kotlin
package com.ayush.serialize_deserialize import android.content.Intentimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.TextViewimport com.google.gson.Gson class SecondActivity : AppCompatActivity() { lateinit var data : StudentInfo lateinit var tvId : TextView lateinit var tvName : TextView lateinit var tvRoll : TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_second) tvId = findViewById(R.id.tvId) tvName = findViewById(R.id.tvName) tvRoll= findViewById(R.id.tvRoll) val json = intent.getStringExtra("data") data = Gson().fromJson(json,StudentInfo::class.java) tvId.text = data.id.toString() tvName.text = data.Name tvRoll.text = data.RollNo.toString() }}
So, our app is ready and we can see the output.
Output:
Output
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Android SDK and it's Components
Flutter - Custom Bottom Navigation Bar
Retrofit with Kotlin Coroutine in Android
How to Post Data to API using Retrofit in Android?
Flutter - Stack Widget
Kotlin constructor
Android UI Layouts
Kotlin Array
Retrofit with Kotlin Coroutine in Android
Kotlin Setters and Getters
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Dec, 2021"
},
{
"code": null,
"e": 426,
"s": 28,
"text": "When we need to send some data from one activity to another, we can use intents with putExtra() function. But we putExtra supports primitive data types. So if we need to pass and the user defines the object, we need to serialize it first, then send it to the destination. While receiving the data we need to deserialize it. We will serialize and deserialize objects to JSON using the Gson library."
},
{
"code": null,
"e": 487,
"s": 426,
"text": "Step 1: Create a new project in android studio using kotlin."
},
{
"code": null,
"e": 528,
"s": 487,
"text": "Step 2: Create a user-defined data class"
},
{
"code": null,
"e": 535,
"s": 528,
"text": "Kotlin"
},
{
"code": "package com.ayush.serialize_deserialize data class StudentInfo(val id: Int, val Name :String, val RollNo : Int)",
"e": 648,
"s": 535,
"text": null
},
{
"code": null,
"e": 706,
"s": 648,
"text": "Step 3: Create a new activity where we will send the data"
},
{
"code": null,
"e": 710,
"s": 706,
"text": "XML"
},
{
"code": "<?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:gravity=\"center\" android:orientation=\"vertical\" android:layout_height=\"match_parent\" tools:context=\".SecondActivity\"> <TextView android:id=\"@+id/tvId\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"ID\" android:textStyle=\"bold\" android:textColor=\"#7CB342\" android:textSize=\"22sp\"/> <TextView android:id=\"@+id/tvName\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"NAME\" android:textStyle=\"bold\" android:textColor=\"#7CB342\" android:layout_margin=\"4dp\" android:textSize=\"22sp\"/> <TextView android:id=\"@+id/tvRoll\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"ROLL\" android:textStyle=\"bold\" android:textColor=\"#7CB342\" android:textSize=\"22sp\"/></LinearLayout>",
"e": 1930,
"s": 710,
"text": null
},
{
"code": null,
"e": 2077,
"s": 1930,
"text": "Step 4: Now we will create an object of user define class, and convert it into JSON data using Gson().toJson() function and send it to the intent."
},
{
"code": null,
"e": 2084,
"s": 2077,
"text": "Kotlin"
},
{
"code": "package com.ayush.serialize_deserialize import android.content.Intentimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport com.google.gson.Gson class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val stu01 = StudentInfo(1,\"AMAN\",10) val json = Gson().toJson(stu01) val intent = Intent(this,SecondActivity::class.java) intent.putExtra(\"data\",json) startActivity(intent) }}",
"e": 2657,
"s": 2084,
"text": null
},
{
"code": null,
"e": 2766,
"s": 2657,
"text": "Step 5: We will extract data from intent using getExtra() method and deserialize it using Gson().fromJson()."
},
{
"code": null,
"e": 2773,
"s": 2766,
"text": "Kotlin"
},
{
"code": "package com.ayush.serialize_deserialize import android.content.Intentimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.TextViewimport com.google.gson.Gson class SecondActivity : AppCompatActivity() { lateinit var data : StudentInfo lateinit var tvId : TextView lateinit var tvName : TextView lateinit var tvRoll : TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_second) tvId = findViewById(R.id.tvId) tvName = findViewById(R.id.tvName) tvRoll= findViewById(R.id.tvRoll) val json = intent.getStringExtra(\"data\") data = Gson().fromJson(json,StudentInfo::class.java) tvId.text = data.id.toString() tvName.text = data.Name tvRoll.text = data.RollNo.toString() }}",
"e": 3652,
"s": 2773,
"text": null
},
{
"code": null,
"e": 3700,
"s": 3652,
"text": "So, our app is ready and we can see the output."
},
{
"code": null,
"e": 3708,
"s": 3700,
"text": "Output:"
},
{
"code": null,
"e": 3715,
"s": 3708,
"text": "Output"
},
{
"code": null,
"e": 3723,
"s": 3715,
"text": "Android"
},
{
"code": null,
"e": 3730,
"s": 3723,
"text": "Kotlin"
},
{
"code": null,
"e": 3738,
"s": 3730,
"text": "Android"
},
{
"code": null,
"e": 3836,
"s": 3738,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3868,
"s": 3836,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 3907,
"s": 3868,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 3949,
"s": 3907,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 4000,
"s": 3949,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 4023,
"s": 4000,
"text": "Flutter - Stack Widget"
},
{
"code": null,
"e": 4042,
"s": 4023,
"text": "Kotlin constructor"
},
{
"code": null,
"e": 4061,
"s": 4042,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 4074,
"s": 4061,
"text": "Kotlin Array"
},
{
"code": null,
"e": 4116,
"s": 4074,
"text": "Retrofit with Kotlin Coroutine in Android"
}
] |
Design Issues of Distributed System
|
29 Jun, 2022
Heterogeneity : Heterogeneity is applied to the network, computer hardware, operating system and implementation of different developers. A key component of the heterogeneous distributed system client-server environment is middleware. Middleware is a set of services that enables application and end-user to interacts with each other across a heterogeneous distributed system.Openness: The openness of the distributed system is determined primarily by the degree to which new resource-sharing services can be made available to the users. Open systems are characterized by the fact that their key interfaces are published. It is based on a uniform communication mechanism and published interface for access to shared resources. It can be constructed from heterogeneous hardware and software.Scalability: Scalability of the system should remain efficient even with a significant increase in the number of users and resources connected.Security : Security of information system has three components Confidentially, integrity and availability. Encryption protects shared resources, keeps sensitive information secrets when transmitted.Failure Handling: When some faults occur in hardware and the software program, it may produce incorrect results or they may stop before they have completed the intended computation so corrective measures should to implemented to handle this case. Failure handling is difficult in distributed systems because the failure is partial i, e, some components fail while others continue to function.Concurrency: There is a possibility that several clients will attempt to access a shared resource at the same time. Multiple users make requests on the same resources, i.e read, write, and update. Each resource must be safe in a concurrent environment. Any object that represents a shared resource in a distributed system must ensure that it operates correctly in a concurrent environment.Transparency : Transparency ensures that the distributes system should be perceived as a single entity by the users or the application programmers rather than the collection of autonomous systems, which is cooperating. The user should be unaware of where the services are located and the transferring from a local machine to a remote one should be transparent.
Heterogeneity : Heterogeneity is applied to the network, computer hardware, operating system and implementation of different developers. A key component of the heterogeneous distributed system client-server environment is middleware. Middleware is a set of services that enables application and end-user to interacts with each other across a heterogeneous distributed system.
Openness: The openness of the distributed system is determined primarily by the degree to which new resource-sharing services can be made available to the users. Open systems are characterized by the fact that their key interfaces are published. It is based on a uniform communication mechanism and published interface for access to shared resources. It can be constructed from heterogeneous hardware and software.
Scalability: Scalability of the system should remain efficient even with a significant increase in the number of users and resources connected.
Security : Security of information system has three components Confidentially, integrity and availability. Encryption protects shared resources, keeps sensitive information secrets when transmitted.
Failure Handling: When some faults occur in hardware and the software program, it may produce incorrect results or they may stop before they have completed the intended computation so corrective measures should to implemented to handle this case. Failure handling is difficult in distributed systems because the failure is partial i, e, some components fail while others continue to function.
Concurrency: There is a possibility that several clients will attempt to access a shared resource at the same time. Multiple users make requests on the same resources, i.e read, write, and update. Each resource must be safe in a concurrent environment. Any object that represents a shared resource in a distributed system must ensure that it operates correctly in a concurrent environment.
Transparency : Transparency ensures that the distributes system should be perceived as a single entity by the users or the application programmers rather than the collection of autonomous systems, which is cooperating. The user should be unaware of where the services are located and the transferring from a local machine to a remote one should be transparent.
Want to get a Software Developer/Engineer job at a leading tech company? or Want to make a smooth transition from SDE I to SDE II or Senior Developer profiles? If yes, then you’re required to dive deep into the System Design world! A decent command over System Design concepts is very much essential, especially for the working professionals, to get a much-needed advantage over others during tech interviews.
And that’s why, GeeksforGeeks is providing you with an in-depth interview-centric System Design – Live Course that will help you prepare for the questions related to System Designs for Google, Amazon, Adobe, Uber, and other product-based companies.
pall58183
Information-Security
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Jun, 2022"
},
{
"code": null,
"e": 2300,
"s": 28,
"text": "Heterogeneity : Heterogeneity is applied to the network, computer hardware, operating system and implementation of different developers. A key component of the heterogeneous distributed system client-server environment is middleware. Middleware is a set of services that enables application and end-user to interacts with each other across a heterogeneous distributed system.Openness: The openness of the distributed system is determined primarily by the degree to which new resource-sharing services can be made available to the users. Open systems are characterized by the fact that their key interfaces are published. It is based on a uniform communication mechanism and published interface for access to shared resources. It can be constructed from heterogeneous hardware and software.Scalability: Scalability of the system should remain efficient even with a significant increase in the number of users and resources connected.Security : Security of information system has three components Confidentially, integrity and availability. Encryption protects shared resources, keeps sensitive information secrets when transmitted.Failure Handling: When some faults occur in hardware and the software program, it may produce incorrect results or they may stop before they have completed the intended computation so corrective measures should to implemented to handle this case. Failure handling is difficult in distributed systems because the failure is partial i, e, some components fail while others continue to function.Concurrency: There is a possibility that several clients will attempt to access a shared resource at the same time. Multiple users make requests on the same resources, i.e read, write, and update. Each resource must be safe in a concurrent environment. Any object that represents a shared resource in a distributed system must ensure that it operates correctly in a concurrent environment.Transparency : Transparency ensures that the distributes system should be perceived as a single entity by the users or the application programmers rather than the collection of autonomous systems, which is cooperating. The user should be unaware of where the services are located and the transferring from a local machine to a remote one should be transparent."
},
{
"code": null,
"e": 2676,
"s": 2300,
"text": "Heterogeneity : Heterogeneity is applied to the network, computer hardware, operating system and implementation of different developers. A key component of the heterogeneous distributed system client-server environment is middleware. Middleware is a set of services that enables application and end-user to interacts with each other across a heterogeneous distributed system."
},
{
"code": null,
"e": 3091,
"s": 2676,
"text": "Openness: The openness of the distributed system is determined primarily by the degree to which new resource-sharing services can be made available to the users. Open systems are characterized by the fact that their key interfaces are published. It is based on a uniform communication mechanism and published interface for access to shared resources. It can be constructed from heterogeneous hardware and software."
},
{
"code": null,
"e": 3235,
"s": 3091,
"text": "Scalability: Scalability of the system should remain efficient even with a significant increase in the number of users and resources connected."
},
{
"code": null,
"e": 3434,
"s": 3235,
"text": "Security : Security of information system has three components Confidentially, integrity and availability. Encryption protects shared resources, keeps sensitive information secrets when transmitted."
},
{
"code": null,
"e": 3827,
"s": 3434,
"text": "Failure Handling: When some faults occur in hardware and the software program, it may produce incorrect results or they may stop before they have completed the intended computation so corrective measures should to implemented to handle this case. Failure handling is difficult in distributed systems because the failure is partial i, e, some components fail while others continue to function."
},
{
"code": null,
"e": 4217,
"s": 3827,
"text": "Concurrency: There is a possibility that several clients will attempt to access a shared resource at the same time. Multiple users make requests on the same resources, i.e read, write, and update. Each resource must be safe in a concurrent environment. Any object that represents a shared resource in a distributed system must ensure that it operates correctly in a concurrent environment."
},
{
"code": null,
"e": 4578,
"s": 4217,
"text": "Transparency : Transparency ensures that the distributes system should be perceived as a single entity by the users or the application programmers rather than the collection of autonomous systems, which is cooperating. The user should be unaware of where the services are located and the transferring from a local machine to a remote one should be transparent."
},
{
"code": null,
"e": 4989,
"s": 4578,
"text": "Want to get a Software Developer/Engineer job at a leading tech company? or Want to make a smooth transition from SDE I to SDE II or Senior Developer profiles? If yes, then you’re required to dive deep into the System Design world! A decent command over System Design concepts is very much essential, especially for the working professionals, to get a much-needed advantage over others during tech interviews. "
},
{
"code": null,
"e": 5238,
"s": 4989,
"text": "And that’s why, GeeksforGeeks is providing you with an in-depth interview-centric System Design – Live Course that will help you prepare for the questions related to System Designs for Google, Amazon, Adobe, Uber, and other product-based companies."
},
{
"code": null,
"e": 5248,
"s": 5238,
"text": "pall58183"
},
{
"code": null,
"e": 5269,
"s": 5248,
"text": "Information-Security"
},
{
"code": null,
"e": 5287,
"s": 5269,
"text": "Computer Networks"
},
{
"code": null,
"e": 5305,
"s": 5287,
"text": "Computer Networks"
}
] |
Internal and External Commands in Linux
|
03 Jul, 2020
The UNIX system is command-based i.e things happen because of the commands that you key in. All UNIX commands are seldom more than four characters long.They are grouped into two categories:
Internal Commands : Commands which are built into the shell. For all the shell built-in commands, execution of the same is fast in the sense that the shell doesn’t have to search the given path for them in the PATH variable, and also no process needs to be spawned for executing it.Examples: source, cd, fg, etc.
External Commands : Commands which aren’t built into the shell. When an external command has to be executed, the shell looks for its path given in the PATH variable, and also a new process has to be spawned and the command gets executed. They are usually located in /bin or /usr/bin. For example, when you execute the “cat” command, which usually is at /usr/bin, the executable /usr/bin/cat gets executed.Examples: ls, cat etc.
If you know about UNIX commands, you must have heard about the ls command. Since ls is a program or file having an independent existence in the /bin directory(or /usr/bin), it is branded as an external command that actually means that the ls command is not built into the shell and these are executables present in a separate file. In simple words, when you will key in the ls command, to be executed it will be found in /bin. Most commands are external in nature, but there are some which are not really found anywhere, and some which are normally not executed even if they are in one of the directories specified by PATH. For instance, take echo command:
$type echo
echo is a shell builtin
echo isn’t an external command in the sense that, when you type echo, the shell won’t look in its PATH to locate it(even if it is there in /bin). Rather, it will execute it from its own set of built-in commands that are not stored as separate files. These built-in commands, of which echo is a member, are known as internal commands.
You now might have noticed that it’s the shell that actually does all these works. This program starts running as soon as the user log in and dies when the user logs out. The shell is an external command with a difference, it possesses its own set of internal commands. So, if a command exists both as an internal command of the shell as well as external one(in /bin or /usr/bib), the shell will accord top priority to its own internal command of the same name.
This is exactly the case with echo which is also found in /bin, but rarely ever executed because the shell makes sure that the internal echo command takes precedence over the external. Now, talk more about the internal and external commands.
Getting the list of Internal Commands
If you are using bash shell you can get the list of shell built-in commands with help command :
$help
// this will list all
the shell built-in commands //
How to find out whether a command is internal or external?
In addition to this you can also find out about a particular command i.e whether it is internal or external with the help of type command :
$type cat
cat is /bin/cat
//specifying that cat is
external type//
$type cd
cd is a shell builtin
//specifying that cd is
internal type//
Internal vs External
The question that when to use which command between internal and external command is of no use cause the user uses a command according to the need of the problem he wants to solve. The only difference that exists between internal and external commands is that internal commands work much faster than the external ones as the shell has to look for the path when it comes to the use of external commands.
There are some cases where you can avoid the use of external by using internal in place of them, like if you need to add two numbers you can do it as:
//use of internal command let
for addition//
$let c=a+b
instead of using :
//use of external command expr
for addition//
$c=`expr $a+$b`
In such a case, the use of let will be a better option as it is a shell built-in command so it will work faster than the expr which is an external command.
manav014
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n03 Jul, 2020"
},
{
"code": null,
"e": 242,
"s": 52,
"text": "The UNIX system is command-based i.e things happen because of the commands that you key in. All UNIX commands are seldom more than four characters long.They are grouped into two categories:"
},
{
"code": null,
"e": 555,
"s": 242,
"text": "Internal Commands : Commands which are built into the shell. For all the shell built-in commands, execution of the same is fast in the sense that the shell doesn’t have to search the given path for them in the PATH variable, and also no process needs to be spawned for executing it.Examples: source, cd, fg, etc."
},
{
"code": null,
"e": 983,
"s": 555,
"text": "External Commands : Commands which aren’t built into the shell. When an external command has to be executed, the shell looks for its path given in the PATH variable, and also a new process has to be spawned and the command gets executed. They are usually located in /bin or /usr/bin. For example, when you execute the “cat” command, which usually is at /usr/bin, the executable /usr/bin/cat gets executed.Examples: ls, cat etc."
},
{
"code": null,
"e": 1640,
"s": 983,
"text": "If you know about UNIX commands, you must have heard about the ls command. Since ls is a program or file having an independent existence in the /bin directory(or /usr/bin), it is branded as an external command that actually means that the ls command is not built into the shell and these are executables present in a separate file. In simple words, when you will key in the ls command, to be executed it will be found in /bin. Most commands are external in nature, but there are some which are not really found anywhere, and some which are normally not executed even if they are in one of the directories specified by PATH. For instance, take echo command:"
},
{
"code": null,
"e": 1676,
"s": 1640,
"text": "$type echo\necho is a shell builtin\n"
},
{
"code": null,
"e": 2010,
"s": 1676,
"text": "echo isn’t an external command in the sense that, when you type echo, the shell won’t look in its PATH to locate it(even if it is there in /bin). Rather, it will execute it from its own set of built-in commands that are not stored as separate files. These built-in commands, of which echo is a member, are known as internal commands."
},
{
"code": null,
"e": 2472,
"s": 2010,
"text": "You now might have noticed that it’s the shell that actually does all these works. This program starts running as soon as the user log in and dies when the user logs out. The shell is an external command with a difference, it possesses its own set of internal commands. So, if a command exists both as an internal command of the shell as well as external one(in /bin or /usr/bib), the shell will accord top priority to its own internal command of the same name."
},
{
"code": null,
"e": 2714,
"s": 2472,
"text": "This is exactly the case with echo which is also found in /bin, but rarely ever executed because the shell makes sure that the internal echo command takes precedence over the external. Now, talk more about the internal and external commands."
},
{
"code": null,
"e": 2752,
"s": 2714,
"text": "Getting the list of Internal Commands"
},
{
"code": null,
"e": 2848,
"s": 2752,
"text": "If you are using bash shell you can get the list of shell built-in commands with help command :"
},
{
"code": null,
"e": 2909,
"s": 2848,
"text": "$help\n\n// this will list all\nthe shell built-in commands //\n"
},
{
"code": null,
"e": 2968,
"s": 2909,
"text": "How to find out whether a command is internal or external?"
},
{
"code": null,
"e": 3108,
"s": 2968,
"text": "In addition to this you can also find out about a particular command i.e whether it is internal or external with the help of type command :"
},
{
"code": null,
"e": 3250,
"s": 3108,
"text": "$type cat\ncat is /bin/cat\n\n//specifying that cat is\nexternal type//\n\n$type cd\ncd is a shell builtin\n\n//specifying that cd is\ninternal type//\n"
},
{
"code": null,
"e": 3271,
"s": 3250,
"text": "Internal vs External"
},
{
"code": null,
"e": 3674,
"s": 3271,
"text": "The question that when to use which command between internal and external command is of no use cause the user uses a command according to the need of the problem he wants to solve. The only difference that exists between internal and external commands is that internal commands work much faster than the external ones as the shell has to look for the path when it comes to the use of external commands."
},
{
"code": null,
"e": 3825,
"s": 3674,
"text": "There are some cases where you can avoid the use of external by using internal in place of them, like if you need to add two numbers you can do it as:"
},
{
"code": null,
"e": 3883,
"s": 3825,
"text": "//use of internal command let\nfor addition//\n\n$let c=a+b\n"
},
{
"code": null,
"e": 3902,
"s": 3883,
"text": "instead of using :"
},
{
"code": null,
"e": 3966,
"s": 3902,
"text": "//use of external command expr\nfor addition//\n\n$c=`expr $a+$b`\n"
},
{
"code": null,
"e": 4122,
"s": 3966,
"text": "In such a case, the use of let will be a better option as it is a shell built-in command so it will work faster than the expr which is an external command."
},
{
"code": null,
"e": 4131,
"s": 4122,
"text": "manav014"
},
{
"code": null,
"e": 4142,
"s": 4131,
"text": "Linux-Unix"
}
] |
How to make Range Slider and Selector in Plotly? - GeeksforGeeks
|
01 Oct, 2020
A Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library.
In plotly, the range slider is a custom range-type input control. It allows selecting a value or a range of values between a specified minimum and maximum range. And the range selector is a tool for selecting ranges to display within the chart. It provides buttons to select pre-configured ranges in the chart. It also provides input boxes where the minimum and maximum dates can be manually input.
Example:
Python3
import plotly.graph_objects as pximport plotly.express as goimport numpy as np df = go.data.tips() x = df['total_bill']y = df['day'] plot = px.Figure(data=[px.Scatter( x=x, y=y, mode='lines',)]) plot.update_layout( xaxis=dict( rangeselector=dict( buttons=list([ dict(count=1, step="day", stepmode="backward"), ]) ), rangeslider=dict( visible=True ), )) plot.show()
Output:
Media error: Format(s) not supported or source(s) not found
Python-Plotly
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
|
[
{
"code": null,
"e": 23524,
"s": 23496,
"text": "\n01 Oct, 2020"
},
{
"code": null,
"e": 23828,
"s": 23524,
"text": "A Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library."
},
{
"code": null,
"e": 24227,
"s": 23828,
"text": "In plotly, the range slider is a custom range-type input control. It allows selecting a value or a range of values between a specified minimum and maximum range. And the range selector is a tool for selecting ranges to display within the chart. It provides buttons to select pre-configured ranges in the chart. It also provides input boxes where the minimum and maximum dates can be manually input."
},
{
"code": null,
"e": 24236,
"s": 24227,
"text": "Example:"
},
{
"code": null,
"e": 24244,
"s": 24236,
"text": "Python3"
},
{
"code": "import plotly.graph_objects as pximport plotly.express as goimport numpy as np df = go.data.tips() x = df['total_bill']y = df['day'] plot = px.Figure(data=[px.Scatter( x=x, y=y, mode='lines',)]) plot.update_layout( xaxis=dict( rangeselector=dict( buttons=list([ dict(count=1, step=\"day\", stepmode=\"backward\"), ]) ), rangeslider=dict( visible=True ), )) plot.show()",
"e": 24745,
"s": 24244,
"text": null
},
{
"code": null,
"e": 24753,
"s": 24745,
"text": "Output:"
},
{
"code": null,
"e": 24813,
"s": 24753,
"text": "Media error: Format(s) not supported or source(s) not found"
},
{
"code": null,
"e": 24827,
"s": 24813,
"text": "Python-Plotly"
},
{
"code": null,
"e": 24834,
"s": 24827,
"text": "Python"
},
{
"code": null,
"e": 24932,
"s": 24834,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 24960,
"s": 24932,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 25010,
"s": 24960,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 25032,
"s": 25010,
"text": "Python map() function"
},
{
"code": null,
"e": 25076,
"s": 25032,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 25094,
"s": 25076,
"text": "Python Dictionary"
},
{
"code": null,
"e": 25117,
"s": 25094,
"text": "Taking input in Python"
},
{
"code": null,
"e": 25152,
"s": 25117,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 25174,
"s": 25152,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 25206,
"s": 25174,
"text": "How to Install PIP on Windows ?"
}
] |
How to upload single/multiple image to cloudinary using node.js ? - GeeksforGeeks
|
20 Jan, 2022
Cloudinary is an end-to-end image and video management solution for websites and mobile apps, covering everything from image and video uploads, storage, manipulations, optimizations to delivery.
Installation:
Step 1: Go to the project directory and initialize the project using the below command in the terminal.npm init -y
Step 1: Go to the project directory and initialize the project using the below command in the terminal.
npm init -y
Step 2: Install the required npm packages using the following command.npm install express multer cloudinary
Step 2: Install the required npm packages using the following command.
npm install express multer cloudinary
Step 3: Create 2 files in the current project directory named index.js and public/index.html as shown in the below project directory.
Step 3: Create 2 files in the current project directory named index.js and public/index.html as shown in the below project directory.
Project Structure:
index.html: It basically contains 2 forms i.e single and multiple file upload.
index.html
<!DOCTYPE html><body style="padding: 30px;"> <form method="POST" action="/profile-upload-single" enctype="multipart/form-data"> <div> <label>Upload profile picture</label> <input type="file" name="profile-file" required/> </div> <div> <input type="submit" value="Upload" /> </div> </form> <br><hr><br> <form method="POST" action="/profile-upload-multiple" enctype="multipart/form-data"> <div> <label>Upload multiple profile picture</label> <input type="file" name="profile-files" required multiple /> </div> <div> <input type="submit" value="Upload" /> </div> </form></body></html>
index.js: Replace cloud_name, api_key, api_secret with your cloudinary credentials which you can find on cloudinary dashboard.
index.js
// Requiring moduleconst express = require("express");const multer = require("multer");const port = 3000;const app = express();const cloudinary = require("cloudinary").v2;const bodyParser = require("body-parser");const fs = require("fs"); // Creating uploads folder if not already present// In "uploads" folder we will temporarily upload// image before uploading to cloudinaryif (!fs.existsSync("./uploads")) { fs.mkdirSync("./uploads");} // Multer setupvar storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, "./uploads"); }, filename: function (req, file, cb) { cb(null, file.originalname); },}); var upload = multer({ storage: storage }); // Body parser configurationapp.use(bodyParser.json());app.use(bodyParser.urlencoded({ extended: true })); app.use(express.static(__dirname + "/public"));app.use("/uploads", express.static("uploads")); // Cloudinary configurationcloudinary.config({ cloud_name: "YOUR_CLOUD_NAME", api_key: "YOUR_API_NAME", api_secret: "YOUR_API_SECRET",}); async function uploadToCloudinary(locaFilePath) { // locaFilePath: path of image which was just // uploaded to "uploads" folder var mainFolderName = "main"; // filePathOnCloudinary: path of image we want // to set when it is uploaded to cloudinary var filePathOnCloudinary = mainFolderName + "/" + locaFilePath; return cloudinary.uploader .upload(locaFilePath, { public_id: filePathOnCloudinary }) .then((result) => { // Image has been successfully uploaded on // cloudinary So we dont need local image // file anymore // Remove file from local uploads folder fs.unlinkSync(locaFilePath); return { message: "Success", url: result.url, }; }) .catch((error) => { // Remove file from local uploads folder fs.unlinkSync(locaFilePath); return { message: "Fail" }; });} function buildSuccessMsg(urlList) { // Building success msg to display on screen var response = `<h1> <a href="/">Click to go to Home page</a><br> </h1><hr>`; // Iterating over urls of images and creating basic // html to render images on screen for (var i = 0; i < urlList.length; i++) { response += "File uploaded successfully.<br><br>"; response += `FILE URL: <a href="${urlList[i]}"> ${urlList[i]}</a>.<br><br>`; response += `<img src="${urlList[i]}" /><br><hr>`; } response += `<br><p>Now you can store this url in database or // do anything with it based on use case.</p>`; return response;} app.post( "/profile-upload-single", upload.single("profile-file"), async (req, res, next) => { // req.file is the `profile-file` file // req.body will hold the text fields, // if there were any // req.file.path will have path of image // stored in uploads folder var locaFilePath = req.file.path; // Upload the local image to Cloudinary // and get image url as response var result = await uploadToCloudinary(locaFilePath); // Generate html to display images on web page. var response = buildSuccessMsg([result.url]); return res.send(response); }); app.post( "/profile-upload-multiple", upload.array("profile-files", 12), async (req, res, next) => { // req.files is array of `profile-files` files // req.body will contain the text fields, // if there were any var imageUrlList = []; for (var i = 0; i < req.files.length; i++) { var locaFilePath = req.files[i].path; // Upload the local image to Cloudinary // and get image url as response var result = await uploadToCloudinary(locaFilePath); imageUrlList.push(result.url); } var response = buildSuccessMsg(imageUrlList); return res.send(response); }); app.listen(port, () => { console.log(`Server running on port ${port}! \nClick http://localhost:3000/`);});
Steps to run the program:
node index.js
Output: Open the browser and visit http://localhost:3000. You could now see the following 2 forms i.e single and multiple image upload as shown below.
References: https://cloudinary.com/documentation/node_integration.
rajeev0719singh
sooda367
sagar0719kumar
Node.js-Methods
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Express.js express.Router() Function
JWT Authentication with Node.js
Express.js req.params Property
Difference between npm i and npm ci in Node.js
Mongoose Populate() Method
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Convert a string to an integer in JavaScript
|
[
{
"code": null,
"e": 24922,
"s": 24894,
"text": "\n20 Jan, 2022"
},
{
"code": null,
"e": 25117,
"s": 24922,
"text": "Cloudinary is an end-to-end image and video management solution for websites and mobile apps, covering everything from image and video uploads, storage, manipulations, optimizations to delivery."
},
{
"code": null,
"e": 25131,
"s": 25117,
"text": "Installation:"
},
{
"code": null,
"e": 25246,
"s": 25131,
"text": "Step 1: Go to the project directory and initialize the project using the below command in the terminal.npm init -y"
},
{
"code": null,
"e": 25350,
"s": 25246,
"text": "Step 1: Go to the project directory and initialize the project using the below command in the terminal."
},
{
"code": null,
"e": 25362,
"s": 25350,
"text": "npm init -y"
},
{
"code": null,
"e": 25470,
"s": 25362,
"text": "Step 2: Install the required npm packages using the following command.npm install express multer cloudinary"
},
{
"code": null,
"e": 25541,
"s": 25470,
"text": "Step 2: Install the required npm packages using the following command."
},
{
"code": null,
"e": 25579,
"s": 25541,
"text": "npm install express multer cloudinary"
},
{
"code": null,
"e": 25713,
"s": 25579,
"text": "Step 3: Create 2 files in the current project directory named index.js and public/index.html as shown in the below project directory."
},
{
"code": null,
"e": 25847,
"s": 25713,
"text": "Step 3: Create 2 files in the current project directory named index.js and public/index.html as shown in the below project directory."
},
{
"code": null,
"e": 25866,
"s": 25847,
"text": "Project Structure:"
},
{
"code": null,
"e": 25945,
"s": 25866,
"text": "index.html: It basically contains 2 forms i.e single and multiple file upload."
},
{
"code": null,
"e": 25956,
"s": 25945,
"text": "index.html"
},
{
"code": "<!DOCTYPE html><body style=\"padding: 30px;\"> <form method=\"POST\" action=\"/profile-upload-single\" enctype=\"multipart/form-data\"> <div> <label>Upload profile picture</label> <input type=\"file\" name=\"profile-file\" required/> </div> <div> <input type=\"submit\" value=\"Upload\" /> </div> </form> <br><hr><br> <form method=\"POST\" action=\"/profile-upload-multiple\" enctype=\"multipart/form-data\"> <div> <label>Upload multiple profile picture</label> <input type=\"file\" name=\"profile-files\" required multiple /> </div> <div> <input type=\"submit\" value=\"Upload\" /> </div> </form></body></html>",
"e": 26704,
"s": 25956,
"text": null
},
{
"code": null,
"e": 26831,
"s": 26704,
"text": "index.js: Replace cloud_name, api_key, api_secret with your cloudinary credentials which you can find on cloudinary dashboard."
},
{
"code": null,
"e": 26840,
"s": 26831,
"text": "index.js"
},
{
"code": "// Requiring moduleconst express = require(\"express\");const multer = require(\"multer\");const port = 3000;const app = express();const cloudinary = require(\"cloudinary\").v2;const bodyParser = require(\"body-parser\");const fs = require(\"fs\"); // Creating uploads folder if not already present// In \"uploads\" folder we will temporarily upload// image before uploading to cloudinaryif (!fs.existsSync(\"./uploads\")) { fs.mkdirSync(\"./uploads\");} // Multer setupvar storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, \"./uploads\"); }, filename: function (req, file, cb) { cb(null, file.originalname); },}); var upload = multer({ storage: storage }); // Body parser configurationapp.use(bodyParser.json());app.use(bodyParser.urlencoded({ extended: true })); app.use(express.static(__dirname + \"/public\"));app.use(\"/uploads\", express.static(\"uploads\")); // Cloudinary configurationcloudinary.config({ cloud_name: \"YOUR_CLOUD_NAME\", api_key: \"YOUR_API_NAME\", api_secret: \"YOUR_API_SECRET\",}); async function uploadToCloudinary(locaFilePath) { // locaFilePath: path of image which was just // uploaded to \"uploads\" folder var mainFolderName = \"main\"; // filePathOnCloudinary: path of image we want // to set when it is uploaded to cloudinary var filePathOnCloudinary = mainFolderName + \"/\" + locaFilePath; return cloudinary.uploader .upload(locaFilePath, { public_id: filePathOnCloudinary }) .then((result) => { // Image has been successfully uploaded on // cloudinary So we dont need local image // file anymore // Remove file from local uploads folder fs.unlinkSync(locaFilePath); return { message: \"Success\", url: result.url, }; }) .catch((error) => { // Remove file from local uploads folder fs.unlinkSync(locaFilePath); return { message: \"Fail\" }; });} function buildSuccessMsg(urlList) { // Building success msg to display on screen var response = `<h1> <a href=\"/\">Click to go to Home page</a><br> </h1><hr>`; // Iterating over urls of images and creating basic // html to render images on screen for (var i = 0; i < urlList.length; i++) { response += \"File uploaded successfully.<br><br>\"; response += `FILE URL: <a href=\"${urlList[i]}\"> ${urlList[i]}</a>.<br><br>`; response += `<img src=\"${urlList[i]}\" /><br><hr>`; } response += `<br><p>Now you can store this url in database or // do anything with it based on use case.</p>`; return response;} app.post( \"/profile-upload-single\", upload.single(\"profile-file\"), async (req, res, next) => { // req.file is the `profile-file` file // req.body will hold the text fields, // if there were any // req.file.path will have path of image // stored in uploads folder var locaFilePath = req.file.path; // Upload the local image to Cloudinary // and get image url as response var result = await uploadToCloudinary(locaFilePath); // Generate html to display images on web page. var response = buildSuccessMsg([result.url]); return res.send(response); }); app.post( \"/profile-upload-multiple\", upload.array(\"profile-files\", 12), async (req, res, next) => { // req.files is array of `profile-files` files // req.body will contain the text fields, // if there were any var imageUrlList = []; for (var i = 0; i < req.files.length; i++) { var locaFilePath = req.files[i].path; // Upload the local image to Cloudinary // and get image url as response var result = await uploadToCloudinary(locaFilePath); imageUrlList.push(result.url); } var response = buildSuccessMsg(imageUrlList); return res.send(response); }); app.listen(port, () => { console.log(`Server running on port ${port}! \\nClick http://localhost:3000/`);});",
"e": 31048,
"s": 26840,
"text": null
},
{
"code": null,
"e": 31074,
"s": 31048,
"text": "Steps to run the program:"
},
{
"code": null,
"e": 31088,
"s": 31074,
"text": "node index.js"
},
{
"code": null,
"e": 31239,
"s": 31088,
"text": "Output: Open the browser and visit http://localhost:3000. You could now see the following 2 forms i.e single and multiple image upload as shown below."
},
{
"code": null,
"e": 31306,
"s": 31239,
"text": "References: https://cloudinary.com/documentation/node_integration."
},
{
"code": null,
"e": 31322,
"s": 31306,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 31331,
"s": 31322,
"text": "sooda367"
},
{
"code": null,
"e": 31346,
"s": 31331,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 31362,
"s": 31346,
"text": "Node.js-Methods"
},
{
"code": null,
"e": 31379,
"s": 31362,
"text": "NodeJS-Questions"
},
{
"code": null,
"e": 31386,
"s": 31379,
"text": "Picked"
},
{
"code": null,
"e": 31394,
"s": 31386,
"text": "Node.js"
},
{
"code": null,
"e": 31411,
"s": 31394,
"text": "Web Technologies"
},
{
"code": null,
"e": 31509,
"s": 31411,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31518,
"s": 31509,
"text": "Comments"
},
{
"code": null,
"e": 31531,
"s": 31518,
"text": "Old Comments"
},
{
"code": null,
"e": 31568,
"s": 31531,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 31600,
"s": 31568,
"text": "JWT Authentication with Node.js"
},
{
"code": null,
"e": 31631,
"s": 31600,
"text": "Express.js req.params Property"
},
{
"code": null,
"e": 31678,
"s": 31631,
"text": "Difference between npm i and npm ci in Node.js"
},
{
"code": null,
"e": 31705,
"s": 31678,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 31747,
"s": 31705,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 31790,
"s": 31747,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 31852,
"s": 31790,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 31902,
"s": 31852,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
What are the rules for the Publisher interface in Java 9?
|
A Publisher is a provider of an unbounded number of sequenced elements publishing them according to demand received from its Subscribers. Publisher<T> interface is responsible for publishing elements of type T and provides a subscribe() method for subscribers to connect to it.
public interface Publisher<T> {
public void subscribe(Subscriber<? super T> s);
}
Rules for Publisher interface:
The total number of onNext() methods signaled by Publisher to a Subscriber must be less than or equal to a total number of elements requested by Subscriber ́s Subscription at all times.
A Publisher may signal fewer onNext() methods than requested, and terminate the Subscription by calling onComplete() or onError() methods.
The onSubscribe(), onNext(), onError(), and onComplete() methods signaled to a Subscriber must be signaled serially.
If Publisher fails, then it must signal an onError() method.
If Publisher terminates successfully, then it must signal an onComplete() method.
If Publisher signals either onError() or onComplete() method on Subscriber, then Subscriber’s Subscription must be canceled.
Once terminal state has signaled (onError(), onComplete()), it is required that no further signals can occur.
If Subscription is canceled, its Subscriber must stop being signaled.
Publisher.subscribe() method must call onSubscribe() method on the provided Subscriber prior to any other signals to that Subscriber and returns normally, except when the provided Subscriber is null. In this case, it must throw a NullPointerException to the caller.
Publisher.subscribe() method may call as many times as required with a different Subscriber each time.
A Publisher may support multiple Subscribers and decides whether each Subscription can be unicast or multicast.
|
[
{
"code": null,
"e": 1340,
"s": 1062,
"text": "A Publisher is a provider of an unbounded number of sequenced elements publishing them according to demand received from its Subscribers. Publisher<T> interface is responsible for publishing elements of type T and provides a subscribe() method for subscribers to connect to it."
},
{
"code": null,
"e": 1425,
"s": 1340,
"text": "public interface Publisher<T> {\n public void subscribe(Subscriber<? super T> s);\n}"
},
{
"code": null,
"e": 1456,
"s": 1425,
"text": "Rules for Publisher interface:"
},
{
"code": null,
"e": 1642,
"s": 1456,
"text": "The total number of onNext() methods signaled by Publisher to a Subscriber must be less than or equal to a total number of elements requested by Subscriber ́s Subscription at all times."
},
{
"code": null,
"e": 1781,
"s": 1642,
"text": "A Publisher may signal fewer onNext() methods than requested, and terminate the Subscription by calling onComplete() or onError() methods."
},
{
"code": null,
"e": 1898,
"s": 1781,
"text": "The onSubscribe(), onNext(), onError(), and onComplete() methods signaled to a Subscriber must be signaled serially."
},
{
"code": null,
"e": 1959,
"s": 1898,
"text": "If Publisher fails, then it must signal an onError() method."
},
{
"code": null,
"e": 2041,
"s": 1959,
"text": "If Publisher terminates successfully, then it must signal an onComplete() method."
},
{
"code": null,
"e": 2166,
"s": 2041,
"text": "If Publisher signals either onError() or onComplete() method on Subscriber, then Subscriber’s Subscription must be canceled."
},
{
"code": null,
"e": 2276,
"s": 2166,
"text": "Once terminal state has signaled (onError(), onComplete()), it is required that no further signals can occur."
},
{
"code": null,
"e": 2346,
"s": 2276,
"text": "If Subscription is canceled, its Subscriber must stop being signaled."
},
{
"code": null,
"e": 2612,
"s": 2346,
"text": "Publisher.subscribe() method must call onSubscribe() method on the provided Subscriber prior to any other signals to that Subscriber and returns normally, except when the provided Subscriber is null. In this case, it must throw a NullPointerException to the caller."
},
{
"code": null,
"e": 2715,
"s": 2612,
"text": "Publisher.subscribe() method may call as many times as required with a different Subscriber each time."
},
{
"code": null,
"e": 2827,
"s": 2715,
"text": "A Publisher may support multiple Subscribers and decides whether each Subscription can be unicast or multicast."
}
] |
Support Vector Machine Python Example | by Cory Maklin | Towards Data Science
|
Support Vector Machine (SVM) is a supervised machine learning algorithm capable of performing classification, regression and even outlier detection. The linear SVM classifier works by drawing a straight line between two classes. All the data points that fall on one side of the line will be labeled as one class and all the points that fall on the other side will be labeled as the second. Sounds simple enough, but there’s an infinite amount of lines to choose from. How do we know which line will do the best job of classifying the data? This is where the LSVM algorithm comes in to play. The LSVM algorithm will select a line that not only separates the two classes but stays as far away from the closest samples as possible. In fact, the “support vector” in “support vector machine” refers to two position vectors drawn from the origin to the points which dictate the decision boundary.
Suppose, we had a vector w which is always normal to the hyperplane (perpendicular to the line in 2 dimensions). We can determine how far away a sample is from our decision boundary by projecting the position vector of the sample on to the vector w. As a quick refresher, the dot product of two vectors is proportional to the projection of the first vector on to the second.
If it’s a positive sample, we’re going to insist that the proceeding decision function (the dot product of w and the position vector of a given sample plus some constant) returns a value greater than or equal to 1.
Similarly, if it’s a negative sample, we’re going to insist that the proceeding decision function returns a value smaller than or equal to -1.
In other words, we won’t consider any samples located between the decision boundary and support vectors.
As stated in the MIT lecture, we introduce an additional variable stickily for convenience. The variable y will be equal to positive one for all positive samples and negative one for all negative samples.
After multiplying by y, the equations for the positive and negative samples are equal to one another.
Meaning, we can simplify the constraints down to a single equation.
Next, we need to address the process by which we go about maximizing the margin. To get an equation for the width of the margin, we subtract the first support vector from the one below it and the multiply the result by the unit vector of w which is always perpendicular to the decision boundary.
Using the constraints from above and a bit of algebra, we get the following.
Therefore, in order to select the optimal decision boundary, we must maximize the equation we just computed. We apply a few more tricks before proceeding (refer to the MIT lecture).
Now, in most machine learning algorithms, we’d use something like gradient descent to minimize said function, however, for support vector machines, we use the Lagrangian. The Lagrangian is beyond the scope of this article but if you’re in need of a quick crash course, I recommend checking out Khan Academy. In essence, using Lagrangian, we can solve for the global minimum like we’d do in high school level calculus (i.e. take the derivative of the function and make it equal to zero). The Lagrange tells us to subtract the cost function by the summation over all the constraints where each of those constraints will be multiplied by some constant alpha (normally written as lambda for the Lagrangian).
Then, we perform some more algebra, plugging the equations we found in the previous step back into the original equation.
Before we can proceed any further, we need to express the equation in terms of matrices instead of summations. The reason being, the qp function from the CVXOPT library, which we’ll use to solve the Lagrangian, accepts very specific arguments. Thus, we need to go from:
Where:
And:
To:
We can achieve this using the following identities:
In applying them, we get:
Note: X is the multiplication of x an y (not to be confused with x)
Then, we map the variables to those expected by the CVXOPT library.
Now, we’re ready to write some code. We’ll start off by importing the necessary libraries.
import numpy as npimport cvxoptfrom sklearn.datasets.samples_generator import make_blobsfrom sklearn.model_selection import train_test_splitfrom matplotlib import pyplot as pltfrom sklearn.svm import LinearSVCfrom sklearn.metrics import confusion_matrix
Then, we define our SVM class. As we mentioned previously, instead of using gradient descent to find the best fitting line as in the case of Linear Regression, we can directly solve for w and b using the Lagrangian.
class SVM:def fit(self, X, y): n_samples, n_features = X.shape# P = X^T X K = np.zeros((n_samples, n_samples)) for i in range(n_samples): for j in range(n_samples): K[i,j] = np.dot(X[i], X[j])P = cvxopt.matrix(np.outer(y, y) * K)# q = -1 (1xN) q = cvxopt.matrix(np.ones(n_samples) * -1)# A = y^T A = cvxopt.matrix(y, (1, n_samples))# b = 0 b = cvxopt.matrix(0.0)# -1 (NxN) G = cvxopt.matrix(np.diag(np.ones(n_samples) * -1))# 0 (1xN) h = cvxopt.matrix(np.zeros(n_samples))solution = cvxopt.solvers.qp(P, q, G, h, A, b)# Lagrange multipliers a = np.ravel(solution['x'])# Lagrange have non zero lagrange multipliers sv = a > 1e-5 ind = np.arange(len(a))[sv] self.a = a[sv] self.sv = X[sv] self.sv_y = y[sv]# Intercept self.b = 0 for n in range(len(self.a)): self.b += self.sv_y[n] self.b -= np.sum(self.a * self.sv_y * K[ind[n], sv]) self.b /= len(self.a)# Weights self.w = np.zeros(n_features) for n in range(len(self.a)): self.w += self.a[n] * self.sv_y[n] * self.sv[n] def project(self, X): return np.dot(X, self.w) + self.b def predict(self, X): return np.sign(self.project(X))
To keep things simple, we’ll use the scikit-learn library to generate linearly separable data. We label the negative samples as -1 instead of 0. cvxopt expects the data to be in a specific format which is why we take an intermediate step.
X, y = make_blobs(n_samples=250, centers=2, random_state=0, cluster_std=0.60)y[y == 0] = -1tmp = np.ones(len(X))y = tmp * y
Let’s get a feel for the data by plotting it.
plt.scatter(X[:, 0], X[:, 1], c=y, cmap='winter')
We split the data into training and testing sets.
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
Then, we create and train an instance of our support vector machine class.
svm = SVM()svm.fit(X_train, y_train)
Next, we plot the decision boundary and support vectors.
def f(x, w, b, c=0): return (-w[0] * x - b + c) / w[1]plt.scatter(X_train[:, 0], X_train[:, 1], c=y_train, cmap='winter')# w.x + b = 0a0 = -4; a1 = f(a0, svm.w, svm.b)b0 = 4; b1 = f(b0, svm.w, svm.b)plt.plot([a0,b0], [a1,b1], 'k')# w.x + b = 1a0 = -4; a1 = f(a0, svm.w, svm.b, 1)b0 = 4; b1 = f(b0, svm.w, svm.b, 1)plt.plot([a0,b0], [a1,b1], 'k--')# w.x + b = -1a0 = -4; a1 = f(a0, svm.w, svm.b, -1)b0 = 4; b1 = f(b0, svm.w, svm.b, -1)plt.plot([a0,b0], [a1,b1], 'k--')
We use our model to predict the classes of the samples in the testing set. Given that we’re using our model to classify data, we use a confusion matrix to evaluate its accuracy.
y_pred = svm.predict(X_test)confusion_matrix(y_test, y_pred)
Let’s attempt the same thing using the scikit-learn implementation of the support vector classifier.
svc = LinearSVC()svc.fit(X_train, y_train)
After training our model, we plot the decision boundary and support vectors.
plt.scatter(X_train[:, 0], X_train[:, 1], c=y_train, cmap='winter');ax = plt.gca()xlim = ax.get_xlim()w = svc.coef_[0]a = -w[0] / w[1]xx = np.linspace(xlim[0], xlim[1])yy = a * xx - svc.intercept_[0] / w[1]plt.plot(xx, yy)yy = a * xx - (svc.intercept_[0] - 1) / w[1]plt.plot(xx, yy, 'k--')yy = a * xx - (svc.intercept_[0] + 1) / w[1]plt.plot(xx, yy, 'k--')
Again, we predict which sample belongs to what class based off which side of the line they fall.
y_pred = svc.predict(X_test)confusion_matrix(y_test, y_pred)
As we can see, the classifier correctly classified every sample.
We saw how we could go about using the Lagrangian to determine the line that best separates our data. In the real world, most problems are not linear separable. Thus, we make use of something called the kernel trick to separate the data using something other than a straight line. Stay tuned for an upcoming article where we cover this topic.
|
[
{
"code": null,
"e": 938,
"s": 47,
"text": "Support Vector Machine (SVM) is a supervised machine learning algorithm capable of performing classification, regression and even outlier detection. The linear SVM classifier works by drawing a straight line between two classes. All the data points that fall on one side of the line will be labeled as one class and all the points that fall on the other side will be labeled as the second. Sounds simple enough, but there’s an infinite amount of lines to choose from. How do we know which line will do the best job of classifying the data? This is where the LSVM algorithm comes in to play. The LSVM algorithm will select a line that not only separates the two classes but stays as far away from the closest samples as possible. In fact, the “support vector” in “support vector machine” refers to two position vectors drawn from the origin to the points which dictate the decision boundary."
},
{
"code": null,
"e": 1313,
"s": 938,
"text": "Suppose, we had a vector w which is always normal to the hyperplane (perpendicular to the line in 2 dimensions). We can determine how far away a sample is from our decision boundary by projecting the position vector of the sample on to the vector w. As a quick refresher, the dot product of two vectors is proportional to the projection of the first vector on to the second."
},
{
"code": null,
"e": 1528,
"s": 1313,
"text": "If it’s a positive sample, we’re going to insist that the proceeding decision function (the dot product of w and the position vector of a given sample plus some constant) returns a value greater than or equal to 1."
},
{
"code": null,
"e": 1671,
"s": 1528,
"text": "Similarly, if it’s a negative sample, we’re going to insist that the proceeding decision function returns a value smaller than or equal to -1."
},
{
"code": null,
"e": 1776,
"s": 1671,
"text": "In other words, we won’t consider any samples located between the decision boundary and support vectors."
},
{
"code": null,
"e": 1981,
"s": 1776,
"text": "As stated in the MIT lecture, we introduce an additional variable stickily for convenience. The variable y will be equal to positive one for all positive samples and negative one for all negative samples."
},
{
"code": null,
"e": 2083,
"s": 1981,
"text": "After multiplying by y, the equations for the positive and negative samples are equal to one another."
},
{
"code": null,
"e": 2151,
"s": 2083,
"text": "Meaning, we can simplify the constraints down to a single equation."
},
{
"code": null,
"e": 2447,
"s": 2151,
"text": "Next, we need to address the process by which we go about maximizing the margin. To get an equation for the width of the margin, we subtract the first support vector from the one below it and the multiply the result by the unit vector of w which is always perpendicular to the decision boundary."
},
{
"code": null,
"e": 2524,
"s": 2447,
"text": "Using the constraints from above and a bit of algebra, we get the following."
},
{
"code": null,
"e": 2706,
"s": 2524,
"text": "Therefore, in order to select the optimal decision boundary, we must maximize the equation we just computed. We apply a few more tricks before proceeding (refer to the MIT lecture)."
},
{
"code": null,
"e": 3410,
"s": 2706,
"text": "Now, in most machine learning algorithms, we’d use something like gradient descent to minimize said function, however, for support vector machines, we use the Lagrangian. The Lagrangian is beyond the scope of this article but if you’re in need of a quick crash course, I recommend checking out Khan Academy. In essence, using Lagrangian, we can solve for the global minimum like we’d do in high school level calculus (i.e. take the derivative of the function and make it equal to zero). The Lagrange tells us to subtract the cost function by the summation over all the constraints where each of those constraints will be multiplied by some constant alpha (normally written as lambda for the Lagrangian)."
},
{
"code": null,
"e": 3532,
"s": 3410,
"text": "Then, we perform some more algebra, plugging the equations we found in the previous step back into the original equation."
},
{
"code": null,
"e": 3802,
"s": 3532,
"text": "Before we can proceed any further, we need to express the equation in terms of matrices instead of summations. The reason being, the qp function from the CVXOPT library, which we’ll use to solve the Lagrangian, accepts very specific arguments. Thus, we need to go from:"
},
{
"code": null,
"e": 3809,
"s": 3802,
"text": "Where:"
},
{
"code": null,
"e": 3814,
"s": 3809,
"text": "And:"
},
{
"code": null,
"e": 3818,
"s": 3814,
"text": "To:"
},
{
"code": null,
"e": 3870,
"s": 3818,
"text": "We can achieve this using the following identities:"
},
{
"code": null,
"e": 3896,
"s": 3870,
"text": "In applying them, we get:"
},
{
"code": null,
"e": 3964,
"s": 3896,
"text": "Note: X is the multiplication of x an y (not to be confused with x)"
},
{
"code": null,
"e": 4032,
"s": 3964,
"text": "Then, we map the variables to those expected by the CVXOPT library."
},
{
"code": null,
"e": 4123,
"s": 4032,
"text": "Now, we’re ready to write some code. We’ll start off by importing the necessary libraries."
},
{
"code": null,
"e": 4377,
"s": 4123,
"text": "import numpy as npimport cvxoptfrom sklearn.datasets.samples_generator import make_blobsfrom sklearn.model_selection import train_test_splitfrom matplotlib import pyplot as pltfrom sklearn.svm import LinearSVCfrom sklearn.metrics import confusion_matrix"
},
{
"code": null,
"e": 4593,
"s": 4377,
"text": "Then, we define our SVM class. As we mentioned previously, instead of using gradient descent to find the best fitting line as in the case of Linear Regression, we can directly solve for w and b using the Lagrangian."
},
{
"code": null,
"e": 5903,
"s": 4593,
"text": "class SVM:def fit(self, X, y): n_samples, n_features = X.shape# P = X^T X K = np.zeros((n_samples, n_samples)) for i in range(n_samples): for j in range(n_samples): K[i,j] = np.dot(X[i], X[j])P = cvxopt.matrix(np.outer(y, y) * K)# q = -1 (1xN) q = cvxopt.matrix(np.ones(n_samples) * -1)# A = y^T A = cvxopt.matrix(y, (1, n_samples))# b = 0 b = cvxopt.matrix(0.0)# -1 (NxN) G = cvxopt.matrix(np.diag(np.ones(n_samples) * -1))# 0 (1xN) h = cvxopt.matrix(np.zeros(n_samples))solution = cvxopt.solvers.qp(P, q, G, h, A, b)# Lagrange multipliers a = np.ravel(solution['x'])# Lagrange have non zero lagrange multipliers sv = a > 1e-5 ind = np.arange(len(a))[sv] self.a = a[sv] self.sv = X[sv] self.sv_y = y[sv]# Intercept self.b = 0 for n in range(len(self.a)): self.b += self.sv_y[n] self.b -= np.sum(self.a * self.sv_y * K[ind[n], sv]) self.b /= len(self.a)# Weights self.w = np.zeros(n_features) for n in range(len(self.a)): self.w += self.a[n] * self.sv_y[n] * self.sv[n] def project(self, X): return np.dot(X, self.w) + self.b def predict(self, X): return np.sign(self.project(X))"
},
{
"code": null,
"e": 6142,
"s": 5903,
"text": "To keep things simple, we’ll use the scikit-learn library to generate linearly separable data. We label the negative samples as -1 instead of 0. cvxopt expects the data to be in a specific format which is why we take an intermediate step."
},
{
"code": null,
"e": 6283,
"s": 6142,
"text": "X, y = make_blobs(n_samples=250, centers=2, random_state=0, cluster_std=0.60)y[y == 0] = -1tmp = np.ones(len(X))y = tmp * y"
},
{
"code": null,
"e": 6329,
"s": 6283,
"text": "Let’s get a feel for the data by plotting it."
},
{
"code": null,
"e": 6379,
"s": 6329,
"text": "plt.scatter(X[:, 0], X[:, 1], c=y, cmap='winter')"
},
{
"code": null,
"e": 6429,
"s": 6379,
"text": "We split the data into training and testing sets."
},
{
"code": null,
"e": 6503,
"s": 6429,
"text": "X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)"
},
{
"code": null,
"e": 6578,
"s": 6503,
"text": "Then, we create and train an instance of our support vector machine class."
},
{
"code": null,
"e": 6615,
"s": 6578,
"text": "svm = SVM()svm.fit(X_train, y_train)"
},
{
"code": null,
"e": 6672,
"s": 6615,
"text": "Next, we plot the decision boundary and support vectors."
},
{
"code": null,
"e": 7143,
"s": 6672,
"text": "def f(x, w, b, c=0): return (-w[0] * x - b + c) / w[1]plt.scatter(X_train[:, 0], X_train[:, 1], c=y_train, cmap='winter')# w.x + b = 0a0 = -4; a1 = f(a0, svm.w, svm.b)b0 = 4; b1 = f(b0, svm.w, svm.b)plt.plot([a0,b0], [a1,b1], 'k')# w.x + b = 1a0 = -4; a1 = f(a0, svm.w, svm.b, 1)b0 = 4; b1 = f(b0, svm.w, svm.b, 1)plt.plot([a0,b0], [a1,b1], 'k--')# w.x + b = -1a0 = -4; a1 = f(a0, svm.w, svm.b, -1)b0 = 4; b1 = f(b0, svm.w, svm.b, -1)plt.plot([a0,b0], [a1,b1], 'k--')"
},
{
"code": null,
"e": 7321,
"s": 7143,
"text": "We use our model to predict the classes of the samples in the testing set. Given that we’re using our model to classify data, we use a confusion matrix to evaluate its accuracy."
},
{
"code": null,
"e": 7382,
"s": 7321,
"text": "y_pred = svm.predict(X_test)confusion_matrix(y_test, y_pred)"
},
{
"code": null,
"e": 7483,
"s": 7382,
"text": "Let’s attempt the same thing using the scikit-learn implementation of the support vector classifier."
},
{
"code": null,
"e": 7526,
"s": 7483,
"text": "svc = LinearSVC()svc.fit(X_train, y_train)"
},
{
"code": null,
"e": 7603,
"s": 7526,
"text": "After training our model, we plot the decision boundary and support vectors."
},
{
"code": null,
"e": 7960,
"s": 7603,
"text": "plt.scatter(X_train[:, 0], X_train[:, 1], c=y_train, cmap='winter');ax = plt.gca()xlim = ax.get_xlim()w = svc.coef_[0]a = -w[0] / w[1]xx = np.linspace(xlim[0], xlim[1])yy = a * xx - svc.intercept_[0] / w[1]plt.plot(xx, yy)yy = a * xx - (svc.intercept_[0] - 1) / w[1]plt.plot(xx, yy, 'k--')yy = a * xx - (svc.intercept_[0] + 1) / w[1]plt.plot(xx, yy, 'k--')"
},
{
"code": null,
"e": 8057,
"s": 7960,
"text": "Again, we predict which sample belongs to what class based off which side of the line they fall."
},
{
"code": null,
"e": 8118,
"s": 8057,
"text": "y_pred = svc.predict(X_test)confusion_matrix(y_test, y_pred)"
},
{
"code": null,
"e": 8183,
"s": 8118,
"text": "As we can see, the classifier correctly classified every sample."
}
] |
Style Bootstrap 4 card with bg-success class
|
To set positive action to a card in Bootstrap, use the bg-success class with the card class
Set positive action and use “card bg-success” −
<div class="card bg-success text-white">
Now add the body of the card using the card-body class −
<div class="card bg-success text-white">
<div class="card-body">India won by 7 wickets</div>
</div>
You can try to run the following code to implement the card-success class −
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h3>Result</h3>
<p>Result of the first two matches between India and Australia:</p>
<div class="card bg-success text-white">
<div class="card-body">India won by 10 runs</div>
</div><br>
<div class="card bg-success text-white">
<div class="card-body">India won by 7 wickets</div>
</div>
</div>
</body>
</html>
|
[
{
"code": null,
"e": 1154,
"s": 1062,
"text": "To set positive action to a card in Bootstrap, use the bg-success class with the card class"
},
{
"code": null,
"e": 1202,
"s": 1154,
"text": "Set positive action and use “card bg-success” −"
},
{
"code": null,
"e": 1243,
"s": 1202,
"text": "<div class=\"card bg-success text-white\">"
},
{
"code": null,
"e": 1300,
"s": 1243,
"text": "Now add the body of the card using the card-body class −"
},
{
"code": null,
"e": 1402,
"s": 1300,
"text": "<div class=\"card bg-success text-white\">\n <div class=\"card-body\">India won by 7 wickets</div>\n</div>"
},
{
"code": null,
"e": 1478,
"s": 1402,
"text": "You can try to run the following code to implement the card-success class −"
},
{
"code": null,
"e": 1488,
"s": 1478,
"text": "Live Demo"
},
{
"code": null,
"e": 2353,
"s": 1488,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head> \n <title>Bootstrap Example</title>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css\">\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js\"></script>\n </head>\n<body>\n <div class=\"container\">\n <h3>Result</h3>\n <p>Result of the first two matches between India and Australia:</p>\n <div class=\"card bg-success text-white\">\n <div class=\"card-body\">India won by 10 runs</div>\n </div><br>\n <div class=\"card bg-success text-white\">\n <div class=\"card-body\">India won by 7 wickets</div>\n </div>\n </div>\n</body>\n</html>"
}
] |
Python program to sort a List according to the Length of the Elements?
|
Here we use one user input array and we have to sorted the list according to the length of the elements. Here we use Python inbuilt function sorted().
Input::[“mona”,”pp”,”aaa”]
Lengths are [4,2,3]
So, the sorted array should be [2,3,4]
Output::[“pp”,”aaa”,”mona”]
Step 1: Input list element.
Step 2: apply sorted (A,len) function.
# To sort a list
def sortedlist(A):
newlist = sorted(A, key=len)
return newlist
# Driver code
A=list()
n=int(input("Enter the size of the List ::"))
print("Enter the Element ::")
for i in range(int(n)):
k=input("")
A.append(k)
print("SORTED LIST ::>",sortedlist(A))
Enter the size of the List ::5
Enter the Element ::
mona
gulli
adwaita
aadrika
pinki
SORTED LIST ::> ['mona', 'gulli', 'pinki', 'adwaita', 'aadrika']
|
[
{
"code": null,
"e": 1213,
"s": 1062,
"text": "Here we use one user input array and we have to sorted the list according to the length of the elements. Here we use Python inbuilt function sorted()."
},
{
"code": null,
"e": 1328,
"s": 1213,
"text": "Input::[“mona”,”pp”,”aaa”]\nLengths are [4,2,3]\nSo, the sorted array should be [2,3,4]\nOutput::[“pp”,”aaa”,”mona”]\n"
},
{
"code": null,
"e": 1396,
"s": 1328,
"text": "Step 1: Input list element.\nStep 2: apply sorted (A,len) function.\n"
},
{
"code": null,
"e": 1675,
"s": 1396,
"text": "# To sort a list \ndef sortedlist(A):\n newlist = sorted(A, key=len)\n return newlist\n# Driver code\nA=list()\nn=int(input(\"Enter the size of the List ::\"))\nprint(\"Enter the Element ::\")\nfor i in range(int(n)):\n k=input(\"\")\n A.append(k)\nprint(\"SORTED LIST ::>\",sortedlist(A))"
},
{
"code": null,
"e": 1826,
"s": 1675,
"text": "Enter the size of the List ::5\nEnter the Element ::\nmona\ngulli\nadwaita\naadrika\npinki\nSORTED LIST ::> ['mona', 'gulli', 'pinki', 'adwaita', 'aadrika']\n"
}
] |
Emergency vs Non-Emergency Vehicle Classification | by Venus Rohilla | Towards Data Science
|
Fatalities due to traffic delays of emergency vehicles such as ambulance & fire brigade is a huge problem. In daily life, we often see that emergency vehicles face difficulty in passing through traffic. So differentiating a vehicle into an emergency and non emergency category can be an important component in traffic monitoring as well as self drive car systems as reaching on time to their destination is critical for these services.
In order to find a solution to this problem we would try building a Image classification model that would classify vehicle images as either belonging to the emergency vehicle or non-emergency vehicle category.
The first thing we need to do is to get train and test data set of vehicle images. Here the data set used to build the classification model is downloaded from Analytics vidhya , it consists of emergency and non emergency vehicle images where emergency vehicles usually includes police cars, ambulance and fire brigades .
After this is done we can read in the provided training data set using pandas.
We would be using the fastai vision library for building our image classification model.
from fastai.vision import *df = pd.read_csv('/content/train.csv')df.head()
We have two columns. The image_names column which contains the names of the images and the emergency_or_not column which contains the labels for each image.Here 1 represents label for emergency vehicles and 0 for non emergency vehicles.
This quick look at the data frame provides us with enough information to load in the data and start building our image classification model but before we will do that we will apply transformations to the images that would help us in generalizing our model , that is to gain a high accuracy.
The transformations we would be applying are : do_flip — enabled by default — and flip_vert,max_rotate=50.We will also play around with the lighting by tuning the max_lighting=0.1 and max_warp=0.
tfms= get_transforms(do_flip=True,flip_vert=True,max_rotate=50,max_lighting=0.1,max_warp=0 )
Now that we have our transforms ready to be applied we can load in the data using FastAIs data block api.
data = ImageDataBunch.from_df('/content/cars', df,ds_tfms=tfms,label_delim= None,valid_pct=0.2,fn_col=0, label_col=1 , size=299,bs=64).normalize(imagenet_stats)
The .normalize(imagenet_stats) method above is used to normalize the data set based on the stats of the RGB channels from the ImageNet data set.
What normalization does is that it brings down the intensities of images (original intensity of images is between 0 and 255) between 0 and 1 .This helps increase the computation power of our model .
Now that we’ve loaded our data set, let us have a peek into what it looks like:
data.show_batch(rows=3, figsize=(7,7)
We can also check this by calling a function that tells us about the number of image classes.
print(data.classes)[0, 1]
Since we have our data ready so its time to feed it into a model .We can do this by building a convolution neural network from scratch but doing this would be practically inefficient . So, we take the weights of a pre trained CNN model that has learnt to recognize features(certain kind of things e.g gradient, edges circles e.t.c)
Here we would be using a pre-trained ResNet50 Convolution Neural Net model, and use transfer learning to learn weights of only the last layer of the network.
Transfer learning is when you begin with an existing (trained) neural network used for image recognition — and then tweak it a bit (or more) here and there to train a model for your particular use case, we do this because training a neural network form scratch would mean needing approximately 300,000 image samples, and to achieve really good performance, we’re going to need at least a million images. But with transfer learning we can achieve high performance with limited data set and in much less time .
We would be fine tuning it by keeping some layers frozen and unfreezing some of them and training over it. This is because the top layers learn simple basic features and we need not to train those layers , while the later layers learn more sophisticated features .
In the above picture each different layer learns different features of the images .The latter layers of this convolution neural networks learns features like eyes of birds e.t.c .
We use the cnn_learner function for loading a pre-trained ResNet50 network, that was trained on around a million images from the ImageNet database.
learn =cnn_learner(data,resnet50,pretrained=True,metrics=[accuracy])
Let us now fit one cycle of 4 epochs to see how our model performs on this data set:
learn.fit_one_cycle(4)
The reason for using just 4 epochs is to get an idea of how our model performs and later fine tuning it for better results. As we can see our validation loss is greater then our training loss this clearly indicates that our model is suffering from the problem of under fitting.
Let’s have a look at our model’s predictions :
interp = ClassificationInterpretation.from_learner(learn)
Interpreting top losses:
interp.plot_top_losses(9, figsize=(7,7))
Looking at the top losses we can tell our model makes the same mistake as a human can make when looking at some cars for the first time that seemed to be emergency vehicles but interpreted as non emergency vehicles.
Another useful tool, kind of, is to use something called a confusion matrix which basically shows you for every actual type of emergency and non emergency vehicle prediction , how many times was it predicted to be that .
`interp.plot_confusion_matrix(figsize=(8,8), dpi=60)
17 times our model predicted emergency vehicles as non emergency vehicles , while 4 times it predicted non emergency vehicles as emergency vehicles. Confused uh? after all we are dealing with a confusion matrix!
A frozen layer is a layer that is not trained i.e it is not updated.
So far anything we have done has not changed the pre-trained model weights .All we have done is we added some new layers on top and learned how to mix and match pre-trained features.
But we want the model to learn features specific to our images .In order to do so we would unfreeze some of the layer to update the weights of the entire network according to our images .
Layer one which detects edge and gradient and layer two which detects curves and corners don’t need much learning, they don’t need to change much. while the much later layers need to change. This is universally true when training for other image recognition.
The earlier layers have more general-purpose features. Therefore we would expect them to need less fine-tuning for new datasets. For this reason we will use different learning rates for different layers: the first few layers will be at 1e-4 for basic geometric features and layers closest to the pixels,and 1e-2 as before for the layers we add on top (fully connected layers). We refer to this as differential learning rates.
learn.unfreeze()
We would again run a fit-one-cycle on our unfreeze network and see how it goes now.
learn.fit_one_cycle(3)
The most important hyper-parameter for tuning our model is learning rate.It helps us in finding the optimal solution by adjusting the weights of our network with respect the loss gradient.The lower the value, the slower we travel along the downward slope. While this might be a good idea (using a low learning rate) in terms of making sure that we do not miss any local minima, it could also mean that we’ll be taking a long time to converge — especially if we get stuck on a plateau region.
Here we can see the various effects of learning rate on convergence.
Hence Picking the right learning rate is important, rather than giving it a random guess or multiple trial-and-errors.
To do this we would be using a function called lr_find().This function is an implementation of Leslie Smith’s paper( Cyclical Learning Rates for Training Neural Networks.) on tuning neural network hyper-parameters.
learn.lr_find()
To understand it better we would plot it with help of another function.
learn.recorder.plot()
The learning rate is plotted against the losses.With the help of this graph we can pick our learning rate very easily.
As we can see the loss start increasing after 1e-03 so we would pick a number before that also for updating weights of initial layers we would be choosing a lower learning rate .1e-04 seems good.
With the chosen learning rate we will again train our unfreeze model but this time a bit longer with 10 epochs.
We would use accuracy as another parameter often called metric to evaluate how our model is doing .
or
Before going further let us also get an intuition about fit_one_cycle method.
In this method we do a cycle with two steps of equal lengths, one going from a lower learning rate to a higher one than go back to the minimum.The maximum should be the value picked with the Learning Rate Finder, and the lower one can be ten times lower. -to read a bit more about fit_one_cycle ,do check out this blog .
Now Lets see how our model is doing?
learn.fit_one_cycle(10,max_lr=slice(1e-4,1e-3))
Our model is doing good enough ,there is no under-fitting as our model had this problem earlier and no over-fitting also (Over fitting would mean that the training loss is much lower than the validation loss), as our validation loss is just approximately 0.02 times greater then training loss.
We have reached an accuracy of 96.96%~ 97%.
Since we have updated our model’s weights according to our vehicle classifying problem we will freeze the layers of our model and save it with a name car_classification.
learn.freeze()learn.save('car_classification')
We were able to reach an accuracy of approximately 97% , while we can experiment more with our model in terms of increasing number of epochs , finding more optimal learning rates using plot function, more data augmentation techniques, etc.
[1]:https://arxiv.org/pdf/1803.09820.pdf
[2]:https://sgugger.github.io/the-1cycle-policy.html
[3]:https://arxiv.org/pdf/1506.01186.pdf
[4]:Lesson 1 Notebook, fast.ai Part 1 V2
That’s all for today .💃🏻
Thank you for reading!
|
[
{
"code": null,
"e": 608,
"s": 172,
"text": "Fatalities due to traffic delays of emergency vehicles such as ambulance & fire brigade is a huge problem. In daily life, we often see that emergency vehicles face difficulty in passing through traffic. So differentiating a vehicle into an emergency and non emergency category can be an important component in traffic monitoring as well as self drive car systems as reaching on time to their destination is critical for these services."
},
{
"code": null,
"e": 818,
"s": 608,
"text": "In order to find a solution to this problem we would try building a Image classification model that would classify vehicle images as either belonging to the emergency vehicle or non-emergency vehicle category."
},
{
"code": null,
"e": 1139,
"s": 818,
"text": "The first thing we need to do is to get train and test data set of vehicle images. Here the data set used to build the classification model is downloaded from Analytics vidhya , it consists of emergency and non emergency vehicle images where emergency vehicles usually includes police cars, ambulance and fire brigades ."
},
{
"code": null,
"e": 1218,
"s": 1139,
"text": "After this is done we can read in the provided training data set using pandas."
},
{
"code": null,
"e": 1307,
"s": 1218,
"text": "We would be using the fastai vision library for building our image classification model."
},
{
"code": null,
"e": 1382,
"s": 1307,
"text": "from fastai.vision import *df = pd.read_csv('/content/train.csv')df.head()"
},
{
"code": null,
"e": 1619,
"s": 1382,
"text": "We have two columns. The image_names column which contains the names of the images and the emergency_or_not column which contains the labels for each image.Here 1 represents label for emergency vehicles and 0 for non emergency vehicles."
},
{
"code": null,
"e": 1910,
"s": 1619,
"text": "This quick look at the data frame provides us with enough information to load in the data and start building our image classification model but before we will do that we will apply transformations to the images that would help us in generalizing our model , that is to gain a high accuracy."
},
{
"code": null,
"e": 2106,
"s": 1910,
"text": "The transformations we would be applying are : do_flip — enabled by default — and flip_vert,max_rotate=50.We will also play around with the lighting by tuning the max_lighting=0.1 and max_warp=0."
},
{
"code": null,
"e": 2199,
"s": 2106,
"text": "tfms= get_transforms(do_flip=True,flip_vert=True,max_rotate=50,max_lighting=0.1,max_warp=0 )"
},
{
"code": null,
"e": 2305,
"s": 2199,
"text": "Now that we have our transforms ready to be applied we can load in the data using FastAIs data block api."
},
{
"code": null,
"e": 2466,
"s": 2305,
"text": "data = ImageDataBunch.from_df('/content/cars', df,ds_tfms=tfms,label_delim= None,valid_pct=0.2,fn_col=0, label_col=1 , size=299,bs=64).normalize(imagenet_stats)"
},
{
"code": null,
"e": 2611,
"s": 2466,
"text": "The .normalize(imagenet_stats) method above is used to normalize the data set based on the stats of the RGB channels from the ImageNet data set."
},
{
"code": null,
"e": 2810,
"s": 2611,
"text": "What normalization does is that it brings down the intensities of images (original intensity of images is between 0 and 255) between 0 and 1 .This helps increase the computation power of our model ."
},
{
"code": null,
"e": 2890,
"s": 2810,
"text": "Now that we’ve loaded our data set, let us have a peek into what it looks like:"
},
{
"code": null,
"e": 2928,
"s": 2890,
"text": "data.show_batch(rows=3, figsize=(7,7)"
},
{
"code": null,
"e": 3022,
"s": 2928,
"text": "We can also check this by calling a function that tells us about the number of image classes."
},
{
"code": null,
"e": 3048,
"s": 3022,
"text": "print(data.classes)[0, 1]"
},
{
"code": null,
"e": 3380,
"s": 3048,
"text": "Since we have our data ready so its time to feed it into a model .We can do this by building a convolution neural network from scratch but doing this would be practically inefficient . So, we take the weights of a pre trained CNN model that has learnt to recognize features(certain kind of things e.g gradient, edges circles e.t.c)"
},
{
"code": null,
"e": 3538,
"s": 3380,
"text": "Here we would be using a pre-trained ResNet50 Convolution Neural Net model, and use transfer learning to learn weights of only the last layer of the network."
},
{
"code": null,
"e": 4047,
"s": 3538,
"text": "Transfer learning is when you begin with an existing (trained) neural network used for image recognition — and then tweak it a bit (or more) here and there to train a model for your particular use case, we do this because training a neural network form scratch would mean needing approximately 300,000 image samples, and to achieve really good performance, we’re going to need at least a million images. But with transfer learning we can achieve high performance with limited data set and in much less time ."
},
{
"code": null,
"e": 4312,
"s": 4047,
"text": "We would be fine tuning it by keeping some layers frozen and unfreezing some of them and training over it. This is because the top layers learn simple basic features and we need not to train those layers , while the later layers learn more sophisticated features ."
},
{
"code": null,
"e": 4492,
"s": 4312,
"text": "In the above picture each different layer learns different features of the images .The latter layers of this convolution neural networks learns features like eyes of birds e.t.c ."
},
{
"code": null,
"e": 4640,
"s": 4492,
"text": "We use the cnn_learner function for loading a pre-trained ResNet50 network, that was trained on around a million images from the ImageNet database."
},
{
"code": null,
"e": 4709,
"s": 4640,
"text": "learn =cnn_learner(data,resnet50,pretrained=True,metrics=[accuracy])"
},
{
"code": null,
"e": 4794,
"s": 4709,
"text": "Let us now fit one cycle of 4 epochs to see how our model performs on this data set:"
},
{
"code": null,
"e": 4817,
"s": 4794,
"text": "learn.fit_one_cycle(4)"
},
{
"code": null,
"e": 5095,
"s": 4817,
"text": "The reason for using just 4 epochs is to get an idea of how our model performs and later fine tuning it for better results. As we can see our validation loss is greater then our training loss this clearly indicates that our model is suffering from the problem of under fitting."
},
{
"code": null,
"e": 5142,
"s": 5095,
"text": "Let’s have a look at our model’s predictions :"
},
{
"code": null,
"e": 5200,
"s": 5142,
"text": "interp = ClassificationInterpretation.from_learner(learn)"
},
{
"code": null,
"e": 5225,
"s": 5200,
"text": "Interpreting top losses:"
},
{
"code": null,
"e": 5266,
"s": 5225,
"text": "interp.plot_top_losses(9, figsize=(7,7))"
},
{
"code": null,
"e": 5482,
"s": 5266,
"text": "Looking at the top losses we can tell our model makes the same mistake as a human can make when looking at some cars for the first time that seemed to be emergency vehicles but interpreted as non emergency vehicles."
},
{
"code": null,
"e": 5703,
"s": 5482,
"text": "Another useful tool, kind of, is to use something called a confusion matrix which basically shows you for every actual type of emergency and non emergency vehicle prediction , how many times was it predicted to be that ."
},
{
"code": null,
"e": 5756,
"s": 5703,
"text": "`interp.plot_confusion_matrix(figsize=(8,8), dpi=60)"
},
{
"code": null,
"e": 5968,
"s": 5756,
"text": "17 times our model predicted emergency vehicles as non emergency vehicles , while 4 times it predicted non emergency vehicles as emergency vehicles. Confused uh? after all we are dealing with a confusion matrix!"
},
{
"code": null,
"e": 6037,
"s": 5968,
"text": "A frozen layer is a layer that is not trained i.e it is not updated."
},
{
"code": null,
"e": 6220,
"s": 6037,
"text": "So far anything we have done has not changed the pre-trained model weights .All we have done is we added some new layers on top and learned how to mix and match pre-trained features."
},
{
"code": null,
"e": 6408,
"s": 6220,
"text": "But we want the model to learn features specific to our images .In order to do so we would unfreeze some of the layer to update the weights of the entire network according to our images ."
},
{
"code": null,
"e": 6667,
"s": 6408,
"text": "Layer one which detects edge and gradient and layer two which detects curves and corners don’t need much learning, they don’t need to change much. while the much later layers need to change. This is universally true when training for other image recognition."
},
{
"code": null,
"e": 7093,
"s": 6667,
"text": "The earlier layers have more general-purpose features. Therefore we would expect them to need less fine-tuning for new datasets. For this reason we will use different learning rates for different layers: the first few layers will be at 1e-4 for basic geometric features and layers closest to the pixels,and 1e-2 as before for the layers we add on top (fully connected layers). We refer to this as differential learning rates."
},
{
"code": null,
"e": 7110,
"s": 7093,
"text": "learn.unfreeze()"
},
{
"code": null,
"e": 7194,
"s": 7110,
"text": "We would again run a fit-one-cycle on our unfreeze network and see how it goes now."
},
{
"code": null,
"e": 7217,
"s": 7194,
"text": "learn.fit_one_cycle(3)"
},
{
"code": null,
"e": 7709,
"s": 7217,
"text": "The most important hyper-parameter for tuning our model is learning rate.It helps us in finding the optimal solution by adjusting the weights of our network with respect the loss gradient.The lower the value, the slower we travel along the downward slope. While this might be a good idea (using a low learning rate) in terms of making sure that we do not miss any local minima, it could also mean that we’ll be taking a long time to converge — especially if we get stuck on a plateau region."
},
{
"code": null,
"e": 7778,
"s": 7709,
"text": "Here we can see the various effects of learning rate on convergence."
},
{
"code": null,
"e": 7897,
"s": 7778,
"text": "Hence Picking the right learning rate is important, rather than giving it a random guess or multiple trial-and-errors."
},
{
"code": null,
"e": 8112,
"s": 7897,
"text": "To do this we would be using a function called lr_find().This function is an implementation of Leslie Smith’s paper( Cyclical Learning Rates for Training Neural Networks.) on tuning neural network hyper-parameters."
},
{
"code": null,
"e": 8128,
"s": 8112,
"text": "learn.lr_find()"
},
{
"code": null,
"e": 8200,
"s": 8128,
"text": "To understand it better we would plot it with help of another function."
},
{
"code": null,
"e": 8222,
"s": 8200,
"text": "learn.recorder.plot()"
},
{
"code": null,
"e": 8341,
"s": 8222,
"text": "The learning rate is plotted against the losses.With the help of this graph we can pick our learning rate very easily."
},
{
"code": null,
"e": 8537,
"s": 8341,
"text": "As we can see the loss start increasing after 1e-03 so we would pick a number before that also for updating weights of initial layers we would be choosing a lower learning rate .1e-04 seems good."
},
{
"code": null,
"e": 8649,
"s": 8537,
"text": "With the chosen learning rate we will again train our unfreeze model but this time a bit longer with 10 epochs."
},
{
"code": null,
"e": 8749,
"s": 8649,
"text": "We would use accuracy as another parameter often called metric to evaluate how our model is doing ."
},
{
"code": null,
"e": 8752,
"s": 8749,
"text": "or"
},
{
"code": null,
"e": 8830,
"s": 8752,
"text": "Before going further let us also get an intuition about fit_one_cycle method."
},
{
"code": null,
"e": 9151,
"s": 8830,
"text": "In this method we do a cycle with two steps of equal lengths, one going from a lower learning rate to a higher one than go back to the minimum.The maximum should be the value picked with the Learning Rate Finder, and the lower one can be ten times lower. -to read a bit more about fit_one_cycle ,do check out this blog ."
},
{
"code": null,
"e": 9188,
"s": 9151,
"text": "Now Lets see how our model is doing?"
},
{
"code": null,
"e": 9236,
"s": 9188,
"text": "learn.fit_one_cycle(10,max_lr=slice(1e-4,1e-3))"
},
{
"code": null,
"e": 9530,
"s": 9236,
"text": "Our model is doing good enough ,there is no under-fitting as our model had this problem earlier and no over-fitting also (Over fitting would mean that the training loss is much lower than the validation loss), as our validation loss is just approximately 0.02 times greater then training loss."
},
{
"code": null,
"e": 9574,
"s": 9530,
"text": "We have reached an accuracy of 96.96%~ 97%."
},
{
"code": null,
"e": 9744,
"s": 9574,
"text": "Since we have updated our model’s weights according to our vehicle classifying problem we will freeze the layers of our model and save it with a name car_classification."
},
{
"code": null,
"e": 9791,
"s": 9744,
"text": "learn.freeze()learn.save('car_classification')"
},
{
"code": null,
"e": 10031,
"s": 9791,
"text": "We were able to reach an accuracy of approximately 97% , while we can experiment more with our model in terms of increasing number of epochs , finding more optimal learning rates using plot function, more data augmentation techniques, etc."
},
{
"code": null,
"e": 10072,
"s": 10031,
"text": "[1]:https://arxiv.org/pdf/1803.09820.pdf"
},
{
"code": null,
"e": 10125,
"s": 10072,
"text": "[2]:https://sgugger.github.io/the-1cycle-policy.html"
},
{
"code": null,
"e": 10166,
"s": 10125,
"text": "[3]:https://arxiv.org/pdf/1506.01186.pdf"
},
{
"code": null,
"e": 10207,
"s": 10166,
"text": "[4]:Lesson 1 Notebook, fast.ai Part 1 V2"
},
{
"code": null,
"e": 10232,
"s": 10207,
"text": "That’s all for today .💃🏻"
}
] |
Calculate depth of a full Binary tree from Preorder - GeeksforGeeks
|
20 May, 2021
Given preorder of a binary tree, calculate its depth(or height) [starting from depth 0]. The preorder is given as a string with two possible characters.
‘l’ denotes the leaf‘n’ denotes internal node
‘l’ denotes the leaf
‘n’ denotes internal node
The given tree can be seen as a full binary tree where every node has 0 or two children. The two children of a node can ‘n’ or ‘l’ or mix of both.Examples :
Input : nlnll
Output : 2
Explanation :
Input : nlnnlll
Output : 3
Preorder of the binary tree is given so traverse Also, we would be given a string of char (formed of ‘n’ and ‘l’), so there is no need to implement tree also.The recursion function would be: 1) Base Case: return 0; when tree[i] = ‘l’ or i >= strlen(tree) 2) find_depth( tree[i++] ) //left subtree 3) find_depth( tree[i++] ) //right subtreeWhere i is the index of the string tree.
C++
Java
Python3
C#
Javascript
// C++ program to find height of full binary tree// using preorder#include <bits/stdc++.h>using namespace std; // function to return max of left subtree height// or right subtree heightint findDepthRec(char tree[], int n, int& index){ if (index >= n || tree[index] == 'l') return 0; // calc height of left subtree (In preorder // left subtree is processed before right) index++; int left = findDepthRec(tree, n, index); // calc height of right subtree index++; int right = findDepthRec(tree, n, index); return max(left, right) + 1;} // Wrapper over findDepthRec()int findDepth(char tree[], int n){ int index = 0; findDepthRec(tree, n, index);} // Driver programint main(){ // Your C++ Code char tree[] = "nlnnlll"; int n = strlen(tree); cout << findDepth(tree, n) << endl; return 0;}
// Java program to find height// of full binary tree using// preorderimport java .io.*; class GFG{ // function to return max // of left subtree height // or right subtree height static int findDepthRec(String tree, int n, int index) { if (index >= n || tree.charAt(index) == 'l') return 0; // calc height of left subtree // (In preorder left subtree // is processed before right) index++; int left = findDepthRec(tree, n, index); // calc height of // right subtree index++; int right = findDepthRec(tree, n, index); return Math.max(left, right) + 1; } // Wrapper over findDepthRec() static int findDepth(String tree, int n) { int index = 0; return (findDepthRec(tree, n, index)); } // Driver Code static public void main(String[] args) { String tree = "nlnnlll"; int n = tree.length(); System.out.println(findDepth(tree, n)); }} // This code is contributed// by anuj_67.
#Python program to find height of full binary tree# using preorder # function to return max of left subtree height# or right subtree heightdef findDepthRec(tree, n, index) : if (index[0] >= n or tree[index[0]] == 'l'): return 0 # calc height of left subtree (In preorder # left subtree is processed before right) index[0] += 1 left = findDepthRec(tree, n, index) # calc height of right subtree index[0] += 1 right = findDepthRec(tree, n, index) return (max(left, right) + 1) # Wrapper over findDepthRec()def findDepth(tree, n) : index = [0] return findDepthRec(tree, n, index) # Driver program to test above functionsif __name__ == '__main__': tree= "nlnnlll" n = len(tree) print(findDepth(tree, n)) # This code is contributed by SHUBHAMSINGH10
// C# program to find height of// full binary tree using preorderusing System; class GFG { // function to return max of left subtree // height or right subtree height static int findDepthRec(char[] tree, int n, int index) { if (index >= n || tree[index] == 'l') return 0; // calc height of left subtree (In preorder // left subtree is processed before right) index++; int left = findDepthRec(tree, n, index); // calc height of right subtree index++; int right = findDepthRec(tree, n, index); return Math.Max(left, right) + 1; } // Wrapper over findDepthRec() static int findDepth(char[] tree, int n) { int index = 0; return (findDepthRec(tree, n, index)); } // Driver program static public void Main() { char[] tree = "nlnnlll".ToCharArray(); int n = tree.Length; Console.WriteLine(findDepth(tree, n)); }} // This code is contributed by vt_m.
<script> // Javascript program to find height of // full binary tree using preorder // function to return max of left subtree // height or right subtree height function findDepthRec(tree, n, index) { if (index >= n || tree[index] == 'l') return 0; // calc height of left subtree (In preorder // left subtree is processed before right) index++; let left = findDepthRec(tree, n, index); // calc height of right subtree index++; let right = findDepthRec(tree, n, index); return Math.max(left, right) + 1; } // Wrapper over findDepthRec() function findDepth(tree, n) { let index = 0; return (findDepthRec(tree, n, index)); } let tree = "nlnnlll".split(''); let n = tree.length; document.write(findDepth(tree, n)); </script>
Output:
3
Time Complexity: O(N)
Auxiliary Space: O(1)
YouTube<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=RCfG0Bw75rk" 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 Shubham Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to 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.
vt_m
SHUBHAMSINGH10
rohitsingh07052
divyeshrabadiya07
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Tree Traversals (Inorder, Preorder and Postorder)
Binary Tree | Set 1 (Introduction)
Level Order Binary Tree Traversal
AVL Tree | Set 1 (Insertion)
Inorder Tree Traversal without Recursion
Binary Tree | Set 3 (Types of Binary Tree)
Write a Program to Find the Maximum Depth or Height of a Tree
Binary Tree | Set 2 (Properties)
Decision Tree
A program to check if a binary tree is BST or not
|
[
{
"code": null,
"e": 35848,
"s": 35820,
"text": "\n20 May, 2021"
},
{
"code": null,
"e": 36002,
"s": 35848,
"text": "Given preorder of a binary tree, calculate its depth(or height) [starting from depth 0]. The preorder is given as a string with two possible characters. "
},
{
"code": null,
"e": 36048,
"s": 36002,
"text": "‘l’ denotes the leaf‘n’ denotes internal node"
},
{
"code": null,
"e": 36069,
"s": 36048,
"text": "‘l’ denotes the leaf"
},
{
"code": null,
"e": 36095,
"s": 36069,
"text": "‘n’ denotes internal node"
},
{
"code": null,
"e": 36254,
"s": 36095,
"text": "The given tree can be seen as a full binary tree where every node has 0 or two children. The two children of a node can ‘n’ or ‘l’ or mix of both.Examples : "
},
{
"code": null,
"e": 36294,
"s": 36254,
"text": "Input : nlnll\nOutput : 2\nExplanation :"
},
{
"code": null,
"e": 36322,
"s": 36294,
"text": "Input : nlnnlll\nOutput : 3"
},
{
"code": null,
"e": 36705,
"s": 36324,
"text": "Preorder of the binary tree is given so traverse Also, we would be given a string of char (formed of ‘n’ and ‘l’), so there is no need to implement tree also.The recursion function would be: 1) Base Case: return 0; when tree[i] = ‘l’ or i >= strlen(tree) 2) find_depth( tree[i++] ) //left subtree 3) find_depth( tree[i++] ) //right subtreeWhere i is the index of the string tree. "
},
{
"code": null,
"e": 36709,
"s": 36705,
"text": "C++"
},
{
"code": null,
"e": 36714,
"s": 36709,
"text": "Java"
},
{
"code": null,
"e": 36722,
"s": 36714,
"text": "Python3"
},
{
"code": null,
"e": 36725,
"s": 36722,
"text": "C#"
},
{
"code": null,
"e": 36736,
"s": 36725,
"text": "Javascript"
},
{
"code": "// C++ program to find height of full binary tree// using preorder#include <bits/stdc++.h>using namespace std; // function to return max of left subtree height// or right subtree heightint findDepthRec(char tree[], int n, int& index){ if (index >= n || tree[index] == 'l') return 0; // calc height of left subtree (In preorder // left subtree is processed before right) index++; int left = findDepthRec(tree, n, index); // calc height of right subtree index++; int right = findDepthRec(tree, n, index); return max(left, right) + 1;} // Wrapper over findDepthRec()int findDepth(char tree[], int n){ int index = 0; findDepthRec(tree, n, index);} // Driver programint main(){ // Your C++ Code char tree[] = \"nlnnlll\"; int n = strlen(tree); cout << findDepth(tree, n) << endl; return 0;}",
"e": 37580,
"s": 36736,
"text": null
},
{
"code": "// Java program to find height// of full binary tree using// preorderimport java .io.*; class GFG{ // function to return max // of left subtree height // or right subtree height static int findDepthRec(String tree, int n, int index) { if (index >= n || tree.charAt(index) == 'l') return 0; // calc height of left subtree // (In preorder left subtree // is processed before right) index++; int left = findDepthRec(tree, n, index); // calc height of // right subtree index++; int right = findDepthRec(tree, n, index); return Math.max(left, right) + 1; } // Wrapper over findDepthRec() static int findDepth(String tree, int n) { int index = 0; return (findDepthRec(tree, n, index)); } // Driver Code static public void main(String[] args) { String tree = \"nlnnlll\"; int n = tree.length(); System.out.println(findDepth(tree, n)); }} // This code is contributed// by anuj_67.",
"e": 38742,
"s": 37580,
"text": null
},
{
"code": "#Python program to find height of full binary tree# using preorder # function to return max of left subtree height# or right subtree heightdef findDepthRec(tree, n, index) : if (index[0] >= n or tree[index[0]] == 'l'): return 0 # calc height of left subtree (In preorder # left subtree is processed before right) index[0] += 1 left = findDepthRec(tree, n, index) # calc height of right subtree index[0] += 1 right = findDepthRec(tree, n, index) return (max(left, right) + 1) # Wrapper over findDepthRec()def findDepth(tree, n) : index = [0] return findDepthRec(tree, n, index) # Driver program to test above functionsif __name__ == '__main__': tree= \"nlnnlll\" n = len(tree) print(findDepth(tree, n)) # This code is contributed by SHUBHAMSINGH10",
"e": 39554,
"s": 38742,
"text": null
},
{
"code": "// C# program to find height of// full binary tree using preorderusing System; class GFG { // function to return max of left subtree // height or right subtree height static int findDepthRec(char[] tree, int n, int index) { if (index >= n || tree[index] == 'l') return 0; // calc height of left subtree (In preorder // left subtree is processed before right) index++; int left = findDepthRec(tree, n, index); // calc height of right subtree index++; int right = findDepthRec(tree, n, index); return Math.Max(left, right) + 1; } // Wrapper over findDepthRec() static int findDepth(char[] tree, int n) { int index = 0; return (findDepthRec(tree, n, index)); } // Driver program static public void Main() { char[] tree = \"nlnnlll\".ToCharArray(); int n = tree.Length; Console.WriteLine(findDepth(tree, n)); }} // This code is contributed by vt_m.",
"e": 40551,
"s": 39554,
"text": null
},
{
"code": "<script> // Javascript program to find height of // full binary tree using preorder // function to return max of left subtree // height or right subtree height function findDepthRec(tree, n, index) { if (index >= n || tree[index] == 'l') return 0; // calc height of left subtree (In preorder // left subtree is processed before right) index++; let left = findDepthRec(tree, n, index); // calc height of right subtree index++; let right = findDepthRec(tree, n, index); return Math.max(left, right) + 1; } // Wrapper over findDepthRec() function findDepth(tree, n) { let index = 0; return (findDepthRec(tree, n, index)); } let tree = \"nlnnlll\".split(''); let n = tree.length; document.write(findDepth(tree, n)); </script>",
"e": 41423,
"s": 40551,
"text": null
},
{
"code": null,
"e": 41432,
"s": 41423,
"text": "Output: "
},
{
"code": null,
"e": 41434,
"s": 41432,
"text": "3"
},
{
"code": null,
"e": 41456,
"s": 41434,
"text": "Time Complexity: O(N)"
},
{
"code": null,
"e": 41478,
"s": 41456,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 41770,
"s": 41478,
"text": "YouTube<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=RCfG0Bw75rk\" 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": 42191,
"s": 41770,
"text": "This article is contributed by Shubham Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to 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. "
},
{
"code": null,
"e": 42196,
"s": 42191,
"text": "vt_m"
},
{
"code": null,
"e": 42211,
"s": 42196,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 42227,
"s": 42211,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 42245,
"s": 42227,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 42250,
"s": 42245,
"text": "Tree"
},
{
"code": null,
"e": 42255,
"s": 42250,
"text": "Tree"
},
{
"code": null,
"e": 42353,
"s": 42255,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 42362,
"s": 42353,
"text": "Comments"
},
{
"code": null,
"e": 42375,
"s": 42362,
"text": "Old Comments"
},
{
"code": null,
"e": 42425,
"s": 42375,
"text": "Tree Traversals (Inorder, Preorder and Postorder)"
},
{
"code": null,
"e": 42460,
"s": 42425,
"text": "Binary Tree | Set 1 (Introduction)"
},
{
"code": null,
"e": 42494,
"s": 42460,
"text": "Level Order Binary Tree Traversal"
},
{
"code": null,
"e": 42523,
"s": 42494,
"text": "AVL Tree | Set 1 (Insertion)"
},
{
"code": null,
"e": 42564,
"s": 42523,
"text": "Inorder Tree Traversal without Recursion"
},
{
"code": null,
"e": 42607,
"s": 42564,
"text": "Binary Tree | Set 3 (Types of Binary Tree)"
},
{
"code": null,
"e": 42669,
"s": 42607,
"text": "Write a Program to Find the Maximum Depth or Height of a Tree"
},
{
"code": null,
"e": 42702,
"s": 42669,
"text": "Binary Tree | Set 2 (Properties)"
},
{
"code": null,
"e": 42716,
"s": 42702,
"text": "Decision Tree"
}
] |
Python unittest - How to nicely mock a web crawler function? - GeeksforGeeks
|
01 Apr, 2021
Prerequisite: Python | Unit Test Objects Patching
Unit Testing is the first level of software testing where the smallest testable parts of the software are tested. This is used to validate that each unit of the software performs as designed. The Unittest framework is python’s xUnit style framework. Before deep-diving into “How to nicely mock a web crawler” let us understand some fundamentals about that.
Mock is a submodule (class) of unittest module. The mock module allows us to replace particular portions of the whole system that we are testing with mock objects.
Import mock class from unittest.mock module.
Create an instance of the Mock class.
Set mock object’s method.
Print result
Let’s understand mock by mimicking another python class. In this example, we will see methods that were called on our mocked class, also what parameters were passed to them.
Python3
# importing mock from unittest.mock modulefrom unittest.mock import Mock # defining instance of our mockour_mock = Mock() # defining mock object’s __str__ methodour_mock.__str__ = Mock(return_value='GeeksforGeeks Mocking Example') # executing str function for outputprint(str(our_mock))
Output:
GeeksforGeeks Mocking Example
Picked
Python-ctype
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n01 Apr, 2021"
},
{
"code": null,
"e": 24342,
"s": 24292,
"text": "Prerequisite: Python | Unit Test Objects Patching"
},
{
"code": null,
"e": 24699,
"s": 24342,
"text": "Unit Testing is the first level of software testing where the smallest testable parts of the software are tested. This is used to validate that each unit of the software performs as designed. The Unittest framework is python’s xUnit style framework. Before deep-diving into “How to nicely mock a web crawler” let us understand some fundamentals about that."
},
{
"code": null,
"e": 24863,
"s": 24699,
"text": "Mock is a submodule (class) of unittest module. The mock module allows us to replace particular portions of the whole system that we are testing with mock objects."
},
{
"code": null,
"e": 24908,
"s": 24863,
"text": "Import mock class from unittest.mock module."
},
{
"code": null,
"e": 24946,
"s": 24908,
"text": "Create an instance of the Mock class."
},
{
"code": null,
"e": 24972,
"s": 24946,
"text": "Set mock object’s method."
},
{
"code": null,
"e": 24985,
"s": 24972,
"text": "Print result"
},
{
"code": null,
"e": 25159,
"s": 24985,
"text": "Let’s understand mock by mimicking another python class. In this example, we will see methods that were called on our mocked class, also what parameters were passed to them."
},
{
"code": null,
"e": 25167,
"s": 25159,
"text": "Python3"
},
{
"code": "# importing mock from unittest.mock modulefrom unittest.mock import Mock # defining instance of our mockour_mock = Mock() # defining mock object’s __str__ methodour_mock.__str__ = Mock(return_value='GeeksforGeeks Mocking Example') # executing str function for outputprint(str(our_mock))",
"e": 25457,
"s": 25167,
"text": null
},
{
"code": null,
"e": 25465,
"s": 25457,
"text": "Output:"
},
{
"code": null,
"e": 25495,
"s": 25465,
"text": "GeeksforGeeks Mocking Example"
},
{
"code": null,
"e": 25502,
"s": 25495,
"text": "Picked"
},
{
"code": null,
"e": 25515,
"s": 25502,
"text": "Python-ctype"
},
{
"code": null,
"e": 25530,
"s": 25515,
"text": "python-modules"
},
{
"code": null,
"e": 25537,
"s": 25530,
"text": "Python"
},
{
"code": null,
"e": 25635,
"s": 25537,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25667,
"s": 25635,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25723,
"s": 25667,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 25765,
"s": 25723,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 25807,
"s": 25765,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 25829,
"s": 25807,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 25868,
"s": 25829,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 25899,
"s": 25868,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 25954,
"s": 25899,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 25983,
"s": 25954,
"text": "Create a directory in Python"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.