title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Count number of sub-sequences with GCD 1 - GeeksforGeeks | 25 Nov, 2021
Given an array of N numbers, the task is to count the number of subsequences that have gcd equal to 1.
Examples:
Input: a[] = {3, 4, 8, 16}
Output: 7
The subsequences are:
{3, 4}, {3, 8}, {3, 16}, {3, 4, 8},
{3, 4, 16}, {3, 8, 16}, {3, 4, 8, 16}
Input: a[] = {1, 2, 4}
Output: 4
A simple solution is to generate all subsequences or subsets. For every subsequence, check if its GCD is 1 or not. If 1, increment the result.
When we have values in array (say all smaller than 1000), we can optimize the above solution as we know that number of possible GCDs would be small. We modify the recursive subset generation algorithm where consider two cases for every element, we either include or exclude it. We keep track of current GCD and if we have already counted for this GCD, we return the count. So when we are considering a subset, some GCDs would appear again and again. Therefore the problem can be solved using Dynamic Programming. Given below are the steps to solve the above problem:
Start from every index and call the recursive function by taking the index element.
In the recursive function, we iterate till we reach N.
The two recursive calls will be based on either we take the index element or not.
The base case will be to return 1 if we have reached the end and the gcd till now is 1.
Two recursive calls will be func(ind+1, gcd(a[i], prevgcd)) and func(ind+1, prevgcd)
The overlapping subproblems can be avoided by using memoization technique.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find the number// of subsequences with gcd 1#include <bits/stdc++.h>using namespace std;#define MAX 1000int gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // Recursive function to calculate the number// of subsequences with gcd 1 starting with// particular indexint func(int ind, int g, int dp[][MAX], int n, int a[]){ // Base case if (ind == n) { if (g == 1) return 1; else return 0; } // If already visited if (dp[ind][g] != -1) return dp[ind][g]; // Either we take or we do not int ans = func(ind + 1, g, dp, n, a) + func(ind + 1, gcd(a[ind], g), dp, n, a); // Return the answer return dp[ind][g] = ans;} // Function to return the number of subsequencesint countSubsequences(int a[], int n){ // Hash table to memoize int dp[n][MAX]; memset(dp, -1, sizeof dp); // Count the number of subsequences int count = 0; // Count for every subsequence for (int i = 0; i < n; i++) count += func(i + 1, a[i], dp, n, a); return count;} // Driver Codeint main(){ int a[] = { 3, 4, 8, 16 }; int n = sizeof(a) / sizeof(a[0]); cout << countSubsequences(a, n); return 0;}
// Java program to find the number// of subsequences with gcd 1class GFG{ static final int MAX = 1000;static int gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // Recursive function to calculate the number// of subsequences with gcd 1 starting with// particular indexstatic int func(int ind, int g, int dp[][], int n, int a[]){ // Base case if (ind == n) { if (g == 1) return 1; else return 0; } // If already visited if (dp[ind][g] != -1) return dp[ind][g]; // Either we take or we do not int ans = func(ind + 1, g, dp, n, a) + func(ind + 1, gcd(a[ind], g), dp, n, a); // Return the answer return dp[ind][g] = ans;} // Function to return the// number of subsequencesstatic int countSubsequences(int a[], int n){ // Hash table to memoize int dp[][] = new int[n][MAX]; for(int i = 0; i < n; i++) for(int j = 0; j < MAX; j++) dp[i][j] = -1; // Count the number of subsequences int count = 0; // Count for every subsequence for (int i = 0; i < n; i++) count += func(i + 1, a[i], dp, n, a); return count;} // Driver Codepublic static void main(String args[]){ int a[] = { 3, 4, 8, 16 }; int n = a.length; System.out.println(countSubsequences(a, n));}} // This code is contributed by Arnab Kundu
# Python3 program to find the number# of subsequences with gcd 1 MAX = 1000 def gcd(a, b): if (a == 0): return b return gcd(b % a, a) # Recursive function to calculate the# number of subsequences with gcd 1# starting with particular indexdef func(ind, g, dp, n, a): # Base case if (ind == n): if (g == 1): return 1 else: return 0 # If already visited if (dp[ind][g] != -1): return dp[ind][g] # Either we take or we do not ans = (func(ind + 1, g, dp, n, a) + func(ind + 1, gcd(a[ind], g), dp, n, a)) # Return the answer dp[ind][g] = ans return dp[ind][g] # Function to return the number# of subsequencesdef countSubsequences(a, n): # Hash table to memoize dp = [[-1 for i in range(MAX)] for i in range(n)] # Count the number of subsequences count = 0 # Count for every subsequence for i in range(n): count += func(i + 1, a[i], dp, n, a) return count # Driver Codea = [3, 4, 8, 16 ]n = len(a)print(countSubsequences(a, n)) # This code is contributed by mohit kumar 29
// C# program to find the number// of subsequences with gcd 1using System; class GFG{ static int gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // Recursive function to calculate the number// of subsequences with gcd 1 starting with// particular indexstatic int func(int ind, int g, int [][] dp, int n, int [] a){ // Base case if (ind == n) { if (g == 1) return 1; else return 0; } // If already visited if (dp[ind][g] != -1) return dp[ind][g]; // Either we take or we do not int ans = func(ind + 1, g, dp, n, a) + func(ind + 1, gcd(a[ind], g), dp, n, a); // Return the answer return dp[ind][g] = ans;} // Function to return the// number of subsequencesstatic int countSubsequences(int [] a, int n){ // Hash table to memoize int [][] dp = new int[n][]; for(int i = 0; i < n; i++) for(int j = 0; j < 1000; j++) dp[i][j] = -1; // Count the number of subsequences int count = 0; // Count for every subsequence for (int i = 0; i < n; i++) count += func(i + 1, a[i], dp, n, a); return count;} // Driver Codepublic static void Main(){ int [] a = { 3, 4, 8, 16 }; int n = 4; int x = countSubsequences(a, n); Console.Write(x);}} // This code is contributed by// mohit kumar 29
<?php// PHP program to find the number// of subsequences with gcd 1 $GLOBALS['MAX'] = 1000; function gcd($a, $b){ if ($a == 0) return $b; return gcd($b % $a, $a);} // Recursive function to calculate the// number of subsequences with gcd 1// starting with particular indexfunction func($ind, $g, $dp, $n, $a){ // Base case if ($ind == $n) { if ($g == 1) return 1; else return 0; } // If already visited if ($dp[$ind][$g] != -1) return $dp[$ind][$g]; // Either we take or we do not $ans = func($ind + 1, $g, $dp, $n, $a) + func($ind + 1, gcd($a[$ind], $g), $dp, $n, $a); // Return the answer $dp[$ind][$g] = $ans; return $dp[$ind][$g] ;} // Function to return the number// of subsequencesfunction countSubsequences($a, $n){ // Hash table to memoize $dp = array(array()) ; for($i = 0 ; $i < $n ; $i++) for($j = 0; $j < $GLOBALS['MAX']; $j++) $dp[$i][$j] = -1 ; // Count the number of subsequences $count = 0; // Count for every subsequence for ($i = 0; $i < $n; $i++) $count += func($i + 1, $a[$i], $dp, $n, $a); return $count;} // Driver Code$a = array(3, 4, 8, 16);$n = sizeof($a) ; echo countSubsequences($a, $n); // This code is contributed by Ryuga?>
<script> // JavaScript program to find the number// of subsequences with gcd 1 var MAX = 1000; function gcd(a , b) { if (a == 0) return b; return gcd(b % a, a); } // Recursive function to calculate the number // of subsequences with gcd 1 starting with // particular index function func(ind , g , dp , n , a) { // Base case if (ind == n) { if (g == 1) return 1; else return 0; } // If already visited if (dp[ind][g] != -1) return dp[ind][g]; // Either we take or we do not var ans = func(ind + 1, g, dp, n, a) + func(ind + 1, gcd(a[ind], g), dp, n, a); // Return the answer return dp[ind][g] = ans; } // Function to return the // number of subsequences function countSubsequences(a , n) { // Hash table to memoize var dp = Array(n).fill().map(()=>Array(MAX).fill(0)); for (i = 0; i < n; i++) for (j = 0; j < MAX; j++) dp[i][j] = -1; // Count the number of subsequences var count = 0; // Count for every subsequence for (i = 0; i < n; i++) count += func(i + 1, a[i], dp, n, a); return count; } // Driver Code var a = [ 3, 4, 8, 16 ]; var n = a.length; document.write(countSubsequences(a, n)); // This code contributed by Rajput-Ji </script>
7
Alternate Solution: Count number of subsets of a set with GCD equal to a given number
Dynamic programming approach to this problem without memoization:
Basically, the approach will be making a 2d matrix in which i coordinate will be the position of elements of the given array and j coordinate will be numbers from 0 to 100 ie. gcd can vary from 0 to 100 if array elements are not enough large. we will iterate on given array and the 2d matrix will store information that till ith position that how many subsequences are there having gcd vary from 1 to 100. later on, we will add dp[i][1] to get all subsequence having gcd as 1.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for above approach#include <bits/stdc++.h>using namespace std; // This function calculates// gcd of two numberint gcd(int a, int b){ if (b == 0) return a; return gcd(b, a % b);} // This function will return total// subsequencesint countSubsequences(int arr[], int n){ // Declare a dp 2d array long long int dp[n][101] = {0}; // Iterate i from 0 to n - 1 for(int i = 0; i < n; i++) { dp[i][arr[i]] = 1; // Iterate j from i - 1 to 0 for(int j = i - 1; j >= 0; j--) { if(arr[j] < arr[i]) { // Iterate k from 0 to 100 for(int k = 0; k <= 100; k++) { // Find gcd of two number int GCD = gcd(arr[i], k); // dp[i][GCD] is summation of // dp[i][GCD] and dp[j][k] dp[i][GCD] = dp[i][GCD] + dp[j][k]; } } } } // Add all elements of dp[i][1] long long int sum = 0; for(int i = 0; i < n; i++) { sum=(sum + dp[i][1]); } // Return sum return sum;} // Driver codeint main(){ int a[] = { 3, 4, 8, 16 }; int n = sizeof(a) / sizeof(a[0]); // Function Call cout << countSubsequences(a, n); return 0;}
// Java program for the// above approachimport java.util.*; class GFG{ // This function calculates// gcd of two numberstatic int gcd(int a, int b){ if (b == 0) return a; return gcd(b, a % b);} // This function will return total// subsequencesstatic long countSubsequences(int arr[], int n){ // Declare a dp 2d array long dp[][] = new long[n][101]; for(int i = 0; i < n; i++) { for(int j = 0; j < 101; j++) { dp[i][j] = 0; } } // Iterate i from 0 to n - 1 for(int i = 0; i < n; i++) { dp[i][arr[i]] = 1; // Iterate j from i - 1 to 0 for(int j = i - 1; j >= 0; j--) { if (arr[j] < arr[i]) { // Iterate k from 0 to 100 for(int k = 0; k <= 100; k++) { // Find gcd of two number int GCD = gcd(arr[i], k); // dp[i][GCD] is summation of // dp[i][GCD] and dp[j][k] dp[i][GCD] = dp[i][GCD] + dp[j][k]; } } } } // Add all elements of dp[i][1] long sum = 0; for(int i = 0; i < n; i++) { sum = (sum + dp[i][1]); } // Return sum return sum;} // Driver codepublic static void main(String args[]){ int a[] = { 3, 4, 8, 16 }; int n = a.length; // Function Call System.out.println(countSubsequences(a, n));}} // This code is contributed by bolliranadheer
# Python3 program for the# above approach # This function calculates# gcd of two numberdef gcd(a, b): if (b == 0): return a; return gcd(b, a % b); # This function will return total# subsequencesdef countSubsequences(arr, n): # Declare a dp 2d array dp = [[0 for i in range(101)] for j in range(n)] # Iterate i from 0 to n - 1 for i in range(n): dp[i][arr[i]] = 1; # Iterate j from i - 1 to 0 for j in range(i - 1, -1, -1): if (arr[j] < arr[i]): # Iterate k from 0 to 100 for k in range(101): # Find gcd of two number GCD = gcd(arr[i], k); # dp[i][GCD] is summation of # dp[i][GCD] and dp[j][k] dp[i][GCD] = dp[i][GCD] + dp[j][k]; # Add all elements of dp[i][1] sum = 0; for i in range(n): sum = (sum + dp[i][1]); # Return sum return sum; # Driver codeif __name__=='__main__': a = [ 3, 4, 8, 16 ] n = len(a) # Function Call print(countSubsequences(a,n)) # This code is contributed by Pratham76
// C# program for the above approachusing System;using System.Collections;using System.Collections.Generic; class GFG{ // This function calculates// gcd of two numberstatic int gcd(int a, int b){ if (b == 0) return a; return gcd(b, a % b);} // This function will return total// subsequencesstatic long countSubsequences(int []arr, int n){ // Declare a dp 2d array long [,]dp = new long[n, 101]; for(int i = 0; i < n; i++) { for(int j = 0; j < 101; j++) { dp[i, j] = 0; } } // Iterate i from 0 to n - 1 for(int i = 0; i < n; i++) { dp[i, arr[i]] = 1; // Iterate j from i - 1 to 0 for(int j = i - 1; j >= 0; j--) { if (arr[j] < arr[i]) { // Iterate k from 0 to 100 for(int k = 0; k <= 100; k++) { // Find gcd of two number int GCD = gcd(arr[i], k); // dp[i,GCD] is summation of // dp[i,GCD] and dp[j,k] dp[i, GCD] = dp[i, GCD] + dp[j, k]; } } } } // Add all elements of dp[i,1] long sum = 0; for(int i = 0; i < n; i++) { sum = (sum + dp[i, 1]); } // Return sum return sum;} // Driver codepublic static void Main(string []args){ int []a = { 3, 4, 8, 16 }; int n = a.Length; // Function Call Console.WriteLine(countSubsequences(a, n));}} // This code is contributed by rutvik_56
<script>// javascript program for the// above approach // This function calculates // gcd of two number function gcd(a , b) { if (b == 0) return a; return gcd(b, a % b); } // This function will return total // subsequences function countSubsequences(arr , n) { // Declare a dp 2d array var dp = Array(n).fill().map(()=>Array(101).fill(0)); for (i = 0; i < n; i++) { for (j = 0; j < 101; j++) { dp[i][j] = 0; } } // Iterate i from 0 to n - 1 for (i = 0; i < n; i++) { dp[i][arr[i]] = 1; // Iterate j from i - 1 to 0 for (j = i - 1; j >= 0; j--) { if (arr[j] < arr[i]) { // Iterate k from 0 to 100 for (k = 0; k <= 100; k++) { // Find gcd of two number var GCD = gcd(arr[i], k); // dp[i][GCD] is summation of // dp[i][GCD] and dp[j][k] dp[i][GCD] = dp[i][GCD] + dp[j][k]; } } } } // Add all elements of dp[i][1] var sum = 0; for (i = 0; i < n; i++) { sum = (sum + dp[i][1]); } // Return sum return sum; } // Driver code var a = [ 3, 4, 8, 16 ]; var n = a.length; // Function Call document.write(countSubsequences(a, n)); // This code contributed by aashish1995</script>
7
mohit kumar 29
ankthon
andrew1234
mansibhardwaj009
bolliranadheer
rutvik_56
pratham76
Rajput-Ji
aashish1995
rkbhola5
GCD-LCM
subsequence
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count pairs with given sum
Chocolate Distribution Problem
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
Find duplicates in O(n) time and O(1) extra space | Set 1
Find subarray with given sum | Set 1 (Nonnegative Numbers)
Remove duplicates from sorted array
Move all negative numbers to beginning and positive to end with constant extra space
Building Heap from Array | [
{
"code": null,
"e": 26065,
"s": 26037,
"text": "\n25 Nov, 2021"
},
{
"code": null,
"e": 26169,
"s": 26065,
"text": "Given an array of N numbers, the task is to count the number of subsequences that have gcd equal to 1. "
},
{
"code": null,
"e": 26180,
"s": 26169,
"text": "Examples: "
},
{
"code": null,
"e": 26350,
"s": 26180,
"text": "Input: a[] = {3, 4, 8, 16} \nOutput: 7\nThe subsequences are: \n{3, 4}, {3, 8}, {3, 16}, {3, 4, 8},\n{3, 4, 16}, {3, 8, 16}, {3, 4, 8, 16}\n\nInput: a[] = {1, 2, 4}\nOutput: 4"
},
{
"code": null,
"e": 26493,
"s": 26350,
"text": "A simple solution is to generate all subsequences or subsets. For every subsequence, check if its GCD is 1 or not. If 1, increment the result."
},
{
"code": null,
"e": 27061,
"s": 26493,
"text": "When we have values in array (say all smaller than 1000), we can optimize the above solution as we know that number of possible GCDs would be small. We modify the recursive subset generation algorithm where consider two cases for every element, we either include or exclude it. We keep track of current GCD and if we have already counted for this GCD, we return the count. So when we are considering a subset, some GCDs would appear again and again. Therefore the problem can be solved using Dynamic Programming. Given below are the steps to solve the above problem: "
},
{
"code": null,
"e": 27145,
"s": 27061,
"text": "Start from every index and call the recursive function by taking the index element."
},
{
"code": null,
"e": 27200,
"s": 27145,
"text": "In the recursive function, we iterate till we reach N."
},
{
"code": null,
"e": 27282,
"s": 27200,
"text": "The two recursive calls will be based on either we take the index element or not."
},
{
"code": null,
"e": 27370,
"s": 27282,
"text": "The base case will be to return 1 if we have reached the end and the gcd till now is 1."
},
{
"code": null,
"e": 27455,
"s": 27370,
"text": "Two recursive calls will be func(ind+1, gcd(a[i], prevgcd)) and func(ind+1, prevgcd)"
},
{
"code": null,
"e": 27530,
"s": 27455,
"text": "The overlapping subproblems can be avoided by using memoization technique."
},
{
"code": null,
"e": 27583,
"s": 27530,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27587,
"s": 27583,
"text": "C++"
},
{
"code": null,
"e": 27592,
"s": 27587,
"text": "Java"
},
{
"code": null,
"e": 27600,
"s": 27592,
"text": "Python3"
},
{
"code": null,
"e": 27603,
"s": 27600,
"text": "C#"
},
{
"code": null,
"e": 27607,
"s": 27603,
"text": "PHP"
},
{
"code": null,
"e": 27618,
"s": 27607,
"text": "Javascript"
},
{
"code": "// C++ program to find the number// of subsequences with gcd 1#include <bits/stdc++.h>using namespace std;#define MAX 1000int gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // Recursive function to calculate the number// of subsequences with gcd 1 starting with// particular indexint func(int ind, int g, int dp[][MAX], int n, int a[]){ // Base case if (ind == n) { if (g == 1) return 1; else return 0; } // If already visited if (dp[ind][g] != -1) return dp[ind][g]; // Either we take or we do not int ans = func(ind + 1, g, dp, n, a) + func(ind + 1, gcd(a[ind], g), dp, n, a); // Return the answer return dp[ind][g] = ans;} // Function to return the number of subsequencesint countSubsequences(int a[], int n){ // Hash table to memoize int dp[n][MAX]; memset(dp, -1, sizeof dp); // Count the number of subsequences int count = 0; // Count for every subsequence for (int i = 0; i < n; i++) count += func(i + 1, a[i], dp, n, a); return count;} // Driver Codeint main(){ int a[] = { 3, 4, 8, 16 }; int n = sizeof(a) / sizeof(a[0]); cout << countSubsequences(a, n); return 0;}",
"e": 28857,
"s": 27618,
"text": null
},
{
"code": "// Java program to find the number// of subsequences with gcd 1class GFG{ static final int MAX = 1000;static int gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // Recursive function to calculate the number// of subsequences with gcd 1 starting with// particular indexstatic int func(int ind, int g, int dp[][], int n, int a[]){ // Base case if (ind == n) { if (g == 1) return 1; else return 0; } // If already visited if (dp[ind][g] != -1) return dp[ind][g]; // Either we take or we do not int ans = func(ind + 1, g, dp, n, a) + func(ind + 1, gcd(a[ind], g), dp, n, a); // Return the answer return dp[ind][g] = ans;} // Function to return the// number of subsequencesstatic int countSubsequences(int a[], int n){ // Hash table to memoize int dp[][] = new int[n][MAX]; for(int i = 0; i < n; i++) for(int j = 0; j < MAX; j++) dp[i][j] = -1; // Count the number of subsequences int count = 0; // Count for every subsequence for (int i = 0; i < n; i++) count += func(i + 1, a[i], dp, n, a); return count;} // Driver Codepublic static void main(String args[]){ int a[] = { 3, 4, 8, 16 }; int n = a.length; System.out.println(countSubsequences(a, n));}} // This code is contributed by Arnab Kundu",
"e": 30247,
"s": 28857,
"text": null
},
{
"code": "# Python3 program to find the number# of subsequences with gcd 1 MAX = 1000 def gcd(a, b): if (a == 0): return b return gcd(b % a, a) # Recursive function to calculate the# number of subsequences with gcd 1# starting with particular indexdef func(ind, g, dp, n, a): # Base case if (ind == n): if (g == 1): return 1 else: return 0 # If already visited if (dp[ind][g] != -1): return dp[ind][g] # Either we take or we do not ans = (func(ind + 1, g, dp, n, a) + func(ind + 1, gcd(a[ind], g), dp, n, a)) # Return the answer dp[ind][g] = ans return dp[ind][g] # Function to return the number# of subsequencesdef countSubsequences(a, n): # Hash table to memoize dp = [[-1 for i in range(MAX)] for i in range(n)] # Count the number of subsequences count = 0 # Count for every subsequence for i in range(n): count += func(i + 1, a[i], dp, n, a) return count # Driver Codea = [3, 4, 8, 16 ]n = len(a)print(countSubsequences(a, n)) # This code is contributed by mohit kumar 29",
"e": 31383,
"s": 30247,
"text": null
},
{
"code": "// C# program to find the number// of subsequences with gcd 1using System; class GFG{ static int gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // Recursive function to calculate the number// of subsequences with gcd 1 starting with// particular indexstatic int func(int ind, int g, int [][] dp, int n, int [] a){ // Base case if (ind == n) { if (g == 1) return 1; else return 0; } // If already visited if (dp[ind][g] != -1) return dp[ind][g]; // Either we take or we do not int ans = func(ind + 1, g, dp, n, a) + func(ind + 1, gcd(a[ind], g), dp, n, a); // Return the answer return dp[ind][g] = ans;} // Function to return the// number of subsequencesstatic int countSubsequences(int [] a, int n){ // Hash table to memoize int [][] dp = new int[n][]; for(int i = 0; i < n; i++) for(int j = 0; j < 1000; j++) dp[i][j] = -1; // Count the number of subsequences int count = 0; // Count for every subsequence for (int i = 0; i < n; i++) count += func(i + 1, a[i], dp, n, a); return count;} // Driver Codepublic static void Main(){ int [] a = { 3, 4, 8, 16 }; int n = 4; int x = countSubsequences(a, n); Console.Write(x);}} // This code is contributed by// mohit kumar 29",
"e": 32750,
"s": 31383,
"text": null
},
{
"code": "<?php// PHP program to find the number// of subsequences with gcd 1 $GLOBALS['MAX'] = 1000; function gcd($a, $b){ if ($a == 0) return $b; return gcd($b % $a, $a);} // Recursive function to calculate the// number of subsequences with gcd 1// starting with particular indexfunction func($ind, $g, $dp, $n, $a){ // Base case if ($ind == $n) { if ($g == 1) return 1; else return 0; } // If already visited if ($dp[$ind][$g] != -1) return $dp[$ind][$g]; // Either we take or we do not $ans = func($ind + 1, $g, $dp, $n, $a) + func($ind + 1, gcd($a[$ind], $g), $dp, $n, $a); // Return the answer $dp[$ind][$g] = $ans; return $dp[$ind][$g] ;} // Function to return the number// of subsequencesfunction countSubsequences($a, $n){ // Hash table to memoize $dp = array(array()) ; for($i = 0 ; $i < $n ; $i++) for($j = 0; $j < $GLOBALS['MAX']; $j++) $dp[$i][$j] = -1 ; // Count the number of subsequences $count = 0; // Count for every subsequence for ($i = 0; $i < $n; $i++) $count += func($i + 1, $a[$i], $dp, $n, $a); return $count;} // Driver Code$a = array(3, 4, 8, 16);$n = sizeof($a) ; echo countSubsequences($a, $n); // This code is contributed by Ryuga?>",
"e": 34143,
"s": 32750,
"text": null
},
{
"code": "<script> // JavaScript program to find the number// of subsequences with gcd 1 var MAX = 1000; function gcd(a , b) { if (a == 0) return b; return gcd(b % a, a); } // Recursive function to calculate the number // of subsequences with gcd 1 starting with // particular index function func(ind , g , dp , n , a) { // Base case if (ind == n) { if (g == 1) return 1; else return 0; } // If already visited if (dp[ind][g] != -1) return dp[ind][g]; // Either we take or we do not var ans = func(ind + 1, g, dp, n, a) + func(ind + 1, gcd(a[ind], g), dp, n, a); // Return the answer return dp[ind][g] = ans; } // Function to return the // number of subsequences function countSubsequences(a , n) { // Hash table to memoize var dp = Array(n).fill().map(()=>Array(MAX).fill(0)); for (i = 0; i < n; i++) for (j = 0; j < MAX; j++) dp[i][j] = -1; // Count the number of subsequences var count = 0; // Count for every subsequence for (i = 0; i < n; i++) count += func(i + 1, a[i], dp, n, a); return count; } // Driver Code var a = [ 3, 4, 8, 16 ]; var n = a.length; document.write(countSubsequences(a, n)); // This code contributed by Rajput-Ji </script>",
"e": 35612,
"s": 34143,
"text": null
},
{
"code": null,
"e": 35614,
"s": 35612,
"text": "7"
},
{
"code": null,
"e": 35700,
"s": 35614,
"text": "Alternate Solution: Count number of subsets of a set with GCD equal to a given number"
},
{
"code": null,
"e": 35766,
"s": 35700,
"text": "Dynamic programming approach to this problem without memoization:"
},
{
"code": null,
"e": 36244,
"s": 35766,
"text": "Basically, the approach will be making a 2d matrix in which i coordinate will be the position of elements of the given array and j coordinate will be numbers from 0 to 100 ie. gcd can vary from 0 to 100 if array elements are not enough large. we will iterate on given array and the 2d matrix will store information that till ith position that how many subsequences are there having gcd vary from 1 to 100. later on, we will add dp[i][1] to get all subsequence having gcd as 1."
},
{
"code": null,
"e": 36295,
"s": 36244,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 36299,
"s": 36295,
"text": "C++"
},
{
"code": null,
"e": 36304,
"s": 36299,
"text": "Java"
},
{
"code": null,
"e": 36312,
"s": 36304,
"text": "Python3"
},
{
"code": null,
"e": 36315,
"s": 36312,
"text": "C#"
},
{
"code": null,
"e": 36326,
"s": 36315,
"text": "Javascript"
},
{
"code": "// C++ program for above approach#include <bits/stdc++.h>using namespace std; // This function calculates// gcd of two numberint gcd(int a, int b){ if (b == 0) return a; return gcd(b, a % b);} // This function will return total// subsequencesint countSubsequences(int arr[], int n){ // Declare a dp 2d array long long int dp[n][101] = {0}; // Iterate i from 0 to n - 1 for(int i = 0; i < n; i++) { dp[i][arr[i]] = 1; // Iterate j from i - 1 to 0 for(int j = i - 1; j >= 0; j--) { if(arr[j] < arr[i]) { // Iterate k from 0 to 100 for(int k = 0; k <= 100; k++) { // Find gcd of two number int GCD = gcd(arr[i], k); // dp[i][GCD] is summation of // dp[i][GCD] and dp[j][k] dp[i][GCD] = dp[i][GCD] + dp[j][k]; } } } } // Add all elements of dp[i][1] long long int sum = 0; for(int i = 0; i < n; i++) { sum=(sum + dp[i][1]); } // Return sum return sum;} // Driver codeint main(){ int a[] = { 3, 4, 8, 16 }; int n = sizeof(a) / sizeof(a[0]); // Function Call cout << countSubsequences(a, n); return 0;}",
"e": 37694,
"s": 36326,
"text": null
},
{
"code": "// Java program for the// above approachimport java.util.*; class GFG{ // This function calculates// gcd of two numberstatic int gcd(int a, int b){ if (b == 0) return a; return gcd(b, a % b);} // This function will return total// subsequencesstatic long countSubsequences(int arr[], int n){ // Declare a dp 2d array long dp[][] = new long[n][101]; for(int i = 0; i < n; i++) { for(int j = 0; j < 101; j++) { dp[i][j] = 0; } } // Iterate i from 0 to n - 1 for(int i = 0; i < n; i++) { dp[i][arr[i]] = 1; // Iterate j from i - 1 to 0 for(int j = i - 1; j >= 0; j--) { if (arr[j] < arr[i]) { // Iterate k from 0 to 100 for(int k = 0; k <= 100; k++) { // Find gcd of two number int GCD = gcd(arr[i], k); // dp[i][GCD] is summation of // dp[i][GCD] and dp[j][k] dp[i][GCD] = dp[i][GCD] + dp[j][k]; } } } } // Add all elements of dp[i][1] long sum = 0; for(int i = 0; i < n; i++) { sum = (sum + dp[i][1]); } // Return sum return sum;} // Driver codepublic static void main(String args[]){ int a[] = { 3, 4, 8, 16 }; int n = a.length; // Function Call System.out.println(countSubsequences(a, n));}} // This code is contributed by bolliranadheer",
"e": 39343,
"s": 37694,
"text": null
},
{
"code": "# Python3 program for the# above approach # This function calculates# gcd of two numberdef gcd(a, b): if (b == 0): return a; return gcd(b, a % b); # This function will return total# subsequencesdef countSubsequences(arr, n): # Declare a dp 2d array dp = [[0 for i in range(101)] for j in range(n)] # Iterate i from 0 to n - 1 for i in range(n): dp[i][arr[i]] = 1; # Iterate j from i - 1 to 0 for j in range(i - 1, -1, -1): if (arr[j] < arr[i]): # Iterate k from 0 to 100 for k in range(101): # Find gcd of two number GCD = gcd(arr[i], k); # dp[i][GCD] is summation of # dp[i][GCD] and dp[j][k] dp[i][GCD] = dp[i][GCD] + dp[j][k]; # Add all elements of dp[i][1] sum = 0; for i in range(n): sum = (sum + dp[i][1]); # Return sum return sum; # Driver codeif __name__=='__main__': a = [ 3, 4, 8, 16 ] n = len(a) # Function Call print(countSubsequences(a,n)) # This code is contributed by Pratham76",
"e": 40595,
"s": 39343,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections;using System.Collections.Generic; class GFG{ // This function calculates// gcd of two numberstatic int gcd(int a, int b){ if (b == 0) return a; return gcd(b, a % b);} // This function will return total// subsequencesstatic long countSubsequences(int []arr, int n){ // Declare a dp 2d array long [,]dp = new long[n, 101]; for(int i = 0; i < n; i++) { for(int j = 0; j < 101; j++) { dp[i, j] = 0; } } // Iterate i from 0 to n - 1 for(int i = 0; i < n; i++) { dp[i, arr[i]] = 1; // Iterate j from i - 1 to 0 for(int j = i - 1; j >= 0; j--) { if (arr[j] < arr[i]) { // Iterate k from 0 to 100 for(int k = 0; k <= 100; k++) { // Find gcd of two number int GCD = gcd(arr[i], k); // dp[i,GCD] is summation of // dp[i,GCD] and dp[j,k] dp[i, GCD] = dp[i, GCD] + dp[j, k]; } } } } // Add all elements of dp[i,1] long sum = 0; for(int i = 0; i < n; i++) { sum = (sum + dp[i, 1]); } // Return sum return sum;} // Driver codepublic static void Main(string []args){ int []a = { 3, 4, 8, 16 }; int n = a.Length; // Function Call Console.WriteLine(countSubsequences(a, n));}} // This code is contributed by rutvik_56",
"e": 42301,
"s": 40595,
"text": null
},
{
"code": "<script>// javascript program for the// above approach // This function calculates // gcd of two number function gcd(a , b) { if (b == 0) return a; return gcd(b, a % b); } // This function will return total // subsequences function countSubsequences(arr , n) { // Declare a dp 2d array var dp = Array(n).fill().map(()=>Array(101).fill(0)); for (i = 0; i < n; i++) { for (j = 0; j < 101; j++) { dp[i][j] = 0; } } // Iterate i from 0 to n - 1 for (i = 0; i < n; i++) { dp[i][arr[i]] = 1; // Iterate j from i - 1 to 0 for (j = i - 1; j >= 0; j--) { if (arr[j] < arr[i]) { // Iterate k from 0 to 100 for (k = 0; k <= 100; k++) { // Find gcd of two number var GCD = gcd(arr[i], k); // dp[i][GCD] is summation of // dp[i][GCD] and dp[j][k] dp[i][GCD] = dp[i][GCD] + dp[j][k]; } } } } // Add all elements of dp[i][1] var sum = 0; for (i = 0; i < n; i++) { sum = (sum + dp[i][1]); } // Return sum return sum; } // Driver code var a = [ 3, 4, 8, 16 ]; var n = a.length; // Function Call document.write(countSubsequences(a, n)); // This code contributed by aashish1995</script>",
"e": 43854,
"s": 42301,
"text": null
},
{
"code": null,
"e": 43856,
"s": 43854,
"text": "7"
},
{
"code": null,
"e": 43873,
"s": 43858,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 43881,
"s": 43873,
"text": "ankthon"
},
{
"code": null,
"e": 43892,
"s": 43881,
"text": "andrew1234"
},
{
"code": null,
"e": 43909,
"s": 43892,
"text": "mansibhardwaj009"
},
{
"code": null,
"e": 43924,
"s": 43909,
"text": "bolliranadheer"
},
{
"code": null,
"e": 43934,
"s": 43924,
"text": "rutvik_56"
},
{
"code": null,
"e": 43944,
"s": 43934,
"text": "pratham76"
},
{
"code": null,
"e": 43954,
"s": 43944,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 43966,
"s": 43954,
"text": "aashish1995"
},
{
"code": null,
"e": 43975,
"s": 43966,
"text": "rkbhola5"
},
{
"code": null,
"e": 43983,
"s": 43975,
"text": "GCD-LCM"
},
{
"code": null,
"e": 43995,
"s": 43983,
"text": "subsequence"
},
{
"code": null,
"e": 44002,
"s": 43995,
"text": "Arrays"
},
{
"code": null,
"e": 44009,
"s": 44002,
"text": "Arrays"
},
{
"code": null,
"e": 44107,
"s": 44009,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 44134,
"s": 44107,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 44165,
"s": 44134,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 44190,
"s": 44165,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 44228,
"s": 44190,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 44249,
"s": 44228,
"text": "Next Greater Element"
},
{
"code": null,
"e": 44307,
"s": 44249,
"text": "Find duplicates in O(n) time and O(1) extra space | Set 1"
},
{
"code": null,
"e": 44366,
"s": 44307,
"text": "Find subarray with given sum | Set 1 (Nonnegative Numbers)"
},
{
"code": null,
"e": 44402,
"s": 44366,
"text": "Remove duplicates from sorted array"
},
{
"code": null,
"e": 44487,
"s": 44402,
"text": "Move all negative numbers to beginning and positive to end with constant extra space"
}
] |
Matcher pattern() method in Java with Examples - GeeksforGeeks | 26 Nov, 2018
The pattern() method of Matcher Class is used to get the pattern to be matched by this matcher.
Syntax:
public Pattern pattern()
Parameters: This method do not accepts any parameter.
Return Value: This method returns a Pattern which is the pattern to be matched by this Matcher.
Below examples illustrate the Matcher.pattern() method:
Example 1:
// Java code to illustrate pattern() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = "Geeks"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = "GeeksForGeeks"; // Create a matcher for the input String Matcher matcher = pattern.matcher(stringToBeMatched); // Get the Pattern using pattern() method System.out.println("Pattern: " + matcher.pattern()); }}
Pattern: Geeks
Example 2:
// Java code to illustrate pattern() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = "GFG"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = "GFGFGFGFGFGFGFGFGFG"; // Create a matcher for the input String Matcher matcher = pattern.matcher(stringToBeMatched); // Get the Pattern using pattern() method System.out.println("Pattern: " + matcher.pattern()); }}
Pattern: GFG
Reference: Oracle Doc
Java - util package
Java-Functions
Java-Matcher
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
Stream In Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java | [
{
"code": null,
"e": 26261,
"s": 26233,
"text": "\n26 Nov, 2018"
},
{
"code": null,
"e": 26357,
"s": 26261,
"text": "The pattern() method of Matcher Class is used to get the pattern to be matched by this matcher."
},
{
"code": null,
"e": 26365,
"s": 26357,
"text": "Syntax:"
},
{
"code": null,
"e": 26391,
"s": 26365,
"text": "public Pattern pattern()\n"
},
{
"code": null,
"e": 26445,
"s": 26391,
"text": "Parameters: This method do not accepts any parameter."
},
{
"code": null,
"e": 26541,
"s": 26445,
"text": "Return Value: This method returns a Pattern which is the pattern to be matched by this Matcher."
},
{
"code": null,
"e": 26597,
"s": 26541,
"text": "Below examples illustrate the Matcher.pattern() method:"
},
{
"code": null,
"e": 26608,
"s": 26597,
"text": "Example 1:"
},
{
"code": "// Java code to illustrate pattern() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = \"Geeks\"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = \"GeeksForGeeks\"; // Create a matcher for the input String Matcher matcher = pattern.matcher(stringToBeMatched); // Get the Pattern using pattern() method System.out.println(\"Pattern: \" + matcher.pattern()); }}",
"e": 27285,
"s": 26608,
"text": null
},
{
"code": null,
"e": 27301,
"s": 27285,
"text": "Pattern: Geeks\n"
},
{
"code": null,
"e": 27312,
"s": 27301,
"text": "Example 2:"
},
{
"code": "// Java code to illustrate pattern() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = \"GFG\"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = \"GFGFGFGFGFGFGFGFGFG\"; // Create a matcher for the input String Matcher matcher = pattern.matcher(stringToBeMatched); // Get the Pattern using pattern() method System.out.println(\"Pattern: \" + matcher.pattern()); }}",
"e": 27993,
"s": 27312,
"text": null
},
{
"code": null,
"e": 28007,
"s": 27993,
"text": "Pattern: GFG\n"
},
{
"code": null,
"e": 28029,
"s": 28007,
"text": "Reference: Oracle Doc"
},
{
"code": null,
"e": 28049,
"s": 28029,
"text": "Java - util package"
},
{
"code": null,
"e": 28064,
"s": 28049,
"text": "Java-Functions"
},
{
"code": null,
"e": 28077,
"s": 28064,
"text": "Java-Matcher"
},
{
"code": null,
"e": 28082,
"s": 28077,
"text": "Java"
},
{
"code": null,
"e": 28087,
"s": 28082,
"text": "Java"
},
{
"code": null,
"e": 28185,
"s": 28087,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28236,
"s": 28185,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 28266,
"s": 28236,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 28285,
"s": 28266,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 28300,
"s": 28285,
"text": "Stream In Java"
},
{
"code": null,
"e": 28331,
"s": 28300,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 28349,
"s": 28331,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 28381,
"s": 28349,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 28401,
"s": 28381,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 28433,
"s": 28401,
"text": "Multidimensional Arrays in Java"
}
] |
Python - Alternate Strings Concatenation - GeeksforGeeks | 27 Feb, 2020
The problem of getting concatenation of a list is quite generic and we might some day face the issue of getting the concatenation of alternate elements and get the list of 2 elements containing concatenation of alternate elements. Let’s discuss certain ways in which this can be performed.
Method #1 : Using list comprehension + list slicing + join()List slicing clubbed with list comprehension can be used to perform this particular task. We can have list comprehension to get run the logic and list slicing can slice out the alternate character, concat by the join() function.
# Python3 code to demonstrate# Alternate Strings Concatenation# using list comprehension + list slicing # initializing list test_list = ["GFG", "is", "for", "Computer", "Science", "learning"] # printing original list print("The original list : " + str(test_list)) # using list comprehension + list slicing# Alternate Strings Concatenationres = [" ".join(test_list[i : : 2]) for i in range(len(test_list) // (len(test_list)//2))] # print resultprint("The alternate elements concatenation list : " + str(res))
The original list : ['GFG', 'is', 'for', 'Computer', 'Science', 'learning']
The alternate elements concatenation list : ['GFG for Science', 'is Computer learning']
Method #2 : Using loopThis is the brute method to perform this particular task in which we have the concatenation of alternate elements in different element indices and then return the output list.
# Python3 code to demonstrate# Alternate Strings Concatenation# using loop # initializing list test_list = ["GFG", "is", " for", " Computer", " Science", " learning"] # printing original list print("The original list : " + str(test_list)) # using loop# Alternate Strings Concatenationres = ["", ""]for i in range(0, len(test_list)): if(i % 2): res[1] += test_list[i] else : res[0] += test_list[i] # print resultprint("The alternate elements concatenation list : " + str(res))
The original list : ['GFG', 'is', 'for', 'Computer', 'Science', 'learning']
The alternate elements concatenation list : ['GFG for Science', 'is Computer learning']
Python list-programs
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python? | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n27 Feb, 2020"
},
{
"code": null,
"e": 25827,
"s": 25537,
"text": "The problem of getting concatenation of a list is quite generic and we might some day face the issue of getting the concatenation of alternate elements and get the list of 2 elements containing concatenation of alternate elements. Let’s discuss certain ways in which this can be performed."
},
{
"code": null,
"e": 26116,
"s": 25827,
"text": "Method #1 : Using list comprehension + list slicing + join()List slicing clubbed with list comprehension can be used to perform this particular task. We can have list comprehension to get run the logic and list slicing can slice out the alternate character, concat by the join() function."
},
{
"code": "# Python3 code to demonstrate# Alternate Strings Concatenation# using list comprehension + list slicing # initializing list test_list = [\"GFG\", \"is\", \"for\", \"Computer\", \"Science\", \"learning\"] # printing original list print(\"The original list : \" + str(test_list)) # using list comprehension + list slicing# Alternate Strings Concatenationres = [\" \".join(test_list[i : : 2]) for i in range(len(test_list) // (len(test_list)//2))] # print resultprint(\"The alternate elements concatenation list : \" + str(res))",
"e": 26677,
"s": 26116,
"text": null
},
{
"code": null,
"e": 26842,
"s": 26677,
"text": "The original list : ['GFG', 'is', 'for', 'Computer', 'Science', 'learning']\nThe alternate elements concatenation list : ['GFG for Science', 'is Computer learning']\n"
},
{
"code": null,
"e": 27042,
"s": 26844,
"text": "Method #2 : Using loopThis is the brute method to perform this particular task in which we have the concatenation of alternate elements in different element indices and then return the output list."
},
{
"code": "# Python3 code to demonstrate# Alternate Strings Concatenation# using loop # initializing list test_list = [\"GFG\", \"is\", \" for\", \" Computer\", \" Science\", \" learning\"] # printing original list print(\"The original list : \" + str(test_list)) # using loop# Alternate Strings Concatenationres = [\"\", \"\"]for i in range(0, len(test_list)): if(i % 2): res[1] += test_list[i] else : res[0] += test_list[i] # print resultprint(\"The alternate elements concatenation list : \" + str(res))",
"e": 27543,
"s": 27042,
"text": null
},
{
"code": null,
"e": 27708,
"s": 27543,
"text": "The original list : ['GFG', 'is', 'for', 'Computer', 'Science', 'learning']\nThe alternate elements concatenation list : ['GFG for Science', 'is Computer learning']\n"
},
{
"code": null,
"e": 27729,
"s": 27708,
"text": "Python list-programs"
},
{
"code": null,
"e": 27752,
"s": 27729,
"text": "Python string-programs"
},
{
"code": null,
"e": 27759,
"s": 27752,
"text": "Python"
},
{
"code": null,
"e": 27775,
"s": 27759,
"text": "Python Programs"
},
{
"code": null,
"e": 27873,
"s": 27775,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27905,
"s": 27873,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27947,
"s": 27905,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27989,
"s": 27947,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28016,
"s": 27989,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28072,
"s": 28016,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28094,
"s": 28072,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28133,
"s": 28094,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 28179,
"s": 28133,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 28217,
"s": 28179,
"text": "Python | Convert a list to dictionary"
}
] |
Creating Custom SeekBar in Android - GeeksforGeeks | 12 Dec, 2021
SeekBar can be understood as an extension of ProgressBar in Android. You have to just drag the thumb on SeekBar and drag it towards the backward or forward direction and store the current value of progress changed. SeekBar is widely used in different applications ex – Audio player Video Player etc. You can implement the traditional SeekBar provided by Android. In this article, we will see how we can customize the android SeekBar. For creating a custom SeekBar first we will design our SeekBar and thumb of seekBar for this we will add layout files in drawable. We can use pictures as a thumb too for that instead of creating a layout we have to just put the picture on the drawable rest things will be the same.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2:
Wait for some time, After the build finish, you will see a MainActivity.java file and an XML file inside res -> layout named as activity_main.xml. We will create our custom SeekBar and implement that on our activity_main.xml.
Step 3:
Now right click on drawable -> new -> drawable resource file, name the file as custom_seekbar.xml and specify Root element as layer-list -> click on OK. a new file custom_seekbar.xml will be created
Step 4:
Now in custom_seekbar.xml inside the layer-list add an item and give a shape to it. specify the color, height, corners of the SeekBar. Also, add another item of the same shape and size but you can change the color, left part of SeekBar’s thumb will be of this color.
Step 5:
Now again click on drawable -> new -> drawable resource file, name the file as thumb.xml and specify Root element as shape -> click on OK. a new file thumb.xml will be created. Inside this file give the height, radius, and color of the thumb. these things can be changed. It totally depends upon how you want to design.
Step 6:
Now go to the activity_main.xml create a layout and inside the layout add a SeekBar. Specify the height width of SeekBar and the max progress that you want to use set progress to 0.
android:progressDrawable="@drawable/custom_seekbar"
android:thumb="@drawable/thumb"
android:max="50"
android:progress="0"
This will create a customized Seekbar inside activity_main.xml.
Step 7:
Now open MainActivity.java class Declare objects of SeekBar and TextView, inside onCreate method initialize both objects using findViewById() method. Perform an event of SeekBar change listener that will hold progress value, and by using this event set the progress value inside TextView.
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
// increment or decrement on process changed
// increase the textsize
// with the value of progress
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
value.setText(progress+"/"+"50");
}..
Step 8
Build and run the app. Put the thumb on Seekbar and move it either forward or backward it will display the process.
Code for the above implementation is given below:
Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
package com.abhi.customseekbar; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle;import android.view.View;import android.widget.SeekBar;import android.widget.TextView; public class MainActivity extends AppCompatActivity { SeekBar seekBar; TextView value; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initialize the seekBar object seekBar=findViewById(R.id.seekbar); value=findViewById(R.id.progress); // calling the seekbar event change listener seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override // increment or decrement on process changed // increase the textsize // with the value of progress public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { value.setText(progress+"/"+"50"); } @Override public void onStartTrackingTouch(SeekBar seekBar) { // This method will automatically // called when the user touches the SeekBar } @Override public void onStopTrackingTouch(SeekBar seekBar) { // This method will automatically // called when the user // stops touching the SeekBar } }); }}
Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:background="#458C85" tools:context=".MainActivity"> <RelativeLayout android:id="@+id/Relative_1" android:layout_width="match_parent" android:layout_height="350dp" android:layout_weight="2"> <TextView android:id="@+id/textViewSelectSizeOfArray" android:layout_width="273dp" android:layout_height="wrap_content" android:layout_above="@+id/seekbar" android:layout_alignParentStart="true" android:layout_alignParentEnd="true" android:layout_marginBottom="9dp" android:text="Custom Seek Bar" android:textAlignment="center" android:textColor="@color/white" android:textSize="25dp" /> <SeekBar android:id="@+id/seekbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:indeterminate="false" android:max="50" android:progress="0" android:progressDrawable="@drawable/custom_seekbar" android:thumb="@drawable/thumb" /> <TextView android:id="@+id/progress" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" android:layout_alignParentBottom="true" android:layout_marginLeft="0dp" android:layout_marginRight="0dp" android:layout_marginBottom="199dp" android:padding="10dp" android:text="0" android:textAlignment="center" android:textColor="@color/white" android:textSize="30dp" android:textStyle="bold"> </TextView> </RelativeLayout> </LinearLayout>
Below is the code for the custom_seekbar.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <!-- color, size, shape height of seekbar --> <item android:gravity="center_vertical"> <shape android:shape="rectangle"> <solid android:color="#605A5C"/> <size android:height="30dp"/> <corners android:radius="9dp"/> </shape> </item> <!-- color, size, shape height of seekbar when u drag it--> <item android:gravity="center_vertical"> <scale android:scaleWidth="100%"> <selector> <item android:state_enabled="false" android:drawable="@color/purple_200"/> <item> <shape android:shape="rectangle"> <solid android:color="@color/black"/> <size android:height="30dp"/> <corners android:radius="9dp"/> </shape> </item> </selector> </scale> </item></layer-list>
Below is the code for the thumb.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android"> <solid android:color="@color/purple_200"/> <size android:height="30dp" android:width="25dp"/> <corners android:radius="5dp"/></shape>
Output:
Project Link: Click Here
anikaseth98
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Resource Raw Folder in Android Studio
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
Retrofit with Kotlin Coroutine in Android
How to Post Data to API using Retrofit in Android?
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
Arrays.sort() in Java with examples | [
{
"code": null,
"e": 26407,
"s": 26379,
"text": "\n12 Dec, 2021"
},
{
"code": null,
"e": 27124,
"s": 26407,
"text": "SeekBar can be understood as an extension of ProgressBar in Android. You have to just drag the thumb on SeekBar and drag it towards the backward or forward direction and store the current value of progress changed. SeekBar is widely used in different applications ex – Audio player Video Player etc. You can implement the traditional SeekBar provided by Android. In this article, we will see how we can customize the android SeekBar. For creating a custom SeekBar first we will design our SeekBar and thumb of seekBar for this we will add layout files in drawable. We can use pictures as a thumb too for that instead of creating a layout we have to just put the picture on the drawable rest things will be the same."
},
{
"code": null,
"e": 27153,
"s": 27124,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 27315,
"s": 27153,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 27324,
"s": 27315,
"text": "Step 2: "
},
{
"code": null,
"e": 27551,
"s": 27324,
"text": "Wait for some time, After the build finish, you will see a MainActivity.java file and an XML file inside res -> layout named as activity_main.xml. We will create our custom SeekBar and implement that on our activity_main.xml."
},
{
"code": null,
"e": 27560,
"s": 27551,
"text": "Step 3: "
},
{
"code": null,
"e": 27759,
"s": 27560,
"text": "Now right click on drawable -> new -> drawable resource file, name the file as custom_seekbar.xml and specify Root element as layer-list -> click on OK. a new file custom_seekbar.xml will be created"
},
{
"code": null,
"e": 27769,
"s": 27759,
"text": "Step 4: "
},
{
"code": null,
"e": 28036,
"s": 27769,
"text": "Now in custom_seekbar.xml inside the layer-list add an item and give a shape to it. specify the color, height, corners of the SeekBar. Also, add another item of the same shape and size but you can change the color, left part of SeekBar’s thumb will be of this color."
},
{
"code": null,
"e": 28046,
"s": 28036,
"text": "Step 5: "
},
{
"code": null,
"e": 28367,
"s": 28046,
"text": "Now again click on drawable -> new -> drawable resource file, name the file as thumb.xml and specify Root element as shape -> click on OK. a new file thumb.xml will be created. Inside this file give the height, radius, and color of the thumb. these things can be changed. It totally depends upon how you want to design."
},
{
"code": null,
"e": 28377,
"s": 28367,
"text": "Step 6: "
},
{
"code": null,
"e": 28559,
"s": 28377,
"text": "Now go to the activity_main.xml create a layout and inside the layout add a SeekBar. Specify the height width of SeekBar and the max progress that you want to use set progress to 0."
},
{
"code": null,
"e": 28682,
"s": 28559,
"text": "android:progressDrawable=\"@drawable/custom_seekbar\"\nandroid:thumb=\"@drawable/thumb\" \nandroid:max=\"50\"\nandroid:progress=\"0\""
},
{
"code": null,
"e": 28746,
"s": 28682,
"text": "This will create a customized Seekbar inside activity_main.xml."
},
{
"code": null,
"e": 28755,
"s": 28746,
"text": "Step 7: "
},
{
"code": null,
"e": 29045,
"s": 28755,
"text": "Now open MainActivity.java class Declare objects of SeekBar and TextView, inside onCreate method initialize both objects using findViewById() method. Perform an event of SeekBar change listener that will hold progress value, and by using this event set the progress value inside TextView."
},
{
"code": null,
"e": 29455,
"s": 29045,
"text": "seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {\n @Override\n // increment or decrement on process changed\n // increase the textsize\n // with the value of progress\n public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {\n value.setText(progress+\"/\"+\"50\");\n\n \n }.."
},
{
"code": null,
"e": 29462,
"s": 29455,
"text": "Step 8"
},
{
"code": null,
"e": 29578,
"s": 29462,
"text": "Build and run the app. Put the thumb on Seekbar and move it either forward or backward it will display the process."
},
{
"code": null,
"e": 29628,
"s": 29578,
"text": "Code for the above implementation is given below:"
},
{
"code": null,
"e": 29752,
"s": 29628,
"text": "Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 29757,
"s": 29752,
"text": "Java"
},
{
"code": "package com.abhi.customseekbar; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle;import android.view.View;import android.widget.SeekBar;import android.widget.TextView; public class MainActivity extends AppCompatActivity { SeekBar seekBar; TextView value; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initialize the seekBar object seekBar=findViewById(R.id.seekbar); value=findViewById(R.id.progress); // calling the seekbar event change listener seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override // increment or decrement on process changed // increase the textsize // with the value of progress public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { value.setText(progress+\"/\"+\"50\"); } @Override public void onStartTrackingTouch(SeekBar seekBar) { // This method will automatically // called when the user touches the SeekBar } @Override public void onStopTrackingTouch(SeekBar seekBar) { // This method will automatically // called when the user // stops touching the SeekBar } }); }}",
"e": 31235,
"s": 29757,
"text": null
},
{
"code": null,
"e": 31286,
"s": 31235,
"text": "Below is the code for the activity_main.xml file. "
},
{
"code": null,
"e": 31290,
"s": 31286,
"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:layout_height=\"match_parent\" android:orientation=\"vertical\" android:background=\"#458C85\" tools:context=\".MainActivity\"> <RelativeLayout android:id=\"@+id/Relative_1\" android:layout_width=\"match_parent\" android:layout_height=\"350dp\" android:layout_weight=\"2\"> <TextView android:id=\"@+id/textViewSelectSizeOfArray\" android:layout_width=\"273dp\" android:layout_height=\"wrap_content\" android:layout_above=\"@+id/seekbar\" android:layout_alignParentStart=\"true\" android:layout_alignParentEnd=\"true\" android:layout_marginBottom=\"9dp\" android:text=\"Custom Seek Bar\" android:textAlignment=\"center\" android:textColor=\"@color/white\" android:textSize=\"25dp\" /> <SeekBar android:id=\"@+id/seekbar\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:indeterminate=\"false\" android:max=\"50\" android:progress=\"0\" android:progressDrawable=\"@drawable/custom_seekbar\" android:thumb=\"@drawable/thumb\" /> <TextView android:id=\"@+id/progress\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignParentLeft=\"true\" android:layout_alignParentRight=\"true\" android:layout_alignParentBottom=\"true\" android:layout_marginLeft=\"0dp\" android:layout_marginRight=\"0dp\" android:layout_marginBottom=\"199dp\" android:padding=\"10dp\" android:text=\"0\" android:textAlignment=\"center\" android:textColor=\"@color/white\" android:textSize=\"30dp\" android:textStyle=\"bold\"> </TextView> </RelativeLayout> </LinearLayout>",
"e": 33496,
"s": 31290,
"text": null
},
{
"code": null,
"e": 33548,
"s": 33496,
"text": "Below is the code for the custom_seekbar.xml file. "
},
{
"code": null,
"e": 33552,
"s": 33548,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><layer-list xmlns:android=\"http://schemas.android.com/apk/res/android\"> <!-- color, size, shape height of seekbar --> <item android:gravity=\"center_vertical\"> <shape android:shape=\"rectangle\"> <solid android:color=\"#605A5C\"/> <size android:height=\"30dp\"/> <corners android:radius=\"9dp\"/> </shape> </item> <!-- color, size, shape height of seekbar when u drag it--> <item android:gravity=\"center_vertical\"> <scale android:scaleWidth=\"100%\"> <selector> <item android:state_enabled=\"false\" android:drawable=\"@color/purple_200\"/> <item> <shape android:shape=\"rectangle\"> <solid android:color=\"@color/black\"/> <size android:height=\"30dp\"/> <corners android:radius=\"9dp\"/> </shape> </item> </selector> </scale> </item></layer-list>",
"e": 34588,
"s": 33552,
"text": null
},
{
"code": null,
"e": 34631,
"s": 34588,
"text": "Below is the code for the thumb.xml file. "
},
{
"code": null,
"e": 34635,
"s": 34631,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><shape xmlns:android=\"http://schemas.android.com/apk/res/android\"> <solid android:color=\"@color/purple_200\"/> <size android:height=\"30dp\" android:width=\"25dp\"/> <corners android:radius=\"5dp\"/></shape>",
"e": 34883,
"s": 34635,
"text": null
},
{
"code": null,
"e": 34891,
"s": 34883,
"text": "Output:"
},
{
"code": null,
"e": 34916,
"s": 34891,
"text": "Project Link: Click Here"
},
{
"code": null,
"e": 34928,
"s": 34916,
"text": "anikaseth98"
},
{
"code": null,
"e": 34936,
"s": 34928,
"text": "Android"
},
{
"code": null,
"e": 34941,
"s": 34936,
"text": "Java"
},
{
"code": null,
"e": 34946,
"s": 34941,
"text": "Java"
},
{
"code": null,
"e": 34954,
"s": 34946,
"text": "Android"
},
{
"code": null,
"e": 35052,
"s": 34954,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35090,
"s": 35052,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 35129,
"s": 35090,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 35179,
"s": 35129,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 35221,
"s": 35179,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 35272,
"s": 35221,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 35287,
"s": 35272,
"text": "Arrays in Java"
},
{
"code": null,
"e": 35331,
"s": 35287,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 35353,
"s": 35331,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 35404,
"s": 35353,
"text": "Object Oriented Programming (OOPs) Concept in Java"
}
] |
Formatting Dates in Python - 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
Hi everyone, In this tutorial, we will learn how to format dates in Python with many examples using the built-in datetime module that provides classes to work with dates and time. We will learn how to convert objects of date, time, datetime into a string representation and a string into datetime object using strftime() and strptime() methods.
In this section, we will see how to convert the date, time, datetime objects into their string representation.
Let’s import the datetime module and create an object of class time.
# importing datetime module
import datetime
# using time class from datetime module
# we create a time class object
ex_time = datetime.time(13,50,25,65800)
print(ex_time)
# printing the type of object
print(type(ex_time))
Output:
12:50:25.065800
<class 'datetime.time'>
The output is in format hours:minutes:seconds.microseconds. Let’s verify these by printing the attributes separately.
# Printing all attributes separately
print("Hour : ",ex_time.hour)
print("Minutes : ",ex_time.minute)
print("Seconds : ",ex_time.second)
print("Microseconds : ",ex_time.microsecond)
Output:
Hour : 13
Minutes : 50
Seconds : 25
Microseconds : 65800
Now we have a time object, its time to use strftime() method to convert it into a string. We will use some format codes to achieve all this. It is similar to how the string formatting is done. You can refer to this tutorial on string formatting to know more.
Refer to the link of Format Codes in the reference section at the end to know more about Format codes used in Date and Time formatting
%H, %M, %S format codes
%H – Hour (24-hour clock) as a zero-padded decimal number.
%M – Minute as a zero-padded decimal number.
%S – Second as a zero-padded decimal number.
%H – Hour (24-hour clock) as a zero-padded decimal number.
%M – Minute as a zero-padded decimal number.
%S – Second as a zero-padded decimal number.
print(ex_time.strftime("%H-%M-%S"))
Output:
13-50-25
%I, %f, %p format codes
%I – Hour (12-hour clock) as a zero-padded decimal number.
%f – Microsecond as a decimal number, zero-padded on the left.
%p – Locale’s equivalent of either AM or PM.
%I – Hour (12-hour clock) as a zero-padded decimal number.
%f – Microsecond as a decimal number, zero-padded on the left.
%p – Locale’s equivalent of either AM or PM.
print(ex_time.strftime("%I:%M:%S.%f %p"))
Output:
01:50:25.065800 PM
As we have done in the above section, in this section we will create an object of type datetime. Since format codes remain the same, By the end of this section, we will be able to format most of the dates and times.
ex_date = datetime.datetime(year=2020, month=11, day=10, hour=16, minute=38, second=40)
print(ex_date)
print(type(ex_date))
Output:
2020-11-10 16:38:40
<class 'datetime.datetime'>
We see that we have created a datetime object with defined date and time, let us see how to print the same date-time differently using other format codes.
%d, %m, %Y format codes
%d – Day of the month as a zero-padded decimal number
%m – Month as a zero-padded decimal number.
%Y – Year with century as a decimal number.
%d – Day of the month as a zero-padded decimal number
%m – Month as a zero-padded decimal number.
%Y – Year with century as a decimal number.
print(ex_date.strftime("%d/%m/%Y %H-%M-%S"))
Output:
10/11/2020 16-38-40
%a, %w, %y, %b format codes
%a – Weekday as locale’s abbreviated name.
%w – Weekday as a decimal number, where 0 is Sunday and 6 is Saturday.
%b – Month as locale’s abbreviated name.
%y – Year with century as a decimal number.
%a – Weekday as locale’s abbreviated name.
%w – Weekday as a decimal number, where 0 is Sunday and 6 is Saturday.
%b – Month as locale’s abbreviated name.
%y – Year with century as a decimal number.
print(ex_date.strftime("%a %w %d-%b-%y %H-%M-%S"))
Output:
Tue 2 10-Nov-20 16-38-40
%A, %B, %W format codes
%A – Weekday as locale’s full name.
%B – Month as locale’s full name.
%W – Week number of the year (Monday as the first day of the week) as a decimal number. All days in a new year preceding the first Monday are considered to be in week 0.
%A – Weekday as locale’s full name.
%B – Month as locale’s full name.
%W – Week number of the year (Monday as the first day of the week) as a decimal number. All days in a new year preceding the first Monday are considered to be in week 0.
print(ex_date.strftime("%A %W '%d %B %Y' %H-%M-%S %p"))
Output:
Tuesday 45 '10 November 2020' 16-38-40 PM
With these, we have finished the section and know how to convert a datetime object into a string representation using format codes. Let’s see how we can convert a string to a datetime object.
In this section, we will use the same format codes and a string to represent that string into a date-time representation. The strptime() method of datetime class from datetime module takes 2 parameters, a string of date and a format string in which we want to convert respectively. This format string is made up of the format codes that we have studied and any inappropriate conversion will lead to a value error.
import datetime
date_string1 = "15/09/20"
print(datetime.datetime.strptime(date_string1,'%d/%m/%y'))
Output:
2020-09-15 00:00:00
date_string2 = "Nov15202016-05-30"
print(datetime.datetime.strptime(date_string2,'%b%d%Y%H-%M-%S'))
Output:
2020-11-15 16:05:30
In this tutorial, we have how to format dates in Python. If you have any doubt, feel free to ask in the comment section.
Format Codes
Different ways to do String formatting in Python
Date yyyymmdd format in Shell Script
Happy Learning 🙂
How to create Python Iterable class ?
Python Number Systems Example
Different ways to do String formatting in Python
Convert any Number to Python Binary Number
Python Operators Example
How to read JSON file in Python ?
Python How to read input from keyboard
How to Remove Spaces from String in Python
How to remove empty lists from a Python List
How to sort python dictionary by key ?
Python TypeCasting for Different Types
What are the different ways to Sort Objects in Python ?
Java 13 Text Blocks – Formatting String in Java 13
How to remove special characters from String in Python
Python – How to create Zip File in Python ?
How to create Python Iterable class ?
Python Number Systems Example
Different ways to do String formatting in Python
Convert any Number to Python Binary Number
Python Operators Example
How to read JSON file in Python ?
Python How to read input from keyboard
How to Remove Spaces from String in Python
How to remove empty lists from a Python List
How to sort python dictionary by key ?
Python TypeCasting for Different Types
What are the different ways to Sort Objects in Python ?
Java 13 Text Blocks – Formatting String in Java 13
How to remove special characters from String in Python
Python – How to create Zip File in Python ?
Δ
Python – Introduction
Python – Features
Python – Install on Windows
Python – Modes of Program
Python – Number System
Python – Identifiers
Python – Operators
Python – Ternary Operator
Python – Command Line Arguments
Python – Keywords
Python – Data Types
Python – Upgrade Python PIP
Python – Virtual Environment
Pyhton – Type Casting
Python – String to Int
Python – Conditional Statements
Python – if statement
Python – *args and **kwargs
Python – Date Formatting
Python – Read input from keyboard
Python – raw_input
Python – List In Depth
Python – List Comprehension
Python – Set in Depth
Python – Dictionary in Depth
Python – Tuple in Depth
Python – Stack Datastructure
Python – Classes and Objects
Python – Constructors
Python – Object Introspection
Python – Inheritance
Python – Decorators
Python – Serialization with Pickle
Python – Exceptions Handling
Python – User defined Exceptions
Python – Multiprocessing
Python – Default function parameters
Python – Lambdas Functions
Python – NumPy Library
Python – MySQL Connector
Python – MySQL Create Database
Python – MySQL Read Data
Python – MySQL Insert Data
Python – MySQL Update Records
Python – MySQL Delete Records
Python – String Case Conversion
Howto – Find biggest of 2 numbers
Howto – Remove duplicates from List
Howto – Convert any Number to Binary
Howto – Merge two Lists
Howto – Merge two dicts
Howto – Get Characters Count in a File
Howto – Get Words Count in a File
Howto – Remove Spaces from String
Howto – Read Env variables
Howto – Read a text File
Howto – Read a JSON File
Howto – Read Config.ini files
Howto – Iterate Dictionary
Howto – Convert List Of Objects to CSV
Howto – Merge two dict in Python
Howto – create Zip File
Howto – Get OS info
Howto – Get size of Directory
Howto – Check whether a file exists
Howto – Remove key from dictionary
Howto – Sort Objects
Howto – Create or Delete Directories
Howto – Read CSV File
Howto – Create Python Iterable class
Howto – Access for loop index
Howto – Clear all elements from List
Howto – Remove empty lists from a List
Howto – Remove special characters from String
Howto – Sort dictionary by key
Howto – Filter a list | [
{
"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": 743,
"s": 398,
"text": "Hi everyone, In this tutorial, we will learn how to format dates in Python with many examples using the built-in datetime module that provides classes to work with dates and time. We will learn how to convert objects of date, time, datetime into a string representation and a string into datetime object using strftime() and strptime() methods."
},
{
"code": null,
"e": 854,
"s": 743,
"text": "In this section, we will see how to convert the date, time, datetime objects into their string representation."
},
{
"code": null,
"e": 923,
"s": 854,
"text": "Let’s import the datetime module and create an object of class time."
},
{
"code": null,
"e": 1145,
"s": 923,
"text": "# importing datetime module\nimport datetime\n# using time class from datetime module\n# we create a time class object\nex_time = datetime.time(13,50,25,65800)\nprint(ex_time)\n# printing the type of object\nprint(type(ex_time))"
},
{
"code": null,
"e": 1153,
"s": 1145,
"text": "Output:"
},
{
"code": null,
"e": 1193,
"s": 1153,
"text": "12:50:25.065800\n<class 'datetime.time'>"
},
{
"code": null,
"e": 1311,
"s": 1193,
"text": "The output is in format hours:minutes:seconds.microseconds. Let’s verify these by printing the attributes separately."
},
{
"code": null,
"e": 1493,
"s": 1311,
"text": "# Printing all attributes separately\nprint(\"Hour : \",ex_time.hour)\nprint(\"Minutes : \",ex_time.minute)\nprint(\"Seconds : \",ex_time.second)\nprint(\"Microseconds : \",ex_time.microsecond)"
},
{
"code": null,
"e": 1501,
"s": 1493,
"text": "Output:"
},
{
"code": null,
"e": 1558,
"s": 1501,
"text": "Hour : 13\nMinutes : 50\nSeconds : 25\nMicroseconds : 65800"
},
{
"code": null,
"e": 1817,
"s": 1558,
"text": "Now we have a time object, its time to use strftime() method to convert it into a string. We will use some format codes to achieve all this. It is similar to how the string formatting is done. You can refer to this tutorial on string formatting to know more."
},
{
"code": null,
"e": 1952,
"s": 1817,
"text": "Refer to the link of Format Codes in the reference section at the end to know more about Format codes used in Date and Time formatting"
},
{
"code": null,
"e": 2130,
"s": 1952,
"text": "\n %H, %M, %S format codes\n\n%H – Hour (24-hour clock) as a zero-padded decimal number.\n%M – Minute as a zero-padded decimal number.\n%S – Second as a zero-padded decimal number.\n\n"
},
{
"code": null,
"e": 2189,
"s": 2130,
"text": "%H – Hour (24-hour clock) as a zero-padded decimal number."
},
{
"code": null,
"e": 2234,
"s": 2189,
"text": "%M – Minute as a zero-padded decimal number."
},
{
"code": null,
"e": 2279,
"s": 2234,
"text": "%S – Second as a zero-padded decimal number."
},
{
"code": null,
"e": 2315,
"s": 2279,
"text": "print(ex_time.strftime(\"%H-%M-%S\"))"
},
{
"code": null,
"e": 2323,
"s": 2315,
"text": "Output:"
},
{
"code": null,
"e": 2332,
"s": 2323,
"text": "13-50-25"
},
{
"code": null,
"e": 2528,
"s": 2332,
"text": "\n %I, %f, %p format codes\n\n%I – Hour (12-hour clock) as a zero-padded decimal number.\n%f – Microsecond as a decimal number, zero-padded on the left.\n%p – Locale’s equivalent of either AM or PM.\n\n"
},
{
"code": null,
"e": 2587,
"s": 2528,
"text": "%I – Hour (12-hour clock) as a zero-padded decimal number."
},
{
"code": null,
"e": 2650,
"s": 2587,
"text": "%f – Microsecond as a decimal number, zero-padded on the left."
},
{
"code": null,
"e": 2695,
"s": 2650,
"text": "%p – Locale’s equivalent of either AM or PM."
},
{
"code": null,
"e": 2737,
"s": 2695,
"text": "print(ex_time.strftime(\"%I:%M:%S.%f %p\"))"
},
{
"code": null,
"e": 2745,
"s": 2737,
"text": "Output:"
},
{
"code": null,
"e": 2764,
"s": 2745,
"text": "01:50:25.065800 PM"
},
{
"code": null,
"e": 2980,
"s": 2764,
"text": "As we have done in the above section, in this section we will create an object of type datetime. Since format codes remain the same, By the end of this section, we will be able to format most of the dates and times."
},
{
"code": null,
"e": 3104,
"s": 2980,
"text": "ex_date = datetime.datetime(year=2020, month=11, day=10, hour=16, minute=38, second=40)\nprint(ex_date)\nprint(type(ex_date))"
},
{
"code": null,
"e": 3112,
"s": 3104,
"text": "Output:"
},
{
"code": null,
"e": 3161,
"s": 3112,
"text": "2020-11-10 16:38:40\n\n<class 'datetime.datetime'>"
},
{
"code": null,
"e": 3316,
"s": 3161,
"text": "We see that we have created a datetime object with defined date and time, let us see how to print the same date-time differently using other format codes."
},
{
"code": null,
"e": 3487,
"s": 3316,
"text": "\n %d, %m, %Y format codes\n\n%d – Day of the month as a zero-padded decimal number\n%m – Month as a zero-padded decimal number.\n%Y – Year with century as a decimal number.\n\n"
},
{
"code": null,
"e": 3541,
"s": 3487,
"text": "%d – Day of the month as a zero-padded decimal number"
},
{
"code": null,
"e": 3585,
"s": 3541,
"text": "%m – Month as a zero-padded decimal number."
},
{
"code": null,
"e": 3629,
"s": 3585,
"text": "%Y – Year with century as a decimal number."
},
{
"code": null,
"e": 3674,
"s": 3629,
"text": "print(ex_date.strftime(\"%d/%m/%Y %H-%M-%S\"))"
},
{
"code": null,
"e": 3682,
"s": 3674,
"text": "Output:"
},
{
"code": null,
"e": 3702,
"s": 3682,
"text": "10/11/2020 16-38-40"
},
{
"code": null,
"e": 3934,
"s": 3702,
"text": "\n %a, %w, %y, %b format codes\n\n%a – Weekday as locale’s abbreviated name.\n%w – Weekday as a decimal number, where 0 is Sunday and 6 is Saturday.\n%b – Month as locale’s abbreviated name.\n%y – Year with century as a decimal number.\n\n"
},
{
"code": null,
"e": 3977,
"s": 3934,
"text": "%a – Weekday as locale’s abbreviated name."
},
{
"code": null,
"e": 4048,
"s": 3977,
"text": "%w – Weekday as a decimal number, where 0 is Sunday and 6 is Saturday."
},
{
"code": null,
"e": 4089,
"s": 4048,
"text": "%b – Month as locale’s abbreviated name."
},
{
"code": null,
"e": 4133,
"s": 4089,
"text": "%y – Year with century as a decimal number."
},
{
"code": null,
"e": 4184,
"s": 4133,
"text": "print(ex_date.strftime(\"%a %w %d-%b-%y %H-%M-%S\"))"
},
{
"code": null,
"e": 4192,
"s": 4184,
"text": "Output:"
},
{
"code": null,
"e": 4217,
"s": 4192,
"text": "Tue 2 10-Nov-20 16-38-40"
},
{
"code": null,
"e": 4486,
"s": 4217,
"text": "\n %A, %B, %W format codes\n\n%A – Weekday as locale’s full name.\n%B – Month as locale’s full name.\n%W – Week number of the year (Monday as the first day of the week) as a decimal number. All days in a new year preceding the first Monday are considered to be in week 0.\n\n"
},
{
"code": null,
"e": 4522,
"s": 4486,
"text": "%A – Weekday as locale’s full name."
},
{
"code": null,
"e": 4556,
"s": 4522,
"text": "%B – Month as locale’s full name."
},
{
"code": null,
"e": 4726,
"s": 4556,
"text": "%W – Week number of the year (Monday as the first day of the week) as a decimal number. All days in a new year preceding the first Monday are considered to be in week 0."
},
{
"code": null,
"e": 4782,
"s": 4726,
"text": "print(ex_date.strftime(\"%A %W '%d %B %Y' %H-%M-%S %p\"))"
},
{
"code": null,
"e": 4790,
"s": 4782,
"text": "Output:"
},
{
"code": null,
"e": 4832,
"s": 4790,
"text": "Tuesday 45 '10 November 2020' 16-38-40 PM"
},
{
"code": null,
"e": 5024,
"s": 4832,
"text": "With these, we have finished the section and know how to convert a datetime object into a string representation using format codes. Let’s see how we can convert a string to a datetime object."
},
{
"code": null,
"e": 5438,
"s": 5024,
"text": "In this section, we will use the same format codes and a string to represent that string into a date-time representation. The strptime() method of datetime class from datetime module takes 2 parameters, a string of date and a format string in which we want to convert respectively. This format string is made up of the format codes that we have studied and any inappropriate conversion will lead to a value error."
},
{
"code": null,
"e": 5540,
"s": 5438,
"text": "import datetime\n\ndate_string1 = \"15/09/20\"\nprint(datetime.datetime.strptime(date_string1,'%d/%m/%y'))"
},
{
"code": null,
"e": 5548,
"s": 5540,
"text": "Output:"
},
{
"code": null,
"e": 5568,
"s": 5548,
"text": "2020-09-15 00:00:00"
},
{
"code": null,
"e": 5668,
"s": 5568,
"text": "date_string2 = \"Nov15202016-05-30\"\nprint(datetime.datetime.strptime(date_string2,'%b%d%Y%H-%M-%S'))"
},
{
"code": null,
"e": 5676,
"s": 5668,
"text": "Output:"
},
{
"code": null,
"e": 5696,
"s": 5676,
"text": "2020-11-15 16:05:30"
},
{
"code": null,
"e": 5817,
"s": 5696,
"text": "In this tutorial, we have how to format dates in Python. If you have any doubt, feel free to ask in the comment section."
},
{
"code": null,
"e": 5831,
"s": 5817,
"text": "Format Codes "
},
{
"code": null,
"e": 5880,
"s": 5831,
"text": "Different ways to do String formatting in Python"
},
{
"code": null,
"e": 5917,
"s": 5880,
"text": "Date yyyymmdd format in Shell Script"
},
{
"code": null,
"e": 5934,
"s": 5917,
"text": "Happy Learning 🙂"
},
{
"code": null,
"e": 6566,
"s": 5934,
"text": "\nHow to create Python Iterable class ?\nPython Number Systems Example\nDifferent ways to do String formatting in Python\nConvert any Number to Python Binary Number\nPython Operators Example\nHow to read JSON file in Python ?\nPython How to read input from keyboard\nHow to Remove Spaces from String in Python\nHow to remove empty lists from a Python List\nHow to sort python dictionary by key ?\nPython TypeCasting for Different Types\nWhat are the different ways to Sort Objects in Python ?\nJava 13 Text Blocks – Formatting String in Java 13\nHow to remove special characters from String in Python\nPython – How to create Zip File in Python ?\n"
},
{
"code": null,
"e": 6604,
"s": 6566,
"text": "How to create Python Iterable class ?"
},
{
"code": null,
"e": 6634,
"s": 6604,
"text": "Python Number Systems Example"
},
{
"code": null,
"e": 6683,
"s": 6634,
"text": "Different ways to do String formatting in Python"
},
{
"code": null,
"e": 6726,
"s": 6683,
"text": "Convert any Number to Python Binary Number"
},
{
"code": null,
"e": 6751,
"s": 6726,
"text": "Python Operators Example"
},
{
"code": null,
"e": 6785,
"s": 6751,
"text": "How to read JSON file in Python ?"
},
{
"code": null,
"e": 6824,
"s": 6785,
"text": "Python How to read input from keyboard"
},
{
"code": null,
"e": 6867,
"s": 6824,
"text": "How to Remove Spaces from String in Python"
},
{
"code": null,
"e": 6912,
"s": 6867,
"text": "How to remove empty lists from a Python List"
},
{
"code": null,
"e": 6951,
"s": 6912,
"text": "How to sort python dictionary by key ?"
},
{
"code": null,
"e": 6990,
"s": 6951,
"text": "Python TypeCasting for Different Types"
},
{
"code": null,
"e": 7046,
"s": 6990,
"text": "What are the different ways to Sort Objects in Python ?"
},
{
"code": null,
"e": 7097,
"s": 7046,
"text": "Java 13 Text Blocks – Formatting String in Java 13"
},
{
"code": null,
"e": 7152,
"s": 7097,
"text": "How to remove special characters from String in Python"
},
{
"code": null,
"e": 7196,
"s": 7152,
"text": "Python – How to create Zip File in Python ?"
},
{
"code": null,
"e": 7202,
"s": 7200,
"text": "Δ"
},
{
"code": null,
"e": 7225,
"s": 7202,
"text": " Python – Introduction"
},
{
"code": null,
"e": 7244,
"s": 7225,
"text": " Python – Features"
},
{
"code": null,
"e": 7273,
"s": 7244,
"text": " Python – Install on Windows"
},
{
"code": null,
"e": 7300,
"s": 7273,
"text": " Python – Modes of Program"
},
{
"code": null,
"e": 7324,
"s": 7300,
"text": " Python – Number System"
},
{
"code": null,
"e": 7346,
"s": 7324,
"text": " Python – Identifiers"
},
{
"code": null,
"e": 7366,
"s": 7346,
"text": " Python – Operators"
},
{
"code": null,
"e": 7393,
"s": 7366,
"text": " Python – Ternary Operator"
},
{
"code": null,
"e": 7426,
"s": 7393,
"text": " Python – Command Line Arguments"
},
{
"code": null,
"e": 7445,
"s": 7426,
"text": " Python – Keywords"
},
{
"code": null,
"e": 7466,
"s": 7445,
"text": " Python – Data Types"
},
{
"code": null,
"e": 7495,
"s": 7466,
"text": " Python – Upgrade Python PIP"
},
{
"code": null,
"e": 7525,
"s": 7495,
"text": " Python – Virtual Environment"
},
{
"code": null,
"e": 7548,
"s": 7525,
"text": " Pyhton – Type Casting"
},
{
"code": null,
"e": 7572,
"s": 7548,
"text": " Python – String to Int"
},
{
"code": null,
"e": 7605,
"s": 7572,
"text": " Python – Conditional Statements"
},
{
"code": null,
"e": 7628,
"s": 7605,
"text": " Python – if statement"
},
{
"code": null,
"e": 7657,
"s": 7628,
"text": " Python – *args and **kwargs"
},
{
"code": null,
"e": 7683,
"s": 7657,
"text": " Python – Date Formatting"
},
{
"code": null,
"e": 7718,
"s": 7683,
"text": " Python – Read input from keyboard"
},
{
"code": null,
"e": 7738,
"s": 7718,
"text": " Python – raw_input"
},
{
"code": null,
"e": 7762,
"s": 7738,
"text": " Python – List In Depth"
},
{
"code": null,
"e": 7791,
"s": 7762,
"text": " Python – List Comprehension"
},
{
"code": null,
"e": 7814,
"s": 7791,
"text": " Python – Set in Depth"
},
{
"code": null,
"e": 7844,
"s": 7814,
"text": " Python – Dictionary in Depth"
},
{
"code": null,
"e": 7869,
"s": 7844,
"text": " Python – Tuple in Depth"
},
{
"code": null,
"e": 7899,
"s": 7869,
"text": " Python – Stack Datastructure"
},
{
"code": null,
"e": 7929,
"s": 7899,
"text": " Python – Classes and Objects"
},
{
"code": null,
"e": 7952,
"s": 7929,
"text": " Python – Constructors"
},
{
"code": null,
"e": 7983,
"s": 7952,
"text": " Python – Object Introspection"
},
{
"code": null,
"e": 8005,
"s": 7983,
"text": " Python – Inheritance"
},
{
"code": null,
"e": 8026,
"s": 8005,
"text": " Python – Decorators"
},
{
"code": null,
"e": 8062,
"s": 8026,
"text": " Python – Serialization with Pickle"
},
{
"code": null,
"e": 8092,
"s": 8062,
"text": " Python – Exceptions Handling"
},
{
"code": null,
"e": 8126,
"s": 8092,
"text": " Python – User defined Exceptions"
},
{
"code": null,
"e": 8152,
"s": 8126,
"text": " Python – Multiprocessing"
},
{
"code": null,
"e": 8190,
"s": 8152,
"text": " Python – Default function parameters"
},
{
"code": null,
"e": 8218,
"s": 8190,
"text": " Python – Lambdas Functions"
},
{
"code": null,
"e": 8242,
"s": 8218,
"text": " Python – NumPy Library"
},
{
"code": null,
"e": 8268,
"s": 8242,
"text": " Python – MySQL Connector"
},
{
"code": null,
"e": 8300,
"s": 8268,
"text": " Python – MySQL Create Database"
},
{
"code": null,
"e": 8326,
"s": 8300,
"text": " Python – MySQL Read Data"
},
{
"code": null,
"e": 8354,
"s": 8326,
"text": " Python – MySQL Insert Data"
},
{
"code": null,
"e": 8385,
"s": 8354,
"text": " Python – MySQL Update Records"
},
{
"code": null,
"e": 8416,
"s": 8385,
"text": " Python – MySQL Delete Records"
},
{
"code": null,
"e": 8449,
"s": 8416,
"text": " Python – String Case Conversion"
},
{
"code": null,
"e": 8484,
"s": 8449,
"text": " Howto – Find biggest of 2 numbers"
},
{
"code": null,
"e": 8521,
"s": 8484,
"text": " Howto – Remove duplicates from List"
},
{
"code": null,
"e": 8559,
"s": 8521,
"text": " Howto – Convert any Number to Binary"
},
{
"code": null,
"e": 8585,
"s": 8559,
"text": " Howto – Merge two Lists"
},
{
"code": null,
"e": 8610,
"s": 8585,
"text": " Howto – Merge two dicts"
},
{
"code": null,
"e": 8650,
"s": 8610,
"text": " Howto – Get Characters Count in a File"
},
{
"code": null,
"e": 8685,
"s": 8650,
"text": " Howto – Get Words Count in a File"
},
{
"code": null,
"e": 8720,
"s": 8685,
"text": " Howto – Remove Spaces from String"
},
{
"code": null,
"e": 8749,
"s": 8720,
"text": " Howto – Read Env variables"
},
{
"code": null,
"e": 8775,
"s": 8749,
"text": " Howto – Read a text File"
},
{
"code": null,
"e": 8801,
"s": 8775,
"text": " Howto – Read a JSON File"
},
{
"code": null,
"e": 8833,
"s": 8801,
"text": " Howto – Read Config.ini files"
},
{
"code": null,
"e": 8861,
"s": 8833,
"text": " Howto – Iterate Dictionary"
},
{
"code": null,
"e": 8901,
"s": 8861,
"text": " Howto – Convert List Of Objects to CSV"
},
{
"code": null,
"e": 8935,
"s": 8901,
"text": " Howto – Merge two dict in Python"
},
{
"code": null,
"e": 8960,
"s": 8935,
"text": " Howto – create Zip File"
},
{
"code": null,
"e": 8981,
"s": 8960,
"text": " Howto – Get OS info"
},
{
"code": null,
"e": 9012,
"s": 8981,
"text": " Howto – Get size of Directory"
},
{
"code": null,
"e": 9049,
"s": 9012,
"text": " Howto – Check whether a file exists"
},
{
"code": null,
"e": 9086,
"s": 9049,
"text": " Howto – Remove key from dictionary"
},
{
"code": null,
"e": 9108,
"s": 9086,
"text": " Howto – Sort Objects"
},
{
"code": null,
"e": 9146,
"s": 9108,
"text": " Howto – Create or Delete Directories"
},
{
"code": null,
"e": 9169,
"s": 9146,
"text": " Howto – Read CSV File"
},
{
"code": null,
"e": 9207,
"s": 9169,
"text": " Howto – Create Python Iterable class"
},
{
"code": null,
"e": 9238,
"s": 9207,
"text": " Howto – Access for loop index"
},
{
"code": null,
"e": 9276,
"s": 9238,
"text": " Howto – Clear all elements from List"
},
{
"code": null,
"e": 9316,
"s": 9276,
"text": " Howto – Remove empty lists from a List"
},
{
"code": null,
"e": 9363,
"s": 9316,
"text": " Howto – Remove special characters from String"
},
{
"code": null,
"e": 9395,
"s": 9363,
"text": " Howto – Sort dictionary by key"
}
] |
How to check if the Azure resource group is empty or not using PowerShell? | To check if the resource group is empty or not we need to check if the resource group contains any resources.
For this example, We have a resource group name called the TestRG and we need to check if it is empty.
$resources = Get-AzResource -ResourceGroupName TestRG
if($resources){"Resource group is not empty"}
else{"Resource group is empty"}
Resource group is empty
To check if the resource groups in the particular subscription are empty or not, use the below code.
Connect-AZAccount
Set-AzContext -SubscriptionName 'Your Subscription Name'
$rgs = Get-AzResourceGroup
Write-Output "Empty Resource Groups"
foreach($rg in $rgs.ResourceGroupName){
$resources = Get-AzResource -ResourceGroupName $rg
if(!($resources)){ $rg }
} | [
{
"code": null,
"e": 1172,
"s": 1062,
"text": "To check if the resource group is empty or not we need to check if the resource group contains any resources."
},
{
"code": null,
"e": 1276,
"s": 1172,
"text": "For this example, We have a resource group name called the TestRG and we need to check if it is empty."
},
{
"code": null,
"e": 1408,
"s": 1276,
"text": "$resources = Get-AzResource -ResourceGroupName TestRG\nif($resources){\"Resource group is not empty\"}\nelse{\"Resource group is empty\"}"
},
{
"code": null,
"e": 1432,
"s": 1408,
"text": "Resource group is empty"
},
{
"code": null,
"e": 1533,
"s": 1432,
"text": "To check if the resource groups in the particular subscription are empty or not, use the below code."
},
{
"code": null,
"e": 1799,
"s": 1533,
"text": "Connect-AZAccount\nSet-AzContext -SubscriptionName 'Your Subscription Name'\n$rgs = Get-AzResourceGroup\n\nWrite-Output \"Empty Resource Groups\"\nforeach($rg in $rgs.ResourceGroupName){\n $resources = Get-AzResource -ResourceGroupName $rg\n if(!($resources)){ $rg }\n}"
}
] |
Connection Between Logistic Regression & Naive Bayes | Towards Data Science | Both Naive Bayes and Logistic Regression are quite commonly used classifiers and in this post, we will try to find and understand the connection between these classifiers. We will also go through an example using Palmer Penguin Dataset which is available under CC-0 license. What you can expect to learn from this post?
Basics of Probability and Likelihood.
How Naive Bayes Classifier Works?
Discriminative and Generative Classifier.
Connection Between Naive Bayes and Logistic Regression.
All the formulas used here are from my notebook and the link is given under the References section along with other useful references. Let’s begin!
Each probability distribution has a probability density function (PDF) for continuous distribution e.g. Gaussian distribution (or a probability mass function or PMF for discrete distribution, e.g. binomial distribution) which indicates the probability of a sample (some point) taking a particular value. This function is usually denoted by P(y|θ) where y is the value of the sample and θ is the parameter that describes the PDF/PMF. When more than one sample is drawn independently of one another then we can write as —
We consider the PDF’s in calculations when we know the distribution (and corresponding parameter θ) and want to deduce y’s. Here we think of θ as fixed (known) for different samples and we want to deduce different y’s. The likelihood function is the same but with a twist. Here y’s are known and θ is the variable that we want to determine. At this point, we can briefly introduce the idea of Maximum Likelihood Estimation (MLE).
Maximum Likelihood Estimation: MLE is closely related with the modelling of the data; If we observe data points y1, y2,....,yn and assume that they are from a distribution parametrized by θ, then likelihood is given by L(y1, y2,....,yn|θ); for MLE then our task is to estimate the θ for which likelihood is maximum. For independent observations, we can write the expression for best θ as below —
Convention for optimization is minimizing a function; thus maximizing the likelihood boils down to minimizing the negative log-likelihood. These are the concepts we will be using later, now let’s move to the Naive Bayes Classifier.
Naive Bayes Classifier is an example of a generative classifier while Logistic Regression is an example of a discriminative classifier. But what do we mean by generative and discriminative?
Discriminative Classifier: In general a classification problem can simply be thought of as predicting a class label for a given input vector p(C_k | x). In the discriminative model, we assume some functional form for p(C_k | x) and estimate parameters directly from training data.
Generative Classifier: In the generative model we estimate the parameters of p(x | C_k) i.e. probability distribution of the inputs for each class along with the class priors p(C_k). Both of them are used in Bayes’ theorem to calculate p(C_k | x).
We have defined the class labels as C_k, let’s define the Bayes’ theorem based on that —
p(x) can be thought of as a normalizing constant; p(x)=∑ p(x|C_k) p(C_k), the ∑ is over the class labels k.
Let’s consider a generalized scenario where our data have d features and K classes then the equation above can be written as —
Class conditional probability term can be greatly simplified by assuming ‘naively’ that each of the data features X_i’s are conditionally independent of each other given the class Y. Now we rewrite the equation (2.2), as follows —
This is the fundamental equation for the Naive Bayes Classifier. Once the class prior distribution and class-conditional densities are estimated, the Naive Bayes classifier model can then make a class prediction Y^ (y hat) for a new data input X~
Since the denominator p(X_1, X_2,..., X_d) in our case is constant for a given input. We can use Maximum A Posteriori (MAP) estimation to estimate p(Y=c_k) and p(X_i | Y=c_k). The former is then the relative frequency of class in the training set. These will be more clear when we will do the coding part later.
The different naive Bayes classifiers differ mainly by the assumptions they make regarding the distribution of p(X_i | Y=c_k). This is very important for the MAP estimation, for example, if we assume class conditionals are univariate Gaussians the parameters that need to be determined are mean and standard deviations. The number of parameters to be estimated depends on features and classes.
Instead of the generalized case above for Naive Bayes classifier with K classes, we simply consider 2 classes i.e. Y is now boolean (0/1, True/False). Since Logistic Regression (LogReg) is a discriminative algorithm, it starts by assuming a functional form for P(Y|X).
As expected the functional form of the conditional class distribution for Logistic Regression is basically the sigmoid function. In a separate post, I discussed in detail how you can reach logistic regression starting from linear regression. The parameters (weights w) can be derived using the training data. We can expand Eq. 7, for Y (class label) as boolean —
To assign Y=0 for a given X, we then impose a simple condition as below —
We will use Gaussian Naive Bayes (GNB) Classifier and recover the form of P(Y|X) and compare it with the Logistic Regression results.
In the Gaussian Naive Bayes (GNB) classifier, we will assume that class conditional distributions p(X_i | Y=c_k) are univariate Gaussians. Let’s write the assumptions explicitly —
Y has a Boolean form (i.e 0/1, True/False) and it’s governed by a Bernoulli distribution.Since it’s a GNB, for class conditionals P(X_i | Y=c_k) we assume univariate Gaussians.For all i and j≠i, X_i, X_j are conditionally independent given Y.
Y has a Boolean form (i.e 0/1, True/False) and it’s governed by a Bernoulli distribution.
Since it’s a GNB, for class conditionals P(X_i | Y=c_k) we assume univariate Gaussians.
For all i and j≠i, X_i, X_j are conditionally independent given Y.
Let’s write P(Y=1|X) using Bayes’ Rule —
We can further simplify this equation by introducing Exponential and Natural Logarithm as below —
Let’s assume P(Y=1|X)=π, ⟹P(Y=0|X)=1−π and also use the conditional independence of data points for a given class label to rewrite the equation above as below —
For class conditionals P(X_i | Y=c_k) we assume univariate Gaussians with parameters N(μ_{ik}, σ_i), i.e., the standard deviations are independent of class (Y). We will use this to simplify the denominator of the equation above.
We can use this expression back to the equation before (Eq. 11) to write the posterior distribution for Y=1 in a more compact form as below —
Writing P(Y=1|X) in this form gives us the possibility to directly compare with Eq. 8, i.e. the functional form of the conditional class distribution for Logistic Regression and we get the parameters (weights and bias) in terms of Gaussian mean and standard deviation as below—
Here we have arrived at the generative formulation of Logistic Regression starting from Gaussian Naive Bayes distribution and, we can also find the relation between the parameters of these two distributions for a given binary classification problem.
Best way to understand the steps above is to implement them and for this purpose, I will be using the Palmer Penguin Dataset, which is very similar to the Iris Dataset. Let’s start by importing the necessary libraries and loading the dataset.
It’s a dataset consisting of 3 different species of Penguins ‘Adelie’, ‘Gentoo’ and ‘Chinstrap’ and some of the features such as bill length, flipper length etc. are given. We can see the penguin class distribution based on two parameters ‘bill length’ and ‘bill depth’ using a simple one-line code as below —
penguin_nonan_df = penguin.dropna(how=’any’, axis=0, inplace=False)sns_fgrid=sns.FacetGrid(penguin_nonan_df, hue=”species”, height=6).map(plt.scatter, “bill_length_mm”, “bill_depth_mm”).add_legend()plt.xlabel(‘Bill Length (mm)’, fontsize=12)plt.ylabel(‘Bill Depth (mm)’, fontsize=12)
Instead of working with all the available features, we will select only these two features to make things simple.
penguin_nonan_selected_df = penguin_nonan_df[['species', 'bill_length_mm', 'bill_depth_mm']]X=penguin_nonan_selected_df.drop(['species'], axis=1)Y=penguin_nonan_selected_df['species']from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.2, random_state=30, stratify=Y)print (X_train.shape, y_train.shape, X_test.shape)>>> (266, 2) (266,) (67, 2)X_train = X_train.to_numpy()X_test = X_test.to_numpy()y_train = y_train.to_numpy()y_test = y_test.to_numpy()
To build a Naive Bayes Classifier from scratch, first, we need to define a prior distribution for the classes and in this case, we will count the number of unique classes and divide by the total number of samples to get the class prior distribution. We can define it as below —
Let’s print the prior distribution based on the training samples —
prior = get_prior(y_train)print (prior)print (‘check prior probs: ‘, prior.probs,)>>> [0.43984962 0.20300752 0.35714286]tfp.distributions.Categorical("Categorical", batch_shape=[], event_shape=[], dtype=int32)>>> check prior probs: tf.Tensor([0.43984962 0.20300752 0.35714286], shape=(3,), dtype=float64)
After defining the prior distribution, we will define the class conditional distribution and as I’ve described before, for Gaussian NB, we will assume univariate Gaussian distributions as shown in the equation below. To remember, for our problem, we have 2 features and 3 classes.
To define the class conditionals we need to know the mean and variances and for Normal distributions, they can be easily calculated, check here.
Let’s put them all together and define the class conditional function.
Check the code block again to understand and comprehend that it does give us back Eq. 15 using mean and variance from Eq. 16. We can also print to check the mean and variance for the training data —
class_conditionals, mu, sigma2 = class_conditionals_MLE(X_train, y_train)print (class_conditionals)print (‘check mu and variance: ‘, ‘\n’)print (‘mu: ‘, mu, )print (‘sigma2: ‘, sigma2, )# batch shape : 3 classes, event shape : 2 features>>> tfp.distributions.MultivariateNormalDiag("MultivariateNormalDiag", batch_shape=[3], event_shape=[2], dtype=float64)>>> check mu and variance:>>> mu: [ListWrapper([39.017094017093996, 18.389743589743592]), ListWrapper([49.12592592592592, 18.479629629629624]), ListWrapper([48.063157894736854, 15.058947368421052])]>>> sigma2: [[7.205861640733441, 1.5171597633136102], [10.038216735253773, 1.1042146776406032], [9.476642659279785, 0.9687357340720222]]
Finally, we make the predictions on the test set. So we select sample by sample and use the info from prior probabilities and class conditionals. Here we are building a function to represent Eq. 5 and Eq. 6 that we wrote at the very beginning of the post.
def predict_class(prior_dist, class_cond_dist, x):“””We will use prior distribution (P(Y|C)), class-conditional distribution(P(X|Y)),and test data-set with shape (batch_shape, 2).“”” y = np.zeros((x.shape[0]), dtype=int) for i, train_point in enumerate(x): likelihood = tf.cast(class_cond_dist.prob(train_point), dtype=tf.float32) #class_cond_dist.prob has dtype float64 prior_prob = tf.cast(prior_dist.probs, dtype=tf.float32) numerator = likelihood * prior_prob denominator = tf.reduce_sum(numerator) P = tf.math.divide(numerator, denominator) # till eq. 5 #print (‘check posterior shape: ‘, P.shape) Y = tf.argmax(P) # exact similar to np.argmax [get the class] # back to eq. 6 y[i] = int(Y) return y
We can predict the classes of the test data-points and compare them with the original labels —
predictions = predict_class(prior, class_conditionals, X_test)
Plotting a decision boundary (using contour plot) for the test data points will result in the figure below
All of the above tasks can be done using Sklearn and with only a few lines of code —
from sklearn.naive_bayes import GaussianNBsklearn_GNB = GaussianNB()sklearn_GNB.fit(X_train, y_train)predictions_sklearn = sklearn_GNB.predict(X_test)
It’s always good to know the working behind the scenes for these basic algorithms and we can compare the fit parameters which are very close to the parameters we’ve obtained before—
print ('variance:', sklearn_GNB.var_)print ('mean: ', sklearn_GNB.theta_)>>> variance: [[ 7.20586167 1.51715979] [10.03821677 1.10421471] [ 9.47664269 0.96873576]]mean: [[39.01709402 18.38974359] [49.12592593 18.47962963] [48.06315789 15.05894737]]
Let’s plot the decision regions for a comparison with our hard-coded GNB classifier—
They look very much comparable as expected. Let’s move to explicitly connecting GNB and Logistic Regression classifier for a binary classification problem.
As discussed before, to connect Naive Bayes and logistic regression, we will think of binary classification. Since there’re 3 classes in the Penguin dataset, first, we transform the problem as one vs rest classifier and then determine the logistic regression parameters. Also on the derivation of GNB as a binary classifier, we will use the same σ_i for two different classes (no k dependence). So here we will be finding 6 parameters; 4 for μ_{ik} & 2 for σ_i. This rules out the possibility of using the class conditional function that we have used before because μ_{ik} is used in the standard deviation formula and the means depend on the classes as well as features. So we have to write a function to use gradient descent type optimization to learn the class independent standard deviations. This is the main coding task.
Before all of these, we need to binarize the labels and to do that we will use label 1 for samples with label 2.
class_types_dict = {'Adelie':0, 'Chinstrap':1, 'Gentoo':2}y_train_cat = np.vectorize(class_types_dict.get)(y_train)y_train_cat_binary = y_train_caty_train_cat_binary[np.where(y_train_cat_binary == 2)] = 1 # gentoo == chinstrapy_test_cat = np.vectorize(class_types_dict.get)(y_test)y_test_cat_binary = np.array(y_test_cat)y_test_cat_binary[np.where(y_test_cat_binary == 2)] = 1print (‘check shapes: ‘, y_train_cat_binary.shape, y_test_cat_binary.shape, y_train_cat_binary.dtype, ‘\n’, y_train_cat.shape)>>> check shapes: (266,) (67,) int64>>> (266,)
We can plot the data distribution and it looks as below —
We can use the prior distribution function to get the class label priors for these 2 classes
prior_binary = get_prior(y_train_cat_binary)print (prior_binary.probs, print (type(prior_binary)))>>> [0.43984962 0.56015038]<class 'tensorflow_probability.python.distributions.categorical.Categorical'>tf.Tensor([0.43984962 0.56015038], shape=(2,), dtype=float64) None
Compared with the previous prior distribution, we will see that the Adelie penguin class has the same prior (0.43) and expectedly Gentoo and Chinstrap prior distributions are added (≈ 0.20 + 0.35).
For learning the standard deviations we will minimize the negative log-likelihood using gradient descent given the data and labels.
Once the training finishes, we can retrieve the parameters as —
print(class_conditionals_binary.loc.numpy())print (class_conditionals_binary.covariance().numpy())
Using the class conditionals we can plot the contours as below —
We can also plot the decision boundary for the binary GNB classifier —
Once we have the means and the diagonal covariance matrix we are ready to find the parameters for logistic regression. The weight and bias parameters are derived using mean and covariance in Eq. 14, let’s rewrite them one more time —
With this, we’ve come to the end of the post! Lot’s of important and fundamental concepts are covered and I hope you’ll find this helpful.
[1] Penguin Dataset, Licensed under CC-0 and free to adapt.
[2] Machine Learning Book; by Tom Mitchell, Carnegie Mellon University; New Chapters.
[3] Full Notebook used for this post. GitHub Link.
Stay strong !! | [
{
"code": null,
"e": 492,
"s": 172,
"text": "Both Naive Bayes and Logistic Regression are quite commonly used classifiers and in this post, we will try to find and understand the connection between these classifiers. We will also go through an example using Palmer Penguin Dataset which is available under CC-0 license. What you can expect to learn from this post?"
},
{
"code": null,
"e": 530,
"s": 492,
"text": "Basics of Probability and Likelihood."
},
{
"code": null,
"e": 564,
"s": 530,
"text": "How Naive Bayes Classifier Works?"
},
{
"code": null,
"e": 606,
"s": 564,
"text": "Discriminative and Generative Classifier."
},
{
"code": null,
"e": 662,
"s": 606,
"text": "Connection Between Naive Bayes and Logistic Regression."
},
{
"code": null,
"e": 810,
"s": 662,
"text": "All the formulas used here are from my notebook and the link is given under the References section along with other useful references. Let’s begin!"
},
{
"code": null,
"e": 1330,
"s": 810,
"text": "Each probability distribution has a probability density function (PDF) for continuous distribution e.g. Gaussian distribution (or a probability mass function or PMF for discrete distribution, e.g. binomial distribution) which indicates the probability of a sample (some point) taking a particular value. This function is usually denoted by P(y|θ) where y is the value of the sample and θ is the parameter that describes the PDF/PMF. When more than one sample is drawn independently of one another then we can write as —"
},
{
"code": null,
"e": 1760,
"s": 1330,
"text": "We consider the PDF’s in calculations when we know the distribution (and corresponding parameter θ) and want to deduce y’s. Here we think of θ as fixed (known) for different samples and we want to deduce different y’s. The likelihood function is the same but with a twist. Here y’s are known and θ is the variable that we want to determine. At this point, we can briefly introduce the idea of Maximum Likelihood Estimation (MLE)."
},
{
"code": null,
"e": 2156,
"s": 1760,
"text": "Maximum Likelihood Estimation: MLE is closely related with the modelling of the data; If we observe data points y1, y2,....,yn and assume that they are from a distribution parametrized by θ, then likelihood is given by L(y1, y2,....,yn|θ); for MLE then our task is to estimate the θ for which likelihood is maximum. For independent observations, we can write the expression for best θ as below —"
},
{
"code": null,
"e": 2388,
"s": 2156,
"text": "Convention for optimization is minimizing a function; thus maximizing the likelihood boils down to minimizing the negative log-likelihood. These are the concepts we will be using later, now let’s move to the Naive Bayes Classifier."
},
{
"code": null,
"e": 2578,
"s": 2388,
"text": "Naive Bayes Classifier is an example of a generative classifier while Logistic Regression is an example of a discriminative classifier. But what do we mean by generative and discriminative?"
},
{
"code": null,
"e": 2859,
"s": 2578,
"text": "Discriminative Classifier: In general a classification problem can simply be thought of as predicting a class label for a given input vector p(C_k | x). In the discriminative model, we assume some functional form for p(C_k | x) and estimate parameters directly from training data."
},
{
"code": null,
"e": 3107,
"s": 2859,
"text": "Generative Classifier: In the generative model we estimate the parameters of p(x | C_k) i.e. probability distribution of the inputs for each class along with the class priors p(C_k). Both of them are used in Bayes’ theorem to calculate p(C_k | x)."
},
{
"code": null,
"e": 3196,
"s": 3107,
"text": "We have defined the class labels as C_k, let’s define the Bayes’ theorem based on that —"
},
{
"code": null,
"e": 3304,
"s": 3196,
"text": "p(x) can be thought of as a normalizing constant; p(x)=∑ p(x|C_k) p(C_k), the ∑ is over the class labels k."
},
{
"code": null,
"e": 3431,
"s": 3304,
"text": "Let’s consider a generalized scenario where our data have d features and K classes then the equation above can be written as —"
},
{
"code": null,
"e": 3662,
"s": 3431,
"text": "Class conditional probability term can be greatly simplified by assuming ‘naively’ that each of the data features X_i’s are conditionally independent of each other given the class Y. Now we rewrite the equation (2.2), as follows —"
},
{
"code": null,
"e": 3909,
"s": 3662,
"text": "This is the fundamental equation for the Naive Bayes Classifier. Once the class prior distribution and class-conditional densities are estimated, the Naive Bayes classifier model can then make a class prediction Y^ (y hat) for a new data input X~"
},
{
"code": null,
"e": 4221,
"s": 3909,
"text": "Since the denominator p(X_1, X_2,..., X_d) in our case is constant for a given input. We can use Maximum A Posteriori (MAP) estimation to estimate p(Y=c_k) and p(X_i | Y=c_k). The former is then the relative frequency of class in the training set. These will be more clear when we will do the coding part later."
},
{
"code": null,
"e": 4615,
"s": 4221,
"text": "The different naive Bayes classifiers differ mainly by the assumptions they make regarding the distribution of p(X_i | Y=c_k). This is very important for the MAP estimation, for example, if we assume class conditionals are univariate Gaussians the parameters that need to be determined are mean and standard deviations. The number of parameters to be estimated depends on features and classes."
},
{
"code": null,
"e": 4884,
"s": 4615,
"text": "Instead of the generalized case above for Naive Bayes classifier with K classes, we simply consider 2 classes i.e. Y is now boolean (0/1, True/False). Since Logistic Regression (LogReg) is a discriminative algorithm, it starts by assuming a functional form for P(Y|X)."
},
{
"code": null,
"e": 5247,
"s": 4884,
"text": "As expected the functional form of the conditional class distribution for Logistic Regression is basically the sigmoid function. In a separate post, I discussed in detail how you can reach logistic regression starting from linear regression. The parameters (weights w) can be derived using the training data. We can expand Eq. 7, for Y (class label) as boolean —"
},
{
"code": null,
"e": 5321,
"s": 5247,
"text": "To assign Y=0 for a given X, we then impose a simple condition as below —"
},
{
"code": null,
"e": 5455,
"s": 5321,
"text": "We will use Gaussian Naive Bayes (GNB) Classifier and recover the form of P(Y|X) and compare it with the Logistic Regression results."
},
{
"code": null,
"e": 5635,
"s": 5455,
"text": "In the Gaussian Naive Bayes (GNB) classifier, we will assume that class conditional distributions p(X_i | Y=c_k) are univariate Gaussians. Let’s write the assumptions explicitly —"
},
{
"code": null,
"e": 5879,
"s": 5635,
"text": "Y has a Boolean form (i.e 0/1, True/False) and it’s governed by a Bernoulli distribution.Since it’s a GNB, for class conditionals P(X_i | Y=c_k) we assume univariate Gaussians.For all i and j≠i, X_i, X_j are conditionally independent given Y."
},
{
"code": null,
"e": 5969,
"s": 5879,
"text": "Y has a Boolean form (i.e 0/1, True/False) and it’s governed by a Bernoulli distribution."
},
{
"code": null,
"e": 6057,
"s": 5969,
"text": "Since it’s a GNB, for class conditionals P(X_i | Y=c_k) we assume univariate Gaussians."
},
{
"code": null,
"e": 6125,
"s": 6057,
"text": "For all i and j≠i, X_i, X_j are conditionally independent given Y."
},
{
"code": null,
"e": 6166,
"s": 6125,
"text": "Let’s write P(Y=1|X) using Bayes’ Rule —"
},
{
"code": null,
"e": 6264,
"s": 6166,
"text": "We can further simplify this equation by introducing Exponential and Natural Logarithm as below —"
},
{
"code": null,
"e": 6425,
"s": 6264,
"text": "Let’s assume P(Y=1|X)=π, ⟹P(Y=0|X)=1−π and also use the conditional independence of data points for a given class label to rewrite the equation above as below —"
},
{
"code": null,
"e": 6654,
"s": 6425,
"text": "For class conditionals P(X_i | Y=c_k) we assume univariate Gaussians with parameters N(μ_{ik}, σ_i), i.e., the standard deviations are independent of class (Y). We will use this to simplify the denominator of the equation above."
},
{
"code": null,
"e": 6796,
"s": 6654,
"text": "We can use this expression back to the equation before (Eq. 11) to write the posterior distribution for Y=1 in a more compact form as below —"
},
{
"code": null,
"e": 7074,
"s": 6796,
"text": "Writing P(Y=1|X) in this form gives us the possibility to directly compare with Eq. 8, i.e. the functional form of the conditional class distribution for Logistic Regression and we get the parameters (weights and bias) in terms of Gaussian mean and standard deviation as below—"
},
{
"code": null,
"e": 7324,
"s": 7074,
"text": "Here we have arrived at the generative formulation of Logistic Regression starting from Gaussian Naive Bayes distribution and, we can also find the relation between the parameters of these two distributions for a given binary classification problem."
},
{
"code": null,
"e": 7567,
"s": 7324,
"text": "Best way to understand the steps above is to implement them and for this purpose, I will be using the Palmer Penguin Dataset, which is very similar to the Iris Dataset. Let’s start by importing the necessary libraries and loading the dataset."
},
{
"code": null,
"e": 7877,
"s": 7567,
"text": "It’s a dataset consisting of 3 different species of Penguins ‘Adelie’, ‘Gentoo’ and ‘Chinstrap’ and some of the features such as bill length, flipper length etc. are given. We can see the penguin class distribution based on two parameters ‘bill length’ and ‘bill depth’ using a simple one-line code as below —"
},
{
"code": null,
"e": 8161,
"s": 7877,
"text": "penguin_nonan_df = penguin.dropna(how=’any’, axis=0, inplace=False)sns_fgrid=sns.FacetGrid(penguin_nonan_df, hue=”species”, height=6).map(plt.scatter, “bill_length_mm”, “bill_depth_mm”).add_legend()plt.xlabel(‘Bill Length (mm)’, fontsize=12)plt.ylabel(‘Bill Depth (mm)’, fontsize=12)"
},
{
"code": null,
"e": 8275,
"s": 8161,
"text": "Instead of working with all the available features, we will select only these two features to make things simple."
},
{
"code": null,
"e": 8797,
"s": 8275,
"text": "penguin_nonan_selected_df = penguin_nonan_df[['species', 'bill_length_mm', 'bill_depth_mm']]X=penguin_nonan_selected_df.drop(['species'], axis=1)Y=penguin_nonan_selected_df['species']from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.2, random_state=30, stratify=Y)print (X_train.shape, y_train.shape, X_test.shape)>>> (266, 2) (266,) (67, 2)X_train = X_train.to_numpy()X_test = X_test.to_numpy()y_train = y_train.to_numpy()y_test = y_test.to_numpy()"
},
{
"code": null,
"e": 9075,
"s": 8797,
"text": "To build a Naive Bayes Classifier from scratch, first, we need to define a prior distribution for the classes and in this case, we will count the number of unique classes and divide by the total number of samples to get the class prior distribution. We can define it as below —"
},
{
"code": null,
"e": 9142,
"s": 9075,
"text": "Let’s print the prior distribution based on the training samples —"
},
{
"code": null,
"e": 9448,
"s": 9142,
"text": "prior = get_prior(y_train)print (prior)print (‘check prior probs: ‘, prior.probs,)>>> [0.43984962 0.20300752 0.35714286]tfp.distributions.Categorical(\"Categorical\", batch_shape=[], event_shape=[], dtype=int32)>>> check prior probs: tf.Tensor([0.43984962 0.20300752 0.35714286], shape=(3,), dtype=float64)"
},
{
"code": null,
"e": 9729,
"s": 9448,
"text": "After defining the prior distribution, we will define the class conditional distribution and as I’ve described before, for Gaussian NB, we will assume univariate Gaussian distributions as shown in the equation below. To remember, for our problem, we have 2 features and 3 classes."
},
{
"code": null,
"e": 9874,
"s": 9729,
"text": "To define the class conditionals we need to know the mean and variances and for Normal distributions, they can be easily calculated, check here."
},
{
"code": null,
"e": 9945,
"s": 9874,
"text": "Let’s put them all together and define the class conditional function."
},
{
"code": null,
"e": 10144,
"s": 9945,
"text": "Check the code block again to understand and comprehend that it does give us back Eq. 15 using mean and variance from Eq. 16. We can also print to check the mean and variance for the training data —"
},
{
"code": null,
"e": 10837,
"s": 10144,
"text": "class_conditionals, mu, sigma2 = class_conditionals_MLE(X_train, y_train)print (class_conditionals)print (‘check mu and variance: ‘, ‘\\n’)print (‘mu: ‘, mu, )print (‘sigma2: ‘, sigma2, )# batch shape : 3 classes, event shape : 2 features>>> tfp.distributions.MultivariateNormalDiag(\"MultivariateNormalDiag\", batch_shape=[3], event_shape=[2], dtype=float64)>>> check mu and variance:>>> mu: [ListWrapper([39.017094017093996, 18.389743589743592]), ListWrapper([49.12592592592592, 18.479629629629624]), ListWrapper([48.063157894736854, 15.058947368421052])]>>> sigma2: [[7.205861640733441, 1.5171597633136102], [10.038216735253773, 1.1042146776406032], [9.476642659279785, 0.9687357340720222]]"
},
{
"code": null,
"e": 11093,
"s": 10837,
"text": "Finally, we make the predictions on the test set. So we select sample by sample and use the info from prior probabilities and class conditionals. Here we are building a function to represent Eq. 5 and Eq. 6 that we wrote at the very beginning of the post."
},
{
"code": null,
"e": 11857,
"s": 11093,
"text": "def predict_class(prior_dist, class_cond_dist, x):“””We will use prior distribution (P(Y|C)), class-conditional distribution(P(X|Y)),and test data-set with shape (batch_shape, 2).“”” y = np.zeros((x.shape[0]), dtype=int) for i, train_point in enumerate(x): likelihood = tf.cast(class_cond_dist.prob(train_point), dtype=tf.float32) #class_cond_dist.prob has dtype float64 prior_prob = tf.cast(prior_dist.probs, dtype=tf.float32) numerator = likelihood * prior_prob denominator = tf.reduce_sum(numerator) P = tf.math.divide(numerator, denominator) # till eq. 5 #print (‘check posterior shape: ‘, P.shape) Y = tf.argmax(P) # exact similar to np.argmax [get the class] # back to eq. 6 y[i] = int(Y) return y"
},
{
"code": null,
"e": 11952,
"s": 11857,
"text": "We can predict the classes of the test data-points and compare them with the original labels —"
},
{
"code": null,
"e": 12015,
"s": 11952,
"text": "predictions = predict_class(prior, class_conditionals, X_test)"
},
{
"code": null,
"e": 12122,
"s": 12015,
"text": "Plotting a decision boundary (using contour plot) for the test data points will result in the figure below"
},
{
"code": null,
"e": 12207,
"s": 12122,
"text": "All of the above tasks can be done using Sklearn and with only a few lines of code —"
},
{
"code": null,
"e": 12358,
"s": 12207,
"text": "from sklearn.naive_bayes import GaussianNBsklearn_GNB = GaussianNB()sklearn_GNB.fit(X_train, y_train)predictions_sklearn = sklearn_GNB.predict(X_test)"
},
{
"code": null,
"e": 12540,
"s": 12358,
"text": "It’s always good to know the working behind the scenes for these basic algorithms and we can compare the fit parameters which are very close to the parameters we’ve obtained before—"
},
{
"code": null,
"e": 12794,
"s": 12540,
"text": "print ('variance:', sklearn_GNB.var_)print ('mean: ', sklearn_GNB.theta_)>>> variance: [[ 7.20586167 1.51715979] [10.03821677 1.10421471] [ 9.47664269 0.96873576]]mean: [[39.01709402 18.38974359] [49.12592593 18.47962963] [48.06315789 15.05894737]]"
},
{
"code": null,
"e": 12879,
"s": 12794,
"text": "Let’s plot the decision regions for a comparison with our hard-coded GNB classifier—"
},
{
"code": null,
"e": 13035,
"s": 12879,
"text": "They look very much comparable as expected. Let’s move to explicitly connecting GNB and Logistic Regression classifier for a binary classification problem."
},
{
"code": null,
"e": 13862,
"s": 13035,
"text": "As discussed before, to connect Naive Bayes and logistic regression, we will think of binary classification. Since there’re 3 classes in the Penguin dataset, first, we transform the problem as one vs rest classifier and then determine the logistic regression parameters. Also on the derivation of GNB as a binary classifier, we will use the same σ_i for two different classes (no k dependence). So here we will be finding 6 parameters; 4 for μ_{ik} & 2 for σ_i. This rules out the possibility of using the class conditional function that we have used before because μ_{ik} is used in the standard deviation formula and the means depend on the classes as well as features. So we have to write a function to use gradient descent type optimization to learn the class independent standard deviations. This is the main coding task."
},
{
"code": null,
"e": 13975,
"s": 13862,
"text": "Before all of these, we need to binarize the labels and to do that we will use label 1 for samples with label 2."
},
{
"code": null,
"e": 14525,
"s": 13975,
"text": "class_types_dict = {'Adelie':0, 'Chinstrap':1, 'Gentoo':2}y_train_cat = np.vectorize(class_types_dict.get)(y_train)y_train_cat_binary = y_train_caty_train_cat_binary[np.where(y_train_cat_binary == 2)] = 1 # gentoo == chinstrapy_test_cat = np.vectorize(class_types_dict.get)(y_test)y_test_cat_binary = np.array(y_test_cat)y_test_cat_binary[np.where(y_test_cat_binary == 2)] = 1print (‘check shapes: ‘, y_train_cat_binary.shape, y_test_cat_binary.shape, y_train_cat_binary.dtype, ‘\\n’, y_train_cat.shape)>>> check shapes: (266,) (67,) int64>>> (266,)"
},
{
"code": null,
"e": 14583,
"s": 14525,
"text": "We can plot the data distribution and it looks as below —"
},
{
"code": null,
"e": 14676,
"s": 14583,
"text": "We can use the prior distribution function to get the class label priors for these 2 classes"
},
{
"code": null,
"e": 14945,
"s": 14676,
"text": "prior_binary = get_prior(y_train_cat_binary)print (prior_binary.probs, print (type(prior_binary)))>>> [0.43984962 0.56015038]<class 'tensorflow_probability.python.distributions.categorical.Categorical'>tf.Tensor([0.43984962 0.56015038], shape=(2,), dtype=float64) None"
},
{
"code": null,
"e": 15143,
"s": 14945,
"text": "Compared with the previous prior distribution, we will see that the Adelie penguin class has the same prior (0.43) and expectedly Gentoo and Chinstrap prior distributions are added (≈ 0.20 + 0.35)."
},
{
"code": null,
"e": 15275,
"s": 15143,
"text": "For learning the standard deviations we will minimize the negative log-likelihood using gradient descent given the data and labels."
},
{
"code": null,
"e": 15339,
"s": 15275,
"text": "Once the training finishes, we can retrieve the parameters as —"
},
{
"code": null,
"e": 15438,
"s": 15339,
"text": "print(class_conditionals_binary.loc.numpy())print (class_conditionals_binary.covariance().numpy())"
},
{
"code": null,
"e": 15503,
"s": 15438,
"text": "Using the class conditionals we can plot the contours as below —"
},
{
"code": null,
"e": 15574,
"s": 15503,
"text": "We can also plot the decision boundary for the binary GNB classifier —"
},
{
"code": null,
"e": 15808,
"s": 15574,
"text": "Once we have the means and the diagonal covariance matrix we are ready to find the parameters for logistic regression. The weight and bias parameters are derived using mean and covariance in Eq. 14, let’s rewrite them one more time —"
},
{
"code": null,
"e": 15947,
"s": 15808,
"text": "With this, we’ve come to the end of the post! Lot’s of important and fundamental concepts are covered and I hope you’ll find this helpful."
},
{
"code": null,
"e": 16007,
"s": 15947,
"text": "[1] Penguin Dataset, Licensed under CC-0 and free to adapt."
},
{
"code": null,
"e": 16093,
"s": 16007,
"text": "[2] Machine Learning Book; by Tom Mitchell, Carnegie Mellon University; New Chapters."
},
{
"code": null,
"e": 16144,
"s": 16093,
"text": "[3] Full Notebook used for this post. GitHub Link."
}
] |
How can we use SIGNAL statement with MySQL triggers? | Actually, MySQL SIGNAL statement is an error handling mechanism for handling unexpected occurrences and a graceful exit from the application if need to be. Basically, it provides error information to the handler. Its basic syntax would be as follows −
SIGNAL SQLSTATE | condition_value
[SET signal_information_item = value_1,[, signal_information_item] = value_2,
etc;]
Here, the SIGNAL keyword is an SQLSTATE value or a condition name declared by a DECLARE CONDITION statement. The SIGNAL statement must always specify an SQLSTATE value or a named condition that defined with an SQLSTATE value. The SQLSTATE value for a The SIGNAL statement consists of a five-character alphanumeric code. We must not start our own SQLSTATE code with '00' because such values indicate success and are not valid for signaling an error. If our value is invalid, a Bad SQLSTATE error occurs. For catch-all error handling, we should assign an SQLSTATE value of '45000', which signifies an “unhandled user-defined exception.”
To illustrate the use of SIGNAL statement with MySQL triggers we are using the following example in which we are creating a BEFORE INSERT trigger on the student_age table. It will throw an error message using SIGNAL statement if we will try to enter the age of less than 0.
mysql> Create trigger before_insert_studentage BEFORE INSERT on
student_age FOR EACH ROW BEGIN IF NEW.age<0 then SIGNAL SQLSTATE
'45000' SET MESSAGE_TEXT = 'age less than 0'; END if; END; //
Query OK, 0 rows affected (0.12 sec)
mysql> Insert into student_age(age, name) values(-10,'gaurav')//
ERROR 1644 (45000): age less than 0
It is clear from the above result set that if we will try to insert age less than 0 then it will throw an error using SIGNAL statement. | [
{
"code": null,
"e": 1314,
"s": 1062,
"text": "Actually, MySQL SIGNAL statement is an error handling mechanism for handling unexpected occurrences and a graceful exit from the application if need to be. Basically, it provides error information to the handler. Its basic syntax would be as follows −"
},
{
"code": null,
"e": 1432,
"s": 1314,
"text": "SIGNAL SQLSTATE | condition_value\n[SET signal_information_item = value_1,[, signal_information_item] = value_2,\netc;]"
},
{
"code": null,
"e": 2067,
"s": 1432,
"text": "Here, the SIGNAL keyword is an SQLSTATE value or a condition name declared by a DECLARE CONDITION statement. The SIGNAL statement must always specify an SQLSTATE value or a named condition that defined with an SQLSTATE value. The SQLSTATE value for a The SIGNAL statement consists of a five-character alphanumeric code. We must not start our own SQLSTATE code with '00' because such values indicate success and are not valid for signaling an error. If our value is invalid, a Bad SQLSTATE error occurs. For catch-all error handling, we should assign an SQLSTATE value of '45000', which signifies an “unhandled user-defined exception.”"
},
{
"code": null,
"e": 2341,
"s": 2067,
"text": "To illustrate the use of SIGNAL statement with MySQL triggers we are using the following example in which we are creating a BEFORE INSERT trigger on the student_age table. It will throw an error message using SIGNAL statement if we will try to enter the age of less than 0."
},
{
"code": null,
"e": 2671,
"s": 2341,
"text": "mysql> Create trigger before_insert_studentage BEFORE INSERT on\nstudent_age FOR EACH ROW BEGIN IF NEW.age<0 then SIGNAL SQLSTATE\n'45000' SET MESSAGE_TEXT = 'age less than 0'; END if; END; //\nQuery OK, 0 rows affected (0.12 sec)\n\nmysql> Insert into student_age(age, name) values(-10,'gaurav')//\nERROR 1644 (45000): age less than 0"
},
{
"code": null,
"e": 2807,
"s": 2671,
"text": "It is clear from the above result set that if we will try to insert age less than 0 then it will throw an error using SIGNAL statement."
}
] |
Set the width and margin of the modal with Bootstrap | Use the .modal-dialog class in Bootstrap to set the width and margin of the modal.
You can try to run the following code to implement .modal-dialog class −
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Example</title>
<link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class = "container">
<h2>Web Browser</h2>
<button type = "button" class = "btn btn-lg" data-toggle = "modal" data-target = "#new">More</button>
<div class = "modal fade" id="new" role = "dialog">
<div class = "modal-dialog">
<div class = "modal-content">
<div class = "modal-header">
<button type = "button" class = "close" data-dismiss = "modal">&times;</button>
<h4 class = "modal-title">Warning</h4>
</div>
<div class = "modal-body">
<p>If JavaScript isn't enabled in your web browser, then you may not be able to see this information correcty.</p>
</div>
<div class = "modal-footer">
<button type = "button" class = "btn btn-default" data-dismiss = "modal">Close</button>
</div>
</div>
</div>
</div>
</div>
</body>
</html> | [
{
"code": null,
"e": 1145,
"s": 1062,
"text": "Use the .modal-dialog class in Bootstrap to set the width and margin of the modal."
},
{
"code": null,
"e": 1218,
"s": 1145,
"text": "You can try to run the following code to implement .modal-dialog class −"
},
{
"code": null,
"e": 1228,
"s": 1218,
"text": "Live Demo"
},
{
"code": null,
"e": 2662,
"s": 1228,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link rel = \"stylesheet\" href = \"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\">\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src = \"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <div class = \"container\">\n <h2>Web Browser</h2>\n <button type = \"button\" class = \"btn btn-lg\" data-toggle = \"modal\" data-target = \"#new\">More</button>\n <div class = \"modal fade\" id=\"new\" role = \"dialog\">\n <div class = \"modal-dialog\">\n <div class = \"modal-content\">\n <div class = \"modal-header\">\n <button type = \"button\" class = \"close\" data-dismiss = \"modal\">&times;</button>\n <h4 class = \"modal-title\">Warning</h4>\n </div>\n <div class = \"modal-body\">\n <p>If JavaScript isn't enabled in your web browser, then you may not be able to see this information correcty.</p>\n </div>\n <div class = \"modal-footer\">\n <button type = \"button\" class = \"btn btn-default\" data-dismiss = \"modal\">Close</button>\n </div>\n </div>\n </div>\n </div>\n </div>\n </body>\n</html>"
}
] |
C++ Variable Types | A variable provides us with named storage that our programs can manipulate. Each variable in C++ has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.
The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because C++ is case-sensitive −
There are following basic types of variable in C++ as explained in last chapter −
bool
Stores either value true or false.
char
Typically a single octet (one byte). This is an integer type.
int
The most natural size of integer for the machine.
float
A single-precision floating point value.
double
A double-precision floating point value.
void
Represents the absence of type.
wchar_t
A wide character type.
C++ also allows to define various other types of variables, which we will cover in subsequent chapters like Enumeration, Pointer, Array, Reference, Data structures, and Classes.
Following section will cover how to define, declare and use various types of variables.
A variable definition tells the compiler where and how much storage to create for the variable. A variable definition specifies a data type, and contains a list of one or more variables of that type as follows −
type variable_list;
Here, type must be a valid C++ data type including char, w_char, int, float, double, bool or any user-defined object, etc., and variable_list may consist of one or more identifier names separated by commas. Some valid declarations are shown here −
int i, j, k;
char c, ch;
float f, salary;
double d;
The line int i, j, k; both declares and defines the variables i, j and k; which instructs the compiler to create variables named i, j and k of type int.
Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an equal sign followed by a constant expression as follows −
type variable_name = value;
Some examples are −
extern int d = 3, f = 5; // declaration of d and f.
int d = 3, f = 5; // definition and initializing d and f.
byte z = 22; // definition and initializes z.
char x = 'x'; // the variable x has the value 'x'.
For definition without an initializer: variables with static storage duration are implicitly initialized with NULL (all bytes have the value 0); the initial value of all other variables is undefined.
A variable declaration provides assurance to the compiler that there is one variable existing with the given type and name so that compiler proceed for further compilation without needing complete detail about the variable. A variable declaration has its meaning at the time of compilation only, compiler needs actual variable definition at the time of linking of the program.
A variable declaration is useful when you are using multiple files and you define your variable in one of the files which will be available at the time of linking of the program. You will use extern keyword to declare a variable at any place. Though you can declare a variable multiple times in your C++ program, but it can be defined only once in a file, a function or a block of code.
Try the following example where a variable has been declared at the top, but it has been defined inside the main function −
#include <iostream>
using namespace std;
// Variable declaration:
extern int a, b;
extern int c;
extern float f;
int main () {
// Variable definition:
int a, b;
int c;
float f;
// actual initialization
a = 10;
b = 20;
c = a + b;
cout << c << endl ;
f = 70.0/3.0;
cout << f << endl ;
return 0;
}
When the above code is compiled and executed, it produces the following result −
30
23.3333
Same concept applies on function declaration where you provide a function name at the time of its declaration and its actual definition can be given anywhere else. For example −
// function declaration
int func();
int main() {
// function call
int i = func();
}
// function definition
int func() {
return 0;
}
There are two kinds of expressions in C++ −
lvalue − Expressions that refer to a memory location is called "lvalue" expression. An lvalue may appear as either the left-hand or right-hand side of an assignment.
lvalue − Expressions that refer to a memory location is called "lvalue" expression. An lvalue may appear as either the left-hand or right-hand side of an assignment.
rvalue − The term rvalue refers to a data value that is stored at some address in memory. An rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear on the right- but not left-hand side of an assignment.
rvalue − The term rvalue refers to a data value that is stored at some address in memory. An rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear on the right- but not left-hand side of an assignment.
Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric literals are rvalues and so may not be assigned and can not appear on the left-hand side. Following is a valid statement −
int g = 20;
But the following is not a valid statement and would generate compile-time error −
10 = 20;
154 Lectures
11.5 hours
Arnab Chakraborty
14 Lectures
57 mins
Kaushik Roy Chowdhury
30 Lectures
12.5 hours
Frahaan Hussain
54 Lectures
3.5 hours
Frahaan Hussain
77 Lectures
5.5 hours
Frahaan Hussain
12 Lectures
3.5 hours
Frahaan Hussain
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2621,
"s": 2318,
"text": "A variable provides us with named storage that our programs can manipulate. Each variable in C++ has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable."
},
{
"code": null,
"e": 2836,
"s": 2621,
"text": "The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because C++ is case-sensitive −"
},
{
"code": null,
"e": 2918,
"s": 2836,
"text": "There are following basic types of variable in C++ as explained in last chapter −"
},
{
"code": null,
"e": 2923,
"s": 2918,
"text": "bool"
},
{
"code": null,
"e": 2958,
"s": 2923,
"text": "Stores either value true or false."
},
{
"code": null,
"e": 2963,
"s": 2958,
"text": "char"
},
{
"code": null,
"e": 3025,
"s": 2963,
"text": "Typically a single octet (one byte). This is an integer type."
},
{
"code": null,
"e": 3029,
"s": 3025,
"text": "int"
},
{
"code": null,
"e": 3079,
"s": 3029,
"text": "The most natural size of integer for the machine."
},
{
"code": null,
"e": 3085,
"s": 3079,
"text": "float"
},
{
"code": null,
"e": 3126,
"s": 3085,
"text": "A single-precision floating point value."
},
{
"code": null,
"e": 3133,
"s": 3126,
"text": "double"
},
{
"code": null,
"e": 3174,
"s": 3133,
"text": "A double-precision floating point value."
},
{
"code": null,
"e": 3179,
"s": 3174,
"text": "void"
},
{
"code": null,
"e": 3211,
"s": 3179,
"text": "Represents the absence of type."
},
{
"code": null,
"e": 3219,
"s": 3211,
"text": "wchar_t"
},
{
"code": null,
"e": 3242,
"s": 3219,
"text": "A wide character type."
},
{
"code": null,
"e": 3420,
"s": 3242,
"text": "C++ also allows to define various other types of variables, which we will cover in subsequent chapters like Enumeration, Pointer, Array, Reference, Data structures, and Classes."
},
{
"code": null,
"e": 3508,
"s": 3420,
"text": "Following section will cover how to define, declare and use various types of variables."
},
{
"code": null,
"e": 3720,
"s": 3508,
"text": "A variable definition tells the compiler where and how much storage to create for the variable. A variable definition specifies a data type, and contains a list of one or more variables of that type as follows −"
},
{
"code": null,
"e": 3741,
"s": 3720,
"text": "type variable_list;\n"
},
{
"code": null,
"e": 3989,
"s": 3741,
"text": "Here, type must be a valid C++ data type including char, w_char, int, float, double, bool or any user-defined object, etc., and variable_list may consist of one or more identifier names separated by commas. Some valid declarations are shown here −"
},
{
"code": null,
"e": 4048,
"s": 3989,
"text": "int i, j, k;\nchar c, ch;\nfloat f, salary;\ndouble d;\n"
},
{
"code": null,
"e": 4201,
"s": 4048,
"text": "The line int i, j, k; both declares and defines the variables i, j and k; which instructs the compiler to create variables named i, j and k of type int."
},
{
"code": null,
"e": 4369,
"s": 4201,
"text": "Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an equal sign followed by a constant expression as follows −"
},
{
"code": null,
"e": 4398,
"s": 4369,
"text": "type variable_name = value;\n"
},
{
"code": null,
"e": 4418,
"s": 4398,
"text": "Some examples are −"
},
{
"code": null,
"e": 4671,
"s": 4418,
"text": "extern int d = 3, f = 5; // declaration of d and f. \nint d = 3, f = 5; // definition and initializing d and f. \nbyte z = 22; // definition and initializes z. \nchar x = 'x'; // the variable x has the value 'x'.\n"
},
{
"code": null,
"e": 4871,
"s": 4671,
"text": "For definition without an initializer: variables with static storage duration are implicitly initialized with NULL (all bytes have the value 0); the initial value of all other variables is undefined."
},
{
"code": null,
"e": 5248,
"s": 4871,
"text": "A variable declaration provides assurance to the compiler that there is one variable existing with the given type and name so that compiler proceed for further compilation without needing complete detail about the variable. A variable declaration has its meaning at the time of compilation only, compiler needs actual variable definition at the time of linking of the program."
},
{
"code": null,
"e": 5635,
"s": 5248,
"text": "A variable declaration is useful when you are using multiple files and you define your variable in one of the files which will be available at the time of linking of the program. You will use extern keyword to declare a variable at any place. Though you can declare a variable multiple times in your C++ program, but it can be defined only once in a file, a function or a block of code."
},
{
"code": null,
"e": 5759,
"s": 5635,
"text": "Try the following example where a variable has been declared at the top, but it has been defined inside the main function −"
},
{
"code": null,
"e": 6101,
"s": 5759,
"text": "#include <iostream>\nusing namespace std;\n\n// Variable declaration:\nextern int a, b;\nextern int c;\nextern float f;\n \nint main () {\n // Variable definition:\n int a, b;\n int c;\n float f;\n \n // actual initialization\n a = 10;\n b = 20;\n c = a + b;\n \n cout << c << endl ;\n\n f = 70.0/3.0;\n cout << f << endl ;\n \n return 0;\n}"
},
{
"code": null,
"e": 6182,
"s": 6101,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 6194,
"s": 6182,
"text": "30\n23.3333\n"
},
{
"code": null,
"e": 6372,
"s": 6194,
"text": "Same concept applies on function declaration where you provide a function name at the time of its declaration and its actual definition can be given anywhere else. For example −"
},
{
"code": null,
"e": 6515,
"s": 6372,
"text": "// function declaration\nint func();\nint main() {\n // function call\n int i = func();\n}\n\n// function definition\nint func() {\n return 0;\n}\n"
},
{
"code": null,
"e": 6559,
"s": 6515,
"text": "There are two kinds of expressions in C++ −"
},
{
"code": null,
"e": 6726,
"s": 6559,
"text": "lvalue − Expressions that refer to a memory location is called \"lvalue\" expression. An lvalue may appear as either the left-hand or right-hand side of an assignment."
},
{
"code": null,
"e": 6893,
"s": 6726,
"text": "lvalue − Expressions that refer to a memory location is called \"lvalue\" expression. An lvalue may appear as either the left-hand or right-hand side of an assignment."
},
{
"code": null,
"e": 7138,
"s": 6893,
"text": "rvalue − The term rvalue refers to a data value that is stored at some address in memory. An rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear on the right- but not left-hand side of an assignment."
},
{
"code": null,
"e": 7383,
"s": 7138,
"text": "rvalue − The term rvalue refers to a data value that is stored at some address in memory. An rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear on the right- but not left-hand side of an assignment."
},
{
"code": null,
"e": 7594,
"s": 7383,
"text": "Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric literals are rvalues and so may not be assigned and can not appear on the left-hand side. Following is a valid statement −"
},
{
"code": null,
"e": 7607,
"s": 7594,
"text": "int g = 20;\n"
},
{
"code": null,
"e": 7690,
"s": 7607,
"text": "But the following is not a valid statement and would generate compile-time error −"
},
{
"code": null,
"e": 7700,
"s": 7690,
"text": "10 = 20;\n"
},
{
"code": null,
"e": 7737,
"s": 7700,
"text": "\n 154 Lectures \n 11.5 hours \n"
},
{
"code": null,
"e": 7756,
"s": 7737,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 7788,
"s": 7756,
"text": "\n 14 Lectures \n 57 mins\n"
},
{
"code": null,
"e": 7811,
"s": 7788,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 7847,
"s": 7811,
"text": "\n 30 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 7864,
"s": 7847,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 7899,
"s": 7864,
"text": "\n 54 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 7916,
"s": 7899,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 7951,
"s": 7916,
"text": "\n 77 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 7968,
"s": 7951,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 8003,
"s": 7968,
"text": "\n 12 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 8020,
"s": 8003,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 8027,
"s": 8020,
"text": " Print"
},
{
"code": null,
"e": 8038,
"s": 8027,
"text": " Add Notes"
}
] |
\ddot - Tex Command | \ddot - Used to draw double dot accent over the argument.
{ \ddot #1 }
\ddot command draws double dot accent over the argument.
\ddot x
x ̈
\ddot x
x ̈
\ddot x
14 Lectures
52 mins
Ashraf Said
11 Lectures
1 hours
Ashraf Said
9 Lectures
1 hours
Emenwa Global, Ejike IfeanyiChukwu
29 Lectures
2.5 hours
Mohammad Nauman
14 Lectures
1 hours
Daniel Stern
15 Lectures
47 mins
Nishant Kumar
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 8044,
"s": 7986,
"text": "\\ddot - Used to draw double dot accent over the argument."
},
{
"code": null,
"e": 8057,
"s": 8044,
"text": "{ \\ddot #1 }"
},
{
"code": null,
"e": 8114,
"s": 8057,
"text": "\\ddot command draws double dot accent over the argument."
},
{
"code": null,
"e": 8131,
"s": 8114,
"text": "\n\\ddot x\n\nx ̈\n\n\n"
},
{
"code": null,
"e": 8146,
"s": 8131,
"text": "\\ddot x\n\nx ̈\n\n"
},
{
"code": null,
"e": 8154,
"s": 8146,
"text": "\\ddot x"
},
{
"code": null,
"e": 8186,
"s": 8154,
"text": "\n 14 Lectures \n 52 mins\n"
},
{
"code": null,
"e": 8199,
"s": 8186,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8232,
"s": 8199,
"text": "\n 11 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8245,
"s": 8232,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8277,
"s": 8245,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8313,
"s": 8277,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 8348,
"s": 8313,
"text": "\n 29 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8365,
"s": 8348,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 8398,
"s": 8365,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8412,
"s": 8398,
"text": " Daniel Stern"
},
{
"code": null,
"e": 8444,
"s": 8412,
"text": "\n 15 Lectures \n 47 mins\n"
},
{
"code": null,
"e": 8459,
"s": 8444,
"text": " Nishant Kumar"
},
{
"code": null,
"e": 8466,
"s": 8459,
"text": " Print"
},
{
"code": null,
"e": 8477,
"s": 8466,
"text": " Add Notes"
}
] |
Convert Binary Number in a Linked List to Integer in C++ | Suppose we have one ‘head’ which is a reference node to a singly-linked list. The value of each node present in the linked list is either 0 or 1. This linked list stores the binary representation of a number. We have to return the decimal value of the number present in the linked list. So if the list is like [1,0,1,1,0,1]
To solve this, we will follow these steps −
x := convert the list elements into an array
x := convert the list elements into an array
then reverse the list x
then reverse the list x
ans := 0, and temp := 1
ans := 0, and temp := 1
for i in range i := 0, to size of x – 1ans := ans + x[i] * temptemp := temp * 2
for i in range i := 0, to size of x – 1
ans := ans + x[i] * temp
ans := ans + x[i] * temp
temp := temp * 2
temp := temp * 2
return ans
return ans
Let us see the following implementation to get a better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
class ListNode{
public:
int val;
ListNode *next;
ListNode(int data){
val = data;
next = NULL;
}
};
ListNode *make_list(vector<int> v){
ListNode *head = new ListNode(v[0]);
for(int i = 1; i<v.size(); i++){
ListNode *ptr = head;
while(ptr->next != NULL){
ptr = ptr->next;
}
ptr->next = new ListNode(v[i]);
}
return head;
}
class Solution {
public:
vector <int> getVector(ListNode* node){
vector <int> result;
while(node){
result.push_back(node->val);
node = node->next;
}
return result;
}
int getDecimalValue(ListNode* head) {
vector <int> x = getVector(head);
reverse(x.begin(), x.end());
int ans = 0;
int temp = 1;
for(int i = 0; i < x.size(); i++){
ans += x[i] * temp;
temp *= 2;
}
return ans;
}
};
main(){
Solution ob;
vector<int> v = {1,0,1,1,0,1};
ListNode *head = make_list(v);
cout << ob.getDecimalValue(head);
}
[1,0,1,1,0,1]
45 | [
{
"code": null,
"e": 1386,
"s": 1062,
"text": "Suppose we have one ‘head’ which is a reference node to a singly-linked list. The value of each node present in the linked list is either 0 or 1. This linked list stores the binary representation of a number. We have to return the decimal value of the number present in the linked list. So if the list is like [1,0,1,1,0,1]"
},
{
"code": null,
"e": 1430,
"s": 1386,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1475,
"s": 1430,
"text": "x := convert the list elements into an array"
},
{
"code": null,
"e": 1520,
"s": 1475,
"text": "x := convert the list elements into an array"
},
{
"code": null,
"e": 1544,
"s": 1520,
"text": "then reverse the list x"
},
{
"code": null,
"e": 1568,
"s": 1544,
"text": "then reverse the list x"
},
{
"code": null,
"e": 1592,
"s": 1568,
"text": "ans := 0, and temp := 1"
},
{
"code": null,
"e": 1616,
"s": 1592,
"text": "ans := 0, and temp := 1"
},
{
"code": null,
"e": 1696,
"s": 1616,
"text": "for i in range i := 0, to size of x – 1ans := ans + x[i] * temptemp := temp * 2"
},
{
"code": null,
"e": 1736,
"s": 1696,
"text": "for i in range i := 0, to size of x – 1"
},
{
"code": null,
"e": 1761,
"s": 1736,
"text": "ans := ans + x[i] * temp"
},
{
"code": null,
"e": 1786,
"s": 1761,
"text": "ans := ans + x[i] * temp"
},
{
"code": null,
"e": 1803,
"s": 1786,
"text": "temp := temp * 2"
},
{
"code": null,
"e": 1820,
"s": 1803,
"text": "temp := temp * 2"
},
{
"code": null,
"e": 1831,
"s": 1820,
"text": "return ans"
},
{
"code": null,
"e": 1842,
"s": 1831,
"text": "return ans"
},
{
"code": null,
"e": 1914,
"s": 1842,
"text": "Let us see the following implementation to get a better understanding −"
},
{
"code": null,
"e": 1925,
"s": 1914,
"text": " Live Demo"
},
{
"code": null,
"e": 3006,
"s": 1925,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nclass ListNode{\n public:\n int val;\n ListNode *next;\n ListNode(int data){\n val = data;\n next = NULL;\n }\n};\nListNode *make_list(vector<int> v){\n ListNode *head = new ListNode(v[0]);\n for(int i = 1; i<v.size(); i++){\n ListNode *ptr = head;\n while(ptr->next != NULL){\n ptr = ptr->next;\n }\n ptr->next = new ListNode(v[i]);\n }\n return head;\n}\nclass Solution {\npublic:\n vector <int> getVector(ListNode* node){\n vector <int> result;\n while(node){\n result.push_back(node->val);\n node = node->next;\n }\n return result;\n }\n int getDecimalValue(ListNode* head) {\n vector <int> x = getVector(head);\n reverse(x.begin(), x.end());\n int ans = 0;\n int temp = 1;\n for(int i = 0; i < x.size(); i++){\n ans += x[i] * temp;\n temp *= 2;\n }\n return ans;\n }\n};\nmain(){\n Solution ob;\n vector<int> v = {1,0,1,1,0,1};\n ListNode *head = make_list(v);\n cout << ob.getDecimalValue(head);\n}"
},
{
"code": null,
"e": 3020,
"s": 3006,
"text": "[1,0,1,1,0,1]"
},
{
"code": null,
"e": 3023,
"s": 3020,
"text": "45"
}
] |
Initialize a window as maximized in Tkinter Python | Tkinter creates a default window with its default size while initializing the application. We can customize the geometry of the window using the geometry method.
However, in order to maximize the window, we can use the state() method which can be used for scaling the tkinter window. It maximizes the window after passing the “zoomed” state value to it.
#Import the required libraries
from tkinter import *
#Create an instance of tkinter frame
win= Tk()
#Set the geometry of frame
win.geometry("600x400")
#Create a text label
Label(win,text="It takes only 21 days to create a new Habit", font=('Times
New Roman bold',15)).pack(pady=20)
#Maximize the window using state property
win.state('zoomed')
win.mainloop()
Running the above code will maximize the tkinter window. | [
{
"code": null,
"e": 1224,
"s": 1062,
"text": "Tkinter creates a default window with its default size while initializing the application. We can customize the geometry of the window using the geometry method."
},
{
"code": null,
"e": 1416,
"s": 1224,
"text": "However, in order to maximize the window, we can use the state() method which can be used for scaling the tkinter window. It maximizes the window after passing the “zoomed” state value to it."
},
{
"code": null,
"e": 1780,
"s": 1416,
"text": "#Import the required libraries\nfrom tkinter import *\n\n#Create an instance of tkinter frame\nwin= Tk()\n\n#Set the geometry of frame\nwin.geometry(\"600x400\")\n\n#Create a text label\nLabel(win,text=\"It takes only 21 days to create a new Habit\", font=('Times\nNew Roman bold',15)).pack(pady=20)\n\n#Maximize the window using state property\nwin.state('zoomed')\n\nwin.mainloop()"
},
{
"code": null,
"e": 1837,
"s": 1780,
"text": "Running the above code will maximize the tkinter window."
}
] |
Difference between 'and' and '&' in Python - GeeksforGeeks | 25 Jan, 2021
and is a Logical AND that returns True if both the operands are true whereas ‘&’ is a bitwise operator in Python that acts on bits and performs bit by bit operation.
Note: When an integer value is 0, it is considered as False otherwise True when using logically.
Example:
# Python program to demonstrate # the difference between and, & # operator a = 14b = 4 print(b and a) # print_stat1print(b & a) # print_stat2
Output:
14
4
This is because ‘and’ tests whether both expressions are logically True while ‘&’performs bitwise AND operation on the result of both statements.
In print statement 1, compiler checks if the first statement is True. If the first statement is False, it does not check the second statement and returns False immediately. This is known as “lazy evaluation”. If the first statement is True then the second condition is checked and according to rules of AND operation, True is the result only if both the statements are True. In the case of the above example, the compiler checks the 1st statement which is True as the value of b is 4, then the compiler moves towards the second statement which is also True because the value of a is 14. Hence, the output is also 14.
In print statement 2, the compiler is doing bitwise & operation of the results of statements. Here, the statement is getting evaluated as follows:The value of 4 in binary is 0000 0100 and the value of 14 in binary is 0000 1110. On performing bitwise and we get –
0000 0100
& = 0000 0100 = 4
0000 1110
Hence, the output is 4.
To elaborate on this, we can take another example.
Example:
# Python program to demonstrate# the difference between and, & # operator a, b = 9, 10print(a & b)#line 1print(a and b)#line 2
Output:
8
10
The first line is performing bitwise AND on a and b and the second line is evaluating the statement inside print and printing answer.In line 1, a = 1001, b = 1010, Performing & on a and b, gives us 1000 which is the binary value of decimal value 8.In line 2, the expression ‘a and b’ first evaluates a; if a is False (or Zero), its value is returned immediately because of “lazy evaluation” explained above, else, b is evaluated. If b is also non-zero then the resulting value is returned. The value of b is returned because it is the last value where checking ends for the truthfulness of the statement.Hence the use of boolean and ‘and’ is recommended in a loop.
shrishti_m180521ca
python-basics
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
How To Convert Python Dictionary To JSON? | [
{
"code": null,
"e": 24140,
"s": 24112,
"text": "\n25 Jan, 2021"
},
{
"code": null,
"e": 24306,
"s": 24140,
"text": "and is a Logical AND that returns True if both the operands are true whereas ‘&’ is a bitwise operator in Python that acts on bits and performs bit by bit operation."
},
{
"code": null,
"e": 24403,
"s": 24306,
"text": "Note: When an integer value is 0, it is considered as False otherwise True when using logically."
},
{
"code": null,
"e": 24412,
"s": 24403,
"text": "Example:"
},
{
"code": "# Python program to demonstrate # the difference between and, & # operator a = 14b = 4 print(b and a) # print_stat1print(b & a) # print_stat2",
"e": 24557,
"s": 24412,
"text": null
},
{
"code": null,
"e": 24565,
"s": 24557,
"text": "Output:"
},
{
"code": null,
"e": 24570,
"s": 24565,
"text": "14\n4"
},
{
"code": null,
"e": 24716,
"s": 24570,
"text": "This is because ‘and’ tests whether both expressions are logically True while ‘&’performs bitwise AND operation on the result of both statements."
},
{
"code": null,
"e": 25333,
"s": 24716,
"text": "In print statement 1, compiler checks if the first statement is True. If the first statement is False, it does not check the second statement and returns False immediately. This is known as “lazy evaluation”. If the first statement is True then the second condition is checked and according to rules of AND operation, True is the result only if both the statements are True. In the case of the above example, the compiler checks the 1st statement which is True as the value of b is 4, then the compiler moves towards the second statement which is also True because the value of a is 14. Hence, the output is also 14."
},
{
"code": null,
"e": 25596,
"s": 25333,
"text": "In print statement 2, the compiler is doing bitwise & operation of the results of statements. Here, the statement is getting evaluated as follows:The value of 4 in binary is 0000 0100 and the value of 14 in binary is 0000 1110. On performing bitwise and we get –"
},
{
"code": null,
"e": 25639,
"s": 25596,
"text": "0000 0100\n & = 0000 0100 = 4\n0000 1110\n"
},
{
"code": null,
"e": 25663,
"s": 25639,
"text": "Hence, the output is 4."
},
{
"code": null,
"e": 25714,
"s": 25663,
"text": "To elaborate on this, we can take another example."
},
{
"code": null,
"e": 25723,
"s": 25714,
"text": "Example:"
},
{
"code": "# Python program to demonstrate# the difference between and, & # operator a, b = 9, 10print(a & b)#line 1print(a and b)#line 2",
"e": 25851,
"s": 25723,
"text": null
},
{
"code": null,
"e": 25859,
"s": 25851,
"text": "Output:"
},
{
"code": null,
"e": 25864,
"s": 25859,
"text": "8\n10"
},
{
"code": null,
"e": 26529,
"s": 25864,
"text": "The first line is performing bitwise AND on a and b and the second line is evaluating the statement inside print and printing answer.In line 1, a = 1001, b = 1010, Performing & on a and b, gives us 1000 which is the binary value of decimal value 8.In line 2, the expression ‘a and b’ first evaluates a; if a is False (or Zero), its value is returned immediately because of “lazy evaluation” explained above, else, b is evaluated. If b is also non-zero then the resulting value is returned. The value of b is returned because it is the last value where checking ends for the truthfulness of the statement.Hence the use of boolean and ‘and’ is recommended in a loop."
},
{
"code": null,
"e": 26548,
"s": 26529,
"text": "shrishti_m180521ca"
},
{
"code": null,
"e": 26562,
"s": 26548,
"text": "python-basics"
},
{
"code": null,
"e": 26569,
"s": 26562,
"text": "Python"
},
{
"code": null,
"e": 26667,
"s": 26569,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26685,
"s": 26667,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26720,
"s": 26685,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26742,
"s": 26720,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26774,
"s": 26742,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26816,
"s": 26774,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26842,
"s": 26816,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26879,
"s": 26842,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 26923,
"s": 26879,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 26952,
"s": 26923,
"text": "*args and **kwargs in Python"
}
] |
Koko Eating Bananas in C++ | Suppose we have N piles of bananas, the i-th pile has piles[i] bananas. Here the guards have gone and will come back in H hours. Koko can decide her bananas-per-hour eating speed is K. Each hour, she takes some pile of bananas, and eats K bananas from that pile. If the pile has less than K bananas, then she consumes all of them instead, and won't eat any more bananas during this hour. Consider Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back. We have to find the minimum integer K such that she can eat all the bananas within H hours.
So if the input is like [3,6,7,11], and H = 8, then the output will be 4.
To solve this, we will follow these steps −
Define a method called ok(), this will take array a, two values x and h
Define a method called ok(), this will take array a, two values x and h
time := 0
time := 0
for i in range 0 to size of atime := time + a[i] / xtime := time + i when a[i] mod x is 0
for i in range 0 to size of a
time := time + a[i] / x
time := time + a[i] / x
time := time + i when a[i] mod x is 0
time := time + i when a[i] mod x is 0
return true when time <= H
return true when time <= H
From the main method do the following
From the main method do the following
n := size of the piles array, set sum := 0, low := 1, high := 0
n := size of the piles array, set sum := 0, low := 1, high := 0
for i in range 0 to n – 1high := max of piles[i] and high
for i in range 0 to n – 1
high := max of piles[i] and high
high := max of piles[i] and high
while low < highmid := low + (high – low ) /2if ok(piles, mid, H) is true, then set high := mid, otherwise low := mid + 1if ok(piles, mid, H) is true, then set high := mid, otherwise low := mid + 1
while low < high
mid := low + (high – low ) /2
mid := low + (high – low ) /2
if ok(piles, mid, H) is true, then set high := mid, otherwise low := mid + 1
if ok(piles, mid, H) is true, then set high := mid, otherwise low := mid + 1
if ok(piles, mid, H) is true, then set high := mid, otherwise low := mid + 1
if ok(piles, mid, H) is true, then set high := mid, otherwise low := mid + 1
return high
return high
Let us see the following implementation to get better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
typedef long long int lli;
class Solution {
public:
bool ok(vector <int>& a, int x, int H){
int time = 0;
for(int i = 0; i < a.size(); i++){
time += a[i] / x;
time += (a[i] % x ? 1 : 0);
}
return time <= H;
}
int minEatingSpeed(vector<int>& piles, int H) {
int n = piles.size();
lli low = 1;
lli sum = 0;
lli high = 0;
for(int i = 0; i < n; i++)high = max((lli)piles[i], high);
while(low < high){
int mid = low + (high - low) / 2;
if(ok(piles, mid, H)){
high = mid;
}else{
low = mid + 1;
}
}
return high;
}
};
main(){
vector<int> v = {3,6,7,11};
Solution ob;
cout << (ob.minEatingSpeed(v, 8));
}
[3,6,7,11]
8
4 | [
{
"code": null,
"e": 1655,
"s": 1062,
"text": "Suppose we have N piles of bananas, the i-th pile has piles[i] bananas. Here the guards have gone and will come back in H hours. Koko can decide her bananas-per-hour eating speed is K. Each hour, she takes some pile of bananas, and eats K bananas from that pile. If the pile has less than K bananas, then she consumes all of them instead, and won't eat any more bananas during this hour. Consider Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back. We have to find the minimum integer K such that she can eat all the bananas within H hours."
},
{
"code": null,
"e": 1729,
"s": 1655,
"text": "So if the input is like [3,6,7,11], and H = 8, then the output will be 4."
},
{
"code": null,
"e": 1773,
"s": 1729,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1845,
"s": 1773,
"text": "Define a method called ok(), this will take array a, two values x and h"
},
{
"code": null,
"e": 1917,
"s": 1845,
"text": "Define a method called ok(), this will take array a, two values x and h"
},
{
"code": null,
"e": 1927,
"s": 1917,
"text": "time := 0"
},
{
"code": null,
"e": 1937,
"s": 1927,
"text": "time := 0"
},
{
"code": null,
"e": 2027,
"s": 1937,
"text": "for i in range 0 to size of atime := time + a[i] / xtime := time + i when a[i] mod x is 0"
},
{
"code": null,
"e": 2057,
"s": 2027,
"text": "for i in range 0 to size of a"
},
{
"code": null,
"e": 2081,
"s": 2057,
"text": "time := time + a[i] / x"
},
{
"code": null,
"e": 2105,
"s": 2081,
"text": "time := time + a[i] / x"
},
{
"code": null,
"e": 2143,
"s": 2105,
"text": "time := time + i when a[i] mod x is 0"
},
{
"code": null,
"e": 2181,
"s": 2143,
"text": "time := time + i when a[i] mod x is 0"
},
{
"code": null,
"e": 2208,
"s": 2181,
"text": "return true when time <= H"
},
{
"code": null,
"e": 2235,
"s": 2208,
"text": "return true when time <= H"
},
{
"code": null,
"e": 2273,
"s": 2235,
"text": "From the main method do the following"
},
{
"code": null,
"e": 2311,
"s": 2273,
"text": "From the main method do the following"
},
{
"code": null,
"e": 2375,
"s": 2311,
"text": "n := size of the piles array, set sum := 0, low := 1, high := 0"
},
{
"code": null,
"e": 2439,
"s": 2375,
"text": "n := size of the piles array, set sum := 0, low := 1, high := 0"
},
{
"code": null,
"e": 2497,
"s": 2439,
"text": "for i in range 0 to n – 1high := max of piles[i] and high"
},
{
"code": null,
"e": 2523,
"s": 2497,
"text": "for i in range 0 to n – 1"
},
{
"code": null,
"e": 2556,
"s": 2523,
"text": "high := max of piles[i] and high"
},
{
"code": null,
"e": 2589,
"s": 2556,
"text": "high := max of piles[i] and high"
},
{
"code": null,
"e": 2787,
"s": 2589,
"text": "while low < highmid := low + (high – low ) /2if ok(piles, mid, H) is true, then set high := mid, otherwise low := mid + 1if ok(piles, mid, H) is true, then set high := mid, otherwise low := mid + 1"
},
{
"code": null,
"e": 2804,
"s": 2787,
"text": "while low < high"
},
{
"code": null,
"e": 2834,
"s": 2804,
"text": "mid := low + (high – low ) /2"
},
{
"code": null,
"e": 2864,
"s": 2834,
"text": "mid := low + (high – low ) /2"
},
{
"code": null,
"e": 2941,
"s": 2864,
"text": "if ok(piles, mid, H) is true, then set high := mid, otherwise low := mid + 1"
},
{
"code": null,
"e": 3018,
"s": 2941,
"text": "if ok(piles, mid, H) is true, then set high := mid, otherwise low := mid + 1"
},
{
"code": null,
"e": 3095,
"s": 3018,
"text": "if ok(piles, mid, H) is true, then set high := mid, otherwise low := mid + 1"
},
{
"code": null,
"e": 3172,
"s": 3095,
"text": "if ok(piles, mid, H) is true, then set high := mid, otherwise low := mid + 1"
},
{
"code": null,
"e": 3184,
"s": 3172,
"text": "return high"
},
{
"code": null,
"e": 3196,
"s": 3184,
"text": "return high"
},
{
"code": null,
"e": 3266,
"s": 3196,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 3277,
"s": 3266,
"text": " Live Demo"
},
{
"code": null,
"e": 4093,
"s": 3277,
"text": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long int lli;\nclass Solution {\n public:\n bool ok(vector <int>& a, int x, int H){\n int time = 0;\n for(int i = 0; i < a.size(); i++){\n time += a[i] / x;\n time += (a[i] % x ? 1 : 0);\n }\n return time <= H;\n }\n int minEatingSpeed(vector<int>& piles, int H) {\n int n = piles.size();\n lli low = 1;\n lli sum = 0;\n lli high = 0;\n for(int i = 0; i < n; i++)high = max((lli)piles[i], high);\n while(low < high){\n int mid = low + (high - low) / 2;\n if(ok(piles, mid, H)){\n high = mid;\n }else{\n low = mid + 1;\n }\n }\n return high;\n }\n};\nmain(){\n vector<int> v = {3,6,7,11};\n Solution ob;\n cout << (ob.minEatingSpeed(v, 8));\n}"
},
{
"code": null,
"e": 4106,
"s": 4093,
"text": "[3,6,7,11]\n8"
},
{
"code": null,
"e": 4108,
"s": 4106,
"text": "4"
}
] |
How to set background color of an android activity to yellow Programatically? | This example demonstrates how do I set background color of an android activity to yellow programmatically.
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.
<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:id="@+id/relativeLayout"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textStyle="bold"
android:textSize="24sp"
android:text="The color of the Activity is Yellow"/>
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.RelativeLayout;
public class MainActivity extends AppCompatActivity {
RelativeLayout relativeLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
relativeLayout = findViewById(R.id.relativeLayout);
relativeLayout.setBackgroundColor(Color.YELLOW);
}
}
Step 4 - Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code. | [
{
"code": null,
"e": 1169,
"s": 1062,
"text": "This example demonstrates how do I set background color of an android activity to yellow programmatically."
},
{
"code": null,
"e": 1298,
"s": 1169,
"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": 1363,
"s": 1298,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1919,
"s": 1363,
"text": "<RelativeLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:id=\"@+id/relativeLayout\"\n tools:context=\".MainActivity\">\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:textStyle=\"bold\"\n android:textSize=\"24sp\"\n android:text=\"The color of the Activity is Yellow\"/>\n</RelativeLayout>"
},
{
"code": null,
"e": 1976,
"s": 1919,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 2485,
"s": 1976,
"text": "import android.graphics.Color;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.widget.RelativeLayout;\npublic class MainActivity extends AppCompatActivity {\n RelativeLayout relativeLayout;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n relativeLayout = findViewById(R.id.relativeLayout);\n relativeLayout.setBackgroundColor(Color.YELLOW);\n }\n}"
},
{
"code": null,
"e": 2540,
"s": 2485,
"text": "Step 4 - Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3213,
"s": 2540,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 3560,
"s": 3213,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –"
},
{
"code": null,
"e": 3601,
"s": 3560,
"text": "Click here to download the project code."
}
] |
How to Speed Up Android Studio? - GeeksforGeeks | 30 Nov, 2021
A slow Android Studio is a pain in the butt for an android developer. Developing an application with a slow IDE is not a cakewalk. It’s also annoying that when you are focusing on the logic building for your app, and you got a kick to work and at that time your android studio suddenly starts lagging. You will really not feel good at that time. In the previous versions, the android studio was more heavy software Google is updating it and making it more scalable for developers. But it is even also heavy software which will suck your computer’s ram. If your pc is not having a high configuration you can’t run other applications like Google Chrome when your android studio is running. If you try to do so then your pc will start hanging.
In this article, we will try our best to solve this problem. We will try to set up an android studio like a charm so that we can run a smoother development environment. It will save our time in developing an application and will also not be going through a painful process at the time of development.
Minimum space and configuration requirements: Officially android studio requires a minimum of 4GB RAM but 8GB RAM is recommended for it. It also requires a minimum of 2GB Disk Space but 4GB Disk Space is recommended for it. But these are the minimum requirements.
It’s been observed many times that android studio is actively consuming ram of 4GB. So, First of all, we have to think that, in order to speed up the android studio what are the steps we have to take. This article will be divided into two parts in the first part we will see that how can we speed up the build process of android studio and in the second part we will know that how can we fast this slow and heavy software called the android studio.
The Gradle build is the most important part of developing an android application. Sometimes it takes much more time than it should then it becomes a painful process. These are the few best tips to reduce the Gradle Build time.
Step 1: Enable Offline Work
Many times we don’t need to go with the online build process of the Gradle we can do it offline. Why not do it in offline mode. It will save our time and escape the unnecessary checks for the dependencies. We can always enable the online build process when we require this. We can turn it off for now. Go to View >> Tool Windows >> Gradle and then click on the icon Toggle Offline Mode. Again clicking on the icon will off Offline Mode.
Step 2: Enable Gradle Daemon and Parallel Build
Enabling Parallel Build will reduce Gradle build timings cause it will build modules parallelly. Enabling the Gradle Daemon will also help to speed up the build process. Go to Gradle Scripts >> gradle.properties and add these two lines of code.
Java
# When configured, Gradle will run in incubating parallel mode.# This option should only be used with decoupled projects.org.gradle.parallel=true # When set to true the Gradle daemon is used to run the build. For local developer builds this is our favorite property.# The developer environment is optimized for speed and feedback so we nearly always run Gradle jobs with the daemon.org.gradle.daemon=true
Step 3: Enable Incremental Dexing
Turning on Incremental Dexing will also speed up the build process of the application. Go to build.gradle(module:app) and add this block.
Java
dexOptions { incremental true}
Note: From Android Gradle Plugin 8.0 onward, there is no need to use dexOptions as the AndroidGradle plugin optimizes dexing automatically. Therefore using it has no effect.
Step 4: Disable Antivirus
In the Gradle build process, the android studio needs to access multiple files repeatedly. An antivirus is by default don’t giving direct access to the android studio to those files it will check the file and then it gives the access. The procedure of checking files first and then giving access to android studio slows down the process of Gradle build. So if you are confident enough that on your pc you haven’t downloaded any malware files from unauthorized websites or locations then you can turn the antivirus off. It will also help in speeding up the process of the Gradle Build. I think there’s no need to tell you that how can you turn off the antivirus of your pc you would be knowing that.
Step 5: Disable Proxy Server of Android Studio
By default proxy server is off in the android studio, but in some cases, your proxy server may be on. Disabling it will help to run a smoother build process. For disable it, Go to File >> Settings >> Appearance and Behaviour >> System Settings >> HTTP Proxy and Select No Proxy.
We have done some factful settings for speeding up the Gradle Build process. Now let’s do some settings which can help us to make our Android Studio Faster.
Step 1: Disable Useless Plugins
There may be many plugins in Android Studio that you are not using it. Disabling it will free up some space and reduce complex processes. To do so, Open Preferences >> Plugins and Disable the plugins you are not using.
Step 2: Use SSD
A solid-state drive is a great product in which you can invest. It will not only fast up your android studio it will also fast your PC 2 to 3 times. SSD has really faster than Hard disk drives.
Step 3: Adjust memory setting
Go to Appearance & Behavior >> System Settings >> Memory Settings. Tweak these settings according to your preference. Increasing a little bit of heap size can help. Too much heap allocation is also not a good thing.
Step 4: Ignore Thumbs.db
Go to File>> Settings>> Editor>> File Types>> and in Field of Ignore files and Folders add Thumbs.db. It also can speed up your Android Studio.
Step 5: Free Up Space and Cache
For clearing the Gradle Cache:
On Windows:
%USERPROFILE%\.gradle\caches
On Mac:
/ UNIX: ~/.gradle/caches/
For Clearing the cache of the whole android studio:
File >> Invalidate Cache and Restart.
Step 6: Delete Unused and Unwanted Projects
In our android studio projects folder, many junk apps can also exist which we have created somehow but we have not done any work on those apps. The apps that exist are not needed for you then you can delete these unwanted apps it will free up space and remove a little unwanted load from android studio. For doing so, check the following path:
C:\Users\%USER%\AndroidStudioProjects
and delete those junk apps.
Step 7: Try to use a single project at a time
We have talked before on the topic that how much heavy software is the android studio and how heavy the process is the gradle build of the application. If we are not having a high configuration PC then we should not work on many apps at the same time and also should not do the gradle build for two applications at a time. If we are doing so then it may cause that our pc can be hanged. We should work on a single project at a time.
Step 8: Try to run the application on a physical device instead of an emulator
Android studio provides the emulators for running our application for development purposes. Emulators provided by them will also be putting an extra load and make android studio bulky which can be a cause for the hanging of android studio. We should run our application on a physical device instead of that emulator it will lead to a smooth development process. You can refer to the article How to Run the Android App on a Real Device?
Step 9: Update android studio
Google is also trying to make smoother and faster IDE for the Development. He is trying to update its algorithms and make the android studio as fast it can be. So updating to the latest version is a useful step for you if you are running on the older versions. So you should keep your Android Studio Updated.
duttabhishek0
Android-Studio
Picked
Android
GBlog
TechTips
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Flutter - Custom Bottom Navigation Bar
Retrofit with Kotlin Coroutine in Android
GridView in Android with Example
How to Change the Background Color After Clicking the Button in Android?
Android Listview in Java with Example
Roadmap to Become a Web Developer in 2022
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
Socket Programming in C/C++
DSA Sheet by Love Babbar
GET and POST requests using Python | [
{
"code": null,
"e": 25140,
"s": 25112,
"text": "\n30 Nov, 2021"
},
{
"code": null,
"e": 25881,
"s": 25140,
"text": "A slow Android Studio is a pain in the butt for an android developer. Developing an application with a slow IDE is not a cakewalk. It’s also annoying that when you are focusing on the logic building for your app, and you got a kick to work and at that time your android studio suddenly starts lagging. You will really not feel good at that time. In the previous versions, the android studio was more heavy software Google is updating it and making it more scalable for developers. But it is even also heavy software which will suck your computer’s ram. If your pc is not having a high configuration you can’t run other applications like Google Chrome when your android studio is running. If you try to do so then your pc will start hanging."
},
{
"code": null,
"e": 26183,
"s": 25881,
"text": "In this article, we will try our best to solve this problem. We will try to set up an android studio like a charm so that we can run a smoother development environment. It will save our time in developing an application and will also not be going through a painful process at the time of development. "
},
{
"code": null,
"e": 26448,
"s": 26183,
"text": "Minimum space and configuration requirements: Officially android studio requires a minimum of 4GB RAM but 8GB RAM is recommended for it. It also requires a minimum of 2GB Disk Space but 4GB Disk Space is recommended for it. But these are the minimum requirements. "
},
{
"code": null,
"e": 26897,
"s": 26448,
"text": "It’s been observed many times that android studio is actively consuming ram of 4GB. So, First of all, we have to think that, in order to speed up the android studio what are the steps we have to take. This article will be divided into two parts in the first part we will see that how can we speed up the build process of android studio and in the second part we will know that how can we fast this slow and heavy software called the android studio."
},
{
"code": null,
"e": 27124,
"s": 26897,
"text": "The Gradle build is the most important part of developing an android application. Sometimes it takes much more time than it should then it becomes a painful process. These are the few best tips to reduce the Gradle Build time."
},
{
"code": null,
"e": 27152,
"s": 27124,
"text": "Step 1: Enable Offline Work"
},
{
"code": null,
"e": 27589,
"s": 27152,
"text": "Many times we don’t need to go with the online build process of the Gradle we can do it offline. Why not do it in offline mode. It will save our time and escape the unnecessary checks for the dependencies. We can always enable the online build process when we require this. We can turn it off for now. Go to View >> Tool Windows >> Gradle and then click on the icon Toggle Offline Mode. Again clicking on the icon will off Offline Mode."
},
{
"code": null,
"e": 27637,
"s": 27589,
"text": "Step 2: Enable Gradle Daemon and Parallel Build"
},
{
"code": null,
"e": 27882,
"s": 27637,
"text": "Enabling Parallel Build will reduce Gradle build timings cause it will build modules parallelly. Enabling the Gradle Daemon will also help to speed up the build process. Go to Gradle Scripts >> gradle.properties and add these two lines of code."
},
{
"code": null,
"e": 27887,
"s": 27882,
"text": "Java"
},
{
"code": "# When configured, Gradle will run in incubating parallel mode.# This option should only be used with decoupled projects.org.gradle.parallel=true # When set to true the Gradle daemon is used to run the build. For local developer builds this is our favorite property.# The developer environment is optimized for speed and feedback so we nearly always run Gradle jobs with the daemon.org.gradle.daemon=true",
"e": 28292,
"s": 27887,
"text": null
},
{
"code": null,
"e": 28326,
"s": 28292,
"text": "Step 3: Enable Incremental Dexing"
},
{
"code": null,
"e": 28464,
"s": 28326,
"text": "Turning on Incremental Dexing will also speed up the build process of the application. Go to build.gradle(module:app) and add this block."
},
{
"code": null,
"e": 28469,
"s": 28464,
"text": "Java"
},
{
"code": "dexOptions { incremental true}",
"e": 28503,
"s": 28469,
"text": null
},
{
"code": null,
"e": 28678,
"s": 28503,
"text": "Note: From Android Gradle Plugin 8.0 onward, there is no need to use dexOptions as the AndroidGradle plugin optimizes dexing automatically. Therefore using it has no effect. "
},
{
"code": null,
"e": 28705,
"s": 28678,
"text": "Step 4: Disable Antivirus "
},
{
"code": null,
"e": 29404,
"s": 28705,
"text": "In the Gradle build process, the android studio needs to access multiple files repeatedly. An antivirus is by default don’t giving direct access to the android studio to those files it will check the file and then it gives the access. The procedure of checking files first and then giving access to android studio slows down the process of Gradle build. So if you are confident enough that on your pc you haven’t downloaded any malware files from unauthorized websites or locations then you can turn the antivirus off. It will also help in speeding up the process of the Gradle Build. I think there’s no need to tell you that how can you turn off the antivirus of your pc you would be knowing that."
},
{
"code": null,
"e": 29451,
"s": 29404,
"text": "Step 5: Disable Proxy Server of Android Studio"
},
{
"code": null,
"e": 29731,
"s": 29451,
"text": "By default proxy server is off in the android studio, but in some cases, your proxy server may be on. Disabling it will help to run a smoother build process. For disable it, Go to File >> Settings >> Appearance and Behaviour >> System Settings >> HTTP Proxy and Select No Proxy. "
},
{
"code": null,
"e": 29888,
"s": 29731,
"text": "We have done some factful settings for speeding up the Gradle Build process. Now let’s do some settings which can help us to make our Android Studio Faster."
},
{
"code": null,
"e": 29920,
"s": 29888,
"text": "Step 1: Disable Useless Plugins"
},
{
"code": null,
"e": 30139,
"s": 29920,
"text": "There may be many plugins in Android Studio that you are not using it. Disabling it will free up some space and reduce complex processes. To do so, Open Preferences >> Plugins and Disable the plugins you are not using."
},
{
"code": null,
"e": 30155,
"s": 30139,
"text": "Step 2: Use SSD"
},
{
"code": null,
"e": 30349,
"s": 30155,
"text": "A solid-state drive is a great product in which you can invest. It will not only fast up your android studio it will also fast your PC 2 to 3 times. SSD has really faster than Hard disk drives."
},
{
"code": null,
"e": 30379,
"s": 30349,
"text": "Step 3: Adjust memory setting"
},
{
"code": null,
"e": 30595,
"s": 30379,
"text": "Go to Appearance & Behavior >> System Settings >> Memory Settings. Tweak these settings according to your preference. Increasing a little bit of heap size can help. Too much heap allocation is also not a good thing."
},
{
"code": null,
"e": 30620,
"s": 30595,
"text": "Step 4: Ignore Thumbs.db"
},
{
"code": null,
"e": 30764,
"s": 30620,
"text": "Go to File>> Settings>> Editor>> File Types>> and in Field of Ignore files and Folders add Thumbs.db. It also can speed up your Android Studio."
},
{
"code": null,
"e": 30796,
"s": 30764,
"text": "Step 5: Free Up Space and Cache"
},
{
"code": null,
"e": 30827,
"s": 30796,
"text": "For clearing the Gradle Cache:"
},
{
"code": null,
"e": 30840,
"s": 30827,
"text": "On Windows: "
},
{
"code": null,
"e": 30869,
"s": 30840,
"text": "%USERPROFILE%\\.gradle\\caches"
},
{
"code": null,
"e": 30877,
"s": 30869,
"text": "On Mac:"
},
{
"code": null,
"e": 30904,
"s": 30877,
"text": "/ UNIX: ~/.gradle/caches/ "
},
{
"code": null,
"e": 30956,
"s": 30904,
"text": "For Clearing the cache of the whole android studio:"
},
{
"code": null,
"e": 30994,
"s": 30956,
"text": "File >> Invalidate Cache and Restart."
},
{
"code": null,
"e": 31039,
"s": 30994,
"text": "Step 6: Delete Unused and Unwanted Projects "
},
{
"code": null,
"e": 31383,
"s": 31039,
"text": "In our android studio projects folder, many junk apps can also exist which we have created somehow but we have not done any work on those apps. The apps that exist are not needed for you then you can delete these unwanted apps it will free up space and remove a little unwanted load from android studio. For doing so, check the following path:"
},
{
"code": null,
"e": 31422,
"s": 31383,
"text": "C:\\Users\\%USER%\\AndroidStudioProjects "
},
{
"code": null,
"e": 31450,
"s": 31422,
"text": "and delete those junk apps."
},
{
"code": null,
"e": 31496,
"s": 31450,
"text": "Step 7: Try to use a single project at a time"
},
{
"code": null,
"e": 31930,
"s": 31496,
"text": "We have talked before on the topic that how much heavy software is the android studio and how heavy the process is the gradle build of the application. If we are not having a high configuration PC then we should not work on many apps at the same time and also should not do the gradle build for two applications at a time. If we are doing so then it may cause that our pc can be hanged. We should work on a single project at a time. "
},
{
"code": null,
"e": 32009,
"s": 31930,
"text": "Step 8: Try to run the application on a physical device instead of an emulator"
},
{
"code": null,
"e": 32445,
"s": 32009,
"text": "Android studio provides the emulators for running our application for development purposes. Emulators provided by them will also be putting an extra load and make android studio bulky which can be a cause for the hanging of android studio. We should run our application on a physical device instead of that emulator it will lead to a smooth development process. You can refer to the article How to Run the Android App on a Real Device?"
},
{
"code": null,
"e": 32475,
"s": 32445,
"text": "Step 9: Update android studio"
},
{
"code": null,
"e": 32785,
"s": 32475,
"text": "Google is also trying to make smoother and faster IDE for the Development. He is trying to update its algorithms and make the android studio as fast it can be. So updating to the latest version is a useful step for you if you are running on the older versions. So you should keep your Android Studio Updated. "
},
{
"code": null,
"e": 32799,
"s": 32785,
"text": "duttabhishek0"
},
{
"code": null,
"e": 32814,
"s": 32799,
"text": "Android-Studio"
},
{
"code": null,
"e": 32821,
"s": 32814,
"text": "Picked"
},
{
"code": null,
"e": 32829,
"s": 32821,
"text": "Android"
},
{
"code": null,
"e": 32835,
"s": 32829,
"text": "GBlog"
},
{
"code": null,
"e": 32844,
"s": 32835,
"text": "TechTips"
},
{
"code": null,
"e": 32852,
"s": 32844,
"text": "Android"
},
{
"code": null,
"e": 32950,
"s": 32852,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32959,
"s": 32950,
"text": "Comments"
},
{
"code": null,
"e": 32972,
"s": 32959,
"text": "Old Comments"
},
{
"code": null,
"e": 33011,
"s": 32972,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 33053,
"s": 33011,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 33086,
"s": 33053,
"text": "GridView in Android with Example"
},
{
"code": null,
"e": 33159,
"s": 33086,
"text": "How to Change the Background Color After Clicking the Button in Android?"
},
{
"code": null,
"e": 33197,
"s": 33159,
"text": "Android Listview in Java with Example"
},
{
"code": null,
"e": 33239,
"s": 33197,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 33313,
"s": 33239,
"text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..."
},
{
"code": null,
"e": 33341,
"s": 33313,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 33366,
"s": 33341,
"text": "DSA Sheet by Love Babbar"
}
] |
What are the high level I/O functions in C language? | I/O refers to the input - output functions in C language.
These are easily understood by human beings
The advantage is portability.
These are easily understood by computer.
The advantage is that execution time is less.
The disadvantage is that Non portability.
The high level input - output (I/O) functions are explained below −
fprintf ( )
The syntax is as follows −
fprintf (file pointer, " control string”, variable list)
For example,
FILE *fp;
fprintf (fp, "%d%c”, a,b);
fscanf ( )
The syntax is as follows −
fscanf(file pointer, "control string”, & variable list);
For example,
FILE *fp;
fscanf (fp, "%d%c”, &a,&b);
putc ( )
It is used for writing a character into a file.
The syntax is as follows −
putc (char ch, FILE *fp);
For example,
FILE *fp;
char ch;
putc(ch, fp);
get c ( )
It is used to read a character from file.
The syntax is as follows −
char getc (FILE *fp);
For example,
FILE *fp;
char ch;
ch = getc(fp);
putw( )
It is used for writing a number into file.
The syntax is as follows −
putw (int num, FILE *fp);
For example,
FILE *fp;
int num;
putw(num, fp);
getw ( )
It is used for reading a number from a file.
The syntax is as follows −
int getw (FILE *fp);
For example,
FILE *fp;
int num;
num = getw(fp);
fputc( )
It is used for writing a character in to a file.
The syntax is as follows −
fputc (char ch, FILE *fp);
For example,
FILE *fp;
char ch;
fputc (ch.fp);
fgetc( )
It is used for reading a character from a file.
The syntax is as follows −
fputc (char ch, FILE *fp);
For example,
FILE *fp;
char ch;
ch = fgetc(fp);
fgets ( )
It is used for reading a string from a file.
The syntax is as follows
fgets (string variable, No. of characters, File pointer);
For example,
FILE *fp;
char str [30];
fgets (str,30,fp);
fputs ( )
It is used for writing a string into a file.
The syntax is as follows −
fputs (string variable, file pointer);
For example,
FILE *fp;
char str[30];
fputs (str,fp);
fread ( )
It is used for reading entire record at a time.
The syntax is as follows −
fread( & structure variable, size of (structure variable), no of records, file pointer);
For example,
struct emp{
int eno;
char ename [30];
float sal;
} e;
FILE *fp;
fread (&e, sizeof (e), 1, fp);
fwrite ( )
It is used for writing an entire record at a time.
The syntax is as follows −
fwrite( & structure variable , size of structure variable, no of records, file pointer);
For example,
struct emp{
int eno:
char ename [30];
float sal;
} e;
FILE *fp;
fwrite (&e, sizeof(e), 1, fp);
Following is the C program for storing numbers from 1 to 10 and to print the same −
//Program for storing no’s from 1 to 10 and print the same
#include<stdio.h>
int main( ){
FILE *fp;
int i;
fp = fopen ("num.txt", "w");
for (i =1; i<= 10; i++){
putw (i, fp);
}
fclose (fp);
fp =fopen ("num.txt", "r");
printf ("file content is");
for (i =1; i<= 10; i++){
i= getw(fp);
printf ("%d",i);
}
fclose (fp);
return 0;
}
When the above program is executed, it produces the following result −
file content is12345678910
Given below is another C program for storing the details of 5 students into a file and print the same by using fread ( ) and fwrite ( ) −
#include<stdio.h>
struct student{
int sno;
char sname [30];
float marks;
char temp;
};
main ( ){
struct student s[60];
int i;
FILE *fp;
fp = fopen ("student1.txt", "w");
for (i=0; i<2; i++){
printf ("enter details of student %d\n", i+1);
printf("student number:");
scanf("%d",&s[i].sno);
scanf("%c",&s[i].temp);
printf("student name:");
gets(s[i].sname);
printf("student marks:");
scanf("%f",&s[i].marks);
fwrite(&s[i], sizeof(s[i]),1,fp);
}
fclose (fp);
fp = fopen ("student1.txt", "r");
for (i=0; i<2; i++){
printf ("details of student %d are\n", i+1);
fread (&s[i], sizeof (s[i]) ,1,fp);
printf("student number = %d\n", s[i]. sno);
printf("student name = %s\n", s[i]. sname);
printf("marks = %f\n", s[i]. marks);
}
fclose(fp);
getch( );
}
When the above program is executed, it produces the following result −
enter details of student 1
student number:1
student name:bhanu
student marks:50
enter details of student 2
student number:2
student name:priya
student marks:69
details of student 1 are
student number = 1
student name = bhanu
marks = 50.000000
details of student 2 are
student number = 2
student name = priya
marks = 69.000000 | [
{
"code": null,
"e": 1120,
"s": 1062,
"text": "I/O refers to the input - output functions in C language."
},
{
"code": null,
"e": 1164,
"s": 1120,
"text": "These are easily understood by human beings"
},
{
"code": null,
"e": 1194,
"s": 1164,
"text": "The advantage is portability."
},
{
"code": null,
"e": 1235,
"s": 1194,
"text": "These are easily understood by computer."
},
{
"code": null,
"e": 1281,
"s": 1235,
"text": "The advantage is that execution time is less."
},
{
"code": null,
"e": 1323,
"s": 1281,
"text": "The disadvantage is that Non portability."
},
{
"code": null,
"e": 1391,
"s": 1323,
"text": "The high level input - output (I/O) functions are explained below −"
},
{
"code": null,
"e": 1403,
"s": 1391,
"text": "fprintf ( )"
},
{
"code": null,
"e": 1430,
"s": 1403,
"text": "The syntax is as follows −"
},
{
"code": null,
"e": 1487,
"s": 1430,
"text": "fprintf (file pointer, \" control string”, variable list)"
},
{
"code": null,
"e": 1500,
"s": 1487,
"text": "For example,"
},
{
"code": null,
"e": 1537,
"s": 1500,
"text": "FILE *fp;\nfprintf (fp, \"%d%c”, a,b);"
},
{
"code": null,
"e": 1548,
"s": 1537,
"text": "fscanf ( )"
},
{
"code": null,
"e": 1575,
"s": 1548,
"text": "The syntax is as follows −"
},
{
"code": null,
"e": 1632,
"s": 1575,
"text": "fscanf(file pointer, \"control string”, & variable list);"
},
{
"code": null,
"e": 1645,
"s": 1632,
"text": "For example,"
},
{
"code": null,
"e": 1683,
"s": 1645,
"text": "FILE *fp;\nfscanf (fp, \"%d%c”, &a,&b);"
},
{
"code": null,
"e": 1692,
"s": 1683,
"text": "putc ( )"
},
{
"code": null,
"e": 1740,
"s": 1692,
"text": "It is used for writing a character into a file."
},
{
"code": null,
"e": 1767,
"s": 1740,
"text": "The syntax is as follows −"
},
{
"code": null,
"e": 1793,
"s": 1767,
"text": "putc (char ch, FILE *fp);"
},
{
"code": null,
"e": 1806,
"s": 1793,
"text": "For example,"
},
{
"code": null,
"e": 1839,
"s": 1806,
"text": "FILE *fp;\nchar ch;\nputc(ch, fp);"
},
{
"code": null,
"e": 1849,
"s": 1839,
"text": "get c ( )"
},
{
"code": null,
"e": 1891,
"s": 1849,
"text": "It is used to read a character from file."
},
{
"code": null,
"e": 1918,
"s": 1891,
"text": "The syntax is as follows −"
},
{
"code": null,
"e": 1940,
"s": 1918,
"text": "char getc (FILE *fp);"
},
{
"code": null,
"e": 1953,
"s": 1940,
"text": "For example,"
},
{
"code": null,
"e": 1987,
"s": 1953,
"text": "FILE *fp;\nchar ch;\nch = getc(fp);"
},
{
"code": null,
"e": 1995,
"s": 1987,
"text": "putw( )"
},
{
"code": null,
"e": 2038,
"s": 1995,
"text": "It is used for writing a number into file."
},
{
"code": null,
"e": 2065,
"s": 2038,
"text": "The syntax is as follows −"
},
{
"code": null,
"e": 2091,
"s": 2065,
"text": "putw (int num, FILE *fp);"
},
{
"code": null,
"e": 2104,
"s": 2091,
"text": "For example,"
},
{
"code": null,
"e": 2138,
"s": 2104,
"text": "FILE *fp;\nint num;\nputw(num, fp);"
},
{
"code": null,
"e": 2147,
"s": 2138,
"text": "getw ( )"
},
{
"code": null,
"e": 2192,
"s": 2147,
"text": "It is used for reading a number from a file."
},
{
"code": null,
"e": 2219,
"s": 2192,
"text": "The syntax is as follows −"
},
{
"code": null,
"e": 2240,
"s": 2219,
"text": "int getw (FILE *fp);"
},
{
"code": null,
"e": 2253,
"s": 2240,
"text": "For example,"
},
{
"code": null,
"e": 2288,
"s": 2253,
"text": "FILE *fp;\nint num;\nnum = getw(fp);"
},
{
"code": null,
"e": 2297,
"s": 2288,
"text": "fputc( )"
},
{
"code": null,
"e": 2346,
"s": 2297,
"text": "It is used for writing a character in to a file."
},
{
"code": null,
"e": 2373,
"s": 2346,
"text": "The syntax is as follows −"
},
{
"code": null,
"e": 2400,
"s": 2373,
"text": "fputc (char ch, FILE *fp);"
},
{
"code": null,
"e": 2413,
"s": 2400,
"text": "For example,"
},
{
"code": null,
"e": 2447,
"s": 2413,
"text": "FILE *fp;\nchar ch;\nfputc (ch.fp);"
},
{
"code": null,
"e": 2456,
"s": 2447,
"text": "fgetc( )"
},
{
"code": null,
"e": 2504,
"s": 2456,
"text": "It is used for reading a character from a file."
},
{
"code": null,
"e": 2531,
"s": 2504,
"text": "The syntax is as follows −"
},
{
"code": null,
"e": 2558,
"s": 2531,
"text": "fputc (char ch, FILE *fp);"
},
{
"code": null,
"e": 2571,
"s": 2558,
"text": "For example,"
},
{
"code": null,
"e": 2606,
"s": 2571,
"text": "FILE *fp;\nchar ch;\nch = fgetc(fp);"
},
{
"code": null,
"e": 2616,
"s": 2606,
"text": "fgets ( )"
},
{
"code": null,
"e": 2661,
"s": 2616,
"text": "It is used for reading a string from a file."
},
{
"code": null,
"e": 2686,
"s": 2661,
"text": "The syntax is as follows"
},
{
"code": null,
"e": 2744,
"s": 2686,
"text": "fgets (string variable, No. of characters, File pointer);"
},
{
"code": null,
"e": 2757,
"s": 2744,
"text": "For example,"
},
{
"code": null,
"e": 2801,
"s": 2757,
"text": "FILE *fp;\nchar str [30];\nfgets (str,30,fp);"
},
{
"code": null,
"e": 2811,
"s": 2801,
"text": "fputs ( )"
},
{
"code": null,
"e": 2856,
"s": 2811,
"text": "It is used for writing a string into a file."
},
{
"code": null,
"e": 2883,
"s": 2856,
"text": "The syntax is as follows −"
},
{
"code": null,
"e": 2922,
"s": 2883,
"text": "fputs (string variable, file pointer);"
},
{
"code": null,
"e": 2935,
"s": 2922,
"text": "For example,"
},
{
"code": null,
"e": 2975,
"s": 2935,
"text": "FILE *fp;\nchar str[30];\nfputs (str,fp);"
},
{
"code": null,
"e": 2985,
"s": 2975,
"text": "fread ( )"
},
{
"code": null,
"e": 3033,
"s": 2985,
"text": "It is used for reading entire record at a time."
},
{
"code": null,
"e": 3060,
"s": 3033,
"text": "The syntax is as follows −"
},
{
"code": null,
"e": 3149,
"s": 3060,
"text": "fread( & structure variable, size of (structure variable), no of records, file pointer);"
},
{
"code": null,
"e": 3162,
"s": 3149,
"text": "For example,"
},
{
"code": null,
"e": 3266,
"s": 3162,
"text": "struct emp{\n int eno;\n char ename [30];\n float sal;\n} e;\nFILE *fp;\nfread (&e, sizeof (e), 1, fp);"
},
{
"code": null,
"e": 3277,
"s": 3266,
"text": "fwrite ( )"
},
{
"code": null,
"e": 3328,
"s": 3277,
"text": "It is used for writing an entire record at a time."
},
{
"code": null,
"e": 3355,
"s": 3328,
"text": "The syntax is as follows −"
},
{
"code": null,
"e": 3444,
"s": 3355,
"text": "fwrite( & structure variable , size of structure variable, no of records, file pointer);"
},
{
"code": null,
"e": 3457,
"s": 3444,
"text": "For example,"
},
{
"code": null,
"e": 3561,
"s": 3457,
"text": "struct emp{\n int eno:\n char ename [30];\n float sal;\n} e;\nFILE *fp;\nfwrite (&e, sizeof(e), 1, fp);"
},
{
"code": null,
"e": 3645,
"s": 3561,
"text": "Following is the C program for storing numbers from 1 to 10 and to print the same −"
},
{
"code": null,
"e": 4027,
"s": 3645,
"text": "//Program for storing no’s from 1 to 10 and print the same\n#include<stdio.h>\nint main( ){\n FILE *fp;\n int i;\n fp = fopen (\"num.txt\", \"w\");\n for (i =1; i<= 10; i++){\n putw (i, fp);\n }\n fclose (fp);\n fp =fopen (\"num.txt\", \"r\");\n printf (\"file content is\");\n for (i =1; i<= 10; i++){\n i= getw(fp);\n printf (\"%d\",i);\n }\n fclose (fp);\n return 0;\n}"
},
{
"code": null,
"e": 4098,
"s": 4027,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 4125,
"s": 4098,
"text": "file content is12345678910"
},
{
"code": null,
"e": 4263,
"s": 4125,
"text": "Given below is another C program for storing the details of 5 students into a file and print the same by using fread ( ) and fwrite ( ) −"
},
{
"code": null,
"e": 5137,
"s": 4263,
"text": "#include<stdio.h>\nstruct student{\n int sno;\n char sname [30];\n float marks;\n char temp;\n};\nmain ( ){\n struct student s[60];\n int i;\n FILE *fp;\n fp = fopen (\"student1.txt\", \"w\");\n for (i=0; i<2; i++){\n printf (\"enter details of student %d\\n\", i+1);\n printf(\"student number:\");\n scanf(\"%d\",&s[i].sno);\n scanf(\"%c\",&s[i].temp);\n printf(\"student name:\");\n gets(s[i].sname);\n printf(\"student marks:\");\n scanf(\"%f\",&s[i].marks);\n fwrite(&s[i], sizeof(s[i]),1,fp);\n }\n fclose (fp);\n fp = fopen (\"student1.txt\", \"r\");\n for (i=0; i<2; i++){\n printf (\"details of student %d are\\n\", i+1);\n fread (&s[i], sizeof (s[i]) ,1,fp);\n printf(\"student number = %d\\n\", s[i]. sno);\n printf(\"student name = %s\\n\", s[i]. sname);\n printf(\"marks = %f\\n\", s[i]. marks);\n }\n fclose(fp);\n getch( );\n}"
},
{
"code": null,
"e": 5208,
"s": 5137,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 5534,
"s": 5208,
"text": "enter details of student 1\nstudent number:1\nstudent name:bhanu\nstudent marks:50\nenter details of student 2\nstudent number:2\nstudent name:priya\nstudent marks:69\ndetails of student 1 are\nstudent number = 1\nstudent name = bhanu\nmarks = 50.000000\ndetails of student 2 are\nstudent number = 2\nstudent name = priya\nmarks = 69.000000"
}
] |
How to make a background 20% transparent on Android | If you want to give transparent background for your view, This example demonstrate about How to make a background 20% transparent on Android.
All hex value from 100% to 0% alpha
100% — FF
99% — FC
98% — FA
97% — F7
96% — F5
95% — F2
94% — F0
93% — ED
92% — EB
91% — E8
90% — E6
89% — E3
88% — E0
87% — DE
86% — DB
85% — D9
84% — D6
83% — D4
82% — D1
81% — CF
80% — CC
79% — C9
78% — C7
77% — C4
76% — C2
75% — BF
74% — BD
73% — BA
72% — B8
71% — B5
70% — B3
69% — B0
68% — AD
67% — AB
66% — A8
65% — A6
64% — A3
63% — A1
62% — 9E
61% — 9C
60% — 99
59% — 96
58% — 94
57% — 91
56% — 8F
55% — 8C
54% — 8A
53% — 87
52% — 85
51% — 82
50% — 80
49% — 7D
48% — 7A
47% — 78
46% — 75
45% — 73
44% — 70
43% — 6E
42% — 6B
41% — 69
40% — 66
39% — 63
38% — 61
37% — 5E
36% — 5C
35% — 59
34% — 57
33% — 54
32% — 52
31% — 4F
30% — 4D
29% — 4A
28% — 47
27% — 45
26% — 42
25% — 40
24% — 3D
23% — 3B
22% — 38
21% — 36
20% — 33
19% — 30
18% — 2E
17% — 2B
16% — 29
15% — 26
14% — 24
13% — 21
12% — 1F
11% — 1C
10% — 1A
9% — 17
8% — 14
7% — 12
6% — 0F
5% — 0D
4% — 0A
3% — 08
2% — 05
1% — 03
0% — 00
For example, if you want to give 20% transparent background for yellow color (#FFFF00). So your background color would be #33FFFF00
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:background="#33FFFF00"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="@+id/text"
android:textSize="18sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
In the above code we have give 20% transparent yellow background for text view.
Step 3 − Add the following code to src/MainActivity.java
package com.example.andy.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView=findViewById(R.id.text);
textView.setText("Tutorialspoint india pvt ltd");
}
}
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 Runicon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
In the above result, it is not pure yellow color. it shows 20% transparent yellow color
Click here to download the project code | [
{
"code": null,
"e": 1204,
"s": 1062,
"text": "If you want to give transparent background for your view, This example demonstrate about How to make a background 20% transparent on Android."
},
{
"code": null,
"e": 1240,
"s": 1204,
"text": "All hex value from 100% to 0% alpha"
},
{
"code": null,
"e": 1250,
"s": 1240,
"text": "100% — FF"
},
{
"code": null,
"e": 1259,
"s": 1250,
"text": "99% — FC"
},
{
"code": null,
"e": 1268,
"s": 1259,
"text": "98% — FA"
},
{
"code": null,
"e": 1277,
"s": 1268,
"text": "97% — F7"
},
{
"code": null,
"e": 1286,
"s": 1277,
"text": "96% — F5"
},
{
"code": null,
"e": 1295,
"s": 1286,
"text": "95% — F2"
},
{
"code": null,
"e": 1304,
"s": 1295,
"text": "94% — F0"
},
{
"code": null,
"e": 1313,
"s": 1304,
"text": "93% — ED"
},
{
"code": null,
"e": 1322,
"s": 1313,
"text": "92% — EB"
},
{
"code": null,
"e": 1331,
"s": 1322,
"text": "91% — E8"
},
{
"code": null,
"e": 1340,
"s": 1331,
"text": "90% — E6"
},
{
"code": null,
"e": 1349,
"s": 1340,
"text": "89% — E3"
},
{
"code": null,
"e": 1358,
"s": 1349,
"text": "88% — E0"
},
{
"code": null,
"e": 1367,
"s": 1358,
"text": "87% — DE"
},
{
"code": null,
"e": 1376,
"s": 1367,
"text": "86% — DB"
},
{
"code": null,
"e": 1385,
"s": 1376,
"text": "85% — D9"
},
{
"code": null,
"e": 1394,
"s": 1385,
"text": "84% — D6"
},
{
"code": null,
"e": 1403,
"s": 1394,
"text": "83% — D4"
},
{
"code": null,
"e": 1412,
"s": 1403,
"text": "82% — D1"
},
{
"code": null,
"e": 1421,
"s": 1412,
"text": "81% — CF"
},
{
"code": null,
"e": 1430,
"s": 1421,
"text": "80% — CC"
},
{
"code": null,
"e": 1439,
"s": 1430,
"text": "79% — C9"
},
{
"code": null,
"e": 1448,
"s": 1439,
"text": "78% — C7"
},
{
"code": null,
"e": 1457,
"s": 1448,
"text": "77% — C4"
},
{
"code": null,
"e": 1466,
"s": 1457,
"text": "76% — C2"
},
{
"code": null,
"e": 1475,
"s": 1466,
"text": "75% — BF"
},
{
"code": null,
"e": 1484,
"s": 1475,
"text": "74% — BD"
},
{
"code": null,
"e": 1493,
"s": 1484,
"text": "73% — BA"
},
{
"code": null,
"e": 1502,
"s": 1493,
"text": "72% — B8"
},
{
"code": null,
"e": 1511,
"s": 1502,
"text": "71% — B5"
},
{
"code": null,
"e": 1520,
"s": 1511,
"text": "70% — B3"
},
{
"code": null,
"e": 1529,
"s": 1520,
"text": "69% — B0"
},
{
"code": null,
"e": 1538,
"s": 1529,
"text": "68% — AD"
},
{
"code": null,
"e": 1547,
"s": 1538,
"text": "67% — AB"
},
{
"code": null,
"e": 1556,
"s": 1547,
"text": "66% — A8"
},
{
"code": null,
"e": 1565,
"s": 1556,
"text": "65% — A6"
},
{
"code": null,
"e": 1574,
"s": 1565,
"text": "64% — A3"
},
{
"code": null,
"e": 1583,
"s": 1574,
"text": "63% — A1"
},
{
"code": null,
"e": 1592,
"s": 1583,
"text": "62% — 9E"
},
{
"code": null,
"e": 1601,
"s": 1592,
"text": "61% — 9C"
},
{
"code": null,
"e": 1610,
"s": 1601,
"text": "60% — 99"
},
{
"code": null,
"e": 1619,
"s": 1610,
"text": "59% — 96"
},
{
"code": null,
"e": 1628,
"s": 1619,
"text": "58% — 94"
},
{
"code": null,
"e": 1637,
"s": 1628,
"text": "57% — 91"
},
{
"code": null,
"e": 1646,
"s": 1637,
"text": "56% — 8F"
},
{
"code": null,
"e": 1655,
"s": 1646,
"text": "55% — 8C"
},
{
"code": null,
"e": 1664,
"s": 1655,
"text": "54% — 8A"
},
{
"code": null,
"e": 1673,
"s": 1664,
"text": "53% — 87"
},
{
"code": null,
"e": 1682,
"s": 1673,
"text": "52% — 85"
},
{
"code": null,
"e": 1691,
"s": 1682,
"text": "51% — 82"
},
{
"code": null,
"e": 1700,
"s": 1691,
"text": "50% — 80"
},
{
"code": null,
"e": 1709,
"s": 1700,
"text": "49% — 7D"
},
{
"code": null,
"e": 1718,
"s": 1709,
"text": "48% — 7A"
},
{
"code": null,
"e": 1727,
"s": 1718,
"text": "47% — 78"
},
{
"code": null,
"e": 1736,
"s": 1727,
"text": "46% — 75"
},
{
"code": null,
"e": 1745,
"s": 1736,
"text": "45% — 73"
},
{
"code": null,
"e": 1754,
"s": 1745,
"text": "44% — 70"
},
{
"code": null,
"e": 1763,
"s": 1754,
"text": "43% — 6E"
},
{
"code": null,
"e": 1772,
"s": 1763,
"text": "42% — 6B"
},
{
"code": null,
"e": 1781,
"s": 1772,
"text": "41% — 69"
},
{
"code": null,
"e": 1790,
"s": 1781,
"text": "40% — 66"
},
{
"code": null,
"e": 1799,
"s": 1790,
"text": "39% — 63"
},
{
"code": null,
"e": 1808,
"s": 1799,
"text": "38% — 61"
},
{
"code": null,
"e": 1817,
"s": 1808,
"text": "37% — 5E"
},
{
"code": null,
"e": 1826,
"s": 1817,
"text": "36% — 5C"
},
{
"code": null,
"e": 1835,
"s": 1826,
"text": "35% — 59"
},
{
"code": null,
"e": 1844,
"s": 1835,
"text": "34% — 57"
},
{
"code": null,
"e": 1853,
"s": 1844,
"text": "33% — 54"
},
{
"code": null,
"e": 1862,
"s": 1853,
"text": "32% — 52"
},
{
"code": null,
"e": 1871,
"s": 1862,
"text": "31% — 4F"
},
{
"code": null,
"e": 1880,
"s": 1871,
"text": "30% — 4D"
},
{
"code": null,
"e": 1889,
"s": 1880,
"text": "29% — 4A"
},
{
"code": null,
"e": 1898,
"s": 1889,
"text": "28% — 47"
},
{
"code": null,
"e": 1907,
"s": 1898,
"text": "27% — 45"
},
{
"code": null,
"e": 1916,
"s": 1907,
"text": "26% — 42"
},
{
"code": null,
"e": 1925,
"s": 1916,
"text": "25% — 40"
},
{
"code": null,
"e": 1934,
"s": 1925,
"text": "24% — 3D"
},
{
"code": null,
"e": 1943,
"s": 1934,
"text": "23% — 3B"
},
{
"code": null,
"e": 1952,
"s": 1943,
"text": "22% — 38"
},
{
"code": null,
"e": 1961,
"s": 1952,
"text": "21% — 36"
},
{
"code": null,
"e": 1970,
"s": 1961,
"text": "20% — 33"
},
{
"code": null,
"e": 1979,
"s": 1970,
"text": "19% — 30"
},
{
"code": null,
"e": 1988,
"s": 1979,
"text": "18% — 2E"
},
{
"code": null,
"e": 1997,
"s": 1988,
"text": "17% — 2B"
},
{
"code": null,
"e": 2006,
"s": 1997,
"text": "16% — 29"
},
{
"code": null,
"e": 2015,
"s": 2006,
"text": "15% — 26"
},
{
"code": null,
"e": 2024,
"s": 2015,
"text": "14% — 24"
},
{
"code": null,
"e": 2033,
"s": 2024,
"text": "13% — 21"
},
{
"code": null,
"e": 2042,
"s": 2033,
"text": "12% — 1F"
},
{
"code": null,
"e": 2051,
"s": 2042,
"text": "11% — 1C"
},
{
"code": null,
"e": 2060,
"s": 2051,
"text": "10% — 1A"
},
{
"code": null,
"e": 2068,
"s": 2060,
"text": "9% — 17"
},
{
"code": null,
"e": 2076,
"s": 2068,
"text": "8% — 14"
},
{
"code": null,
"e": 2084,
"s": 2076,
"text": "7% — 12"
},
{
"code": null,
"e": 2092,
"s": 2084,
"text": "6% — 0F"
},
{
"code": null,
"e": 2100,
"s": 2092,
"text": "5% — 0D"
},
{
"code": null,
"e": 2108,
"s": 2100,
"text": "4% — 0A"
},
{
"code": null,
"e": 2116,
"s": 2108,
"text": "3% — 08"
},
{
"code": null,
"e": 2124,
"s": 2116,
"text": "2% — 05"
},
{
"code": null,
"e": 2132,
"s": 2124,
"text": "1% — 03"
},
{
"code": null,
"e": 2140,
"s": 2132,
"text": "0% — 00"
},
{
"code": null,
"e": 2272,
"s": 2140,
"text": "For example, if you want to give 20% transparent background for yellow color (#FFFF00). So your background color would be #33FFFF00"
},
{
"code": null,
"e": 2401,
"s": 2272,
"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": 2466,
"s": 2401,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 3013,
"s": 2466,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\"\n android:background=\"#33FFFF00\"\n android:gravity=\"center\"\n android:orientation=\"vertical\">\n <TextView\n android:id=\"@+id/text\"\n android:textSize=\"18sp\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\" />\n</LinearLayout>"
},
{
"code": null,
"e": 3093,
"s": 3013,
"text": "In the above code we have give 20% transparent yellow background for text view."
},
{
"code": null,
"e": 3150,
"s": 3093,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3728,
"s": 3150,
"text": "package com.example.andy.myapplication;\n\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.TextView;\nimport org.w3c.dom.Text;\nimport java.util.Locale;\n\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n TextView textView=findViewById(R.id.text);\n textView.setText(\"Tutorialspoint india pvt ltd\");\n }\n}"
},
{
"code": null,
"e": 4073,
"s": 3728,
"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 Runicon 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": 4161,
"s": 4073,
"text": "In the above result, it is not pure yellow color. it shows 20% transparent yellow color"
},
{
"code": null,
"e": 4201,
"s": 4161,
"text": "Click here to download the project code"
}
] |
Segmenting Credit Card Customers with Machine Learning | by Rebecca Vickery | Towards Data Science | Segmentation in marketing is a technique used to divide customers or other entities into groups based on attributes such as behaviour or demographics. It is useful to identify segments of customers who may respond in a similar way to specific marketing techniques such as email subject lines or display advertisements. As it gives businesses the ability to tailor marketing messages and timing to generate better response rates and provide improved consumer experiences.
In the following post, I will be using a dataset containing a number of behavioural attributes for credit card customers. The dataset can be downloaded from the Kaggle website. I will be using the scikit-learn python machine learning library to apply an unsupervised machine learning technique known as clustering to identify segments that may not immediately be apparent to human cognition.
The dataset consists of 18 features about the behaviour of credit card customers. These include variables such as the balance currently on the card, the number of purchases that have been made on the account, the credit limit, and many others. A complete data dictionary can be found on the data download page.
Setting up
I am running the following code in JupyterLab. I am using the iPython magic extension watermark to record the versions of tools that I am running this in. The output of this is shown below if you having any trouble running the code. Library imports are also shown below.
%load_ext watermark%watermark -d -m -v -p numpy,matplotlib,sklearn,seaborn,pandas -g
import pandas as pdimport numpy as npfrom sklearn.cluster import KMeansfrom sklearn import preprocessingimport matplotlib.pyplot as plt%matplotlib inlineimport seaborn as sns
To begin with, we will need to inspect the data to find out what cleaning and transformation may be needed. The scikit-learn library requires that all data have no null values and that all values must be numeric.
To begin with, I have read in the downloaded csv file.
TRAIN_FILE = 'CC GENERAL.csv'train_data = pd.read_csv(TRAIN_FILE)
Firstly I run the following to inspect the data types to find out if there are any categorical variables that may need transforming. We can see from the result that all features are numeric except for CUST_ID. But since we won’t need this feature to train the model we don’t have to do any transforming here.
print("Data Types:", train_data.dtypes)output:Data Types: CUST_ID objectBALANCE float64BALANCE_FREQUENCY float64PURCHASES float64ONEOFF_PURCHASES float64INSTALLMENTS_PURCHASES float64CASH_ADVANCE float64PURCHASES_FREQUENCY float64ONEOFF_PURCHASES_FREQUENCY float64PURCHASES_INSTALLMENTS_FREQUENCY float64CASH_ADVANCE_FREQUENCY float64CASH_ADVANCE_TRX int64PURCHASES_TRX int64CREDIT_LIMIT float64PAYMENTS float64MINIMUM_PAYMENTS float64PRC_FULL_PAYMENT float64TENURE int64
Running the following code tells me that only two features have null values ‘CREDIT_LIMIT’ and ‘MINIMUM_PAYMENTS’. Additionally, less than 5% of each column has nulls. This means that we should be ok to fill these with a sensible replacement value and should still be able to use the feature.
train_data.apply(lambda x: sum(x.isnull()/len(train_data)))Output:CUST_ID 0.000000BALANCE 0.000000BALANCE_FREQUENCY 0.000000PURCHASES 0.000000ONEOFF_PURCHASES 0.000000INSTALLMENTS_PURCHASES 0.000000CASH_ADVANCE 0.000000PURCHASES_FREQUENCY 0.000000ONEOFF_PURCHASES_FREQUENCY 0.000000PURCHASES_INSTALLMENTS_FREQUENCY 0.000000CASH_ADVANCE_FREQUENCY 0.000000CASH_ADVANCE_TRX 0.000000PURCHASES_TRX 0.000000CREDIT_LIMIT 0.000112PAYMENTS 0.000000MINIMUM_PAYMENTS 0.034972PRC_FULL_PAYMENT 0.000000TENURE 0.000000
The following code fills the missing value with the most commonly occurring value in the column. We could equally use mean or median, or indeed another approach but we will start here and iterate on this if needed.
train_clean = train_data.apply(lambda x:x.fillna(x.value_counts().index[0]))
I am also going to drop the CUST_ID column as we won’t need this for training.
cols_to_drop = 'CUST_ID'train_clean = train_clean.drop([cols_to_drop], axis=1)
The final piece of processing I will do before training a model is to scale the features.
The model that I am going to use for clustering in this post is K-Means. The following, in simple terms, is how the algorithm works:
Takes a predetermined number of clusters.Finds the centroids for each of these clusters, essentially the means.Assigns each data point to its nearest cluster based on the squared Euclidean distance.Once trained clusters for new unseen data points can be identified based on Euclidean distance.
Takes a predetermined number of clusters.
Finds the centroids for each of these clusters, essentially the means.
Assigns each data point to its nearest cluster based on the squared Euclidean distance.
Once trained clusters for new unseen data points can be identified based on Euclidean distance.
As it is reliant on this distance metric feature scaling is a very important consideration. In the example of the data set I am using let’s take two features PURCHASES_FREQUENCY and BALANCE. The feature PURCHASES_FREQUENCY is a number between 0 and 1, whereas BALANCE as it is a monetary value in this dataset is between £0 and £19,043. These features have very different scales which means that if we don’t normalise them so that they are on the same scale. There are likely to be instances where the algorithm will give more weight to one variable.
The following code scales all the features in the data frame. I am using the min_max_scaler for the first iteration. Different techniques for scaling may have different results.
x = train_clean.valuesmin_max_scaler = preprocessing.MinMaxScaler()x_scaled = min_max_scaler.fit_transform(x)train_clean = pd.DataFrame(x_scaled,columns=train_clean.columns)
To illustrate how this looks here are the PURCHASES_FREQUENCY and BALANCE columns before scaling.
And after scaling.
I mentioned previously that we need to tell the K-Means algorithm the number of clusters it should use. There are a number of techniques that can be used to find the optimal number. For this example, I am going to use the elbow method so named because the chart that it produces is similar in shape to the curve of an elbow. This method computes the sum of squared distances for clusters k. As more clusters are used the variance will reduce until you reach a point at which increasing clusters no longer results in a better model. This is illustrated in the following code borrowed from this article. Thank you Tola Alade!
Sum_of_squared_distances = []K = range(1,15)for k in K: km = KMeans(n_clusters=k) km = km.fit(train_clean) Sum_of_squared_distances.append(km.inertia_)plt.plot(K, Sum_of_squared_distances, 'bx-')plt.xlabel('k')plt.ylabel('Sum_of_squared_distances')plt.title('Elbow Method For Optimal k')plt.show()
You can see that after 8 clusters adding more gives minimal benefit to the model. I am therefore going to use 8 clusters to train my model.
Before training, I am going to divide the data set into a train and test set. The following code divides the data reserving 20% for testing.
np.random.seed(0)msk = np.random.rand(len(train_clean)) < 0.8train = train_clean[msk]test = train_clean[~msk]
I then convert both the train and test set into numpy arrays.
X = np.array(train)X_test = np.array(test)
Next, I call the KMeans fit method using 8 clusters.
kmeans = KMeans(n_clusters=8, random_state=0).fit(X)
Using the trained model I will now predict the clusters on the test set.
y_k = kmeans.predict(X_test)
I’ll now assign the prediction as a new column on the original test data frame to analyse the results.
test['PREDICTED_CLUSTER'] = y_k
I am going to use the pandas groupby function to analyse a selected number of features for the clusters in order to understand if the model has successfully identified unique segments.
train_summary = test.groupby(by='PREDICTED_CLUSTER').mean()train_summary = train_summary[['BALANCE', 'PURCHASES', 'PURCHASES_FREQUENCY','CREDIT_LIMIT', 'ONEOFF_PURCHASES_FREQUENCY', 'MINIMUM_PAYMENTS','PRC_FULL_PAYMENT', 'PAYMENTS']]train_summary
This gives the following output.
Just looking at ‘PURCHASES_FREQUENCY’ we can see that the model has identified some high-frequency purchase segments, clusters 2 and 3. Let’s understand the differences between these two segments to further determine why they are in separate clusters. We can see that cluster 3 has a higher number of total purchases, a higher credit limit, they make frequent one-off purchases and are more likely to pay in full. We can draw the conclusion that these are high-value customers and therefore there will almost certainly be a difference between how you may market to these customers.
As a first iteration of the model, this appears to be identifying some useful segments. There are many ways in which we could tune the model including alternative data cleaning methods, feature engineering, dropping features with high correlation and hyperparameter optimisation. However, for the purpose of this post I wanted to give a high-level end to end view of how to start a machine learning model that performs unsupervised clustering. | [
{
"code": null,
"e": 643,
"s": 172,
"text": "Segmentation in marketing is a technique used to divide customers or other entities into groups based on attributes such as behaviour or demographics. It is useful to identify segments of customers who may respond in a similar way to specific marketing techniques such as email subject lines or display advertisements. As it gives businesses the ability to tailor marketing messages and timing to generate better response rates and provide improved consumer experiences."
},
{
"code": null,
"e": 1035,
"s": 643,
"text": "In the following post, I will be using a dataset containing a number of behavioural attributes for credit card customers. The dataset can be downloaded from the Kaggle website. I will be using the scikit-learn python machine learning library to apply an unsupervised machine learning technique known as clustering to identify segments that may not immediately be apparent to human cognition."
},
{
"code": null,
"e": 1346,
"s": 1035,
"text": "The dataset consists of 18 features about the behaviour of credit card customers. These include variables such as the balance currently on the card, the number of purchases that have been made on the account, the credit limit, and many others. A complete data dictionary can be found on the data download page."
},
{
"code": null,
"e": 1357,
"s": 1346,
"text": "Setting up"
},
{
"code": null,
"e": 1628,
"s": 1357,
"text": "I am running the following code in JupyterLab. I am using the iPython magic extension watermark to record the versions of tools that I am running this in. The output of this is shown below if you having any trouble running the code. Library imports are also shown below."
},
{
"code": null,
"e": 1713,
"s": 1628,
"text": "%load_ext watermark%watermark -d -m -v -p numpy,matplotlib,sklearn,seaborn,pandas -g"
},
{
"code": null,
"e": 1888,
"s": 1713,
"text": "import pandas as pdimport numpy as npfrom sklearn.cluster import KMeansfrom sklearn import preprocessingimport matplotlib.pyplot as plt%matplotlib inlineimport seaborn as sns"
},
{
"code": null,
"e": 2101,
"s": 1888,
"text": "To begin with, we will need to inspect the data to find out what cleaning and transformation may be needed. The scikit-learn library requires that all data have no null values and that all values must be numeric."
},
{
"code": null,
"e": 2156,
"s": 2101,
"text": "To begin with, I have read in the downloaded csv file."
},
{
"code": null,
"e": 2222,
"s": 2156,
"text": "TRAIN_FILE = 'CC GENERAL.csv'train_data = pd.read_csv(TRAIN_FILE)"
},
{
"code": null,
"e": 2531,
"s": 2222,
"text": "Firstly I run the following to inspect the data types to find out if there are any categorical variables that may need transforming. We can see from the result that all features are numeric except for CUST_ID. But since we won’t need this feature to train the model we don’t have to do any transforming here."
},
{
"code": null,
"e": 3364,
"s": 2531,
"text": "print(\"Data Types:\", train_data.dtypes)output:Data Types: CUST_ID objectBALANCE float64BALANCE_FREQUENCY float64PURCHASES float64ONEOFF_PURCHASES float64INSTALLMENTS_PURCHASES float64CASH_ADVANCE float64PURCHASES_FREQUENCY float64ONEOFF_PURCHASES_FREQUENCY float64PURCHASES_INSTALLMENTS_FREQUENCY float64CASH_ADVANCE_FREQUENCY float64CASH_ADVANCE_TRX int64PURCHASES_TRX int64CREDIT_LIMIT float64PAYMENTS float64MINIMUM_PAYMENTS float64PRC_FULL_PAYMENT float64TENURE int64"
},
{
"code": null,
"e": 3657,
"s": 3364,
"text": "Running the following code tells me that only two features have null values ‘CREDIT_LIMIT’ and ‘MINIMUM_PAYMENTS’. Additionally, less than 5% of each column has nulls. This means that we should be ok to fill these with a sensible replacement value and should still be able to use the feature."
},
{
"code": null,
"e": 4516,
"s": 3657,
"text": "train_data.apply(lambda x: sum(x.isnull()/len(train_data)))Output:CUST_ID 0.000000BALANCE 0.000000BALANCE_FREQUENCY 0.000000PURCHASES 0.000000ONEOFF_PURCHASES 0.000000INSTALLMENTS_PURCHASES 0.000000CASH_ADVANCE 0.000000PURCHASES_FREQUENCY 0.000000ONEOFF_PURCHASES_FREQUENCY 0.000000PURCHASES_INSTALLMENTS_FREQUENCY 0.000000CASH_ADVANCE_FREQUENCY 0.000000CASH_ADVANCE_TRX 0.000000PURCHASES_TRX 0.000000CREDIT_LIMIT 0.000112PAYMENTS 0.000000MINIMUM_PAYMENTS 0.034972PRC_FULL_PAYMENT 0.000000TENURE 0.000000"
},
{
"code": null,
"e": 4731,
"s": 4516,
"text": "The following code fills the missing value with the most commonly occurring value in the column. We could equally use mean or median, or indeed another approach but we will start here and iterate on this if needed."
},
{
"code": null,
"e": 4808,
"s": 4731,
"text": "train_clean = train_data.apply(lambda x:x.fillna(x.value_counts().index[0]))"
},
{
"code": null,
"e": 4887,
"s": 4808,
"text": "I am also going to drop the CUST_ID column as we won’t need this for training."
},
{
"code": null,
"e": 4966,
"s": 4887,
"text": "cols_to_drop = 'CUST_ID'train_clean = train_clean.drop([cols_to_drop], axis=1)"
},
{
"code": null,
"e": 5056,
"s": 4966,
"text": "The final piece of processing I will do before training a model is to scale the features."
},
{
"code": null,
"e": 5189,
"s": 5056,
"text": "The model that I am going to use for clustering in this post is K-Means. The following, in simple terms, is how the algorithm works:"
},
{
"code": null,
"e": 5483,
"s": 5189,
"text": "Takes a predetermined number of clusters.Finds the centroids for each of these clusters, essentially the means.Assigns each data point to its nearest cluster based on the squared Euclidean distance.Once trained clusters for new unseen data points can be identified based on Euclidean distance."
},
{
"code": null,
"e": 5525,
"s": 5483,
"text": "Takes a predetermined number of clusters."
},
{
"code": null,
"e": 5596,
"s": 5525,
"text": "Finds the centroids for each of these clusters, essentially the means."
},
{
"code": null,
"e": 5684,
"s": 5596,
"text": "Assigns each data point to its nearest cluster based on the squared Euclidean distance."
},
{
"code": null,
"e": 5780,
"s": 5684,
"text": "Once trained clusters for new unseen data points can be identified based on Euclidean distance."
},
{
"code": null,
"e": 6331,
"s": 5780,
"text": "As it is reliant on this distance metric feature scaling is a very important consideration. In the example of the data set I am using let’s take two features PURCHASES_FREQUENCY and BALANCE. The feature PURCHASES_FREQUENCY is a number between 0 and 1, whereas BALANCE as it is a monetary value in this dataset is between £0 and £19,043. These features have very different scales which means that if we don’t normalise them so that they are on the same scale. There are likely to be instances where the algorithm will give more weight to one variable."
},
{
"code": null,
"e": 6509,
"s": 6331,
"text": "The following code scales all the features in the data frame. I am using the min_max_scaler for the first iteration. Different techniques for scaling may have different results."
},
{
"code": null,
"e": 6683,
"s": 6509,
"text": "x = train_clean.valuesmin_max_scaler = preprocessing.MinMaxScaler()x_scaled = min_max_scaler.fit_transform(x)train_clean = pd.DataFrame(x_scaled,columns=train_clean.columns)"
},
{
"code": null,
"e": 6781,
"s": 6683,
"text": "To illustrate how this looks here are the PURCHASES_FREQUENCY and BALANCE columns before scaling."
},
{
"code": null,
"e": 6800,
"s": 6781,
"text": "And after scaling."
},
{
"code": null,
"e": 7424,
"s": 6800,
"text": "I mentioned previously that we need to tell the K-Means algorithm the number of clusters it should use. There are a number of techniques that can be used to find the optimal number. For this example, I am going to use the elbow method so named because the chart that it produces is similar in shape to the curve of an elbow. This method computes the sum of squared distances for clusters k. As more clusters are used the variance will reduce until you reach a point at which increasing clusters no longer results in a better model. This is illustrated in the following code borrowed from this article. Thank you Tola Alade!"
},
{
"code": null,
"e": 7731,
"s": 7424,
"text": "Sum_of_squared_distances = []K = range(1,15)for k in K: km = KMeans(n_clusters=k) km = km.fit(train_clean) Sum_of_squared_distances.append(km.inertia_)plt.plot(K, Sum_of_squared_distances, 'bx-')plt.xlabel('k')plt.ylabel('Sum_of_squared_distances')plt.title('Elbow Method For Optimal k')plt.show()"
},
{
"code": null,
"e": 7871,
"s": 7731,
"text": "You can see that after 8 clusters adding more gives minimal benefit to the model. I am therefore going to use 8 clusters to train my model."
},
{
"code": null,
"e": 8012,
"s": 7871,
"text": "Before training, I am going to divide the data set into a train and test set. The following code divides the data reserving 20% for testing."
},
{
"code": null,
"e": 8122,
"s": 8012,
"text": "np.random.seed(0)msk = np.random.rand(len(train_clean)) < 0.8train = train_clean[msk]test = train_clean[~msk]"
},
{
"code": null,
"e": 8184,
"s": 8122,
"text": "I then convert both the train and test set into numpy arrays."
},
{
"code": null,
"e": 8227,
"s": 8184,
"text": "X = np.array(train)X_test = np.array(test)"
},
{
"code": null,
"e": 8280,
"s": 8227,
"text": "Next, I call the KMeans fit method using 8 clusters."
},
{
"code": null,
"e": 8333,
"s": 8280,
"text": "kmeans = KMeans(n_clusters=8, random_state=0).fit(X)"
},
{
"code": null,
"e": 8406,
"s": 8333,
"text": "Using the trained model I will now predict the clusters on the test set."
},
{
"code": null,
"e": 8435,
"s": 8406,
"text": "y_k = kmeans.predict(X_test)"
},
{
"code": null,
"e": 8538,
"s": 8435,
"text": "I’ll now assign the prediction as a new column on the original test data frame to analyse the results."
},
{
"code": null,
"e": 8570,
"s": 8538,
"text": "test['PREDICTED_CLUSTER'] = y_k"
},
{
"code": null,
"e": 8755,
"s": 8570,
"text": "I am going to use the pandas groupby function to analyse a selected number of features for the clusters in order to understand if the model has successfully identified unique segments."
},
{
"code": null,
"e": 9125,
"s": 8755,
"text": "train_summary = test.groupby(by='PREDICTED_CLUSTER').mean()train_summary = train_summary[['BALANCE', 'PURCHASES', 'PURCHASES_FREQUENCY','CREDIT_LIMIT', 'ONEOFF_PURCHASES_FREQUENCY', 'MINIMUM_PAYMENTS','PRC_FULL_PAYMENT', 'PAYMENTS']]train_summary"
},
{
"code": null,
"e": 9158,
"s": 9125,
"text": "This gives the following output."
},
{
"code": null,
"e": 9740,
"s": 9158,
"text": "Just looking at ‘PURCHASES_FREQUENCY’ we can see that the model has identified some high-frequency purchase segments, clusters 2 and 3. Let’s understand the differences between these two segments to further determine why they are in separate clusters. We can see that cluster 3 has a higher number of total purchases, a higher credit limit, they make frequent one-off purchases and are more likely to pay in full. We can draw the conclusion that these are high-value customers and therefore there will almost certainly be a difference between how you may market to these customers."
}
] |
Find indices of all occurrence of one string in other - GeeksforGeeks | 28 May, 2021
Given two strings, str1 and str2, the task is to print the indices(Consider, indices starting from 0) of the occurrence of str2 in str1. If no such index occurs, print “NONE”.
Examples:
Input : GeeksforGeeks
Geeks
Output : 0 8
Input : GFG
g
Output : NONE
A simple solution is to check all substrings of a given string one by one. If a substring matches print its index.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find indices of all// occurrences of one string in other.#include <iostream>using namespace std;void printIndex(string str, string s){ bool flag = false; for (int i = 0; i < str.length(); i++) { if (str.substr(i, s.length()) == s) { cout << i << " "; flag = true; } } if (flag == false) cout << "NONE";}int main(){ string str1 = "GeeksforGeeks"; string str2 = "Geeks"; printIndex(str1, str2); return 0;}
// Java program to find indices of all// occurrences of one String in other.class GFG { static void printIndex(String str, String s) { boolean flag = false; for (int i = 0; i < str.length() - s.length() + 1; i++) { if (str.substring(i, i + s.length()).equals(s)) { System.out.print(i + " "); flag = true; } } if (flag == false) { System.out.println("NONE"); } } // Driver code public static void main(String[] args) { String str1 = "GeeksforGeeks"; String str2 = "Geeks"; printIndex(str1, str2); }} // This code is contributed by Rajput-JI
# Python program to find indices of all# occurrences of one String in other.def printIndex(str, s): flag = False; for i in range(len(str)): if (str[i:i + len(s)] == s): print( i, end =" "); flag = True; if (flag == False): print("NONE"); # Driver code str1 = "GeeksforGeeks";str2 = "Geeks";printIndex(str1, str2); # This code contributed by PrinciRaj1992
// C# program to find indices of all// occurrences of one String in other.using System; class GFG { static void printIndex(String str, String s) { bool flag = false; for (int i = 0; i < str.Length - s.Length + 1; i++) { if (str.Substring(i, s.Length) .Equals(s)) { Console.Write(i + " "); flag = true; } } if (flag == false) { Console.WriteLine("NONE"); } } // Driver code public static void Main(String[] args) { String str1 = "GeeksforGeeks"; String str2 = "Geeks"; printIndex(str1, str2); }} // This code is contributed by 29AjayKumar
<?php// PHP program to find indices of all// occurrences of one string in other.function printIndex($str, $s){ $flag = false; for ($i = 0; $i < strlen($str); $i++) { if (substr($str,$i, strlen($s)) == $s) { echo $i . " "; $flag = true; } } if ($flag == false) echo "NONE";} // Driver Code$str1 = "GeeksforGeeks";$str2 = "Geeks";printIndex($str1, $str2); // This code is contributed by mits?>
<script> // JavaScript program to find indices of all // occurrences of one String in other. function printIndex(str, s) { var flag = false; for (var i = 0; i < str.length - s.length + 1; i++) { if (str.substring(i, s.length + i) == s) { document.write(i + " "); flag = true; } } if (flag === false) { document.write("NONE"); } } // Driver code var str1 = "GeeksforGeeks"; var str2 = "Geeks"; printIndex(str1, str2);</script>
0 8
Time Complexity : O(n * n)
An efficient solution is to KMP string matching algorithm.
Rajput-Ji
29AjayKumar
princiraj1992
Mithun Kumar
ManasChhabra2
rdtank
cpp-string
C++
Strings
Strings
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)
Write a program to reverse an array or string
Reverse a string in Java
Longest Common Subsequence | DP-4
Write a program to print all permutations of a given string
Check for Balanced Brackets in an expression (well-formedness) using Stack | [
{
"code": null,
"e": 24124,
"s": 24096,
"text": "\n28 May, 2021"
},
{
"code": null,
"e": 24300,
"s": 24124,
"text": "Given two strings, str1 and str2, the task is to print the indices(Consider, indices starting from 0) of the occurrence of str2 in str1. If no such index occurs, print “NONE”."
},
{
"code": null,
"e": 24310,
"s": 24300,
"text": "Examples:"
},
{
"code": null,
"e": 24396,
"s": 24310,
"text": "Input : GeeksforGeeks\n Geeks\nOutput : 0 8\n\nInput : GFG\n g\nOutput : NONE"
},
{
"code": null,
"e": 24512,
"s": 24396,
"text": "A simple solution is to check all substrings of a given string one by one. If a substring matches print its index. "
},
{
"code": null,
"e": 24516,
"s": 24512,
"text": "C++"
},
{
"code": null,
"e": 24521,
"s": 24516,
"text": "Java"
},
{
"code": null,
"e": 24529,
"s": 24521,
"text": "Python3"
},
{
"code": null,
"e": 24532,
"s": 24529,
"text": "C#"
},
{
"code": null,
"e": 24536,
"s": 24532,
"text": "PHP"
},
{
"code": null,
"e": 24547,
"s": 24536,
"text": "Javascript"
},
{
"code": "// C++ program to find indices of all// occurrences of one string in other.#include <iostream>using namespace std;void printIndex(string str, string s){ bool flag = false; for (int i = 0; i < str.length(); i++) { if (str.substr(i, s.length()) == s) { cout << i << \" \"; flag = true; } } if (flag == false) cout << \"NONE\";}int main(){ string str1 = \"GeeksforGeeks\"; string str2 = \"Geeks\"; printIndex(str1, str2); return 0;}",
"e": 25038,
"s": 24547,
"text": null
},
{
"code": "// Java program to find indices of all// occurrences of one String in other.class GFG { static void printIndex(String str, String s) { boolean flag = false; for (int i = 0; i < str.length() - s.length() + 1; i++) { if (str.substring(i, i + s.length()).equals(s)) { System.out.print(i + \" \"); flag = true; } } if (flag == false) { System.out.println(\"NONE\"); } } // Driver code public static void main(String[] args) { String str1 = \"GeeksforGeeks\"; String str2 = \"Geeks\"; printIndex(str1, str2); }} // This code is contributed by Rajput-JI",
"e": 25722,
"s": 25038,
"text": null
},
{
"code": "# Python program to find indices of all# occurrences of one String in other.def printIndex(str, s): flag = False; for i in range(len(str)): if (str[i:i + len(s)] == s): print( i, end =\" \"); flag = True; if (flag == False): print(\"NONE\"); # Driver code str1 = \"GeeksforGeeks\";str2 = \"Geeks\";printIndex(str1, str2); # This code contributed by PrinciRaj1992",
"e": 26151,
"s": 25722,
"text": null
},
{
"code": "// C# program to find indices of all// occurrences of one String in other.using System; class GFG { static void printIndex(String str, String s) { bool flag = false; for (int i = 0; i < str.Length - s.Length + 1; i++) { if (str.Substring(i, s.Length) .Equals(s)) { Console.Write(i + \" \"); flag = true; } } if (flag == false) { Console.WriteLine(\"NONE\"); } } // Driver code public static void Main(String[] args) { String str1 = \"GeeksforGeeks\"; String str2 = \"Geeks\"; printIndex(str1, str2); }} // This code is contributed by 29AjayKumar",
"e": 26881,
"s": 26151,
"text": null
},
{
"code": "<?php// PHP program to find indices of all// occurrences of one string in other.function printIndex($str, $s){ $flag = false; for ($i = 0; $i < strlen($str); $i++) { if (substr($str,$i, strlen($s)) == $s) { echo $i . \" \"; $flag = true; } } if ($flag == false) echo \"NONE\";} // Driver Code$str1 = \"GeeksforGeeks\";$str2 = \"Geeks\";printIndex($str1, $str2); // This code is contributed by mits?>",
"e": 27339,
"s": 26881,
"text": null
},
{
"code": "<script> // JavaScript program to find indices of all // occurrences of one String in other. function printIndex(str, s) { var flag = false; for (var i = 0; i < str.length - s.length + 1; i++) { if (str.substring(i, s.length + i) == s) { document.write(i + \" \"); flag = true; } } if (flag === false) { document.write(\"NONE\"); } } // Driver code var str1 = \"GeeksforGeeks\"; var str2 = \"Geeks\"; printIndex(str1, str2);</script>",
"e": 27891,
"s": 27339,
"text": null
},
{
"code": null,
"e": 27895,
"s": 27891,
"text": "0 8"
},
{
"code": null,
"e": 27925,
"s": 27897,
"text": "Time Complexity : O(n * n) "
},
{
"code": null,
"e": 27985,
"s": 27925,
"text": "An efficient solution is to KMP string matching algorithm. "
},
{
"code": null,
"e": 27995,
"s": 27985,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 28007,
"s": 27995,
"text": "29AjayKumar"
},
{
"code": null,
"e": 28021,
"s": 28007,
"text": "princiraj1992"
},
{
"code": null,
"e": 28034,
"s": 28021,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 28048,
"s": 28034,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 28055,
"s": 28048,
"text": "rdtank"
},
{
"code": null,
"e": 28066,
"s": 28055,
"text": "cpp-string"
},
{
"code": null,
"e": 28070,
"s": 28066,
"text": "C++"
},
{
"code": null,
"e": 28078,
"s": 28070,
"text": "Strings"
},
{
"code": null,
"e": 28086,
"s": 28078,
"text": "Strings"
},
{
"code": null,
"e": 28090,
"s": 28086,
"text": "CPP"
},
{
"code": null,
"e": 28188,
"s": 28090,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28216,
"s": 28188,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 28236,
"s": 28216,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 28260,
"s": 28236,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 28293,
"s": 28260,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 28337,
"s": 28293,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 28383,
"s": 28337,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 28408,
"s": 28383,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 28442,
"s": 28408,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 28502,
"s": 28442,
"text": "Write a program to print all permutations of a given string"
}
] |
Convert Pictures to ASCII Art. A brief guide on how images work and... | by Nicholas Obert | Towards Data Science | I’m sure many of you have heard of ASCII art, a graphic design technique that uses the printable ASCII character set to compose pictures. The simplest form of this art are emoticons such as :-) or :-3. But can you represent a more complex image with just printable ASCII characters?
First of all, is important to clarify how an image is represented in computer systems. Pictures are usually stored in formats such as .png or .jpg on the disk. All these file types have a similar structure: they’re roughly composed of an header and a data section. The former stores useful information about the image such as its format signature, whereas the latter stores the actual pixel data.
The actual image you see is composed of pixels, the smallest addressable element of a raster image which we’re all familiar with. They’re usually represented as a set of channels, also referred as colors. Among the most common color values there are the classic RGB (Red Green Blue) and RGBA (Red Green Blue Alpha). The difference between the two is that the latter has an additional channel, called “alpha”, that specifies the image opacity. RGBA is what we’ll be working with since it can also be used to represent a void background.
Now that we’ve seen how images are represented, it’s time to talk about how a pixel can be transformed into an actual ASCII character. To understand this, we must first take a look at pixel color intensity. This value refers to the sum of all the pixel’s channels, divided by the sum of the maximum values the channels can have (in this case 255).
From now on I’ll be using Python for the code examples for its simplicity and readability, but feel free to use any technology you prefer. I’ll also be using the PIL image library to keep the code as simple and abstract as possible.
The first line imports static types needed for clarity. If you don’t know what they are, check out my article on type hints.
In this code snippet I’ve defined a new Pixel type, a Tuple of four integers each representing one of the channels in a RGBA pixel. I’ve then defined a function that extracts the given pixel’s intensity. It first sums all the channel values and then divides the result by the maximum value a pixel’s channels can reach to effectively get an intensity percentage.
Once we’ve calculated the pixel’s intensity, it’s time to map it to an ASCII character. For this we have to define a character set we’ll be using to represent the pixels.
The character set is ordered from the lightest, the space, to the heaviest, the @. This means that the more intense a pixel is, the more space its corresponding ASCII character occupies.
The function maps the given pixel intensity to a character in the set. The result of intensity * len(CHARACTERS) is rounded since indexes must be integers.
Now, lets glue these code snippets together with a simple script:
Once we have obtained an ASCII string representation of the image, we have to find a way to view it graphically. The easiest way to to that is to print it to the console. Since images are usually organized in rows of pixels, when printing them we must also use newline characters accordingly.
Here I’ve written a simple function that prints an ASCII art to the console and how it can be called from the main function:
Let’s see this script in action! We’ll convert a simple image like this one:
Assuming we’ve called the image file image.png and the script converter.py, the command would look like this:
python converter.py image.png# Or if you are on a Unix-like system and the script is executable./converter.py image.png
This will produce the following output to the console:
As you can see the picture gets a bit distorted due to the spacing between the lines. This is a limitation of many terminal emulators, but there’s an easy solution.
We’ve already seen how to convert an image to its ASCII representation, but it would be nicer of you could save the result into an actual file. But why HTML?
It’s supported by all web browsers.
You can easily zoom in and out depending on the scale of the image.
It can be still composed of only ASCII characters.
Let’s write a function to save the resulting image into an HTML file:
Now that we’ve completed the our image converter, let’s take some time to look at a few cool pictures and their ASCII version:
Here’s the link to the project’s GitHub repository I’ve based this article on. I’ll also directly include the source code in the gist below in case you were short on time:
In case someone is interested, I’ve also set up a simple free website that converts your images into ASCII. I disclaim though that this is not a serious project and may contain bugs and vulnerabilities, so don’t even remotely think about relying on it for anything.
In this article you have briefly learnt how image files are structured and, most importantly, how to convert the single pixels into their corresponding ASCII character.
This kind of ASCII art could be used, for example, as design elements in a web page. ASCII image conversion could also be the base for some cool photo filters and video effects to be used on social media. Moreover, even if you couldn’t make use of this technique, it would still be a nice coding exercise.
I hope you enjoyed this article and learnt something new along the way,
Thanks for reading! | [
{
"code": null,
"e": 455,
"s": 172,
"text": "I’m sure many of you have heard of ASCII art, a graphic design technique that uses the printable ASCII character set to compose pictures. The simplest form of this art are emoticons such as :-) or :-3. But can you represent a more complex image with just printable ASCII characters?"
},
{
"code": null,
"e": 852,
"s": 455,
"text": "First of all, is important to clarify how an image is represented in computer systems. Pictures are usually stored in formats such as .png or .jpg on the disk. All these file types have a similar structure: they’re roughly composed of an header and a data section. The former stores useful information about the image such as its format signature, whereas the latter stores the actual pixel data."
},
{
"code": null,
"e": 1388,
"s": 852,
"text": "The actual image you see is composed of pixels, the smallest addressable element of a raster image which we’re all familiar with. They’re usually represented as a set of channels, also referred as colors. Among the most common color values there are the classic RGB (Red Green Blue) and RGBA (Red Green Blue Alpha). The difference between the two is that the latter has an additional channel, called “alpha”, that specifies the image opacity. RGBA is what we’ll be working with since it can also be used to represent a void background."
},
{
"code": null,
"e": 1736,
"s": 1388,
"text": "Now that we’ve seen how images are represented, it’s time to talk about how a pixel can be transformed into an actual ASCII character. To understand this, we must first take a look at pixel color intensity. This value refers to the sum of all the pixel’s channels, divided by the sum of the maximum values the channels can have (in this case 255)."
},
{
"code": null,
"e": 1969,
"s": 1736,
"text": "From now on I’ll be using Python for the code examples for its simplicity and readability, but feel free to use any technology you prefer. I’ll also be using the PIL image library to keep the code as simple and abstract as possible."
},
{
"code": null,
"e": 2094,
"s": 1969,
"text": "The first line imports static types needed for clarity. If you don’t know what they are, check out my article on type hints."
},
{
"code": null,
"e": 2457,
"s": 2094,
"text": "In this code snippet I’ve defined a new Pixel type, a Tuple of four integers each representing one of the channels in a RGBA pixel. I’ve then defined a function that extracts the given pixel’s intensity. It first sums all the channel values and then divides the result by the maximum value a pixel’s channels can reach to effectively get an intensity percentage."
},
{
"code": null,
"e": 2628,
"s": 2457,
"text": "Once we’ve calculated the pixel’s intensity, it’s time to map it to an ASCII character. For this we have to define a character set we’ll be using to represent the pixels."
},
{
"code": null,
"e": 2815,
"s": 2628,
"text": "The character set is ordered from the lightest, the space, to the heaviest, the @. This means that the more intense a pixel is, the more space its corresponding ASCII character occupies."
},
{
"code": null,
"e": 2971,
"s": 2815,
"text": "The function maps the given pixel intensity to a character in the set. The result of intensity * len(CHARACTERS) is rounded since indexes must be integers."
},
{
"code": null,
"e": 3037,
"s": 2971,
"text": "Now, lets glue these code snippets together with a simple script:"
},
{
"code": null,
"e": 3330,
"s": 3037,
"text": "Once we have obtained an ASCII string representation of the image, we have to find a way to view it graphically. The easiest way to to that is to print it to the console. Since images are usually organized in rows of pixels, when printing them we must also use newline characters accordingly."
},
{
"code": null,
"e": 3455,
"s": 3330,
"text": "Here I’ve written a simple function that prints an ASCII art to the console and how it can be called from the main function:"
},
{
"code": null,
"e": 3532,
"s": 3455,
"text": "Let’s see this script in action! We’ll convert a simple image like this one:"
},
{
"code": null,
"e": 3642,
"s": 3532,
"text": "Assuming we’ve called the image file image.png and the script converter.py, the command would look like this:"
},
{
"code": null,
"e": 3762,
"s": 3642,
"text": "python converter.py image.png# Or if you are on a Unix-like system and the script is executable./converter.py image.png"
},
{
"code": null,
"e": 3817,
"s": 3762,
"text": "This will produce the following output to the console:"
},
{
"code": null,
"e": 3982,
"s": 3817,
"text": "As you can see the picture gets a bit distorted due to the spacing between the lines. This is a limitation of many terminal emulators, but there’s an easy solution."
},
{
"code": null,
"e": 4140,
"s": 3982,
"text": "We’ve already seen how to convert an image to its ASCII representation, but it would be nicer of you could save the result into an actual file. But why HTML?"
},
{
"code": null,
"e": 4176,
"s": 4140,
"text": "It’s supported by all web browsers."
},
{
"code": null,
"e": 4244,
"s": 4176,
"text": "You can easily zoom in and out depending on the scale of the image."
},
{
"code": null,
"e": 4295,
"s": 4244,
"text": "It can be still composed of only ASCII characters."
},
{
"code": null,
"e": 4365,
"s": 4295,
"text": "Let’s write a function to save the resulting image into an HTML file:"
},
{
"code": null,
"e": 4492,
"s": 4365,
"text": "Now that we’ve completed the our image converter, let’s take some time to look at a few cool pictures and their ASCII version:"
},
{
"code": null,
"e": 4664,
"s": 4492,
"text": "Here’s the link to the project’s GitHub repository I’ve based this article on. I’ll also directly include the source code in the gist below in case you were short on time:"
},
{
"code": null,
"e": 4930,
"s": 4664,
"text": "In case someone is interested, I’ve also set up a simple free website that converts your images into ASCII. I disclaim though that this is not a serious project and may contain bugs and vulnerabilities, so don’t even remotely think about relying on it for anything."
},
{
"code": null,
"e": 5099,
"s": 4930,
"text": "In this article you have briefly learnt how image files are structured and, most importantly, how to convert the single pixels into their corresponding ASCII character."
},
{
"code": null,
"e": 5405,
"s": 5099,
"text": "This kind of ASCII art could be used, for example, as design elements in a web page. ASCII image conversion could also be the base for some cool photo filters and video effects to be used on social media. Moreover, even if you couldn’t make use of this technique, it would still be a nice coding exercise."
},
{
"code": null,
"e": 5477,
"s": 5405,
"text": "I hope you enjoyed this article and learnt something new along the way,"
}
] |
Swap two variables in one line in C/C+ | Here is an example of swapping in C language,
Live Demo
#include <stdio.h>
int main() {
int a = 28, b = 8;
a += b -= a = b - a; // method 1
printf("After Swapping : %d\t%d", a, b);
(a ^= b), (b ^= a), (a ^= b); // method 2
printf("\nAfter Swapping again : %d\t%d", a, b);
return 0;
}
After Swapping : 828
After Swapping again : 288
In the above program, there are two variables a and b and initialized with the values 28 and 8 respectively. There are so many methods to swap two numbers in one line and we displayed two methods here.
a += b -= a = b - a; // method 1
printf("After Swapping : %d\t%d", a, b);
(a ^= b), (b ^= a), (a ^= b); // method 2
printf("\nAfter Swapping again : %d\t%d", a, b); | [
{
"code": null,
"e": 1108,
"s": 1062,
"text": "Here is an example of swapping in C language,"
},
{
"code": null,
"e": 1119,
"s": 1108,
"text": " Live Demo"
},
{
"code": null,
"e": 1365,
"s": 1119,
"text": "#include <stdio.h>\nint main() {\n int a = 28, b = 8;\n a += b -= a = b - a; // method 1\n printf(\"After Swapping : %d\\t%d\", a, b);\n (a ^= b), (b ^= a), (a ^= b); // method 2\n printf(\"\\nAfter Swapping again : %d\\t%d\", a, b);\n return 0;\n}"
},
{
"code": null,
"e": 1413,
"s": 1365,
"text": "After Swapping : 828\nAfter Swapping again : 288"
},
{
"code": null,
"e": 1615,
"s": 1413,
"text": "In the above program, there are two variables a and b and initialized with the values 28 and 8 respectively. There are so many methods to swap two numbers in one line and we displayed two methods here."
},
{
"code": null,
"e": 1780,
"s": 1615,
"text": "a += b -= a = b - a; // method 1\nprintf(\"After Swapping : %d\\t%d\", a, b);\n(a ^= b), (b ^= a), (a ^= b); // method 2\nprintf(\"\\nAfter Swapping again : %d\\t%d\", a, b);"
}
] |
1[0]1 Pattern Count | Practice | GeeksforGeeks | Given a string S, your task is to find the number of patterns of form 1[0]1 where [0] represents any number of zeroes (minimum requirement is one 0) there should not be any other character except 0 in the [0] sequence.
Example 1:
Input:
S = "100001abc101"
Output: 2
Explanation:
The two patterns are "100001" and "101".
Example 2:
Input:
S = "1001ab010abc01001"
Output: 2
Explanation:
The two patterns are "1001"(at start)
and "1001"(at end).
User Task:
Your task is to complete the function patternCount() which takes a single argument(string S) and returns the count of patterns. You need not take any input or print anything.
Expected Time Complexity: O(|S|).
Expected Auxiliary Space: O(1).
Constraints:
1<=Length of String<=10^5
0
surjit200120012 months ago
C++
int patternCount(string S)
{
int n=S.length();
int prev=-1;
int res=0;
for(int i=0;i<n;i++){
if(S[i]=='1'){
if(prev!=-1){
if(i-prev>1)res++;
}
prev=i;
}else if(S[i]!='0'){
prev=-1;
}
}
return res;
}
0
mayank20213 months ago
C++int patternCount(string S) { int count=0,i; for(i=0; i<S.size();i++) { if(S[i]=='1') { if(S[i+1]!='0') continue; else { while(S[i+1]=='0') i=i+1; i=i+1; } if(S[i]=='1') { i=i-1; count++; } } } return count;
}
0
kushbooagarwal35844 months ago
class Solution
{
public:
int patternCount(string s)
{
//code here.
int zeroes = 0,count = 0;
int i = 0;
while(i<s.size()){
if(s[i] == '1'){
while(s[i+1] == '0'){
zeroes++;
i++;
}
if(s[i+1] == '1' && zeroes >= 1){
count++;
}
zeroes = 0;
}
i++;
}
return count;
}
};
0
tanujyoti9997 months ago
class Solution
{
public:
int patternCount(string s)
{
int i=0, cnt=0;
int n=s.length();
while(i<n)
{
while(i<n&& s[i]!='1') i++;
while(i<n && s[i]=='1') i++;
while(i<n && s[i]=='0') i++;
if(i<n && s[i]=='1') cnt++;
}
return cnt;
//code here.
}
};
0
ANKIT SINHA8 months ago
ANKIT SINHA
int patternCount(string s) { int i,n=s.size(),t=0; for(i=0;i<n;) {="" if(s[i]="='1')" {="" int="" c="0;" i++;="" while(s[i]="='0')" {="" i++;="" c++;="" }="" if(c="">0 && s[i]=='1') t++; } else i++; } return t; }https://uploads.disquscdn.c...
0
ANKIT SINHA
This comment was deleted.
0
pk verma10 months ago
pk verma
class Solution{ public: int patternCount(string s) { int ans=0; for(int i=0;i<s.size();i++) {="" if(s[i]="='1'" &&="" s[i+1]="='0'" &&="" i+1<s.size())="" {="" int="" j="i+1;" while(s[j]="='0'" &&="" j<s.size())="" j++;="" if(s[j]="='1')" ans++;="" i="j-1;" }="" }="" return="" ans;="" }="" };<="" spoiler="">
0
Jyoti11 months ago
Jyoti
0
Ravi Kumar1 year ago
Ravi Kumar
Correct AnswerC++
int patternCount(string s) { int cnt = 0; for(int i = 0; i < s.length()-1;) { bool flag1 = false; if(s[i] == '1') { flag1 = true; i++; bool flag = false; while(s[i] != '1') { if(s[i] == '0') flag = true; else if(s[i] != '0' && s[i] != '1') {flag = false;break;} i++; } if(flag == true) cnt++; } if(flag1 == false) i++; } return cnt; }
0
Himanshu Aswal1 year ago
Himanshu Aswal
C++ O(N) SOLUTION
class Solution{public: int patternCount(string s) { int n = s.size(); int sum = 0; bool o1 = 0; int zero = 0; for (int i = 0; i < n; i++) { if (s[i] == '1') { if (zero == 0) { o1 = 1; } else if (zero != 0 and o1) { sum++; zero = 0; } } else if (s[i] == '0' and o1) { zero++; } else { o1 = 0; zero = 0; } } return sum; }};
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": 457,
"s": 238,
"text": "Given a string S, your task is to find the number of patterns of form 1[0]1 where [0] represents any number of zeroes (minimum requirement is one 0) there should not be any other character except 0 in the [0] sequence."
},
{
"code": null,
"e": 469,
"s": 457,
"text": "\nExample 1:"
},
{
"code": null,
"e": 559,
"s": 469,
"text": "Input:\nS = \"100001abc101\"\nOutput: 2\nExplanation:\nThe two patterns are \"100001\" and \"101\"."
},
{
"code": null,
"e": 571,
"s": 559,
"text": "\nExample 2:"
},
{
"code": null,
"e": 683,
"s": 571,
"text": "Input:\nS = \"1001ab010abc01001\"\nOutput: 2\nExplanation:\nThe two patterns are \"1001\"(at start)\nand \"1001\"(at end)."
},
{
"code": null,
"e": 870,
"s": 683,
"text": "\nUser Task:\nYour task is to complete the function patternCount() which takes a single argument(string S) and returns the count of patterns. You need not take any input or print anything."
},
{
"code": null,
"e": 937,
"s": 870,
"text": "\nExpected Time Complexity: O(|S|).\nExpected Auxiliary Space: O(1)."
},
{
"code": null,
"e": 977,
"s": 937,
"text": "\nConstraints:\n1<=Length of String<=10^5"
},
{
"code": null,
"e": 979,
"s": 977,
"text": "0"
},
{
"code": null,
"e": 1006,
"s": 979,
"text": "surjit200120012 months ago"
},
{
"code": null,
"e": 1010,
"s": 1006,
"text": "C++"
},
{
"code": null,
"e": 1452,
"s": 1010,
"text": "int patternCount(string S) \n { \n int n=S.length();\n int prev=-1;\n int res=0;\n for(int i=0;i<n;i++){\n if(S[i]=='1'){\n if(prev!=-1){\n if(i-prev>1)res++;\n }\n prev=i;\n }else if(S[i]!='0'){\n prev=-1;\n }\n }\n return res;\n } "
},
{
"code": null,
"e": 1454,
"s": 1452,
"text": "0"
},
{
"code": null,
"e": 1477,
"s": 1454,
"text": "mayank20213 months ago"
},
{
"code": null,
"e": 1984,
"s": 1477,
"text": "C++int patternCount(string S) { int count=0,i; for(i=0; i<S.size();i++) { if(S[i]=='1') { if(S[i+1]!='0') continue; else { while(S[i+1]=='0') i=i+1; i=i+1; } if(S[i]=='1') { i=i-1; count++; } } } return count;"
},
{
"code": null,
"e": 1995,
"s": 1984,
"text": " } "
},
{
"code": null,
"e": 1997,
"s": 1995,
"text": "0"
},
{
"code": null,
"e": 2028,
"s": 1997,
"text": "kushbooagarwal35844 months ago"
},
{
"code": null,
"e": 2614,
"s": 2028,
"text": "class Solution\n{\n public:\n int patternCount(string s) \n { \n //code here.\n int zeroes = 0,count = 0;\n int i = 0;\n while(i<s.size()){\n if(s[i] == '1'){\n while(s[i+1] == '0'){\n zeroes++;\n i++;\n }\n if(s[i+1] == '1' && zeroes >= 1){\n count++;\n }\n zeroes = 0;\n }\n i++;\n }\n return count;\n } \n\n};"
},
{
"code": null,
"e": 2616,
"s": 2614,
"text": "0"
},
{
"code": null,
"e": 2641,
"s": 2616,
"text": "tanujyoti9997 months ago"
},
{
"code": null,
"e": 3068,
"s": 2641,
"text": "class Solution\n{\n public:\n int patternCount(string s) \n { \n int i=0, cnt=0;\n int n=s.length();\n while(i<n)\n {\n while(i<n&& s[i]!='1') i++;\n while(i<n && s[i]=='1') i++;\n while(i<n && s[i]=='0') i++;\n if(i<n && s[i]=='1') cnt++;\n }\n return cnt;\n //code here.\n } \n\n};"
},
{
"code": null,
"e": 3070,
"s": 3068,
"text": "0"
},
{
"code": null,
"e": 3094,
"s": 3070,
"text": "ANKIT SINHA8 months ago"
},
{
"code": null,
"e": 3106,
"s": 3094,
"text": "ANKIT SINHA"
},
{
"code": null,
"e": 3474,
"s": 3106,
"text": " int patternCount(string s) { int i,n=s.size(),t=0; for(i=0;i<n;) {=\"\" if(s[i]=\"='1')\" {=\"\" int=\"\" c=\"0;\" i++;=\"\" while(s[i]=\"='0')\" {=\"\" i++;=\"\" c++;=\"\" }=\"\" if(c=\"\">0 && s[i]=='1') t++; } else i++; } return t; }https://uploads.disquscdn.c..."
},
{
"code": null,
"e": 3476,
"s": 3474,
"text": "0"
},
{
"code": null,
"e": 3488,
"s": 3476,
"text": "ANKIT SINHA"
},
{
"code": null,
"e": 3514,
"s": 3488,
"text": "This comment was deleted."
},
{
"code": null,
"e": 3516,
"s": 3514,
"text": "0"
},
{
"code": null,
"e": 3538,
"s": 3516,
"text": "pk verma10 months ago"
},
{
"code": null,
"e": 3547,
"s": 3538,
"text": "pk verma"
},
{
"code": null,
"e": 3897,
"s": 3547,
"text": "class Solution{ public: int patternCount(string s) { int ans=0; for(int i=0;i<s.size();i++) {=\"\" if(s[i]=\"='1'\" &&=\"\" s[i+1]=\"='0'\" &&=\"\" i+1<s.size())=\"\" {=\"\" int=\"\" j=\"i+1;\" while(s[j]=\"='0'\" &&=\"\" j<s.size())=\"\" j++;=\"\" if(s[j]=\"='1')\" ans++;=\"\" i=\"j-1;\" }=\"\" }=\"\" return=\"\" ans;=\"\" }=\"\" };<=\"\" spoiler=\"\">"
},
{
"code": null,
"e": 3899,
"s": 3897,
"text": "0"
},
{
"code": null,
"e": 3918,
"s": 3899,
"text": "Jyoti11 months ago"
},
{
"code": null,
"e": 3924,
"s": 3918,
"text": "Jyoti"
},
{
"code": null,
"e": 3926,
"s": 3924,
"text": "0"
},
{
"code": null,
"e": 3947,
"s": 3926,
"text": "Ravi Kumar1 year ago"
},
{
"code": null,
"e": 3958,
"s": 3947,
"text": "Ravi Kumar"
},
{
"code": null,
"e": 3976,
"s": 3958,
"text": "Correct AnswerC++"
},
{
"code": null,
"e": 4609,
"s": 3976,
"text": "int patternCount(string s) { int cnt = 0; for(int i = 0; i < s.length()-1;) { bool flag1 = false; if(s[i] == '1') { flag1 = true; i++; bool flag = false; while(s[i] != '1') { if(s[i] == '0') flag = true; else if(s[i] != '0' && s[i] != '1') {flag = false;break;} i++; } if(flag == true) cnt++; } if(flag1 == false) i++; } return cnt; }"
},
{
"code": null,
"e": 4611,
"s": 4609,
"text": "0"
},
{
"code": null,
"e": 4636,
"s": 4611,
"text": "Himanshu Aswal1 year ago"
},
{
"code": null,
"e": 4651,
"s": 4636,
"text": "Himanshu Aswal"
},
{
"code": null,
"e": 4669,
"s": 4651,
"text": "C++ O(N) SOLUTION"
},
{
"code": null,
"e": 5121,
"s": 4669,
"text": "class Solution{public: int patternCount(string s) { int n = s.size(); int sum = 0; bool o1 = 0; int zero = 0; for (int i = 0; i < n; i++) { if (s[i] == '1') { if (zero == 0) { o1 = 1; } else if (zero != 0 and o1) { sum++; zero = 0; } } else if (s[i] == '0' and o1) { zero++; } else { o1 = 0; zero = 0; } } return sum; }};"
},
{
"code": null,
"e": 5267,
"s": 5121,
"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": 5303,
"s": 5267,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 5313,
"s": 5303,
"text": "\nProblem\n"
},
{
"code": null,
"e": 5323,
"s": 5313,
"text": "\nContest\n"
},
{
"code": null,
"e": 5386,
"s": 5323,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 5534,
"s": 5386,
"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": 5742,
"s": 5534,
"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": 5848,
"s": 5742,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
First Unique Character in a String in Python | Suppose we have a string and we have to find the first unique character in the string. So if the string is like “people”, the first letter whose occurrence is one is ‘o’. So the index will be returned, that is 2 here. If there is no such character, then return -1.
To solve this, we will follow these steps −
create one frequency map
for each character c in the string, doif c is not in frequency, then insert it into frequency, and put value 1otherwise, increase the count in frequency
if c is not in frequency, then insert it into frequency, and put value 1
otherwise, increase the count in frequency
Scan the frequency map, if the value of a specific key is 1, then return that key, otherwise return -1
Let us see the following implementation to get a better understanding −
Live Demo
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
frequency = {}
for i in s:
if i not in frequency:
frequency[i] = 1
else:
frequency[i] +=1
for i in range(len(s)):
if frequency[s[i]] == 1:
return i
return -1
ob1 = Solution()
print(ob1.firstUniqChar("people"))
print(ob1.firstUniqChar("abaabba"))
"people"
"abaabba"
2
-1 | [
{
"code": null,
"e": 1327,
"s": 1062,
"text": "Suppose we have a string and we have to find the first unique character in the string. So if the string is like “people”, the first letter whose occurrence is one is ‘o’. So the index will be returned, that is 2 here. If there is no such character, then return -1."
},
{
"code": null,
"e": 1371,
"s": 1327,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1396,
"s": 1371,
"text": "create one frequency map"
},
{
"code": null,
"e": 1549,
"s": 1396,
"text": "for each character c in the string, doif c is not in frequency, then insert it into frequency, and put value 1otherwise, increase the count in frequency"
},
{
"code": null,
"e": 1622,
"s": 1549,
"text": "if c is not in frequency, then insert it into frequency, and put value 1"
},
{
"code": null,
"e": 1665,
"s": 1622,
"text": "otherwise, increase the count in frequency"
},
{
"code": null,
"e": 1768,
"s": 1665,
"text": "Scan the frequency map, if the value of a specific key is 1, then return that key, otherwise return -1"
},
{
"code": null,
"e": 1840,
"s": 1768,
"text": "Let us see the following implementation to get a better understanding −"
},
{
"code": null,
"e": 1851,
"s": 1840,
"text": " Live Demo"
},
{
"code": null,
"e": 2296,
"s": 1851,
"text": "class Solution(object):\n def firstUniqChar(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n frequency = {}\n for i in s:\n if i not in frequency:\n frequency[i] = 1\n else:\n frequency[i] +=1\n for i in range(len(s)):\n if frequency[s[i]] == 1:\n return i\n return -1\nob1 = Solution()\nprint(ob1.firstUniqChar(\"people\"))\nprint(ob1.firstUniqChar(\"abaabba\"))"
},
{
"code": null,
"e": 2315,
"s": 2296,
"text": "\"people\"\n\"abaabba\""
},
{
"code": null,
"e": 2320,
"s": 2315,
"text": "2\n-1"
}
] |
C++ Program to Add Two Distances (in inch-feet) System Using Structures | A structure is a collection of items of different data types. It is very useful in creating complex data structures with different data type records. A structure is defined with the struct keyword.
An example of a structure is as follows −
struct DistanceFI {
int feet;
int inch;
};
The above structure defines a distance in the form of feet and inches.
A program to add two distances in inch-feet using a structure in C++ is given as follows −
Live Demo
#include <iostream>
using namespace std;
struct DistanceFI {
int feet;
int inch;
};
int main() {
struct DistanceFI distance1, distance2, distance3;
cout << "Enter feet of Distance 1: "<<endl;
cin >> distance1.feet;
cout << "Enter inches of Distance 1: "<<endl;
cin >> distance1.inch;
cout << "Enter feet of Distance 2: "<<endl;
cin >> distance2.feet;
cout << "Enter inches of Distance 2: "<<endl;
cin >> distance2.inch;
distance3.feet = distance1.feet + distance2.feet;
distance3.inch = distance1.inch + distance2.inch;
if(distance3.inch > 12) {
distance3.feet++;
distance3.inch = distance3.inch - 12;
}
cout << endl << "Sum of both distances is " << distance3.feet << " feet and " << distance3.inch << " inches";
return 0;
}
The output of the above program is as follows
Enter feet of Distance 1: 5
Enter inches of Distance 1: 9
Enter feet of Distance 2: 2
Enter inches of Distance 2: 6
Sum of both distances is 8 feet and 3 inches
In the above program, the structure DistanceFI is defined that contains the distance in feet and inches. This is given below −
struct DistanceFI{
int feet;
int inch;
};
The values of both distances to be added are acquired from the user. This is given below −
cout << "Enter feet of Distance 1: "<<endl;
cin >> distance1.feet;
cout << "Enter inches of Distance 1: "<<endl;
cin >> distance1.inch;
cout << "Enter feet of Distance 2: "<<endl;
cin >> distance2.feet;
cout << "Enter inches of Distance 2: "<<endl;
cin >> distance2.inch;
The feet and inches of the two distances are added individually. If the inches are greater than 12, then 1 is added to the feet and 12 is subtracted from the inches. This is done because 1 feet = 12 inches. The code snippet for this is given below −
distance3.feet = distance1.feet + distance2.feet;
distance3.inch = distance1.inch + distance2.inch;
if(distance3.inch > 12) {
distance3.feet++;
distance3.inch = distance3.inch - 12;
}
Finally the value of feet and inches in the added distance is displayed. This is given below −
cout << endl << "Sum of both distances is " << distance3.feet << " feet and " << distance3.inch << " inches"; | [
{
"code": null,
"e": 1260,
"s": 1062,
"text": "A structure is a collection of items of different data types. It is very useful in creating complex data structures with different data type records. A structure is defined with the struct keyword."
},
{
"code": null,
"e": 1302,
"s": 1260,
"text": "An example of a structure is as follows −"
},
{
"code": null,
"e": 1351,
"s": 1302,
"text": "struct DistanceFI {\n int feet;\n int inch;\n};"
},
{
"code": null,
"e": 1422,
"s": 1351,
"text": "The above structure defines a distance in the form of feet and inches."
},
{
"code": null,
"e": 1513,
"s": 1422,
"text": "A program to add two distances in inch-feet using a structure in C++ is given as follows −"
},
{
"code": null,
"e": 1524,
"s": 1513,
"text": " Live Demo"
},
{
"code": null,
"e": 2317,
"s": 1524,
"text": "#include <iostream>\n\nusing namespace std;\nstruct DistanceFI {\n int feet;\n int inch;\n};\nint main() {\n struct DistanceFI distance1, distance2, distance3;\n cout << \"Enter feet of Distance 1: \"<<endl;\n cin >> distance1.feet;\n cout << \"Enter inches of Distance 1: \"<<endl;\n cin >> distance1.inch;\n\n cout << \"Enter feet of Distance 2: \"<<endl;\n cin >> distance2.feet;\n cout << \"Enter inches of Distance 2: \"<<endl;\n cin >> distance2.inch;\n\n distance3.feet = distance1.feet + distance2.feet;\n distance3.inch = distance1.inch + distance2.inch;\n\n if(distance3.inch > 12) {\n distance3.feet++;\n distance3.inch = distance3.inch - 12;\n }\n cout << endl << \"Sum of both distances is \" << distance3.feet << \" feet and \" << distance3.inch << \" inches\";\n return 0;\n}"
},
{
"code": null,
"e": 2363,
"s": 2317,
"text": "The output of the above program is as follows"
},
{
"code": null,
"e": 2524,
"s": 2363,
"text": "Enter feet of Distance 1: 5\nEnter inches of Distance 1: 9\nEnter feet of Distance 2: 2\nEnter inches of Distance 2: 6\nSum of both distances is 8 feet and 3 inches"
},
{
"code": null,
"e": 2651,
"s": 2524,
"text": "In the above program, the structure DistanceFI is defined that contains the distance in feet and inches. This is given below −"
},
{
"code": null,
"e": 2699,
"s": 2651,
"text": "struct DistanceFI{\n int feet;\n int inch;\n};"
},
{
"code": null,
"e": 2790,
"s": 2699,
"text": "The values of both distances to be added are acquired from the user. This is given below −"
},
{
"code": null,
"e": 3063,
"s": 2790,
"text": "cout << \"Enter feet of Distance 1: \"<<endl;\ncin >> distance1.feet;\ncout << \"Enter inches of Distance 1: \"<<endl;\ncin >> distance1.inch;\n\ncout << \"Enter feet of Distance 2: \"<<endl;\ncin >> distance2.feet;\ncout << \"Enter inches of Distance 2: \"<<endl;\ncin >> distance2.inch;"
},
{
"code": null,
"e": 3313,
"s": 3063,
"text": "The feet and inches of the two distances are added individually. If the inches are greater than 12, then 1 is added to the feet and 12 is subtracted from the inches. This is done because 1 feet = 12 inches. The code snippet for this is given below −"
},
{
"code": null,
"e": 3503,
"s": 3313,
"text": "distance3.feet = distance1.feet + distance2.feet;\ndistance3.inch = distance1.inch + distance2.inch;\nif(distance3.inch > 12) {\n distance3.feet++;\n distance3.inch = distance3.inch - 12;\n}"
},
{
"code": null,
"e": 3598,
"s": 3503,
"text": "Finally the value of feet and inches in the added distance is displayed. This is given below −"
},
{
"code": null,
"e": 3708,
"s": 3598,
"text": "cout << endl << \"Sum of both distances is \" << distance3.feet << \" feet and \" << distance3.inch << \" inches\";"
}
] |
Scala List sum() method with example - GeeksforGeeks | 26 Jul, 2019
The sum() method is utilized to add all the elements of the stated list.
Method Definition: def sum(num: math.Numeric[B]): B
Return Type: It returns the sum of all the elements of the list.
Example #1:
// Scala program of sum()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a list val m1 = List(1, 2, 3, 4, 5, 7) // Applying sum method val result = m1.sum // Displays output println(result) }}
22
Example #2:
// Scala program of sum()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a list val m1 = List(1, 0) // Applying sum method val result = m1.sum // Displays output println(result) }}
1
Scala
Scala-list
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Scala Tutorial – Learn Scala with Step By Step Guide
Type Casting in Scala
Scala Lists
Class and Object in Scala
Break statement in Scala
Scala String substring() method with example
Lambda Expression in Scala
Scala String replace() method with example
Operators in Scala
Scala | Arrays | [
{
"code": null,
"e": 23575,
"s": 23547,
"text": "\n26 Jul, 2019"
},
{
"code": null,
"e": 23648,
"s": 23575,
"text": "The sum() method is utilized to add all the elements of the stated list."
},
{
"code": null,
"e": 23700,
"s": 23648,
"text": "Method Definition: def sum(num: math.Numeric[B]): B"
},
{
"code": null,
"e": 23765,
"s": 23700,
"text": "Return Type: It returns the sum of all the elements of the list."
},
{
"code": null,
"e": 23777,
"s": 23765,
"text": "Example #1:"
},
{
"code": "// Scala program of sum()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a list val m1 = List(1, 2, 3, 4, 5, 7) // Applying sum method val result = m1.sum // Displays output println(result) }}",
"e": 24110,
"s": 23777,
"text": null
},
{
"code": null,
"e": 24114,
"s": 24110,
"text": "22\n"
},
{
"code": null,
"e": 24126,
"s": 24114,
"text": "Example #2:"
},
{
"code": "// Scala program of sum()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a list val m1 = List(1, 0) // Applying sum method val result = m1.sum // Displays output println(result) }}",
"e": 24447,
"s": 24126,
"text": null
},
{
"code": null,
"e": 24450,
"s": 24447,
"text": "1\n"
},
{
"code": null,
"e": 24456,
"s": 24450,
"text": "Scala"
},
{
"code": null,
"e": 24467,
"s": 24456,
"text": "Scala-list"
},
{
"code": null,
"e": 24480,
"s": 24467,
"text": "Scala-Method"
},
{
"code": null,
"e": 24486,
"s": 24480,
"text": "Scala"
},
{
"code": null,
"e": 24584,
"s": 24486,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 24593,
"s": 24584,
"text": "Comments"
},
{
"code": null,
"e": 24606,
"s": 24593,
"text": "Old Comments"
},
{
"code": null,
"e": 24659,
"s": 24606,
"text": "Scala Tutorial – Learn Scala with Step By Step Guide"
},
{
"code": null,
"e": 24681,
"s": 24659,
"text": "Type Casting in Scala"
},
{
"code": null,
"e": 24693,
"s": 24681,
"text": "Scala Lists"
},
{
"code": null,
"e": 24719,
"s": 24693,
"text": "Class and Object in Scala"
},
{
"code": null,
"e": 24744,
"s": 24719,
"text": "Break statement in Scala"
},
{
"code": null,
"e": 24789,
"s": 24744,
"text": "Scala String substring() method with example"
},
{
"code": null,
"e": 24816,
"s": 24789,
"text": "Lambda Expression in Scala"
},
{
"code": null,
"e": 24859,
"s": 24816,
"text": "Scala String replace() method with example"
},
{
"code": null,
"e": 24878,
"s": 24859,
"text": "Operators in Scala"
}
] |
WPF - Nesting of Layout | Nesting of layout means the use layout panel inside another layout, e.g. define stack panels inside a grid. This concept is widely used to take the advantages of multiple layouts in an application. In the following example, we will be using stack panels inside a grid.
Let’s have a look at the following XAML code.
<Window x:Class = "WPFNestingLayouts.MainWindow"
xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d = "http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local = "clr-namespace:WPFNestingLayouts"
mc:Ignorable = "d" Title = "MainWindow" Height = "350" Width = "604">
<Grid Background = "AntiqueWhite">
<Grid.RowDefinitions>
<RowDefinition Height = "*" />
<RowDefinition Height = "*" />
<RowDefinition Height = "*" />
<RowDefinition Height = "*" />
<RowDefinition Height = "*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width = "*" />
</Grid.ColumnDefinitions>
<Label Content = "Employee Info" FontSize = "15"
FontWeight = "Bold" Grid.Column = "0" Grid.Row = "0"/>
<StackPanel Grid.Column = "0" Grid.Row = "1" Orientation = "Horizontal">
<Label Content = "Name" VerticalAlignment = "Center" Width = "70"/>
<TextBox Name = "txtName" Text = "Muhammad Ali" VerticalAlignment = "Center"
Width = "200">
</TextBox>
</StackPanel>
<StackPanel Grid.Column = "0" Grid.Row = "2" Orientation = "Horizontal">
<Label Content = "ID" VerticalAlignment = "Center" Width = "70"/>
<TextBox Name = "txtCity" Text = "421" VerticalAlignment = "Center"
Width = "50">
</TextBox>
</StackPanel>
<StackPanel Grid.Column = "0" Grid.Row = "3" Orientation = "Horizontal">
<Label Content = "Age" VerticalAlignment = "Center" Width = "70"/>
<TextBox Name = "txtState" Text = "32" VerticalAlignment = "Center"
Width = "50"></TextBox>
</StackPanel>
<StackPanel Grid.Column = "0" Grid.Row = "4" Orientation = "Horizontal">
<Label Content = "Title" VerticalAlignment = "Center" Width = "70"/>
<TextBox Name = "txtCountry" Text = "Programmer" VerticalAlignment = "Center"
Width = "200"></TextBox>
</StackPanel>
</Grid>
</Window>
When you compile and execute the above code, it will produce the following window.
We recommend that you execute the above example code and try other nesting layouts.
31 Lectures
2.5 hours
Anadi Sharma
30 Lectures
2.5 hours
Taurius Litvinavicius
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2289,
"s": 2020,
"text": "Nesting of layout means the use layout panel inside another layout, e.g. define stack panels inside a grid. This concept is widely used to take the advantages of multiple layouts in an application. In the following example, we will be using stack panels inside a grid."
},
{
"code": null,
"e": 2335,
"s": 2289,
"text": "Let’s have a look at the following XAML code."
},
{
"code": null,
"e": 4581,
"s": 2335,
"text": "<Window x:Class = \"WPFNestingLayouts.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n xmlns:d = \"http://schemas.microsoft.com/expression/blend/2008\" \n xmlns:mc = \"http://schemas.openxmlformats.org/markup-compatibility/2006\" \n xmlns:local = \"clr-namespace:WPFNestingLayouts\" \n mc:Ignorable = \"d\" Title = \"MainWindow\" Height = \"350\" Width = \"604\">\n\t\n <Grid Background = \"AntiqueWhite\"> \n <Grid.RowDefinitions> \n <RowDefinition Height = \"*\" /> \n <RowDefinition Height = \"*\" /> \n <RowDefinition Height = \"*\" /> \n <RowDefinition Height = \"*\" /> \n <RowDefinition Height = \"*\" /> \n </Grid.RowDefinitions> \n\t\t\n <Grid.ColumnDefinitions> \n <ColumnDefinition Width = \"*\" /> \n </Grid.ColumnDefinitions> \n\t\t\n <Label Content = \"Employee Info\" FontSize = \"15\"\n FontWeight = \"Bold\" Grid.Column = \"0\" Grid.Row = \"0\"/> \n\t\t\t\n <StackPanel Grid.Column = \"0\" Grid.Row = \"1\" Orientation = \"Horizontal\"> \n <Label Content = \"Name\" VerticalAlignment = \"Center\" Width = \"70\"/> \n <TextBox Name = \"txtName\" Text = \"Muhammad Ali\" VerticalAlignment = \"Center\"\n Width = \"200\">\n </TextBox> \n </StackPanel>\n\t\t\n <StackPanel Grid.Column = \"0\" Grid.Row = \"2\" Orientation = \"Horizontal\"> \n <Label Content = \"ID\" VerticalAlignment = \"Center\" Width = \"70\"/> \n <TextBox Name = \"txtCity\" Text = \"421\" VerticalAlignment = \"Center\"\n Width = \"50\">\n </TextBox> \n </StackPanel>\n\t\t\n <StackPanel Grid.Column = \"0\" Grid.Row = \"3\" Orientation = \"Horizontal\"> \n <Label Content = \"Age\" VerticalAlignment = \"Center\" Width = \"70\"/> \n <TextBox Name = \"txtState\" Text = \"32\" VerticalAlignment = \"Center\"\n Width = \"50\"></TextBox> \n </StackPanel> \n\t\t\n <StackPanel Grid.Column = \"0\" Grid.Row = \"4\" Orientation = \"Horizontal\"> \n <Label Content = \"Title\" VerticalAlignment = \"Center\" Width = \"70\"/> \n <TextBox Name = \"txtCountry\" Text = \"Programmer\" VerticalAlignment = \"Center\"\n Width = \"200\"></TextBox> \n </StackPanel> \n\t\t\n </Grid> \n\t\n</Window> \t\t "
},
{
"code": null,
"e": 4664,
"s": 4581,
"text": "When you compile and execute the above code, it will produce the following window."
},
{
"code": null,
"e": 4748,
"s": 4664,
"text": "We recommend that you execute the above example code and try other nesting layouts."
},
{
"code": null,
"e": 4783,
"s": 4748,
"text": "\n 31 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4797,
"s": 4783,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4832,
"s": 4797,
"text": "\n 30 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4855,
"s": 4832,
"text": " Taurius Litvinavicius"
},
{
"code": null,
"e": 4862,
"s": 4855,
"text": " Print"
},
{
"code": null,
"e": 4873,
"s": 4862,
"text": " Add Notes"
}
] |
Deploying a Deep Learning Model on Heroku using Flask and Python | by Soumya Gupta | Towards Data Science | In my last post, we have seen how to deploy a machine learning model on the web using Python and Flask(Link below)
medium.com
It was cool to make predictions via CLI, but then there were issues such as manually starting the server and the lack of a simple GUI(Graphical user interface).
In this post, we will try to address the above issues via deploying our model on the Heroku Server and therefore setting up a simple 24X7 running HTML website of our own for the end-users to make predictions.
Let’s start the journey from the very basics of creating a Deep Learning Model and then going step by step through the deployment process along with learning new concepts.
Creation of a Deep Learning Model
Step1. Creating a simple Keras Model for IRIS dataset
The Iris dataset was used in R.A. Fisher’s classic 1936 paper. It includes three iris species with 50 samples each as well as some properties about each flower.
The columns in this dataset are:
Id
SepalLengthCm
SepalWidthCm
PetalLengthCm
PetalWidthCm
Species
Let’s import the necessary libraries and then load the data from iris.csv into a pandas dataframe for better understanding.
import numpy as npimport pandas as pdiris = pd.read_csv(“../DATA/iris.csv”)iris.head()
Step 2. Defining X and y for training purposes
Now once we have loaded our data we can define our X and y for training purposes, our initial four columns will contribute X and species will be labeled as y which denotes our true labels from the dataset.
X = iris.drop(‘species’,axis=1)y = iris[‘species’]
Step 3. Binarizing the labels of species
As we can see in our dataset “species” contains data which is in the String format and therefore we should encode the same into numbers, for doing the same we can use LabelBinarizer from sklearn.preprocessing library via below code
from sklearn.preprocessing import LabelBinarizerencoder = LabelBinarizer()y = encoder.fit_transform(y)
Now if we’ll check our “y” it should be binarized as below, where [1,0,0] denotes the flower “Setosa”, [0,1,0] denotes “Virginica” and [0,0,1] denotes “Versicolor”.
Step 4. Scaling the data
It’s always important to scale our data before feeding the model to ensure we have the values of all the columns present in the same range, you can use any of the scalers present in scikit-learn such as StandardScaler or MinMaxScaler, we are using MinMax scaler below
from sklearn.preprocessing import MinMaxScalerscaler = MinMaxScaler()scaled_X = scaler.fit_transform(X)
Please note that we are scaling our whole X and the same will be used for training our deep learning model, you can incorporate more steps such as train_test_split as per your own modeling steps.
Step 5. Creating the Keras model
Let’s start creating a simple Keras model by importing below libraries and calling the Sequential API
from tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import Densemodel = Sequential()model.add(Dense(units=4,activation=’relu’))model.add(Dense(units=32,activation=’relu’))model.add(Dense(units=16,activation=’relu’))# Last layer for multi-class classification of 3 speciesmodel.add(Dense(units=3,activation=’softmax’))model.compile(optimizer=’adam’,loss=’categorical_crossentropy’,metrics=[‘accuracy’])
In the above code, we have started with creating a Sequential Keras model with the first layer as dense having 4 inputs for the 4 columns in our X (Sepal Length, Sepal Width, Petal Length, Petal Width).
After this, we have added 2 hidden layers and using “relu” as the activation function for all the layers except the last one.
The last layer contains 3 units for 3 respective classes of flowers ( Setosa, Virginica, and Versicolor) with “softmax” activation function as we are dealing with Multi-Class classification problem, also while compiling the model we are using “adam” optimizer along with “accuracy” as metrics to maximize the same and minimizing our defined loss “categorical_crossentropy” with each epoch.
Step 6. Training and saving the model
Finally, let’s start training our Keras model on some 100+ epochs, you can add mechanism of callbacks such as EarlyStopping in case you want to reduce the runtime of training.
model.fit(scaled_X,y,epochs=150)Epoch 1/150150/150 [==============================] - 0s 1ms/sample - loss: 1.1053 - accuracy: 0.3333Epoch 2/150150/150 [==============================] - 0s 93us/sample - loss: 1.0953 - accuracy: 0.3467Epoch 3/150150/150 [==============================] - 0s 86us/sample - loss: 1.0864 - accuracy: 0.5667Epoch 4/150150/150 [==============================] - 0s 100us/sample - loss: 1.0770 - accuracy: 0.6200Epoch 5/150150/150 [==============================] - 0s 86us/sample - loss: 1.0669 - accuracy: 0.4867
Post completion of training we’ll be reaching around 95% accuracy without overfitting the data. Now let’s save our model for using it later under the deployment process.
model.save(“final_iris_model.h5”)
This will save the model in your current working directory.
Step 7. Saving the scaler
We’ll also save the scaler in the present working directory so that we can scale user input data before passing it to our model and displaying the results on our website.
import joblibjoblib.dump(scaler,’iris_scaler.pkl’)
Deployment through Flask, Python on Heroku
It’s great to have our model saved along with scaler and let’s now dive into the steps of setting our own flask app and deploying it on Heroku Server.
Let’s start creating our app.py file which will be used later for deployment on Heroku Server.
Step 1. Importing the required libraries
from flask import Flask, render_template, session, redirect, url_for, sessionfrom flask_wtf import FlaskFormfrom wtforms import TextField,SubmitFieldfrom wtforms.validators import NumberRangeimport numpy as np from tensorflow.keras.models import load_modelimport joblib
Step 2. Defining a function for returning our model’s prediction
def return_prediction(model,scaler,sample_json): s_len = sample_json[‘sepal_length’] s_wid = sample_json[‘sepal_width’] p_len = sample_json[‘petal_length’] p_wid = sample_json[‘petal_width’] flower = [[s_len,s_wid,p_len,p_wid]] flower = scaler.transform(flower) classes = np.array([‘setosa’, ‘versicolor’, ‘virginica’]) class_ind = model.predict_classes(flower) return classes[class_ind][0]
In the above function, we are passing three parameters, our model, scaler and sample_json for data input from the HTML page.
JSON (JavaScript Object Notation) is the most widely used data format for data interchange on the web. This data interchange can happen between two computer applications at different geographical locations or running within the same hardware machine.
Primarily, JSON is built on below structure like a python dictionary
A collection of name/value pairs.
"employee": {"id": 1,"name": "Admin","location": "USA"}
In a similar manner, we have captured the data of sepal_length/width, petal_length/width from the incoming request
s_len = sample_json[‘sepal_length’] s_wid = sample_json[‘sepal_width’] p_len = sample_json[‘petal_length’] p_wid = sample_json[‘petal_width’]
After completion of the above steps, we have scaled our flower list and we’ve used model.predict_classes() function to get the class labels corresponding to our flower data in the below code, see the link below for more details on this function.
https://kite.com/python/docs/tensorflow.keras.Sequential.predict_classes
flower = [[s_len,s_wid,p_len,p_wid]]flower = scaler.transform(flower)classes = np.array([‘setosa’, ‘versicolor’, ‘virginica’])class_ind = model.predict_classes(flower)return classes[class_ind][0]
Step 3. Defining the app routes and completing the app.py file
In the below code comments are defined above each code block for better understanding, also please visit my last post from the below link in case you need some more understanding towards the basic flask architecture.
https://medium.com/analytics-vidhya/deploying-a-machine-learning-model-on-web-using-flask-and-python-54b86c44e14a
app = Flask(__name__)# Configure a secret SECRET_KEYapp.config[‘SECRET_KEY’] = ‘someRandomKey’# Loading the model and scalerflower_model = load_model(“final_iris_model.h5”)flower_scaler = joblib.load(“iris_scaler.pkl”)# Now create a WTForm Classclass FlowerForm(FlaskForm): sep_len = TextField(‘Sepal Length’) sep_wid = TextField(‘Sepal Width’) pet_len = TextField(‘Petal Length’) pet_wid = TextField(‘Petal Width’) submit = SubmitField(‘Analyze’) @app.route(‘/’, methods=[‘GET’, ‘POST’]) def index(): # Create instance of the form. form = FlowerForm() # If the form is valid on submission if form.validate_on_submit(): # Grab the data from the input on the form. session[‘sep_len’] = form.sep_len.data session[‘sep_wid’] = form.sep_wid.data session[‘pet_len’] = form.pet_len.data session[‘pet_wid’] = form.pet_wid.datareturn redirect(url_for(“prediction”))return render_template(‘home.html’, form=form)@app.route(‘/prediction’)def prediction(): #Defining content dictionary content = {}content[‘sepal_length’] = float(session[‘sep_len’]) content[‘sepal_width’] = float(session[‘sep_wid’]) content[‘petal_length’] = float(session[‘pet_len’]) content[‘petal_width’] = float(session[‘pet_wid’]) results = return_prediction(model=flower_model,scaler=flower_scaler,sample_json=content)return render_template(‘prediction.html’,results=results)if __name__ == ‘__main__’: app.run(debug=True)
Let’s understand the above code in pieces.
We are configuring a secret key. The secret key is needed to keep the client-side sessions secure in Flask. You can generate any random key of your choice.
We are using @app.route decorator for home and prediction page, refer my last post for details on these.
Also, we are creating WT Forms. Using Flask-WTF, we can define the form fields in our Python script and render them using an HTML template,
TextField Represents <input type = ‘text’> HTML form element
please install Flask-WTF via below script
pip install flask-wtf
Step 4. Defining our HTML forms for taking input from the end-user.
Now let’s proceed towards the last step to keep everything ready for the deployment.
We are going to create two basic HTML forms for end-user inputs namely home.html and prediction.html.
You can also view the code at Step 3 having both of them defined via @app.route decorator to connect Flask with the HTML templates.
home.html
<h1>Welcome to IRIS prediction</h1><h2>Please enter your flower measurements below:</h2><form method=”POST”> {# This hidden_tag is a CSRF security feature. #} {{ form.hidden_tag() }} {{ form.sep_len.label }} {{form.sep_len}} <br> {{ form.sep_wid.label}} {{form.sep_wid}} <br> {{form.pet_len.label}}{{form.pet_len}} <br> {{form.pet_wid.label}}{{form.pet_wid}} <br> {{ form.submit() }}</form>
In the above form each given entry such as -
form.sep_len, form.sep_wid etc are TextFields defined by us in Step 3 within FlowerForm class, so that once users enter the data same gets passed to a FlaskSession.
Prediction.html
<h1>Thank You. Here is the Information You Gave:</h1><ul> <li>Sepal Length: {{session[‘sep_len’]}}</li> <li>Sepal Width : {{session[‘sep_wid’]}}</li> <li>Petal Length: {{session[‘pet_len’]}}</li> <li>Petal Width : {{session[‘pet_wid’]}}</li></ul><h2>Your Predicted Flower Class is: {{results}}</h2>
And then we are passing the same data to our content dictionary defined inside prediction function in Step 3, and further using the same data as input for our model. Finally, we are displaying the results variable from Step3. into our prediction.html page.
Wrapping up everything and Deploying on Heroku
Now we have reached the last step which is deploying everything on the Heroku.
Step 1. Please set up your Project working directory in the below manner, having a separate templates folder containing your home.html and prediction.html files.
Also please add the Procfile(no extensions) with below code as a one-liner
web: gunicorn app:app
“Gunicorn”, is a Web Server Gateway Interface (WSGI) server implementation that is commonly used to run Python web applications, here app is our app.py file name.
Step 2. Create a conda virtual env for setting up all the libraries
Run below code on Anaconda Prompt after navigating to your project directory and then activate the environment.
Step1. conda create — name mydevenv python=3.7Step2. activate mydevenv
Install below libraries for your newly created environment and generate requirements.txt for Heroku
Step1. pip install flaskStep2. pip install flask-wtfStep3. pip install tensorflow2.0.0a0Step4. pip install scikit-learnStep5. pip install gunicornStep6. pip freeze > requirements.txt
Now your working directory should have requirements.txt created for Heroku deployment.
Step 3. Creating a Heroku account and install Heroku CLI for deployment
Signup for a new Heroku account https://www.heroku.com/
Install the Heroku CLI along with GIT as per your operating system
https://devcenter.heroku.com/articles/heroku-cli#download-and-install
https://git-scm.com/downloads
Please restart your system once completed, type heroku on command prompt and if there is no error of “Heroku not found” you are good to proceed to the next step.
Step 4. Deploying the app to Heroku Server
Login to Heroku by opening a new command prompt and typing below.
heroku login
press any key and once done you will be redirected to login page in your browser, complete the login process there.
Now go to the Heroku home page and click on create a new app as below
After completing the above follow few last steps for deployment to the server.
Initialize a git repository in the directory. Replace ml-deployment-app with your own app name.
$ cd my-project/$ git init$ heroku git:remote -a ml-deployment-app
Commit your code to the repository and deploy it to Heroku using Git.
$ git add .$ git commit -am "adding files"$ git push heroku master
Finally, you should be able to see the success message on CLI as below along with the URL for your app.
Congratulations on your own live app hosted on the Web.
See the running app on the below web address.
https://ml-deployment-app.herokuapp.com/
In case you have missed something or facing issues all the code files are present on the below link of Github.
https://github.com/guptasoumya26/ml-deployment-app-heroku
In this post, we learned about Flask with Web, how to integrate it with the HTML website, and most importantly how to apply this knowledge to deploy the same on a WebServer, so that end-users can interact with our ML model anytime without any external dependency.
I hope you found this tutorial useful, Thank you for reading till here. I’m curious about what you think so hit me with some comments.You can also get in touch with me directly through email or connect with me on LinkedIn. | [
{
"code": null,
"e": 287,
"s": 172,
"text": "In my last post, we have seen how to deploy a machine learning model on the web using Python and Flask(Link below)"
},
{
"code": null,
"e": 298,
"s": 287,
"text": "medium.com"
},
{
"code": null,
"e": 459,
"s": 298,
"text": "It was cool to make predictions via CLI, but then there were issues such as manually starting the server and the lack of a simple GUI(Graphical user interface)."
},
{
"code": null,
"e": 668,
"s": 459,
"text": "In this post, we will try to address the above issues via deploying our model on the Heroku Server and therefore setting up a simple 24X7 running HTML website of our own for the end-users to make predictions."
},
{
"code": null,
"e": 840,
"s": 668,
"text": "Let’s start the journey from the very basics of creating a Deep Learning Model and then going step by step through the deployment process along with learning new concepts."
},
{
"code": null,
"e": 874,
"s": 840,
"text": "Creation of a Deep Learning Model"
},
{
"code": null,
"e": 928,
"s": 874,
"text": "Step1. Creating a simple Keras Model for IRIS dataset"
},
{
"code": null,
"e": 1089,
"s": 928,
"text": "The Iris dataset was used in R.A. Fisher’s classic 1936 paper. It includes three iris species with 50 samples each as well as some properties about each flower."
},
{
"code": null,
"e": 1122,
"s": 1089,
"text": "The columns in this dataset are:"
},
{
"code": null,
"e": 1125,
"s": 1122,
"text": "Id"
},
{
"code": null,
"e": 1139,
"s": 1125,
"text": "SepalLengthCm"
},
{
"code": null,
"e": 1152,
"s": 1139,
"text": "SepalWidthCm"
},
{
"code": null,
"e": 1166,
"s": 1152,
"text": "PetalLengthCm"
},
{
"code": null,
"e": 1179,
"s": 1166,
"text": "PetalWidthCm"
},
{
"code": null,
"e": 1187,
"s": 1179,
"text": "Species"
},
{
"code": null,
"e": 1311,
"s": 1187,
"text": "Let’s import the necessary libraries and then load the data from iris.csv into a pandas dataframe for better understanding."
},
{
"code": null,
"e": 1398,
"s": 1311,
"text": "import numpy as npimport pandas as pdiris = pd.read_csv(“../DATA/iris.csv”)iris.head()"
},
{
"code": null,
"e": 1445,
"s": 1398,
"text": "Step 2. Defining X and y for training purposes"
},
{
"code": null,
"e": 1651,
"s": 1445,
"text": "Now once we have loaded our data we can define our X and y for training purposes, our initial four columns will contribute X and species will be labeled as y which denotes our true labels from the dataset."
},
{
"code": null,
"e": 1702,
"s": 1651,
"text": "X = iris.drop(‘species’,axis=1)y = iris[‘species’]"
},
{
"code": null,
"e": 1743,
"s": 1702,
"text": "Step 3. Binarizing the labels of species"
},
{
"code": null,
"e": 1975,
"s": 1743,
"text": "As we can see in our dataset “species” contains data which is in the String format and therefore we should encode the same into numbers, for doing the same we can use LabelBinarizer from sklearn.preprocessing library via below code"
},
{
"code": null,
"e": 2078,
"s": 1975,
"text": "from sklearn.preprocessing import LabelBinarizerencoder = LabelBinarizer()y = encoder.fit_transform(y)"
},
{
"code": null,
"e": 2243,
"s": 2078,
"text": "Now if we’ll check our “y” it should be binarized as below, where [1,0,0] denotes the flower “Setosa”, [0,1,0] denotes “Virginica” and [0,0,1] denotes “Versicolor”."
},
{
"code": null,
"e": 2268,
"s": 2243,
"text": "Step 4. Scaling the data"
},
{
"code": null,
"e": 2536,
"s": 2268,
"text": "It’s always important to scale our data before feeding the model to ensure we have the values of all the columns present in the same range, you can use any of the scalers present in scikit-learn such as StandardScaler or MinMaxScaler, we are using MinMax scaler below"
},
{
"code": null,
"e": 2640,
"s": 2536,
"text": "from sklearn.preprocessing import MinMaxScalerscaler = MinMaxScaler()scaled_X = scaler.fit_transform(X)"
},
{
"code": null,
"e": 2836,
"s": 2640,
"text": "Please note that we are scaling our whole X and the same will be used for training our deep learning model, you can incorporate more steps such as train_test_split as per your own modeling steps."
},
{
"code": null,
"e": 2869,
"s": 2836,
"text": "Step 5. Creating the Keras model"
},
{
"code": null,
"e": 2971,
"s": 2869,
"text": "Let’s start creating a simple Keras model by importing below libraries and calling the Sequential API"
},
{
"code": null,
"e": 3396,
"s": 2971,
"text": "from tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import Densemodel = Sequential()model.add(Dense(units=4,activation=’relu’))model.add(Dense(units=32,activation=’relu’))model.add(Dense(units=16,activation=’relu’))# Last layer for multi-class classification of 3 speciesmodel.add(Dense(units=3,activation=’softmax’))model.compile(optimizer=’adam’,loss=’categorical_crossentropy’,metrics=[‘accuracy’])"
},
{
"code": null,
"e": 3599,
"s": 3396,
"text": "In the above code, we have started with creating a Sequential Keras model with the first layer as dense having 4 inputs for the 4 columns in our X (Sepal Length, Sepal Width, Petal Length, Petal Width)."
},
{
"code": null,
"e": 3725,
"s": 3599,
"text": "After this, we have added 2 hidden layers and using “relu” as the activation function for all the layers except the last one."
},
{
"code": null,
"e": 4115,
"s": 3725,
"text": "The last layer contains 3 units for 3 respective classes of flowers ( Setosa, Virginica, and Versicolor) with “softmax” activation function as we are dealing with Multi-Class classification problem, also while compiling the model we are using “adam” optimizer along with “accuracy” as metrics to maximize the same and minimizing our defined loss “categorical_crossentropy” with each epoch."
},
{
"code": null,
"e": 4153,
"s": 4115,
"text": "Step 6. Training and saving the model"
},
{
"code": null,
"e": 4329,
"s": 4153,
"text": "Finally, let’s start training our Keras model on some 100+ epochs, you can add mechanism of callbacks such as EarlyStopping in case you want to reduce the runtime of training."
},
{
"code": null,
"e": 4872,
"s": 4329,
"text": "model.fit(scaled_X,y,epochs=150)Epoch 1/150150/150 [==============================] - 0s 1ms/sample - loss: 1.1053 - accuracy: 0.3333Epoch 2/150150/150 [==============================] - 0s 93us/sample - loss: 1.0953 - accuracy: 0.3467Epoch 3/150150/150 [==============================] - 0s 86us/sample - loss: 1.0864 - accuracy: 0.5667Epoch 4/150150/150 [==============================] - 0s 100us/sample - loss: 1.0770 - accuracy: 0.6200Epoch 5/150150/150 [==============================] - 0s 86us/sample - loss: 1.0669 - accuracy: 0.4867"
},
{
"code": null,
"e": 5042,
"s": 4872,
"text": "Post completion of training we’ll be reaching around 95% accuracy without overfitting the data. Now let’s save our model for using it later under the deployment process."
},
{
"code": null,
"e": 5076,
"s": 5042,
"text": "model.save(“final_iris_model.h5”)"
},
{
"code": null,
"e": 5136,
"s": 5076,
"text": "This will save the model in your current working directory."
},
{
"code": null,
"e": 5162,
"s": 5136,
"text": "Step 7. Saving the scaler"
},
{
"code": null,
"e": 5333,
"s": 5162,
"text": "We’ll also save the scaler in the present working directory so that we can scale user input data before passing it to our model and displaying the results on our website."
},
{
"code": null,
"e": 5384,
"s": 5333,
"text": "import joblibjoblib.dump(scaler,’iris_scaler.pkl’)"
},
{
"code": null,
"e": 5427,
"s": 5384,
"text": "Deployment through Flask, Python on Heroku"
},
{
"code": null,
"e": 5578,
"s": 5427,
"text": "It’s great to have our model saved along with scaler and let’s now dive into the steps of setting our own flask app and deploying it on Heroku Server."
},
{
"code": null,
"e": 5673,
"s": 5578,
"text": "Let’s start creating our app.py file which will be used later for deployment on Heroku Server."
},
{
"code": null,
"e": 5714,
"s": 5673,
"text": "Step 1. Importing the required libraries"
},
{
"code": null,
"e": 5984,
"s": 5714,
"text": "from flask import Flask, render_template, session, redirect, url_for, sessionfrom flask_wtf import FlaskFormfrom wtforms import TextField,SubmitFieldfrom wtforms.validators import NumberRangeimport numpy as np from tensorflow.keras.models import load_modelimport joblib"
},
{
"code": null,
"e": 6049,
"s": 5984,
"text": "Step 2. Defining a function for returning our model’s prediction"
},
{
"code": null,
"e": 6444,
"s": 6049,
"text": "def return_prediction(model,scaler,sample_json): s_len = sample_json[‘sepal_length’] s_wid = sample_json[‘sepal_width’] p_len = sample_json[‘petal_length’] p_wid = sample_json[‘petal_width’] flower = [[s_len,s_wid,p_len,p_wid]] flower = scaler.transform(flower) classes = np.array([‘setosa’, ‘versicolor’, ‘virginica’]) class_ind = model.predict_classes(flower) return classes[class_ind][0]"
},
{
"code": null,
"e": 6569,
"s": 6444,
"text": "In the above function, we are passing three parameters, our model, scaler and sample_json for data input from the HTML page."
},
{
"code": null,
"e": 6820,
"s": 6569,
"text": "JSON (JavaScript Object Notation) is the most widely used data format for data interchange on the web. This data interchange can happen between two computer applications at different geographical locations or running within the same hardware machine."
},
{
"code": null,
"e": 6889,
"s": 6820,
"text": "Primarily, JSON is built on below structure like a python dictionary"
},
{
"code": null,
"e": 6923,
"s": 6889,
"text": "A collection of name/value pairs."
},
{
"code": null,
"e": 7001,
"s": 6923,
"text": "\"employee\": {\"id\": 1,\"name\": \"Admin\",\"location\": \"USA\"}"
},
{
"code": null,
"e": 7116,
"s": 7001,
"text": "In a similar manner, we have captured the data of sepal_length/width, petal_length/width from the incoming request"
},
{
"code": null,
"e": 7258,
"s": 7116,
"text": "s_len = sample_json[‘sepal_length’] s_wid = sample_json[‘sepal_width’] p_len = sample_json[‘petal_length’] p_wid = sample_json[‘petal_width’]"
},
{
"code": null,
"e": 7504,
"s": 7258,
"text": "After completion of the above steps, we have scaled our flower list and we’ve used model.predict_classes() function to get the class labels corresponding to our flower data in the below code, see the link below for more details on this function."
},
{
"code": null,
"e": 7577,
"s": 7504,
"text": "https://kite.com/python/docs/tensorflow.keras.Sequential.predict_classes"
},
{
"code": null,
"e": 7773,
"s": 7577,
"text": "flower = [[s_len,s_wid,p_len,p_wid]]flower = scaler.transform(flower)classes = np.array([‘setosa’, ‘versicolor’, ‘virginica’])class_ind = model.predict_classes(flower)return classes[class_ind][0]"
},
{
"code": null,
"e": 7836,
"s": 7773,
"text": "Step 3. Defining the app routes and completing the app.py file"
},
{
"code": null,
"e": 8053,
"s": 7836,
"text": "In the below code comments are defined above each code block for better understanding, also please visit my last post from the below link in case you need some more understanding towards the basic flask architecture."
},
{
"code": null,
"e": 8167,
"s": 8053,
"text": "https://medium.com/analytics-vidhya/deploying-a-machine-learning-model-on-web-using-flask-and-python-54b86c44e14a"
},
{
"code": null,
"e": 9562,
"s": 8167,
"text": "app = Flask(__name__)# Configure a secret SECRET_KEYapp.config[‘SECRET_KEY’] = ‘someRandomKey’# Loading the model and scalerflower_model = load_model(“final_iris_model.h5”)flower_scaler = joblib.load(“iris_scaler.pkl”)# Now create a WTForm Classclass FlowerForm(FlaskForm): sep_len = TextField(‘Sepal Length’) sep_wid = TextField(‘Sepal Width’) pet_len = TextField(‘Petal Length’) pet_wid = TextField(‘Petal Width’) submit = SubmitField(‘Analyze’) @app.route(‘/’, methods=[‘GET’, ‘POST’]) def index(): # Create instance of the form. form = FlowerForm() # If the form is valid on submission if form.validate_on_submit(): # Grab the data from the input on the form. session[‘sep_len’] = form.sep_len.data session[‘sep_wid’] = form.sep_wid.data session[‘pet_len’] = form.pet_len.data session[‘pet_wid’] = form.pet_wid.datareturn redirect(url_for(“prediction”))return render_template(‘home.html’, form=form)@app.route(‘/prediction’)def prediction(): #Defining content dictionary content = {}content[‘sepal_length’] = float(session[‘sep_len’]) content[‘sepal_width’] = float(session[‘sep_wid’]) content[‘petal_length’] = float(session[‘pet_len’]) content[‘petal_width’] = float(session[‘pet_wid’]) results = return_prediction(model=flower_model,scaler=flower_scaler,sample_json=content)return render_template(‘prediction.html’,results=results)if __name__ == ‘__main__’: app.run(debug=True)"
},
{
"code": null,
"e": 9605,
"s": 9562,
"text": "Let’s understand the above code in pieces."
},
{
"code": null,
"e": 9761,
"s": 9605,
"text": "We are configuring a secret key. The secret key is needed to keep the client-side sessions secure in Flask. You can generate any random key of your choice."
},
{
"code": null,
"e": 9866,
"s": 9761,
"text": "We are using @app.route decorator for home and prediction page, refer my last post for details on these."
},
{
"code": null,
"e": 10006,
"s": 9866,
"text": "Also, we are creating WT Forms. Using Flask-WTF, we can define the form fields in our Python script and render them using an HTML template,"
},
{
"code": null,
"e": 10067,
"s": 10006,
"text": "TextField Represents <input type = ‘text’> HTML form element"
},
{
"code": null,
"e": 10109,
"s": 10067,
"text": "please install Flask-WTF via below script"
},
{
"code": null,
"e": 10131,
"s": 10109,
"text": "pip install flask-wtf"
},
{
"code": null,
"e": 10199,
"s": 10131,
"text": "Step 4. Defining our HTML forms for taking input from the end-user."
},
{
"code": null,
"e": 10284,
"s": 10199,
"text": "Now let’s proceed towards the last step to keep everything ready for the deployment."
},
{
"code": null,
"e": 10386,
"s": 10284,
"text": "We are going to create two basic HTML forms for end-user inputs namely home.html and prediction.html."
},
{
"code": null,
"e": 10518,
"s": 10386,
"text": "You can also view the code at Step 3 having both of them defined via @app.route decorator to connect Flask with the HTML templates."
},
{
"code": null,
"e": 10528,
"s": 10518,
"text": "home.html"
},
{
"code": null,
"e": 10919,
"s": 10528,
"text": "<h1>Welcome to IRIS prediction</h1><h2>Please enter your flower measurements below:</h2><form method=”POST”> {# This hidden_tag is a CSRF security feature. #} {{ form.hidden_tag() }} {{ form.sep_len.label }} {{form.sep_len}} <br> {{ form.sep_wid.label}} {{form.sep_wid}} <br> {{form.pet_len.label}}{{form.pet_len}} <br> {{form.pet_wid.label}}{{form.pet_wid}} <br> {{ form.submit() }}</form>"
},
{
"code": null,
"e": 10964,
"s": 10919,
"text": "In the above form each given entry such as -"
},
{
"code": null,
"e": 11129,
"s": 10964,
"text": "form.sep_len, form.sep_wid etc are TextFields defined by us in Step 3 within FlowerForm class, so that once users enter the data same gets passed to a FlaskSession."
},
{
"code": null,
"e": 11145,
"s": 11129,
"text": "Prediction.html"
},
{
"code": null,
"e": 11444,
"s": 11145,
"text": "<h1>Thank You. Here is the Information You Gave:</h1><ul> <li>Sepal Length: {{session[‘sep_len’]}}</li> <li>Sepal Width : {{session[‘sep_wid’]}}</li> <li>Petal Length: {{session[‘pet_len’]}}</li> <li>Petal Width : {{session[‘pet_wid’]}}</li></ul><h2>Your Predicted Flower Class is: {{results}}</h2>"
},
{
"code": null,
"e": 11701,
"s": 11444,
"text": "And then we are passing the same data to our content dictionary defined inside prediction function in Step 3, and further using the same data as input for our model. Finally, we are displaying the results variable from Step3. into our prediction.html page."
},
{
"code": null,
"e": 11748,
"s": 11701,
"text": "Wrapping up everything and Deploying on Heroku"
},
{
"code": null,
"e": 11827,
"s": 11748,
"text": "Now we have reached the last step which is deploying everything on the Heroku."
},
{
"code": null,
"e": 11989,
"s": 11827,
"text": "Step 1. Please set up your Project working directory in the below manner, having a separate templates folder containing your home.html and prediction.html files."
},
{
"code": null,
"e": 12064,
"s": 11989,
"text": "Also please add the Procfile(no extensions) with below code as a one-liner"
},
{
"code": null,
"e": 12086,
"s": 12064,
"text": "web: gunicorn app:app"
},
{
"code": null,
"e": 12249,
"s": 12086,
"text": "“Gunicorn”, is a Web Server Gateway Interface (WSGI) server implementation that is commonly used to run Python web applications, here app is our app.py file name."
},
{
"code": null,
"e": 12317,
"s": 12249,
"text": "Step 2. Create a conda virtual env for setting up all the libraries"
},
{
"code": null,
"e": 12429,
"s": 12317,
"text": "Run below code on Anaconda Prompt after navigating to your project directory and then activate the environment."
},
{
"code": null,
"e": 12500,
"s": 12429,
"text": "Step1. conda create — name mydevenv python=3.7Step2. activate mydevenv"
},
{
"code": null,
"e": 12600,
"s": 12500,
"text": "Install below libraries for your newly created environment and generate requirements.txt for Heroku"
},
{
"code": null,
"e": 12783,
"s": 12600,
"text": "Step1. pip install flaskStep2. pip install flask-wtfStep3. pip install tensorflow2.0.0a0Step4. pip install scikit-learnStep5. pip install gunicornStep6. pip freeze > requirements.txt"
},
{
"code": null,
"e": 12870,
"s": 12783,
"text": "Now your working directory should have requirements.txt created for Heroku deployment."
},
{
"code": null,
"e": 12942,
"s": 12870,
"text": "Step 3. Creating a Heroku account and install Heroku CLI for deployment"
},
{
"code": null,
"e": 12998,
"s": 12942,
"text": "Signup for a new Heroku account https://www.heroku.com/"
},
{
"code": null,
"e": 13065,
"s": 12998,
"text": "Install the Heroku CLI along with GIT as per your operating system"
},
{
"code": null,
"e": 13135,
"s": 13065,
"text": "https://devcenter.heroku.com/articles/heroku-cli#download-and-install"
},
{
"code": null,
"e": 13165,
"s": 13135,
"text": "https://git-scm.com/downloads"
},
{
"code": null,
"e": 13327,
"s": 13165,
"text": "Please restart your system once completed, type heroku on command prompt and if there is no error of “Heroku not found” you are good to proceed to the next step."
},
{
"code": null,
"e": 13370,
"s": 13327,
"text": "Step 4. Deploying the app to Heroku Server"
},
{
"code": null,
"e": 13436,
"s": 13370,
"text": "Login to Heroku by opening a new command prompt and typing below."
},
{
"code": null,
"e": 13449,
"s": 13436,
"text": "heroku login"
},
{
"code": null,
"e": 13565,
"s": 13449,
"text": "press any key and once done you will be redirected to login page in your browser, complete the login process there."
},
{
"code": null,
"e": 13635,
"s": 13565,
"text": "Now go to the Heroku home page and click on create a new app as below"
},
{
"code": null,
"e": 13714,
"s": 13635,
"text": "After completing the above follow few last steps for deployment to the server."
},
{
"code": null,
"e": 13810,
"s": 13714,
"text": "Initialize a git repository in the directory. Replace ml-deployment-app with your own app name."
},
{
"code": null,
"e": 13877,
"s": 13810,
"text": "$ cd my-project/$ git init$ heroku git:remote -a ml-deployment-app"
},
{
"code": null,
"e": 13947,
"s": 13877,
"text": "Commit your code to the repository and deploy it to Heroku using Git."
},
{
"code": null,
"e": 14014,
"s": 13947,
"text": "$ git add .$ git commit -am \"adding files\"$ git push heroku master"
},
{
"code": null,
"e": 14118,
"s": 14014,
"text": "Finally, you should be able to see the success message on CLI as below along with the URL for your app."
},
{
"code": null,
"e": 14174,
"s": 14118,
"text": "Congratulations on your own live app hosted on the Web."
},
{
"code": null,
"e": 14220,
"s": 14174,
"text": "See the running app on the below web address."
},
{
"code": null,
"e": 14261,
"s": 14220,
"text": "https://ml-deployment-app.herokuapp.com/"
},
{
"code": null,
"e": 14372,
"s": 14261,
"text": "In case you have missed something or facing issues all the code files are present on the below link of Github."
},
{
"code": null,
"e": 14430,
"s": 14372,
"text": "https://github.com/guptasoumya26/ml-deployment-app-heroku"
},
{
"code": null,
"e": 14694,
"s": 14430,
"text": "In this post, we learned about Flask with Web, how to integrate it with the HTML website, and most importantly how to apply this knowledge to deploy the same on a WebServer, so that end-users can interact with our ML model anytime without any external dependency."
}
] |
Git Reset | reset is the command we use when we want to move the repository back to a previous commit, discarding any changes made after that commit.
Step 1: Find the previous commit:
Step 2: Move the repository back to that step:
After the previous chapter, we have a part in our commit history we could go back to. Let's try and do that with reset.
First thing, we need to find the point we want to return to. To do that, we need to go through the
log.
To avoid the very long log list, we are going to use the
--oneline option,
which gives just one line per commit showing:
The first seven characters of the commit hash - this is what we need to
refer to in our reset command.
the commit message
So let's find the point we want to reset to:
git log --oneline
e56ba1f (HEAD -> master) Revert "Just a regular update, definitely no accidents here..."
52418f7 Just a regular update, definitely no accidents here...
9a9add8 (origin/master) Added .gitignore
81912ba Corrected spelling error
3fdaa5b Merge pull request #1 from w3schools-test/update-readme
836e5bf (origin/update-readme, update-readme) Updated readme for GitHub Branches
daf4f7c (origin/html-skeleton, html-skeleton) Updated index.html with basic meta
facaeae (gh-page/master) Merge branch 'master' of https://github.com/w3schools-test/hello-world
e7de78f Updated index.html. Resized image
5a04b6f Updated README.md with a line about focus
d29d69f Updated README.md with a line about GitHub
e0b6038 merged with hello-world-images after fixing conflicts
1f1584e added new image
dfa79db updated index.html with emergency fix
0312c55 Added image to Hello World
09f4acd Updated index.html with a new line
221ec6e First release of Hello World!
We want to return to the commit:
9a9add8 (origin/master) Added .gitignore,
the last one before we started to mess with things.
We reset our repository back to the specific commit using
git reset
commithash (commithash being
the first 7 characters of the commit hash we found in the
log):
git reset 9a9add8
Now let's check the log again:
git log --oneline
9a9add8 (HEAD -> master, origin/master) Added .gitignore
81912ba Corrected spelling error
3fdaa5b Merge pull request #1 from w3schools-test/update-readme
836e5bf (origin/update-readme, update-readme) Updated readme for GitHub Branches
daf4f7c (origin/html-skeleton, html-skeleton) Updated index.html with basic meta
facaeae (gh-page/master) Merge branch 'master' of https://github.com/w3schools-test/hello-world
e7de78f Updated index.html. Resized image
5a04b6f Updated README.md with a line about focus
d29d69f Updated README.md with a line about GitHub
e0b6038 merged with hello-world-images after fixing conflicts
1f1584e added new image
dfa79db updated index.html with emergency fix
0312c55 Added image to Hello World
09f4acd Updated index.html with a new line
221ec6e First release of Hello World!
Warning: Messing with the commit history of a repository can be dangerous.
It is usually ok to make these kinds of changes to your own local repository. However, you should avoid making changes that rewrite history to
remote repositories, especially if others are working with them.
Even though the commits are no longer showing up in the
log, it is not removed from Git.
If you know the commit hash you can reset to it:
git reset e56ba1f
Now let's check the log again:
git log --oneline
e56ba1f (HEAD -> master) Revert "Just a regular update, definitely no accidents here..."
52418f7 Just a regular update, definitely no accidents here...
9a9add8 (origin/master) Added .gitignore
81912ba Corrected spelling error
3fdaa5b Merge pull request #1 from w3schools-test/update-readme
836e5bf (origin/update-readme, update-readme) Updated readme for GitHub Branches
daf4f7c (origin/html-skeleton, html-skeleton) Updated index.html with basic meta
facaeae (gh-page/master) Merge branch 'master' of https://github.com/w3schools-test/hello-world
e7de78f Updated index.html. Resized image
5a04b6f Updated README.md with a line about focus
d29d69f Updated README.md with a line about GitHub
e0b6038 merged with hello-world-images after fixing conflicts
1f1584e added new image
dfa79db updated index.html with emergency fix
0312c55 Added image to Hello World
09f4acd Updated index.html with a new line
221ec6e First release of Hello World!
reset to the commit with the hash abc1234:
git
Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your message has been sent to W3Schools. | [
{
"code": null,
"e": 138,
"s": 0,
"text": "reset is the command we use when we want to move the repository back to a previous commit, discarding any changes made after that commit."
},
{
"code": null,
"e": 172,
"s": 138,
"text": "Step 1: Find the previous commit:"
},
{
"code": null,
"e": 219,
"s": 172,
"text": "Step 2: Move the repository back to that step:"
},
{
"code": null,
"e": 339,
"s": 219,
"text": "After the previous chapter, we have a part in our commit history we could go back to. Let's try and do that with reset."
},
{
"code": null,
"e": 444,
"s": 339,
"text": "First thing, we need to find the point we want to return to. To do that, we need to go through the \nlog."
},
{
"code": null,
"e": 567,
"s": 444,
"text": "To avoid the very long log list, we are going to use the \n--oneline option, \nwhich gives just one line per commit showing:"
},
{
"code": null,
"e": 673,
"s": 567,
"text": "The first seven characters of the commit hash - this is what we need to \n refer to in our reset command."
},
{
"code": null,
"e": 692,
"s": 673,
"text": "the commit message"
},
{
"code": null,
"e": 737,
"s": 692,
"text": "So let's find the point we want to reset to:"
},
{
"code": null,
"e": 1694,
"s": 737,
"text": "git log --oneline\ne56ba1f (HEAD -> master) Revert \"Just a regular update, definitely no accidents here...\"\n52418f7 Just a regular update, definitely no accidents here...\n9a9add8 (origin/master) Added .gitignore\n81912ba Corrected spelling error\n3fdaa5b Merge pull request #1 from w3schools-test/update-readme\n836e5bf (origin/update-readme, update-readme) Updated readme for GitHub Branches\ndaf4f7c (origin/html-skeleton, html-skeleton) Updated index.html with basic meta\nfacaeae (gh-page/master) Merge branch 'master' of https://github.com/w3schools-test/hello-world\ne7de78f Updated index.html. Resized image\n5a04b6f Updated README.md with a line about focus\nd29d69f Updated README.md with a line about GitHub\ne0b6038 merged with hello-world-images after fixing conflicts\n1f1584e added new image\ndfa79db updated index.html with emergency fix\n0312c55 Added image to Hello World\n09f4acd Updated index.html with a new line\n221ec6e First release of Hello World!"
},
{
"code": null,
"e": 1823,
"s": 1694,
"text": "We want to return to the commit: \n9a9add8 (origin/master) Added .gitignore, \nthe last one before we started to mess with things."
},
{
"code": null,
"e": 1987,
"s": 1823,
"text": "We reset our repository back to the specific commit using \ngit reset \ncommithash (commithash being \nthe first 7 characters of the commit hash we found in the\nlog):"
},
{
"code": null,
"e": 2005,
"s": 1987,
"text": "git reset 9a9add8"
},
{
"code": null,
"e": 2036,
"s": 2005,
"text": "Now let's check the log again:"
},
{
"code": null,
"e": 2857,
"s": 2036,
"text": "git log --oneline\n9a9add8 (HEAD -> master, origin/master) Added .gitignore\n81912ba Corrected spelling error\n3fdaa5b Merge pull request #1 from w3schools-test/update-readme\n836e5bf (origin/update-readme, update-readme) Updated readme for GitHub Branches\ndaf4f7c (origin/html-skeleton, html-skeleton) Updated index.html with basic meta\nfacaeae (gh-page/master) Merge branch 'master' of https://github.com/w3schools-test/hello-world\ne7de78f Updated index.html. Resized image\n5a04b6f Updated README.md with a line about focus\nd29d69f Updated README.md with a line about GitHub\ne0b6038 merged with hello-world-images after fixing conflicts\n1f1584e added new image\ndfa79db updated index.html with emergency fix\n0312c55 Added image to Hello World\n09f4acd Updated index.html with a new line\n221ec6e First release of Hello World!"
},
{
"code": null,
"e": 3146,
"s": 2857,
"text": "Warning: Messing with the commit history of a repository can be dangerous. \n It is usually ok to make these kinds of changes to your own local repository. However, you should avoid making changes that rewrite history to \n remote repositories, especially if others are working with them."
},
{
"code": null,
"e": 3236,
"s": 3146,
"text": "Even though the commits are no longer showing up in the \nlog, it is not removed from Git."
},
{
"code": null,
"e": 3285,
"s": 3236,
"text": "If you know the commit hash you can reset to it:"
},
{
"code": null,
"e": 3303,
"s": 3285,
"text": "git reset e56ba1f"
},
{
"code": null,
"e": 3334,
"s": 3303,
"text": "Now let's check the log again:"
},
{
"code": null,
"e": 4291,
"s": 3334,
"text": "git log --oneline\ne56ba1f (HEAD -> master) Revert \"Just a regular update, definitely no accidents here...\"\n52418f7 Just a regular update, definitely no accidents here...\n9a9add8 (origin/master) Added .gitignore\n81912ba Corrected spelling error\n3fdaa5b Merge pull request #1 from w3schools-test/update-readme\n836e5bf (origin/update-readme, update-readme) Updated readme for GitHub Branches\ndaf4f7c (origin/html-skeleton, html-skeleton) Updated index.html with basic meta\nfacaeae (gh-page/master) Merge branch 'master' of https://github.com/w3schools-test/hello-world\ne7de78f Updated index.html. Resized image\n5a04b6f Updated README.md with a line about focus\nd29d69f Updated README.md with a line about GitHub\ne0b6038 merged with hello-world-images after fixing conflicts\n1f1584e added new image\ndfa79db updated index.html with emergency fix\n0312c55 Added image to Hello World\n09f4acd Updated index.html with a new line\n221ec6e First release of Hello World!"
},
{
"code": null,
"e": 4334,
"s": 4291,
"text": "reset to the commit with the hash abc1234:"
},
{
"code": null,
"e": 4341,
"s": 4334,
"text": "git \n"
},
{
"code": null,
"e": 4361,
"s": 4341,
"text": "\nStart the Exercise"
},
{
"code": null,
"e": 4394,
"s": 4361,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 4436,
"s": 4394,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 4543,
"s": 4436,
"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": 4562,
"s": 4543,
"text": "[email protected]"
}
] |
Create a transition effect on hover pagination with CSS | To create a transition effect on hover pagination, use the transition property.
You can try to run the following code to add transition effect −
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
.demo {
display: inline-block;
}
.demo a {
color: red;
padding: 5px 12px;
text-decoration: none;
border-radius: 5px;
transition: background-color 2s;
}
.demo a.active {
background-color: orange;
color: white;
border-radius: 5px;
}
.demo a:hover:not(.active) {
background-color: yellow;
}
</style>
</head>
<body>
<h2>Our Quizzes</h2>
<div class = "demo">
<a href = "prev.html"><</a>
<a href = "quiz1.html">Quiz1</a>
<a href = "quiz2.html">Quiz2</a>
<a href = "quiz3.html">Quiz3</a>
<a href = "quiz4.html" class="active">Quiz4</a>
<a href = "next.html">></a>
</div>
</body>
</html> | [
{
"code": null,
"e": 1142,
"s": 1062,
"text": "To create a transition effect on hover pagination, use the transition property."
},
{
"code": null,
"e": 1207,
"s": 1142,
"text": "You can try to run the following code to add transition effect −"
},
{
"code": null,
"e": 1217,
"s": 1207,
"text": "Live Demo"
},
{
"code": null,
"e": 2123,
"s": 1217,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n .demo {\n display: inline-block;\n }\n .demo a {\n color: red;\n padding: 5px 12px;\n text-decoration: none;\n border-radius: 5px;\n transition: background-color 2s;\n }\n .demo a.active {\n background-color: orange;\n color: white;\n border-radius: 5px;\n }\n .demo a:hover:not(.active) {\n background-color: yellow;\n }\n </style>\n </head>\n <body>\n <h2>Our Quizzes</h2>\n <div class = \"demo\">\n <a href = \"prev.html\"><</a>\n <a href = \"quiz1.html\">Quiz1</a>\n <a href = \"quiz2.html\">Quiz2</a>\n <a href = \"quiz3.html\">Quiz3</a>\n <a href = \"quiz4.html\" class=\"active\">Quiz4</a>\n <a href = \"next.html\">></a>\n </div>\n </body>\n</html>"
}
] |
2 ways to Create ArrayList in Java - onlinetutorialspoint | PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In this tutorial, we will see 2 ways to create ArrayList in Java.
Java Provides 2 different ways to create an ArrayList,
Creating ArrayList using Arrays class, Arrays.asList();
Syntax :
ArrayList list = new ArrayList(Arrays.asList(Object obj1, Object obj2, Object obj3, ..,objn));
Example :
[java]
import java.util.ArrayList;
import java.util.Arrays;
public class Method1 {
public static void main(String args[]) {
ArrayList<String> fruits = new ArrayList<String>(
Arrays.asList("Apple", "Banana", "Grapes","Mango"));
System.out.println("List of all Fruits – "+fruits);
}
}
[/java]
Output :
List of all Fruits - [Apple, Banana, Grapes, Mango]
Creating ArrayList using java.util.ArrayList class constructor.
Syntax :
ArrayList fruitsList = new ArrayList();
fruitsList.add("Banana");
fruitsList.add("Apple");
fruitsList.add("Grapes");
fruitsList.add("Mango");
Example :
[java]
import java.util.ArrayList;
import java.util.Arrays;
public class Sample {
public static void main(String args[]) {
ArrayList fruitsList = new ArrayList();
fruitsList.add("Banana");
fruitsList.add("Apple");
fruitsList.add("Grapes");
fruitsList.add("Mango");
System.out.println("List of all Fruits – "+fruitsList);
}
}
[/java]
Output :
List of all Fruits - [Banana, Apple, Grapes, Mango]
Reference :
How Arrays Works in Java
How ArrayList works in Java
Happy Learning 🙂
How to Convert Iterable to Stream Java 8
5 Ways to Iterate ArrayList in Java
Java 8 How to get common elements from two lists
4 ways to create an Object in Java
Python – How to remove key from dictionary ?
Java 8 Stream Filter Example with Objects
JAXB Map to XML Conversion Example
ArrayList in Java
How to add elements to ArrayList in Java
Difference between ArrayList vs Vector in Java
How to Sort ArrayList in Java Ascending Order
How to Sort ArrayList in Java Descending Order
User defined sorting with Java 8 Comparator
Java how to convert ArrayList to Array Example
How to create Java Smiley Swing
How to Convert Iterable to Stream Java 8
5 Ways to Iterate ArrayList in Java
Java 8 How to get common elements from two lists
4 ways to create an Object in Java
Python – How to remove key from dictionary ?
Java 8 Stream Filter Example with Objects
JAXB Map to XML Conversion Example
ArrayList in Java
How to add elements to ArrayList in Java
Difference between ArrayList vs Vector in Java
How to Sort ArrayList in Java Ascending Order
How to Sort ArrayList in Java Descending Order
User defined sorting with Java 8 Comparator
Java how to convert ArrayList to Array Example
How to create Java Smiley Swing
Δ
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": 464,
"s": 398,
"text": "In this tutorial, we will see 2 ways to create ArrayList in Java."
},
{
"code": null,
"e": 519,
"s": 464,
"text": "Java Provides 2 different ways to create an ArrayList,"
},
{
"code": null,
"e": 575,
"s": 519,
"text": "Creating ArrayList using Arrays class, Arrays.asList();"
},
{
"code": null,
"e": 584,
"s": 575,
"text": "Syntax :"
},
{
"code": null,
"e": 679,
"s": 584,
"text": "ArrayList list = new ArrayList(Arrays.asList(Object obj1, Object obj2, Object obj3, ..,objn));"
},
{
"code": null,
"e": 689,
"s": 679,
"text": "Example :"
},
{
"code": null,
"e": 749,
"s": 689,
"text": "[java]\nimport java.util.ArrayList;\nimport java.util.Arrays;"
},
{
"code": null,
"e": 980,
"s": 749,
"text": "public class Method1 {\npublic static void main(String args[]) {\nArrayList<String> fruits = new ArrayList<String>(\nArrays.asList(\"Apple\", \"Banana\", \"Grapes\",\"Mango\"));\nSystem.out.println(\"List of all Fruits – \"+fruits);\n}\n}\n[/java]"
},
{
"code": null,
"e": 989,
"s": 980,
"text": "Output :"
},
{
"code": null,
"e": 1041,
"s": 989,
"text": "List of all Fruits - [Apple, Banana, Grapes, Mango]"
},
{
"code": null,
"e": 1105,
"s": 1041,
"text": "Creating ArrayList using java.util.ArrayList class constructor."
},
{
"code": null,
"e": 1114,
"s": 1105,
"text": "Syntax :"
},
{
"code": null,
"e": 1288,
"s": 1114,
"text": "ArrayList fruitsList = new ArrayList();\n fruitsList.add(\"Banana\");\n fruitsList.add(\"Apple\");\n fruitsList.add(\"Grapes\");\n fruitsList.add(\"Mango\");"
},
{
"code": null,
"e": 1298,
"s": 1288,
"text": "Example :"
},
{
"code": null,
"e": 1358,
"s": 1298,
"text": "[java]\nimport java.util.ArrayList;\nimport java.util.Arrays;"
},
{
"code": null,
"e": 1631,
"s": 1358,
"text": "public class Sample {\npublic static void main(String args[]) {\nArrayList fruitsList = new ArrayList();\nfruitsList.add(\"Banana\");\nfruitsList.add(\"Apple\");\nfruitsList.add(\"Grapes\");\nfruitsList.add(\"Mango\");\nSystem.out.println(\"List of all Fruits – \"+fruitsList);\n}\n}\n[/java]"
},
{
"code": null,
"e": 1640,
"s": 1631,
"text": "Output :"
},
{
"code": null,
"e": 1692,
"s": 1640,
"text": "List of all Fruits - [Banana, Apple, Grapes, Mango]"
},
{
"code": null,
"e": 1704,
"s": 1692,
"text": "Reference :"
},
{
"code": null,
"e": 1729,
"s": 1704,
"text": "How Arrays Works in Java"
},
{
"code": null,
"e": 1757,
"s": 1729,
"text": "How ArrayList works in Java"
},
{
"code": null,
"e": 1774,
"s": 1757,
"text": "Happy Learning 🙂"
},
{
"code": null,
"e": 2381,
"s": 1774,
"text": "\nHow to Convert Iterable to Stream Java 8\n5 Ways to Iterate ArrayList in Java\nJava 8 How to get common elements from two lists\n4 ways to create an Object in Java\nPython – How to remove key from dictionary ?\nJava 8 Stream Filter Example with Objects\nJAXB Map to XML Conversion Example\nArrayList in Java\nHow to add elements to ArrayList in Java\nDifference between ArrayList vs Vector in Java\nHow to Sort ArrayList in Java Ascending Order\nHow to Sort ArrayList in Java Descending Order\nUser defined sorting with Java 8 Comparator\nJava how to convert ArrayList to Array Example\nHow to create Java Smiley Swing\n"
},
{
"code": null,
"e": 2422,
"s": 2381,
"text": "How to Convert Iterable to Stream Java 8"
},
{
"code": null,
"e": 2458,
"s": 2422,
"text": "5 Ways to Iterate ArrayList in Java"
},
{
"code": null,
"e": 2507,
"s": 2458,
"text": "Java 8 How to get common elements from two lists"
},
{
"code": null,
"e": 2542,
"s": 2507,
"text": "4 ways to create an Object in Java"
},
{
"code": null,
"e": 2587,
"s": 2542,
"text": "Python – How to remove key from dictionary ?"
},
{
"code": null,
"e": 2629,
"s": 2587,
"text": "Java 8 Stream Filter Example with Objects"
},
{
"code": null,
"e": 2664,
"s": 2629,
"text": "JAXB Map to XML Conversion Example"
},
{
"code": null,
"e": 2682,
"s": 2664,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 2723,
"s": 2682,
"text": "How to add elements to ArrayList in Java"
},
{
"code": null,
"e": 2770,
"s": 2723,
"text": "Difference between ArrayList vs Vector in Java"
},
{
"code": null,
"e": 2816,
"s": 2770,
"text": "How to Sort ArrayList in Java Ascending Order"
},
{
"code": null,
"e": 2863,
"s": 2816,
"text": "How to Sort ArrayList in Java Descending Order"
},
{
"code": null,
"e": 2907,
"s": 2863,
"text": "User defined sorting with Java 8 Comparator"
},
{
"code": null,
"e": 2954,
"s": 2907,
"text": "Java how to convert ArrayList to Array Example"
},
{
"code": null,
"e": 2986,
"s": 2954,
"text": "How to create Java Smiley Swing"
},
{
"code": null,
"e": 2992,
"s": 2990,
"text": "Δ"
},
{
"code": null,
"e": 3016,
"s": 2992,
"text": " Install Java on Mac OS"
},
{
"code": null,
"e": 3044,
"s": 3016,
"text": " Install AWS CLI on Windows"
},
{
"code": null,
"e": 3073,
"s": 3044,
"text": " Install Minikube on Windows"
},
{
"code": null,
"e": 3108,
"s": 3073,
"text": " Install Docker Toolbox on Windows"
},
{
"code": null,
"e": 3135,
"s": 3108,
"text": " Install SOAPUI on Windows"
},
{
"code": null,
"e": 3162,
"s": 3135,
"text": " Install Gradle on Windows"
},
{
"code": null,
"e": 3191,
"s": 3162,
"text": " Install RabbitMQ on Windows"
},
{
"code": null,
"e": 3217,
"s": 3191,
"text": " Install PuTTY on windows"
},
{
"code": null,
"e": 3243,
"s": 3217,
"text": " Install Mysql on Windows"
},
{
"code": null,
"e": 3279,
"s": 3243,
"text": " Install Hibernate Tools in Eclipse"
},
{
"code": null,
"e": 3313,
"s": 3279,
"text": " Install Elasticsearch on Windows"
},
{
"code": null,
"e": 3339,
"s": 3313,
"text": " Install Maven on Windows"
},
{
"code": null,
"e": 3364,
"s": 3339,
"text": " Install Maven on Ubuntu"
},
{
"code": null,
"e": 3398,
"s": 3364,
"text": " Install Maven on Windows Command"
},
{
"code": null,
"e": 3433,
"s": 3398,
"text": " Add OJDBC jar to Maven Repository"
},
{
"code": null,
"e": 3457,
"s": 3433,
"text": " Install Ant on Windows"
},
{
"code": null,
"e": 3486,
"s": 3457,
"text": " Install RabbitMQ on Windows"
},
{
"code": null,
"e": 3518,
"s": 3486,
"text": " Install Apache Kafka on Ubuntu"
},
{
"code": null,
"e": 3551,
"s": 3518,
"text": " Install Apache Kafka on Windows"
},
{
"code": null,
"e": 3576,
"s": 3551,
"text": " Java8 – Install Windows"
},
{
"code": null,
"e": 3593,
"s": 3576,
"text": " Java8 – foreach"
},
{
"code": null,
"e": 3621,
"s": 3593,
"text": " Java8 – forEach with index"
},
{
"code": null,
"e": 3652,
"s": 3621,
"text": " Java8 – Stream Filter Objects"
},
{
"code": null,
"e": 3684,
"s": 3652,
"text": " Java8 – Comparator Userdefined"
},
{
"code": null,
"e": 3704,
"s": 3684,
"text": " Java8 – GroupingBy"
},
{
"code": null,
"e": 3724,
"s": 3704,
"text": " Java8 – SummingInt"
},
{
"code": null,
"e": 3748,
"s": 3724,
"text": " Java8 – walk ReadFiles"
},
{
"code": null,
"e": 3778,
"s": 3748,
"text": " Java8 – JAVA_HOME on Windows"
},
{
"code": null,
"e": 3810,
"s": 3778,
"text": " Howto – Install Java on Mac OS"
},
{
"code": null,
"e": 3846,
"s": 3810,
"text": " Howto – Convert Iterable to Stream"
},
{
"code": null,
"e": 3890,
"s": 3846,
"text": " Howto – Get common elements from two Lists"
},
{
"code": null,
"e": 3922,
"s": 3890,
"text": " Howto – Convert List to String"
},
{
"code": null,
"e": 3963,
"s": 3922,
"text": " Howto – Concatenate Arrays using Stream"
},
{
"code": null,
"e": 4000,
"s": 3963,
"text": " Howto – Remove duplicates from List"
},
{
"code": null,
"e": 4040,
"s": 4000,
"text": " Howto – Filter null values from Stream"
},
{
"code": null,
"e": 4069,
"s": 4040,
"text": " Howto – Convert List to Map"
},
{
"code": null,
"e": 4101,
"s": 4069,
"text": " Howto – Convert Stream to List"
},
{
"code": null,
"e": 4121,
"s": 4101,
"text": " Howto – Sort a Map"
},
{
"code": null,
"e": 4143,
"s": 4121,
"text": " Howto – Filter a Map"
},
{
"code": null,
"e": 4173,
"s": 4143,
"text": " Howto – Get Current UTC Time"
},
{
"code": null,
"e": 4224,
"s": 4173,
"text": " Howto – Verify an Array contains a specific value"
},
{
"code": null,
"e": 4260,
"s": 4224,
"text": " Howto – Convert ArrayList to Array"
},
{
"code": null,
"e": 4292,
"s": 4260,
"text": " Howto – Read File Line By Line"
},
{
"code": null,
"e": 4327,
"s": 4292,
"text": " Howto – Convert Date to LocalDate"
},
{
"code": null,
"e": 4350,
"s": 4327,
"text": " Howto – Merge Streams"
},
{
"code": null,
"e": 4397,
"s": 4350,
"text": " Howto – Resolve NullPointerException in toMap"
},
{
"code": null,
"e": 4422,
"s": 4397,
"text": " Howto -Get Stream count"
},
{
"code": null,
"e": 4466,
"s": 4422,
"text": " Howto – Get Min and Max values in a Stream"
}
] |
Explain the accessing of structure variable in C language | The structure is a user-defined data type, which is used to store a collection of different data types of data.
The structure is similar to an array. The only difference is that an array is used to store the same data types whereas, the structure is used to store different data types.
The keyword struct is for declaring the structure.
Variables inside the structure are the members of the structure.
A structure can be declared as follows −
Struct structurename{
//member declaration
};
Following is the C program for accessing a structure variable −
Live Demo
struct book{
int pages;
float price;
char author[20];
};
Accessing structure members in C
#include<stdio.h>
//Declaring structure//
struct{
char name[50];
int roll;
float percentage;
char grade[50];
}s1,s2;
void main(){
//Reading User I/p//
printf("enter Name of 1st student : ");
gets(s1.name);
printf("enter Roll number of 1st student : ");
scanf("%d",&s1.roll);
printf("Enter the average of 1st student : ");
scanf("%f",&s1.percentage);
printf("Enter grade status of 1st student : ");
scanf("%s",s1.grade);
//Printing O/p//
printf("The name of 1st student is : %s\n",s1.name);
printf("The roll number of 1st student is : %d\n",s1.roll);
printf("The average of 1st student is : %f\n",s1.percentage);
printf("The student 1 grade is : %s and percentage of %f\n",s1.grade,s1.percentage);
}
When the above program is executed, it produces the following result −
enter Name of 1st student: Bhanu
enter Roll number of 1st student: 2
Enter the average of 1st student: 68
Enter grade status of 1st student: A
The name of 1st student is: Bhanu
The roll number of 1st student is: 2
The average of 1st student is: 68.000000
The student 1 grade is: A and percentage of 68.000000 | [
{
"code": null,
"e": 1174,
"s": 1062,
"text": "The structure is a user-defined data type, which is used to store a collection of different data types of data."
},
{
"code": null,
"e": 1348,
"s": 1174,
"text": "The structure is similar to an array. The only difference is that an array is used to store the same data types whereas, the structure is used to store different data types."
},
{
"code": null,
"e": 1399,
"s": 1348,
"text": "The keyword struct is for declaring the structure."
},
{
"code": null,
"e": 1464,
"s": 1399,
"text": "Variables inside the structure are the members of the structure."
},
{
"code": null,
"e": 1505,
"s": 1464,
"text": "A structure can be declared as follows −"
},
{
"code": null,
"e": 1554,
"s": 1505,
"text": "Struct structurename{\n //member declaration\n};"
},
{
"code": null,
"e": 1618,
"s": 1554,
"text": "Following is the C program for accessing a structure variable −"
},
{
"code": null,
"e": 1629,
"s": 1618,
"text": " Live Demo"
},
{
"code": null,
"e": 2481,
"s": 1629,
"text": "struct book{\n int pages;\n float price;\n char author[20];\n};\nAccessing structure members in C\n#include<stdio.h>\n//Declaring structure//\nstruct{\n char name[50];\n int roll;\n float percentage;\n char grade[50];\n}s1,s2;\nvoid main(){\n //Reading User I/p//\n printf(\"enter Name of 1st student : \");\n gets(s1.name);\n printf(\"enter Roll number of 1st student : \");\n scanf(\"%d\",&s1.roll);\n printf(\"Enter the average of 1st student : \");\n scanf(\"%f\",&s1.percentage);\n printf(\"Enter grade status of 1st student : \");\n scanf(\"%s\",s1.grade);\n //Printing O/p//\n printf(\"The name of 1st student is : %s\\n\",s1.name);\n printf(\"The roll number of 1st student is : %d\\n\",s1.roll);\n printf(\"The average of 1st student is : %f\\n\",s1.percentage);\n printf(\"The student 1 grade is : %s and percentage of %f\\n\",s1.grade,s1.percentage);\n}"
},
{
"code": null,
"e": 2552,
"s": 2481,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 2861,
"s": 2552,
"text": "enter Name of 1st student: Bhanu\nenter Roll number of 1st student: 2\nEnter the average of 1st student: 68\nEnter grade status of 1st student: A\nThe name of 1st student is: Bhanu\nThe roll number of 1st student is: 2\nThe average of 1st student is: 68.000000\nThe student 1 grade is: A and percentage of 68.000000"
}
] |
How to Create Circular ImageView in Android using CardView? - GeeksforGeeks | 18 Feb, 2021
Displaying an Image in Android is done easily using ImageView., But what if one wants to display a circular image? It is seen that many Android apps use CircularImageView to show the profile images, status, stories, and many other things but doing this with a normal ImageView is a bit difficult. This article will help to create a circular image using CardView. Through cardCornerRadius one can customize the corner of the ImageView. A sample image is given below to get an idea about what we are going to create in this article. Note that we are going to implement this project using the Java language.
Note:
One may perform the same operation in another two methods. Please refer to the link below.
How to create a Circular image view in Android without using any library?
How to Create a CircularImageView in Android using hdodenhof Library?
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Add dependency to the build.gradle file
Go to build.gradle file and add this dependency and click on Sync Now button.
implementation ‘androidx.cardview:cardview:1.0.0’
Step 3: Working with the activity_main.xml file
Next, go to the activity_main.xml file, which represents the UI of the project. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail.
Note: Change android:src=”@drawable/your_image” to your Image name
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout 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"> <!-- Using CardView for CircularImageView --> <androidx.cardview.widget.CardView android:id="@+id/cardView" android:layout_width="200dp" android:layout_height="200dp" android:layout_centerHorizontal="true" android:layout_marginTop="150dp" app:cardCornerRadius="100dp"> <!-- add a Image image.png in your Drawable folder --> <ImageView android:id="@+id/imageView" android:layout_width="match_parent" android:layout_height="match_parent" android:scaleType="centerCrop" android:src="@drawable/circular" /> </androidx.cardview.widget.CardView> <TextView android:id="@+id/textView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/cardView" android:layout_marginTop="25dp" android:gravity="center" android:text="Circular ImageView" android:textColor="@color/colorPrimary" android:textSize="20sp" android:textStyle="bold" /> </RelativeLayout>
Step 4: Working with the MainActivity.java file
Finally, go to the MainActivity.kt file, and refer to the following code. Below is the code for the MainActivity.kt file. We have added a Toast message only. It Toasts a message as you click on the Image.
Java
import android.os.Bundle;import android.view.View;import android.widget.ImageView;import android.widget.Toast;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageView = (ImageView) findViewById(R.id.imageView); imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this, "This is a Circular ImageView", Toast.LENGTH_SHORT).show(); } }); }}
android
Android-View
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
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 Listview in Java with Example
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Reverse a string in Java
Arrays.sort() in Java with examples | [
{
"code": null,
"e": 24751,
"s": 24723,
"text": "\n18 Feb, 2021"
},
{
"code": null,
"e": 25356,
"s": 24751,
"text": "Displaying an Image in Android is done easily using ImageView., But what if one wants to display a circular image? It is seen that many Android apps use CircularImageView to show the profile images, status, stories, and many other things but doing this with a normal ImageView is a bit difficult. This article will help to create a circular image using CardView. Through cardCornerRadius one can customize the corner of the ImageView. A sample image is given below to get an idea about what we are going to create in this article. Note that we are going to implement this project using the Java language."
},
{
"code": null,
"e": 25362,
"s": 25356,
"text": "Note:"
},
{
"code": null,
"e": 25453,
"s": 25362,
"text": "One may perform the same operation in another two methods. Please refer to the link below."
},
{
"code": null,
"e": 25527,
"s": 25453,
"text": "How to create a Circular image view in Android without using any library?"
},
{
"code": null,
"e": 25597,
"s": 25527,
"text": "How to Create a CircularImageView in Android using hdodenhof Library?"
},
{
"code": null,
"e": 25626,
"s": 25597,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 25788,
"s": 25626,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 25836,
"s": 25788,
"text": "Step 2: Add dependency to the build.gradle file"
},
{
"code": null,
"e": 25915,
"s": 25836,
"text": " Go to build.gradle file and add this dependency and click on Sync Now button."
},
{
"code": null,
"e": 25965,
"s": 25915,
"text": "implementation ‘androidx.cardview:cardview:1.0.0’"
},
{
"code": null,
"e": 26013,
"s": 25965,
"text": "Step 3: Working with the activity_main.xml file"
},
{
"code": null,
"e": 26217,
"s": 26013,
"text": "Next, go to the activity_main.xml file, which represents the UI of the project. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 26284,
"s": 26217,
"text": "Note: Change android:src=”@drawable/your_image” to your Image name"
},
{
"code": null,
"e": 26288,
"s": 26284,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout 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\"> <!-- Using CardView for CircularImageView --> <androidx.cardview.widget.CardView android:id=\"@+id/cardView\" android:layout_width=\"200dp\" android:layout_height=\"200dp\" android:layout_centerHorizontal=\"true\" android:layout_marginTop=\"150dp\" app:cardCornerRadius=\"100dp\"> <!-- add a Image image.png in your Drawable folder --> <ImageView android:id=\"@+id/imageView\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:scaleType=\"centerCrop\" android:src=\"@drawable/circular\" /> </androidx.cardview.widget.CardView> <TextView android:id=\"@+id/textView\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/cardView\" android:layout_marginTop=\"25dp\" android:gravity=\"center\" android:text=\"Circular ImageView\" android:textColor=\"@color/colorPrimary\" android:textSize=\"20sp\" android:textStyle=\"bold\" /> </RelativeLayout>",
"e": 27716,
"s": 26288,
"text": null
},
{
"code": null,
"e": 27764,
"s": 27716,
"text": "Step 4: Working with the MainActivity.java file"
},
{
"code": null,
"e": 27969,
"s": 27764,
"text": "Finally, go to the MainActivity.kt file, and refer to the following code. Below is the code for the MainActivity.kt file. We have added a Toast message only. It Toasts a message as you click on the Image."
},
{
"code": null,
"e": 27974,
"s": 27969,
"text": "Java"
},
{
"code": "import android.os.Bundle;import android.view.View;import android.widget.ImageView;import android.widget.Toast;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageView = (ImageView) findViewById(R.id.imageView); imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this, \"This is a Circular ImageView\", Toast.LENGTH_SHORT).show(); } }); }}",
"e": 28704,
"s": 27974,
"text": null
},
{
"code": null,
"e": 28712,
"s": 28704,
"text": "android"
},
{
"code": null,
"e": 28725,
"s": 28712,
"text": "Android-View"
},
{
"code": null,
"e": 28733,
"s": 28725,
"text": "Android"
},
{
"code": null,
"e": 28738,
"s": 28733,
"text": "Java"
},
{
"code": null,
"e": 28743,
"s": 28738,
"text": "Java"
},
{
"code": null,
"e": 28751,
"s": 28743,
"text": "Android"
},
{
"code": null,
"e": 28849,
"s": 28751,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28858,
"s": 28849,
"text": "Comments"
},
{
"code": null,
"e": 28871,
"s": 28858,
"text": "Old Comments"
},
{
"code": null,
"e": 28910,
"s": 28871,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 28960,
"s": 28910,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 29011,
"s": 28960,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 29053,
"s": 29011,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 29091,
"s": 29053,
"text": "Android Listview in Java with Example"
},
{
"code": null,
"e": 29106,
"s": 29091,
"text": "Arrays in Java"
},
{
"code": null,
"e": 29150,
"s": 29106,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 29172,
"s": 29150,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 29197,
"s": 29172,
"text": "Reverse a string in Java"
}
] |
Python | Ways to convert list of ASCII value to string - GeeksforGeeks | 29 Jun, 2019
Given a list of ASCII values, write a Python program to convert those values to their character and make a string. Given below are a few methods to solve the problem.
Method #1: Using Naive Method
# Python code to demonstrate # conversion of list of ascii values# to string # Initialising listini_list = [71, 101, 101, 107, 115, 102, 111, 114, 71, 101, 101, 107, 115] # Printing initial listprint ("Initial list", ini_list) # Using Naive Methodres = ""for val in ini_list: res = res + chr(val) # Printing resultant stringprint ("Resultant string", str(res))
Output:
Initial list [71, 101, 101, 107, 115, 102, 111, 114, 71, 101, 101, 107, 115]Resultant string GeeksforGeeks
Method #2: Using map()
# Python code to demonstrate # conversion of list of ascii values# to string # Initialising listini_list = [71, 101, 101, 107, 115, 102, 111, 114, 71, 101, 101, 107, 115] # Printing initial listprint ("Initial list", ini_list) # Using map and joinres = ''.join(map(chr, ini_list)) # Print the resultant stringprint ("Resultant string", str(res))
Output:
Initial list [71, 101, 101, 107, 115, 102, 111, 114, 71, 101, 101, 107, 115]Resultant string GeeksforGeeks
Method #3: Using join and list comprehension
# Python code to demonstrate # conversion of a list of ascii values# to string # Initialising listini_list = [71, 101, 101, 107, 115, 102, 111, 114, 71, 101, 101, 107, 115] # Printing initial listprint ("Initial list", ini_list) # Using list comprehension and joinres = ''.join(chr(val) for val in ini_list) # Print the resultant stringprint ("Resultant string", str(res))
Output:
Initial list [71, 101, 101, 107, 115, 102, 111, 114, 71, 101, 101, 107, 115]Resultant string GeeksforGeeks
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python? | [
{
"code": null,
"e": 26065,
"s": 26037,
"text": "\n29 Jun, 2019"
},
{
"code": null,
"e": 26232,
"s": 26065,
"text": "Given a list of ASCII values, write a Python program to convert those values to their character and make a string. Given below are a few methods to solve the problem."
},
{
"code": null,
"e": 26262,
"s": 26232,
"text": "Method #1: Using Naive Method"
},
{
"code": "# Python code to demonstrate # conversion of list of ascii values# to string # Initialising listini_list = [71, 101, 101, 107, 115, 102, 111, 114, 71, 101, 101, 107, 115] # Printing initial listprint (\"Initial list\", ini_list) # Using Naive Methodres = \"\"for val in ini_list: res = res + chr(val) # Printing resultant stringprint (\"Resultant string\", str(res))",
"e": 26642,
"s": 26262,
"text": null
},
{
"code": null,
"e": 26650,
"s": 26642,
"text": "Output:"
},
{
"code": null,
"e": 26757,
"s": 26650,
"text": "Initial list [71, 101, 101, 107, 115, 102, 111, 114, 71, 101, 101, 107, 115]Resultant string GeeksforGeeks"
},
{
"code": null,
"e": 26780,
"s": 26757,
"text": "Method #2: Using map()"
},
{
"code": "# Python code to demonstrate # conversion of list of ascii values# to string # Initialising listini_list = [71, 101, 101, 107, 115, 102, 111, 114, 71, 101, 101, 107, 115] # Printing initial listprint (\"Initial list\", ini_list) # Using map and joinres = ''.join(map(chr, ini_list)) # Print the resultant stringprint (\"Resultant string\", str(res))",
"e": 27142,
"s": 26780,
"text": null
},
{
"code": null,
"e": 27150,
"s": 27142,
"text": "Output:"
},
{
"code": null,
"e": 27257,
"s": 27150,
"text": "Initial list [71, 101, 101, 107, 115, 102, 111, 114, 71, 101, 101, 107, 115]Resultant string GeeksforGeeks"
},
{
"code": null,
"e": 27302,
"s": 27257,
"text": "Method #3: Using join and list comprehension"
},
{
"code": "# Python code to demonstrate # conversion of a list of ascii values# to string # Initialising listini_list = [71, 101, 101, 107, 115, 102, 111, 114, 71, 101, 101, 107, 115] # Printing initial listprint (\"Initial list\", ini_list) # Using list comprehension and joinres = ''.join(chr(val) for val in ini_list) # Print the resultant stringprint (\"Resultant string\", str(res))",
"e": 27691,
"s": 27302,
"text": null
},
{
"code": null,
"e": 27699,
"s": 27691,
"text": "Output:"
},
{
"code": null,
"e": 27806,
"s": 27699,
"text": "Initial list [71, 101, 101, 107, 115, 102, 111, 114, 71, 101, 101, 107, 115]Resultant string GeeksforGeeks"
},
{
"code": null,
"e": 27827,
"s": 27806,
"text": "Python list-programs"
},
{
"code": null,
"e": 27834,
"s": 27827,
"text": "Python"
},
{
"code": null,
"e": 27850,
"s": 27834,
"text": "Python Programs"
},
{
"code": null,
"e": 27948,
"s": 27850,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27966,
"s": 27948,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27998,
"s": 27966,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28020,
"s": 27998,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28062,
"s": 28020,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28088,
"s": 28062,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28110,
"s": 28088,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28149,
"s": 28110,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 28195,
"s": 28149,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 28233,
"s": 28195,
"text": "Python | Convert a list to dictionary"
}
] |
How to limit the number of results returned from grep in Linux? | In order to be able to grep limit the number of results returned from grep command in Linux, we must first understand what a grep command is and how to use it on Linux.
The grep command in Linux is used to filter searches in a file for a particular pattern of characters. It is one of the most used Linux utility commands to display the lines that contain the pattern that we are trying to search.
Normally, the pattern that we are trying to search in the file is referred to as the regular expression.
grep [options] pattern [files]
While there are plenty of different options available to us, some of the most used are −
-c : It lists only a count of the lines that match a pattern
-h : displays the matched lines only.
-i : Ignores, case for matching
-l : prints filenames only
-n : Display the matched lines and their line numbers.
-v : It prints out all the lines that do not match the pattern
grep -rni "word" *
In the above command replace the “word” placeholder with
For that we make use of the command shown below −
grep -rni "func main()" *
The above command will try to find a string “func main()” in all the files in a particular directory and also in the subdirectories as well.
main.go:120:func main() {}
In case we only want to find a particular pattern in a single directory and not the subdirectories then we need to use the command shown below −
grep -s "func main()" *
In the above command we made use of the -s flag which will help us to not get a warning for each subdirectory that is present inside the directory where we are running the command.
main.go:120:func main() {}
Now, consider that I have a .txt file and the content of the file looks something like this.
immukul@192 d2 % cat 2.txt
orange apple is great together
apple not great
is apple good
orange good apple not
Now I want to use the grep command for all the lines that contain both the words ‘apple’ and ‘orange’.
grep 'orange' 2.txt | grep 'apple'
immukul@192 d2 % grep 'orange' 2.txt | grep 'apple'
orange apple is great together
orange good apple not
Now that we can notice that two strings matched with our grep query, we can limit the result with the help of the command shown below
grep -m 1 'orange' 2.txt | grep 'apple
immukul@192 d2 % grep -m 1 'orange' 2.txt | grep 'apple'
orange apple is great together | [
{
"code": null,
"e": 1231,
"s": 1062,
"text": "In order to be able to grep limit the number of results returned from grep command in Linux, we must first understand what a grep command is and how to use it on Linux."
},
{
"code": null,
"e": 1460,
"s": 1231,
"text": "The grep command in Linux is used to filter searches in a file for a particular pattern of characters. It is one of the most used Linux utility commands to display the lines that contain the pattern that we are trying to search."
},
{
"code": null,
"e": 1565,
"s": 1460,
"text": "Normally, the pattern that we are trying to search in the file is referred to as the regular expression."
},
{
"code": null,
"e": 1596,
"s": 1565,
"text": "grep [options] pattern [files]"
},
{
"code": null,
"e": 1685,
"s": 1596,
"text": "While there are plenty of different options available to us, some of the most used are −"
},
{
"code": null,
"e": 1961,
"s": 1685,
"text": "-c : It lists only a count of the lines that match a pattern\n-h : displays the matched lines only.\n-i : Ignores, case for matching\n-l : prints filenames only\n-n : Display the matched lines and their line numbers.\n-v : It prints out all the lines that do not match the pattern"
},
{
"code": null,
"e": 1980,
"s": 1961,
"text": "grep -rni \"word\" *"
},
{
"code": null,
"e": 2037,
"s": 1980,
"text": "In the above command replace the “word” placeholder with"
},
{
"code": null,
"e": 2087,
"s": 2037,
"text": "For that we make use of the command shown below −"
},
{
"code": null,
"e": 2113,
"s": 2087,
"text": "grep -rni \"func main()\" *"
},
{
"code": null,
"e": 2254,
"s": 2113,
"text": "The above command will try to find a string “func main()” in all the files in a particular directory and also in the subdirectories as well."
},
{
"code": null,
"e": 2282,
"s": 2254,
"text": "main.go:120:func main() {}\n"
},
{
"code": null,
"e": 2427,
"s": 2282,
"text": "In case we only want to find a particular pattern in a single directory and not the subdirectories then we need to use the command shown below −"
},
{
"code": null,
"e": 2451,
"s": 2427,
"text": "grep -s \"func main()\" *"
},
{
"code": null,
"e": 2632,
"s": 2451,
"text": "In the above command we made use of the -s flag which will help us to not get a warning for each subdirectory that is present inside the directory where we are running the command."
},
{
"code": null,
"e": 2659,
"s": 2632,
"text": "main.go:120:func main() {}"
},
{
"code": null,
"e": 2752,
"s": 2659,
"text": "Now, consider that I have a .txt file and the content of the file looks something like this."
},
{
"code": null,
"e": 2862,
"s": 2752,
"text": "immukul@192 d2 % cat 2.txt\norange apple is great together\napple not great\nis apple good\norange good apple not"
},
{
"code": null,
"e": 2965,
"s": 2862,
"text": "Now I want to use the grep command for all the lines that contain both the words ‘apple’ and ‘orange’."
},
{
"code": null,
"e": 3000,
"s": 2965,
"text": "grep 'orange' 2.txt | grep 'apple'"
},
{
"code": null,
"e": 3105,
"s": 3000,
"text": "immukul@192 d2 % grep 'orange' 2.txt | grep 'apple'\norange apple is great together\norange good apple not"
},
{
"code": null,
"e": 3239,
"s": 3105,
"text": "Now that we can notice that two strings matched with our grep query, we can limit the result with the help of the command shown below"
},
{
"code": null,
"e": 3278,
"s": 3239,
"text": "grep -m 1 'orange' 2.txt | grep 'apple"
},
{
"code": null,
"e": 3367,
"s": 3278,
"text": "immukul@192 d2 % grep -m 1 'orange' 2.txt | grep 'apple'\n\norange apple is great together"
}
] |
Python - Get first element in List of tuples - GeeksforGeeks | 23 Aug, 2021
In this article. we will discuss how to get the first element in the list of tuples in Python.
Create a list of tuples and display them:
Python3
# create tuples with college# id and name and store in a listdata=[(1,'sravan'), (2,'ojaswi'), (3,'bobby'), (4,'rohith'), (5,'gnanesh')] # display dataprint(data)
Output:
[(1, ‘sravan’), (2, ‘ojaswi’), (3, ‘bobby’), (4, ‘rohith’), (5, ‘gnanesh’)]
We can iterate through the entire list of tuples and get first by using the index, index-0 will give the first element in each tuple in a list.
Syntax: for var in list_of_tuple:
print(var[0])
Example: Here we will get the first IE student id from the list of tuples.
Python3
# create tuples with college id# and name and store in a listdata = [(1,'sravan'), (2,'ojaswi'), (3,'bobby'),(4,'rohith'), (5,'gnanesh')] # iterate using for loop# to access first elementsfor i in data: print(i[0])
Output:
1
2
3
4
5
Zip is used to combine two or more data/data structures. Here we can use zip() function by using the index as 0 to get the first element.
Syntax: list(zip(*data))[0]
Example: Python code to access first element in List of the tuple.
Python3
# create tuples with college id# and name and store in a listdata = [(1,'sravan'),(2,'ojaswi'), (3,'bobby'),(4,'rohith'), (5,'gnanesh')] # get first element using zipprint(list(zip(*data))[0])
Output:
(1, 2, 3, 4, 5)
Here we are using the map function along with itemgetter() method to get the first elements, here also we are using index – 0 to get the first elements. itemgetter() method is available in the operator module, so we need to import operator
Syntax: map(operator.itemgetter(0), data)
Example: Python program to access first elements.
Python3
import operator # create tuples with college id# and name and store in a listdata = [(1,'sravan'),(2,'ojaswi'), (3,'bobby'),(4,'rohith'), (5,'gnanesh')] # map the data using item# getter method with first elementsfirst_data = map(operator.itemgetter(0), data) # display first elementsfor i in first_data: print(i)
Output:
1
2
3
4
5
Here we are using lambda expression along with map() function, here also we are using index 0 to get the first data.
Syntax: map(lambda x: x[0], data)
Where,
x is an iterator to get first elements
data is the list of tuples data
Example: Python code to access first elements.
Python3
# create tuples with college id# and name and store in a listdata=[(1,'sravan'),(2,'ojaswi'), (3,'bobby'),(4,'rohith'), (5,'gnanesh')] # map with lambda expression to get first elementfirst_data = map(lambda x: x[0], data) # display datafor i in first_data: print(i)
Output:
1
2
3
4
5
Picked
Python List-of-Tuples
Python
Python Programs
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
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not | [
{
"code": null,
"e": 24212,
"s": 24184,
"text": "\n23 Aug, 2021"
},
{
"code": null,
"e": 24307,
"s": 24212,
"text": "In this article. we will discuss how to get the first element in the list of tuples in Python."
},
{
"code": null,
"e": 24349,
"s": 24307,
"text": "Create a list of tuples and display them:"
},
{
"code": null,
"e": 24357,
"s": 24349,
"text": "Python3"
},
{
"code": "# create tuples with college# id and name and store in a listdata=[(1,'sravan'), (2,'ojaswi'), (3,'bobby'), (4,'rohith'), (5,'gnanesh')] # display dataprint(data)",
"e": 24531,
"s": 24357,
"text": null
},
{
"code": null,
"e": 24539,
"s": 24531,
"text": "Output:"
},
{
"code": null,
"e": 24615,
"s": 24539,
"text": "[(1, ‘sravan’), (2, ‘ojaswi’), (3, ‘bobby’), (4, ‘rohith’), (5, ‘gnanesh’)]"
},
{
"code": null,
"e": 24759,
"s": 24615,
"text": "We can iterate through the entire list of tuples and get first by using the index, index-0 will give the first element in each tuple in a list."
},
{
"code": null,
"e": 24793,
"s": 24759,
"text": "Syntax: for var in list_of_tuple:"
},
{
"code": null,
"e": 24829,
"s": 24793,
"text": " print(var[0])"
},
{
"code": null,
"e": 24904,
"s": 24829,
"text": "Example: Here we will get the first IE student id from the list of tuples."
},
{
"code": null,
"e": 24912,
"s": 24904,
"text": "Python3"
},
{
"code": "# create tuples with college id# and name and store in a listdata = [(1,'sravan'), (2,'ojaswi'), (3,'bobby'),(4,'rohith'), (5,'gnanesh')] # iterate using for loop# to access first elementsfor i in data: print(i[0])",
"e": 25144,
"s": 24912,
"text": null
},
{
"code": null,
"e": 25152,
"s": 25144,
"text": "Output:"
},
{
"code": null,
"e": 25162,
"s": 25152,
"text": "1\n2\n3\n4\n5"
},
{
"code": null,
"e": 25300,
"s": 25162,
"text": "Zip is used to combine two or more data/data structures. Here we can use zip() function by using the index as 0 to get the first element."
},
{
"code": null,
"e": 25328,
"s": 25300,
"text": "Syntax: list(zip(*data))[0]"
},
{
"code": null,
"e": 25395,
"s": 25328,
"text": "Example: Python code to access first element in List of the tuple."
},
{
"code": null,
"e": 25403,
"s": 25395,
"text": "Python3"
},
{
"code": "# create tuples with college id# and name and store in a listdata = [(1,'sravan'),(2,'ojaswi'), (3,'bobby'),(4,'rohith'), (5,'gnanesh')] # get first element using zipprint(list(zip(*data))[0])",
"e": 25611,
"s": 25403,
"text": null
},
{
"code": null,
"e": 25619,
"s": 25611,
"text": "Output:"
},
{
"code": null,
"e": 25635,
"s": 25619,
"text": "(1, 2, 3, 4, 5)"
},
{
"code": null,
"e": 25875,
"s": 25635,
"text": "Here we are using the map function along with itemgetter() method to get the first elements, here also we are using index – 0 to get the first elements. itemgetter() method is available in the operator module, so we need to import operator"
},
{
"code": null,
"e": 25917,
"s": 25875,
"text": "Syntax: map(operator.itemgetter(0), data)"
},
{
"code": null,
"e": 25967,
"s": 25917,
"text": "Example: Python program to access first elements."
},
{
"code": null,
"e": 25975,
"s": 25967,
"text": "Python3"
},
{
"code": "import operator # create tuples with college id# and name and store in a listdata = [(1,'sravan'),(2,'ojaswi'), (3,'bobby'),(4,'rohith'), (5,'gnanesh')] # map the data using item# getter method with first elementsfirst_data = map(operator.itemgetter(0), data) # display first elementsfor i in first_data: print(i)",
"e": 26309,
"s": 25975,
"text": null
},
{
"code": null,
"e": 26317,
"s": 26309,
"text": "Output:"
},
{
"code": null,
"e": 26327,
"s": 26317,
"text": "1\n2\n3\n4\n5"
},
{
"code": null,
"e": 26444,
"s": 26327,
"text": "Here we are using lambda expression along with map() function, here also we are using index 0 to get the first data."
},
{
"code": null,
"e": 26478,
"s": 26444,
"text": "Syntax: map(lambda x: x[0], data)"
},
{
"code": null,
"e": 26485,
"s": 26478,
"text": "Where,"
},
{
"code": null,
"e": 26524,
"s": 26485,
"text": "x is an iterator to get first elements"
},
{
"code": null,
"e": 26556,
"s": 26524,
"text": "data is the list of tuples data"
},
{
"code": null,
"e": 26603,
"s": 26556,
"text": "Example: Python code to access first elements."
},
{
"code": null,
"e": 26611,
"s": 26603,
"text": "Python3"
},
{
"code": "# create tuples with college id# and name and store in a listdata=[(1,'sravan'),(2,'ojaswi'), (3,'bobby'),(4,'rohith'), (5,'gnanesh')] # map with lambda expression to get first elementfirst_data = map(lambda x: x[0], data) # display datafor i in first_data: print(i)",
"e": 26893,
"s": 26611,
"text": null
},
{
"code": null,
"e": 26901,
"s": 26893,
"text": "Output:"
},
{
"code": null,
"e": 26911,
"s": 26901,
"text": "1\n2\n3\n4\n5"
},
{
"code": null,
"e": 26918,
"s": 26911,
"text": "Picked"
},
{
"code": null,
"e": 26940,
"s": 26918,
"text": "Python List-of-Tuples"
},
{
"code": null,
"e": 26947,
"s": 26940,
"text": "Python"
},
{
"code": null,
"e": 26963,
"s": 26947,
"text": "Python Programs"
},
{
"code": null,
"e": 27061,
"s": 26963,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27070,
"s": 27061,
"text": "Comments"
},
{
"code": null,
"e": 27083,
"s": 27070,
"text": "Old Comments"
},
{
"code": null,
"e": 27115,
"s": 27083,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27170,
"s": 27115,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 27226,
"s": 27170,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27265,
"s": 27226,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27307,
"s": 27265,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27329,
"s": 27307,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27368,
"s": 27329,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27414,
"s": 27368,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 27452,
"s": 27414,
"text": "Python | Convert a list to dictionary"
}
] |
Creating a dataframe using Excel files - GeeksforGeeks | 16 Aug, 2021
Let’s see how to read excel files to Pandas dataframe objects using Pandas.Code #1 : Read an excel file using read_excel() method of pandas.
Python3
# import pandas lib as pdimport pandas as pd # read by default 1st sheet of an excel filedataframe1 = pd.read_excel('SampleWork.xlsx') print(dataframe1)
Output :
Name Age Stream Percentage
0 Ankit 18 Math 95
1 Rahul 19 Science 90
2 Shaurya 20 Commerce 85
3 Aishwarya 18 Math 80
4 Priyanka 19 Science 75
Code #2 : Reading Specific Sheets using ‘sheet_name’ of read_excel() method.
Python3
# import pandas lib as pdimport pandas as pd # read 2nd sheet of an excel filedataframe2 = pd.read_excel('SampleWork.xlsx', sheet_name = 1) print(dataframe2)
Output :
Name Age Stream Percentage
0 Priya 18 Math 95
1 shivangi 19 Science 90
2 Jeet 20 Commerce 85
3 Ananya 18 Math 80
4 Swapnil 19 Science 75
Code #3 : Reading Specific Columns using ‘usecols’ parameter of read_excel() method.
Python3
# import pandas lib as pdimport pandas as pd require_cols = [0, 3] # only read specific columns from an excel filerequired_df = pd.read_excel('SampleWork.xlsx', usecols = require_cols) print(required_df)
Output :
Name Percentage
0 Ankit 95
1 Rahul 90
2 Shaurya 85
3 Aishwarya 80
4 Priyanka 75
Code #4 : Handling missing data using ‘na_values’ parameter of the read_excel() method.
Python3
# import pandas lib as pdimport pandas as pd # Handling missing values of 3rd sheet of an excel file.dataframe = pd.read_excel('SampleWork.xlsx', na_values = "Missing", sheet_name = 2) print(dataframe)
Output :
Name Age Stream Percentage
0 Priya 18 Math 95
1 shivangi 19 Science 90
2 Jeet 20 NaN 85
3 Ananya 18 Math 80
4 Swapnil 19 Science 75
Code #5 : Skip starting rows when Reading an Excel File using ‘skiprows’ parameter of read_excel() method.
Python3
# import pandas lib as pdimport pandas as pd # read 2nd sheet of an excel file after# skipping starting two rowsdf = pd.read_excel('SampleWork.xlsx', sheet_name = 1, skiprows = 2) print(df)
Output :
shivangi 19 Science 90
0 Jeet 20 Commerce 85
1 Ananya 18 Math 80
2 Swapnil 19 Science 75
Code #6 : Set the header to any row and start reading from that row, using ‘header’ parameter of the read_excel() method.
Python3
# import pandas lib as pdimport pandas as pd # setting the 3rd row as header.df = pd.read_excel('SampleWork.xlsx', sheet_name = 1, header = 2) print(df)
Output :
shivangi 19 Science 90
0 Jeet 20 Commerce 85
1 Ananya 18 Math 80
2 Swapnil 19 Science 75
Code #7 : Reading Multiple Excel Sheets using ‘sheet_name’ parameter of the read_excel()method.
Python3
# import pandas lib as pdimport pandas as pd # read both 1st and 2nd sheet.df = pd.read_excel('SampleWork.xlsx', na_values = "Missing", sheet_name =[0, 1]) print(df)
Output :
OrderedDict([(0, Name Age Stream Percentage
0 Ankit 18 Math 95
1 Rahul 19 Science 90
2 Shaurya 20 Commerce 85
3 Aishwarya 18 Math 80
4 Priyanka 19 Science 75),
(1, Name Age Stream Percentage
0 Priya 18 Math 95
1 shivangi 19 Science 90
2 Jeet 20 Commerce 85
3 Ananya 18 Math 80
4 Swapnil 19 Science 75)])
Code #8 : Reading all Sheets of the excel file together using ‘sheet_name’ parameter of the read_excel() method.
Python3
# import pandas lib as pdimport pandas as pd # read all sheets together.all_sheets_df = pd.read_excel('SampleWork.xlsx', na_values = "Missing", sheet_name = None) print(all_sheets_df)
Output :
OrderedDict([('Sheet1', Name Age Stream Percentage
0 Ankit 18 Math 95
1 Rahul 19 Science 90
2 Shaurya 20 Commerce 85
3 Aishwarya 18 Math 80
4 Priyanka 19 Science 75),
('Sheet2', Name Age Stream Percentage
0 Priya 18 Math 95
1 shivangi 19 Science 90
2 Jeet 20 Commerce 85
3 Ananya 18 Math 80
4 Swapnil 19 Science 75),
('Sheet3', Name Age Stream Percentage
0 Priya 18 Math 95
1 shivangi 19 Science 90
2 Jeet 20 NaN 85
3 Ananya 18 Math 80
4 Swapnil 19 Science 75)])
surindertarika1234
pandas-dataframe-program
Picked
Python pandas-dataFrame
Python-excel
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Create a Pandas DataFrame from Lists | [
{
"code": null,
"e": 26321,
"s": 26293,
"text": "\n16 Aug, 2021"
},
{
"code": null,
"e": 26464,
"s": 26321,
"text": "Let’s see how to read excel files to Pandas dataframe objects using Pandas.Code #1 : Read an excel file using read_excel() method of pandas. "
},
{
"code": null,
"e": 26472,
"s": 26464,
"text": "Python3"
},
{
"code": "# import pandas lib as pdimport pandas as pd # read by default 1st sheet of an excel filedataframe1 = pd.read_excel('SampleWork.xlsx') print(dataframe1)",
"e": 26625,
"s": 26472,
"text": null
},
{
"code": null,
"e": 26636,
"s": 26625,
"text": "Output : "
},
{
"code": null,
"e": 26876,
"s": 26636,
"text": " Name Age Stream Percentage\n0 Ankit 18 Math 95\n1 Rahul 19 Science 90\n2 Shaurya 20 Commerce 85\n3 Aishwarya 18 Math 80\n4 Priyanka 19 Science 75"
},
{
"code": null,
"e": 26957,
"s": 26876,
"text": " Code #2 : Reading Specific Sheets using ‘sheet_name’ of read_excel() method. "
},
{
"code": null,
"e": 26965,
"s": 26957,
"text": "Python3"
},
{
"code": "# import pandas lib as pdimport pandas as pd # read 2nd sheet of an excel filedataframe2 = pd.read_excel('SampleWork.xlsx', sheet_name = 1) print(dataframe2)",
"e": 27123,
"s": 26965,
"text": null
},
{
"code": null,
"e": 27134,
"s": 27123,
"text": "Output : "
},
{
"code": null,
"e": 27368,
"s": 27134,
"text": " Name Age Stream Percentage\n0 Priya 18 Math 95\n1 shivangi 19 Science 90\n2 Jeet 20 Commerce 85\n3 Ananya 18 Math 80\n4 Swapnil 19 Science 75"
},
{
"code": null,
"e": 27457,
"s": 27368,
"text": " Code #3 : Reading Specific Columns using ‘usecols’ parameter of read_excel() method. "
},
{
"code": null,
"e": 27465,
"s": 27457,
"text": "Python3"
},
{
"code": "# import pandas lib as pdimport pandas as pd require_cols = [0, 3] # only read specific columns from an excel filerequired_df = pd.read_excel('SampleWork.xlsx', usecols = require_cols) print(required_df)",
"e": 27669,
"s": 27465,
"text": null
},
{
"code": null,
"e": 27680,
"s": 27669,
"text": "Output : "
},
{
"code": null,
"e": 27830,
"s": 27680,
"text": " Name Percentage\n0 Ankit 95\n1 Rahul 90\n2 Shaurya 85\n3 Aishwarya 80\n4 Priyanka 75"
},
{
"code": null,
"e": 27922,
"s": 27830,
"text": " Code #4 : Handling missing data using ‘na_values’ parameter of the read_excel() method. "
},
{
"code": null,
"e": 27930,
"s": 27922,
"text": "Python3"
},
{
"code": "# import pandas lib as pdimport pandas as pd # Handling missing values of 3rd sheet of an excel file.dataframe = pd.read_excel('SampleWork.xlsx', na_values = \"Missing\", sheet_name = 2) print(dataframe)",
"e": 28183,
"s": 27930,
"text": null
},
{
"code": null,
"e": 28194,
"s": 28183,
"text": "Output : "
},
{
"code": null,
"e": 28422,
"s": 28194,
"text": " Name Age Stream Percentage\n0 Priya 18 Math 95\n1 shivangi 19 Science 90\n2 Jeet 20 NaN 85\n3 Ananya 18 Math 80\n4 Swapnil 19 Science 75"
},
{
"code": null,
"e": 28533,
"s": 28422,
"text": " Code #5 : Skip starting rows when Reading an Excel File using ‘skiprows’ parameter of read_excel() method. "
},
{
"code": null,
"e": 28541,
"s": 28533,
"text": "Python3"
},
{
"code": "# import pandas lib as pdimport pandas as pd # read 2nd sheet of an excel file after# skipping starting two rowsdf = pd.read_excel('SampleWork.xlsx', sheet_name = 1, skiprows = 2) print(df)",
"e": 28731,
"s": 28541,
"text": null
},
{
"code": null,
"e": 28742,
"s": 28731,
"text": "Output : "
},
{
"code": null,
"e": 28858,
"s": 28742,
"text": " shivangi 19 Science 90\n0 Jeet 20 Commerce 85\n1 Ananya 18 Math 80\n2 Swapnil 19 Science 75"
},
{
"code": null,
"e": 28984,
"s": 28858,
"text": " Code #6 : Set the header to any row and start reading from that row, using ‘header’ parameter of the read_excel() method. "
},
{
"code": null,
"e": 28992,
"s": 28984,
"text": "Python3"
},
{
"code": "# import pandas lib as pdimport pandas as pd # setting the 3rd row as header.df = pd.read_excel('SampleWork.xlsx', sheet_name = 1, header = 2) print(df)",
"e": 29145,
"s": 28992,
"text": null
},
{
"code": null,
"e": 29156,
"s": 29145,
"text": "Output : "
},
{
"code": null,
"e": 29272,
"s": 29156,
"text": " shivangi 19 Science 90\n0 Jeet 20 Commerce 85\n1 Ananya 18 Math 80\n2 Swapnil 19 Science 75"
},
{
"code": null,
"e": 29372,
"s": 29272,
"text": " Code #7 : Reading Multiple Excel Sheets using ‘sheet_name’ parameter of the read_excel()method. "
},
{
"code": null,
"e": 29380,
"s": 29372,
"text": "Python3"
},
{
"code": "# import pandas lib as pdimport pandas as pd # read both 1st and 2nd sheet.df = pd.read_excel('SampleWork.xlsx', na_values = \"Missing\", sheet_name =[0, 1]) print(df)",
"e": 29585,
"s": 29380,
"text": null
},
{
"code": null,
"e": 29596,
"s": 29585,
"text": "Output : "
},
{
"code": null,
"e": 30097,
"s": 29596,
"text": "OrderedDict([(0, Name Age Stream Percentage\n0 Ankit 18 Math 95\n1 Rahul 19 Science 90\n2 Shaurya 20 Commerce 85\n3 Aishwarya 18 Math 80\n4 Priyanka 19 Science 75),\n\n(1, Name Age Stream Percentage\n0 Priya 18 Math 95\n1 shivangi 19 Science 90\n2 Jeet 20 Commerce 85\n3 Ananya 18 Math 80\n4 Swapnil 19 Science 75)])"
},
{
"code": null,
"e": 30214,
"s": 30097,
"text": " Code #8 : Reading all Sheets of the excel file together using ‘sheet_name’ parameter of the read_excel() method. "
},
{
"code": null,
"e": 30222,
"s": 30214,
"text": "Python3"
},
{
"code": "# import pandas lib as pdimport pandas as pd # read all sheets together.all_sheets_df = pd.read_excel('SampleWork.xlsx', na_values = \"Missing\", sheet_name = None) print(all_sheets_df)",
"e": 30458,
"s": 30222,
"text": null
},
{
"code": null,
"e": 30469,
"s": 30458,
"text": "Output : "
},
{
"code": null,
"e": 31227,
"s": 30469,
"text": "OrderedDict([('Sheet1', Name Age Stream Percentage\n0 Ankit 18 Math 95\n1 Rahul 19 Science 90\n2 Shaurya 20 Commerce 85\n3 Aishwarya 18 Math 80\n4 Priyanka 19 Science 75),\n\n('Sheet2', Name Age Stream Percentage\n0 Priya 18 Math 95\n1 shivangi 19 Science 90\n2 Jeet 20 Commerce 85\n3 Ananya 18 Math 80\n4 Swapnil 19 Science 75), \n\n('Sheet3', Name Age Stream Percentage\n0 Priya 18 Math 95\n1 shivangi 19 Science 90\n2 Jeet 20 NaN 85\n3 Ananya 18 Math 80\n4 Swapnil 19 Science 75)])"
},
{
"code": null,
"e": 31248,
"s": 31229,
"text": "surindertarika1234"
},
{
"code": null,
"e": 31273,
"s": 31248,
"text": "pandas-dataframe-program"
},
{
"code": null,
"e": 31280,
"s": 31273,
"text": "Picked"
},
{
"code": null,
"e": 31304,
"s": 31280,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 31317,
"s": 31304,
"text": "Python-excel"
},
{
"code": null,
"e": 31331,
"s": 31317,
"text": "Python-pandas"
},
{
"code": null,
"e": 31338,
"s": 31331,
"text": "Python"
},
{
"code": null,
"e": 31436,
"s": 31338,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31454,
"s": 31436,
"text": "Python Dictionary"
},
{
"code": null,
"e": 31489,
"s": 31454,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 31521,
"s": 31489,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 31543,
"s": 31521,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 31585,
"s": 31543,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 31615,
"s": 31585,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 31641,
"s": 31615,
"text": "Python String | replace()"
},
{
"code": null,
"e": 31685,
"s": 31641,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 31714,
"s": 31685,
"text": "*args and **kwargs in Python"
}
] |
Adding elements of an array until every element becomes greater than or equal to k - GeeksforGeeks | 06 Jul, 2021
We are given a list of N unsorted elements, we need to find minimum number of steps in which the elements of the list can be added to make all the elements greater than or equal to K. We are allowed to add two elements together and make them one.Examples:
Input : arr[] = {1 10 12 9 2 3}
K = 6
Output : 2
First we add (1 + 2), now the new list becomes
3 10 12 9 3, then we add (3 + 3), now the new
list becomes 6 10 12 9, Now all the elements in
the list are greater than 6. Hence the output is
2 i:e 2 operations are required
to do this.
As we can see from above explanation, we need to extract two smallest elements and then add their sum to list. We need to continue this step until all elements are greater than or equal to K.Method 1 (Brute Force): We can create a simple array the sort it and then add two minimum elements and keep on storing them back in the array until all the elements become greater than K.Method 2 (Efficient): If we take a closer look, we can notice that this problem is similar to Huffman coding. We use Min Heap as the main operations here are extract min and insert. Both of these operations can be done in O(Log n) time.
C++
Java
C#
Javascript
// A C++ program to count minimum steps to make all// elements greater than or equal to k.#include<bits/stdc++.h>using namespace std; // A class for Min Heapclass MinHeap{ int *harr; int capacity; // maximum size int heap_size; // Current countpublic: // Constructor MinHeap(int *arr, int capacity); // to heapify a subtree with root at // given index void heapify(int ); int parent(int i) { return (i-1)/2; } // to get index of left child of // node at index i int left(int i) { return (2*i + 1); } // to get index of right child of // node at index i int right(int i) { return (2*i + 2); } // to extract the root which is the // minimum element int extractMin(); // Returns the minimum key (key at // root) from min heap int getMin() { return harr[0]; } int getSize() { return heap_size; } // Inserts a new key 'k' void insertKey(int k);}; // Constructor: Builds a heap from// a given array a[] of given sizeMinHeap::MinHeap(int arr[], int n){ heap_size = n; capacity = n; harr = new int[n]; for (int i=0; i<n; i++) harr[i] = arr[i]; // building the heap from first // non-leaf node by calling max // heapify function for (int i=n/2-1; i>=0; i--) heapify(i);} // Inserts a new key 'k'void MinHeap::insertKey(int k){ // First insert the new key at the end heap_size++; int i = heap_size - 1; harr[i] = k; // Fix the min heap property if it is violated while (i != 0 && harr[parent(i)] > harr[i]) { swap(harr[i], harr[parent(i)]); i = parent(i); }} // Method to remove minimum element// (or root) from min heapint MinHeap::extractMin(){ if (heap_size <= 0) return INT_MAX; if (heap_size == 1) { heap_size--; return harr[0]; } // Store the minimum value, and // remove it from heap int root = harr[0]; harr[0] = harr[heap_size-1]; heap_size--; heapify(0); return root;} // A recursive method to heapify a subtree// with root at given index. This method// assumes that the subtrees are already// heapifiedvoid MinHeap::heapify(int i){ int l = left(i); int r = right(i); int smallest = i; if (l < heap_size && harr[l] < harr[i]) smallest = l; if (r < heap_size && harr[r] < harr[smallest]) smallest = r; if (smallest != i) { swap(harr[i], harr[smallest]); heapify(smallest); }} // Returns count of steps needed to make// all elements greater than or equal to// k by adding elementsint countMinOps(int arr[], int n, int k){ // Build a min heap of array elements MinHeap h(arr, n); long int res = 0; while (h.getMin() < k) { if (h.getSize() == 1) return -1; // Extract two minimum elements // and insert their sum int first = h.extractMin(); int second = h.extractMin(); h.insertKey(first + second); res++; } return res;} // Driver codeint main(){ int arr[] = {1, 10, 12, 9, 2, 3}; int n = sizeof(arr)/sizeof(arr[0]); int k = 6; cout << countMinOps(arr, n, k); return 0;}
// A Java program to count minimum steps to make all// elements greater than or equal to k.public class Add_Elements { // A class for Min Heap static class MinHeap { int[] harr; int capacity; // maximum size int heap_size; // Current count // Constructor: Builds a heap from // a given array a[] of given size MinHeap(int arr[], int n) { heap_size = n; capacity = n; harr = new int[n]; for (int i=0; i<n; i++) harr[i] = arr[i]; // building the heap from first // non-leaf node by calling max // heapify function for (int i=n/2-1; i>=0; i--) heapify(i); } // A recursive method to heapify a subtree // with root at given index. This method // assumes that the subtrees are already // heapified void heapify(int i) { int l = left(i); int r = right(i); int smallest = i; if (l < heap_size && harr[l] < harr[i]) smallest = l; if (r < heap_size && harr[r] < harr[smallest]) smallest = r; if (smallest != i) { int temp = harr[i]; harr[i] = harr[smallest]; harr[smallest] = temp; heapify(smallest); } } static int parent(int i) { return (i-1)/2; } // to get index of left child of // node at index i static int left(int i) { return (2*i + 1); } // to get index of right child of // node at index i int right(int i) { return (2*i + 2); } // Method to remove minimum element // (or root) from min heap int extractMin() { if (heap_size <= 0) return Integer.MAX_VALUE; if (heap_size == 1) { heap_size--; return harr[0]; } // Store the minimum value, and // remove it from heap int root = harr[0]; harr[0] = harr[heap_size-1]; heap_size--; heapify(0); return root; } // Returns the minimum key (key at // root) from min heap int getMin() { return harr[0]; } int getSize() { return heap_size; } // Inserts a new key 'k' void insertKey(int k) { // First insert the new key at the end heap_size++; int i = heap_size - 1; harr[i] = k; // Fix the min heap property if it is violated while (i != 0 && harr[parent(i)] > harr[i]) { int temp = harr[i]; harr[i] = harr[parent(i)]; harr[parent(i)] = temp; i = parent(i); } } } // Returns count of steps needed to make // all elements greater than or equal to // k by adding elements static int countMinOps(int arr[], int n, int k) { // Build a min heap of array elements MinHeap h = new MinHeap(arr, n); int res = 0; while (h.getMin() < k) { if (h.getSize() == 1) return -1; // Extract two minimum elements // and insert their sum int first = h.extractMin(); int second = h.extractMin(); h.insertKey(first + second); res++; } return res; } // Driver code public static void main(String args[]) { int arr[] = {1, 10, 12, 9, 2, 3}; int n = arr.length; int k = 6; System.out.println(countMinOps(arr, n, k)); }}// This code is contributed by Sumit Ghosh
// A C# program to count minimum steps to make all// elements greater than or equal to k.using System; public class Add_Elements{ // A class for Min Heap public class MinHeap { public int[] harr; public int capacity; // maximum size public int heap_size; // Current count // Constructor: Builds a heap from // a given array a[] of given size public MinHeap(int []arr, int n) { heap_size = n; capacity = n; harr = new int[n]; for (int i = 0; i < n; i++) harr[i] = arr[i]; // building the heap from first // non-leaf node by calling max // heapify function for (int i = n/2-1; i >= 0; i--) heapify(i); } // A recursive method to heapify a subtree // with root at given index. This method // assumes that the subtrees are already // heapified public void heapify(int i) { int l = left(i); int r = right(i); int smallest = i; if (l < heap_size && harr[l] < harr[i]) smallest = l; if (r < heap_size && harr[r] < harr[smallest]) smallest = r; if (smallest != i) { int temp = harr[i]; harr[i] = harr[smallest]; harr[smallest] = temp; heapify(smallest); } } public static int parent(int i) { return (i-1)/2; } // to get index of left child of // node at index i static int left(int i) { return (2*i + 1); } // to get index of right child of // node at index i public int right(int i) { return (2*i + 2); } // Method to remove minimum element // (or root) from min heap public int extractMin() { if (heap_size <= 0) return int.MaxValue; if (heap_size == 1) { heap_size--; return harr[0]; } // Store the minimum value, and // remove it from heap int root = harr[0]; harr[0] = harr[heap_size-1]; heap_size--; heapify(0); return root; } // Returns the minimum key (key at // root) from min heap public int getMin() { return harr[0]; } public int getSize() { return heap_size; } // Inserts a new key 'k' public void insertKey(int k) { // First insert the new key at the end heap_size++; int i = heap_size - 1; harr[i] = k; // Fix the min heap property if it is violated while (i != 0 && harr[parent(i)] > harr[i]) { int temp = harr[i]; harr[i] = harr[parent(i)]; harr[parent(i)] = temp; i = parent(i); } } } // Returns count of steps needed to make // all elements greater than or equal to // k by adding elements static int countMinOps(int []arr, int n, int k) { // Build a min heap of array elements MinHeap h = new MinHeap(arr, n); int res = 0; while (h.getMin() < k) { if (h.getSize() == 1) return -1; // Extract two minimum elements // and insert their sum int first = h.extractMin(); int second = h.extractMin(); h.insertKey(first + second); res++; } return res; } // Driver code public static void Main(String []args) { int []arr = {1, 10, 12, 9, 2, 3}; int n = arr.Length; int k = 6; Console.WriteLine(countMinOps(arr, n, k)); }} // This code has been contributed by 29AjayKumar
<script> // A JavaScript program to count minimum steps to make all// elements greater than or equal to k. let harr;let capacity; // maximum sizelet heap_size; // Current count // Constructor: Builds a heap from // a given array a[] of given sizefunction MinHeap(arr,n){ heap_size = n; capacity = n; harr = new Array(n); for (let i=0; i<n; i++) harr[i] = arr[i]; // building the heap from first // non-leaf node by calling max // heapify function for (let i=n/2-1; i>=0; i--) heapify(i);} // A recursive method to heapify a subtree // with root at given index. This method // assumes that the subtrees are already // heapifiedfunction heapify(i){ let l = left(i); let r = right(i); let smallest = i; if (l < heap_size && harr[l] < harr[i]) smallest = l; if (r < heap_size && harr[r] < harr[smallest]) smallest = r; if (smallest != i) { let temp = harr[i]; harr[i] = harr[smallest]; harr[smallest] = temp; heapify(smallest); }} function parent(i){ return (i-1)/2;} // to get index of left child of // node at index ifunction left(i){ return (2*i + 1);} // to get index of right child of // node at index ifunction right(i){ return (2*i + 2);} // Method to remove minimum element // (or root) from min heapfunction extractMin(){ if (heap_size <= 0) return Number.MAX_VALUE; if (heap_size == 1) { heap_size--; return harr[0]; } // Store the minimum value, and // remove it from heap let root = harr[0]; harr[0] = harr[heap_size-1]; heap_size--; heapify(0); return root;} // Returns the minimum key (key at // root) from min heapfunction getMin(){ return harr[0];} function getSize(){ return heap_size;} // Inserts a new key 'k'function insertKey(k){ // First insert the new key at the end heap_size++; let i = heap_size - 1; harr[i] = k; // Fix the min heap property if it is violated while (i != 0 && harr[parent(i)] > harr[i]) { let temp = harr[i]; harr[i] = harr[parent(i)]; harr[parent(i)] = temp; i = parent(i); }} // Returns count of steps needed to make // all elements greater than or equal to // k by adding elementsfunction countMinOps(arr,n,k){ // Build a min heap of array elements MinHeap(arr, n); let res = 0; while (getMin() < k) { if (getSize() == 1) return -1; // Extract two minimum elements // and insert their sum let first = extractMin(); let second = extractMin(); insertKey(first + second); res++; } return res;} // Driver codelet arr=[1, 10, 12, 9, 2, 3];let n = arr.length;let k = 6;document.write(countMinOps(arr, n, k)); // This code is contributed by rag2127 </script>
Output:
2
This article is contributed by Sarthak Kohli. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
29AjayKumar
rag2127
Arrays
Heap
Arrays
Heap
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
HeapSort
Binary Heap
K'th Smallest/Largest Element in Unsorted Array | Set 1
k largest(or smallest) elements in an array
Building Heap from Array | [
{
"code": null,
"e": 26559,
"s": 26531,
"text": "\n06 Jul, 2021"
},
{
"code": null,
"e": 26817,
"s": 26559,
"text": "We are given a list of N unsorted elements, we need to find minimum number of steps in which the elements of the list can be added to make all the elements greater than or equal to K. We are allowed to add two elements together and make them one.Examples: "
},
{
"code": null,
"e": 27116,
"s": 26817,
"text": "Input : arr[] = {1 10 12 9 2 3}\n K = 6\nOutput : 2\nFirst we add (1 + 2), now the new list becomes \n3 10 12 9 3, then we add (3 + 3), now the new \nlist becomes 6 10 12 9, Now all the elements in \nthe list are greater than 6. Hence the output is \n2 i:e 2 operations are required \nto do this."
},
{
"code": null,
"e": 27735,
"s": 27118,
"text": "As we can see from above explanation, we need to extract two smallest elements and then add their sum to list. We need to continue this step until all elements are greater than or equal to K.Method 1 (Brute Force): We can create a simple array the sort it and then add two minimum elements and keep on storing them back in the array until all the elements become greater than K.Method 2 (Efficient): If we take a closer look, we can notice that this problem is similar to Huffman coding. We use Min Heap as the main operations here are extract min and insert. Both of these operations can be done in O(Log n) time. "
},
{
"code": null,
"e": 27739,
"s": 27735,
"text": "C++"
},
{
"code": null,
"e": 27744,
"s": 27739,
"text": "Java"
},
{
"code": null,
"e": 27747,
"s": 27744,
"text": "C#"
},
{
"code": null,
"e": 27758,
"s": 27747,
"text": "Javascript"
},
{
"code": "// A C++ program to count minimum steps to make all// elements greater than or equal to k.#include<bits/stdc++.h>using namespace std; // A class for Min Heapclass MinHeap{ int *harr; int capacity; // maximum size int heap_size; // Current countpublic: // Constructor MinHeap(int *arr, int capacity); // to heapify a subtree with root at // given index void heapify(int ); int parent(int i) { return (i-1)/2; } // to get index of left child of // node at index i int left(int i) { return (2*i + 1); } // to get index of right child of // node at index i int right(int i) { return (2*i + 2); } // to extract the root which is the // minimum element int extractMin(); // Returns the minimum key (key at // root) from min heap int getMin() { return harr[0]; } int getSize() { return heap_size; } // Inserts a new key 'k' void insertKey(int k);}; // Constructor: Builds a heap from// a given array a[] of given sizeMinHeap::MinHeap(int arr[], int n){ heap_size = n; capacity = n; harr = new int[n]; for (int i=0; i<n; i++) harr[i] = arr[i]; // building the heap from first // non-leaf node by calling max // heapify function for (int i=n/2-1; i>=0; i--) heapify(i);} // Inserts a new key 'k'void MinHeap::insertKey(int k){ // First insert the new key at the end heap_size++; int i = heap_size - 1; harr[i] = k; // Fix the min heap property if it is violated while (i != 0 && harr[parent(i)] > harr[i]) { swap(harr[i], harr[parent(i)]); i = parent(i); }} // Method to remove minimum element// (or root) from min heapint MinHeap::extractMin(){ if (heap_size <= 0) return INT_MAX; if (heap_size == 1) { heap_size--; return harr[0]; } // Store the minimum value, and // remove it from heap int root = harr[0]; harr[0] = harr[heap_size-1]; heap_size--; heapify(0); return root;} // A recursive method to heapify a subtree// with root at given index. This method// assumes that the subtrees are already// heapifiedvoid MinHeap::heapify(int i){ int l = left(i); int r = right(i); int smallest = i; if (l < heap_size && harr[l] < harr[i]) smallest = l; if (r < heap_size && harr[r] < harr[smallest]) smallest = r; if (smallest != i) { swap(harr[i], harr[smallest]); heapify(smallest); }} // Returns count of steps needed to make// all elements greater than or equal to// k by adding elementsint countMinOps(int arr[], int n, int k){ // Build a min heap of array elements MinHeap h(arr, n); long int res = 0; while (h.getMin() < k) { if (h.getSize() == 1) return -1; // Extract two minimum elements // and insert their sum int first = h.extractMin(); int second = h.extractMin(); h.insertKey(first + second); res++; } return res;} // Driver codeint main(){ int arr[] = {1, 10, 12, 9, 2, 3}; int n = sizeof(arr)/sizeof(arr[0]); int k = 6; cout << countMinOps(arr, n, k); return 0;}",
"e": 30959,
"s": 27758,
"text": null
},
{
"code": "// A Java program to count minimum steps to make all// elements greater than or equal to k.public class Add_Elements { // A class for Min Heap static class MinHeap { int[] harr; int capacity; // maximum size int heap_size; // Current count // Constructor: Builds a heap from // a given array a[] of given size MinHeap(int arr[], int n) { heap_size = n; capacity = n; harr = new int[n]; for (int i=0; i<n; i++) harr[i] = arr[i]; // building the heap from first // non-leaf node by calling max // heapify function for (int i=n/2-1; i>=0; i--) heapify(i); } // A recursive method to heapify a subtree // with root at given index. This method // assumes that the subtrees are already // heapified void heapify(int i) { int l = left(i); int r = right(i); int smallest = i; if (l < heap_size && harr[l] < harr[i]) smallest = l; if (r < heap_size && harr[r] < harr[smallest]) smallest = r; if (smallest != i) { int temp = harr[i]; harr[i] = harr[smallest]; harr[smallest] = temp; heapify(smallest); } } static int parent(int i) { return (i-1)/2; } // to get index of left child of // node at index i static int left(int i) { return (2*i + 1); } // to get index of right child of // node at index i int right(int i) { return (2*i + 2); } // Method to remove minimum element // (or root) from min heap int extractMin() { if (heap_size <= 0) return Integer.MAX_VALUE; if (heap_size == 1) { heap_size--; return harr[0]; } // Store the minimum value, and // remove it from heap int root = harr[0]; harr[0] = harr[heap_size-1]; heap_size--; heapify(0); return root; } // Returns the minimum key (key at // root) from min heap int getMin() { return harr[0]; } int getSize() { return heap_size; } // Inserts a new key 'k' void insertKey(int k) { // First insert the new key at the end heap_size++; int i = heap_size - 1; harr[i] = k; // Fix the min heap property if it is violated while (i != 0 && harr[parent(i)] > harr[i]) { int temp = harr[i]; harr[i] = harr[parent(i)]; harr[parent(i)] = temp; i = parent(i); } } } // Returns count of steps needed to make // all elements greater than or equal to // k by adding elements static int countMinOps(int arr[], int n, int k) { // Build a min heap of array elements MinHeap h = new MinHeap(arr, n); int res = 0; while (h.getMin() < k) { if (h.getSize() == 1) return -1; // Extract two minimum elements // and insert their sum int first = h.extractMin(); int second = h.extractMin(); h.insertKey(first + second); res++; } return res; } // Driver code public static void main(String args[]) { int arr[] = {1, 10, 12, 9, 2, 3}; int n = arr.length; int k = 6; System.out.println(countMinOps(arr, n, k)); }}// This code is contributed by Sumit Ghosh",
"e": 34989,
"s": 30959,
"text": null
},
{
"code": "// A C# program to count minimum steps to make all// elements greater than or equal to k.using System; public class Add_Elements{ // A class for Min Heap public class MinHeap { public int[] harr; public int capacity; // maximum size public int heap_size; // Current count // Constructor: Builds a heap from // a given array a[] of given size public MinHeap(int []arr, int n) { heap_size = n; capacity = n; harr = new int[n]; for (int i = 0; i < n; i++) harr[i] = arr[i]; // building the heap from first // non-leaf node by calling max // heapify function for (int i = n/2-1; i >= 0; i--) heapify(i); } // A recursive method to heapify a subtree // with root at given index. This method // assumes that the subtrees are already // heapified public void heapify(int i) { int l = left(i); int r = right(i); int smallest = i; if (l < heap_size && harr[l] < harr[i]) smallest = l; if (r < heap_size && harr[r] < harr[smallest]) smallest = r; if (smallest != i) { int temp = harr[i]; harr[i] = harr[smallest]; harr[smallest] = temp; heapify(smallest); } } public static int parent(int i) { return (i-1)/2; } // to get index of left child of // node at index i static int left(int i) { return (2*i + 1); } // to get index of right child of // node at index i public int right(int i) { return (2*i + 2); } // Method to remove minimum element // (or root) from min heap public int extractMin() { if (heap_size <= 0) return int.MaxValue; if (heap_size == 1) { heap_size--; return harr[0]; } // Store the minimum value, and // remove it from heap int root = harr[0]; harr[0] = harr[heap_size-1]; heap_size--; heapify(0); return root; } // Returns the minimum key (key at // root) from min heap public int getMin() { return harr[0]; } public int getSize() { return heap_size; } // Inserts a new key 'k' public void insertKey(int k) { // First insert the new key at the end heap_size++; int i = heap_size - 1; harr[i] = k; // Fix the min heap property if it is violated while (i != 0 && harr[parent(i)] > harr[i]) { int temp = harr[i]; harr[i] = harr[parent(i)]; harr[parent(i)] = temp; i = parent(i); } } } // Returns count of steps needed to make // all elements greater than or equal to // k by adding elements static int countMinOps(int []arr, int n, int k) { // Build a min heap of array elements MinHeap h = new MinHeap(arr, n); int res = 0; while (h.getMin() < k) { if (h.getSize() == 1) return -1; // Extract two minimum elements // and insert their sum int first = h.extractMin(); int second = h.extractMin(); h.insertKey(first + second); res++; } return res; } // Driver code public static void Main(String []args) { int []arr = {1, 10, 12, 9, 2, 3}; int n = arr.Length; int k = 6; Console.WriteLine(countMinOps(arr, n, k)); }} // This code has been contributed by 29AjayKumar",
"e": 39093,
"s": 34989,
"text": null
},
{
"code": "<script> // A JavaScript program to count minimum steps to make all// elements greater than or equal to k. let harr;let capacity; // maximum sizelet heap_size; // Current count // Constructor: Builds a heap from // a given array a[] of given sizefunction MinHeap(arr,n){ heap_size = n; capacity = n; harr = new Array(n); for (let i=0; i<n; i++) harr[i] = arr[i]; // building the heap from first // non-leaf node by calling max // heapify function for (let i=n/2-1; i>=0; i--) heapify(i);} // A recursive method to heapify a subtree // with root at given index. This method // assumes that the subtrees are already // heapifiedfunction heapify(i){ let l = left(i); let r = right(i); let smallest = i; if (l < heap_size && harr[l] < harr[i]) smallest = l; if (r < heap_size && harr[r] < harr[smallest]) smallest = r; if (smallest != i) { let temp = harr[i]; harr[i] = harr[smallest]; harr[smallest] = temp; heapify(smallest); }} function parent(i){ return (i-1)/2;} // to get index of left child of // node at index ifunction left(i){ return (2*i + 1);} // to get index of right child of // node at index ifunction right(i){ return (2*i + 2);} // Method to remove minimum element // (or root) from min heapfunction extractMin(){ if (heap_size <= 0) return Number.MAX_VALUE; if (heap_size == 1) { heap_size--; return harr[0]; } // Store the minimum value, and // remove it from heap let root = harr[0]; harr[0] = harr[heap_size-1]; heap_size--; heapify(0); return root;} // Returns the minimum key (key at // root) from min heapfunction getMin(){ return harr[0];} function getSize(){ return heap_size;} // Inserts a new key 'k'function insertKey(k){ // First insert the new key at the end heap_size++; let i = heap_size - 1; harr[i] = k; // Fix the min heap property if it is violated while (i != 0 && harr[parent(i)] > harr[i]) { let temp = harr[i]; harr[i] = harr[parent(i)]; harr[parent(i)] = temp; i = parent(i); }} // Returns count of steps needed to make // all elements greater than or equal to // k by adding elementsfunction countMinOps(arr,n,k){ // Build a min heap of array elements MinHeap(arr, n); let res = 0; while (getMin() < k) { if (getSize() == 1) return -1; // Extract two minimum elements // and insert their sum let first = extractMin(); let second = extractMin(); insertKey(first + second); res++; } return res;} // Driver codelet arr=[1, 10, 12, 9, 2, 3];let n = arr.length;let k = 6;document.write(countMinOps(arr, n, k)); // This code is contributed by rag2127 </script>",
"e": 42489,
"s": 39093,
"text": null
},
{
"code": null,
"e": 42499,
"s": 42489,
"text": "Output: "
},
{
"code": null,
"e": 42501,
"s": 42499,
"text": "2"
},
{
"code": null,
"e": 42923,
"s": 42501,
"text": "This article is contributed by Sarthak Kohli. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 42935,
"s": 42923,
"text": "29AjayKumar"
},
{
"code": null,
"e": 42943,
"s": 42935,
"text": "rag2127"
},
{
"code": null,
"e": 42950,
"s": 42943,
"text": "Arrays"
},
{
"code": null,
"e": 42955,
"s": 42950,
"text": "Heap"
},
{
"code": null,
"e": 42962,
"s": 42955,
"text": "Arrays"
},
{
"code": null,
"e": 42967,
"s": 42962,
"text": "Heap"
},
{
"code": null,
"e": 43065,
"s": 42967,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 43133,
"s": 43065,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 43177,
"s": 43133,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 43225,
"s": 43177,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 43248,
"s": 43225,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 43280,
"s": 43248,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 43289,
"s": 43280,
"text": "HeapSort"
},
{
"code": null,
"e": 43301,
"s": 43289,
"text": "Binary Heap"
},
{
"code": null,
"e": 43357,
"s": 43301,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 1"
},
{
"code": null,
"e": 43401,
"s": 43357,
"text": "k largest(or smallest) elements in an array"
}
] |
How to rotate only text in annotation in ggplot2? - GeeksforGeeks | 03 Mar, 2021
R has ggplot2 which is a data visualization package for the statistical programming language R. After analyzing and plotting graphs, we can add an annotation in our graph by annotate() function.
Syntax: annotate()
Parameters:
geom : specify text
x : x axis location
y : y axis location
label : custom textual content
color : color of textual content
size : size of text
fontface : fontface of text
angle : angle of text
Approach
Import module
Create dataframe
Plot graph
Use annotate() function with required parameters
First, let’s create a simple line plot.
Program:
R
# Import Packagelibrary(ggplot2) # df datasetdf <- data.frame(a=c(2,4,8), b=c(5, 10, 15)) # Basic plotplot = ggplot(df, aes(x = a, y = b)) + geom_point() + geom_line() # angle=90plot + annotate('text', x = 6, y = 10, label = 'GeeksForGeeks', size = 10, angle='90')
Output:
We can rotate text in annotation by angle parameter. To modify the angle of text, an “angle” argument is used. In the below example, the angle assigned to the text “GeeksForGeeks” is 180.
To change the font face of text, use fontface argument and assign one type of font face like bold, Italic, etc. Here, an italic font-face is assigned to the text.
Program :
R
# Import Packagelibrary(ggplot2) # df datasetdf <- data.frame(a=c(2,4,8), b=c(5, 10, 15)) # Basic plotplot = ggplot(df, aes(x = a, y = b)) + geom_point() + geom_line() plot + annotate('text', x = 6, y = 7.5, label = 'GeeksForGeeks', size = 10, fontface='bold', angle='180')
Output:
Example 2:
R
# Import Packagelibrary(ggplot2) # df datasetdf <- data.frame(a=c(2,4,8), b=c(5, 10, 15)) # Basic plotmyplot = ggplot(df, aes(x = a, y = b)) + geom_point() + geom_line() myplot + annotate('text', x = 6, y = 10, label = 'GeeksForGeeks', size = 10, angle='90')
Output:
Picked
R-ggplot
Technical Scripter 2020
R Language
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
R - if statement
How to filter R dataframe by multiple conditions?
Plot mean and standard deviation using ggplot2 in R
How to import an Excel File into R ? | [
{
"code": null,
"e": 26487,
"s": 26459,
"text": "\n03 Mar, 2021"
},
{
"code": null,
"e": 26682,
"s": 26487,
"text": "R has ggplot2 which is a data visualization package for the statistical programming language R. After analyzing and plotting graphs, we can add an annotation in our graph by annotate() function."
},
{
"code": null,
"e": 26701,
"s": 26682,
"text": "Syntax: annotate()"
},
{
"code": null,
"e": 26713,
"s": 26701,
"text": "Parameters:"
},
{
"code": null,
"e": 26733,
"s": 26713,
"text": "geom : specify text"
},
{
"code": null,
"e": 26753,
"s": 26733,
"text": "x : x axis location"
},
{
"code": null,
"e": 26773,
"s": 26753,
"text": "y : y axis location"
},
{
"code": null,
"e": 26804,
"s": 26773,
"text": "label : custom textual content"
},
{
"code": null,
"e": 26837,
"s": 26804,
"text": "color : color of textual content"
},
{
"code": null,
"e": 26857,
"s": 26837,
"text": "size : size of text"
},
{
"code": null,
"e": 26885,
"s": 26857,
"text": "fontface : fontface of text"
},
{
"code": null,
"e": 26907,
"s": 26885,
"text": "angle : angle of text"
},
{
"code": null,
"e": 26916,
"s": 26907,
"text": "Approach"
},
{
"code": null,
"e": 26930,
"s": 26916,
"text": "Import module"
},
{
"code": null,
"e": 26947,
"s": 26930,
"text": "Create dataframe"
},
{
"code": null,
"e": 26958,
"s": 26947,
"text": "Plot graph"
},
{
"code": null,
"e": 27007,
"s": 26958,
"text": "Use annotate() function with required parameters"
},
{
"code": null,
"e": 27047,
"s": 27007,
"text": "First, let’s create a simple line plot."
},
{
"code": null,
"e": 27056,
"s": 27047,
"text": "Program:"
},
{
"code": null,
"e": 27058,
"s": 27056,
"text": "R"
},
{
"code": "# Import Packagelibrary(ggplot2) # df datasetdf <- data.frame(a=c(2,4,8), b=c(5, 10, 15)) # Basic plotplot = ggplot(df, aes(x = a, y = b)) + geom_point() + geom_line() # angle=90plot + annotate('text', x = 6, y = 10, label = 'GeeksForGeeks', size = 10, angle='90')",
"e": 27388,
"s": 27058,
"text": null
},
{
"code": null,
"e": 27396,
"s": 27388,
"text": "Output:"
},
{
"code": null,
"e": 27585,
"s": 27396,
"text": "We can rotate text in annotation by angle parameter. To modify the angle of text, an “angle” argument is used. In the below example, the angle assigned to the text “GeeksForGeeks” is 180. "
},
{
"code": null,
"e": 27748,
"s": 27585,
"text": "To change the font face of text, use fontface argument and assign one type of font face like bold, Italic, etc. Here, an italic font-face is assigned to the text."
},
{
"code": null,
"e": 27758,
"s": 27748,
"text": "Program :"
},
{
"code": null,
"e": 27760,
"s": 27758,
"text": "R"
},
{
"code": "# Import Packagelibrary(ggplot2) # df datasetdf <- data.frame(a=c(2,4,8), b=c(5, 10, 15)) # Basic plotplot = ggplot(df, aes(x = a, y = b)) + geom_point() + geom_line() plot + annotate('text', x = 6, y = 7.5, label = 'GeeksForGeeks', size = 10, fontface='bold', angle='180')",
"e": 28122,
"s": 27760,
"text": null
},
{
"code": null,
"e": 28130,
"s": 28122,
"text": "Output:"
},
{
"code": null,
"e": 28141,
"s": 28130,
"text": "Example 2:"
},
{
"code": null,
"e": 28143,
"s": 28141,
"text": "R"
},
{
"code": "# Import Packagelibrary(ggplot2) # df datasetdf <- data.frame(a=c(2,4,8), b=c(5, 10, 15)) # Basic plotmyplot = ggplot(df, aes(x = a, y = b)) + geom_point() + geom_line() myplot + annotate('text', x = 6, y = 10, label = 'GeeksForGeeks', size = 10, angle='90')",
"e": 28474,
"s": 28143,
"text": null
},
{
"code": null,
"e": 28482,
"s": 28474,
"text": "Output:"
},
{
"code": null,
"e": 28489,
"s": 28482,
"text": "Picked"
},
{
"code": null,
"e": 28498,
"s": 28489,
"text": "R-ggplot"
},
{
"code": null,
"e": 28522,
"s": 28498,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 28533,
"s": 28522,
"text": "R Language"
},
{
"code": null,
"e": 28552,
"s": 28533,
"text": "Technical Scripter"
},
{
"code": null,
"e": 28650,
"s": 28552,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28702,
"s": 28650,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 28737,
"s": 28702,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 28775,
"s": 28737,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 28833,
"s": 28775,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 28876,
"s": 28833,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 28925,
"s": 28876,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 28942,
"s": 28925,
"text": "R - if statement"
},
{
"code": null,
"e": 28992,
"s": 28942,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 29044,
"s": 28992,
"text": "Plot mean and standard deviation using ggplot2 in R"
}
] |
Find if array can be divided into two subarrays of equal sum | 04 Jul, 2022
Given an array of integers, find if it’s possible to remove exactly one integer from the array that divides the array into two subarrays with the same sum.
Examples:
Input: arr = [6, 2, 3, 2, 1]
Output: true
Explanation: On removing element 2 at index 1,
the array gets divided into two subarrays [6]
and [3, 2, 1] having equal sum
Input: arr = [6, 1, 3, 2, 5]
Output: true
Explanation: On removing element 3 at index 2,
the array gets divided into two subarrays [6, 1]
and [2, 5] having equal sum.
Input: arr = [6, -2, -3, 2, 3]
Output: true
Explanation: On removing element 6 at index 0,
the array gets divided into two sets []
and [-2, -3, 2, 3] having equal sum
Input: arr = [6, -2, 3, 2, 3]
Output: false
A naive solution would be to consider all elements of the array and calculate their left and right sum and return true if left and right sum are found to be equal. The time complexity of this solution would be O(n2).
The efficient solution involves calculating sum of all elements of the array in advance. Then for each element of the array, we can calculate its right sum in O(1) time by using total sum of the array elements minus sum of elements found so far. The time complexity of this solution would be O(n) and auxiliary space used by it will be O(1).
Below is the implementation of above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to divide the array into two// subarrays with the same sum on removing// exactly one integer from the array#include <iostream>using namespace std; // Utility function to print the sub-arrayvoid printSubArray(int arr[], int start, int end){ cout << "[ "; for (int i = start; i <= end; i++) cout << arr[i] << " "; cout << "] ";} // Function that divides the array into two subarrays// with the same sumbool divideArray(int arr[], int n){ // sum stores sum of all elements of the array int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; // sum stores sum till previous index of the array int sum_so_far = 0; for (int i = 0; i < n; i++) { // If on removing arr[i], we get equals left // and right half if (2 * sum_so_far + arr[i] == sum) { cout << "The array can be divided into" "two subarrays with equal sum\nThe" " two subarrays are - "; printSubArray(arr, 0, i - 1); printSubArray(arr, i + 1, n - 1); return true; } // add current element to sum_so_far sum_so_far += arr[i]; } // The array cannot be divided cout << "The array cannot be divided into two " "subarrays with equal sum"; return false;} // Driver codeint main(){ int arr[] = {6, 2, 3, 2, 1}; int n = sizeof(arr)/sizeof(arr[0]); divideArray(arr, n); return 0;}
// Java program to divide the array into two// subarrays with the same sum on removing// exactly one integer from the arrayimport java.io.*; class GFG{ // Utility function to print the sub-array static void printSubArray(int arr[], int start, int end) { System.out.print("[ "); for (int i = start; i <= end; i++) System.out.print(arr[i] +" "); System.out.print("] "); } // Function that divides the array into two subarrays // with the same sum static boolean divideArray(int arr[], int n) { // sum stores sum of all elements of the array int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; // sum stores sum till previous index of the array int sum_so_far = 0; for (int i = 0; i < n; i++) { // If on removing arr[i], we get equals left // and right half if (2 * sum_so_far + arr[i] == sum) { System.out.print("The array can be divided into " +"two subarrays with equal sum\nThe" +" two subarrays are - "); printSubArray(arr, 0, i - 1); printSubArray(arr, i + 1, n - 1); return true; } // add current element to sum_so_far sum_so_far += arr[i]; } // The array cannot be divided System.out.println("The array cannot be divided into two " +"subarrays with equal sum"); return false; } // Driver program public static void main (String[] args) { int arr[] = {6, 2, 3, 2, 1}; int n = arr.length; divideArray(arr, n); }} // This code is contributed by Pramod Kumar
''' Python3 program to divide the arrayinto two subarrays with the same sum onremoving exactly one integer from the array''' # Utility function to print the sub-arraydef printSubArray(arr, start, end): print ("[ ", end = "") for i in range(start, end+1): print (arr[i], end =" ") print ("]", end ="") # Function that divides the array into# two subarrays with the same sumdef divideArray(arr, n): # sum stores sum of all # elements of the array sum = 0 for i in range(0, n): sum += arr[i] # sum stores sum till previous # index of the array sum_so_far = 0 for i in range(0, n): # If on removing arr[i], we get # equals left and right half if 2 * sum_so_far + arr[i] == sum: print ("The array can be divided into", "two subarrays with equal sum") print ("two subarrays are -", end = "") printSubArray(arr, 0, i - 1) printSubArray(arr, i + 1, n - 1) return True # add current element to sum_so_far sum_so_far += arr[i] # The array cannot be divided print ("The array cannot be divided into" "two subarrays with equal sum", end = "") return False # Driver codearr = [6, 2, 3, 2, 1]n = len(arr)divideArray(arr, n) # This code is contributed by Shreyanshi Arun
// C# program to divide the array into two// subarrays with the same sum on removing// exactly one integer from the arrayusing System; class GFG { // Utility function to print the sub-array static void printSubArray(int []arr, int start, int end) { Console.Write("[ "); for (int i = start; i <= end; i++) Console.Write(arr[i] +" "); Console.Write("] "); } // Function that divides the array into // two subarrays with the same sum static bool divideArray(int []arr, int n) { // sum stores sum of all elements of // the array int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; // sum stores sum till previous index // of the array int sum_so_far = 0; for (int i = 0; i < n; i++) { // If on removing arr[i], we get // equals left and right half if (2 * sum_so_far + arr[i] == sum) { Console.Write("The array can be" + " divided into two subarrays" + " with equal sum\nThe two" + " subarrays are - "); printSubArray(arr, 0, i - 1); printSubArray(arr, i + 1, n - 1); return true; } // add current element to sum_so_far sum_so_far += arr[i]; } // The array cannot be divided Console.WriteLine("The array cannot be" + " divided into two subarrays with " + "equal sum"); return false; } // Driver program public static void Main () { int []arr = {6, 2, 3, 2, 1}; int n = arr.Length; divideArray(arr, n); }} // This code is contributed by anuj_67.
<?php// PHP program to divide the array into two// subarrays with the same sum on removing// exactly one integer from the array // Utility function to print the sub-arrayfunction printSubArray($arr, $start, $end){ echo "[ "; for ($i = $start; $i <= $end; $i++) echo $arr[$i] . " "; echo "] ";} // Function that divides the// array into two subarrays// with the same sumfunction divideArray($arr, $n){ // sum stores sum of all // elements of the array $sum = 0; for ($i = 0; $i < $n; $i++) $sum += $arr[$i]; // sum stores sum till previous // index of the array $sum_so_far = 0; for ($i = 0; $i < $n; $i++) { // If on removing arr[i], // we get equals left // and right half if (2 * $sum_so_far + $arr[$i] == $sum) { echo "The array can be divided into" . "two subarrays with equal sum\nThe". " two subarrays are - "; printSubArray($arr, 0, $i - 1); printSubArray($arr, $i + 1, $n - 1); return true; } // add current element // to sum_so_far $sum_so_far += $arr[$i]; } // The array cannot be divided echo "The array cannot be divided into two ". "subarrays with equal sum"; return false;} // Driver code $arr = array(6, 2, 3, 2, 1); $n = sizeof($arr); divideArray($arr, $n); // This code is contributed by Anuj_67?>
<script> // JavaScript program to divide the array into two // subarrays with the same sum on removing // exactly one integer from the array // Utility function to print the sub-array function printSubArray(arr, start, end) { document.write("[ "); for (let i = start; i <= end; i++) document.write(arr[i] +" "); document.write("] "); } // Function that divides the array into // two subarrays with the same sum function divideArray(arr, n) { // sum stores sum of all elements of // the array let sum = 0; for (let i = 0; i < n; i++) sum += arr[i]; // sum stores sum till previous index // of the array let sum_so_far = 0; for (let i = 0; i < n; i++) { // If on removing arr[i], we get // equals left and right half if (2 * sum_so_far + arr[i] == sum) { document.write("The array can be" + " divided into two subarrays" + " with equal sum " + "</br>" + "The two" + " sets are - "); printSubArray(arr, 0, i - 1); printSubArray(arr, i + 1, n - 1); return true; } // add current element to sum_so_far sum_so_far += arr[i]; } // The array cannot be divided document.write("The array cannot be" + " divided into two subarrays with " + "equal sum" + "</br>"); return false; } let arr = [6, 2, 3, 2, 1]; let n = arr.length; divideArray(arr, n); </script>
The array can be divided intotwo subarrays with equal sum
The two subarrays are - [ 6 ] [ 3 2 1 ]
This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
vt_m
nidhi_biet
rameshtravel07
simranarora5sos
hardikkoriintern
subarray
subarray-sum
Arrays
Arrays
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
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Introduction to Arrays
K'th Smallest/Largest Element in Unsorted Array | Set 1
Introduction to Data Structures
Python | Using 2D arrays/lists the right way | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n04 Jul, 2022"
},
{
"code": null,
"e": 208,
"s": 52,
"text": "Given an array of integers, find if it’s possible to remove exactly one integer from the array that divides the array into two subarrays with the same sum."
},
{
"code": null,
"e": 219,
"s": 208,
"text": "Examples: "
},
{
"code": null,
"e": 778,
"s": 219,
"text": "Input: arr = [6, 2, 3, 2, 1]\nOutput: true\nExplanation: On removing element 2 at index 1,\nthe array gets divided into two subarrays [6]\n and [3, 2, 1] having equal sum\n\nInput: arr = [6, 1, 3, 2, 5]\nOutput: true\nExplanation: On removing element 3 at index 2,\nthe array gets divided into two subarrays [6, 1]\nand [2, 5] having equal sum.\n\nInput: arr = [6, -2, -3, 2, 3]\nOutput: true\nExplanation: On removing element 6 at index 0, \nthe array gets divided into two sets [] \nand [-2, -3, 2, 3] having equal sum\n\nInput: arr = [6, -2, 3, 2, 3]\nOutput: false"
},
{
"code": null,
"e": 995,
"s": 778,
"text": "A naive solution would be to consider all elements of the array and calculate their left and right sum and return true if left and right sum are found to be equal. The time complexity of this solution would be O(n2)."
},
{
"code": null,
"e": 1337,
"s": 995,
"text": "The efficient solution involves calculating sum of all elements of the array in advance. Then for each element of the array, we can calculate its right sum in O(1) time by using total sum of the array elements minus sum of elements found so far. The time complexity of this solution would be O(n) and auxiliary space used by it will be O(1)."
},
{
"code": null,
"e": 1384,
"s": 1337,
"text": "Below is the implementation of above approach:"
},
{
"code": null,
"e": 1388,
"s": 1384,
"text": "C++"
},
{
"code": null,
"e": 1393,
"s": 1388,
"text": "Java"
},
{
"code": null,
"e": 1401,
"s": 1393,
"text": "Python3"
},
{
"code": null,
"e": 1404,
"s": 1401,
"text": "C#"
},
{
"code": null,
"e": 1408,
"s": 1404,
"text": "PHP"
},
{
"code": null,
"e": 1419,
"s": 1408,
"text": "Javascript"
},
{
"code": "// C++ program to divide the array into two// subarrays with the same sum on removing// exactly one integer from the array#include <iostream>using namespace std; // Utility function to print the sub-arrayvoid printSubArray(int arr[], int start, int end){ cout << \"[ \"; for (int i = start; i <= end; i++) cout << arr[i] << \" \"; cout << \"] \";} // Function that divides the array into two subarrays// with the same sumbool divideArray(int arr[], int n){ // sum stores sum of all elements of the array int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; // sum stores sum till previous index of the array int sum_so_far = 0; for (int i = 0; i < n; i++) { // If on removing arr[i], we get equals left // and right half if (2 * sum_so_far + arr[i] == sum) { cout << \"The array can be divided into\" \"two subarrays with equal sum\\nThe\" \" two subarrays are - \"; printSubArray(arr, 0, i - 1); printSubArray(arr, i + 1, n - 1); return true; } // add current element to sum_so_far sum_so_far += arr[i]; } // The array cannot be divided cout << \"The array cannot be divided into two \" \"subarrays with equal sum\"; return false;} // Driver codeint main(){ int arr[] = {6, 2, 3, 2, 1}; int n = sizeof(arr)/sizeof(arr[0]); divideArray(arr, n); return 0;}",
"e": 2875,
"s": 1419,
"text": null
},
{
"code": "// Java program to divide the array into two// subarrays with the same sum on removing// exactly one integer from the arrayimport java.io.*; class GFG{ // Utility function to print the sub-array static void printSubArray(int arr[], int start, int end) { System.out.print(\"[ \"); for (int i = start; i <= end; i++) System.out.print(arr[i] +\" \"); System.out.print(\"] \"); } // Function that divides the array into two subarrays // with the same sum static boolean divideArray(int arr[], int n) { // sum stores sum of all elements of the array int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; // sum stores sum till previous index of the array int sum_so_far = 0; for (int i = 0; i < n; i++) { // If on removing arr[i], we get equals left // and right half if (2 * sum_so_far + arr[i] == sum) { System.out.print(\"The array can be divided into \" +\"two subarrays with equal sum\\nThe\" +\" two subarrays are - \"); printSubArray(arr, 0, i - 1); printSubArray(arr, i + 1, n - 1); return true; } // add current element to sum_so_far sum_so_far += arr[i]; } // The array cannot be divided System.out.println(\"The array cannot be divided into two \" +\"subarrays with equal sum\"); return false; } // Driver program public static void main (String[] args) { int arr[] = {6, 2, 3, 2, 1}; int n = arr.length; divideArray(arr, n); }} // This code is contributed by Pramod Kumar",
"e": 4646,
"s": 2875,
"text": null
},
{
"code": "''' Python3 program to divide the arrayinto two subarrays with the same sum onremoving exactly one integer from the array''' # Utility function to print the sub-arraydef printSubArray(arr, start, end): print (\"[ \", end = \"\") for i in range(start, end+1): print (arr[i], end =\" \") print (\"]\", end =\"\") # Function that divides the array into# two subarrays with the same sumdef divideArray(arr, n): # sum stores sum of all # elements of the array sum = 0 for i in range(0, n): sum += arr[i] # sum stores sum till previous # index of the array sum_so_far = 0 for i in range(0, n): # If on removing arr[i], we get # equals left and right half if 2 * sum_so_far + arr[i] == sum: print (\"The array can be divided into\", \"two subarrays with equal sum\") print (\"two subarrays are -\", end = \"\") printSubArray(arr, 0, i - 1) printSubArray(arr, i + 1, n - 1) return True # add current element to sum_so_far sum_so_far += arr[i] # The array cannot be divided print (\"The array cannot be divided into\" \"two subarrays with equal sum\", end = \"\") return False # Driver codearr = [6, 2, 3, 2, 1]n = len(arr)divideArray(arr, n) # This code is contributed by Shreyanshi Arun",
"e": 5983,
"s": 4646,
"text": null
},
{
"code": "// C# program to divide the array into two// subarrays with the same sum on removing// exactly one integer from the arrayusing System; class GFG { // Utility function to print the sub-array static void printSubArray(int []arr, int start, int end) { Console.Write(\"[ \"); for (int i = start; i <= end; i++) Console.Write(arr[i] +\" \"); Console.Write(\"] \"); } // Function that divides the array into // two subarrays with the same sum static bool divideArray(int []arr, int n) { // sum stores sum of all elements of // the array int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; // sum stores sum till previous index // of the array int sum_so_far = 0; for (int i = 0; i < n; i++) { // If on removing arr[i], we get // equals left and right half if (2 * sum_so_far + arr[i] == sum) { Console.Write(\"The array can be\" + \" divided into two subarrays\" + \" with equal sum\\nThe two\" + \" subarrays are - \"); printSubArray(arr, 0, i - 1); printSubArray(arr, i + 1, n - 1); return true; } // add current element to sum_so_far sum_so_far += arr[i]; } // The array cannot be divided Console.WriteLine(\"The array cannot be\" + \" divided into two subarrays with \" + \"equal sum\"); return false; } // Driver program public static void Main () { int []arr = {6, 2, 3, 2, 1}; int n = arr.Length; divideArray(arr, n); }} // This code is contributed by anuj_67.",
"e": 7832,
"s": 5983,
"text": null
},
{
"code": "<?php// PHP program to divide the array into two// subarrays with the same sum on removing// exactly one integer from the array // Utility function to print the sub-arrayfunction printSubArray($arr, $start, $end){ echo \"[ \"; for ($i = $start; $i <= $end; $i++) echo $arr[$i] . \" \"; echo \"] \";} // Function that divides the// array into two subarrays// with the same sumfunction divideArray($arr, $n){ // sum stores sum of all // elements of the array $sum = 0; for ($i = 0; $i < $n; $i++) $sum += $arr[$i]; // sum stores sum till previous // index of the array $sum_so_far = 0; for ($i = 0; $i < $n; $i++) { // If on removing arr[i], // we get equals left // and right half if (2 * $sum_so_far + $arr[$i] == $sum) { echo \"The array can be divided into\" . \"two subarrays with equal sum\\nThe\". \" two subarrays are - \"; printSubArray($arr, 0, $i - 1); printSubArray($arr, $i + 1, $n - 1); return true; } // add current element // to sum_so_far $sum_so_far += $arr[$i]; } // The array cannot be divided echo \"The array cannot be divided into two \". \"subarrays with equal sum\"; return false;} // Driver code $arr = array(6, 2, 3, 2, 1); $n = sizeof($arr); divideArray($arr, $n); // This code is contributed by Anuj_67?>",
"e": 9302,
"s": 7832,
"text": null
},
{
"code": "<script> // JavaScript program to divide the array into two // subarrays with the same sum on removing // exactly one integer from the array // Utility function to print the sub-array function printSubArray(arr, start, end) { document.write(\"[ \"); for (let i = start; i <= end; i++) document.write(arr[i] +\" \"); document.write(\"] \"); } // Function that divides the array into // two subarrays with the same sum function divideArray(arr, n) { // sum stores sum of all elements of // the array let sum = 0; for (let i = 0; i < n; i++) sum += arr[i]; // sum stores sum till previous index // of the array let sum_so_far = 0; for (let i = 0; i < n; i++) { // If on removing arr[i], we get // equals left and right half if (2 * sum_so_far + arr[i] == sum) { document.write(\"The array can be\" + \" divided into two subarrays\" + \" with equal sum \" + \"</br>\" + \"The two\" + \" sets are - \"); printSubArray(arr, 0, i - 1); printSubArray(arr, i + 1, n - 1); return true; } // add current element to sum_so_far sum_so_far += arr[i]; } // The array cannot be divided document.write(\"The array cannot be\" + \" divided into two subarrays with \" + \"equal sum\" + \"</br>\"); return false; } let arr = [6, 2, 3, 2, 1]; let n = arr.length; divideArray(arr, n); </script>",
"e": 11033,
"s": 9302,
"text": null
},
{
"code": null,
"e": 11132,
"s": 11033,
"text": "The array can be divided intotwo subarrays with equal sum\nThe two subarrays are - [ 6 ] [ 3 2 1 ] "
},
{
"code": null,
"e": 11427,
"s": 11132,
"text": "This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 11432,
"s": 11427,
"text": "vt_m"
},
{
"code": null,
"e": 11443,
"s": 11432,
"text": "nidhi_biet"
},
{
"code": null,
"e": 11458,
"s": 11443,
"text": "rameshtravel07"
},
{
"code": null,
"e": 11474,
"s": 11458,
"text": "simranarora5sos"
},
{
"code": null,
"e": 11491,
"s": 11474,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 11500,
"s": 11491,
"text": "subarray"
},
{
"code": null,
"e": 11513,
"s": 11500,
"text": "subarray-sum"
},
{
"code": null,
"e": 11520,
"s": 11513,
"text": "Arrays"
},
{
"code": null,
"e": 11527,
"s": 11520,
"text": "Arrays"
},
{
"code": null,
"e": 11625,
"s": 11527,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11693,
"s": 11625,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 11737,
"s": 11693,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 11769,
"s": 11737,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 11817,
"s": 11769,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 11831,
"s": 11817,
"text": "Linear Search"
},
{
"code": null,
"e": 11916,
"s": 11831,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 11939,
"s": 11916,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 11995,
"s": 11939,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 1"
},
{
"code": null,
"e": 12027,
"s": 11995,
"text": "Introduction to Data Structures"
}
] |
Start and stop a thread in Python | 12 Jun, 2019
The threading library can be used to execute any Python callable in its own thread. To do this, create a Thread instance and supply the callable that you wish to execute as a target as shown in the code given below –
# Code to execute in an independent threadimport time def countdown(n): while n > 0: print('T-minus', n) n -= 1 time.sleep(5) # Create and launch a threadfrom threading import Threadt = Thread(target = countdown, args =(10, ))t.start()
When a thread instance is created, it doesn’t start executing until its start() method (which invokes the target function with the arguments you supplied) is invoked. Threads are executed in their own system-level thread (e.g., a POSIX thread or Windows threads) that is fully managed by the host operating system. Once started, threads run independently until the target function returns. Code #2 : Querying a thread instance to see if it’s still running.
if t.is_alive(): print('Still running')else: print('Completed')
One can also request to join with a thread, which waits for it to terminate.
t.join()
The interpreter remains running until all threads terminate. For long-running threads or background tasks that run forever, consider it making the thread daemonic. Code #3 :
t = Thread(target = countdown, args =(10, ), daemon = True)t.start()
Daemonic threads can’t be joined. However, they are destroyed automatically when the main thread terminates. Beyond the two operations shown, there aren’t many other things to do with threads. For example, there are no operations to terminate a thread, signal a thread, adjust its scheduling, or perform any other high-level operations. To have these features, build them on their own. To be able to terminate threads, the thread must be programmed to poll forexit at selected points. For example, put your thread in a class such as the one mentioned in the code below –
Code #4 : Putting the thread in a class.
class CountdownTask: def __init__(self): self._running = True def terminate(self): self._running = False def run(self, n): while self._running and n > 0: print('T-minus', n) n -= 1 time.sleep(5) c = CountdownTask()t = Thread(target = c.run, args =(10, ))t.start()...# Signal terminationc.terminate() # Wait for actual termination (if needed) t.join()
Polling for thread termination can be tricky to coordinate if threads perform blocking operations such as I/O. For example, a thread blocked indefinitely on an I/O operation may never return to check if it’s been killed. To correctly deal with this case, thread needs to be carefully programmed to utilize timeout loops as shown in the code given below.
Code #5 :
class IOTask: def terminate(self): self._running = False def run(self, sock): # sock is a socket # Set timeout period sock.settimeout(5) while self._running: # Perform a blocking I/O operation w/timeout try: data = sock.recv(8192) break except socket.timeout: continue # Continued processing ... # Terminated return
Due to a global interpreter lock (GIL), Python threads are restricted to an execution model that only allows one thread to execute in the interpreter at any given time. For this reason, Python threads should generally not be used for computationally intensive tasks where trying to achieve parallelism on multiple CPUs. They are much better suited for I/O handling and handling concurrent execution in code that performs blocking operations (e.g., waiting for I/O, waiting for results from a database, etc.). Code #6 : Threads defined via inheritance from the Thread class
from threading import Thread class CountdownThread(Thread): def __init__(self, n): super().__init__() self.n = 0 def run(self): while self.n > 0: print('T-minus', self.n) self.n -= 1 time.sleep(5) c = CountdownThread(5)c.start()
Although this works, it introduces an extra dependency between the code and the threading library. That is, only the resulting code can be used in the context of threads, whereas the technique shown earlier involves writing code with no explicit dependency on threading. By freeing your code of such dependencies, it becomes usable in other contexts that may or may not involve threads. For instance, one might be able to execute the code in a separate process using the multiprocessing module using code given below –
Code #7 :
import multiprocessingc = CountdownTask(5)p = multiprocessing.Process(target = c.run)p.start()...
Again, this only works if the CountdownTask class has been written in a manner that is neutral to the actual means of concurrency (threads, processes, etc).
python-utility
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": "\n12 Jun, 2019"
},
{
"code": null,
"e": 245,
"s": 28,
"text": "The threading library can be used to execute any Python callable in its own thread. To do this, create a Thread instance and supply the callable that you wish to execute as a target as shown in the code given below –"
},
{
"code": "# Code to execute in an independent threadimport time def countdown(n): while n > 0: print('T-minus', n) n -= 1 time.sleep(5) # Create and launch a threadfrom threading import Threadt = Thread(target = countdown, args =(10, ))t.start() ",
"e": 516,
"s": 245,
"text": null
},
{
"code": null,
"e": 973,
"s": 516,
"text": "When a thread instance is created, it doesn’t start executing until its start() method (which invokes the target function with the arguments you supplied) is invoked. Threads are executed in their own system-level thread (e.g., a POSIX thread or Windows threads) that is fully managed by the host operating system. Once started, threads run independently until the target function returns. Code #2 : Querying a thread instance to see if it’s still running."
},
{
"code": "if t.is_alive(): print('Still running')else: print('Completed')",
"e": 1043,
"s": 973,
"text": null
},
{
"code": null,
"e": 1120,
"s": 1043,
"text": "One can also request to join with a thread, which waits for it to terminate."
},
{
"code": "t.join()",
"e": 1129,
"s": 1120,
"text": null
},
{
"code": null,
"e": 1303,
"s": 1129,
"text": "The interpreter remains running until all threads terminate. For long-running threads or background tasks that run forever, consider it making the thread daemonic. Code #3 :"
},
{
"code": "t = Thread(target = countdown, args =(10, ), daemon = True)t.start()",
"e": 1372,
"s": 1303,
"text": null
},
{
"code": null,
"e": 1943,
"s": 1372,
"text": "Daemonic threads can’t be joined. However, they are destroyed automatically when the main thread terminates. Beyond the two operations shown, there aren’t many other things to do with threads. For example, there are no operations to terminate a thread, signal a thread, adjust its scheduling, or perform any other high-level operations. To have these features, build them on their own. To be able to terminate threads, the thread must be programmed to poll forexit at selected points. For example, put your thread in a class such as the one mentioned in the code below –"
},
{
"code": null,
"e": 1984,
"s": 1943,
"text": "Code #4 : Putting the thread in a class."
},
{
"code": "class CountdownTask: def __init__(self): self._running = True def terminate(self): self._running = False def run(self, n): while self._running and n > 0: print('T-minus', n) n -= 1 time.sleep(5) c = CountdownTask()t = Thread(target = c.run, args =(10, ))t.start()...# Signal terminationc.terminate() # Wait for actual termination (if needed) t.join() ",
"e": 2388,
"s": 1984,
"text": null
},
{
"code": null,
"e": 2742,
"s": 2388,
"text": "Polling for thread termination can be tricky to coordinate if threads perform blocking operations such as I/O. For example, a thread blocked indefinitely on an I/O operation may never return to check if it’s been killed. To correctly deal with this case, thread needs to be carefully programmed to utilize timeout loops as shown in the code given below."
},
{
"code": null,
"e": 2752,
"s": 2742,
"text": "Code #5 :"
},
{
"code": "class IOTask: def terminate(self): self._running = False def run(self, sock): # sock is a socket # Set timeout period sock.settimeout(5) while self._running: # Perform a blocking I/O operation w/timeout try: data = sock.recv(8192) break except socket.timeout: continue # Continued processing ... # Terminated return",
"e": 3318,
"s": 2752,
"text": null
},
{
"code": null,
"e": 3891,
"s": 3318,
"text": "Due to a global interpreter lock (GIL), Python threads are restricted to an execution model that only allows one thread to execute in the interpreter at any given time. For this reason, Python threads should generally not be used for computationally intensive tasks where trying to achieve parallelism on multiple CPUs. They are much better suited for I/O handling and handling concurrent execution in code that performs blocking operations (e.g., waiting for I/O, waiting for results from a database, etc.). Code #6 : Threads defined via inheritance from the Thread class"
},
{
"code": "from threading import Thread class CountdownThread(Thread): def __init__(self, n): super().__init__() self.n = 0 def run(self): while self.n > 0: print('T-minus', self.n) self.n -= 1 time.sleep(5) c = CountdownThread(5)c.start()",
"e": 4179,
"s": 3891,
"text": null
},
{
"code": null,
"e": 4698,
"s": 4179,
"text": "Although this works, it introduces an extra dependency between the code and the threading library. That is, only the resulting code can be used in the context of threads, whereas the technique shown earlier involves writing code with no explicit dependency on threading. By freeing your code of such dependencies, it becomes usable in other contexts that may or may not involve threads. For instance, one might be able to execute the code in a separate process using the multiprocessing module using code given below –"
},
{
"code": null,
"e": 4708,
"s": 4698,
"text": "Code #7 :"
},
{
"code": "import multiprocessingc = CountdownTask(5)p = multiprocessing.Process(target = c.run)p.start()...",
"e": 4806,
"s": 4708,
"text": null
},
{
"code": null,
"e": 4963,
"s": 4806,
"text": "Again, this only works if the CountdownTask class has been written in a manner that is neutral to the actual means of concurrency (threads, processes, etc)."
},
{
"code": null,
"e": 4978,
"s": 4963,
"text": "python-utility"
},
{
"code": null,
"e": 4985,
"s": 4978,
"text": "Python"
},
{
"code": null,
"e": 5083,
"s": 4985,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5101,
"s": 5083,
"text": "Python Dictionary"
},
{
"code": null,
"e": 5143,
"s": 5101,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 5165,
"s": 5143,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 5200,
"s": 5165,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 5226,
"s": 5200,
"text": "Python String | replace()"
},
{
"code": null,
"e": 5258,
"s": 5226,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 5287,
"s": 5258,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 5317,
"s": 5287,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 5344,
"s": 5317,
"text": "Python Classes and Objects"
}
] |
Wand noise() function – Python | 04 Oct, 2021
The noise() function is an inbuilt function in the Python Wand ImageMagick library which is used to add noise to the image.
Syntax:
noise(noise_type, attenuate, channel)
Parameters: This function accepts three parameters as mentioned above and defined below:
noise_type: This parameter is used to store the noise type. Some of the available noise types are ‘undefined’, ‘uniform’, ‘gaussian’, ‘multiplicative_gaussian’, ‘impulse’, ‘laplacian’, ‘poisson’, ‘random’.
attenuate: This parameter stores the rate of distribution.
channel: This parameter stores the channel type as “green”, “yellow”, “red” etc.
Return Value: This function returns the Wand ImageMagick object.
Original Image:
Example 1:
Python3
# Import library from Imagefrom wand.image import Image # Import the imagewith Image(filename ='../geeksforgeeks.png') as image: # Clone the image in order to process with image.clone() as noise: # Invoke noise function with Channel "green" and noise poisson noise.noise("poisson", 2, "green") # Save the image noise.save(filename ='noise1.jpg')
Output:
Example 2:
Python3
# Import libraries from the wand from wand.image import Imagefrom wand.drawing import Drawingfrom wand.color import Color with Drawing() as draw: # Set Stroke color the circle to black draw.stroke_color = Color('black') # Set Width of the circle to 2 draw.stroke_width = 1 # Set the fill color to 'White (# FFFFFF)' draw.fill_color = Color('white') # Invoke Circle function with center at 50, 50 and radius 25 draw.circle((200, 200), # Center point (100, 100)) # Perimeter point # Set the font style draw.font = '../Helvetica.ttf' # Set the font size draw.font_size = 30 with Image(width = 400, height = 400, background = Color('# 45ff33')) as pic: # Set the text and its location draw.text(int(pic.width / 3), int(pic.height / 2), 'GeeksForGeeks !') # Draw the picture draw(pic) # Invoke noise function with channel "yellow" and noise as impulse pic.noise("impulse", 3, "yellow") # Save the image pic.save(filename ='noise2.jpg')
Output:
sweetyty
gabaa406
Image-Processing
Python-wand
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Create a directory in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Oct, 2021"
},
{
"code": null,
"e": 152,
"s": 28,
"text": "The noise() function is an inbuilt function in the Python Wand ImageMagick library which is used to add noise to the image."
},
{
"code": null,
"e": 161,
"s": 152,
"text": "Syntax: "
},
{
"code": null,
"e": 199,
"s": 161,
"text": "noise(noise_type, attenuate, channel)"
},
{
"code": null,
"e": 289,
"s": 199,
"text": "Parameters: This function accepts three parameters as mentioned above and defined below: "
},
{
"code": null,
"e": 495,
"s": 289,
"text": "noise_type: This parameter is used to store the noise type. Some of the available noise types are ‘undefined’, ‘uniform’, ‘gaussian’, ‘multiplicative_gaussian’, ‘impulse’, ‘laplacian’, ‘poisson’, ‘random’."
},
{
"code": null,
"e": 554,
"s": 495,
"text": "attenuate: This parameter stores the rate of distribution."
},
{
"code": null,
"e": 635,
"s": 554,
"text": "channel: This parameter stores the channel type as “green”, “yellow”, “red” etc."
},
{
"code": null,
"e": 700,
"s": 635,
"text": "Return Value: This function returns the Wand ImageMagick object."
},
{
"code": null,
"e": 718,
"s": 700,
"text": "Original Image: "
},
{
"code": null,
"e": 731,
"s": 718,
"text": "Example 1: "
},
{
"code": null,
"e": 739,
"s": 731,
"text": "Python3"
},
{
"code": "# Import library from Imagefrom wand.image import Image # Import the imagewith Image(filename ='../geeksforgeeks.png') as image: # Clone the image in order to process with image.clone() as noise: # Invoke noise function with Channel \"green\" and noise poisson noise.noise(\"poisson\", 2, \"green\") # Save the image noise.save(filename ='noise1.jpg')",
"e": 1119,
"s": 739,
"text": null
},
{
"code": null,
"e": 1128,
"s": 1119,
"text": "Output: "
},
{
"code": null,
"e": 1141,
"s": 1128,
"text": "Example 2: "
},
{
"code": null,
"e": 1149,
"s": 1141,
"text": "Python3"
},
{
"code": "# Import libraries from the wand from wand.image import Imagefrom wand.drawing import Drawingfrom wand.color import Color with Drawing() as draw: # Set Stroke color the circle to black draw.stroke_color = Color('black') # Set Width of the circle to 2 draw.stroke_width = 1 # Set the fill color to 'White (# FFFFFF)' draw.fill_color = Color('white') # Invoke Circle function with center at 50, 50 and radius 25 draw.circle((200, 200), # Center point (100, 100)) # Perimeter point # Set the font style draw.font = '../Helvetica.ttf' # Set the font size draw.font_size = 30 with Image(width = 400, height = 400, background = Color('# 45ff33')) as pic: # Set the text and its location draw.text(int(pic.width / 3), int(pic.height / 2), 'GeeksForGeeks !') # Draw the picture draw(pic) # Invoke noise function with channel \"yellow\" and noise as impulse pic.noise(\"impulse\", 3, \"yellow\") # Save the image pic.save(filename ='noise2.jpg')",
"e": 2196,
"s": 1149,
"text": null
},
{
"code": null,
"e": 2205,
"s": 2196,
"text": "Output: "
},
{
"code": null,
"e": 2216,
"s": 2207,
"text": "sweetyty"
},
{
"code": null,
"e": 2225,
"s": 2216,
"text": "gabaa406"
},
{
"code": null,
"e": 2242,
"s": 2225,
"text": "Image-Processing"
},
{
"code": null,
"e": 2254,
"s": 2242,
"text": "Python-wand"
},
{
"code": null,
"e": 2261,
"s": 2254,
"text": "Python"
},
{
"code": null,
"e": 2359,
"s": 2261,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2391,
"s": 2359,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2418,
"s": 2391,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2439,
"s": 2418,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2462,
"s": 2439,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2518,
"s": 2462,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2549,
"s": 2518,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2591,
"s": 2549,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2633,
"s": 2591,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2672,
"s": 2633,
"text": "Python | Get unique values from a list"
}
] |
Underscore.js _.extend() Function | 25 Nov, 2021
The _.extend() function is used to create a copy of all of the properties of the source objects over the destination object and return the destination object. The nested arrays or objects will be copied by using reference, not duplicated.
Syntax:
_.extend(destination, *sources)
Parameters: This function accept two parameters as mentioned above and described below:
destination: This parameter holds the destination object file.
sources: This parameter holds the source object file.
Return Value: It returns a copy all of the properties of the source objects over the destination object, and return the destination object.
Example 1:
<!DOCTYPE html><html> <head> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"> </script></head> <body> <script type="text/javascript"> var obj1 = { key1: 'Geeks', }; var obj2 = { key2: 'GeeksforGeeks', }; console.log(_.extend(obj1, obj2)); </script></body> </html>
Output:
Example 2:
<!DOCTYPE html><html> <head> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"> </script></head> <body> <script type="text/javascript"> var obj1 = { key1: 'Geeks', }; var obj2 = { key2: 'GeeksforGeeks', }; console.log(_.extend({ Company: 'GeeksforGeeks', Address: 'Noida' }, { Contact: '+91 9876543210', Email: '[email protected]' }, { Author: 'Ashok' })); </script></body> </html>
Output:
JavaScript - Underscore.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
How to append HTML code to a div using JavaScript ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Nov, 2021"
},
{
"code": null,
"e": 267,
"s": 28,
"text": "The _.extend() function is used to create a copy of all of the properties of the source objects over the destination object and return the destination object. The nested arrays or objects will be copied by using reference, not duplicated."
},
{
"code": null,
"e": 275,
"s": 267,
"text": "Syntax:"
},
{
"code": null,
"e": 307,
"s": 275,
"text": "_.extend(destination, *sources)"
},
{
"code": null,
"e": 395,
"s": 307,
"text": "Parameters: This function accept two parameters as mentioned above and described below:"
},
{
"code": null,
"e": 458,
"s": 395,
"text": "destination: This parameter holds the destination object file."
},
{
"code": null,
"e": 512,
"s": 458,
"text": "sources: This parameter holds the source object file."
},
{
"code": null,
"e": 652,
"s": 512,
"text": "Return Value: It returns a copy all of the properties of the source objects over the destination object, and return the destination object."
},
{
"code": null,
"e": 663,
"s": 652,
"text": "Example 1:"
},
{
"code": "<!DOCTYPE html><html> <head> <script type=\"text/javascript\" src=\"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\"> </script></head> <body> <script type=\"text/javascript\"> var obj1 = { key1: 'Geeks', }; var obj2 = { key2: 'GeeksforGeeks', }; console.log(_.extend(obj1, obj2)); </script></body> </html>",
"e": 1071,
"s": 663,
"text": null
},
{
"code": null,
"e": 1079,
"s": 1071,
"text": "Output:"
},
{
"code": null,
"e": 1090,
"s": 1079,
"text": "Example 2:"
},
{
"code": "<!DOCTYPE html><html> <head> <script type=\"text/javascript\" src=\"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\"> </script></head> <body> <script type=\"text/javascript\"> var obj1 = { key1: 'Geeks', }; var obj2 = { key2: 'GeeksforGeeks', }; console.log(_.extend({ Company: 'GeeksforGeeks', Address: 'Noida' }, { Contact: '+91 9876543210', Email: '[email protected]' }, { Author: 'Ashok' })); </script></body> </html>",
"e": 1684,
"s": 1090,
"text": null
},
{
"code": null,
"e": 1692,
"s": 1684,
"text": "Output:"
},
{
"code": null,
"e": 1719,
"s": 1692,
"text": "JavaScript - Underscore.js"
},
{
"code": null,
"e": 1730,
"s": 1719,
"text": "JavaScript"
},
{
"code": null,
"e": 1747,
"s": 1730,
"text": "Web Technologies"
},
{
"code": null,
"e": 1845,
"s": 1747,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1906,
"s": 1845,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1978,
"s": 1906,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 2018,
"s": 1978,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2071,
"s": 2018,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 2123,
"s": 2071,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 2185,
"s": 2123,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2218,
"s": 2185,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2279,
"s": 2218,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2329,
"s": 2279,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Stream mapToLong() in Java with examples | 06 Dec, 2018
Stream mapToLong(ToLongFunction mapper) returns a LongStream consisting of the results of applying the given function to the elements of this stream.
Stream mapToLong(ToLongFunction mapper) is an intermediate operation. These operations are always lazy. Intermediate operations are invoked on a Stream instance and after they finish their processing, they give a Stream instance as output.
Syntax :
LongStream mapToLong(ToLongFunction<? super T> mapper)
Where, LongStream is a sequence of primitive
long-valued elements and T is the type
of stream elements. mapper is a stateless function
which is applied to each element and the function
returns the new stream.
Example 1 : mapToLong() function with operation of returning stream satisfying the given function.
// Java code for Stream mapToLong// (ToLongFunction mapper) to get a// LongStream by applying the given function// to the elements of this stream.import java.util.*; class GFG { // Driver code public static void main(String[] args) { System.out.println("The stream after applying " + "the function is : "); // Creating a list of Strings List<String> list = Arrays.asList("25", "225", "1000", "20", "15"); // Using Stream mapToLong(ToLongFunction mapper) // and displaying the corresponding LongStream list.stream().mapToLong(num -> Long.parseLong(num)) .filter(num -> Math.sqrt(num) / 5 == 3 ) .forEach(System.out::println); }}
Output :
The stream after applying the function is :
225
Example 2 : mapToLong() function with returning number of set-bits in string length.
// Java code for Stream mapToLong// (ToLongFunction mapper) to get a// LongStream by applying the given function// to the elements of this stream.import java.util.*; class GFG { // Driver code public static void main(String[] args) { // Creating a list of Strings List<String> list = Arrays.asList("Data Structures", "JAVA", "OOPS", "GeeksforGeeks", "Algorithms"); // Using Stream mapToLong(ToLongFunction mapper) // and displaying the corresponding LongStream // which contains the number of one-bits in // binary representation of String length list.stream().mapToLong(str -> Long.bitCount(str.length())) .forEach(System.out::println); }}
Output :
4
1
1
3
2
Java - util package
Java-Functions
java-stream
Java-Stream interface
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Dec, 2018"
},
{
"code": null,
"e": 178,
"s": 28,
"text": "Stream mapToLong(ToLongFunction mapper) returns a LongStream consisting of the results of applying the given function to the elements of this stream."
},
{
"code": null,
"e": 418,
"s": 178,
"text": "Stream mapToLong(ToLongFunction mapper) is an intermediate operation. These operations are always lazy. Intermediate operations are invoked on a Stream instance and after they finish their processing, they give a Stream instance as output."
},
{
"code": null,
"e": 427,
"s": 418,
"text": "Syntax :"
},
{
"code": null,
"e": 696,
"s": 427,
"text": "LongStream mapToLong(ToLongFunction<? super T> mapper)\n\nWhere, LongStream is a sequence of primitive \nlong-valued elements and T is the type \nof stream elements. mapper is a stateless function \nwhich is applied to each element and the function\nreturns the new stream.\n"
},
{
"code": null,
"e": 795,
"s": 696,
"text": "Example 1 : mapToLong() function with operation of returning stream satisfying the given function."
},
{
"code": "// Java code for Stream mapToLong// (ToLongFunction mapper) to get a// LongStream by applying the given function// to the elements of this stream.import java.util.*; class GFG { // Driver code public static void main(String[] args) { System.out.println(\"The stream after applying \" + \"the function is : \"); // Creating a list of Strings List<String> list = Arrays.asList(\"25\", \"225\", \"1000\", \"20\", \"15\"); // Using Stream mapToLong(ToLongFunction mapper) // and displaying the corresponding LongStream list.stream().mapToLong(num -> Long.parseLong(num)) .filter(num -> Math.sqrt(num) / 5 == 3 ) .forEach(System.out::println); }}",
"e": 1580,
"s": 795,
"text": null
},
{
"code": null,
"e": 1589,
"s": 1580,
"text": "Output :"
},
{
"code": null,
"e": 1639,
"s": 1589,
"text": "The stream after applying the function is : \n225\n"
},
{
"code": null,
"e": 1724,
"s": 1639,
"text": "Example 2 : mapToLong() function with returning number of set-bits in string length."
},
{
"code": "// Java code for Stream mapToLong// (ToLongFunction mapper) to get a// LongStream by applying the given function// to the elements of this stream.import java.util.*; class GFG { // Driver code public static void main(String[] args) { // Creating a list of Strings List<String> list = Arrays.asList(\"Data Structures\", \"JAVA\", \"OOPS\", \"GeeksforGeeks\", \"Algorithms\"); // Using Stream mapToLong(ToLongFunction mapper) // and displaying the corresponding LongStream // which contains the number of one-bits in // binary representation of String length list.stream().mapToLong(str -> Long.bitCount(str.length())) .forEach(System.out::println); }}",
"e": 2487,
"s": 1724,
"text": null
},
{
"code": null,
"e": 2496,
"s": 2487,
"text": "Output :"
},
{
"code": null,
"e": 2507,
"s": 2496,
"text": "4\n1\n1\n3\n2\n"
},
{
"code": null,
"e": 2527,
"s": 2507,
"text": "Java - util package"
},
{
"code": null,
"e": 2542,
"s": 2527,
"text": "Java-Functions"
},
{
"code": null,
"e": 2554,
"s": 2542,
"text": "java-stream"
},
{
"code": null,
"e": 2576,
"s": 2554,
"text": "Java-Stream interface"
},
{
"code": null,
"e": 2581,
"s": 2576,
"text": "Java"
},
{
"code": null,
"e": 2586,
"s": 2581,
"text": "Java"
}
] |
How to List All Tables in a Schema in Oracle Database? | 06 Jul, 2022
Prerequisite: Create Database in MS SQL Server
There are multiple ways to list all the tables present in a Schema in Oracle SQL. Such ways are depicted in the below article. For this article, we will be using the Microsoft SQL Server as our database.
Method 1: This method lists all the information regarding all the tables which are created by the user. The user clause is specified through the expression after WHERE keyword i.e. XTYPE=’U’ (U stands for user).
Query:
SELECT * FROM SYSOBJECTS
WHERE XTYPE='U';
Output:
Method 2: This method lists only selective information regarding all the tables which are created by the user. The user clause is specified through the expression after WHERE keyword i.e. XTYPE=’U’ (U stands for user). Here only the name(NAME), the creation date(CRDATE) and the last reference date(REFDATE) of the table are selected.
Query:
SELECT NAME,CRDATE,REFDATE
FROM SYSOBJECTS WHERE XTYPE='U';
Output:
Method 3: This method lists all the information regarding all the tables. Here, since we have not specified the XTYPE to USER, the query shall display all the tables irrespective of their creators.
Query:
SELECT * FROM SYSOBJECTS;
Output:
Method 4: This method lists only selective information regarding all the tables. Here, since we have not specified the XTYPE to USER, the query shall display all the tables irrespective of their creators. Here only the name(NAME), the creation date(CRDATE) and the last reference date(REFDATE) of the table are selected.
Query:
SELECT NAME,CRDATE,REFDATE
FROM SYSOBJECTS;
Output:
simmytarika5
Oracle
Picked
SQL-Server
SQL
Oracle
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
What is Temporary Table in SQL?
SQL | Sub queries in From Clause
SQL using Python
RANK() Function in SQL Server
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
SQL Query to Compare Two Dates
How to Write a SQL Query For a Specific Date Range and Date Time? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Jul, 2022"
},
{
"code": null,
"e": 75,
"s": 28,
"text": "Prerequisite: Create Database in MS SQL Server"
},
{
"code": null,
"e": 280,
"s": 75,
"text": "There are multiple ways to list all the tables present in a Schema in Oracle SQL. Such ways are depicted in the below article. For this article, we will be using the Microsoft SQL Server as our database. "
},
{
"code": null,
"e": 492,
"s": 280,
"text": "Method 1: This method lists all the information regarding all the tables which are created by the user. The user clause is specified through the expression after WHERE keyword i.e. XTYPE=’U’ (U stands for user)."
},
{
"code": null,
"e": 499,
"s": 492,
"text": "Query:"
},
{
"code": null,
"e": 542,
"s": 499,
"text": "SELECT * FROM SYSOBJECTS \nWHERE XTYPE='U';"
},
{
"code": null,
"e": 550,
"s": 542,
"text": "Output:"
},
{
"code": null,
"e": 885,
"s": 550,
"text": "Method 2: This method lists only selective information regarding all the tables which are created by the user. The user clause is specified through the expression after WHERE keyword i.e. XTYPE=’U’ (U stands for user). Here only the name(NAME), the creation date(CRDATE) and the last reference date(REFDATE) of the table are selected."
},
{
"code": null,
"e": 892,
"s": 885,
"text": "Query:"
},
{
"code": null,
"e": 953,
"s": 892,
"text": "SELECT NAME,CRDATE,REFDATE \nFROM SYSOBJECTS WHERE XTYPE='U';"
},
{
"code": null,
"e": 961,
"s": 953,
"text": "Output:"
},
{
"code": null,
"e": 1159,
"s": 961,
"text": "Method 3: This method lists all the information regarding all the tables. Here, since we have not specified the XTYPE to USER, the query shall display all the tables irrespective of their creators."
},
{
"code": null,
"e": 1166,
"s": 1159,
"text": "Query:"
},
{
"code": null,
"e": 1192,
"s": 1166,
"text": "SELECT * FROM SYSOBJECTS;"
},
{
"code": null,
"e": 1200,
"s": 1192,
"text": "Output:"
},
{
"code": null,
"e": 1521,
"s": 1200,
"text": "Method 4: This method lists only selective information regarding all the tables. Here, since we have not specified the XTYPE to USER, the query shall display all the tables irrespective of their creators. Here only the name(NAME), the creation date(CRDATE) and the last reference date(REFDATE) of the table are selected."
},
{
"code": null,
"e": 1528,
"s": 1521,
"text": "Query:"
},
{
"code": null,
"e": 1572,
"s": 1528,
"text": "SELECT NAME,CRDATE,REFDATE\nFROM SYSOBJECTS;"
},
{
"code": null,
"e": 1580,
"s": 1572,
"text": "Output:"
},
{
"code": null,
"e": 1593,
"s": 1580,
"text": "simmytarika5"
},
{
"code": null,
"e": 1600,
"s": 1593,
"text": "Oracle"
},
{
"code": null,
"e": 1607,
"s": 1600,
"text": "Picked"
},
{
"code": null,
"e": 1618,
"s": 1607,
"text": "SQL-Server"
},
{
"code": null,
"e": 1622,
"s": 1618,
"text": "SQL"
},
{
"code": null,
"e": 1629,
"s": 1622,
"text": "Oracle"
},
{
"code": null,
"e": 1633,
"s": 1629,
"text": "SQL"
},
{
"code": null,
"e": 1731,
"s": 1633,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1797,
"s": 1731,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 1821,
"s": 1797,
"text": "Window functions in SQL"
},
{
"code": null,
"e": 1853,
"s": 1821,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 1886,
"s": 1853,
"text": "SQL | Sub queries in From Clause"
},
{
"code": null,
"e": 1903,
"s": 1886,
"text": "SQL using Python"
},
{
"code": null,
"e": 1933,
"s": 1903,
"text": "RANK() Function in SQL Server"
},
{
"code": null,
"e": 2011,
"s": 1933,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 2047,
"s": 2011,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 2078,
"s": 2047,
"text": "SQL Query to Compare Two Dates"
}
] |
Python Regex | Program to accept string ending with alphanumeric character | 10 Jun, 2021
Prerequisite: Regular expression in PythonGiven a string, write a Python program to check whether the given string is ending with only alphanumeric character or Not.Examples:
Input: ankitrai326
Output: Accept
Input: ankirai@
Output: Discard
In this program, we are using search() method of re module. re.search() : This method either returns None (if the pattern doesn’t match), or re.MatchObject that contains information about the matching part of the string. This method stops after the first match, so this is best suited for testing a regular expression more than extracting data. Alphanumeric characters in the POSIX/C locale consist of either 36 case-insensitive symbols (A-Z and 0-9) or 62 case-sensitive characters (A-Z, a-z and 0-9).Let’s see the Python program for this :
Python3
# Python program to accept string ending# with only alphanumeric character.# import re module # re module provides support# for regular expressionsimport re # Make a regular expression to accept string# ending with alphanumeric characterregex = '[a-zA-z0-9]$' # Define a function for accepting string# ending with alphanumeric characterdef check(string): # pass the regular expression # and the string in search() method if(re.search(regex, string)): print("Accept") else: print("Discard") # Driver Codeif __name__ == '__main__' : # Enter the string string = "ankirai@" # calling run function check(string) string = "ankitrai326" check(string) string = "ankit." check(string) string = "geeksforgeeks" check(string)
Output :
Discard
Accept
Discard
Accept
surinderdawra388
Python Regex-programs
python-regex
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Jun, 2021"
},
{
"code": null,
"e": 205,
"s": 28,
"text": "Prerequisite: Regular expression in PythonGiven a string, write a Python program to check whether the given string is ending with only alphanumeric character or Not.Examples: "
},
{
"code": null,
"e": 272,
"s": 205,
"text": "Input: ankitrai326\nOutput: Accept\n\nInput: ankirai@\nOutput: Discard"
},
{
"code": null,
"e": 816,
"s": 272,
"text": "In this program, we are using search() method of re module. re.search() : This method either returns None (if the pattern doesn’t match), or re.MatchObject that contains information about the matching part of the string. This method stops after the first match, so this is best suited for testing a regular expression more than extracting data. Alphanumeric characters in the POSIX/C locale consist of either 36 case-insensitive symbols (A-Z and 0-9) or 62 case-sensitive characters (A-Z, a-z and 0-9).Let’s see the Python program for this : "
},
{
"code": null,
"e": 824,
"s": 816,
"text": "Python3"
},
{
"code": "# Python program to accept string ending# with only alphanumeric character.# import re module # re module provides support# for regular expressionsimport re # Make a regular expression to accept string# ending with alphanumeric characterregex = '[a-zA-z0-9]$' # Define a function for accepting string# ending with alphanumeric characterdef check(string): # pass the regular expression # and the string in search() method if(re.search(regex, string)): print(\"Accept\") else: print(\"Discard\") # Driver Codeif __name__ == '__main__' : # Enter the string string = \"ankirai@\" # calling run function check(string) string = \"ankitrai326\" check(string) string = \"ankit.\" check(string) string = \"geeksforgeeks\" check(string)",
"e": 1629,
"s": 824,
"text": null
},
{
"code": null,
"e": 1640,
"s": 1629,
"text": "Output : "
},
{
"code": null,
"e": 1670,
"s": 1640,
"text": "Discard\nAccept\nDiscard\nAccept"
},
{
"code": null,
"e": 1689,
"s": 1672,
"text": "surinderdawra388"
},
{
"code": null,
"e": 1711,
"s": 1689,
"text": "Python Regex-programs"
},
{
"code": null,
"e": 1724,
"s": 1711,
"text": "python-regex"
},
{
"code": null,
"e": 1731,
"s": 1724,
"text": "Python"
},
{
"code": null,
"e": 1747,
"s": 1731,
"text": "Python Programs"
},
{
"code": null,
"e": 1845,
"s": 1747,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1863,
"s": 1845,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1905,
"s": 1863,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1927,
"s": 1905,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1953,
"s": 1927,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1985,
"s": 1953,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2028,
"s": 1985,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 2050,
"s": 2028,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2089,
"s": 2050,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2127,
"s": 2089,
"text": "Python | Convert a list to dictionary"
}
] |
How to Create Background Service in Android? | Before getting into example, we should know what service is in android. Service is going to do back ground operation without interact with UI and it works even after activity destroy.
This example demonstrate about how to Create Background Service in Android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:app = "http://schemas.android.com/apk/res-auto"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity">
<TextView
android:id = "@+id/text"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "Start Service"
android:textSize = "25sp"
app:layout_constraintBottom_toBottomOf = "parent"
app:layout_constraintLeft_toLeftOf = "parent"
app:layout_constraintRight_toRightOf = "parent"
app:layout_constraintTop_toTopOf = "parent" />
</android.support.constraint.ConstraintLayout>
In the above code, we have taken text view, when user click on text view, it will start service and stop service.
Step 3 − Add the following code to src/MainActivity.java
package com.example.andy.myapplication;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView text = findViewById(R.id.text);
text.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (text.getText().toString().equals("Started")) {
text.setText("Stoped");
stopService(new Intent(MainActivity.this,service.class));
} else {
text.setText("Started");
startService(new Intent(MainActivity.this,service.class));
}
}
});
}
}
In the above code to start and stop service. We have used intent and passed context and service class. Now create a service class in package folder as service.class and add the following code –
package com.example.andy.myapplication;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class service extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service started by user.", Toast.LENGTH_LONG).show();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service destroyed by user.", Toast.LENGTH_LONG).show();
}
}
Step 4 − Add the following code to manifest.xml
<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = "http://schemas.android.com/apk/res/android"
package = "com.example.andy.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>
<service android:name = ".service"/>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
In the above result is an initial screen, Click on Text view, it will start service as shown below –
In the above result, service is startd now click on text view, it will stop service as shown below -
Click here to download the project code | [
{
"code": null,
"e": 1371,
"s": 1187,
"text": "Before getting into example, we should know what service is in android. Service is going to do back ground operation without interact with UI and it works even after activity destroy."
},
{
"code": null,
"e": 1447,
"s": 1371,
"text": "This example demonstrate about how to Create Background Service in Android."
},
{
"code": null,
"e": 1576,
"s": 1447,
"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": 1641,
"s": 1576,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2482,
"s": 1641,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<android.support.constraint.ConstraintLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:app = \"http://schemas.android.com/apk/res-auto\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\">\n <TextView\n android:id = \"@+id/text\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\"\n android:text = \"Start Service\"\n android:textSize = \"25sp\"\n app:layout_constraintBottom_toBottomOf = \"parent\"\n app:layout_constraintLeft_toLeftOf = \"parent\"\n app:layout_constraintRight_toRightOf = \"parent\"\n app:layout_constraintTop_toTopOf = \"parent\" />\n</android.support.constraint.ConstraintLayout>"
},
{
"code": null,
"e": 2596,
"s": 2482,
"text": "In the above code, we have taken text view, when user click on text view, it will start service and stop service."
},
{
"code": null,
"e": 2653,
"s": 2596,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3615,
"s": 2653,
"text": "package com.example.andy.myapplication;\nimport android.content.Intent;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.util.Log;\nimport android.view.View;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n final TextView text = findViewById(R.id.text);\n text.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (text.getText().toString().equals(\"Started\")) {\n text.setText(\"Stoped\");\n stopService(new Intent(MainActivity.this,service.class));\n } else {\n text.setText(\"Started\");\n startService(new Intent(MainActivity.this,service.class));\n }\n }\n });\n }\n}"
},
{
"code": null,
"e": 3809,
"s": 3615,
"text": "In the above code to start and stop service. We have used intent and passed context and service class. Now create a service class in package folder as service.class and add the following code –"
},
{
"code": null,
"e": 4437,
"s": 3809,
"text": "package com.example.andy.myapplication;\nimport android.app.Service;\nimport android.content.Intent;\nimport android.os.IBinder;\nimport android.widget.Toast;\npublic class service extends Service {\n @Override\n public IBinder onBind(Intent intent) {\n return null;\n }\n @Override\n public int onStartCommand(Intent intent, int flags, int startId) {\n Toast.makeText(this, \"Service started by user.\", Toast.LENGTH_LONG).show();\n return START_STICKY;\n }\n @Override\n public void onDestroy() {\n super.onDestroy();\n Toast.makeText(this, \"Service destroyed by user.\", Toast.LENGTH_LONG).show();\n }\n}"
},
{
"code": null,
"e": 4485,
"s": 4437,
"text": "Step 4 − Add the following code to manifest.xml"
},
{
"code": null,
"e": 5246,
"s": 4485,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\"\n package = \"com.example.andy.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 <service android:name = \".service\"/>\n </application>\n</manifest>"
},
{
"code": null,
"e": 5593,
"s": 5246,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –"
},
{
"code": null,
"e": 5694,
"s": 5593,
"text": "In the above result is an initial screen, Click on Text view, it will start service as shown below –"
},
{
"code": null,
"e": 5795,
"s": 5694,
"text": "In the above result, service is startd now click on text view, it will stop service as shown below -"
},
{
"code": null,
"e": 5835,
"s": 5795,
"text": "Click here to download the project code"
}
] |
sympy.stats.Weibull() in Python | 08 Jun, 2020
With the help of sympy.stats.Weibull() method, we can get the continuous random variable which represents the Weibull distribution.
Syntax : sympy.stats.Weibull(name, alpha, beta)Where, alpha and beta are real number.
Return : Return the continuous random variable.
Example #1 :In this example we can see that by using sympy.stats.Weibull() method, we are able to get the continuous random variable representing Weibull distribution by using this method.
# Import sympy and Weibullfrom sympy.stats import Weibull, densityfrom sympy import Symbol, pprint z = Symbol("z")a = Symbol("a", positive = True)l = Symbol("l", positive = True) # Using sympy.stats.Weibull() methodX = Weibull("x", a, l)gfg = density(X)(z) pprint(gfg)
Output :
l/z\l – 1 -|-|/z\ \a/l*|-| *e\a/—————–a
Example #2 :
# Import sympy and Weibullfrom sympy.stats import Weibull, densityfrom sympy import Symbol, pprint z = 2a = 3l = 4 # Using sympy.stats.Weibull() methodX = Weibull("x", a, l)gfg = density(X)(z) pprint(gfg)
Output :
-16—-8132*e——–81
Python SymPy-Stats
SymPy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Jun, 2020"
},
{
"code": null,
"e": 160,
"s": 28,
"text": "With the help of sympy.stats.Weibull() method, we can get the continuous random variable which represents the Weibull distribution."
},
{
"code": null,
"e": 246,
"s": 160,
"text": "Syntax : sympy.stats.Weibull(name, alpha, beta)Where, alpha and beta are real number."
},
{
"code": null,
"e": 294,
"s": 246,
"text": "Return : Return the continuous random variable."
},
{
"code": null,
"e": 483,
"s": 294,
"text": "Example #1 :In this example we can see that by using sympy.stats.Weibull() method, we are able to get the continuous random variable representing Weibull distribution by using this method."
},
{
"code": "# Import sympy and Weibullfrom sympy.stats import Weibull, densityfrom sympy import Symbol, pprint z = Symbol(\"z\")a = Symbol(\"a\", positive = True)l = Symbol(\"l\", positive = True) # Using sympy.stats.Weibull() methodX = Weibull(\"x\", a, l)gfg = density(X)(z) pprint(gfg)",
"e": 755,
"s": 483,
"text": null
},
{
"code": null,
"e": 764,
"s": 755,
"text": "Output :"
},
{
"code": null,
"e": 804,
"s": 764,
"text": "l/z\\l – 1 -|-|/z\\ \\a/l*|-| *e\\a/—————–a"
},
{
"code": null,
"e": 817,
"s": 804,
"text": "Example #2 :"
},
{
"code": "# Import sympy and Weibullfrom sympy.stats import Weibull, densityfrom sympy import Symbol, pprint z = 2a = 3l = 4 # Using sympy.stats.Weibull() methodX = Weibull(\"x\", a, l)gfg = density(X)(z) pprint(gfg)",
"e": 1025,
"s": 817,
"text": null
},
{
"code": null,
"e": 1034,
"s": 1025,
"text": "Output :"
},
{
"code": null,
"e": 1051,
"s": 1034,
"text": "-16—-8132*e——–81"
},
{
"code": null,
"e": 1070,
"s": 1051,
"text": "Python SymPy-Stats"
},
{
"code": null,
"e": 1076,
"s": 1070,
"text": "SymPy"
},
{
"code": null,
"e": 1083,
"s": 1076,
"text": "Python"
},
{
"code": null,
"e": 1181,
"s": 1083,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1199,
"s": 1181,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1241,
"s": 1199,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1263,
"s": 1241,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1298,
"s": 1263,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1324,
"s": 1298,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1356,
"s": 1324,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1385,
"s": 1356,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1412,
"s": 1385,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1442,
"s": 1412,
"text": "Iterate over a list in Python"
}
] |
shutdown command in Linux with Examples | 27 May, 2019
The shutdown command in Linux is used to shutdown the system in a safe way. You can shutdown the machine immediately, or schedule a shutdown using 24 hour format.It brings the system down in a secure way. When the shutdown is initiated, all logged-in users and processes are notified that the system is going down, and no further logins are allowed.Only root user can execute shutdown command.
Syntax of shutdown Command
shutdown [OPTIONS] [TIME] [MESSAGE]
options – Shutdown options such as halt, power-off (the default option) or reboot the system.
time – The time argument specifies when to perform the shutdown process.
message – The message argument specifies a message which will be broadcast to all users.
Options-r : Requests that the system be rebooted after it has been brought down.-h : Requests that the system be either halted or powered off after it has been brought down, with the choice as to which left up to the system.-H : Requests that the system be halted after it has been brought down.-P : Requests that the system be powered off after it has been brought down.-c : Cancels a running shutdown. TIME is not specified with this option, the first argument is MESSAGE.-k : Only send out the warning messages and disable logins, do not actually bring the system down.
How to use shutdownIn it’s simplest form when used without any argument, shutdown will power off the machine.
sudo shutdown
How to shutdown the system at a specified timeThe time argument can have two different formats. It can be an absolute time in the format hh:mm and relative time in the format +m where m is the number of minutes from now.
The following example will schedule a system shutdown at 05 A.M:
sudo shutdown 05:00
The following example will schedule a system shutdown in 20 minutes from now:
sudo shutdown +20
How to shutdown the system immediatelyTo shutdown your system immediately you can use +0 or its alias now:
sudo shutdown now
How to broadcast a custom messageThe following command will shut down the system in 10 minutes from now and notify the users with message “System upgrade”:
sudo shutdown +10 "System upgrade"
It is important to mention that when specifying a custom wall message you must specify a time argument too.
How to halt your systemThis can be achieved using the -H option.
shutdown -H
Halting means stopping all CPUs and powering off also makes sure the main power is disconnected.
How to make shutdown power-off machineAlthough this is by default, you can still use the -P option to explicitly specify that you want shutdown to power off the system.
shutdown -P
How to reboot using shutdownFor reboot, the option is -r.
shutdown -r
You can also specify a time argument and a custom message:
shutdown -r +5 "Updating Your System"
The command above will reboot the system after 5 minutes and broadcast Updating Your System”How to cancel a scheduled shutdownIf you have scheduled a shutdown and you want to cancel it you can use the -c argument:
sudo shutdown -c
When canceling a scheduled shutdown, you cannot specify a time argument, but you can still broadcast a message that will be sent to all users.
sudo shutdown -c "Canceling the reboot"
linux-command
Linux-system-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
mv command in Linux with examples
chmod command in Linux with examples
nohup Command in Linux with Examples
Introduction to Linux Operating System
Basic Operators in Shell Scripting
Array Basics in Shell Scripting | Set 1 | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 May, 2019"
},
{
"code": null,
"e": 422,
"s": 28,
"text": "The shutdown command in Linux is used to shutdown the system in a safe way. You can shutdown the machine immediately, or schedule a shutdown using 24 hour format.It brings the system down in a secure way. When the shutdown is initiated, all logged-in users and processes are notified that the system is going down, and no further logins are allowed.Only root user can execute shutdown command."
},
{
"code": null,
"e": 449,
"s": 422,
"text": "Syntax of shutdown Command"
},
{
"code": null,
"e": 486,
"s": 449,
"text": "shutdown [OPTIONS] [TIME] [MESSAGE]\n"
},
{
"code": null,
"e": 580,
"s": 486,
"text": "options – Shutdown options such as halt, power-off (the default option) or reboot the system."
},
{
"code": null,
"e": 653,
"s": 580,
"text": "time – The time argument specifies when to perform the shutdown process."
},
{
"code": null,
"e": 742,
"s": 653,
"text": "message – The message argument specifies a message which will be broadcast to all users."
},
{
"code": null,
"e": 1315,
"s": 742,
"text": "Options-r : Requests that the system be rebooted after it has been brought down.-h : Requests that the system be either halted or powered off after it has been brought down, with the choice as to which left up to the system.-H : Requests that the system be halted after it has been brought down.-P : Requests that the system be powered off after it has been brought down.-c : Cancels a running shutdown. TIME is not specified with this option, the first argument is MESSAGE.-k : Only send out the warning messages and disable logins, do not actually bring the system down."
},
{
"code": null,
"e": 1425,
"s": 1315,
"text": "How to use shutdownIn it’s simplest form when used without any argument, shutdown will power off the machine."
},
{
"code": null,
"e": 1440,
"s": 1425,
"text": "sudo shutdown\n"
},
{
"code": null,
"e": 1661,
"s": 1440,
"text": "How to shutdown the system at a specified timeThe time argument can have two different formats. It can be an absolute time in the format hh:mm and relative time in the format +m where m is the number of minutes from now."
},
{
"code": null,
"e": 1726,
"s": 1661,
"text": "The following example will schedule a system shutdown at 05 A.M:"
},
{
"code": null,
"e": 1747,
"s": 1726,
"text": "sudo shutdown 05:00\n"
},
{
"code": null,
"e": 1825,
"s": 1747,
"text": "The following example will schedule a system shutdown in 20 minutes from now:"
},
{
"code": null,
"e": 1843,
"s": 1825,
"text": "sudo shutdown +20"
},
{
"code": null,
"e": 1950,
"s": 1843,
"text": "How to shutdown the system immediatelyTo shutdown your system immediately you can use +0 or its alias now:"
},
{
"code": null,
"e": 1969,
"s": 1950,
"text": "sudo shutdown now\n"
},
{
"code": null,
"e": 2125,
"s": 1969,
"text": "How to broadcast a custom messageThe following command will shut down the system in 10 minutes from now and notify the users with message “System upgrade”:"
},
{
"code": null,
"e": 2161,
"s": 2125,
"text": "sudo shutdown +10 \"System upgrade\"\n"
},
{
"code": null,
"e": 2269,
"s": 2161,
"text": "It is important to mention that when specifying a custom wall message you must specify a time argument too."
},
{
"code": null,
"e": 2334,
"s": 2269,
"text": "How to halt your systemThis can be achieved using the -H option."
},
{
"code": null,
"e": 2347,
"s": 2334,
"text": "shutdown -H\n"
},
{
"code": null,
"e": 2444,
"s": 2347,
"text": "Halting means stopping all CPUs and powering off also makes sure the main power is disconnected."
},
{
"code": null,
"e": 2613,
"s": 2444,
"text": "How to make shutdown power-off machineAlthough this is by default, you can still use the -P option to explicitly specify that you want shutdown to power off the system."
},
{
"code": null,
"e": 2626,
"s": 2613,
"text": "shutdown -P\n"
},
{
"code": null,
"e": 2684,
"s": 2626,
"text": "How to reboot using shutdownFor reboot, the option is -r."
},
{
"code": null,
"e": 2697,
"s": 2684,
"text": "shutdown -r\n"
},
{
"code": null,
"e": 2756,
"s": 2697,
"text": "You can also specify a time argument and a custom message:"
},
{
"code": null,
"e": 2795,
"s": 2756,
"text": "shutdown -r +5 \"Updating Your System\"\n"
},
{
"code": null,
"e": 3009,
"s": 2795,
"text": "The command above will reboot the system after 5 minutes and broadcast Updating Your System”How to cancel a scheduled shutdownIf you have scheduled a shutdown and you want to cancel it you can use the -c argument:"
},
{
"code": null,
"e": 3027,
"s": 3009,
"text": "sudo shutdown -c\n"
},
{
"code": null,
"e": 3170,
"s": 3027,
"text": "When canceling a scheduled shutdown, you cannot specify a time argument, but you can still broadcast a message that will be sent to all users."
},
{
"code": null,
"e": 3211,
"s": 3170,
"text": "sudo shutdown -c \"Canceling the reboot\"\n"
},
{
"code": null,
"e": 3225,
"s": 3211,
"text": "linux-command"
},
{
"code": null,
"e": 3247,
"s": 3225,
"text": "Linux-system-commands"
},
{
"code": null,
"e": 3254,
"s": 3247,
"text": "Picked"
},
{
"code": null,
"e": 3265,
"s": 3254,
"text": "Linux-Unix"
},
{
"code": null,
"e": 3363,
"s": 3265,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3389,
"s": 3363,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 3424,
"s": 3389,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 3461,
"s": 3424,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 3490,
"s": 3461,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 3524,
"s": 3490,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 3561,
"s": 3524,
"text": "chmod command in Linux with examples"
},
{
"code": null,
"e": 3598,
"s": 3561,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 3637,
"s": 3598,
"text": "Introduction to Linux Operating System"
},
{
"code": null,
"e": 3672,
"s": 3637,
"text": "Basic Operators in Shell Scripting"
}
] |
Express.js | app.put() Function | 10 Jun, 2020
The app.put() function routes the HTTP PUT requests to the specified path with the specified callback functions.
Syntax:
app.put(path, callback [, callback ...])
Arguments:
Path: The path for which the middleware function is invoked and can be any of:A string representing a path.A path pattern.A regular expression pattern to match paths.An array of combinations of any of the above.Callback: Callback functions can be:A middleware function.A series of middleware functions (separated by commas).An array of middleware functions.A combination of all of the above.
Path: The path for which the middleware function is invoked and can be any of:A string representing a path.A path pattern.A regular expression pattern to match paths.An array of combinations of any of the above.
A string representing a path.
A path pattern.
A regular expression pattern to match paths.
An array of combinations of any of the above.
Callback: Callback functions can be:A middleware function.A series of middleware functions (separated by commas).An array of middleware functions.A combination of all of the above.
A middleware function.
A series of middleware functions (separated by commas).
An array of middleware functions.
A combination of all of the above.
Installation of express module:
You can visit the link to Install express module. You can install this package by using this command.npm install expressAfter installing express module, you can check your express version in command prompt using the command.npm version expressAfter that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js
You can visit the link to Install express module. You can install this package by using this command.npm install express
npm install express
After installing express module, you can check your express version in command prompt using the command.npm version express
npm version express
After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js
node index.js
Filename: index.js
var express = require('express');var app = express();var PORT = 3000; app.put('/', (req, res) => { res.send("PUT Request Called")}) app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);});
Steps to run the program:
The project structure will look like this:Make sure you have installed express module using following command:npm install expressRun index.js file using below command:node index.jsOutput:Server listening on PORT 3000
Now make PUT request to http://localhost:3000/ and you will get the following output:PUT Request Called
The project structure will look like this:
Make sure you have installed express module using following command:npm install express
npm install express
Run index.js file using below command:node index.jsOutput:Server listening on PORT 3000
node index.js
Output:
Server listening on PORT 3000
Now make PUT request to http://localhost:3000/ and you will get the following output:PUT Request Called
PUT Request Called
So this is how you can use the express app.put() function which routes HTTP PUT requests to the specified path with the specified callback functions.
Express.js
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": "\n10 Jun, 2020"
},
{
"code": null,
"e": 141,
"s": 28,
"text": "The app.put() function routes the HTTP PUT requests to the specified path with the specified callback functions."
},
{
"code": null,
"e": 149,
"s": 141,
"text": "Syntax:"
},
{
"code": null,
"e": 190,
"s": 149,
"text": "app.put(path, callback [, callback ...])"
},
{
"code": null,
"e": 201,
"s": 190,
"text": "Arguments:"
},
{
"code": null,
"e": 593,
"s": 201,
"text": "Path: The path for which the middleware function is invoked and can be any of:A string representing a path.A path pattern.A regular expression pattern to match paths.An array of combinations of any of the above.Callback: Callback functions can be:A middleware function.A series of middleware functions (separated by commas).An array of middleware functions.A combination of all of the above."
},
{
"code": null,
"e": 805,
"s": 593,
"text": "Path: The path for which the middleware function is invoked and can be any of:A string representing a path.A path pattern.A regular expression pattern to match paths.An array of combinations of any of the above."
},
{
"code": null,
"e": 835,
"s": 805,
"text": "A string representing a path."
},
{
"code": null,
"e": 851,
"s": 835,
"text": "A path pattern."
},
{
"code": null,
"e": 896,
"s": 851,
"text": "A regular expression pattern to match paths."
},
{
"code": null,
"e": 942,
"s": 896,
"text": "An array of combinations of any of the above."
},
{
"code": null,
"e": 1123,
"s": 942,
"text": "Callback: Callback functions can be:A middleware function.A series of middleware functions (separated by commas).An array of middleware functions.A combination of all of the above."
},
{
"code": null,
"e": 1146,
"s": 1123,
"text": "A middleware function."
},
{
"code": null,
"e": 1202,
"s": 1146,
"text": "A series of middleware functions (separated by commas)."
},
{
"code": null,
"e": 1236,
"s": 1202,
"text": "An array of middleware functions."
},
{
"code": null,
"e": 1271,
"s": 1236,
"text": "A combination of all of the above."
},
{
"code": null,
"e": 1303,
"s": 1271,
"text": "Installation of express module:"
},
{
"code": null,
"e": 1694,
"s": 1303,
"text": "You can visit the link to Install express module. You can install this package by using this command.npm install expressAfter installing express module, you can check your express version in command prompt using the command.npm version expressAfter that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js"
},
{
"code": null,
"e": 1815,
"s": 1694,
"text": "You can visit the link to Install express module. You can install this package by using this command.npm install express"
},
{
"code": null,
"e": 1835,
"s": 1815,
"text": "npm install express"
},
{
"code": null,
"e": 1959,
"s": 1835,
"text": "After installing express module, you can check your express version in command prompt using the command.npm version express"
},
{
"code": null,
"e": 1979,
"s": 1959,
"text": "npm version express"
},
{
"code": null,
"e": 2127,
"s": 1979,
"text": "After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js"
},
{
"code": null,
"e": 2141,
"s": 2127,
"text": "node index.js"
},
{
"code": null,
"e": 2160,
"s": 2141,
"text": "Filename: index.js"
},
{
"code": "var express = require('express');var app = express();var PORT = 3000; app.put('/', (req, res) => { res.send(\"PUT Request Called\")}) app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);}); ",
"e": 2411,
"s": 2160,
"text": null
},
{
"code": null,
"e": 2437,
"s": 2411,
"text": "Steps to run the program:"
},
{
"code": null,
"e": 2758,
"s": 2437,
"text": "The project structure will look like this:Make sure you have installed express module using following command:npm install expressRun index.js file using below command:node index.jsOutput:Server listening on PORT 3000\nNow make PUT request to http://localhost:3000/ and you will get the following output:PUT Request Called"
},
{
"code": null,
"e": 2801,
"s": 2758,
"text": "The project structure will look like this:"
},
{
"code": null,
"e": 2889,
"s": 2801,
"text": "Make sure you have installed express module using following command:npm install express"
},
{
"code": null,
"e": 2909,
"s": 2889,
"text": "npm install express"
},
{
"code": null,
"e": 2998,
"s": 2909,
"text": "Run index.js file using below command:node index.jsOutput:Server listening on PORT 3000\n"
},
{
"code": null,
"e": 3012,
"s": 2998,
"text": "node index.js"
},
{
"code": null,
"e": 3020,
"s": 3012,
"text": "Output:"
},
{
"code": null,
"e": 3051,
"s": 3020,
"text": "Server listening on PORT 3000\n"
},
{
"code": null,
"e": 3155,
"s": 3051,
"text": "Now make PUT request to http://localhost:3000/ and you will get the following output:PUT Request Called"
},
{
"code": null,
"e": 3174,
"s": 3155,
"text": "PUT Request Called"
},
{
"code": null,
"e": 3324,
"s": 3174,
"text": "So this is how you can use the express app.put() function which routes HTTP PUT requests to the specified path with the specified callback functions."
},
{
"code": null,
"e": 3335,
"s": 3324,
"text": "Express.js"
},
{
"code": null,
"e": 3343,
"s": 3335,
"text": "Node.js"
},
{
"code": null,
"e": 3360,
"s": 3343,
"text": "Web Technologies"
}
] |
Optimal Page Replacement Algorithm | 07 May, 2022
Prerequisite: Page Replacement Algorithms
In operating systems, whenever a new page is referred and not present in memory, page fault occurs and Operating System replaces one of the existing pages with newly needed page. Different page replacement algorithms suggest different ways to decide which page to replace. The target for all algorithms is to reduce number of page faults. In this algorithm, OS replaces the page that will not be used for the longest period of time in future. Examples :
Input : Number of frames, fn = 3
Reference String, pg[] = {7, 0, 1, 2,
0, 3, 0, 4, 2, 3, 0, 3, 2, 1,
2, 0, 1, 7, 0, 1};
Output : No. of hits = 11
No. of misses = 9
Input : Number of frames, fn = 4
Reference String, pg[] = {7, 0, 1, 2,
0, 3, 0, 4, 2, 3, 0, 3, 2};
Output : No. of hits = 7
No. of misses = 6
The idea is simple, for every reference we do following :
If referred page is already present, increment hit count.If not present, find if a page that is never referenced in future. If such a page exists, replace this page with new page. If no such page exists, find a page that is referenced farthest in future. Replace this page with new page.
If referred page is already present, increment hit count.
If not present, find if a page that is never referenced in future. If such a page exists, replace this page with new page. If no such page exists, find a page that is referenced farthest in future. Replace this page with new page.
CPP
Java
// CPP program to demonstrate optimal page// replacement algorithm.#include <bits/stdc++.h>using namespace std; // Function to check whether a page exists// in a frame or notbool search(int key, vector<int>& fr){ for (int i = 0; i < fr.size(); i++) if (fr[i] == key) return true; return false;} // Function to find the frame that will not be used// recently in future after given index in pg[0..pn-1]int predict(int pg[], vector<int>& fr, int pn, int index){ // Store the index of pages which are going // to be used recently in future int res = -1, farthest = index; for (int i = 0; i < fr.size(); i++) { int j; for (j = index; j < pn; j++) { if (fr[i] == pg[j]) { if (j > farthest) { farthest = j; res = i; } break; } } // If a page is never referenced in future, // return it. if (j == pn) return i; } // If all of the frames were not in future, // return any of them, we return 0. Otherwise // we return res. return (res == -1) ? 0 : res;} void optimalPage(int pg[], int pn, int fn){ // Create an array for given number of // frames and initialize it as empty. vector<int> fr; // Traverse through page reference array // and check for miss and hit. int hit = 0; for (int i = 0; i < pn; i++) { // Page found in a frame : HIT if (search(pg[i], fr)) { hit++; continue; } // Page not found in a frame : MISS // If there is space available in frames. if (fr.size() < fn) fr.push_back(pg[i]); // Find the page to be replaced. else { int j = predict(pg, fr, pn, i + 1); fr[j] = pg[i]; } } cout << "No. of hits = " << hit << endl; cout << "No. of misses = " << pn - hit << endl;} // Driver Functionint main(){ int pg[] = { 7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2 }; int pn = sizeof(pg) / sizeof(pg[0]); int fn = 4; optimalPage(pg, pn, fn); return 0;} // This code is contributed by Karandeep Singh
// Java program to demonstrate optimal page// replacement algorithm.import java.io.*;import java.util.*; class GFG { // Function to check whether a page exists // in a frame or not static boolean search(int key, int[] fr) { for (int i = 0; i < fr.length; i++) if (fr[i] == key) return true; return false; } // Function to find the frame that will not be used // recently in future after given index in pg[0..pn-1] static int predict(int pg[], int[] fr, int pn, int index) { // Store the index of pages which are going // to be used recently in future int res = -1, farthest = index; for (int i = 0; i < fr.length; i++) { int j; for (j = index; j < pn; j++) { if (fr[i] == pg[j]) { if (j > farthest) { farthest = j; res = i; } break; } } // If a page is never referenced in future, // return it. if (j == pn) return i; } // If all of the frames were not in future, // return any of them, we return 0. Otherwise // we return res. return (res == -1) ? 0 : res; } static void optimalPage(int pg[], int pn, int fn) { // Create an array for given number of // frames and initialize it as empty. int[] fr = new int[fn]; // Traverse through page reference array // and check for miss and hit. int hit = 0; int index = 0; for (int i = 0; i < pn; i++) { // Page found in a frame : HIT if (search(pg[i], fr)) { hit++; continue; } // Page not found in a frame : MISS // If there is space available in frames. if (index < fn) fr[index++] = pg[i]; // Find the page to be replaced. else { int j = predict(pg, fr, pn, i + 1); fr[j] = pg[i]; } } System.out.println("No. of hits = " + hit); System.out.println("No. of misses = " + (pn - hit)); } // driver function public static void main(String[] args) { int pg[] = { 7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2 }; int pn = pg.length; int fn = 4; optimalPage(pg, pn, fn); }}
Output:
No. of hits = 7
No. of misses = 6
The above implementation can optimized using hashing. We can use an unordered_set in place of vector so that search operation can be done in O(1) time.
Note that optimal page replacement algorithm is not practical as we cannot predict future. However it is used as a reference for other page replacement algorithms.
karandeep1234
gwnyqtutjvkiejlsxv
Greedy
Operating Systems
Operating Systems
Greedy
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Minimum Number of Platforms Required for a Railway/Bus Station
Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)
Policemen catch thieves
Dijkstra’s Algorithm for Adjacency List Representation | Greedy Algo-8
Minimize the maximum difference between the heights
Types of Operating Systems
Banker's Algorithm in Operating System
Disk Scheduling Algorithms
Introduction of Operating System - Set 1
Introduction of Deadlock in Operating System | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n07 May, 2022"
},
{
"code": null,
"e": 96,
"s": 54,
"text": "Prerequisite: Page Replacement Algorithms"
},
{
"code": null,
"e": 550,
"s": 96,
"text": "In operating systems, whenever a new page is referred and not present in memory, page fault occurs and Operating System replaces one of the existing pages with newly needed page. Different page replacement algorithms suggest different ways to decide which page to replace. The target for all algorithms is to reduce number of page faults. In this algorithm, OS replaces the page that will not be used for the longest period of time in future. Examples :"
},
{
"code": null,
"e": 942,
"s": 550,
"text": "Input : Number of frames, fn = 3\n Reference String, pg[] = {7, 0, 1, 2,\n 0, 3, 0, 4, 2, 3, 0, 3, 2, 1,\n 2, 0, 1, 7, 0, 1};\nOutput : No. of hits = 11 \n No. of misses = 9\n\nInput : Number of frames, fn = 4 \n Reference String, pg[] = {7, 0, 1, 2, \n 0, 3, 0, 4, 2, 3, 0, 3, 2};\nOutput : No. of hits = 7\n No. of misses = 6"
},
{
"code": null,
"e": 1000,
"s": 942,
"text": "The idea is simple, for every reference we do following :"
},
{
"code": null,
"e": 1288,
"s": 1000,
"text": "If referred page is already present, increment hit count.If not present, find if a page that is never referenced in future. If such a page exists, replace this page with new page. If no such page exists, find a page that is referenced farthest in future. Replace this page with new page."
},
{
"code": null,
"e": 1346,
"s": 1288,
"text": "If referred page is already present, increment hit count."
},
{
"code": null,
"e": 1577,
"s": 1346,
"text": "If not present, find if a page that is never referenced in future. If such a page exists, replace this page with new page. If no such page exists, find a page that is referenced farthest in future. Replace this page with new page."
},
{
"code": null,
"e": 1583,
"s": 1579,
"text": "CPP"
},
{
"code": null,
"e": 1588,
"s": 1583,
"text": "Java"
},
{
"code": "// CPP program to demonstrate optimal page// replacement algorithm.#include <bits/stdc++.h>using namespace std; // Function to check whether a page exists// in a frame or notbool search(int key, vector<int>& fr){ for (int i = 0; i < fr.size(); i++) if (fr[i] == key) return true; return false;} // Function to find the frame that will not be used// recently in future after given index in pg[0..pn-1]int predict(int pg[], vector<int>& fr, int pn, int index){ // Store the index of pages which are going // to be used recently in future int res = -1, farthest = index; for (int i = 0; i < fr.size(); i++) { int j; for (j = index; j < pn; j++) { if (fr[i] == pg[j]) { if (j > farthest) { farthest = j; res = i; } break; } } // If a page is never referenced in future, // return it. if (j == pn) return i; } // If all of the frames were not in future, // return any of them, we return 0. Otherwise // we return res. return (res == -1) ? 0 : res;} void optimalPage(int pg[], int pn, int fn){ // Create an array for given number of // frames and initialize it as empty. vector<int> fr; // Traverse through page reference array // and check for miss and hit. int hit = 0; for (int i = 0; i < pn; i++) { // Page found in a frame : HIT if (search(pg[i], fr)) { hit++; continue; } // Page not found in a frame : MISS // If there is space available in frames. if (fr.size() < fn) fr.push_back(pg[i]); // Find the page to be replaced. else { int j = predict(pg, fr, pn, i + 1); fr[j] = pg[i]; } } cout << \"No. of hits = \" << hit << endl; cout << \"No. of misses = \" << pn - hit << endl;} // Driver Functionint main(){ int pg[] = { 7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2 }; int pn = sizeof(pg) / sizeof(pg[0]); int fn = 4; optimalPage(pg, pn, fn); return 0;} // This code is contributed by Karandeep Singh",
"e": 3759,
"s": 1588,
"text": null
},
{
"code": "// Java program to demonstrate optimal page// replacement algorithm.import java.io.*;import java.util.*; class GFG { // Function to check whether a page exists // in a frame or not static boolean search(int key, int[] fr) { for (int i = 0; i < fr.length; i++) if (fr[i] == key) return true; return false; } // Function to find the frame that will not be used // recently in future after given index in pg[0..pn-1] static int predict(int pg[], int[] fr, int pn, int index) { // Store the index of pages which are going // to be used recently in future int res = -1, farthest = index; for (int i = 0; i < fr.length; i++) { int j; for (j = index; j < pn; j++) { if (fr[i] == pg[j]) { if (j > farthest) { farthest = j; res = i; } break; } } // If a page is never referenced in future, // return it. if (j == pn) return i; } // If all of the frames were not in future, // return any of them, we return 0. Otherwise // we return res. return (res == -1) ? 0 : res; } static void optimalPage(int pg[], int pn, int fn) { // Create an array for given number of // frames and initialize it as empty. int[] fr = new int[fn]; // Traverse through page reference array // and check for miss and hit. int hit = 0; int index = 0; for (int i = 0; i < pn; i++) { // Page found in a frame : HIT if (search(pg[i], fr)) { hit++; continue; } // Page not found in a frame : MISS // If there is space available in frames. if (index < fn) fr[index++] = pg[i]; // Find the page to be replaced. else { int j = predict(pg, fr, pn, i + 1); fr[j] = pg[i]; } } System.out.println(\"No. of hits = \" + hit); System.out.println(\"No. of misses = \" + (pn - hit)); } // driver function public static void main(String[] args) { int pg[] = { 7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2 }; int pn = pg.length; int fn = 4; optimalPage(pg, pn, fn); }}",
"e": 6253,
"s": 3759,
"text": null
},
{
"code": null,
"e": 6261,
"s": 6253,
"text": "Output:"
},
{
"code": null,
"e": 6295,
"s": 6261,
"text": "No. of hits = 7\nNo. of misses = 6"
},
{
"code": null,
"e": 6447,
"s": 6295,
"text": "The above implementation can optimized using hashing. We can use an unordered_set in place of vector so that search operation can be done in O(1) time."
},
{
"code": null,
"e": 6611,
"s": 6447,
"text": "Note that optimal page replacement algorithm is not practical as we cannot predict future. However it is used as a reference for other page replacement algorithms."
},
{
"code": null,
"e": 6625,
"s": 6611,
"text": "karandeep1234"
},
{
"code": null,
"e": 6644,
"s": 6625,
"text": "gwnyqtutjvkiejlsxv"
},
{
"code": null,
"e": 6651,
"s": 6644,
"text": "Greedy"
},
{
"code": null,
"e": 6669,
"s": 6651,
"text": "Operating Systems"
},
{
"code": null,
"e": 6687,
"s": 6669,
"text": "Operating Systems"
},
{
"code": null,
"e": 6694,
"s": 6687,
"text": "Greedy"
},
{
"code": null,
"e": 6792,
"s": 6694,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6855,
"s": 6792,
"text": "Minimum Number of Platforms Required for a Railway/Bus Station"
},
{
"code": null,
"e": 6936,
"s": 6855,
"text": "Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)"
},
{
"code": null,
"e": 6960,
"s": 6936,
"text": "Policemen catch thieves"
},
{
"code": null,
"e": 7031,
"s": 6960,
"text": "Dijkstra’s Algorithm for Adjacency List Representation | Greedy Algo-8"
},
{
"code": null,
"e": 7083,
"s": 7031,
"text": "Minimize the maximum difference between the heights"
},
{
"code": null,
"e": 7110,
"s": 7083,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 7149,
"s": 7110,
"text": "Banker's Algorithm in Operating System"
},
{
"code": null,
"e": 7176,
"s": 7149,
"text": "Disk Scheduling Algorithms"
},
{
"code": null,
"e": 7217,
"s": 7176,
"text": "Introduction of Operating System - Set 1"
}
] |
Output of Java program | Set 23 (Inheritance) | 05 May, 2022
Prerequisite: Inheritance in Java
1) What is the output of the following program?
Java
public class A extends B{ public static String sing() { return "fa"; } public static void main(String[] args) { A a = new A(); B b = new A(); System.out.println(a.sing() + " " + b.sing()); }}class B{ public static String sing() { return "la"; }}
Output:
fa la
Explanation:
The sing() method won’t be overridden because static methods did’nt support that so when b.sing() executed only sing() method present in Class B executed because b is object of type B; B b = new A(). if you want “fa fa” as the output then simply remove static in the method. Refer to this run-time polymorphism
2) What is the output of the following program?
Java
class Building{ Building() { System.out.println("Geek-Building"); } Building(String name) { this(); System.out.println("Geek-building: String Constructor" + name); }}public class House extends Building{ House() { System.out.println("Geek-House "); } House(String name) { this(); System.out.println("Geek-house: String Constructor" + name); } public static void main(String[] args) { new House("Geek"); }}
Output:
Geek-Building
Geek-House
Geek-house: String ConstructorGeek
Explanation:
Constructors call their superclass default constructors, which execute first, and constructors can be overloaded. First House constructor with one argument is called and flow shifts to no-arg constructor of house class due to this(). From here, due to superclass default constructor, no-arg constructor of building is called. Hence the order shown. For detail See – Constructors in Java
3) What is the output of the following program?
Java
class Base{ final public void show() { System.out.println("Base::show() called"); }}class Derived extends Base{ public void show() { System.out.println("Derived::show() called"); }}class Main{ public static void main(String[] args) { Base b = new Derived(); b.show(); }}
Output:
Compiler Error
Explanation:
Final methods cannot be overridden. For Detail see final keyword. However, if we remove the keyword final then, the output will be
Derived::show() called
4) What is the output of the following program?
Java
public class EH{ public static void main(String args[]) { int divisor =0; int dividend = 11; try { int result=dividend/divisor; System.out.println("The result is "+result); } catch(Exception e) { System.out.println("An exception occurred"); } catch(ArithmeticException ae) { System.out.println("Division by zero"); } finally { System.out.println("We are done!"); } }}
Output:
Compiler error
Explanation:
Exception ArithmeticException has already been caught is shown. Terminal Ordering of catch blocks is important The More specific/subclass (ArithmeticException) need to come earlier and more general/superclass (Exception) need to be written later. The program will execute correctly if the order of the Arithmetic exception and general exception is interchanged.
5) What is the output of the following program?
Java
abstract class Vibrate{ static String s = "-"; Vibrate() { s += "v"; }}public class Echo extends Vibrate{ Echo() { this(7); s += "e"; } Echo(int x) { s += "e2"; } public static void main(String[] args) { System.out.print("made " + s + " "); } static { Echo e = new Echo(); System.out.print("block " + s + " "); }}
Output:
block -ve2e made -ve2e
Explanation:
The static initialization block is the only place where an instance of Echo is created. Then the Echo instance is created, Echos no-arg constructor calls its 1-arg constructor, which then calls Vibrates constructor (which then secretly calls Objects constructor). At that point, the various constructors execute, starting with Objects constructor and working back down to Echos no-arg constructor. see static keyword
Quiz on Inheritance
kalpaj_12
simmytarika5
praveenkumar66118
surinderdawra388
Java-Output
Program Output
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Output of Java Programs | Set 12
Output of C programs | Set 59 (Loops and Control Statements)
unsigned specifier (%u) in C with Examples
How to show full column content in a PySpark Dataframe ?
Output of C++ Program | Set 2
Output of C programs | Set 31 (Pointers)
Output of C programs | Set 35 (Loops)
Output of C programs | Set 64 (Pointers)
Output of Java Programs | Set 14 (Constructors)
Output of C Programs | Set 5 | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n05 May, 2022"
},
{
"code": null,
"e": 87,
"s": 52,
"text": "Prerequisite: Inheritance in Java "
},
{
"code": null,
"e": 136,
"s": 87,
"text": "1) What is the output of the following program? "
},
{
"code": null,
"e": 141,
"s": 136,
"text": "Java"
},
{
"code": "public class A extends B{ public static String sing() { return \"fa\"; } public static void main(String[] args) { A a = new A(); B b = new A(); System.out.println(a.sing() + \" \" + b.sing()); }}class B{ public static String sing() { return \"la\"; }}",
"e": 445,
"s": 141,
"text": null
},
{
"code": null,
"e": 454,
"s": 445,
"text": "Output: "
},
{
"code": null,
"e": 461,
"s": 454,
"text": "fa la "
},
{
"code": null,
"e": 475,
"s": 461,
"text": "Explanation: "
},
{
"code": null,
"e": 787,
"s": 475,
"text": "The sing() method won’t be overridden because static methods did’nt support that so when b.sing() executed only sing() method present in Class B executed because b is object of type B; B b = new A(). if you want “fa fa” as the output then simply remove static in the method. Refer to this run-time polymorphism"
},
{
"code": null,
"e": 837,
"s": 787,
"text": "2) What is the output of the following program? "
},
{
"code": null,
"e": 842,
"s": 837,
"text": "Java"
},
{
"code": "class Building{ Building() { System.out.println(\"Geek-Building\"); } Building(String name) { this(); System.out.println(\"Geek-building: String Constructor\" + name); }}public class House extends Building{ House() { System.out.println(\"Geek-House \"); } House(String name) { this(); System.out.println(\"Geek-house: String Constructor\" + name); } public static void main(String[] args) { new House(\"Geek\"); }}",
"e": 1341,
"s": 842,
"text": null
},
{
"code": null,
"e": 1350,
"s": 1341,
"text": "Output: "
},
{
"code": null,
"e": 1411,
"s": 1350,
"text": "Geek-Building\nGeek-House \nGeek-house: String ConstructorGeek"
},
{
"code": null,
"e": 1425,
"s": 1411,
"text": "Explanation: "
},
{
"code": null,
"e": 1812,
"s": 1425,
"text": "Constructors call their superclass default constructors, which execute first, and constructors can be overloaded. First House constructor with one argument is called and flow shifts to no-arg constructor of house class due to this(). From here, due to superclass default constructor, no-arg constructor of building is called. Hence the order shown. For detail See – Constructors in Java"
},
{
"code": null,
"e": 1862,
"s": 1812,
"text": "3) What is the output of the following program? "
},
{
"code": null,
"e": 1867,
"s": 1862,
"text": "Java"
},
{
"code": "class Base{ final public void show() { System.out.println(\"Base::show() called\"); }}class Derived extends Base{ public void show() { System.out.println(\"Derived::show() called\"); }}class Main{ public static void main(String[] args) { Base b = new Derived(); b.show(); }}",
"e": 2193,
"s": 1867,
"text": null
},
{
"code": null,
"e": 2202,
"s": 2193,
"text": "Output: "
},
{
"code": null,
"e": 2218,
"s": 2202,
"text": "Compiler Error "
},
{
"code": null,
"e": 2232,
"s": 2218,
"text": "Explanation: "
},
{
"code": null,
"e": 2364,
"s": 2232,
"text": "Final methods cannot be overridden. For Detail see final keyword. However, if we remove the keyword final then, the output will be "
},
{
"code": null,
"e": 2387,
"s": 2364,
"text": "Derived::show() called"
},
{
"code": null,
"e": 2436,
"s": 2387,
"text": "4) What is the output of the following program? "
},
{
"code": null,
"e": 2441,
"s": 2436,
"text": "Java"
},
{
"code": "public class EH{ public static void main(String args[]) { int divisor =0; int dividend = 11; try { int result=dividend/divisor; System.out.println(\"The result is \"+result); } catch(Exception e) { System.out.println(\"An exception occurred\"); } catch(ArithmeticException ae) { System.out.println(\"Division by zero\"); } finally { System.out.println(\"We are done!\"); } }}",
"e": 2976,
"s": 2441,
"text": null
},
{
"code": null,
"e": 2985,
"s": 2976,
"text": "Output: "
},
{
"code": null,
"e": 3001,
"s": 2985,
"text": "Compiler error "
},
{
"code": null,
"e": 3015,
"s": 3001,
"text": "Explanation: "
},
{
"code": null,
"e": 3377,
"s": 3015,
"text": "Exception ArithmeticException has already been caught is shown. Terminal Ordering of catch blocks is important The More specific/subclass (ArithmeticException) need to come earlier and more general/superclass (Exception) need to be written later. The program will execute correctly if the order of the Arithmetic exception and general exception is interchanged."
},
{
"code": null,
"e": 3427,
"s": 3377,
"text": "5) What is the output of the following program? "
},
{
"code": null,
"e": 3432,
"s": 3427,
"text": "Java"
},
{
"code": "abstract class Vibrate{ static String s = \"-\"; Vibrate() { s += \"v\"; }}public class Echo extends Vibrate{ Echo() { this(7); s += \"e\"; } Echo(int x) { s += \"e2\"; } public static void main(String[] args) { System.out.print(\"made \" + s + \" \"); } static { Echo e = new Echo(); System.out.print(\"block \" + s + \" \"); }}",
"e": 3844,
"s": 3432,
"text": null
},
{
"code": null,
"e": 3853,
"s": 3844,
"text": "Output: "
},
{
"code": null,
"e": 3877,
"s": 3853,
"text": "block -ve2e made -ve2e "
},
{
"code": null,
"e": 3891,
"s": 3877,
"text": "Explanation: "
},
{
"code": null,
"e": 4308,
"s": 3891,
"text": "The static initialization block is the only place where an instance of Echo is created. Then the Echo instance is created, Echos no-arg constructor calls its 1-arg constructor, which then calls Vibrates constructor (which then secretly calls Objects constructor). At that point, the various constructors execute, starting with Objects constructor and working back down to Echos no-arg constructor. see static keyword"
},
{
"code": null,
"e": 4330,
"s": 4308,
"text": "Quiz on Inheritance "
},
{
"code": null,
"e": 4340,
"s": 4330,
"text": "kalpaj_12"
},
{
"code": null,
"e": 4353,
"s": 4340,
"text": "simmytarika5"
},
{
"code": null,
"e": 4371,
"s": 4353,
"text": "praveenkumar66118"
},
{
"code": null,
"e": 4388,
"s": 4371,
"text": "surinderdawra388"
},
{
"code": null,
"e": 4400,
"s": 4388,
"text": "Java-Output"
},
{
"code": null,
"e": 4415,
"s": 4400,
"text": "Program Output"
},
{
"code": null,
"e": 4513,
"s": 4415,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4546,
"s": 4513,
"text": "Output of Java Programs | Set 12"
},
{
"code": null,
"e": 4607,
"s": 4546,
"text": "Output of C programs | Set 59 (Loops and Control Statements)"
},
{
"code": null,
"e": 4650,
"s": 4607,
"text": "unsigned specifier (%u) in C with Examples"
},
{
"code": null,
"e": 4707,
"s": 4650,
"text": "How to show full column content in a PySpark Dataframe ?"
},
{
"code": null,
"e": 4737,
"s": 4707,
"text": "Output of C++ Program | Set 2"
},
{
"code": null,
"e": 4778,
"s": 4737,
"text": "Output of C programs | Set 31 (Pointers)"
},
{
"code": null,
"e": 4816,
"s": 4778,
"text": "Output of C programs | Set 35 (Loops)"
},
{
"code": null,
"e": 4857,
"s": 4816,
"text": "Output of C programs | Set 64 (Pointers)"
},
{
"code": null,
"e": 4905,
"s": 4857,
"text": "Output of Java Programs | Set 14 (Constructors)"
}
] |
ConcurrentModificationException while using Iterator in Java | 21 Apr, 2021
ConcurrentModificationException has thrown by methods that have detected concurrent modification of an object when such modification is not permissible. If a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this ConcurrentModificationException. Here we will be understanding this exception with an example of why it occurs and how changes are made simultaneously which is the root cause for this exception. In the later part, we will understand how to fix it up.
Example 1: ConcurrentModificationException
Java
// Java Program to ConcurrentModificationException while// using Iterator // Importing ArrayList and Iterator classes from java.util// packageimport java.util.ArrayList;import java.util.Iterator; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an object of ArrayList class // Declaring object of Integer type ArrayList<Integer> list = new ArrayList<>(); // Adding custom integer elements to the object list.add(1); list.add(2); list.add(3); list.add(4); list.add(5); // Iterating over object elements using iterator Iterator<Integer> iterator = list.iterator(); // Condition check // It holds true till there is single element // remainin in the List while (iterator.hasNext()) { // Rolling over to next element using next() // method Integer value = iterator.next(); // Print the element value System.out.println("value: " + value); // If element equals certain value if (value.equals(2)) { // Display command for better readability System.out.println( "========================"); // Removing entered value in object System.out.println("removing value: " + value); // Making changes simultaneously System.out.println( "========================"); list.remove(value); } } }}
Output:
Output Explanation:
ConcurrentModificationException is thrown when the next() method is called as the iterator is iterating the List, and we are making modifications in it simultaneously. Now in order to avoid this exception so let us do discuss a way out of using iterator directly which is as follows:
Example 2: Resolving ConcurrentModificationException
Java
// Java Program to Avoid ConcurrentModificationException by// directly using Iterator // Importing ArrayList and Iterator classes// from java.util packageimport java.util.ArrayList;import java.util.Iterator; // Main classpublic class Main { // Mai driver method public static void main(String[] args) { // Creating an ArrayList object of integer type ArrayList<Integer> list = new ArrayList<>(); // Custom integer elements are added list.add(1); list.add(2); list.add(3); list.add(4); list.add(5); // Iterating directly over elements of object Iterator<Integer> iterator = list.iterator(); // Condition check // It holds true till there is single element // remaining in the List using hasNext() method while (iterator.hasNext()) { // Rolling over elements using next() method Integer value = iterator.next(); // print the values System.out.println("value: " + value); // If value equals certain integer element // entered Say it be 2 if (value.equals(2)) { // Display command only System.out.println( "========================"); // Removing the entered value System.out.println("removing value: " + value); // Display command only System.out.println( "========================"); // Removing current value in Collection // using remove() method iterator.remove(); } } }}
Output:
Output Explanation:
ConcurrentModificationException is not thrown because the remove() method does not cause a ConcurrentModificationException.
Java-Exceptions
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": "\n21 Apr, 2021"
},
{
"code": null,
"e": 573,
"s": 28,
"text": "ConcurrentModificationException has thrown by methods that have detected concurrent modification of an object when such modification is not permissible. If a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this ConcurrentModificationException. Here we will be understanding this exception with an example of why it occurs and how changes are made simultaneously which is the root cause for this exception. In the later part, we will understand how to fix it up."
},
{
"code": null,
"e": 616,
"s": 573,
"text": "Example 1: ConcurrentModificationException"
},
{
"code": null,
"e": 621,
"s": 616,
"text": "Java"
},
{
"code": "// Java Program to ConcurrentModificationException while// using Iterator // Importing ArrayList and Iterator classes from java.util// packageimport java.util.ArrayList;import java.util.Iterator; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an object of ArrayList class // Declaring object of Integer type ArrayList<Integer> list = new ArrayList<>(); // Adding custom integer elements to the object list.add(1); list.add(2); list.add(3); list.add(4); list.add(5); // Iterating over object elements using iterator Iterator<Integer> iterator = list.iterator(); // Condition check // It holds true till there is single element // remainin in the List while (iterator.hasNext()) { // Rolling over to next element using next() // method Integer value = iterator.next(); // Print the element value System.out.println(\"value: \" + value); // If element equals certain value if (value.equals(2)) { // Display command for better readability System.out.println( \"========================\"); // Removing entered value in object System.out.println(\"removing value: \" + value); // Making changes simultaneously System.out.println( \"========================\"); list.remove(value); } } }}",
"e": 2267,
"s": 621,
"text": null
},
{
"code": null,
"e": 2275,
"s": 2267,
"text": "Output:"
},
{
"code": null,
"e": 2295,
"s": 2275,
"text": "Output Explanation:"
},
{
"code": null,
"e": 2579,
"s": 2295,
"text": "ConcurrentModificationException is thrown when the next() method is called as the iterator is iterating the List, and we are making modifications in it simultaneously. Now in order to avoid this exception so let us do discuss a way out of using iterator directly which is as follows:"
},
{
"code": null,
"e": 2632,
"s": 2579,
"text": "Example 2: Resolving ConcurrentModificationException"
},
{
"code": null,
"e": 2637,
"s": 2632,
"text": "Java"
},
{
"code": "// Java Program to Avoid ConcurrentModificationException by// directly using Iterator // Importing ArrayList and Iterator classes// from java.util packageimport java.util.ArrayList;import java.util.Iterator; // Main classpublic class Main { // Mai driver method public static void main(String[] args) { // Creating an ArrayList object of integer type ArrayList<Integer> list = new ArrayList<>(); // Custom integer elements are added list.add(1); list.add(2); list.add(3); list.add(4); list.add(5); // Iterating directly over elements of object Iterator<Integer> iterator = list.iterator(); // Condition check // It holds true till there is single element // remaining in the List using hasNext() method while (iterator.hasNext()) { // Rolling over elements using next() method Integer value = iterator.next(); // print the values System.out.println(\"value: \" + value); // If value equals certain integer element // entered Say it be 2 if (value.equals(2)) { // Display command only System.out.println( \"========================\"); // Removing the entered value System.out.println(\"removing value: \" + value); // Display command only System.out.println( \"========================\"); // Removing current value in Collection // using remove() method iterator.remove(); } } }}",
"e": 4377,
"s": 2637,
"text": null
},
{
"code": null,
"e": 4385,
"s": 4377,
"text": "Output:"
},
{
"code": null,
"e": 4405,
"s": 4385,
"text": "Output Explanation:"
},
{
"code": null,
"e": 4530,
"s": 4405,
"text": "ConcurrentModificationException is not thrown because the remove() method does not cause a ConcurrentModificationException. "
},
{
"code": null,
"e": 4546,
"s": 4530,
"text": "Java-Exceptions"
},
{
"code": null,
"e": 4553,
"s": 4546,
"text": "Picked"
},
{
"code": null,
"e": 4558,
"s": 4553,
"text": "Java"
},
{
"code": null,
"e": 4563,
"s": 4558,
"text": "Java"
},
{
"code": null,
"e": 4661,
"s": 4563,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4676,
"s": 4661,
"text": "Stream In Java"
},
{
"code": null,
"e": 4697,
"s": 4676,
"text": "Introduction to Java"
},
{
"code": null,
"e": 4718,
"s": 4697,
"text": "Constructors in Java"
},
{
"code": null,
"e": 4737,
"s": 4718,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 4754,
"s": 4737,
"text": "Generics in Java"
},
{
"code": null,
"e": 4784,
"s": 4754,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 4810,
"s": 4784,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 4826,
"s": 4810,
"text": "Strings in Java"
},
{
"code": null,
"e": 4863,
"s": 4826,
"text": "Differences between JDK, JRE and JVM"
}
] |
Image Segmentation By Clustering | 18 Jul, 2021
Segmentation By clustering
It is a method to perform Image Segmentation of pixel-wise segmentation. In this type of segmentation, we try to cluster the pixels that are together. There are two approaches for performing the Segmentation by clustering.
Clustering by Merging
Clustering by Divisive
Clustering by merging or Agglomerative Clustering:
In this approach, we follow the bottom-up approach, which means we assign the pixel closest to the cluster. The algorithm for performing the agglomerative clustering as follows:
Take each point as a separate cluster.
For a given number of epochs or until clustering is satisfactory.Merge two clusters with the smallest inter-cluster distance (WCSS).
Merge two clusters with the smallest inter-cluster distance (WCSS).
Repeat the above step
The agglomerative clustering is represented by Dendrogram. It can be performed in 3 methods: by selecting the closest pair for merging, by selecting the farthest pair for merging, or by selecting the pair which is at an average distance (neither closest nor farthest). The dendrogram representing these types of clustering is below:
Nearest clustering
Average Clustering
Farthest Clustering
Clustering by division or Divisive splitting
In this approach, we follow the top-down approach, which means we assign the pixel closest to the cluster. The algorithm for performing the agglomerative clustering as follows:
Construct a single cluster containing all points.
For a given number of epochs or until clustering is satisfactory.Split the cluster into two clusters with the largest inter-cluster distance.
Split the cluster into two clusters with the largest inter-cluster distance.
Repeat the above steps.
In this article, we will be discussing how to perform the K-Means Clustering.
K-Means Clustering
K-means clustering is a very popular clustering algorithm which applied when we have a dataset with labels unknown. The goal is to find certain groups based on some kind of similarity in the data with the number of groups represented by K. This algorithm is generally used in areas like market segmentation, customer segmentation, etc. But, it can also be used to segment different objects in the images on the basis of the pixel values.
The algorithm for image segmentation works as follows:
First, we need to select the value of K in K-means clustering.Select a feature vector for every pixel (color values such as RGB value, texture etc.).Define a similarity measure b/w feature vectors such as Euclidean distance to measure the similarity b/w any two points/pixel.Apply K-means algorithm to the cluster centersApply connected component’s algorithm.Combine any component of size less than the threshold to an adjacent component that is similar to it until you can’t combine more.
First, we need to select the value of K in K-means clustering.
Select a feature vector for every pixel (color values such as RGB value, texture etc.).
Define a similarity measure b/w feature vectors such as Euclidean distance to measure the similarity b/w any two points/pixel.
Apply K-means algorithm to the cluster centers
Apply connected component’s algorithm.
Combine any component of size less than the threshold to an adjacent component that is similar to it until you can’t combine more.
Following are the steps for applying the K-means clustering algorithm:
Select K points and assign them one cluster center each.
Until the cluster center won’t change, perform the following steps:Allocate each point to the nearest cluster center and ensure that each cluster center has one point.Replace the cluster center with the mean of the points assigned to it.
Allocate each point to the nearest cluster center and ensure that each cluster center has one point.
Replace the cluster center with the mean of the points assigned to it.
End
For a certain class of clustering algorithms, there is a parameter commonly referred to as K that specifies the number of clusters to detect. We may have the predefined value of K, if we have domain knowledge about data that how many categories it contains. But, before calculating the optimal value of K, we first need to define the objective function for the above algorithm. The objective function can be given by:
Where j is the number of clusters, and i will be the points belong to the jth cluster. The above objective function is called within-cluster sum of square (WCSS) distance.
A good way to find the optimal value of K is to brute force a smaller range of values (1-10) and plot the graph of WCSS distance vs K. The point where the graph is sharply bent downward can be considered the optimal value of K. This method is called Elbow method.
For image segmentation, we plot the histogram of the image and try to find peaks, valleys in it. Then, we will perform the peakiness test on that histogram.
In this implementation, we will be performing Image Segmentation using K-Means clustering. We will be using OpenCV k-Means API to perform this clustering.
Python3
# importsimport numpy as npimport cv2 as cvimport matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = (12,50) # load imageimg = cv.imread('road.jpg')Z = img.reshape((-1,3))# convert to np.float32Z = np.float32(Z) # define stopping criteria, number of clusters(K) and apply kmeans()# TERM_CRITERIA_EPS : stop when the epsilon value is reached# TERM_CRITERIA_MAX_ITER: stop when Max iteration is reachedcriteria = (cv.TERM_CRITERIA_EPS + cv.TERM_CRITERIA_MAX_ITER, 10, 1.0) fig, ax = plt.subplots(10,2, sharey=True)for i in range(10): K = i+3 # apply K-means algorithm ret,label,center=cv.kmeans(Z,K,None,criteria,attempts = 10, cv.KMEANS_RANDOM_CENTERS) # Now convert back into uint8, and make original image center = np.uint8(center) res = center[label.flatten()] res2 = res.reshape((img.shape)) # plot the original image and K-means image ax[i, 1].imshow(res2) ax[i,1].set_title('K = %s Image'%K) ax[i, 0].imshow(img) ax[i,0].set_title('Original Image')
Image Segmentation for K=3,4,5
Image Segmentation for K=6,7,8
NYU slides
OpenCV K-means
Image-Processing
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Jul, 2021"
},
{
"code": null,
"e": 55,
"s": 28,
"text": "Segmentation By clustering"
},
{
"code": null,
"e": 278,
"s": 55,
"text": "It is a method to perform Image Segmentation of pixel-wise segmentation. In this type of segmentation, we try to cluster the pixels that are together. There are two approaches for performing the Segmentation by clustering."
},
{
"code": null,
"e": 300,
"s": 278,
"text": "Clustering by Merging"
},
{
"code": null,
"e": 323,
"s": 300,
"text": "Clustering by Divisive"
},
{
"code": null,
"e": 374,
"s": 323,
"text": "Clustering by merging or Agglomerative Clustering:"
},
{
"code": null,
"e": 552,
"s": 374,
"text": "In this approach, we follow the bottom-up approach, which means we assign the pixel closest to the cluster. The algorithm for performing the agglomerative clustering as follows:"
},
{
"code": null,
"e": 591,
"s": 552,
"text": "Take each point as a separate cluster."
},
{
"code": null,
"e": 724,
"s": 591,
"text": "For a given number of epochs or until clustering is satisfactory.Merge two clusters with the smallest inter-cluster distance (WCSS)."
},
{
"code": null,
"e": 792,
"s": 724,
"text": "Merge two clusters with the smallest inter-cluster distance (WCSS)."
},
{
"code": null,
"e": 814,
"s": 792,
"text": "Repeat the above step"
},
{
"code": null,
"e": 1147,
"s": 814,
"text": "The agglomerative clustering is represented by Dendrogram. It can be performed in 3 methods: by selecting the closest pair for merging, by selecting the farthest pair for merging, or by selecting the pair which is at an average distance (neither closest nor farthest). The dendrogram representing these types of clustering is below:"
},
{
"code": null,
"e": 1166,
"s": 1147,
"text": "Nearest clustering"
},
{
"code": null,
"e": 1185,
"s": 1166,
"text": "Average Clustering"
},
{
"code": null,
"e": 1205,
"s": 1185,
"text": "Farthest Clustering"
},
{
"code": null,
"e": 1250,
"s": 1205,
"text": "Clustering by division or Divisive splitting"
},
{
"code": null,
"e": 1427,
"s": 1250,
"text": "In this approach, we follow the top-down approach, which means we assign the pixel closest to the cluster. The algorithm for performing the agglomerative clustering as follows:"
},
{
"code": null,
"e": 1477,
"s": 1427,
"text": "Construct a single cluster containing all points."
},
{
"code": null,
"e": 1619,
"s": 1477,
"text": "For a given number of epochs or until clustering is satisfactory.Split the cluster into two clusters with the largest inter-cluster distance."
},
{
"code": null,
"e": 1696,
"s": 1619,
"text": "Split the cluster into two clusters with the largest inter-cluster distance."
},
{
"code": null,
"e": 1720,
"s": 1696,
"text": "Repeat the above steps."
},
{
"code": null,
"e": 1798,
"s": 1720,
"text": "In this article, we will be discussing how to perform the K-Means Clustering."
},
{
"code": null,
"e": 1817,
"s": 1798,
"text": "K-Means Clustering"
},
{
"code": null,
"e": 2255,
"s": 1817,
"text": "K-means clustering is a very popular clustering algorithm which applied when we have a dataset with labels unknown. The goal is to find certain groups based on some kind of similarity in the data with the number of groups represented by K. This algorithm is generally used in areas like market segmentation, customer segmentation, etc. But, it can also be used to segment different objects in the images on the basis of the pixel values."
},
{
"code": null,
"e": 2310,
"s": 2255,
"text": "The algorithm for image segmentation works as follows:"
},
{
"code": null,
"e": 2800,
"s": 2310,
"text": "First, we need to select the value of K in K-means clustering.Select a feature vector for every pixel (color values such as RGB value, texture etc.).Define a similarity measure b/w feature vectors such as Euclidean distance to measure the similarity b/w any two points/pixel.Apply K-means algorithm to the cluster centersApply connected component’s algorithm.Combine any component of size less than the threshold to an adjacent component that is similar to it until you can’t combine more."
},
{
"code": null,
"e": 2863,
"s": 2800,
"text": "First, we need to select the value of K in K-means clustering."
},
{
"code": null,
"e": 2951,
"s": 2863,
"text": "Select a feature vector for every pixel (color values such as RGB value, texture etc.)."
},
{
"code": null,
"e": 3078,
"s": 2951,
"text": "Define a similarity measure b/w feature vectors such as Euclidean distance to measure the similarity b/w any two points/pixel."
},
{
"code": null,
"e": 3125,
"s": 3078,
"text": "Apply K-means algorithm to the cluster centers"
},
{
"code": null,
"e": 3164,
"s": 3125,
"text": "Apply connected component’s algorithm."
},
{
"code": null,
"e": 3295,
"s": 3164,
"text": "Combine any component of size less than the threshold to an adjacent component that is similar to it until you can’t combine more."
},
{
"code": null,
"e": 3366,
"s": 3295,
"text": "Following are the steps for applying the K-means clustering algorithm:"
},
{
"code": null,
"e": 3423,
"s": 3366,
"text": "Select K points and assign them one cluster center each."
},
{
"code": null,
"e": 3661,
"s": 3423,
"text": "Until the cluster center won’t change, perform the following steps:Allocate each point to the nearest cluster center and ensure that each cluster center has one point.Replace the cluster center with the mean of the points assigned to it."
},
{
"code": null,
"e": 3762,
"s": 3661,
"text": "Allocate each point to the nearest cluster center and ensure that each cluster center has one point."
},
{
"code": null,
"e": 3833,
"s": 3762,
"text": "Replace the cluster center with the mean of the points assigned to it."
},
{
"code": null,
"e": 3837,
"s": 3833,
"text": "End"
},
{
"code": null,
"e": 4255,
"s": 3837,
"text": "For a certain class of clustering algorithms, there is a parameter commonly referred to as K that specifies the number of clusters to detect. We may have the predefined value of K, if we have domain knowledge about data that how many categories it contains. But, before calculating the optimal value of K, we first need to define the objective function for the above algorithm. The objective function can be given by:"
},
{
"code": null,
"e": 4427,
"s": 4255,
"text": "Where j is the number of clusters, and i will be the points belong to the jth cluster. The above objective function is called within-cluster sum of square (WCSS) distance."
},
{
"code": null,
"e": 4691,
"s": 4427,
"text": "A good way to find the optimal value of K is to brute force a smaller range of values (1-10) and plot the graph of WCSS distance vs K. The point where the graph is sharply bent downward can be considered the optimal value of K. This method is called Elbow method."
},
{
"code": null,
"e": 4848,
"s": 4691,
"text": "For image segmentation, we plot the histogram of the image and try to find peaks, valleys in it. Then, we will perform the peakiness test on that histogram."
},
{
"code": null,
"e": 5003,
"s": 4848,
"text": "In this implementation, we will be performing Image Segmentation using K-Means clustering. We will be using OpenCV k-Means API to perform this clustering."
},
{
"code": null,
"e": 5011,
"s": 5003,
"text": "Python3"
},
{
"code": "# importsimport numpy as npimport cv2 as cvimport matplotlib.pyplot as plt plt.rcParams[\"figure.figsize\"] = (12,50) # load imageimg = cv.imread('road.jpg')Z = img.reshape((-1,3))# convert to np.float32Z = np.float32(Z) # define stopping criteria, number of clusters(K) and apply kmeans()# TERM_CRITERIA_EPS : stop when the epsilon value is reached# TERM_CRITERIA_MAX_ITER: stop when Max iteration is reachedcriteria = (cv.TERM_CRITERIA_EPS + cv.TERM_CRITERIA_MAX_ITER, 10, 1.0) fig, ax = plt.subplots(10,2, sharey=True)for i in range(10): K = i+3 # apply K-means algorithm ret,label,center=cv.kmeans(Z,K,None,criteria,attempts = 10, cv.KMEANS_RANDOM_CENTERS) # Now convert back into uint8, and make original image center = np.uint8(center) res = center[label.flatten()] res2 = res.reshape((img.shape)) # plot the original image and K-means image ax[i, 1].imshow(res2) ax[i,1].set_title('K = %s Image'%K) ax[i, 0].imshow(img) ax[i,0].set_title('Original Image')",
"e": 6017,
"s": 5011,
"text": null
},
{
"code": null,
"e": 6048,
"s": 6017,
"text": "Image Segmentation for K=3,4,5"
},
{
"code": null,
"e": 6079,
"s": 6048,
"text": "Image Segmentation for K=6,7,8"
},
{
"code": null,
"e": 6090,
"s": 6079,
"text": "NYU slides"
},
{
"code": null,
"e": 6105,
"s": 6090,
"text": "OpenCV K-means"
},
{
"code": null,
"e": 6122,
"s": 6105,
"text": "Image-Processing"
},
{
"code": null,
"e": 6139,
"s": 6122,
"text": "Machine Learning"
},
{
"code": null,
"e": 6146,
"s": 6139,
"text": "Python"
},
{
"code": null,
"e": 6163,
"s": 6146,
"text": "Machine Learning"
}
] |
turtle.register_shape() function in Python | 28 Jul, 2020
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This function is used to add a turtle shape to TurtleScreen’s shapelist.
Syntax :
turtle.register_shape(name, shape=None)
Parameters:
Below is the implementation of the above method with an example :
Python3
# import packageimport turtle # record a polygonturtle.begin_poly() # form a polygonturtle.seth(-45)turtle.circle(20, 90)turtle.circle(10, 90)turtle.circle(20, 90)turtle.circle(10, 90) turtle.end_poly() # get polygonpairs = turtle.get_poly() # register shape with# name : new_shape# polygon : pairsturtle.register_shape("new_shape", pairs) # clear screenturtle.clearscreen() # use new shape and# apply propertiesturtle.shape("new_shape")turtle.fillcolor("blue") # do some motionfor i in range(50): turtle.forward(5+2*i) turtle.right(45)
Output :
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jul, 2020"
},
{
"code": null,
"e": 245,
"s": 28,
"text": "The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses tkinter for the underlying graphics, it needs a version of Python installed with Tk support."
},
{
"code": null,
"e": 318,
"s": 245,
"text": "This function is used to add a turtle shape to TurtleScreen’s shapelist."
},
{
"code": null,
"e": 327,
"s": 318,
"text": "Syntax :"
},
{
"code": null,
"e": 368,
"s": 327,
"text": "turtle.register_shape(name, shape=None)\n"
},
{
"code": null,
"e": 380,
"s": 368,
"text": "Parameters:"
},
{
"code": null,
"e": 446,
"s": 380,
"text": "Below is the implementation of the above method with an example :"
},
{
"code": null,
"e": 454,
"s": 446,
"text": "Python3"
},
{
"code": "# import packageimport turtle # record a polygonturtle.begin_poly() # form a polygonturtle.seth(-45)turtle.circle(20, 90)turtle.circle(10, 90)turtle.circle(20, 90)turtle.circle(10, 90) turtle.end_poly() # get polygonpairs = turtle.get_poly() # register shape with# name : new_shape# polygon : pairsturtle.register_shape(\"new_shape\", pairs) # clear screenturtle.clearscreen() # use new shape and# apply propertiesturtle.shape(\"new_shape\")turtle.fillcolor(\"blue\") # do some motionfor i in range(50): turtle.forward(5+2*i) turtle.right(45)",
"e": 1005,
"s": 454,
"text": null
},
{
"code": null,
"e": 1014,
"s": 1005,
"text": "Output :"
},
{
"code": null,
"e": 1028,
"s": 1014,
"text": "Python-turtle"
},
{
"code": null,
"e": 1035,
"s": 1028,
"text": "Python"
},
{
"code": null,
"e": 1133,
"s": 1035,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1151,
"s": 1133,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1193,
"s": 1151,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1215,
"s": 1193,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1250,
"s": 1215,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1276,
"s": 1250,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1308,
"s": 1276,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1337,
"s": 1308,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1364,
"s": 1337,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1394,
"s": 1364,
"text": "Iterate over a list in Python"
}
] |
Fn Graph — Lightweight pipelines in Python | by James | Towards Data Science | Today we are releasing our new Python modelling pipeline (or function graph) library fn_graph. We have been building and operationalising various types of computational models for the last decade, whether they be machine learning models, financial models or general data pipelines. This library is the result of all our learnings from the past.
fn_graph is a lightweight library that lets you easily build and visualise data-flow style models in python, and then easily move them to your production environment or embed them in your model backed products.
fn_graph is built to improve both the development phase, the production phase, and the maintenance phase of a model’s life cycle.
Model is a very overloaded term, but here we mean it in the holistic sense. This includes statistical and machine learning models, the data preparation logic that precedes them, as well as more classic quantitative models, such as financial models. Associated with the models is all the logic to do testing, evaluation and configuration.
The standard approach to developing models and integrating them into either production systems or products has a number of real irritations and inefficiencies. The standard model development life cycle can be (very coarsely) split into 3 phases:
Model development entails the investigation of any underlying data, design of the solution, preparation of the data, training of any machine learning models, and the testing of any results. This generally happens in a Jupyter notebook, and often on an analyst’s laptop (or personal cloud instance). During this phase the ability to rapidly iterate, try new ideas and share those results with relevant stakeholders is paramount.
Notebooks have been a huge advance for the data community, but they also have some really undesirable qualities. The primary problem is that they are primarily built for experimentation, rather than building something reusable. This is fine in the academic world where primarily you want to show something can be done or prove a specific result, with associated lovely markup, charts and a well written literate-programming style narrative. Unfortunately, and much to the disappointment of many novice data-scientists, this is not what industry wants. Industry wants to be able to run something more than once, in order to hopefully turn a profit.
The common reality is even bleaker, most of the time you don’t get a beautiful Donald Knuth style notebook. Instead due to the nature of notebooks, which militate against modularisation, you get an unsightly mess of very unstructured, un-encapsulated code that often won’t run unless the cells are run in a magical order unknown even to the author. For a suitably complex domain the notebook can become extremely long (because remember it’s not that easy to break things up into modules, and you lose the ability to easily look inside the intermediate results when you do) and very unwieldy.
These considerations extend further into the model life cycle, which we will get to, but also extend horizontally into aspects like extensibility, reusability and the ease of maintaining technical an institutional knowledge across teams.
Once the analyst/data-scientist/modeller has finished their model, the results have been verified and all the numbers look good, the next phase is to put the model into production. This can mean different things for different projects, but it could be moving it to work off production data sources as some sort of scheduled task, or wrapping it up into an API, or integrating it more deeply into the code base of an existing product.
Whatever the case the requirements are very different from the notebook based model development phase. The model development phase prioritises being able to quickly try new things, and being able to deeply inspect all the steps and inner workings of a model. Conversely the production phase prioritises having a clean encapsulation of the model which is simple to configure and repeatedly run end-to-end.
So what often happens is the notebook gets thrown over the fence to a production engineer who now, wanting to write modular reasonably reusable code, has to pull it apart into various functions, classes etc. This inevitably produces subtle errors which take a long time to be ironed out, especially in statistical models where testing is a lot more difficult than just checking the end results are equal.
If the model does not get rewritten it gets wrapped in one big horrible function that makes debugging, testing and maintenance extremely difficult, while often being very inefficient.
Whatever happens, a version of the model is ready to be put into production .. which it is.
After the model has been in production for a while it is time to make a change. This could be because the requirements have changed slightly, or now with more data and usage the results are not giving the behaviour that was initially desired.
These changes require the skills of an analyst/data-scientist/modeller, not a production engineer, to make and validate the changes. Now remember we essentially have two versions of the code, the analyst’s notebook, and the engineer’s module. These probably have a few differences in behaviour as well.
The analyst cannot just use the engineer’s production code, because it is nicely encapsulated so it is difficult to get to the intermediate steps, which is probably what you need to investigate. So either the original notebook has to be patched and updated to accommodate any differences, or the production code has to be turned inside out and flattened into another notebook.
The changes can then be made, and the previous productionisation process has to be repeated. This continues for the effective life of the product. It is not that fun.
fn_graph lets you build composable dataflow style pipelines (well really graphs) out of normal python functions. It does this with minimal boilerplate. This structure allows for the details of a model to be explored and interrogated during model development, and the full pipeline to be easily imported into production code without any changes.
The central trick of the library is that it matches function argument names to function names to build up the graph. This leaves a very clean implementation where everything is just a function, but because we know the structure of the function graph it can interrogate it and access the intermediate results which make inspection very easy. Because each function can and should be pure, as in it should not have any side effects, the code is very reliable and easy to reason about. Once this function graph which we call a Composer has been completed it is just a normal python object that can be imported into production code and have the results called. This is much easier to see in an example (taken from the fn_graph credit model example).
We have a credit_data.csv file which has information on a number of loans in a loan book, and it has a status column with the values PAID, DEFAULT, and LIVE. Where PAID means a loan has been paid off, DEFAULT means the customer has stopped payments before paying off the loan, and finally LIVE means the loan is still being repaid. Additionally it has a number of attributes of the loans as well as the remaining outstanding balance. The goal here is to train a model that predicts which of the LIVE loans will be repaid and ultimately work out what the value of the remaining book is.
Now we link them add them to a Composer which links them:
This will link the two functions, by the function names and the argument names (notice loan_data is the function name, and the argument name for training_data).
We can view this (very simple graph) by going (this works in notebook environments):
Which should get us this.
We can query a result by the function name:
which will get us a result like
That is obviously very simple so let expand it a bit. You can skim through the code, the details are not important, but should hopefully be pretty self-explanatory.
This then gives us the following function graph:
Some things to notice are that it is extremely easy to get a general feel for the flow of the model at a single glance. Additionally it is extremely low on boiler plate. The only additional code are extra one lines per a function. fn_graph also has not tied you to any specific data structure or library, we freely mix normal python data structures with Pandas DataFrames and even a plot.
We can also easily query the intermediate results if we want to investigate:
Having access to the explicit call structure of the function graph allows us to create some very interesting tooling. A sibling project to fn_graph is fn_graph_studio which is a web based explorer for fn_graph composers. It allows a user to navigate through the function graph, viewing and manipulating the results. This is extremely useful during the model development phase (it comes with hot reloading) and once deployed it can be used to allow less technical stakeholders to still get a decent understanding of the model. The studio deserves it’s own post, but it is a very powerful piece of machinery that augment notebooks nicely.
So while fn_graph makes model development easier and clearer, we have not talked about how it makes model productionisation easier. The primary thing is that the Composer is something you can easily manipulate programmatically, and as the name suggests this lets you compose and manage logic.
For the sake of example, lets assume that we wanted to take we want to take our risk model and wrap it up in an API that takes a loan book name, loads the associated data from S3 based on some mapping and then returns the result. Basically we are just creating a function that takes a string as an argument and returns a number.
What we can do is import our composer, and then update it.
This updates the loan_data function, replacing the previous one which loaded form the file system with one that takes a string input and loads an associated file from S3. If we look at the graphviz of that we will see that the loan_data function now takes an input, which has not been provided (hence it is shown as a red error node).
For cases like this where we just want to enter an input into a composer we can use parameters. The simplest example is:
Which sets the loan_book parameter and then calls for the results. This is then extremely easy to wrap in a function:
Which you could easily call in a flask endpoint, or anywhere else.
Notice that we did not have to refactor our initial model in any way, and if changes were made to it they would automatically flow through into production.
Similarly if you needed to investigate a specific result you could either download a file and use the original composer or just directly investigate the production composer. This is possible because you can directly address the intermediate results. For example:
This would not be possible in normally encapsulated code, such as that which a production engineer would write, which would hide the internals of the model. Here we get the best of both worlds, we have a nice encapsulated interface, by being able to call the final result (value_of_live_book), while also having access to the internal workings.
A couple of other features are included, or naturally fall out of fn_graph.
Once models get larger they can become difficult to organise. To help with this fn_graph has the concept of namespaces. Namespaces allow you to compose larger models out of smaller sub-models which making sure their are no naming conflicts. Combined with the fn_graph_studio it makes handling very complex models significantly simpler, and more importantly much easier to explain and collaborate on. We have built very large models with hundreds on functions, such as that below, while easily being able to discuss and implement ongoing changes.
Something common that analysts and data-scientists repetitively re-implement in their notebooks is caching. When working with even slightly larger datasets it drastically slows down iteration time (or is completely prohibitive) if the entire model has to completely rerun for each change. This often results in sprinkles of if statements over a notebook that control whether to calculate a value or just pull it from a previously saved file. Along with some deft out of order cell execution this sort of works, but leaves the notebook messy and very difficult to reproduce, worse changes in the logic may be unwittingly ignored (cache invalidation errors), leading to all sorts of errors and wasted time.
However since fn_graph has the dependency graph or the functions being called caching and cache invalidation becomes a simple exercise that can be uniformly and automatically applied. fn_graph ships with multiple cache backends including a development_cache which will intelligently cache to disk and invalidate the cache when a function changes. This makes the caching completely transparent to the user.
The biggest advantage of fn_graph is that it really is just plain python functions. There is no heavyweight object model that has to be learnt and there is no complicated runtime.
It makes no restrictions on what toolkits you can use, since it really just orchestrates function calls. You can use it with your favourite machine learning library, with pandas, with just plain python data-structures, or whatever niche library you need. You can integrate into any web server, or other task system you may have, as long as it can call a python function there is no restriction.
You can install fn_graph with pip,
pip install fn_graph
You probably want to install fn_graph_studio (which is separated as a dependency because production systems won’t need it), as well as the dependencies of the examples.
pip install fn_graph_studio
Then to run the example we spoke about here run:
fn_graph_studio example credit
You can also find a live gallery site at https://fn_graph.businessoptics.biz/. You can find the documentation at https://fn-graph.readthedocs.io/en/latest/, and checkout the github repositories at:
https://github.com/BusinessOptics/fn_graph
https://github.com/BusinessOptics/fn_graph_studio
We would love to hear your feedback. | [
{
"code": null,
"e": 517,
"s": 172,
"text": "Today we are releasing our new Python modelling pipeline (or function graph) library fn_graph. We have been building and operationalising various types of computational models for the last decade, whether they be machine learning models, financial models or general data pipelines. This library is the result of all our learnings from the past."
},
{
"code": null,
"e": 728,
"s": 517,
"text": "fn_graph is a lightweight library that lets you easily build and visualise data-flow style models in python, and then easily move them to your production environment or embed them in your model backed products."
},
{
"code": null,
"e": 858,
"s": 728,
"text": "fn_graph is built to improve both the development phase, the production phase, and the maintenance phase of a model’s life cycle."
},
{
"code": null,
"e": 1196,
"s": 858,
"text": "Model is a very overloaded term, but here we mean it in the holistic sense. This includes statistical and machine learning models, the data preparation logic that precedes them, as well as more classic quantitative models, such as financial models. Associated with the models is all the logic to do testing, evaluation and configuration."
},
{
"code": null,
"e": 1442,
"s": 1196,
"text": "The standard approach to developing models and integrating them into either production systems or products has a number of real irritations and inefficiencies. The standard model development life cycle can be (very coarsely) split into 3 phases:"
},
{
"code": null,
"e": 1870,
"s": 1442,
"text": "Model development entails the investigation of any underlying data, design of the solution, preparation of the data, training of any machine learning models, and the testing of any results. This generally happens in a Jupyter notebook, and often on an analyst’s laptop (or personal cloud instance). During this phase the ability to rapidly iterate, try new ideas and share those results with relevant stakeholders is paramount."
},
{
"code": null,
"e": 2518,
"s": 1870,
"text": "Notebooks have been a huge advance for the data community, but they also have some really undesirable qualities. The primary problem is that they are primarily built for experimentation, rather than building something reusable. This is fine in the academic world where primarily you want to show something can be done or prove a specific result, with associated lovely markup, charts and a well written literate-programming style narrative. Unfortunately, and much to the disappointment of many novice data-scientists, this is not what industry wants. Industry wants to be able to run something more than once, in order to hopefully turn a profit."
},
{
"code": null,
"e": 3110,
"s": 2518,
"text": "The common reality is even bleaker, most of the time you don’t get a beautiful Donald Knuth style notebook. Instead due to the nature of notebooks, which militate against modularisation, you get an unsightly mess of very unstructured, un-encapsulated code that often won’t run unless the cells are run in a magical order unknown even to the author. For a suitably complex domain the notebook can become extremely long (because remember it’s not that easy to break things up into modules, and you lose the ability to easily look inside the intermediate results when you do) and very unwieldy."
},
{
"code": null,
"e": 3348,
"s": 3110,
"text": "These considerations extend further into the model life cycle, which we will get to, but also extend horizontally into aspects like extensibility, reusability and the ease of maintaining technical an institutional knowledge across teams."
},
{
"code": null,
"e": 3782,
"s": 3348,
"text": "Once the analyst/data-scientist/modeller has finished their model, the results have been verified and all the numbers look good, the next phase is to put the model into production. This can mean different things for different projects, but it could be moving it to work off production data sources as some sort of scheduled task, or wrapping it up into an API, or integrating it more deeply into the code base of an existing product."
},
{
"code": null,
"e": 4187,
"s": 3782,
"text": "Whatever the case the requirements are very different from the notebook based model development phase. The model development phase prioritises being able to quickly try new things, and being able to deeply inspect all the steps and inner workings of a model. Conversely the production phase prioritises having a clean encapsulation of the model which is simple to configure and repeatedly run end-to-end."
},
{
"code": null,
"e": 4592,
"s": 4187,
"text": "So what often happens is the notebook gets thrown over the fence to a production engineer who now, wanting to write modular reasonably reusable code, has to pull it apart into various functions, classes etc. This inevitably produces subtle errors which take a long time to be ironed out, especially in statistical models where testing is a lot more difficult than just checking the end results are equal."
},
{
"code": null,
"e": 4776,
"s": 4592,
"text": "If the model does not get rewritten it gets wrapped in one big horrible function that makes debugging, testing and maintenance extremely difficult, while often being very inefficient."
},
{
"code": null,
"e": 4868,
"s": 4776,
"text": "Whatever happens, a version of the model is ready to be put into production .. which it is."
},
{
"code": null,
"e": 5111,
"s": 4868,
"text": "After the model has been in production for a while it is time to make a change. This could be because the requirements have changed slightly, or now with more data and usage the results are not giving the behaviour that was initially desired."
},
{
"code": null,
"e": 5414,
"s": 5111,
"text": "These changes require the skills of an analyst/data-scientist/modeller, not a production engineer, to make and validate the changes. Now remember we essentially have two versions of the code, the analyst’s notebook, and the engineer’s module. These probably have a few differences in behaviour as well."
},
{
"code": null,
"e": 5791,
"s": 5414,
"text": "The analyst cannot just use the engineer’s production code, because it is nicely encapsulated so it is difficult to get to the intermediate steps, which is probably what you need to investigate. So either the original notebook has to be patched and updated to accommodate any differences, or the production code has to be turned inside out and flattened into another notebook."
},
{
"code": null,
"e": 5958,
"s": 5791,
"text": "The changes can then be made, and the previous productionisation process has to be repeated. This continues for the effective life of the product. It is not that fun."
},
{
"code": null,
"e": 6303,
"s": 5958,
"text": "fn_graph lets you build composable dataflow style pipelines (well really graphs) out of normal python functions. It does this with minimal boilerplate. This structure allows for the details of a model to be explored and interrogated during model development, and the full pipeline to be easily imported into production code without any changes."
},
{
"code": null,
"e": 7048,
"s": 6303,
"text": "The central trick of the library is that it matches function argument names to function names to build up the graph. This leaves a very clean implementation where everything is just a function, but because we know the structure of the function graph it can interrogate it and access the intermediate results which make inspection very easy. Because each function can and should be pure, as in it should not have any side effects, the code is very reliable and easy to reason about. Once this function graph which we call a Composer has been completed it is just a normal python object that can be imported into production code and have the results called. This is much easier to see in an example (taken from the fn_graph credit model example)."
},
{
"code": null,
"e": 7634,
"s": 7048,
"text": "We have a credit_data.csv file which has information on a number of loans in a loan book, and it has a status column with the values PAID, DEFAULT, and LIVE. Where PAID means a loan has been paid off, DEFAULT means the customer has stopped payments before paying off the loan, and finally LIVE means the loan is still being repaid. Additionally it has a number of attributes of the loans as well as the remaining outstanding balance. The goal here is to train a model that predicts which of the LIVE loans will be repaid and ultimately work out what the value of the remaining book is."
},
{
"code": null,
"e": 7692,
"s": 7634,
"text": "Now we link them add them to a Composer which links them:"
},
{
"code": null,
"e": 7853,
"s": 7692,
"text": "This will link the two functions, by the function names and the argument names (notice loan_data is the function name, and the argument name for training_data)."
},
{
"code": null,
"e": 7938,
"s": 7853,
"text": "We can view this (very simple graph) by going (this works in notebook environments):"
},
{
"code": null,
"e": 7964,
"s": 7938,
"text": "Which should get us this."
},
{
"code": null,
"e": 8008,
"s": 7964,
"text": "We can query a result by the function name:"
},
{
"code": null,
"e": 8040,
"s": 8008,
"text": "which will get us a result like"
},
{
"code": null,
"e": 8205,
"s": 8040,
"text": "That is obviously very simple so let expand it a bit. You can skim through the code, the details are not important, but should hopefully be pretty self-explanatory."
},
{
"code": null,
"e": 8254,
"s": 8205,
"text": "This then gives us the following function graph:"
},
{
"code": null,
"e": 8643,
"s": 8254,
"text": "Some things to notice are that it is extremely easy to get a general feel for the flow of the model at a single glance. Additionally it is extremely low on boiler plate. The only additional code are extra one lines per a function. fn_graph also has not tied you to any specific data structure or library, we freely mix normal python data structures with Pandas DataFrames and even a plot."
},
{
"code": null,
"e": 8720,
"s": 8643,
"text": "We can also easily query the intermediate results if we want to investigate:"
},
{
"code": null,
"e": 9357,
"s": 8720,
"text": "Having access to the explicit call structure of the function graph allows us to create some very interesting tooling. A sibling project to fn_graph is fn_graph_studio which is a web based explorer for fn_graph composers. It allows a user to navigate through the function graph, viewing and manipulating the results. This is extremely useful during the model development phase (it comes with hot reloading) and once deployed it can be used to allow less technical stakeholders to still get a decent understanding of the model. The studio deserves it’s own post, but it is a very powerful piece of machinery that augment notebooks nicely."
},
{
"code": null,
"e": 9650,
"s": 9357,
"text": "So while fn_graph makes model development easier and clearer, we have not talked about how it makes model productionisation easier. The primary thing is that the Composer is something you can easily manipulate programmatically, and as the name suggests this lets you compose and manage logic."
},
{
"code": null,
"e": 9979,
"s": 9650,
"text": "For the sake of example, lets assume that we wanted to take we want to take our risk model and wrap it up in an API that takes a loan book name, loads the associated data from S3 based on some mapping and then returns the result. Basically we are just creating a function that takes a string as an argument and returns a number."
},
{
"code": null,
"e": 10038,
"s": 9979,
"text": "What we can do is import our composer, and then update it."
},
{
"code": null,
"e": 10373,
"s": 10038,
"text": "This updates the loan_data function, replacing the previous one which loaded form the file system with one that takes a string input and loads an associated file from S3. If we look at the graphviz of that we will see that the loan_data function now takes an input, which has not been provided (hence it is shown as a red error node)."
},
{
"code": null,
"e": 10494,
"s": 10373,
"text": "For cases like this where we just want to enter an input into a composer we can use parameters. The simplest example is:"
},
{
"code": null,
"e": 10612,
"s": 10494,
"text": "Which sets the loan_book parameter and then calls for the results. This is then extremely easy to wrap in a function:"
},
{
"code": null,
"e": 10679,
"s": 10612,
"text": "Which you could easily call in a flask endpoint, or anywhere else."
},
{
"code": null,
"e": 10835,
"s": 10679,
"text": "Notice that we did not have to refactor our initial model in any way, and if changes were made to it they would automatically flow through into production."
},
{
"code": null,
"e": 11098,
"s": 10835,
"text": "Similarly if you needed to investigate a specific result you could either download a file and use the original composer or just directly investigate the production composer. This is possible because you can directly address the intermediate results. For example:"
},
{
"code": null,
"e": 11443,
"s": 11098,
"text": "This would not be possible in normally encapsulated code, such as that which a production engineer would write, which would hide the internals of the model. Here we get the best of both worlds, we have a nice encapsulated interface, by being able to call the final result (value_of_live_book), while also having access to the internal workings."
},
{
"code": null,
"e": 11519,
"s": 11443,
"text": "A couple of other features are included, or naturally fall out of fn_graph."
},
{
"code": null,
"e": 12065,
"s": 11519,
"text": "Once models get larger they can become difficult to organise. To help with this fn_graph has the concept of namespaces. Namespaces allow you to compose larger models out of smaller sub-models which making sure their are no naming conflicts. Combined with the fn_graph_studio it makes handling very complex models significantly simpler, and more importantly much easier to explain and collaborate on. We have built very large models with hundreds on functions, such as that below, while easily being able to discuss and implement ongoing changes."
},
{
"code": null,
"e": 12770,
"s": 12065,
"text": "Something common that analysts and data-scientists repetitively re-implement in their notebooks is caching. When working with even slightly larger datasets it drastically slows down iteration time (or is completely prohibitive) if the entire model has to completely rerun for each change. This often results in sprinkles of if statements over a notebook that control whether to calculate a value or just pull it from a previously saved file. Along with some deft out of order cell execution this sort of works, but leaves the notebook messy and very difficult to reproduce, worse changes in the logic may be unwittingly ignored (cache invalidation errors), leading to all sorts of errors and wasted time."
},
{
"code": null,
"e": 13176,
"s": 12770,
"text": "However since fn_graph has the dependency graph or the functions being called caching and cache invalidation becomes a simple exercise that can be uniformly and automatically applied. fn_graph ships with multiple cache backends including a development_cache which will intelligently cache to disk and invalidate the cache when a function changes. This makes the caching completely transparent to the user."
},
{
"code": null,
"e": 13356,
"s": 13176,
"text": "The biggest advantage of fn_graph is that it really is just plain python functions. There is no heavyweight object model that has to be learnt and there is no complicated runtime."
},
{
"code": null,
"e": 13751,
"s": 13356,
"text": "It makes no restrictions on what toolkits you can use, since it really just orchestrates function calls. You can use it with your favourite machine learning library, with pandas, with just plain python data-structures, or whatever niche library you need. You can integrate into any web server, or other task system you may have, as long as it can call a python function there is no restriction."
},
{
"code": null,
"e": 13786,
"s": 13751,
"text": "You can install fn_graph with pip,"
},
{
"code": null,
"e": 13807,
"s": 13786,
"text": "pip install fn_graph"
},
{
"code": null,
"e": 13976,
"s": 13807,
"text": "You probably want to install fn_graph_studio (which is separated as a dependency because production systems won’t need it), as well as the dependencies of the examples."
},
{
"code": null,
"e": 14004,
"s": 13976,
"text": "pip install fn_graph_studio"
},
{
"code": null,
"e": 14053,
"s": 14004,
"text": "Then to run the example we spoke about here run:"
},
{
"code": null,
"e": 14084,
"s": 14053,
"text": "fn_graph_studio example credit"
},
{
"code": null,
"e": 14282,
"s": 14084,
"text": "You can also find a live gallery site at https://fn_graph.businessoptics.biz/. You can find the documentation at https://fn-graph.readthedocs.io/en/latest/, and checkout the github repositories at:"
},
{
"code": null,
"e": 14325,
"s": 14282,
"text": "https://github.com/BusinessOptics/fn_graph"
},
{
"code": null,
"e": 14375,
"s": 14325,
"text": "https://github.com/BusinessOptics/fn_graph_studio"
}
] |
Solving your first linear program in Python | by Bhaskar Agarwal | Towards Data Science | You might have come across the term 'linear programming' at some point in data science or research. I will try to explain what it is and how one can implement a linear program in Python.
A linear program finds an optimum solution for a problem where the variables are subject to numerous linear relationships. Furthermore, the problem could require one to maximise or minimise a certain condition, for example minimise the cost of a product, or maximise the profit.
An often discussed example of a linear program is that of the traveling salesman. Starting from his hometown a salesman needs to travel all cities of a district but in order to minimise traveling costs he must take the shortest possible path that crosses each city and ends in his hometown. Generally the best possible path is one that crosses each city only once, thereby resembling a closed loop (starting and ending in the hometown).
Personally I have applied linear programs in a multitude of applications.
Transport Industry: For route optimisation where various depots had to be visited while minimising the operational costs.
Energy industry: Optimise the electricity consumption for a household with a solar panel, while predicting the load pattern.
Logic Problems: Solving logic problems/puzzles using a linear program where all logical constraints have to be satisfied 'in parallel' (topic of the next post).
Bar talk: Think high-school mathematics, linear equations and solving simultaneous linear equations. Basically that is the idea, but add to this an extra condition on the variables that needs to be minimised or maximised.
Technical talk: A linear program optimises an objective function (or cost function) where a set of linear equalities (and inequalities) needs to be satisfied.
I will demonstrate what all this means with a real life example.
I need to bake a cake with four ingredients: flour, eggs, butter and sugar. However, I remember only bits and parts of the recipe as stated below.
total weight of all ingredients was exactly 700 grams
amount of butter was half that of sugar
weight of flour and eggs together was at most 450 grams
weight of eggs and butter combined was at most 300 grams
the weight of eggs plus butter was at most that of flour plus sugar
Is it possible to figure out the optimum values for each of the ingredients from the information above?
The answer is yes. This is what a linear program is designed to do.
We can define each of the variables as
flour: f
eggs: e
butter: b
sugar: s
We can then write each of the conditions as
Note that the equations above follow a pattern. All variables appear on the left and all constants on the right. The inequalities are expressed as less than or equal to. Once we are able to express a problem in the manner above, a linear program can be constructed. The last piece of the puzzle is an objective function. A cost function or objective function is basically another linear relationship (between the variables we are solving for) that requires to be maximised or minimised. This actually further simplifies the question.
An example of a health-conscious cost function could be the following
minimise the butter and sugar consumption
or in other words
We are almost ready to code our linear problem in Python. However, we can formulate the problem in a slightly more code-friendly way. Mathematically we can express a set of linear equations in matrix form which helps us visualise the problem computationally.
We define the following matrices
where the first row contains all our variables that we are solving for in the matrix X and our cost function as c. The equality matrices are in the second row, and matrices describing the inequality conditions are in the last row. The matrices are defined such that they follow the rules of matrix multiplication. This formulation allows us to write our equations as
Thus, using linear algebra our problem takes the form
Note that we use the transpose (superscript T) of matrix c so that we can multiply it with our solution matrix X.
We can now start coding this problem in Python.
My Python setup
Python 3.8.2
SciPy 1.18.1
Numpy 1.4.1
Cvxopt 1.2.3 (optional)
Using SciPy
SciPy in Python offers basic linear programming capabilities. To implement the above program using SciPy, we need to define all matrices accordingly. Below is a working example of the equations above that I implemented using SciPy's optimize library.
Which returns the following output
WITHOUT BOUNDS con: array([ 5.27055590e-08, -3.78719278e-11]) fun: 249.99999998121916 message: 'Optimization terminated successfully.' nit: 5 slack: array([3.39247208e-08, 6.95661413e+01, 7.24656159e+01]) status: 0 success: True x: array([302.8994746 , 147.10052537, 83.33333333, 166.66666665])
The success field in the output above tells us if the optimisation was successful. In fact this message is explicitly returned in the field message or encoded as an integer value in the status filed which can take 5 integer values ranging form 0 to 4. Finally the x field contains the variables we were solving for, returned in the exact order we defined them with our matrix formulation. Thus the solution is
flour = 302.89g
eggs = 147.10g
butter = 83.33g
sugar = 166.66g
The result satisfies all of the conditions we imposed earlier. Total weight of all ingredients is still exactly 700g, the amount of butter and sugar is the minimum possible, butter is still half of sugar and so on.
Note: If you did not get the values above, it might have something to do with the version of SciPy you used and/or the default method used to execute the linear program, i.e. simplex vs. interior-point
Using SciPy and adding bounds for variables
I can make the problem a little more refined by adding some estimates for my variables. For example I remember that the flour was not more than 300g, and that the one time I had a 100g stick of butter I was able to make the cake. I make reasonable guesses for the rest of the variables.
Which returns
WITH BOUNDS con: array([ 4.53132998e-09, -3.25428573e-12]) fun: 249.9999999983819 message: 'Optimization terminated successfully.' nit: 6 slack: array([2.91322522e-09, 5.30261661e+01, 3.93856656e+01]) status: 0 success: True x: array([286.35949946, 163.64050053, 83.33333333, 166.66666667])
The output now implies
flour = 286.35g
eggs = 163.64g
butter = 83.33g
sugar = 166.66g
Note that now the individual amounts of butter and sugar are higher than before. This is perfectly acceptable because the linear program is trying to simultaneously satisfy all the conditions we encoded, including our newly imposed bounds for each of the ingredients. The total is still 700g, butter is still half of sugar, butter is still less than 100g (a bound we imposed), flour +butter is still more than or equal to eggs + sugar and so on. This is the beauty of a linear program. It aims at satisfying every single condition it was passed, therefore returning the most optimum solution.
I wrote a simple parser for the result which returns a more readable output in the form of a dictionary.
With the output
Result (no bounds): {'Flour': 303.0, 'Eggs': 147.0, 'Butter': 83.0, 'Sugar': 167.0}Result (with bounds): {'Flour': 286.0, 'Eggs': 164.0, 'Butter': 83.0, 'Sugar': 167.0}
Using another linear programming library
In Python there are many libraries (CVXOPT, PULP, CVXPY, ECOS, etc.) that basically come with their own LP solvers or act as wrappers around other LP solvers. Thus one can choose a wrapper-solver combination depending on the problem at hand.
Below is the same problem preamble (the matrices and equations) implemented using the CVXOPT libray with a GLPK solver. The main difference here is that one needs to define the equations in cvxopt's own matrix framework. Note that CVXOPT is rather flexible and allows one to use a number of solvers depending on the problem. I did not pass any bounds for the variables.
Which returns the output
solution found [ 2.67e+02] [ 1.83e+02] [ 8.33e+01] [ 1.67e+02]
This is between the two solutions we found using SciPy's own linear optimisation routine above. While the amount of butter and sugar remains consistent, the flour and eggs have different values. Why is that? One reason is that our problem might not be well constructed (especially for values of flour and eggs), but the three solutions are equally acceptable as they satisfy all the constraints. Note that in the last two solutions the sum of flour and eggs remains the same, however the individual values differ by 20 grams. One might need to add another constraint to break this degeneracy.
We can break this degeneracy by adding the equation or knowledge that the weight of flour plus sugar is exactly 500 grams, or in other words
Could you try and add this to the relevant matrices (and code). Then re-run the SciPy solver without bounds, and CVXOPT without bounds to see if the values of the ingredients match?
The entire notebook and the addition of this equation is hosted here.
In general, the solution that a particular solver finds comes down to how a given solver actually solves the linear program. This is the topic of another post and I will refrain from going into the details here. | [
{
"code": null,
"e": 358,
"s": 171,
"text": "You might have come across the term 'linear programming' at some point in data science or research. I will try to explain what it is and how one can implement a linear program in Python."
},
{
"code": null,
"e": 637,
"s": 358,
"text": "A linear program finds an optimum solution for a problem where the variables are subject to numerous linear relationships. Furthermore, the problem could require one to maximise or minimise a certain condition, for example minimise the cost of a product, or maximise the profit."
},
{
"code": null,
"e": 1074,
"s": 637,
"text": "An often discussed example of a linear program is that of the traveling salesman. Starting from his hometown a salesman needs to travel all cities of a district but in order to minimise traveling costs he must take the shortest possible path that crosses each city and ends in his hometown. Generally the best possible path is one that crosses each city only once, thereby resembling a closed loop (starting and ending in the hometown)."
},
{
"code": null,
"e": 1148,
"s": 1074,
"text": "Personally I have applied linear programs in a multitude of applications."
},
{
"code": null,
"e": 1270,
"s": 1148,
"text": "Transport Industry: For route optimisation where various depots had to be visited while minimising the operational costs."
},
{
"code": null,
"e": 1395,
"s": 1270,
"text": "Energy industry: Optimise the electricity consumption for a household with a solar panel, while predicting the load pattern."
},
{
"code": null,
"e": 1556,
"s": 1395,
"text": "Logic Problems: Solving logic problems/puzzles using a linear program where all logical constraints have to be satisfied 'in parallel' (topic of the next post)."
},
{
"code": null,
"e": 1778,
"s": 1556,
"text": "Bar talk: Think high-school mathematics, linear equations and solving simultaneous linear equations. Basically that is the idea, but add to this an extra condition on the variables that needs to be minimised or maximised."
},
{
"code": null,
"e": 1937,
"s": 1778,
"text": "Technical talk: A linear program optimises an objective function (or cost function) where a set of linear equalities (and inequalities) needs to be satisfied."
},
{
"code": null,
"e": 2002,
"s": 1937,
"text": "I will demonstrate what all this means with a real life example."
},
{
"code": null,
"e": 2149,
"s": 2002,
"text": "I need to bake a cake with four ingredients: flour, eggs, butter and sugar. However, I remember only bits and parts of the recipe as stated below."
},
{
"code": null,
"e": 2203,
"s": 2149,
"text": "total weight of all ingredients was exactly 700 grams"
},
{
"code": null,
"e": 2243,
"s": 2203,
"text": "amount of butter was half that of sugar"
},
{
"code": null,
"e": 2299,
"s": 2243,
"text": "weight of flour and eggs together was at most 450 grams"
},
{
"code": null,
"e": 2356,
"s": 2299,
"text": "weight of eggs and butter combined was at most 300 grams"
},
{
"code": null,
"e": 2424,
"s": 2356,
"text": "the weight of eggs plus butter was at most that of flour plus sugar"
},
{
"code": null,
"e": 2528,
"s": 2424,
"text": "Is it possible to figure out the optimum values for each of the ingredients from the information above?"
},
{
"code": null,
"e": 2596,
"s": 2528,
"text": "The answer is yes. This is what a linear program is designed to do."
},
{
"code": null,
"e": 2635,
"s": 2596,
"text": "We can define each of the variables as"
},
{
"code": null,
"e": 2644,
"s": 2635,
"text": "flour: f"
},
{
"code": null,
"e": 2652,
"s": 2644,
"text": "eggs: e"
},
{
"code": null,
"e": 2662,
"s": 2652,
"text": "butter: b"
},
{
"code": null,
"e": 2671,
"s": 2662,
"text": "sugar: s"
},
{
"code": null,
"e": 2715,
"s": 2671,
"text": "We can then write each of the conditions as"
},
{
"code": null,
"e": 3249,
"s": 2715,
"text": "Note that the equations above follow a pattern. All variables appear on the left and all constants on the right. The inequalities are expressed as less than or equal to. Once we are able to express a problem in the manner above, a linear program can be constructed. The last piece of the puzzle is an objective function. A cost function or objective function is basically another linear relationship (between the variables we are solving for) that requires to be maximised or minimised. This actually further simplifies the question."
},
{
"code": null,
"e": 3319,
"s": 3249,
"text": "An example of a health-conscious cost function could be the following"
},
{
"code": null,
"e": 3361,
"s": 3319,
"text": "minimise the butter and sugar consumption"
},
{
"code": null,
"e": 3379,
"s": 3361,
"text": "or in other words"
},
{
"code": null,
"e": 3638,
"s": 3379,
"text": "We are almost ready to code our linear problem in Python. However, we can formulate the problem in a slightly more code-friendly way. Mathematically we can express a set of linear equations in matrix form which helps us visualise the problem computationally."
},
{
"code": null,
"e": 3671,
"s": 3638,
"text": "We define the following matrices"
},
{
"code": null,
"e": 4038,
"s": 3671,
"text": "where the first row contains all our variables that we are solving for in the matrix X and our cost function as c. The equality matrices are in the second row, and matrices describing the inequality conditions are in the last row. The matrices are defined such that they follow the rules of matrix multiplication. This formulation allows us to write our equations as"
},
{
"code": null,
"e": 4092,
"s": 4038,
"text": "Thus, using linear algebra our problem takes the form"
},
{
"code": null,
"e": 4206,
"s": 4092,
"text": "Note that we use the transpose (superscript T) of matrix c so that we can multiply it with our solution matrix X."
},
{
"code": null,
"e": 4254,
"s": 4206,
"text": "We can now start coding this problem in Python."
},
{
"code": null,
"e": 4270,
"s": 4254,
"text": "My Python setup"
},
{
"code": null,
"e": 4283,
"s": 4270,
"text": "Python 3.8.2"
},
{
"code": null,
"e": 4296,
"s": 4283,
"text": "SciPy 1.18.1"
},
{
"code": null,
"e": 4308,
"s": 4296,
"text": "Numpy 1.4.1"
},
{
"code": null,
"e": 4332,
"s": 4308,
"text": "Cvxopt 1.2.3 (optional)"
},
{
"code": null,
"e": 4344,
"s": 4332,
"text": "Using SciPy"
},
{
"code": null,
"e": 4595,
"s": 4344,
"text": "SciPy in Python offers basic linear programming capabilities. To implement the above program using SciPy, we need to define all matrices accordingly. Below is a working example of the equations above that I implemented using SciPy's optimize library."
},
{
"code": null,
"e": 4630,
"s": 4595,
"text": "Which returns the following output"
},
{
"code": null,
"e": 4955,
"s": 4630,
"text": "WITHOUT BOUNDS con: array([ 5.27055590e-08, -3.78719278e-11]) fun: 249.99999998121916 message: 'Optimization terminated successfully.' nit: 5 slack: array([3.39247208e-08, 6.95661413e+01, 7.24656159e+01]) status: 0 success: True x: array([302.8994746 , 147.10052537, 83.33333333, 166.66666665])"
},
{
"code": null,
"e": 5365,
"s": 4955,
"text": "The success field in the output above tells us if the optimisation was successful. In fact this message is explicitly returned in the field message or encoded as an integer value in the status filed which can take 5 integer values ranging form 0 to 4. Finally the x field contains the variables we were solving for, returned in the exact order we defined them with our matrix formulation. Thus the solution is"
},
{
"code": null,
"e": 5381,
"s": 5365,
"text": "flour = 302.89g"
},
{
"code": null,
"e": 5396,
"s": 5381,
"text": "eggs = 147.10g"
},
{
"code": null,
"e": 5412,
"s": 5396,
"text": "butter = 83.33g"
},
{
"code": null,
"e": 5428,
"s": 5412,
"text": "sugar = 166.66g"
},
{
"code": null,
"e": 5643,
"s": 5428,
"text": "The result satisfies all of the conditions we imposed earlier. Total weight of all ingredients is still exactly 700g, the amount of butter and sugar is the minimum possible, butter is still half of sugar and so on."
},
{
"code": null,
"e": 5845,
"s": 5643,
"text": "Note: If you did not get the values above, it might have something to do with the version of SciPy you used and/or the default method used to execute the linear program, i.e. simplex vs. interior-point"
},
{
"code": null,
"e": 5889,
"s": 5845,
"text": "Using SciPy and adding bounds for variables"
},
{
"code": null,
"e": 6176,
"s": 5889,
"text": "I can make the problem a little more refined by adding some estimates for my variables. For example I remember that the flour was not more than 300g, and that the one time I had a 100g stick of butter I was able to make the cake. I make reasonable guesses for the rest of the variables."
},
{
"code": null,
"e": 6190,
"s": 6176,
"text": "Which returns"
},
{
"code": null,
"e": 6510,
"s": 6190,
"text": "WITH BOUNDS con: array([ 4.53132998e-09, -3.25428573e-12]) fun: 249.9999999983819 message: 'Optimization terminated successfully.' nit: 6 slack: array([2.91322522e-09, 5.30261661e+01, 3.93856656e+01]) status: 0 success: True x: array([286.35949946, 163.64050053, 83.33333333, 166.66666667])"
},
{
"code": null,
"e": 6533,
"s": 6510,
"text": "The output now implies"
},
{
"code": null,
"e": 6549,
"s": 6533,
"text": "flour = 286.35g"
},
{
"code": null,
"e": 6564,
"s": 6549,
"text": "eggs = 163.64g"
},
{
"code": null,
"e": 6580,
"s": 6564,
"text": "butter = 83.33g"
},
{
"code": null,
"e": 6596,
"s": 6580,
"text": "sugar = 166.66g"
},
{
"code": null,
"e": 7189,
"s": 6596,
"text": "Note that now the individual amounts of butter and sugar are higher than before. This is perfectly acceptable because the linear program is trying to simultaneously satisfy all the conditions we encoded, including our newly imposed bounds for each of the ingredients. The total is still 700g, butter is still half of sugar, butter is still less than 100g (a bound we imposed), flour +butter is still more than or equal to eggs + sugar and so on. This is the beauty of a linear program. It aims at satisfying every single condition it was passed, therefore returning the most optimum solution."
},
{
"code": null,
"e": 7294,
"s": 7189,
"text": "I wrote a simple parser for the result which returns a more readable output in the form of a dictionary."
},
{
"code": null,
"e": 7310,
"s": 7294,
"text": "With the output"
},
{
"code": null,
"e": 7481,
"s": 7310,
"text": "Result (no bounds): {'Flour': 303.0, 'Eggs': 147.0, 'Butter': 83.0, 'Sugar': 167.0}Result (with bounds): {'Flour': 286.0, 'Eggs': 164.0, 'Butter': 83.0, 'Sugar': 167.0}"
},
{
"code": null,
"e": 7522,
"s": 7481,
"text": "Using another linear programming library"
},
{
"code": null,
"e": 7764,
"s": 7522,
"text": "In Python there are many libraries (CVXOPT, PULP, CVXPY, ECOS, etc.) that basically come with their own LP solvers or act as wrappers around other LP solvers. Thus one can choose a wrapper-solver combination depending on the problem at hand."
},
{
"code": null,
"e": 8134,
"s": 7764,
"text": "Below is the same problem preamble (the matrices and equations) implemented using the CVXOPT libray with a GLPK solver. The main difference here is that one needs to define the equations in cvxopt's own matrix framework. Note that CVXOPT is rather flexible and allows one to use a number of solvers depending on the problem. I did not pass any bounds for the variables."
},
{
"code": null,
"e": 8159,
"s": 8134,
"text": "Which returns the output"
},
{
"code": null,
"e": 8222,
"s": 8159,
"text": "solution found [ 2.67e+02] [ 1.83e+02] [ 8.33e+01] [ 1.67e+02]"
},
{
"code": null,
"e": 8815,
"s": 8222,
"text": "This is between the two solutions we found using SciPy's own linear optimisation routine above. While the amount of butter and sugar remains consistent, the flour and eggs have different values. Why is that? One reason is that our problem might not be well constructed (especially for values of flour and eggs), but the three solutions are equally acceptable as they satisfy all the constraints. Note that in the last two solutions the sum of flour and eggs remains the same, however the individual values differ by 20 grams. One might need to add another constraint to break this degeneracy."
},
{
"code": null,
"e": 8956,
"s": 8815,
"text": "We can break this degeneracy by adding the equation or knowledge that the weight of flour plus sugar is exactly 500 grams, or in other words"
},
{
"code": null,
"e": 9138,
"s": 8956,
"text": "Could you try and add this to the relevant matrices (and code). Then re-run the SciPy solver without bounds, and CVXOPT without bounds to see if the values of the ingredients match?"
},
{
"code": null,
"e": 9208,
"s": 9138,
"text": "The entire notebook and the addition of this equation is hosted here."
}
] |
Principal Component Analysis (PCA) 101, using R | by Peter Nistrup | Towards Data Science | Improving predictability and classification one dimension at a time! “Visualize” 30 dimensions using a 2D-plot!
Make sure to follow my profile if you enjoy this article and want to see more!
For this article we’ll be using the Breast Cancer Wisconsin data set from the UCI Machine learning repo as our data. Go ahead and load it for yourself if you want to follow along:
wdbc <- read.csv("wdbc.csv", header = F)features <- c("radius", "texture", "perimeter", "area", "smoothness", "compactness", "concavity", "concave_points", "symmetry", "fractal_dimension")names(wdbc) <- c("id", "diagnosis", paste0(features,"_mean"), paste0(features,"_se"), paste0(features,"_worst"))
The code above will simply load the data and name all 32 variables. The ID, diagnosis and ten distinct (30) features. From UCI:
“The mean, standard error, and “worst” or largest (mean of the three largest values) of these features were computed for each image, resulting in 30 features. For instance, field 3 is Mean Radius, field 13 is Radius SE, field 23 is Worst Radius.”
Right, so now we’ve loaded our data and find ourselves with 30 variables (thus excluding our response “diagnosis” and the irrelevant ID-variable).
Now some of you might be saying “30 variable is a lot” and some might say “Pfft.. Only 30? I’ve worked with THOUSANDS!!” but rest assured that this is equally applicable in either scenario..!
There’s a few pretty good reasons to use PCA. The plot at the very beginning af the article is a great example of how one would plot multi-dimensional data by using PCA, we actually capture 63.3% (Dim1 44.3% + Dim2 19%) of variance in the entire dataset by just using those two principal components, pretty good when taking into consideration that the original data consisted of 30 features which would be impossible to plot in any meaningful way.
A very powerful consideration is to acknowledge that we never specified a response variable or anything else in our PCA-plot indicating whether a tumor was “benign” or “malignant”. It simply turns out that when we try to describe variance in the data using the linear combinations of the PCA we find some pretty obvious clustering and separation between the “benign” and “malignant” tumors! This makes a great case for developing a classification model based on our features!
Another major “feature” (no pun intended) of PCA is that it can actually directly improve performance of your models, please take a look at this great article to read more:
towardsdatascience.com
Lets get something out the way immediately, PCAs primary purpose is NOT as a ways of feature removal! PCA can reduce dimensionality but it wont reduce the number of features / variables in your data. What this means is that you might discover that you can explain 99% of variance in your 1000 feature dataset by just using 3 principal components but you still need those 1000 features to construct those 3 principal components, this also means that in the case of predicting on future data you still need those same 1000 features on your new observations to construct the corresponding principal components.
Since this is purely introductory I’ll skip the math and give you a quick rundown of the workings of PCA:
Standardize the data (Center and scale).
Calculate the Eigenvectors and Eigenvalues from the covariance matrix or correlation matrix (One could also use Singular Vector Decomposition).
Sort the Eigenvalues in descending order and choose the K largest Eigenvectors (Where K is the desired number of dimensions of the new feature subspace k ≤ d).
Construct the projection matrix W from the selected K Eigenvectors.
Transform the original dataset X via W to obtain a K-dimensional feature subspace Y.
This might sound a bit complicated if you haven’t had a few courses in algebra, but the gist of it is to transform our data from it’s initial state X to a subspace Y with K dimensions where K is — more often than not — less than the original dimensions of X. Thankfully this is easily done using R!
So now we understand a bit about how PCA works and that should be enough for now. Lets actually try it out:
wdbc.pr <- prcomp(wdbc[c(3:32)], center = TRUE, scale = TRUE)summary(wdbc.pr)
This is pretty self-explanatory, the ‘prcomp’ function runs PCA on the data we supply it, in our case that’s ‘wdbc[c(3:32)]’ which is our data excluding the ID and diagnosis variables, then we tell R to center and scale our data (thus standardizing the data). Finally we call for a summary:
Recall that a property of PCA is that our components are sorted from largest to smallest with regard to their standard deviation (Eigenvalues). So let’s make sense of these:
Standard deviation: This is simply the eigenvalues in our case since the data has been centered and scaled (standardized)
Proportion of Variance: This is the amount of variance the component accounts for in the data, ie. PC1 accounts for >44% of total variance in the data alone!
Cumulative Proportion: This is simply the accumulated amount of explained variance, ie. if we used the first 10 components we would be able to account for >95% of total variance in the data.
Right, so how many components do we want? We obviously want to be able to explain as much variance as possible but to do that we would need all 30 components, at the same time we want to reduce the number of dimensions so we definitely want less than 30!
Since we standardized our data and we now have the corresponding eigenvalues of each PC we can actually use these to draw a boundary for us. Since an eigenvalues <1 would mean that the component actually explains less than a single explanatory variable we would like to discard those. If our data is well suited for PCA we should be able to discard these components while retaining at least 70–80% of cumulative variance. Lets plot and see:
screeplot(wdbc.pr, type = "l", npcs = 15, main = "Screeplot of the first 10 PCs")abline(h = 1, col="red", lty=5)legend("topright", legend=c("Eigenvalue = 1"), col=c("red"), lty=5, cex=0.6)cumpro <- cumsum(wdbc.pr$sdev^2 / sum(wdbc.pr$sdev^2))plot(cumpro[0:15], xlab = "PC #", ylab = "Amount of explained variance", main = "Cumulative variance plot")abline(v = 6, col="blue", lty=5)abline(h = 0.88759, col="blue", lty=5)legend("topleft", legend=c("Cut-off @ PC6"), col=c("blue"), lty=5, cex=0.6)
We notice is that the first 6 components has an Eigenvalue >1 and explains almost 90% of variance, this is great! We can effectively reduce dimensionality from 30 to 6 while only “loosing” about 10% of variance!
We also notice that we can actually explain more than 60% of variance with just the first two components. Let’s try plotting these:
plot(wdbc.pr$x[,1],wdbc.pr$x[,2], xlab="PC1 (44.3%)", ylab = "PC2 (19%)", main = "PC1 / PC2 - plot")
Alright, this isn’t really too telling but consider for a moment that this is representing 60%+ of variance in a 30 dimensional dataset. But what do we see from this? There’s some clustering going on in the upper/middle-right. Lets also consider for a moment what the goal of this analysis actually is. We want to explain difference between malignant and benign tumors. Let’s actually add the response variable (diagnosis) to the plot and see if we can make better sense of it:
library("factoextra")fviz_pca_ind(wdbc.pr, geom.ind = "point", pointshape = 21, pointsize = 2, fill.ind = wdbc$diagnosis, col.ind = "black", palette = "jco", addEllipses = TRUE, label = "var", col.var = "black", repel = TRUE, legend.title = "Diagnosis") + ggtitle("2D PCA-plot from 30 feature dataset") + theme(plot.title = element_text(hjust = 0.5))
This is essentially the exact same plot with some fancy ellipses and colors corresponding to the diagnosis of the subject and now we see the beauty of PCA. With just the first two components we can clearly see some separation between the benign and malignant tumors. This is a clear indication that the data is well-suited for some kind of classification model (like discriminant analysis).
Our next immediate goal is to construct some kind of model using the first 6 principal components to predict whether a tumor is benign or malignant and then compare it to a model using the original 30 variables.
We’ll take a look at this in the next article:
towardsdatascience.com
If you want to see and learn more, be sure to follow me on Medium🔍 and Twitter 🐦 | [
{
"code": null,
"e": 284,
"s": 172,
"text": "Improving predictability and classification one dimension at a time! “Visualize” 30 dimensions using a 2D-plot!"
},
{
"code": null,
"e": 363,
"s": 284,
"text": "Make sure to follow my profile if you enjoy this article and want to see more!"
},
{
"code": null,
"e": 543,
"s": 363,
"text": "For this article we’ll be using the Breast Cancer Wisconsin data set from the UCI Machine learning repo as our data. Go ahead and load it for yourself if you want to follow along:"
},
{
"code": null,
"e": 844,
"s": 543,
"text": "wdbc <- read.csv(\"wdbc.csv\", header = F)features <- c(\"radius\", \"texture\", \"perimeter\", \"area\", \"smoothness\", \"compactness\", \"concavity\", \"concave_points\", \"symmetry\", \"fractal_dimension\")names(wdbc) <- c(\"id\", \"diagnosis\", paste0(features,\"_mean\"), paste0(features,\"_se\"), paste0(features,\"_worst\"))"
},
{
"code": null,
"e": 972,
"s": 844,
"text": "The code above will simply load the data and name all 32 variables. The ID, diagnosis and ten distinct (30) features. From UCI:"
},
{
"code": null,
"e": 1219,
"s": 972,
"text": "“The mean, standard error, and “worst” or largest (mean of the three largest values) of these features were computed for each image, resulting in 30 features. For instance, field 3 is Mean Radius, field 13 is Radius SE, field 23 is Worst Radius.”"
},
{
"code": null,
"e": 1366,
"s": 1219,
"text": "Right, so now we’ve loaded our data and find ourselves with 30 variables (thus excluding our response “diagnosis” and the irrelevant ID-variable)."
},
{
"code": null,
"e": 1558,
"s": 1366,
"text": "Now some of you might be saying “30 variable is a lot” and some might say “Pfft.. Only 30? I’ve worked with THOUSANDS!!” but rest assured that this is equally applicable in either scenario..!"
},
{
"code": null,
"e": 2006,
"s": 1558,
"text": "There’s a few pretty good reasons to use PCA. The plot at the very beginning af the article is a great example of how one would plot multi-dimensional data by using PCA, we actually capture 63.3% (Dim1 44.3% + Dim2 19%) of variance in the entire dataset by just using those two principal components, pretty good when taking into consideration that the original data consisted of 30 features which would be impossible to plot in any meaningful way."
},
{
"code": null,
"e": 2482,
"s": 2006,
"text": "A very powerful consideration is to acknowledge that we never specified a response variable or anything else in our PCA-plot indicating whether a tumor was “benign” or “malignant”. It simply turns out that when we try to describe variance in the data using the linear combinations of the PCA we find some pretty obvious clustering and separation between the “benign” and “malignant” tumors! This makes a great case for developing a classification model based on our features!"
},
{
"code": null,
"e": 2655,
"s": 2482,
"text": "Another major “feature” (no pun intended) of PCA is that it can actually directly improve performance of your models, please take a look at this great article to read more:"
},
{
"code": null,
"e": 2678,
"s": 2655,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 3286,
"s": 2678,
"text": "Lets get something out the way immediately, PCAs primary purpose is NOT as a ways of feature removal! PCA can reduce dimensionality but it wont reduce the number of features / variables in your data. What this means is that you might discover that you can explain 99% of variance in your 1000 feature dataset by just using 3 principal components but you still need those 1000 features to construct those 3 principal components, this also means that in the case of predicting on future data you still need those same 1000 features on your new observations to construct the corresponding principal components."
},
{
"code": null,
"e": 3392,
"s": 3286,
"text": "Since this is purely introductory I’ll skip the math and give you a quick rundown of the workings of PCA:"
},
{
"code": null,
"e": 3433,
"s": 3392,
"text": "Standardize the data (Center and scale)."
},
{
"code": null,
"e": 3577,
"s": 3433,
"text": "Calculate the Eigenvectors and Eigenvalues from the covariance matrix or correlation matrix (One could also use Singular Vector Decomposition)."
},
{
"code": null,
"e": 3737,
"s": 3577,
"text": "Sort the Eigenvalues in descending order and choose the K largest Eigenvectors (Where K is the desired number of dimensions of the new feature subspace k ≤ d)."
},
{
"code": null,
"e": 3805,
"s": 3737,
"text": "Construct the projection matrix W from the selected K Eigenvectors."
},
{
"code": null,
"e": 3890,
"s": 3805,
"text": "Transform the original dataset X via W to obtain a K-dimensional feature subspace Y."
},
{
"code": null,
"e": 4189,
"s": 3890,
"text": "This might sound a bit complicated if you haven’t had a few courses in algebra, but the gist of it is to transform our data from it’s initial state X to a subspace Y with K dimensions where K is — more often than not — less than the original dimensions of X. Thankfully this is easily done using R!"
},
{
"code": null,
"e": 4297,
"s": 4189,
"text": "So now we understand a bit about how PCA works and that should be enough for now. Lets actually try it out:"
},
{
"code": null,
"e": 4375,
"s": 4297,
"text": "wdbc.pr <- prcomp(wdbc[c(3:32)], center = TRUE, scale = TRUE)summary(wdbc.pr)"
},
{
"code": null,
"e": 4666,
"s": 4375,
"text": "This is pretty self-explanatory, the ‘prcomp’ function runs PCA on the data we supply it, in our case that’s ‘wdbc[c(3:32)]’ which is our data excluding the ID and diagnosis variables, then we tell R to center and scale our data (thus standardizing the data). Finally we call for a summary:"
},
{
"code": null,
"e": 4840,
"s": 4666,
"text": "Recall that a property of PCA is that our components are sorted from largest to smallest with regard to their standard deviation (Eigenvalues). So let’s make sense of these:"
},
{
"code": null,
"e": 4962,
"s": 4840,
"text": "Standard deviation: This is simply the eigenvalues in our case since the data has been centered and scaled (standardized)"
},
{
"code": null,
"e": 5120,
"s": 4962,
"text": "Proportion of Variance: This is the amount of variance the component accounts for in the data, ie. PC1 accounts for >44% of total variance in the data alone!"
},
{
"code": null,
"e": 5311,
"s": 5120,
"text": "Cumulative Proportion: This is simply the accumulated amount of explained variance, ie. if we used the first 10 components we would be able to account for >95% of total variance in the data."
},
{
"code": null,
"e": 5566,
"s": 5311,
"text": "Right, so how many components do we want? We obviously want to be able to explain as much variance as possible but to do that we would need all 30 components, at the same time we want to reduce the number of dimensions so we definitely want less than 30!"
},
{
"code": null,
"e": 6007,
"s": 5566,
"text": "Since we standardized our data and we now have the corresponding eigenvalues of each PC we can actually use these to draw a boundary for us. Since an eigenvalues <1 would mean that the component actually explains less than a single explanatory variable we would like to discard those. If our data is well suited for PCA we should be able to discard these components while retaining at least 70–80% of cumulative variance. Lets plot and see:"
},
{
"code": null,
"e": 6514,
"s": 6007,
"text": "screeplot(wdbc.pr, type = \"l\", npcs = 15, main = \"Screeplot of the first 10 PCs\")abline(h = 1, col=\"red\", lty=5)legend(\"topright\", legend=c(\"Eigenvalue = 1\"), col=c(\"red\"), lty=5, cex=0.6)cumpro <- cumsum(wdbc.pr$sdev^2 / sum(wdbc.pr$sdev^2))plot(cumpro[0:15], xlab = \"PC #\", ylab = \"Amount of explained variance\", main = \"Cumulative variance plot\")abline(v = 6, col=\"blue\", lty=5)abline(h = 0.88759, col=\"blue\", lty=5)legend(\"topleft\", legend=c(\"Cut-off @ PC6\"), col=c(\"blue\"), lty=5, cex=0.6)"
},
{
"code": null,
"e": 6726,
"s": 6514,
"text": "We notice is that the first 6 components has an Eigenvalue >1 and explains almost 90% of variance, this is great! We can effectively reduce dimensionality from 30 to 6 while only “loosing” about 10% of variance!"
},
{
"code": null,
"e": 6858,
"s": 6726,
"text": "We also notice that we can actually explain more than 60% of variance with just the first two components. Let’s try plotting these:"
},
{
"code": null,
"e": 6959,
"s": 6858,
"text": "plot(wdbc.pr$x[,1],wdbc.pr$x[,2], xlab=\"PC1 (44.3%)\", ylab = \"PC2 (19%)\", main = \"PC1 / PC2 - plot\")"
},
{
"code": null,
"e": 7437,
"s": 6959,
"text": "Alright, this isn’t really too telling but consider for a moment that this is representing 60%+ of variance in a 30 dimensional dataset. But what do we see from this? There’s some clustering going on in the upper/middle-right. Lets also consider for a moment what the goal of this analysis actually is. We want to explain difference between malignant and benign tumors. Let’s actually add the response variable (diagnosis) to the plot and see if we can make better sense of it:"
},
{
"code": null,
"e": 7903,
"s": 7437,
"text": "library(\"factoextra\")fviz_pca_ind(wdbc.pr, geom.ind = \"point\", pointshape = 21, pointsize = 2, fill.ind = wdbc$diagnosis, col.ind = \"black\", palette = \"jco\", addEllipses = TRUE, label = \"var\", col.var = \"black\", repel = TRUE, legend.title = \"Diagnosis\") + ggtitle(\"2D PCA-plot from 30 feature dataset\") + theme(plot.title = element_text(hjust = 0.5))"
},
{
"code": null,
"e": 8294,
"s": 7903,
"text": "This is essentially the exact same plot with some fancy ellipses and colors corresponding to the diagnosis of the subject and now we see the beauty of PCA. With just the first two components we can clearly see some separation between the benign and malignant tumors. This is a clear indication that the data is well-suited for some kind of classification model (like discriminant analysis)."
},
{
"code": null,
"e": 8506,
"s": 8294,
"text": "Our next immediate goal is to construct some kind of model using the first 6 principal components to predict whether a tumor is benign or malignant and then compare it to a model using the original 30 variables."
},
{
"code": null,
"e": 8553,
"s": 8506,
"text": "We’ll take a look at this in the next article:"
},
{
"code": null,
"e": 8576,
"s": 8553,
"text": "towardsdatascience.com"
}
] |
Convex Polygon in C++ | Suppose we have a list of points that form a polygon when joined sequentially, we have to find if this polygon is convex (Convex polygon definition). We have to keep in mind that there are at least 3 and at most 10,000 points. And the coordinates are in the range -10,000 to 10,000.
We can assume the polygon formed by given points is always a simple polygon, in other words, we ensure that exactly two edges intersect at each vertex and that edges otherwise don't intersect each other. So if the input is like: [[0,0],[0,1],[1,1],[1,0]], then it is convex, so returned value will be true.
To solve this, we will follow these steps −
Define a method calc(), this will take ax, ay, bx, by, cx, cy, this will work as follows −
Define a method calc(), this will take ax, ay, bx, by, cx, cy, this will work as follows −
BAx := ax – bx, BAy := ay – by, BCx := cx – bx, BCy := cy - by
BAx := ax – bx, BAy := ay – by, BCx := cx – bx, BCy := cy - by
From the main method do the following
From the main method do the following
neg := false and pos := false, n := size of points array
neg := false and pos := false, n := size of points array
for i in range 0 to n – 1a := i, b := (i + 1) mod n and c := (i + 2) mod ncross_prod := calc(p[a, 0], p[a, 1], p[b, 0], p[b, 1], p[c, 0], p[c, 1])if cross_prod < 0, then neg := true, otherwise when cross_prod > 0, then pos := trueif neg and pos is true, then return false
for i in range 0 to n – 1
a := i, b := (i + 1) mod n and c := (i + 2) mod n
a := i, b := (i + 1) mod n and c := (i + 2) mod n
cross_prod := calc(p[a, 0], p[a, 1], p[b, 0], p[b, 1], p[c, 0], p[c, 1])
cross_prod := calc(p[a, 0], p[a, 1], p[b, 0], p[b, 1], p[c, 0], p[c, 1])
if cross_prod < 0, then neg := true, otherwise when cross_prod > 0, then pos := true
if cross_prod < 0, then neg := true, otherwise when cross_prod > 0, then pos := true
if neg and pos is true, then return false
if neg and pos is true, then return false
return true
return true
Let us see the following implementation to get a better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool isConvex(vector<vector<int>>& points) {
bool neg = false;
bool pos = false;
int n = points.size();
for(int i = 0; i < n; i++){
int a = i;
int b = (i + 1) % n;
int c = (i + 2) % n;
int crossProduct = calc(points[a][0], points[a][1], points[b][0], points[b][1], points[c][0], points[c][1]);
if(crossProduct < 0) neg = true;
else if(crossProduct > 0) pos = true;
if(neg && pos) return false;
}
return true;
}
int calc(int ax, int ay, int bx, int by, int cx, int cy){
int BAx = ax - bx;
int BAy = ay - by;
int BCx = cx - bx;
int BCy = cy - by;
return (BAx * BCy - BAy * BCx);
}
};
main(){
vector<vector<int>> v = {{0,0},{0,1},{1,1},{1,0}};
Solution ob;
cout << (ob.isConvex(v));
}
[[0,0],[0,1],[1,1],[1,0]]
1 | [
{
"code": null,
"e": 1345,
"s": 1062,
"text": "Suppose we have a list of points that form a polygon when joined sequentially, we have to find if this polygon is convex (Convex polygon definition). We have to keep in mind that there are at least 3 and at most 10,000 points. And the coordinates are in the range -10,000 to 10,000."
},
{
"code": null,
"e": 1652,
"s": 1345,
"text": "We can assume the polygon formed by given points is always a simple polygon, in other words, we ensure that exactly two edges intersect at each vertex and that edges otherwise don't intersect each other. So if the input is like: [[0,0],[0,1],[1,1],[1,0]], then it is convex, so returned value will be true."
},
{
"code": null,
"e": 1696,
"s": 1652,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1787,
"s": 1696,
"text": "Define a method calc(), this will take ax, ay, bx, by, cx, cy, this will work as follows −"
},
{
"code": null,
"e": 1878,
"s": 1787,
"text": "Define a method calc(), this will take ax, ay, bx, by, cx, cy, this will work as follows −"
},
{
"code": null,
"e": 1941,
"s": 1878,
"text": "BAx := ax – bx, BAy := ay – by, BCx := cx – bx, BCy := cy - by"
},
{
"code": null,
"e": 2004,
"s": 1941,
"text": "BAx := ax – bx, BAy := ay – by, BCx := cx – bx, BCy := cy - by"
},
{
"code": null,
"e": 2042,
"s": 2004,
"text": "From the main method do the following"
},
{
"code": null,
"e": 2080,
"s": 2042,
"text": "From the main method do the following"
},
{
"code": null,
"e": 2137,
"s": 2080,
"text": "neg := false and pos := false, n := size of points array"
},
{
"code": null,
"e": 2194,
"s": 2137,
"text": "neg := false and pos := false, n := size of points array"
},
{
"code": null,
"e": 2466,
"s": 2194,
"text": "for i in range 0 to n – 1a := i, b := (i + 1) mod n and c := (i + 2) mod ncross_prod := calc(p[a, 0], p[a, 1], p[b, 0], p[b, 1], p[c, 0], p[c, 1])if cross_prod < 0, then neg := true, otherwise when cross_prod > 0, then pos := trueif neg and pos is true, then return false"
},
{
"code": null,
"e": 2492,
"s": 2466,
"text": "for i in range 0 to n – 1"
},
{
"code": null,
"e": 2542,
"s": 2492,
"text": "a := i, b := (i + 1) mod n and c := (i + 2) mod n"
},
{
"code": null,
"e": 2592,
"s": 2542,
"text": "a := i, b := (i + 1) mod n and c := (i + 2) mod n"
},
{
"code": null,
"e": 2665,
"s": 2592,
"text": "cross_prod := calc(p[a, 0], p[a, 1], p[b, 0], p[b, 1], p[c, 0], p[c, 1])"
},
{
"code": null,
"e": 2738,
"s": 2665,
"text": "cross_prod := calc(p[a, 0], p[a, 1], p[b, 0], p[b, 1], p[c, 0], p[c, 1])"
},
{
"code": null,
"e": 2823,
"s": 2738,
"text": "if cross_prod < 0, then neg := true, otherwise when cross_prod > 0, then pos := true"
},
{
"code": null,
"e": 2908,
"s": 2823,
"text": "if cross_prod < 0, then neg := true, otherwise when cross_prod > 0, then pos := true"
},
{
"code": null,
"e": 2950,
"s": 2908,
"text": "if neg and pos is true, then return false"
},
{
"code": null,
"e": 2992,
"s": 2950,
"text": "if neg and pos is true, then return false"
},
{
"code": null,
"e": 3004,
"s": 2992,
"text": "return true"
},
{
"code": null,
"e": 3016,
"s": 3004,
"text": "return true"
},
{
"code": null,
"e": 3088,
"s": 3016,
"text": "Let us see the following implementation to get a better understanding −"
},
{
"code": null,
"e": 3099,
"s": 3088,
"text": " Live Demo"
},
{
"code": null,
"e": 4002,
"s": 3099,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\npublic:\n bool isConvex(vector<vector<int>>& points) {\n bool neg = false;\n bool pos = false;\n int n = points.size();\n for(int i = 0; i < n; i++){\n int a = i;\n int b = (i + 1) % n;\n int c = (i + 2) % n;\n int crossProduct = calc(points[a][0], points[a][1], points[b][0], points[b][1], points[c][0], points[c][1]);\n if(crossProduct < 0) neg = true;\n else if(crossProduct > 0) pos = true;\n if(neg && pos) return false;\n }\n return true;\n }\n int calc(int ax, int ay, int bx, int by, int cx, int cy){\n int BAx = ax - bx;\n int BAy = ay - by;\n int BCx = cx - bx;\n int BCy = cy - by;\n return (BAx * BCy - BAy * BCx);\n }\n};\nmain(){\n vector<vector<int>> v = {{0,0},{0,1},{1,1},{1,0}};\n Solution ob;\n cout << (ob.isConvex(v));\n}"
},
{
"code": null,
"e": 4028,
"s": 4002,
"text": "[[0,0],[0,1],[1,1],[1,0]]"
},
{
"code": null,
"e": 4030,
"s": 4028,
"text": "1"
}
] |
Java program to print all distinct elements of a given integer array in Java | All distinct elements of an array are printed i.e. all the elements in the array are printed only once and duplicate elements are not printed. An example of this is given as follows.
Array = 1 5 9 1 4 9 6 5 9 7
Distinct elements of above array = 1 5 9 4 6 7
A program that demonstrates this is given as follows.
Live Demo
public class Example {
public static void main (String[] args) {
int arr[] = {1, 5, 9, 1, 4, 9, 6, 5, 9, 7};
int n = arr.length;
int i, j;
System.out.print("The array is: ");
for (i = 0; i < n; ++i)
System.out.print(arr[i] + " ");
System.out.print("\nThe distinct elements of above array are: ");
for (i = 0; i < n; i++) {
for (j = 0; j < i; j++)
if (arr[i] == arr[j])
break;
if (i == j)
System.out.print( arr[i] + " ");
}
}
}
The array is: 1 5 9 1 4 9 6 5 9 7
The distinct elements of above array are: 1 5 9 4 6 7
Now let us understand the above program.
First the original array is displayed. This array may contain duplicate elements. The code snippet that demonstrates this is given as follows −
System.out.print("The array is: ");
for (i = 0; i < n; ++i)
System.out.print(arr[i] + " ");
Now, a nested for loop is used to make sure only distinct elements of the array are displayed. The outer loop runs from 0 to n and the inner loop makes sure that an element is printed only if has not occured before. The code snippet that demonstrates this is given as follows −
System.out.print("\nThe distinct elements of above array are: ");
for (i = 0; i < n; i++) {
for (j = 0; j < i; j++)
if (arr[i] == arr[j])
break;
if (i == j)
System.out.print( arr[i] + " ");
} | [
{
"code": null,
"e": 1245,
"s": 1062,
"text": "All distinct elements of an array are printed i.e. all the elements in the array are printed only once and duplicate elements are not printed. An example of this is given as follows."
},
{
"code": null,
"e": 1320,
"s": 1245,
"text": "Array = 1 5 9 1 4 9 6 5 9 7\nDistinct elements of above array = 1 5 9 4 6 7"
},
{
"code": null,
"e": 1374,
"s": 1320,
"text": "A program that demonstrates this is given as follows."
},
{
"code": null,
"e": 1385,
"s": 1374,
"text": " Live Demo"
},
{
"code": null,
"e": 1920,
"s": 1385,
"text": "public class Example {\n public static void main (String[] args) {\n int arr[] = {1, 5, 9, 1, 4, 9, 6, 5, 9, 7};\n int n = arr.length;\n int i, j;\n System.out.print(\"The array is: \");\n for (i = 0; i < n; ++i)\n System.out.print(arr[i] + \" \");\n System.out.print(\"\\nThe distinct elements of above array are: \");\n for (i = 0; i < n; i++) {\n for (j = 0; j < i; j++)\n if (arr[i] == arr[j])\n break;\n if (i == j)\n System.out.print( arr[i] + \" \");\n }\n }\n}"
},
{
"code": null,
"e": 2008,
"s": 1920,
"text": "The array is: 1 5 9 1 4 9 6 5 9 7\nThe distinct elements of above array are: 1 5 9 4 6 7"
},
{
"code": null,
"e": 2049,
"s": 2008,
"text": "Now let us understand the above program."
},
{
"code": null,
"e": 2193,
"s": 2049,
"text": "First the original array is displayed. This array may contain duplicate elements. The code snippet that demonstrates this is given as follows −"
},
{
"code": null,
"e": 2285,
"s": 2193,
"text": "System.out.print(\"The array is: \");\nfor (i = 0; i < n; ++i)\nSystem.out.print(arr[i] + \" \");"
},
{
"code": null,
"e": 2563,
"s": 2285,
"text": "Now, a nested for loop is used to make sure only distinct elements of the array are displayed. The outer loop runs from 0 to n and the inner loop makes sure that an element is printed only if has not occured before. The code snippet that demonstrates this is given as follows −"
},
{
"code": null,
"e": 2770,
"s": 2563,
"text": "System.out.print(\"\\nThe distinct elements of above array are: \");\nfor (i = 0; i < n; i++) {\n for (j = 0; j < i; j++)\n if (arr[i] == arr[j])\n break;\n if (i == j)\n System.out.print( arr[i] + \" \");\n}"
}
] |
Bootstrap - Panels | This chapter will discuss about Bootstrap panels. Panel components are used when you want to put your DOM component in a box. To get a basic panel, just add class .panel to the <div> element. Also add class .panel-default to this element as shown in the following example −
<div class = "panel panel-default">
<div class = "panel-body">
This is a Basic panel
</div>
</div>
There are two ways to add panel heading −
Use .panel-heading class to easily add a heading container to your panel.
Use .panel-heading class to easily add a heading container to your panel.
Use any <h1>-<h6> with a .panel-title class to add a pre-styled heading.
Use any <h1>-<h6> with a .panel-title class to add a pre-styled heading.
The following example demonstrates both the ways −
<div class = "panel panel-default">
<div class = "panel-heading">
Panel heading without title
</div>
<div class = "panel-body">
Panel content
</div>
</div>
<div class = "panel panel-default">
<div class = "panel-heading">
<h3 class = "panel-title">
Panel With title
</h3>
</div>
<div class = "panel-body">
Panel content
</div>
</div>
You can add footers to panels, by wrapping buttons or secondary text in a <div> containing class .panel-footer. The following example demonstrates this.
<div class = "panel panel-default">
<div class = "panel-body">
This is a Basic panel
</div>
<div class = "panel-footer">Panel footer</div>
</div>
Use contextual state classes such as, panel-primary, panel-success, panel-info, panel-warning, panel-danger, to make a panel more meaningful to a particular context.
<div class = "panel panel-primary">
<div class = "panel-heading">
<h3 class = "panel-title">Panel title</h3>
</div>
<div class = "panel-body">
This is a Basic panel
</div>
</div>
<div class = "panel panel-success">
<div class = "panel-heading">
<h3 class = "panel-title">Panel title</h3>
</div>
<div class = "panel-body">
This is a Basic panel
</div>
</div>
<div class = "panel panel-info">
<div class = "panel-heading">
<h3 class = "panel-title">Panel title</h3>
</div>
<div class = "panel-body">
This is a Basic panel
</div>
</div>
<div class = "panel panel-warning">
<div class = "panel-heading">
<h3 class = "panel-title">Panel title</h3>
</div>
<div class = "panel-body">
This is a Basic panel
</div>
</div>
<div class = "panel panel-danger">
<div class = "panel-heading">
<h3 class = "panel-title">Panel title</h3>
</div>
<div class = "panel-body">
This is a Basic panel
</div>
</div>
To get a non-bordered table within a panel, use the class .table within the panel. Suppose there is a <div> containing .panel-body, we add an extra border to the top of the table for separation. If there is no <div> containing .panel-body, then the component moves from panel header to table without interruption.
The following example demonstrates this −
<div class = "panel panel-default">
<div class = "panel-heading">
<h3 class = "panel-title">Panel title</h3>
</div>
<div class = "panel-body">
This is a Basic panel
</div>
<table class = "table">
<tr>
<th>Product</th>
<th>Price </th>
</tr>
<tr>
<td>Product A</td>
<td>200</td>
</tr>
<tr>
<td>Product B</td>
<td>400</td>
</tr>
</table>
</div>
<div class = "panel panel-default">
<div class = "panel-heading">Panel Heading</div>
<table class = "table">
<tr>
<th>Product</th>
<th>Price </th>
</tr>
<tr>
<td>Product A</td>
<td>200</td>
</tr>
<tr>
<td>Product B</td>
<td>400</td>
</tr>
</table>
</div>
You can include list groups within any panel. Create a panel by adding class .panel to the <div> element. Also add class .panel-default to this element. Now within this panel include your list groups. You can learn to create a list group from chapter List Groups.
<div class = "panel panel-default">
<div class ="panel-heading">Panel heading</div>
<div class = "panel-body">
<p>This is a Basic panel content. This is a Basic panel content.
This is a Basic panel content. This is a Basic panel content.
This is a Basic panel content. This is a Basic panel content.
This is a Basic panel content.</p>
</div>
<ul class = "list-group">
<li class = "list-group-item">Free Domain Name Registration</li>
<li class = "list-group-item">Free Window Space hosting</li>
<li class = "list-group-item">Number of Images</li>
<li class = "list-group-item">24*7 support</li>
<li class = "list-group-item">Renewal cost per year</li>
</ul>
</div>
This is a Basic panel content. This is a Basic panel content.
This is a Basic panel content.This is a Basic panel content.
This is a Basic panel content.This is a Basic panel content.
This is a Basic panel content.
Free Domain Name Registration
Free Window Space hosting
Number of Images
24*7 support
Renewal cost per year
26 Lectures
2 hours
Anadi Sharma
54 Lectures
4.5 hours
Frahaan Hussain
161 Lectures
14.5 hours
Eduonix Learning Solutions
20 Lectures
4 hours
Azaz Patel
15 Lectures
1.5 hours
Muhammad Ismail
62 Lectures
8 hours
Yossef Ayman Zedan
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3605,
"s": 3331,
"text": "This chapter will discuss about Bootstrap panels. Panel components are used when you want to put your DOM component in a box. To get a basic panel, just add class .panel to the <div> element. Also add class .panel-default to this element as shown in the following example −"
},
{
"code": null,
"e": 3716,
"s": 3605,
"text": "<div class = \"panel panel-default\">\n <div class = \"panel-body\">\n This is a Basic panel\n </div>\n</div>"
},
{
"code": null,
"e": 3758,
"s": 3716,
"text": "There are two ways to add panel heading −"
},
{
"code": null,
"e": 3832,
"s": 3758,
"text": "Use .panel-heading class to easily add a heading container to your panel."
},
{
"code": null,
"e": 3906,
"s": 3832,
"text": "Use .panel-heading class to easily add a heading container to your panel."
},
{
"code": null,
"e": 3979,
"s": 3906,
"text": "Use any <h1>-<h6> with a .panel-title class to add a pre-styled heading."
},
{
"code": null,
"e": 4052,
"s": 3979,
"text": "Use any <h1>-<h6> with a .panel-title class to add a pre-styled heading."
},
{
"code": null,
"e": 4103,
"s": 4052,
"text": "The following example demonstrates both the ways −"
},
{
"code": null,
"e": 4509,
"s": 4103,
"text": "<div class = \"panel panel-default\">\n <div class = \"panel-heading\">\n Panel heading without title\n </div>\n \n <div class = \"panel-body\">\n Panel content\n </div>\n</div>\n\n<div class = \"panel panel-default\">\n <div class = \"panel-heading\">\n <h3 class = \"panel-title\">\n Panel With title\n </h3>\n </div>\n \n <div class = \"panel-body\">\n Panel content\n </div>\n</div>"
},
{
"code": null,
"e": 4663,
"s": 4509,
"text": "You can add footers to panels, by wrapping buttons or secondary text in a <div> containing class .panel-footer. The following example demonstrates this."
},
{
"code": null,
"e": 4828,
"s": 4663,
"text": "<div class = \"panel panel-default\">\n <div class = \"panel-body\">\n This is a Basic panel\n </div>\n \n <div class = \"panel-footer\">Panel footer</div>\n</div>"
},
{
"code": null,
"e": 4994,
"s": 4828,
"text": "Use contextual state classes such as, panel-primary, panel-success, panel-info, panel-warning, panel-danger, to make a panel more meaningful to a particular context."
},
{
"code": null,
"e": 6029,
"s": 4994,
"text": "<div class = \"panel panel-primary\">\n <div class = \"panel-heading\">\n <h3 class = \"panel-title\">Panel title</h3>\n </div>\n \n <div class = \"panel-body\">\n This is a Basic panel\n </div>\n</div>\n\n<div class = \"panel panel-success\">\n <div class = \"panel-heading\">\n <h3 class = \"panel-title\">Panel title</h3>\n </div>\n \n <div class = \"panel-body\">\n This is a Basic panel\n </div>\n</div>\n\n<div class = \"panel panel-info\">\n <div class = \"panel-heading\">\n <h3 class = \"panel-title\">Panel title</h3>\n </div>\n \n <div class = \"panel-body\">\n This is a Basic panel\n </div>\n</div>\n\n<div class = \"panel panel-warning\">\n <div class = \"panel-heading\">\n <h3 class = \"panel-title\">Panel title</h3>\n </div>\n \n <div class = \"panel-body\">\n This is a Basic panel\n </div>\n</div>\n\n<div class = \"panel panel-danger\">\n <div class = \"panel-heading\">\n <h3 class = \"panel-title\">Panel title</h3>\n </div>\n \n <div class = \"panel-body\">\n This is a Basic panel\n </div>\n</div>"
},
{
"code": null,
"e": 6344,
"s": 6029,
"text": "To get a non-bordered table within a panel, use the class .table within the panel. Suppose there is a <div> containing .panel-body, we add an extra border to the top of the table for separation. If there is no <div> containing .panel-body, then the component moves from panel header to table without interruption."
},
{
"code": null,
"e": 6386,
"s": 6344,
"text": "The following example demonstrates this −"
},
{
"code": null,
"e": 7243,
"s": 6386,
"text": "<div class = \"panel panel-default\">\n <div class = \"panel-heading\">\n <h3 class = \"panel-title\">Panel title</h3>\n </div>\n \n <div class = \"panel-body\">\n This is a Basic panel\n </div>\n \n <table class = \"table\">\n <tr>\n <th>Product</th>\n <th>Price </th>\n </tr>\n \n <tr>\n <td>Product A</td>\n <td>200</td>\n </tr>\n \n <tr>\n <td>Product B</td>\n <td>400</td>\n </tr>\n </table>\n</div>\n\n<div class = \"panel panel-default\">\n <div class = \"panel-heading\">Panel Heading</div>\n \n <table class = \"table\">\n <tr>\n <th>Product</th>\n <th>Price </th>\n </tr>\n \n <tr>\n <td>Product A</td>\n <td>200</td>\n </tr>\n \n <tr>\n <td>Product B</td>\n <td>400</td>\n </tr>\n </table>\n</div>"
},
{
"code": null,
"e": 7507,
"s": 7243,
"text": "You can include list groups within any panel. Create a panel by adding class .panel to the <div> element. Also add class .panel-default to this element. Now within this panel include your list groups. You can learn to create a list group from chapter List Groups."
},
{
"code": null,
"e": 8257,
"s": 7507,
"text": "<div class = \"panel panel-default\">\n <div class =\"panel-heading\">Panel heading</div>\n \n <div class = \"panel-body\">\n <p>This is a Basic panel content. This is a Basic panel content.\n This is a Basic panel content. This is a Basic panel content.\n This is a Basic panel content. This is a Basic panel content.\n This is a Basic panel content.</p>\n </div>\n \n <ul class = \"list-group\">\n <li class = \"list-group-item\">Free Domain Name Registration</li>\n <li class = \"list-group-item\">Free Window Space hosting</li>\n <li class = \"list-group-item\">Number of Images</li>\n <li class = \"list-group-item\">24*7 support</li>\n <li class = \"list-group-item\">Renewal cost per year</li>\n </ul>\n</div>"
},
{
"code": null,
"e": 8521,
"s": 8257,
"text": "This is a Basic panel content. This is a Basic panel content.\n This is a Basic panel content.This is a Basic panel content.\n This is a Basic panel content.This is a Basic panel content.\n This is a Basic panel content.\n "
},
{
"code": null,
"e": 8551,
"s": 8521,
"text": "Free Domain Name Registration"
},
{
"code": null,
"e": 8577,
"s": 8551,
"text": "Free Window Space hosting"
},
{
"code": null,
"e": 8594,
"s": 8577,
"text": "Number of Images"
},
{
"code": null,
"e": 8607,
"s": 8594,
"text": "24*7 support"
},
{
"code": null,
"e": 8629,
"s": 8607,
"text": "Renewal cost per year"
},
{
"code": null,
"e": 8662,
"s": 8629,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 8676,
"s": 8662,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 8711,
"s": 8676,
"text": "\n 54 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 8728,
"s": 8711,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 8765,
"s": 8728,
"text": "\n 161 Lectures \n 14.5 hours \n"
},
{
"code": null,
"e": 8793,
"s": 8765,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 8826,
"s": 8793,
"text": "\n 20 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 8838,
"s": 8826,
"text": " Azaz Patel"
},
{
"code": null,
"e": 8873,
"s": 8838,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 8890,
"s": 8873,
"text": " Muhammad Ismail"
},
{
"code": null,
"e": 8923,
"s": 8890,
"text": "\n 62 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 8943,
"s": 8923,
"text": " Yossef Ayman Zedan"
},
{
"code": null,
"e": 8950,
"s": 8943,
"text": " Print"
},
{
"code": null,
"e": 8961,
"s": 8950,
"text": " Add Notes"
}
] |
How to write partial title of X-axis in italics using ggplot2 of R? | Of course, writing axes titles help viewers to understand the plot in a better way because they add more information to the plot. In general, the axes titles have simple font but we can change partial or complete title to italics to get the viewers attraction. This is needed when we want to highlight the title by making it different. In ggplot2, we can do this by using expression.
Consider the below data frame −
set.seed(1)
x<-rnorm(10)
y<-rnorm(10,1)
df<-data.frame(x,y)
df
x y
1 -0.6264538 2.5117812
2 0.1836433 1.3898432
3 -0.8356286 0.3787594
4 1.5952808 -1.2146999
5 0.3295078 2.1249309
6 -0.8204684 0.9550664
7 0.4874291 0.9838097
8 0.7383247 1.9438362
9 0.5757814 1.8212212
10 -0.3053884 1.5939013
> library(ggplot2)
Creating the scatterplot between x and y −
ggplot(df,aes(x,y))+geom_point()+
+ labs(x=expression(paste("X comes from normal distribution")))
Now suppose we want to write normal distribution in italics then it can be done as shown below −
ggplot(df,aes(x,y))+geom_point()+labs(x=expression(paste("X comes from ",italic("normal distribution")))) | [
{
"code": null,
"e": 1446,
"s": 1062,
"text": "Of course, writing axes titles help viewers to understand the plot in a better way because they add more information to the plot. In general, the axes titles have simple font but we can change partial or complete title to italics to get the viewers attraction. This is needed when we want to highlight the title by making it different. In ggplot2, we can do this by using expression."
},
{
"code": null,
"e": 1478,
"s": 1446,
"text": "Consider the below data frame −"
},
{
"code": null,
"e": 1541,
"s": 1478,
"text": "set.seed(1)\nx<-rnorm(10)\ny<-rnorm(10,1)\ndf<-data.frame(x,y)\ndf"
},
{
"code": null,
"e": 1816,
"s": 1541,
"text": " x y\n1 -0.6264538 2.5117812\n2 0.1836433 1.3898432\n3 -0.8356286 0.3787594\n4 1.5952808 -1.2146999\n5 0.3295078 2.1249309\n6 -0.8204684 0.9550664\n7 0.4874291 0.9838097\n8 0.7383247 1.9438362\n9 0.5757814 1.8212212\n10 -0.3053884 1.5939013\n> library(ggplot2)"
},
{
"code": null,
"e": 1859,
"s": 1816,
"text": "Creating the scatterplot between x and y −"
},
{
"code": null,
"e": 1957,
"s": 1859,
"text": "ggplot(df,aes(x,y))+geom_point()+\n+ labs(x=expression(paste(\"X comes from normal distribution\")))"
},
{
"code": null,
"e": 2054,
"s": 1957,
"text": "Now suppose we want to write normal distribution in italics then it can be done as shown below −"
},
{
"code": null,
"e": 2160,
"s": 2054,
"text": "ggplot(df,aes(x,y))+geom_point()+labs(x=expression(paste(\"X comes from \",italic(\"normal distribution\"))))"
}
] |
Gale–Shapley algorithm simply explained | by Alexander Osipenko | Towards Data Science | From this article, you will learn about stable pairing or stable marriage problem. You will learn how to solve that problem using Game Theory and the Gale-Shapley algorithm in particular. We will use Python to create our own solution using theorem from the original paper from 1962.
In the real world, there are cases when we facing paring problem: student choosing their future universities, man and women seeking each other to create families, internet services that need to be connected with users with the smallest amount of time. In all these cases we need to create stable pairs that need to satisfied certain criteria. We can imagine a stable pair for (A, a) as a pair where no A or a have any better options.
Best way to understand it is to solve practical examples, I can recommend book Insights into Game Theory [1], it contains plenty of exercises that you can solve on paper. But here I wanna use Python to solve that :)
In our example, we will have two groups, women and man. Women’s names will start with a capital letter: A, B, C, D and men with lowercase latter: a, b, c, d. We need to create stable pairs. Before doing that we made a survey to gather some information as our starting point. Each of them was asked to rank people of the opposite sex by their personal sympathy. Where 1 place person that they like the most and 4 people they like the least.
For example, women A answered this way: d, c, a, b
In python, we can create two data frames man and women:
%pylab inline
import pandas as pd
import numpy as np
Populating the interactive namespace from numpy and matplotlib
women = pd.DataFrame({'A': [3,4,2,1], 'B': [3,1,4,2], 'C':[2,3,4,1], 'D':[3,2,1,4]})
women.index = ['a','b','c','d']
man = pd.DataFrame({'A': [1,1,2,4], 'B': [2,4,1,2], 'C':[3,3,3,3], 'D':[4,2,4,1]})
man.index = ['a','b','c','d']
man
women
In data frames, a rank was replaced by number for convenience. For example, if we wanna know the preferences of the women A, we can read column A in the women data frame: 3, 4, 2, 1 for men a, b, c, d respectively. If we wanna know the preferences of the men a we can read a row in the man data frame: 1, 2, 3, 4 for women A, B, C, D respectively.
Thus pair of man and women can be represented as a pair of numbers, for example, pair A and a will create a pair with numbers (3,1). For the women A man a is third in her list, but for the men a, women A is number one in his list.
So in this case men a is fully happy, but women A can try to create a pair with someone higher from her list, for example, man c, and if for c will be better to create a pair with A than with his current partner, both pair will collapse and create new pairs.
That is an example of an unstable pair, a pair in which one or both participants can improve the situation but creating more preferable pairs for them.
So the task is to find stable pairs for all participants. And turns out that there is a way to achieve equilibrium!
David Gale and Lloyd Shapley proved that in cases with when two sets are equal there always a way to create stable pairs. I recommend reading the original paper[2] to be familiar with the elegant prove they provided.
There are different implementations of the Gale-Shapley algorithm in Python [3, 4, 5], let’s create this algorithm closer to pseudocode solution without going into complicated OOP.
In a pseudocode solution looks like this [6]:
function stableMatching { Initialize all m ∈ M and w ∈ W to free while ∃ free man m who still has a woman w to propose to { w = first woman on m’s list to whom m has not yet proposed if w is free (m, w) become engaged else some pair (m', w) already exists if w prefers m to m' m' becomes free (m, w) become engaged else (m', w) remain engaged }}
In Python I was able to create this solution:
%pylab inline
import pandas as pd
import numpy as np
from collections import Counter
from copy import copy
Populating the interactive namespace from numpy and matplotlib
man_list = ['a', 'b', 'c', 'd']
women_list = ['A', 'B', 'C', 'D']
women_df = pd.DataFrame({'A': [3,4,2,1], 'B': [3,1,4,2], 'C':[2,3,4,1], 'D':[3,2,1,4]})
women_df.index = man_list
man_df = pd.DataFrame({'A': [1,1,2,4], 'B': [2,4,1,2], 'C':[3,3,3,3], 'D':[4,2,4,1]})
man_df.index = man_list
women_df
man_df
# dict to control which women each man can make proposals
women_available = {man:women_list for man in man_list}
# waiting list of men that were able to create pair on each iteration
waiting_list = []
# dict to store created pairs
proposals = {}
# variable to count number of iterations
count = 0
# while not all men have pairs
while len(waiting_list)<len(man_list):
# man makes proposals
for man in man_list:
if man not in waiting_list:
# each man make proposal to the top women from it's list
women = women_available[man]
best_choice = man_df.loc[man][man_df.loc[man].index.isin(women)].idxmin()
proposals[(man, best_choice)]=(man_df.loc[man][best_choice],
women_df.loc[man][best_choice])
# if women have more than one proposals
# she will choose the best option
overlays = Counter([key[1] for key in proposals.keys()])
# cycle to choose the best options
for women in overlays.keys():
if overlays[women]>1:
# pairs to drop from proposals
pairs_to_drop = sorted({pair: proposals[pair] for pair in proposals.keys()
if women in pair}.items(),
key=lambda x: x[1][1]
)[1:]
# if man was rejected by woman
# there is no pint for him to make proposal
# second time to the same woman
for p_to_drop in pairs_to_drop:
del proposals[p_to_drop[0]]
_women = copy(women_available[p_to_drop[0][0]])
_women.remove(p_to_drop[0][1])
women_available[p_to_drop[0][0]] = _women
# man who successfully created pairs must be added to the waiting list
waiting_list = [man[0] for man in proposals.keys()]
# update counter
count+=1
proposals
{('b', 'D'): (2, 2),
('d', 'B'): (2, 2),
('c', 'A'): (2, 2),
('a', 'C'): (3, 2)}
count
6
Game Theory is very fun because it operates with situations from the real world. And it’s also most of the time do not require complicated math apparatus, especially in cooperative games.
There are many things about the Gale-Shapley algorithm that we didn’t touch: general case when the number of men is not equal to the number of women and how many maximum iterations this algorithm may take.
After looking at open-source solutions I was sure that I will be able to create more minimalistic and even more Pythonic solution. But I ended up with a pretty messy while cycle...🤷♂️
Insights into Game Theory: An Alternative Mathematical Experience, Cambridge University Press, forthcoming, with Ein-Ya GuraGale D., Shapley L.S. College Admissions and the Stability of Marriage // American Mathematical Monthly. 1962. Vol. 69. P.9–15.https://rosettacode.org/wiki/Stable_marriage_problem#Pythonhttps://pypi.org/project/matching/https://github.com/QuantEcon/MatchingMarkets.pyhttps://en.wikipedia.org/wiki/Stable_marriage_problem
Insights into Game Theory: An Alternative Mathematical Experience, Cambridge University Press, forthcoming, with Ein-Ya Gura
Gale D., Shapley L.S. College Admissions and the Stability of Marriage // American Mathematical Monthly. 1962. Vol. 69. P.9–15. | [
{
"code": null,
"e": 455,
"s": 172,
"text": "From this article, you will learn about stable pairing or stable marriage problem. You will learn how to solve that problem using Game Theory and the Gale-Shapley algorithm in particular. We will use Python to create our own solution using theorem from the original paper from 1962."
},
{
"code": null,
"e": 889,
"s": 455,
"text": "In the real world, there are cases when we facing paring problem: student choosing their future universities, man and women seeking each other to create families, internet services that need to be connected with users with the smallest amount of time. In all these cases we need to create stable pairs that need to satisfied certain criteria. We can imagine a stable pair for (A, a) as a pair where no A or a have any better options."
},
{
"code": null,
"e": 1105,
"s": 889,
"text": "Best way to understand it is to solve practical examples, I can recommend book Insights into Game Theory [1], it contains plenty of exercises that you can solve on paper. But here I wanna use Python to solve that :)"
},
{
"code": null,
"e": 1545,
"s": 1105,
"text": "In our example, we will have two groups, women and man. Women’s names will start with a capital letter: A, B, C, D and men with lowercase latter: a, b, c, d. We need to create stable pairs. Before doing that we made a survey to gather some information as our starting point. Each of them was asked to rank people of the opposite sex by their personal sympathy. Where 1 place person that they like the most and 4 people they like the least."
},
{
"code": null,
"e": 1596,
"s": 1545,
"text": "For example, women A answered this way: d, c, a, b"
},
{
"code": null,
"e": 1652,
"s": 1596,
"text": "In python, we can create two data frames man and women:"
},
{
"code": null,
"e": 1706,
"s": 1652,
"text": "%pylab inline\nimport pandas as pd\nimport numpy as np\n"
},
{
"code": null,
"e": 1770,
"s": 1706,
"text": "Populating the interactive namespace from numpy and matplotlib\n"
},
{
"code": null,
"e": 1888,
"s": 1770,
"text": "women = pd.DataFrame({'A': [3,4,2,1], 'B': [3,1,4,2], 'C':[2,3,4,1], 'D':[3,2,1,4]})\nwomen.index = ['a','b','c','d']\n"
},
{
"code": null,
"e": 2002,
"s": 1888,
"text": "man = pd.DataFrame({'A': [1,1,2,4], 'B': [2,4,1,2], 'C':[3,3,3,3], 'D':[4,2,4,1]})\nman.index = ['a','b','c','d']\n"
},
{
"code": null,
"e": 2007,
"s": 2002,
"text": "man\n"
},
{
"code": null,
"e": 2014,
"s": 2007,
"text": "women\n"
},
{
"code": null,
"e": 2362,
"s": 2014,
"text": "In data frames, a rank was replaced by number for convenience. For example, if we wanna know the preferences of the women A, we can read column A in the women data frame: 3, 4, 2, 1 for men a, b, c, d respectively. If we wanna know the preferences of the men a we can read a row in the man data frame: 1, 2, 3, 4 for women A, B, C, D respectively."
},
{
"code": null,
"e": 2593,
"s": 2362,
"text": "Thus pair of man and women can be represented as a pair of numbers, for example, pair A and a will create a pair with numbers (3,1). For the women A man a is third in her list, but for the men a, women A is number one in his list."
},
{
"code": null,
"e": 2852,
"s": 2593,
"text": "So in this case men a is fully happy, but women A can try to create a pair with someone higher from her list, for example, man c, and if for c will be better to create a pair with A than with his current partner, both pair will collapse and create new pairs."
},
{
"code": null,
"e": 3004,
"s": 2852,
"text": "That is an example of an unstable pair, a pair in which one or both participants can improve the situation but creating more preferable pairs for them."
},
{
"code": null,
"e": 3120,
"s": 3004,
"text": "So the task is to find stable pairs for all participants. And turns out that there is a way to achieve equilibrium!"
},
{
"code": null,
"e": 3337,
"s": 3120,
"text": "David Gale and Lloyd Shapley proved that in cases with when two sets are equal there always a way to create stable pairs. I recommend reading the original paper[2] to be familiar with the elegant prove they provided."
},
{
"code": null,
"e": 3518,
"s": 3337,
"text": "There are different implementations of the Gale-Shapley algorithm in Python [3, 4, 5], let’s create this algorithm closer to pseudocode solution without going into complicated OOP."
},
{
"code": null,
"e": 3564,
"s": 3518,
"text": "In a pseudocode solution looks like this [6]:"
},
{
"code": null,
"e": 3993,
"s": 3564,
"text": "function stableMatching { Initialize all m ∈ M and w ∈ W to free while ∃ free man m who still has a woman w to propose to { w = first woman on m’s list to whom m has not yet proposed if w is free (m, w) become engaged else some pair (m', w) already exists if w prefers m to m' m' becomes free (m, w) become engaged else (m', w) remain engaged }}"
},
{
"code": null,
"e": 4039,
"s": 3993,
"text": "In Python I was able to create this solution:"
},
{
"code": null,
"e": 4147,
"s": 4039,
"text": "%pylab inline\nimport pandas as pd\nimport numpy as np\nfrom collections import Counter\nfrom copy import copy\n"
},
{
"code": null,
"e": 4211,
"s": 4147,
"text": "Populating the interactive namespace from numpy and matplotlib\n"
},
{
"code": null,
"e": 4278,
"s": 4211,
"text": "man_list = ['a', 'b', 'c', 'd']\nwomen_list = ['A', 'B', 'C', 'D']\n"
},
{
"code": null,
"e": 4393,
"s": 4278,
"text": "women_df = pd.DataFrame({'A': [3,4,2,1], 'B': [3,1,4,2], 'C':[2,3,4,1], 'D':[3,2,1,4]})\nwomen_df.index = man_list\n"
},
{
"code": null,
"e": 4504,
"s": 4393,
"text": "man_df = pd.DataFrame({'A': [1,1,2,4], 'B': [2,4,1,2], 'C':[3,3,3,3], 'D':[4,2,4,1]})\nman_df.index = man_list\n"
},
{
"code": null,
"e": 4514,
"s": 4504,
"text": "women_df\n"
},
{
"code": null,
"e": 4522,
"s": 4514,
"text": "man_df\n"
},
{
"code": null,
"e": 4820,
"s": 4522,
"text": "# dict to control which women each man can make proposals\nwomen_available = {man:women_list for man in man_list}\n# waiting list of men that were able to create pair on each iteration\nwaiting_list = []\n# dict to store created pairs\nproposals = {}\n# variable to count number of iterations\ncount = 0\n"
},
{
"code": null,
"e": 6386,
"s": 4820,
"text": "# while not all men have pairs\nwhile len(waiting_list)<len(man_list):\n # man makes proposals\n for man in man_list:\n if man not in waiting_list:\n # each man make proposal to the top women from it's list\n women = women_available[man]\n best_choice = man_df.loc[man][man_df.loc[man].index.isin(women)].idxmin()\n proposals[(man, best_choice)]=(man_df.loc[man][best_choice],\n women_df.loc[man][best_choice])\n # if women have more than one proposals \n # she will choose the best option\n overlays = Counter([key[1] for key in proposals.keys()])\n # cycle to choose the best options\n for women in overlays.keys():\n if overlays[women]>1:\n # pairs to drop from proposals\n pairs_to_drop = sorted({pair: proposals[pair] for pair in proposals.keys() \n if women in pair}.items(), \n key=lambda x: x[1][1]\n )[1:]\n # if man was rejected by woman\n # there is no pint for him to make proposal \n # second time to the same woman\n for p_to_drop in pairs_to_drop:\n del proposals[p_to_drop[0]]\n _women = copy(women_available[p_to_drop[0][0]])\n _women.remove(p_to_drop[0][1])\n women_available[p_to_drop[0][0]] = _women\n # man who successfully created pairs must be added to the waiting list \n waiting_list = [man[0] for man in proposals.keys()]\n # update counter\n count+=1\n"
},
{
"code": null,
"e": 6397,
"s": 6386,
"text": "proposals\n"
},
{
"code": null,
"e": 6481,
"s": 6397,
"text": "{('b', 'D'): (2, 2),\n ('d', 'B'): (2, 2),\n ('c', 'A'): (2, 2),\n ('a', 'C'): (3, 2)}"
},
{
"code": null,
"e": 6488,
"s": 6481,
"text": "count\n"
},
{
"code": null,
"e": 6490,
"s": 6488,
"text": "6"
},
{
"code": null,
"e": 6678,
"s": 6490,
"text": "Game Theory is very fun because it operates with situations from the real world. And it’s also most of the time do not require complicated math apparatus, especially in cooperative games."
},
{
"code": null,
"e": 6884,
"s": 6678,
"text": "There are many things about the Gale-Shapley algorithm that we didn’t touch: general case when the number of men is not equal to the number of women and how many maximum iterations this algorithm may take."
},
{
"code": null,
"e": 7069,
"s": 6884,
"text": "After looking at open-source solutions I was sure that I will be able to create more minimalistic and even more Pythonic solution. But I ended up with a pretty messy while cycle...🤷♂️"
},
{
"code": null,
"e": 7514,
"s": 7069,
"text": "Insights into Game Theory: An Alternative Mathematical Experience, Cambridge University Press, forthcoming, with Ein-Ya GuraGale D., Shapley L.S. College Admissions and the Stability of Marriage // American Mathematical Monthly. 1962. Vol. 69. P.9–15.https://rosettacode.org/wiki/Stable_marriage_problem#Pythonhttps://pypi.org/project/matching/https://github.com/QuantEcon/MatchingMarkets.pyhttps://en.wikipedia.org/wiki/Stable_marriage_problem"
},
{
"code": null,
"e": 7639,
"s": 7514,
"text": "Insights into Game Theory: An Alternative Mathematical Experience, Cambridge University Press, forthcoming, with Ein-Ya Gura"
}
] |
Bulma | Card - GeeksforGeeks | 23 Jun, 2020
Bulma is a free and open-source CSS framework based on Flexbox. It is component rich, compatible, and well documented. It is highly responsive in nature. It uses classes to implement its design.
A Card is a flexible component that can be composed of the content needed. It includes several other components that we have to add exclusively to design our content well. These components are listed below:
card-header: It is a horizontal box type component with a shadow.card-header-title: It is left aligned and bold which is used to represent the header of the card.card-header-icon: It is a placeholder for the icon that is added to the header part of the card.
card-header-title: It is left aligned and bold which is used to represent the header of the card.
card-header-icon: It is a placeholder for the icon that is added to the header part of the card.
card-image: It is a container for including a responsive image.
card-content: It is a container where one can insert any element like paragraphs, icons, buttons or images.
footer: It is a container used to store the footer elements of the card. card-footer-item: It reserved spaces for list of footer items.
card-footer-item: It reserved spaces for list of footer items.
Example 1: This example represents how to create a simple card using Bulma.
html
<!DOCTYPE html><html> <head> <title>Bulma Card</title> <!-- Include Bulma CSS --> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- Custom CSS --> <style> div.columns { margin-top: 80px; } p { font-family: calibri; font-size: 20px; } p.has-text-danger { margin-left: 95px; } </style></head> <body> <div class='container has-text-centered'> <div class='columns is-mobile is-centered'> <div class='column is-5'> <div class="card"> <div class="card-content"> <p class='is-success'> GeeksforGeeks' is a computer science portal.it was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction . </p> <p class='has-text-danger'> ___A computer science portal for geeks </p> </div> </div> </div> </div> </div></body></html>
Output:
Example 2: This example creating a card with header using Bulma.
html
<!DOCTYPE html><html> <head> <title>Bulma Card</title> <!-- Include Bulma CSS --> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- Custom CSS --> <style> div.columns { margin-top: 80px; } p { font-family: calibri; font-size: 20px; } p.has-text-danger { margin-left: 90px; } .card-header-title { font-size: 20px; } </style></head> <body> <div class='container has-text-centered'> <div class='columns is-mobile is-centered'> <div class='column is-5'> <div class="card"> <div class='card-header'> <div class="card-header-title has-text-success"> GeekforGeeks </div> </div> <div class="card-content"> <p class='is-success'> GeeksforGeeks' is a computer science portal.it was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction . </p> <p class='has-text-danger'> ___A computer science portal for geeks </p> </div> </div> </div> </div> </div></body></html>
Output:
Example 3: This example creating a card with header and footer using Bulma.
html
<!DOCTYPE html><html> <head> <title>Bulma Card</title> <!-- Include Bulma CSS --> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- Custom CSS --> <style> div.columns { margin-top: 80px; } p { font-family: calibri; font-size: 20px; } .card-header-title { font-size: 20px; } span { margin-left: 95px; } </style></head> <body> <div class='container has-text-centered'> <div class='columns is-mobile is-centered'> <div class='column is-5'> <div class="card"> <div class='card-header'> <div class="card-header-title has-text-success"> GeekforGeeks </div> </div> <div class="card-content"> <p class='is-success'> GeeksforGeeks' is a computer science portal.it was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction . </p> </div> <div> <footer class="card-footer"> <p class='card-footer-item'> <span class='has-text-danger'> ___A computer science portal for geeks </span> </p> </footer> </div> </div> </div> </div> </div></body></html>
Output:
Example 4: This example creating a card with an image using Bulma.
html
<!DOCTYPE html><html> <head> <title>Bulma Card</title> <!-- Include Bulma CSS --> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- Custom CSS --> <style> div.columns { margin-top: 20px; } p { font-family: calibri; font-size: 20px; } .card-header-title { font-size: 20px; } </style></head> <body> <div class='container has-text-centered'> <div class='columns is-mobile is-centered'> <div class='column is-5'> <div class="card"> <div class="card-image"> <figure class="image is-2by1"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200611151025/gfg202.png" alt="Placeholder image"> </figure> </div> <div class="card-content"> <div class="media"> <div class="media-left"> <figure class="image is-48x48"> <img src="https://media.geeksforgeeks.org/wpcontent/uploads/20200611151025/gfg202.png" alt="Placeholder image"> </figure> </div> <div class="media-content"> <p class="title is-5"> GeekforGeeks </p> <p class="subtitle is-6"> @geeksforgeeks </p> </div> </div> <div class='content'> <div class="media-content"> <p class='is-success'> GeeksforGeeks' is a computer science portal.it was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction . </p> </div> </div> </div> </div> </div> </div> </div></body></html>
Output:
Example 5: This example creating a coloured card with an image using Bulma.
html
<!DOCTYPE html><html> <head> <title>Bulma Card</title> <!-- Include Bulma CSS --> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- Custom CSS --> <style> div.columns { margin-top: 80px; } p { font-family: calibri; font-size: 20px; } .card-header-title { font-size: 20px; } </style></head> <body> <div class='container has-text-centered'> <div class='columns is-mobile is-centered'> <div class='column is-5'> <div class="card has-background-primary"> <div class="card-content"> <div class="media"> <div class="media-left"> <figure class="image is-48x48"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200611151025/gfg202.png" alt="Placeholder image"> </figure> </div> <div class="media-content"> <p class="title is-5"> GeekforGeeks </p> <p class="subtitle is-6"> @geeksforgeeks </p> </div> </div> <div class='content'> <div class="media-content"> <p class='is-success'> GeeksforGeeks' is a computer science portal.it was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction . </p> </div> </div> </div> </div> </div> </div> </div></body></html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
Bulma
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create footer to stay at the bottom of a Web page?
How to update Node.js and NPM to next version ?
CSS to put icon inside an input element in a form
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to set the default value for an HTML <select> element ?
How to update Node.js and NPM to next version ?
How to set input type date in dd-mm-yyyy format using HTML ? | [
{
"code": null,
"e": 26108,
"s": 26080,
"text": "\n23 Jun, 2020"
},
{
"code": null,
"e": 26303,
"s": 26108,
"text": "Bulma is a free and open-source CSS framework based on Flexbox. It is component rich, compatible, and well documented. It is highly responsive in nature. It uses classes to implement its design."
},
{
"code": null,
"e": 26510,
"s": 26303,
"text": "A Card is a flexible component that can be composed of the content needed. It includes several other components that we have to add exclusively to design our content well. These components are listed below:"
},
{
"code": null,
"e": 26769,
"s": 26510,
"text": "card-header: It is a horizontal box type component with a shadow.card-header-title: It is left aligned and bold which is used to represent the header of the card.card-header-icon: It is a placeholder for the icon that is added to the header part of the card."
},
{
"code": null,
"e": 26867,
"s": 26769,
"text": "card-header-title: It is left aligned and bold which is used to represent the header of the card."
},
{
"code": null,
"e": 26964,
"s": 26867,
"text": "card-header-icon: It is a placeholder for the icon that is added to the header part of the card."
},
{
"code": null,
"e": 27028,
"s": 26964,
"text": "card-image: It is a container for including a responsive image."
},
{
"code": null,
"e": 27136,
"s": 27028,
"text": "card-content: It is a container where one can insert any element like paragraphs, icons, buttons or images."
},
{
"code": null,
"e": 27272,
"s": 27136,
"text": "footer: It is a container used to store the footer elements of the card. card-footer-item: It reserved spaces for list of footer items."
},
{
"code": null,
"e": 27335,
"s": 27272,
"text": "card-footer-item: It reserved spaces for list of footer items."
},
{
"code": null,
"e": 27411,
"s": 27335,
"text": "Example 1: This example represents how to create a simple card using Bulma."
},
{
"code": null,
"e": 27416,
"s": 27411,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Bulma Card</title> <!-- Include Bulma CSS --> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- Custom CSS --> <style> div.columns { margin-top: 80px; } p { font-family: calibri; font-size: 20px; } p.has-text-danger { margin-left: 95px; } </style></head> <body> <div class='container has-text-centered'> <div class='columns is-mobile is-centered'> <div class='column is-5'> <div class=\"card\"> <div class=\"card-content\"> <p class='is-success'> GeeksforGeeks' is a computer science portal.it was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction . </p> <p class='has-text-danger'> ___A computer science portal for geeks </p> </div> </div> </div> </div> </div></body></html>",
"e": 28704,
"s": 27416,
"text": null
},
{
"code": null,
"e": 28713,
"s": 28704,
"text": "Output: "
},
{
"code": null,
"e": 28778,
"s": 28713,
"text": "Example 2: This example creating a card with header using Bulma."
},
{
"code": null,
"e": 28783,
"s": 28778,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Bulma Card</title> <!-- Include Bulma CSS --> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- Custom CSS --> <style> div.columns { margin-top: 80px; } p { font-family: calibri; font-size: 20px; } p.has-text-danger { margin-left: 90px; } .card-header-title { font-size: 20px; } </style></head> <body> <div class='container has-text-centered'> <div class='columns is-mobile is-centered'> <div class='column is-5'> <div class=\"card\"> <div class='card-header'> <div class=\"card-header-title has-text-success\"> GeekforGeeks </div> </div> <div class=\"card-content\"> <p class='is-success'> GeeksforGeeks' is a computer science portal.it was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction . </p> <p class='has-text-danger'> ___A computer science portal for geeks </p> </div> </div> </div> </div> </div></body></html>",
"e": 30301,
"s": 28783,
"text": null
},
{
"code": null,
"e": 30309,
"s": 30301,
"text": "Output:"
},
{
"code": null,
"e": 30385,
"s": 30309,
"text": "Example 3: This example creating a card with header and footer using Bulma."
},
{
"code": null,
"e": 30390,
"s": 30385,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Bulma Card</title> <!-- Include Bulma CSS --> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- Custom CSS --> <style> div.columns { margin-top: 80px; } p { font-family: calibri; font-size: 20px; } .card-header-title { font-size: 20px; } span { margin-left: 95px; } </style></head> <body> <div class='container has-text-centered'> <div class='columns is-mobile is-centered'> <div class='column is-5'> <div class=\"card\"> <div class='card-header'> <div class=\"card-header-title has-text-success\"> GeekforGeeks </div> </div> <div class=\"card-content\"> <p class='is-success'> GeeksforGeeks' is a computer science portal.it was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction . </p> </div> <div> <footer class=\"card-footer\"> <p class='card-footer-item'> <span class='has-text-danger'> ___A computer science portal for geeks </span> </p> </footer> </div> </div> </div> </div> </div></body></html>",
"e": 32045,
"s": 30390,
"text": null
},
{
"code": null,
"e": 32054,
"s": 32045,
"text": "Output: "
},
{
"code": null,
"e": 32121,
"s": 32054,
"text": "Example 4: This example creating a card with an image using Bulma."
},
{
"code": null,
"e": 32126,
"s": 32121,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Bulma Card</title> <!-- Include Bulma CSS --> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- Custom CSS --> <style> div.columns { margin-top: 20px; } p { font-family: calibri; font-size: 20px; } .card-header-title { font-size: 20px; } </style></head> <body> <div class='container has-text-centered'> <div class='columns is-mobile is-centered'> <div class='column is-5'> <div class=\"card\"> <div class=\"card-image\"> <figure class=\"image is-2by1\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200611151025/gfg202.png\" alt=\"Placeholder image\"> </figure> </div> <div class=\"card-content\"> <div class=\"media\"> <div class=\"media-left\"> <figure class=\"image is-48x48\"> <img src=\"https://media.geeksforgeeks.org/wpcontent/uploads/20200611151025/gfg202.png\" alt=\"Placeholder image\"> </figure> </div> <div class=\"media-content\"> <p class=\"title is-5\"> GeekforGeeks </p> <p class=\"subtitle is-6\"> @geeksforgeeks </p> </div> </div> <div class='content'> <div class=\"media-content\"> <p class='is-success'> GeeksforGeeks' is a computer science portal.it was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction . </p> </div> </div> </div> </div> </div> </div> </div></body></html>",
"e": 34305,
"s": 32126,
"text": null
},
{
"code": null,
"e": 34314,
"s": 34305,
"text": "Output: "
},
{
"code": null,
"e": 34390,
"s": 34314,
"text": "Example 5: This example creating a coloured card with an image using Bulma."
},
{
"code": null,
"e": 34395,
"s": 34390,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Bulma Card</title> <!-- Include Bulma CSS --> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- Custom CSS --> <style> div.columns { margin-top: 80px; } p { font-family: calibri; font-size: 20px; } .card-header-title { font-size: 20px; } </style></head> <body> <div class='container has-text-centered'> <div class='columns is-mobile is-centered'> <div class='column is-5'> <div class=\"card has-background-primary\"> <div class=\"card-content\"> <div class=\"media\"> <div class=\"media-left\"> <figure class=\"image is-48x48\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200611151025/gfg202.png\" alt=\"Placeholder image\"> </figure> </div> <div class=\"media-content\"> <p class=\"title is-5\"> GeekforGeeks </p> <p class=\"subtitle is-6\"> @geeksforgeeks </p> </div> </div> <div class='content'> <div class=\"media-content\"> <p class='is-success'> GeeksforGeeks' is a computer science portal.it was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction . </p> </div> </div> </div> </div> </div> </div> </div></body></html>",
"e": 36391,
"s": 34395,
"text": null
},
{
"code": null,
"e": 36400,
"s": 36391,
"text": "Output: "
},
{
"code": null,
"e": 36537,
"s": 36400,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 36543,
"s": 36537,
"text": "Bulma"
},
{
"code": null,
"e": 36547,
"s": 36543,
"text": "CSS"
},
{
"code": null,
"e": 36552,
"s": 36547,
"text": "HTML"
},
{
"code": null,
"e": 36569,
"s": 36552,
"text": "Web Technologies"
},
{
"code": null,
"e": 36574,
"s": 36569,
"text": "HTML"
},
{
"code": null,
"e": 36672,
"s": 36574,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36734,
"s": 36672,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 36784,
"s": 36734,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 36842,
"s": 36784,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 36890,
"s": 36842,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 36940,
"s": 36890,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 37002,
"s": 36940,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 37052,
"s": 37002,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 37112,
"s": 37052,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 37160,
"s": 37112,
"text": "How to update Node.js and NPM to next version ?"
}
] |
Lateral Keyword in SQL - GeeksforGeeks | 04 Oct, 2021
The lateral keyword represents a lateral join between two or more tables. It joins the output of the outer query with the output of the underlying lateral subquery. It is like a for-each loop in SQL where the subquery iterates through each row of the concerned table, evaluating the subquery for each row.
The output rows returned by the inner subquery are then added to the result of the join with the outer query. Without Lateral, each subquery would be evaluated independent of each others and could not refer to the items in the table referenced in the outer query.
Syntax of Lateral: A Lateral join is denoted by the keyword Lateral which precedes the inner subquery, as shown below:
SELECT <Column Name>
FROM <Reference Table Name>
LATERAL <Inner Subquery>
Example: Let us assume that we have to find the top 3 students of a class with the highest marks. The query would be a simple one as follows:
SELECT studId, marks
FROM student
ORDER BY marks DESC FETCH FIRST 3 ROWS ONLY
Now assuming that each class has ‘n’ sections and we need to find section-wise top 3 students with the highest marks. Now we would need to join the section tables to get the result and find the top 3 students using the Rank() function. The query would be like this:
SELECT secId, studId, marks
FROM ( SELECT sec.secId, stud.studId, stud.marks,
RANK() OVER (PARTITION BY sec.secId ORDER BY marks DESC) rn
FROM student stud, section sec WHERE sec.secId = stud.secId )
WHERE rn <= 3
This is where Lateral comes to the rescue. We will use our first query where we fetched the top 3 students with the highest marks as the inner subquery. Next, we join the Section table with the inner subquery using the Lateral keyword. The inner query which is to the right of Lateral would be evaluated for every single row in the left table. Here’s how the query would look like:
SELECT sec.secId, stud.studId, stud.marks
FROM section sec,
LATERAL (SELECT studId, marks FROM student stud
WHERE sec.secId = stud.secId
ORDER BY marks DESC FETCH FIRST 3 ROWS ONLY)
Why Use Lateral ? In simple terms, Lateral provides a simpler and cleaner approach for returning more than one columns as the output. Although since the inner subquery has to run for every row of the main query, it makes the query a little slow. Some important applications of Lateral keyword are aggregation of two or more tables and in activity logs where logging might require a lot of temporary data.
varshachoudhary
SQL-basics
DBMS
SQL
Write From Home
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Types of Functional dependencies in DBMS
Introduction of Relational Algebra in DBMS
KDD Process in Data Mining
Structure of Database Management System
Difference between File System and DBMS
SQL | DDL, DQL, DML, DCL and TCL Commands
How to find Nth highest salary from a table
SQL | ALTER (RENAME)
How to Update Multiple Columns in Single Update Statement in SQL?
How to Alter Multiple Columns at Once in SQL Server? | [
{
"code": null,
"e": 24328,
"s": 24300,
"text": "\n04 Oct, 2021"
},
{
"code": null,
"e": 24635,
"s": 24328,
"text": "The lateral keyword represents a lateral join between two or more tables. It joins the output of the outer query with the output of the underlying lateral subquery. It is like a for-each loop in SQL where the subquery iterates through each row of the concerned table, evaluating the subquery for each row. "
},
{
"code": null,
"e": 24900,
"s": 24635,
"text": "The output rows returned by the inner subquery are then added to the result of the join with the outer query. Without Lateral, each subquery would be evaluated independent of each others and could not refer to the items in the table referenced in the outer query. "
},
{
"code": null,
"e": 25020,
"s": 24900,
"text": "Syntax of Lateral: A Lateral join is denoted by the keyword Lateral which precedes the inner subquery, as shown below: "
},
{
"code": null,
"e": 25097,
"s": 25022,
"text": "SELECT <Column Name>\nFROM <Reference Table Name>\nLATERAL <Inner Subquery> "
},
{
"code": null,
"e": 25240,
"s": 25097,
"text": "Example: Let us assume that we have to find the top 3 students of a class with the highest marks. The query would be a simple one as follows: "
},
{
"code": null,
"e": 25323,
"s": 25242,
"text": "SELECT studId, marks \nFROM student \nORDER BY marks DESC FETCH FIRST 3 ROWS ONLY "
},
{
"code": null,
"e": 25590,
"s": 25323,
"text": "Now assuming that each class has ‘n’ sections and we need to find section-wise top 3 students with the highest marks. Now we would need to join the section tables to get the result and find the top 3 students using the Rank() function. The query would be like this: "
},
{
"code": null,
"e": 25824,
"s": 25592,
"text": "SELECT secId, studId, marks \nFROM ( SELECT sec.secId, stud.studId, stud.marks, \n RANK() OVER (PARTITION BY sec.secId ORDER BY marks DESC) rn \n FROM student stud, section sec WHERE sec.secId = stud.secId )\nWHERE rn <= 3 "
},
{
"code": null,
"e": 26207,
"s": 25824,
"text": "This is where Lateral comes to the rescue. We will use our first query where we fetched the top 3 students with the highest marks as the inner subquery. Next, we join the Section table with the inner subquery using the Lateral keyword. The inner query which is to the right of Lateral would be evaluated for every single row in the left table. Here’s how the query would look like: "
},
{
"code": null,
"e": 26413,
"s": 26209,
"text": "SELECT sec.secId, stud.studId, stud.marks \nFROM section sec,\nLATERAL (SELECT studId, marks FROM student stud \n WHERE sec.secId = stud.secId \n ORDER BY marks DESC FETCH FIRST 3 ROWS ONLY) "
},
{
"code": null,
"e": 26819,
"s": 26413,
"text": "Why Use Lateral ? In simple terms, Lateral provides a simpler and cleaner approach for returning more than one columns as the output. Although since the inner subquery has to run for every row of the main query, it makes the query a little slow. Some important applications of Lateral keyword are aggregation of two or more tables and in activity logs where logging might require a lot of temporary data. "
},
{
"code": null,
"e": 26835,
"s": 26819,
"text": "varshachoudhary"
},
{
"code": null,
"e": 26846,
"s": 26835,
"text": "SQL-basics"
},
{
"code": null,
"e": 26851,
"s": 26846,
"text": "DBMS"
},
{
"code": null,
"e": 26855,
"s": 26851,
"text": "SQL"
},
{
"code": null,
"e": 26871,
"s": 26855,
"text": "Write From Home"
},
{
"code": null,
"e": 26876,
"s": 26871,
"text": "DBMS"
},
{
"code": null,
"e": 26880,
"s": 26876,
"text": "SQL"
},
{
"code": null,
"e": 26978,
"s": 26880,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26987,
"s": 26978,
"text": "Comments"
},
{
"code": null,
"e": 27000,
"s": 26987,
"text": "Old Comments"
},
{
"code": null,
"e": 27041,
"s": 27000,
"text": "Types of Functional dependencies in DBMS"
},
{
"code": null,
"e": 27084,
"s": 27041,
"text": "Introduction of Relational Algebra in DBMS"
},
{
"code": null,
"e": 27111,
"s": 27084,
"text": "KDD Process in Data Mining"
},
{
"code": null,
"e": 27151,
"s": 27111,
"text": "Structure of Database Management System"
},
{
"code": null,
"e": 27191,
"s": 27151,
"text": "Difference between File System and DBMS"
},
{
"code": null,
"e": 27233,
"s": 27191,
"text": "SQL | DDL, DQL, DML, DCL and TCL Commands"
},
{
"code": null,
"e": 27277,
"s": 27233,
"text": "How to find Nth highest salary from a table"
},
{
"code": null,
"e": 27298,
"s": 27277,
"text": "SQL | ALTER (RENAME)"
},
{
"code": null,
"e": 27364,
"s": 27298,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
}
] |
Aggregation in LINQ | Performs any type of desired aggregation and allows creating custom aggregations in LINQ.
Module Module1
Sub Main()
Dim num As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9}
Dim intDivByTwo = Aggregate n In num
Where n > 6
Into Count()
Console.WriteLine("Count of Numbers: " & intDivByTwo)
Dim intResult = Aggregate n In num
Where n > 6
Into Average()
Console.WriteLine("Average of Numbers: " & intResult)
intResult = Aggregate n In num
Where n > 6
Into LongCount()
Console.WriteLine("Long Count of Numbers: " & intResult)
intResult = Aggregate n In num
Into Max()
Console.WriteLine("Max of Numbers: " & intResult)
intResult = Aggregate n In num
Into Min()
Console.WriteLine("Min of Numbers: " & intResult)
intResult = Aggregate n In num
Into Sum()
Console.WriteLine("Sum of Numbers: " & intResult)
Console.ReadLine()
End Sub
End Module
When the above VB code is compiled and executed, it produces the following result −
Count of Numbers: 3
Average of Numbers: 8
Long Count of Numbers: 3
Max of Numbers: 9
Min of Numbers: 1
Sum of Numbers: 45
23 Lectures
1.5 hours
Anadi Sharma
37 Lectures
13 hours
Trevoir Williams
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1826,
"s": 1736,
"text": "Performs any type of desired aggregation and allows creating custom aggregations in LINQ."
},
{
"code": null,
"e": 2886,
"s": 1826,
"text": "Module Module1\n\n Sub Main()\n \n Dim num As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9}\n\n Dim intDivByTwo = Aggregate n In num\n Where n > 6\n Into Count()\n Console.WriteLine(\"Count of Numbers: \" & intDivByTwo)\n\n Dim intResult = Aggregate n In num\n Where n > 6\n Into Average()\n\t\t\t\t\t\t\t\n Console.WriteLine(\"Average of Numbers: \" & intResult)\n\n intResult = Aggregate n In num\n Where n > 6\n Into LongCount()\n\t\t\t\t\t \n Console.WriteLine(\"Long Count of Numbers: \" & intResult)\n\n intResult = Aggregate n In num\n Into Max()\n\t\t\t\t\t \n Console.WriteLine(\"Max of Numbers: \" & intResult)\n\n intResult = Aggregate n In num\n Into Min()\n\t\t\t\t\t \n Console.WriteLine(\"Min of Numbers: \" & intResult)\n\n intResult = Aggregate n In num\n Into Sum()\n\t\t\t\t\t \n Console.WriteLine(\"Sum of Numbers: \" & intResult)\n\n Console.ReadLine()\n\n End Sub\n \nEnd Module"
},
{
"code": null,
"e": 2970,
"s": 2886,
"text": "When the above VB code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 3093,
"s": 2970,
"text": "Count of Numbers: 3\nAverage of Numbers: 8\nLong Count of Numbers: 3\nMax of Numbers: 9\nMin of Numbers: 1\nSum of Numbers: 45\n"
},
{
"code": null,
"e": 3128,
"s": 3093,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3142,
"s": 3128,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3176,
"s": 3142,
"text": "\n 37 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3194,
"s": 3176,
"text": " Trevoir Williams"
},
{
"code": null,
"e": 3201,
"s": 3194,
"text": " Print"
},
{
"code": null,
"e": 3212,
"s": 3201,
"text": " Add Notes"
}
] |
Abstract Data Types - GeeksforGeeks | 19 Sep, 2019
Abstract Data type (ADT) is a type (or class) for objects whose behaviour is defined by a set of value and a set of operations.
The definition of ADT only mentions what operations are to be performed but not how these operations will be implemented. It does not specify how data will be organized in memory and what algorithms will be used for implementing the operations. It is called “abstract” because it gives an implementation-independent view. The process of providing only the essentials and hiding the details is known as abstraction.
The user of data type does not need to know how that data type is implemented, for example, we have been using Primitive values like int, float, char data types only with the knowledge that these data type can operate and be performed on without any idea of how they are implemented. So a user only needs to know what a data type can do, but not how it will be implemented. Think of ADT as a black box which hides the inner structure and design of the data type. Now we’ll define three ADTs namely List ADT, Stack ADT, Queue ADT.
List ADTThe data is generally stored in key sequence in a list which has a head structure consisting of count, pointers and address of compare function needed to compare the data in the list.The data node contains the pointer to a data structure and a self-referential pointer which points to the next node in the list.//List ADT Type Definitionstypedef struct node{ void *DataPtr; struct node *link;} Node;typedef struct{ int count; Node *pos; Node *head; Node *rear; int (*compare) (void *argument1, void *argument2)} LIST; The List ADT Functions is given below:A list contains elements of the same type arranged in sequential order and following operations can be performed on the list.get() – Return an element from the list at any given position.insert() – Insert an element at any position of the list.remove() – Remove the first occurrence of any element from a non-empty list.removeAt() – Remove the element at a specified location from a non-empty list.replace() – Replace an element at any position by another element.size() – Return the number of elements in the list.isEmpty() – Return true if the list is empty, otherwise return false.isFull() – Return true if the list is full, otherwise return false.Stack ADTIn Stack ADT Implementation instead of data being stored in each node, the pointer to data is stored.The program allocates memory for the data and address is passed to the stack ADT.The head node and the data nodes are encapsulated in the ADT. The calling function can only see the pointer to the stack.The stack head structure also contains a pointer to top and count of number of entries currently in stack.//Stack ADT Type Definitionstypedef struct node{ void *DataPtr; struct node *link;} StackNode;typedef struct{ int count; StackNode *top;} STACK;A Stack contains elements of the same type arranged in sequential order. All operations take place at a single end that is top of the stack and following operations can be performed:push() – Insert an element at one end of the stack called top.pop() – Remove and return the element at the top of the stack, if it is not empty.peek() – Return the element at the top of the stack without removing it, if the stack is not empty.size() – Return the number of elements in the stack.isEmpty() – Return true if the stack is empty, otherwise return false.isFull() – Return true if the stack is full, otherwise return false.Queue ADTThe queue abstract data type (ADT) follows the basic design of the stack abstract data type.Each node contains a void pointer to the data and the link pointer to the next element in the queue. The program’s responsibility is to allocate memory for storing the data.//Queue ADT Type Definitionstypedef struct node{ void *DataPtr; struct node *next;} QueueNode;typedef struct { QueueNode *front; QueueNode *rear; int count;} QUEUE;A Queue contains elements of the same type arranged in sequential order. Operations take place at both ends, insertion is done at the end and deletion is done at the front. Following operations can be performed:enqueue() – Insert an element at the end of the queue.dequeue() – Remove and return the first element of the queue, if the queue is not empty.peek() – Return the element of the queue without removing it, if the queue is not empty.size() – Return the number of elements in the queue.isEmpty() – Return true if the queue is empty, otherwise return false.isFull() – Return true if the queue is full, otherwise return false.
List ADTThe data is generally stored in key sequence in a list which has a head structure consisting of count, pointers and address of compare function needed to compare the data in the list.The data node contains the pointer to a data structure and a self-referential pointer which points to the next node in the list.//List ADT Type Definitionstypedef struct node{ void *DataPtr; struct node *link;} Node;typedef struct{ int count; Node *pos; Node *head; Node *rear; int (*compare) (void *argument1, void *argument2)} LIST; The List ADT Functions is given below:A list contains elements of the same type arranged in sequential order and following operations can be performed on the list.get() – Return an element from the list at any given position.insert() – Insert an element at any position of the list.remove() – Remove the first occurrence of any element from a non-empty list.removeAt() – Remove the element at a specified location from a non-empty list.replace() – Replace an element at any position by another element.size() – Return the number of elements in the list.isEmpty() – Return true if the list is empty, otherwise return false.isFull() – Return true if the list is full, otherwise return false.
The data is generally stored in key sequence in a list which has a head structure consisting of count, pointers and address of compare function needed to compare the data in the list.
The data node contains the pointer to a data structure and a self-referential pointer which points to the next node in the list.//List ADT Type Definitionstypedef struct node{ void *DataPtr; struct node *link;} Node;typedef struct{ int count; Node *pos; Node *head; Node *rear; int (*compare) (void *argument1, void *argument2)} LIST;
//List ADT Type Definitionstypedef struct node{ void *DataPtr; struct node *link;} Node;typedef struct{ int count; Node *pos; Node *head; Node *rear; int (*compare) (void *argument1, void *argument2)} LIST;
The List ADT Functions is given below:
A list contains elements of the same type arranged in sequential order and following operations can be performed on the list.
get() – Return an element from the list at any given position.
insert() – Insert an element at any position of the list.
remove() – Remove the first occurrence of any element from a non-empty list.
removeAt() – Remove the element at a specified location from a non-empty list.
replace() – Replace an element at any position by another element.
size() – Return the number of elements in the list.
isEmpty() – Return true if the list is empty, otherwise return false.
isFull() – Return true if the list is full, otherwise return false.
Stack ADTIn Stack ADT Implementation instead of data being stored in each node, the pointer to data is stored.The program allocates memory for the data and address is passed to the stack ADT.The head node and the data nodes are encapsulated in the ADT. The calling function can only see the pointer to the stack.The stack head structure also contains a pointer to top and count of number of entries currently in stack.//Stack ADT Type Definitionstypedef struct node{ void *DataPtr; struct node *link;} StackNode;typedef struct{ int count; StackNode *top;} STACK;A Stack contains elements of the same type arranged in sequential order. All operations take place at a single end that is top of the stack and following operations can be performed:push() – Insert an element at one end of the stack called top.pop() – Remove and return the element at the top of the stack, if it is not empty.peek() – Return the element at the top of the stack without removing it, if the stack is not empty.size() – Return the number of elements in the stack.isEmpty() – Return true if the stack is empty, otherwise return false.isFull() – Return true if the stack is full, otherwise return false.
In Stack ADT Implementation instead of data being stored in each node, the pointer to data is stored.
The program allocates memory for the data and address is passed to the stack ADT.
The head node and the data nodes are encapsulated in the ADT. The calling function can only see the pointer to the stack.
The stack head structure also contains a pointer to top and count of number of entries currently in stack.//Stack ADT Type Definitionstypedef struct node{ void *DataPtr; struct node *link;} StackNode;typedef struct{ int count; StackNode *top;} STACK;
//Stack ADT Type Definitionstypedef struct node{ void *DataPtr; struct node *link;} StackNode;typedef struct{ int count; StackNode *top;} STACK;
A Stack contains elements of the same type arranged in sequential order. All operations take place at a single end that is top of the stack and following operations can be performed:
push() – Insert an element at one end of the stack called top.
pop() – Remove and return the element at the top of the stack, if it is not empty.
peek() – Return the element at the top of the stack without removing it, if the stack is not empty.
size() – Return the number of elements in the stack.
isEmpty() – Return true if the stack is empty, otherwise return false.
isFull() – Return true if the stack is full, otherwise return false.
Queue ADTThe queue abstract data type (ADT) follows the basic design of the stack abstract data type.Each node contains a void pointer to the data and the link pointer to the next element in the queue. The program’s responsibility is to allocate memory for storing the data.//Queue ADT Type Definitionstypedef struct node{ void *DataPtr; struct node *next;} QueueNode;typedef struct { QueueNode *front; QueueNode *rear; int count;} QUEUE;A Queue contains elements of the same type arranged in sequential order. Operations take place at both ends, insertion is done at the end and deletion is done at the front. Following operations can be performed:enqueue() – Insert an element at the end of the queue.dequeue() – Remove and return the first element of the queue, if the queue is not empty.peek() – Return the element of the queue without removing it, if the queue is not empty.size() – Return the number of elements in the queue.isEmpty() – Return true if the queue is empty, otherwise return false.isFull() – Return true if the queue is full, otherwise return false.
The queue abstract data type (ADT) follows the basic design of the stack abstract data type.
Each node contains a void pointer to the data and the link pointer to the next element in the queue. The program’s responsibility is to allocate memory for storing the data.//Queue ADT Type Definitionstypedef struct node{ void *DataPtr; struct node *next;} QueueNode;typedef struct { QueueNode *front; QueueNode *rear; int count;} QUEUE;
//Queue ADT Type Definitionstypedef struct node{ void *DataPtr; struct node *next;} QueueNode;typedef struct { QueueNode *front; QueueNode *rear; int count;} QUEUE;
A Queue contains elements of the same type arranged in sequential order. Operations take place at both ends, insertion is done at the end and deletion is done at the front. Following operations can be performed:
enqueue() – Insert an element at the end of the queue.
dequeue() – Remove and return the first element of the queue, if the queue is not empty.
peek() – Return the element of the queue without removing it, if the queue is not empty.
size() – Return the number of elements in the queue.
isEmpty() – Return true if the queue is empty, otherwise return false.
isFull() – Return true if the queue is full, otherwise return false.
From these definitions, we can clearly see that the definitions do not specify how these ADTs will be represented and how the operations will be carried out. There can be different ways to implement an ADT, for example, the List ADT can be implemented using arrays, or singly linked list or doubly linked list. Similarly, stack ADT and Queue ADT can be implemented using arrays or linked lists.
Reference: https://en.wikipedia.org/wiki/Abstract_data_type
This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
JunMo
ranadeepika2409
Data Structures
Data Structures
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
Introduction to Algorithms
Insertion and Deletion in Heaps
Introduction to Tree Data Structure
Hash Map in Python
Differences and Applications of List, Tuple, Set and Dictionary in Python
Priority Queue using Binary Heap
Time complexities of different data structures
Insert a node at a specific position in a linked list | [
{
"code": null,
"e": 25078,
"s": 25050,
"text": "\n19 Sep, 2019"
},
{
"code": null,
"e": 25206,
"s": 25078,
"text": "Abstract Data type (ADT) is a type (or class) for objects whose behaviour is defined by a set of value and a set of operations."
},
{
"code": null,
"e": 25621,
"s": 25206,
"text": "The definition of ADT only mentions what operations are to be performed but not how these operations will be implemented. It does not specify how data will be organized in memory and what algorithms will be used for implementing the operations. It is called “abstract” because it gives an implementation-independent view. The process of providing only the essentials and hiding the details is known as abstraction."
},
{
"code": null,
"e": 26151,
"s": 25621,
"text": "The user of data type does not need to know how that data type is implemented, for example, we have been using Primitive values like int, float, char data types only with the knowledge that these data type can operate and be performed on without any idea of how they are implemented. So a user only needs to know what a data type can do, but not how it will be implemented. Think of ADT as a black box which hides the inner structure and design of the data type. Now we’ll define three ADTs namely List ADT, Stack ADT, Queue ADT."
},
{
"code": null,
"e": 29613,
"s": 26151,
"text": "List ADTThe data is generally stored in key sequence in a list which has a head structure consisting of count, pointers and address of compare function needed to compare the data in the list.The data node contains the pointer to a data structure and a self-referential pointer which points to the next node in the list.//List ADT Type Definitionstypedef struct node{ void *DataPtr; struct node *link;} Node;typedef struct{ int count; Node *pos; Node *head; Node *rear; int (*compare) (void *argument1, void *argument2)} LIST; The List ADT Functions is given below:A list contains elements of the same type arranged in sequential order and following operations can be performed on the list.get() – Return an element from the list at any given position.insert() – Insert an element at any position of the list.remove() – Remove the first occurrence of any element from a non-empty list.removeAt() – Remove the element at a specified location from a non-empty list.replace() – Replace an element at any position by another element.size() – Return the number of elements in the list.isEmpty() – Return true if the list is empty, otherwise return false.isFull() – Return true if the list is full, otherwise return false.Stack ADTIn Stack ADT Implementation instead of data being stored in each node, the pointer to data is stored.The program allocates memory for the data and address is passed to the stack ADT.The head node and the data nodes are encapsulated in the ADT. The calling function can only see the pointer to the stack.The stack head structure also contains a pointer to top and count of number of entries currently in stack.//Stack ADT Type Definitionstypedef struct node{ void *DataPtr; struct node *link;} StackNode;typedef struct{ int count; StackNode *top;} STACK;A Stack contains elements of the same type arranged in sequential order. All operations take place at a single end that is top of the stack and following operations can be performed:push() – Insert an element at one end of the stack called top.pop() – Remove and return the element at the top of the stack, if it is not empty.peek() – Return the element at the top of the stack without removing it, if the stack is not empty.size() – Return the number of elements in the stack.isEmpty() – Return true if the stack is empty, otherwise return false.isFull() – Return true if the stack is full, otherwise return false.Queue ADTThe queue abstract data type (ADT) follows the basic design of the stack abstract data type.Each node contains a void pointer to the data and the link pointer to the next element in the queue. The program’s responsibility is to allocate memory for storing the data.//Queue ADT Type Definitionstypedef struct node{ void *DataPtr; struct node *next;} QueueNode;typedef struct { QueueNode *front; QueueNode *rear; int count;} QUEUE;A Queue contains elements of the same type arranged in sequential order. Operations take place at both ends, insertion is done at the end and deletion is done at the front. Following operations can be performed:enqueue() – Insert an element at the end of the queue.dequeue() – Remove and return the first element of the queue, if the queue is not empty.peek() – Return the element of the queue without removing it, if the queue is not empty.size() – Return the number of elements in the queue.isEmpty() – Return true if the queue is empty, otherwise return false.isFull() – Return true if the queue is full, otherwise return false."
},
{
"code": null,
"e": 30829,
"s": 29613,
"text": "List ADTThe data is generally stored in key sequence in a list which has a head structure consisting of count, pointers and address of compare function needed to compare the data in the list.The data node contains the pointer to a data structure and a self-referential pointer which points to the next node in the list.//List ADT Type Definitionstypedef struct node{ void *DataPtr; struct node *link;} Node;typedef struct{ int count; Node *pos; Node *head; Node *rear; int (*compare) (void *argument1, void *argument2)} LIST; The List ADT Functions is given below:A list contains elements of the same type arranged in sequential order and following operations can be performed on the list.get() – Return an element from the list at any given position.insert() – Insert an element at any position of the list.remove() – Remove the first occurrence of any element from a non-empty list.removeAt() – Remove the element at a specified location from a non-empty list.replace() – Replace an element at any position by another element.size() – Return the number of elements in the list.isEmpty() – Return true if the list is empty, otherwise return false.isFull() – Return true if the list is full, otherwise return false."
},
{
"code": null,
"e": 31013,
"s": 30829,
"text": "The data is generally stored in key sequence in a list which has a head structure consisting of count, pointers and address of compare function needed to compare the data in the list."
},
{
"code": null,
"e": 31349,
"s": 31013,
"text": "The data node contains the pointer to a data structure and a self-referential pointer which points to the next node in the list.//List ADT Type Definitionstypedef struct node{ void *DataPtr; struct node *link;} Node;typedef struct{ int count; Node *pos; Node *head; Node *rear; int (*compare) (void *argument1, void *argument2)} LIST; "
},
{
"code": "//List ADT Type Definitionstypedef struct node{ void *DataPtr; struct node *link;} Node;typedef struct{ int count; Node *pos; Node *head; Node *rear; int (*compare) (void *argument1, void *argument2)} LIST; ",
"e": 31557,
"s": 31349,
"text": null
},
{
"code": null,
"e": 31596,
"s": 31557,
"text": "The List ADT Functions is given below:"
},
{
"code": null,
"e": 31722,
"s": 31596,
"text": "A list contains elements of the same type arranged in sequential order and following operations can be performed on the list."
},
{
"code": null,
"e": 31785,
"s": 31722,
"text": "get() – Return an element from the list at any given position."
},
{
"code": null,
"e": 31843,
"s": 31785,
"text": "insert() – Insert an element at any position of the list."
},
{
"code": null,
"e": 31920,
"s": 31843,
"text": "remove() – Remove the first occurrence of any element from a non-empty list."
},
{
"code": null,
"e": 31999,
"s": 31920,
"text": "removeAt() – Remove the element at a specified location from a non-empty list."
},
{
"code": null,
"e": 32066,
"s": 31999,
"text": "replace() – Replace an element at any position by another element."
},
{
"code": null,
"e": 32118,
"s": 32066,
"text": "size() – Return the number of elements in the list."
},
{
"code": null,
"e": 32188,
"s": 32118,
"text": "isEmpty() – Return true if the list is empty, otherwise return false."
},
{
"code": null,
"e": 32256,
"s": 32188,
"text": "isFull() – Return true if the list is full, otherwise return false."
},
{
"code": null,
"e": 33434,
"s": 32256,
"text": "Stack ADTIn Stack ADT Implementation instead of data being stored in each node, the pointer to data is stored.The program allocates memory for the data and address is passed to the stack ADT.The head node and the data nodes are encapsulated in the ADT. The calling function can only see the pointer to the stack.The stack head structure also contains a pointer to top and count of number of entries currently in stack.//Stack ADT Type Definitionstypedef struct node{ void *DataPtr; struct node *link;} StackNode;typedef struct{ int count; StackNode *top;} STACK;A Stack contains elements of the same type arranged in sequential order. All operations take place at a single end that is top of the stack and following operations can be performed:push() – Insert an element at one end of the stack called top.pop() – Remove and return the element at the top of the stack, if it is not empty.peek() – Return the element at the top of the stack without removing it, if the stack is not empty.size() – Return the number of elements in the stack.isEmpty() – Return true if the stack is empty, otherwise return false.isFull() – Return true if the stack is full, otherwise return false."
},
{
"code": null,
"e": 33536,
"s": 33434,
"text": "In Stack ADT Implementation instead of data being stored in each node, the pointer to data is stored."
},
{
"code": null,
"e": 33618,
"s": 33536,
"text": "The program allocates memory for the data and address is passed to the stack ADT."
},
{
"code": null,
"e": 33740,
"s": 33618,
"text": "The head node and the data nodes are encapsulated in the ADT. The calling function can only see the pointer to the stack."
},
{
"code": null,
"e": 33991,
"s": 33740,
"text": "The stack head structure also contains a pointer to top and count of number of entries currently in stack.//Stack ADT Type Definitionstypedef struct node{ void *DataPtr; struct node *link;} StackNode;typedef struct{ int count; StackNode *top;} STACK;"
},
{
"code": "//Stack ADT Type Definitionstypedef struct node{ void *DataPtr; struct node *link;} StackNode;typedef struct{ int count; StackNode *top;} STACK;",
"e": 34136,
"s": 33991,
"text": null
},
{
"code": null,
"e": 34319,
"s": 34136,
"text": "A Stack contains elements of the same type arranged in sequential order. All operations take place at a single end that is top of the stack and following operations can be performed:"
},
{
"code": null,
"e": 34382,
"s": 34319,
"text": "push() – Insert an element at one end of the stack called top."
},
{
"code": null,
"e": 34465,
"s": 34382,
"text": "pop() – Remove and return the element at the top of the stack, if it is not empty."
},
{
"code": null,
"e": 34565,
"s": 34465,
"text": "peek() – Return the element at the top of the stack without removing it, if the stack is not empty."
},
{
"code": null,
"e": 34618,
"s": 34565,
"text": "size() – Return the number of elements in the stack."
},
{
"code": null,
"e": 34689,
"s": 34618,
"text": "isEmpty() – Return true if the stack is empty, otherwise return false."
},
{
"code": null,
"e": 34758,
"s": 34689,
"text": "isFull() – Return true if the stack is full, otherwise return false."
},
{
"code": null,
"e": 35828,
"s": 34758,
"text": "Queue ADTThe queue abstract data type (ADT) follows the basic design of the stack abstract data type.Each node contains a void pointer to the data and the link pointer to the next element in the queue. The program’s responsibility is to allocate memory for storing the data.//Queue ADT Type Definitionstypedef struct node{ void *DataPtr; struct node *next;} QueueNode;typedef struct { QueueNode *front; QueueNode *rear; int count;} QUEUE;A Queue contains elements of the same type arranged in sequential order. Operations take place at both ends, insertion is done at the end and deletion is done at the front. Following operations can be performed:enqueue() – Insert an element at the end of the queue.dequeue() – Remove and return the first element of the queue, if the queue is not empty.peek() – Return the element of the queue without removing it, if the queue is not empty.size() – Return the number of elements in the queue.isEmpty() – Return true if the queue is empty, otherwise return false.isFull() – Return true if the queue is full, otherwise return false."
},
{
"code": null,
"e": 35921,
"s": 35828,
"text": "The queue abstract data type (ADT) follows the basic design of the stack abstract data type."
},
{
"code": null,
"e": 36259,
"s": 35921,
"text": "Each node contains a void pointer to the data and the link pointer to the next element in the queue. The program’s responsibility is to allocate memory for storing the data.//Queue ADT Type Definitionstypedef struct node{ void *DataPtr; struct node *next;} QueueNode;typedef struct { QueueNode *front; QueueNode *rear; int count;} QUEUE;"
},
{
"code": "//Queue ADT Type Definitionstypedef struct node{ void *DataPtr; struct node *next;} QueueNode;typedef struct { QueueNode *front; QueueNode *rear; int count;} QUEUE;",
"e": 36424,
"s": 36259,
"text": null
},
{
"code": null,
"e": 36636,
"s": 36424,
"text": "A Queue contains elements of the same type arranged in sequential order. Operations take place at both ends, insertion is done at the end and deletion is done at the front. Following operations can be performed:"
},
{
"code": null,
"e": 36691,
"s": 36636,
"text": "enqueue() – Insert an element at the end of the queue."
},
{
"code": null,
"e": 36780,
"s": 36691,
"text": "dequeue() – Remove and return the first element of the queue, if the queue is not empty."
},
{
"code": null,
"e": 36869,
"s": 36780,
"text": "peek() – Return the element of the queue without removing it, if the queue is not empty."
},
{
"code": null,
"e": 36922,
"s": 36869,
"text": "size() – Return the number of elements in the queue."
},
{
"code": null,
"e": 36993,
"s": 36922,
"text": "isEmpty() – Return true if the queue is empty, otherwise return false."
},
{
"code": null,
"e": 37062,
"s": 36993,
"text": "isFull() – Return true if the queue is full, otherwise return false."
},
{
"code": null,
"e": 37457,
"s": 37062,
"text": "From these definitions, we can clearly see that the definitions do not specify how these ADTs will be represented and how the operations will be carried out. There can be different ways to implement an ADT, for example, the List ADT can be implemented using arrays, or singly linked list or doubly linked list. Similarly, stack ADT and Queue ADT can be implemented using arrays or linked lists."
},
{
"code": null,
"e": 37517,
"s": 37457,
"text": "Reference: https://en.wikipedia.org/wiki/Abstract_data_type"
},
{
"code": null,
"e": 37817,
"s": 37517,
"text": "This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 37942,
"s": 37817,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 37948,
"s": 37942,
"text": "JunMo"
},
{
"code": null,
"e": 37964,
"s": 37948,
"text": "ranadeepika2409"
},
{
"code": null,
"e": 37980,
"s": 37964,
"text": "Data Structures"
},
{
"code": null,
"e": 37996,
"s": 37980,
"text": "Data Structures"
},
{
"code": null,
"e": 38094,
"s": 37996,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38143,
"s": 38094,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 38168,
"s": 38143,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 38195,
"s": 38168,
"text": "Introduction to Algorithms"
},
{
"code": null,
"e": 38227,
"s": 38195,
"text": "Insertion and Deletion in Heaps"
},
{
"code": null,
"e": 38263,
"s": 38227,
"text": "Introduction to Tree Data Structure"
},
{
"code": null,
"e": 38282,
"s": 38263,
"text": "Hash Map in Python"
},
{
"code": null,
"e": 38356,
"s": 38282,
"text": "Differences and Applications of List, Tuple, Set and Dictionary in Python"
},
{
"code": null,
"e": 38389,
"s": 38356,
"text": "Priority Queue using Binary Heap"
},
{
"code": null,
"e": 38436,
"s": 38389,
"text": "Time complexities of different data structures"
}
] |
How do I customize the display of edge labels using networkx in Matplotlib? | To set the networkx edge labels offset, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Initialize a graph with edges, name, or graph attributes.
Add multiple nodes.
Position the nodes using Fruchterman-Reingold force-directed algorithm.
Draw the graph G with Matplotlib.
Draw edge labels.
To display the figure, use show() method.
import matplotlib.pylab as plt
import networkx as nx
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
G = nx.DiGraph()
G.add_nodes_from([1, 2, 3, 4])
G.add_edges_from([(1, 2), (2, 3), (3, 4), (4, 1), (1, 3)])
pos = nx.spring_layout(G)
for u, v, d in G.edges(data=True):
d['weight'] = 3
edges, weights = zip(*nx.get_edge_attributes(G, 'weight').items())
nx.draw(G, pos, node_color='b', edge_color=weights,
width=2, with_labels=True)
nx.draw_networkx_edge_labels(G, pos,
{
(1, 2): "x", (2, 3): "y", (3, 4): "w",
(4, 1): "z", (1, 3): "v"
},
label_pos=0.75
)
plt.show() | [
{
"code": null,
"e": 1136,
"s": 1062,
"text": "To set the networkx edge labels offset, we can take the following steps −"
},
{
"code": null,
"e": 1212,
"s": 1136,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1270,
"s": 1212,
"text": "Initialize a graph with edges, name, or graph attributes."
},
{
"code": null,
"e": 1290,
"s": 1270,
"text": "Add multiple nodes."
},
{
"code": null,
"e": 1362,
"s": 1290,
"text": "Position the nodes using Fruchterman-Reingold force-directed algorithm."
},
{
"code": null,
"e": 1396,
"s": 1362,
"text": "Draw the graph G with Matplotlib."
},
{
"code": null,
"e": 1414,
"s": 1396,
"text": "Draw edge labels."
},
{
"code": null,
"e": 1456,
"s": 1414,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 2253,
"s": 1456,
"text": "import matplotlib.pylab as plt\nimport networkx as nx\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nG = nx.DiGraph()\nG.add_nodes_from([1, 2, 3, 4])\nG.add_edges_from([(1, 2), (2, 3), (3, 4), (4, 1), (1, 3)])\n\npos = nx.spring_layout(G)\n\nfor u, v, d in G.edges(data=True):\nd['weight'] = 3\n\nedges, weights = zip(*nx.get_edge_attributes(G, 'weight').items())\n\nnx.draw(G, pos, node_color='b', edge_color=weights,\nwidth=2, with_labels=True)\n\nnx.draw_networkx_edge_labels(G, pos,\n {\n (1, 2): \"x\", (2, 3): \"y\", (3, 4): \"w\",\n (4, 1): \"z\", (1, 3): \"v\"\n },\n label_pos=0.75\n )\nplt.show()"
}
] |
Data Processing Example using Python | by Kamil Mysiak | Towards Data Science | Forbes’s survey found that the least enjoyable part of a data scientist’s job encompasses 80% of their time. 20% is spent collecting data and another 60% is spent cleaning and organizing of data sets. Personally, I disagree with the notion that 80% is the least enjoyable part of our jobs. I often see the task of data cleansing as an open-ended problem. Typically, each data set can be processed in hundreds of different ways depending on the problem at hand but we can very rarely apply the same set of analyses and transformations from one dataset to another. I find that building different processing pipelines and examining how their differences affect model performance is an enjoyable part of my job.
With that said, I want to take the time and walk you through the code and the thought process of preparing a dataset for analysis which in this case will be a regression (ie. multiple regression).
Those of you who follow me know that I’m particular to human resources datasets as I have been working in the industry for most of my career.
If you have a rare HR dataset please share with us :)
We will be working with a dataset of 310 active and terminated employees along with information much as marital status, gender, department, pay rate, state, position, etc. Since we are prepping the data for regression analysis, our target feature is EngagementSurvey.
The code book for our dataset can be found here.
import numpy as npimport pandas as pdimport datetimeimport matplotlib.pyplot as pltimport seaborn as snsfrom sklearn.pipeline import make_pipelinefrom feature_engine import missing_data_imputers as mdifrom feature_engine import categorical_encoders as cefrom sklearn.model_selection import train_test_split%matplotlib inlinewith open('HRDataset.csv') as f: df = pd.read_csv(f)f.close()df.head()df.info()
Upon loading our data we can see a number of unique feature types. We have categorical features such as “Employee_Name” and “Position”. We have binary features such as “MarriedID”. We have continuous features such as “PayRate” and “EmpSatisfaction”. We have discrete features such as “DaysLateLast30” and finally we have date features such as “LastPerformanceReview_Date”.
The first step I typically take is reviewing the unique count of values per feature to determine if any features can be quickly deleted due to very high or very low variability. In other words, do we have any features which have as many unique values as the length of the dataset or features which have just one unique value?
for col in df.columns: print(col, df[col].nunique(), len(df))
df.drop(['Employee_Name'], axis=1, inplace=True)df.drop(['EmpID'], axis=1, inplace=True)df.drop(['DOB'], axis=1, inplace=True)df.drop(['DaysLateLast30'], axis=1, inplace=True)
We can safely remove “Employee_Name”, “Emp_ID”, “DOB” since most if not all, values are unique for each feature. Also, we can remove “DaysLateLast30” as this feature only contains one unique value.
Next, by examining the codebook, which contains the definitions for each feature, we can see that we have many duplicate features. For example, “MarriedStatusID” is a numerical feature that produces the code that matches the married statues in “MaritalDesc” feature. We can drop these features.
df.drop(['MaritalStatusID', 'EmpStatusID', 'DeptID'], axis=1, inplace=True)df.drop(['GenderID'], axis=1, inplace=True)df.drop(['PerformanceScore'], axis=1, inplace=True)df.drop(['MarriedID'], axis=1, inplace=True)
You might be asking yourself “What about ‘PositionID’, ‘Position’, ‘ManagerID’ and ManagerName’?”. As you can see from the output above, the unique value counts for these feature pairs do not match. “PositionID” has 32 unique values whereas “Position” has 30.
df[['PositionID', 'Position']].sort_values('PositionID')[50:70]df[['ManagerName', 'ManagerID']].sort_values(by='ManagerID').tail(50)df.drop('PositionID', axis=1, inplace=True)df.drop('ManagerID', axis=1, inplace=True)
We are going to drop “PositionID” as it does not maintain all available positions and we are going to drop “ManagerID” as “ManagerName” does not contain any missing values.
Next, let’s examine the individual unique values for each feature. This will help us see any odds values and mistakes which will need to be fixed.
for col in df.columns: print(col, df[col].unique(), len(df))
From the codebook, we know that features such as “FromDiversityJobFairID”, and “Termd” are binary codings for “Yes” and “No”. In order to simplify our analysis and help with formatting, we need to convert the binary to string. We also see trailing spaces for the position of “Data Analyst” and Department of “Production” which need to be removed. Finally, we see a coding mistake for “HispanicLatino” which needs to be corrected.
diversity_map = {1: 'yes', 0: 'no'}termd_map = {1: 'yes', 0: 'no'}hispanic_latino_map = {'No': 'no', 'Yes': 'yes', 'no': 'no', 'yes': 'yes'}df['FromDiversityJobFairID'].replace(diversity_map, inplace=True)df['Termd'].replace(termd_map, inplace=True)df['HispanicLatino'].replace(hispanic_latino_map, inplace=True)df['Position'] = df['Position'].str.strip()df['Department'] = df['Department'].str.strip()
You might be asking yourself “How come some zip codes are 5 digits and some are only 4?”. In the US all zip codes are 5 digits long. After a little bit of googling, many Massachusetts zip codes actually begin with zero, and by default, python stripped the zeros which resulted in 4 digit zip codes. Since we will be treating zip codes as a categorical feature the length wouldn’t matter.
Believe it or not but datetime features very often contain a plethora of info just waiting to be unleashed. This is especially evident when one is familiar with the industry from which the data originates from.
df['DateofHire'] = pd.to_datetime(df['DateofHire'])df['DateofTermination'] = pd.to_datetime(df['DateofTermination'])df['LastPerformanceReview_Date'] = pd.to_datetime(df['LastPerformanceReview_Date'])df['DateofHire_month'] = df['DateofHire'].dt.monthdf['DateofHire_day'] = df['DateofHire'].dt.day df['DateofHire_year'] = df['DateofHire'].dt.yeardf['DateofHire_quarter'] = df['DateofHire'].dt.quarterdf['DateofHire_day_week'] = df['DateofHire'].dt.day_name()df['DateofHire_weekday'] = np.where(df['DateofHire_day_week'].isin(['Sunday','Saturday']),'yes','no')df['DateofTerm_month'] = df['DateofTermination'].dt.monthdf['DateofTerm_day'] = df['DateofTermination'].dt.daydf['DateofTerm_year'] = df['DateofTermination'].dt.yeardf['DateofTerm_quarter'] = df['DateofTermination'].dt.quarterdf['DateofTerm_day_week'] = df['DateofTermination'].dt.day_name()df['DateofTerm_weekday'] = np.where(df['DateofTerm_day_week'].isin(['Sunday','Saturday']),'yes','no')df['LastPerform_month'] = df['LastPerformanceReview_Date'].dt.monthdf['LastPerform_day'] = df['LastPerformanceReview_Date'].dt.day df['LastPerform_year'] = df['LastPerformanceReview_Date'].dt.year df['LastPerform_quarter'] = df['LastPerformanceReview_Date'].dt.quarterdf['LastPerform_day_week'] = df['LastPerformanceReview_Date'].dt.day_name()df['LastPerform_weekday'] = np.where(df['LastPerform_day_week'].isin(['Sunday','Saturday']),'yes','no')df['tenure_termed'] = df['DateofTermination'] - df['DateofHire']df['tenure'] = datetime.datetime.today() - df['DateofHire']df['days_since_review'] = datetime.datetime.today() - df['LastPerformanceReview_Date']df.drop(['DateofHire', 'DateofTermination', 'LastPerformanceReview_Date'], axis=1, inplace=True)df.head()
First, we need to convert our features to datetime format. Next, using the “datetime” library we can extract new features from our original datetime features with information such as a month, day, year, quarter, weekday string, and even whether or not the day falls on a weekend. Finally, we can subtract individual dates from each other to calculate things like tenure_termed (terminated date — hire date) and tenure (today’s date — hire date). Once we have extracted the necessary information we can drop the original features.
df['days_since_review'] = df['days_since_review'].astype(str)df['days_since_review'] = [i[0:3] for i in df['days_since_review']]df['days_since_review'] = df['days_since_review'].astype(str)df['days_since_review'] = [i[0:3] for i in df['days_since_review']]df['tenure_termed'] = df['tenure_termed'].astype(str)df['tenure_termed'] = [i[0:2] for i in df['tenure_termed']]for var in df.columns: df[var].replace(to_replace=['NaT','Na'], value=np.nan, inplace=True)df.head()
Perhaps I’m being a little obsessive-compulsive but I like tidy datasets, therefore, let’s remove the irrelevant information such as “days” and the timestamp from these new features. Finally, we convert the ‘NaT” and “Na” to true numpy “NaN”.
for var in df.columns: print(var, '\n', df[var].value_counts()/len(df))df.drop(['CitizenDesc', 'DateofHire_weekday', 'DateofTerm_weekday', 'LastPerform_quarter', 'LastPerform_weekday', 'LastPerform_year'], axis=1, inplace=True)
Cardinality refers to the number of unique values/categories for each feature. Numeric, especially continuous, features will have very high cardinality but we mainly need to concern ourselves from categorical features. First, we need to identify features that contain values/categories which suck up all the variance. In other words, 90%+ of all the observations fall under one or two values. For example, “CitizenDesc” has three unique values but we see that “US Citizen” contains 95% of all the observations. Other features which exhibit this pattern, unfortunately, are our newly engineered features such as “DateofHire_weekday”, “DateofTerm_weekday”, “LastPerform_quarter”, “LastPerform_weekday”, and “LastPerform_year”. We can safely drop these features as they do not provide enough variability to be meaningful.
Using the same code as above, we once again turn our attention onto categorical features but this time we are looking for values which we consider “rare”. How you define “rare” is really up to you but I have found that this decision has to be made a feature by feature. Some values might be rare if they appear less than 1% of the time. In other features, the threshold might be 2% or even 5%. Our ultimate goal will be to group these values together into a new value/category called “rare”. This procedure reduces the overall cardinality of the feature and if you choose to one-hot encode your categories features this method will drastically reduce the number of newly created “dummy” features.
State: Anything less than 1% will be considered ‘rare’
Position: Anything less than 2% will be considered ‘rare’
Zip: Anything less than 2% will be considered ‘rare’
RaceDesc: Anything less than 2% will be considered ‘rare’
RecruitmentSource: Anything less than 2% will be considered ‘rare’
DateofHire_day: Anything less than 2% will be considered ‘rare’
DateofTerm_month: Anything less than 2% will be considered ‘rare’
DateofTerm_day: Anything less than 2% will be considered ‘rare’
LastPerform_day: Anything less than 2% will be considered ‘rare’
LastPerform_day_week: Anything less than 2% will be considered ‘rare’
DateofHire_year: Anything less than 2% will be considered ‘rare’
DateofTerm_year: Anything less than 2% will be considered ‘rare’
ManagerName: Anything less than 5% will be considered ‘rare’
Deciding how to process missing values is one of the most important and contentious decisions a data scientist will make.
for var in df.columns: if df[var].isnull().sum()/len(df) > 0: print(var, df[var].isnull().mean().round(3))df.drop('tenure_termed', axis=1, inplace=True)
TermReason is a categorical feature with only a few missing data points. We can impute this data using the mode as this wouldn’t change the distribution of the feature. Furthermore, we can safely assume that a missing TermReason simply means the employee is still active. The remaining features with missing data are what we call “Missing Not At Random” (MNAR). In other words, there is an underlying reason these features are missing. First, the percentages of missing values seem to repeat which gives us a clue that there is a discernible pattern to these missing values. Secondly, we know from the data that roughly 67% of all employees are active and would not have a Termination Date. Lastly, oftentimes employees hired after a recent performance review cycle will not have a date associated with their last performance review date. If you wish to read more about missing values please consider this resource.
Some would argue 67% of missing values effectively renders the feature useless and I’m going to agree with this notion for our “tenure_termed” feature. Imputing this numerical feature would potentially introduce too much error variance/bias into our data. However, features such as “DateofTerm_month”, and “LastPerform_month” are categorical in nature with a definitive pattern underlying their missing data. I want to capture the importance of the missing values by imputing all missing values with the string “missing”. This way we are introducing another value/category to each feature that appropriately captures the pattern behind the missing values.
On the other hand, “days_since_review” is a numeric feature which is MNAR. In other to capture the significance of these missing values we are going to impute an arbitrary number (ie. -9999) and create a new feature that will indicate whether or not an observation was missing for this feature.
TermReason: impute with mode
DateofTerm_month: impute with ‘missing’ to create a new category
DateofTerm_day: impute with ‘missing’ to create a new category
DateofTerm_year: impute with ‘missing’ to create a new category
DateofTerm_quarter: impute with ‘missing’ to create a new category
DateofTerm_day_week: impute with ‘missing’ to create a new category
LastPerform_month: impute with ‘missing’ to create a new category
LastPerform_day: impute with ‘missing’ to create a new category
LastPerform_day_week: impute with ‘missing’ to create a new category
tenure_termed: drop due to large number of missing data
days_since_review: arbitrary imputation along with a missing indicator feature
Outliers are another contentious topic which requires some thought. There are a number of ways of dealing with outliers. If you have a very large dataset and a relatively small number of outliers you can simply delete them. I’m usually wary of this method as it changes the distribution of said feature(s) which might cause new values to become outliers. That said, it is an option often utilized. Other methods include adding an indicator feature, rescaling the entire feature using np.log(), and transforming a continuous feature into discrete by applying discretization which will encompass the outliers into one bin.
First, we need to identify if we have any outliers. The most well-known method for identifying outliers is the z-score method which standardizes the feature values to a mean of zero, a standard deviation of one, and any value which falls 3 standard deviations (plus or minus) is considered an outlier. Personally, I believe this method is flaw as the z-score relies on the mean and standard deviation of the feature. Both the mean and standard deviation are highly influenced by existing outliers. Any outlier included in the calculation of the mean and standard deviation will expand the range of the z-scores and potentially omitting existing outliers. This problem can be overcome by utilizing the median instead of the mean.
Let’s utilize a more robust method that relies on the inter-quartile range and the median. You can adjust this method and use (3 * IQR) to identify only the extreme outliers.
def outlier_treatment(feature): sorted(feature) q1,q3 = np.percentile(feature , [25,75]) IQR = q3 - q1 lower_range = q1 - (1.5 * IQR) upper_range = q3 + (1.5 * IQR) return lower_range,upper_rangeoutlier_treatment(df['PayRate'])lower_range, upper_range = outlier_treatment(df['PayRate'])df[(df['PayRate'] < lower_range) | (df['PayRate'] > upper_range)]
X = df.drop('EngagementSurvey', axis=1)y = df['EngagementSurvey']X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# impute categorical features with more than 5% missing values w/ a new category 'missing'process_pipe = make_pipeline( mdi.CategoricalVariableImputer(variables=['DateofTerm_month', 'DateofTerm_day','DateofTerm_quarter', 'DateofTerm_day_week','LastPerform_month', 'LastPerform_day','LastPerform_day_week', 'DateofTerm_year'], imputation_method='missing'), # Imputing categorical features with less than 5% missing values w/the mode mdi.CategoricalVariableImputer(variables=['TermReason'], imputation_method='frequent'), # Imputing missing values for numerical feature 'days_since_review' with an arbitrary digit mdi.ArbitraryNumberImputer(arbitrary_number = -99999, variables='days_since_review'), # We are adding a feature to indicate (binary indicator) which records were missing mdi.AddMissingIndicator(variables=['days_since_review']), # Encoding rare categories (less than 1% & the feature must have at least 5 categories) ce.RareLabelCategoricalEncoder(tol=0.01, n_categories=5, variables=['State']), # Encoding rare categories (less than 2% & the feature must have at least 5 categories) ce.RareLabelCategoricalEncoder(tol=0.02, n_categories=5, variables=['Position', 'Zip', 'DateofTerm_day', 'LastPerform_day_week', 'DateofTerm_year', 'RaceDesc', 'TermReason', 'RecruitmentSource','DateofHire_day', 'DateofTerm_month', 'LastPerform_day', 'DateofHire_year']), # Encoding rare categories (less than 5% & the feature must have at least 5 categories) ce.RareLabelCategoricalEncoder(tol=0.05, n_categories=5, variables=['ManagerName']), # Target or Mean encoding for categorical features ce.OrdinalCategoricalEncoder(encoding_method='ordered', variables=['FromDiversityJobFairID', 'Termd','Position', 'State','Zip','Sex', 'MaritalDesc','HispanicLatino', 'RaceDesc', 'TermReason','EmploymentStatus', 'Department', 'ManagerName', 'RecruitmentSource', 'DateofHire_month','DateofHire_day', 'DateofHire_day','DateofHire_quarter', 'DateofHire_day_week', 'DateofTerm_month', 'DateofTerm_day','DateofTerm_year', 'DateofTerm_quarter','DateofTerm_day_week', 'LastPerform_month', 'LastPerform_day', 'LastPerform_day_week'] ))
One topic we haven’t discussed is categorical feature encoding. I typically try and avoid using one-hot encoding due to the fact it has a tendency to greatly expand the feature space. The encoding of “rare” values/categories certainly helps with this issue if we were to use one-hot encoding. That said, I opted to use Target or Mean encoding as it does not expand the feature set. This method replaces the categories with digits from 0 to k-1. We first calculate the mean for the target variable for each category for each categorical feature and then the means are replaced with the aforementioned digits based on the mean size. For example, we have a binary target and the first categorical feature is gender and it has three categories (male, female, and undisclosed). Let’s assume the mean for male is 0.8, female is 0.5, and undisclosed is 0.2. The encoded values will be male=2, female=1 and undisclosed=0.
process_pipe.fit(X_train, y_train)X_train_clean = process_pipe.transform(X_train)X_test_clean = process_pipe.transform(X_test)X_train_clean.head()
Feel free to provide feedback if you believe I might have missed an important step. Thanks for reading! | [
{
"code": null,
"e": 880,
"s": 172,
"text": "Forbes’s survey found that the least enjoyable part of a data scientist’s job encompasses 80% of their time. 20% is spent collecting data and another 60% is spent cleaning and organizing of data sets. Personally, I disagree with the notion that 80% is the least enjoyable part of our jobs. I often see the task of data cleansing as an open-ended problem. Typically, each data set can be processed in hundreds of different ways depending on the problem at hand but we can very rarely apply the same set of analyses and transformations from one dataset to another. I find that building different processing pipelines and examining how their differences affect model performance is an enjoyable part of my job."
},
{
"code": null,
"e": 1077,
"s": 880,
"text": "With that said, I want to take the time and walk you through the code and the thought process of preparing a dataset for analysis which in this case will be a regression (ie. multiple regression)."
},
{
"code": null,
"e": 1219,
"s": 1077,
"text": "Those of you who follow me know that I’m particular to human resources datasets as I have been working in the industry for most of my career."
},
{
"code": null,
"e": 1273,
"s": 1219,
"text": "If you have a rare HR dataset please share with us :)"
},
{
"code": null,
"e": 1541,
"s": 1273,
"text": "We will be working with a dataset of 310 active and terminated employees along with information much as marital status, gender, department, pay rate, state, position, etc. Since we are prepping the data for regression analysis, our target feature is EngagementSurvey."
},
{
"code": null,
"e": 1590,
"s": 1541,
"text": "The code book for our dataset can be found here."
},
{
"code": null,
"e": 1997,
"s": 1590,
"text": "import numpy as npimport pandas as pdimport datetimeimport matplotlib.pyplot as pltimport seaborn as snsfrom sklearn.pipeline import make_pipelinefrom feature_engine import missing_data_imputers as mdifrom feature_engine import categorical_encoders as cefrom sklearn.model_selection import train_test_split%matplotlib inlinewith open('HRDataset.csv') as f: df = pd.read_csv(f)f.close()df.head()df.info()"
},
{
"code": null,
"e": 2370,
"s": 1997,
"text": "Upon loading our data we can see a number of unique feature types. We have categorical features such as “Employee_Name” and “Position”. We have binary features such as “MarriedID”. We have continuous features such as “PayRate” and “EmpSatisfaction”. We have discrete features such as “DaysLateLast30” and finally we have date features such as “LastPerformanceReview_Date”."
},
{
"code": null,
"e": 2696,
"s": 2370,
"text": "The first step I typically take is reviewing the unique count of values per feature to determine if any features can be quickly deleted due to very high or very low variability. In other words, do we have any features which have as many unique values as the length of the dataset or features which have just one unique value?"
},
{
"code": null,
"e": 2761,
"s": 2696,
"text": "for col in df.columns: print(col, df[col].nunique(), len(df))"
},
{
"code": null,
"e": 2937,
"s": 2761,
"text": "df.drop(['Employee_Name'], axis=1, inplace=True)df.drop(['EmpID'], axis=1, inplace=True)df.drop(['DOB'], axis=1, inplace=True)df.drop(['DaysLateLast30'], axis=1, inplace=True)"
},
{
"code": null,
"e": 3135,
"s": 2937,
"text": "We can safely remove “Employee_Name”, “Emp_ID”, “DOB” since most if not all, values are unique for each feature. Also, we can remove “DaysLateLast30” as this feature only contains one unique value."
},
{
"code": null,
"e": 3430,
"s": 3135,
"text": "Next, by examining the codebook, which contains the definitions for each feature, we can see that we have many duplicate features. For example, “MarriedStatusID” is a numerical feature that produces the code that matches the married statues in “MaritalDesc” feature. We can drop these features."
},
{
"code": null,
"e": 3644,
"s": 3430,
"text": "df.drop(['MaritalStatusID', 'EmpStatusID', 'DeptID'], axis=1, inplace=True)df.drop(['GenderID'], axis=1, inplace=True)df.drop(['PerformanceScore'], axis=1, inplace=True)df.drop(['MarriedID'], axis=1, inplace=True)"
},
{
"code": null,
"e": 3904,
"s": 3644,
"text": "You might be asking yourself “What about ‘PositionID’, ‘Position’, ‘ManagerID’ and ManagerName’?”. As you can see from the output above, the unique value counts for these feature pairs do not match. “PositionID” has 32 unique values whereas “Position” has 30."
},
{
"code": null,
"e": 4122,
"s": 3904,
"text": "df[['PositionID', 'Position']].sort_values('PositionID')[50:70]df[['ManagerName', 'ManagerID']].sort_values(by='ManagerID').tail(50)df.drop('PositionID', axis=1, inplace=True)df.drop('ManagerID', axis=1, inplace=True)"
},
{
"code": null,
"e": 4295,
"s": 4122,
"text": "We are going to drop “PositionID” as it does not maintain all available positions and we are going to drop “ManagerID” as “ManagerName” does not contain any missing values."
},
{
"code": null,
"e": 4442,
"s": 4295,
"text": "Next, let’s examine the individual unique values for each feature. This will help us see any odds values and mistakes which will need to be fixed."
},
{
"code": null,
"e": 4506,
"s": 4442,
"text": "for col in df.columns: print(col, df[col].unique(), len(df))"
},
{
"code": null,
"e": 4936,
"s": 4506,
"text": "From the codebook, we know that features such as “FromDiversityJobFairID”, and “Termd” are binary codings for “Yes” and “No”. In order to simplify our analysis and help with formatting, we need to convert the binary to string. We also see trailing spaces for the position of “Data Analyst” and Department of “Production” which need to be removed. Finally, we see a coding mistake for “HispanicLatino” which needs to be corrected."
},
{
"code": null,
"e": 5339,
"s": 4936,
"text": "diversity_map = {1: 'yes', 0: 'no'}termd_map = {1: 'yes', 0: 'no'}hispanic_latino_map = {'No': 'no', 'Yes': 'yes', 'no': 'no', 'yes': 'yes'}df['FromDiversityJobFairID'].replace(diversity_map, inplace=True)df['Termd'].replace(termd_map, inplace=True)df['HispanicLatino'].replace(hispanic_latino_map, inplace=True)df['Position'] = df['Position'].str.strip()df['Department'] = df['Department'].str.strip()"
},
{
"code": null,
"e": 5727,
"s": 5339,
"text": "You might be asking yourself “How come some zip codes are 5 digits and some are only 4?”. In the US all zip codes are 5 digits long. After a little bit of googling, many Massachusetts zip codes actually begin with zero, and by default, python stripped the zeros which resulted in 4 digit zip codes. Since we will be treating zip codes as a categorical feature the length wouldn’t matter."
},
{
"code": null,
"e": 5938,
"s": 5727,
"text": "Believe it or not but datetime features very often contain a plethora of info just waiting to be unleashed. This is especially evident when one is familiar with the industry from which the data originates from."
},
{
"code": null,
"e": 7648,
"s": 5938,
"text": "df['DateofHire'] = pd.to_datetime(df['DateofHire'])df['DateofTermination'] = pd.to_datetime(df['DateofTermination'])df['LastPerformanceReview_Date'] = pd.to_datetime(df['LastPerformanceReview_Date'])df['DateofHire_month'] = df['DateofHire'].dt.monthdf['DateofHire_day'] = df['DateofHire'].dt.day df['DateofHire_year'] = df['DateofHire'].dt.yeardf['DateofHire_quarter'] = df['DateofHire'].dt.quarterdf['DateofHire_day_week'] = df['DateofHire'].dt.day_name()df['DateofHire_weekday'] = np.where(df['DateofHire_day_week'].isin(['Sunday','Saturday']),'yes','no')df['DateofTerm_month'] = df['DateofTermination'].dt.monthdf['DateofTerm_day'] = df['DateofTermination'].dt.daydf['DateofTerm_year'] = df['DateofTermination'].dt.yeardf['DateofTerm_quarter'] = df['DateofTermination'].dt.quarterdf['DateofTerm_day_week'] = df['DateofTermination'].dt.day_name()df['DateofTerm_weekday'] = np.where(df['DateofTerm_day_week'].isin(['Sunday','Saturday']),'yes','no')df['LastPerform_month'] = df['LastPerformanceReview_Date'].dt.monthdf['LastPerform_day'] = df['LastPerformanceReview_Date'].dt.day df['LastPerform_year'] = df['LastPerformanceReview_Date'].dt.year df['LastPerform_quarter'] = df['LastPerformanceReview_Date'].dt.quarterdf['LastPerform_day_week'] = df['LastPerformanceReview_Date'].dt.day_name()df['LastPerform_weekday'] = np.where(df['LastPerform_day_week'].isin(['Sunday','Saturday']),'yes','no')df['tenure_termed'] = df['DateofTermination'] - df['DateofHire']df['tenure'] = datetime.datetime.today() - df['DateofHire']df['days_since_review'] = datetime.datetime.today() - df['LastPerformanceReview_Date']df.drop(['DateofHire', 'DateofTermination', 'LastPerformanceReview_Date'], axis=1, inplace=True)df.head()"
},
{
"code": null,
"e": 8178,
"s": 7648,
"text": "First, we need to convert our features to datetime format. Next, using the “datetime” library we can extract new features from our original datetime features with information such as a month, day, year, quarter, weekday string, and even whether or not the day falls on a weekend. Finally, we can subtract individual dates from each other to calculate things like tenure_termed (terminated date — hire date) and tenure (today’s date — hire date). Once we have extracted the necessary information we can drop the original features."
},
{
"code": null,
"e": 8650,
"s": 8178,
"text": "df['days_since_review'] = df['days_since_review'].astype(str)df['days_since_review'] = [i[0:3] for i in df['days_since_review']]df['days_since_review'] = df['days_since_review'].astype(str)df['days_since_review'] = [i[0:3] for i in df['days_since_review']]df['tenure_termed'] = df['tenure_termed'].astype(str)df['tenure_termed'] = [i[0:2] for i in df['tenure_termed']]for var in df.columns: df[var].replace(to_replace=['NaT','Na'], value=np.nan, inplace=True)df.head()"
},
{
"code": null,
"e": 8893,
"s": 8650,
"text": "Perhaps I’m being a little obsessive-compulsive but I like tidy datasets, therefore, let’s remove the irrelevant information such as “days” and the timestamp from these new features. Finally, we convert the ‘NaT” and “Na” to true numpy “NaN”."
},
{
"code": null,
"e": 9133,
"s": 8893,
"text": "for var in df.columns: print(var, '\\n', df[var].value_counts()/len(df))df.drop(['CitizenDesc', 'DateofHire_weekday', 'DateofTerm_weekday', 'LastPerform_quarter', 'LastPerform_weekday', 'LastPerform_year'], axis=1, inplace=True)"
},
{
"code": null,
"e": 9952,
"s": 9133,
"text": "Cardinality refers to the number of unique values/categories for each feature. Numeric, especially continuous, features will have very high cardinality but we mainly need to concern ourselves from categorical features. First, we need to identify features that contain values/categories which suck up all the variance. In other words, 90%+ of all the observations fall under one or two values. For example, “CitizenDesc” has three unique values but we see that “US Citizen” contains 95% of all the observations. Other features which exhibit this pattern, unfortunately, are our newly engineered features such as “DateofHire_weekday”, “DateofTerm_weekday”, “LastPerform_quarter”, “LastPerform_weekday”, and “LastPerform_year”. We can safely drop these features as they do not provide enough variability to be meaningful."
},
{
"code": null,
"e": 10649,
"s": 9952,
"text": "Using the same code as above, we once again turn our attention onto categorical features but this time we are looking for values which we consider “rare”. How you define “rare” is really up to you but I have found that this decision has to be made a feature by feature. Some values might be rare if they appear less than 1% of the time. In other features, the threshold might be 2% or even 5%. Our ultimate goal will be to group these values together into a new value/category called “rare”. This procedure reduces the overall cardinality of the feature and if you choose to one-hot encode your categories features this method will drastically reduce the number of newly created “dummy” features."
},
{
"code": null,
"e": 10704,
"s": 10649,
"text": "State: Anything less than 1% will be considered ‘rare’"
},
{
"code": null,
"e": 10762,
"s": 10704,
"text": "Position: Anything less than 2% will be considered ‘rare’"
},
{
"code": null,
"e": 10815,
"s": 10762,
"text": "Zip: Anything less than 2% will be considered ‘rare’"
},
{
"code": null,
"e": 10873,
"s": 10815,
"text": "RaceDesc: Anything less than 2% will be considered ‘rare’"
},
{
"code": null,
"e": 10940,
"s": 10873,
"text": "RecruitmentSource: Anything less than 2% will be considered ‘rare’"
},
{
"code": null,
"e": 11004,
"s": 10940,
"text": "DateofHire_day: Anything less than 2% will be considered ‘rare’"
},
{
"code": null,
"e": 11070,
"s": 11004,
"text": "DateofTerm_month: Anything less than 2% will be considered ‘rare’"
},
{
"code": null,
"e": 11134,
"s": 11070,
"text": "DateofTerm_day: Anything less than 2% will be considered ‘rare’"
},
{
"code": null,
"e": 11199,
"s": 11134,
"text": "LastPerform_day: Anything less than 2% will be considered ‘rare’"
},
{
"code": null,
"e": 11269,
"s": 11199,
"text": "LastPerform_day_week: Anything less than 2% will be considered ‘rare’"
},
{
"code": null,
"e": 11334,
"s": 11269,
"text": "DateofHire_year: Anything less than 2% will be considered ‘rare’"
},
{
"code": null,
"e": 11399,
"s": 11334,
"text": "DateofTerm_year: Anything less than 2% will be considered ‘rare’"
},
{
"code": null,
"e": 11460,
"s": 11399,
"text": "ManagerName: Anything less than 5% will be considered ‘rare’"
},
{
"code": null,
"e": 11582,
"s": 11460,
"text": "Deciding how to process missing values is one of the most important and contentious decisions a data scientist will make."
},
{
"code": null,
"e": 11745,
"s": 11582,
"text": "for var in df.columns: if df[var].isnull().sum()/len(df) > 0: print(var, df[var].isnull().mean().round(3))df.drop('tenure_termed', axis=1, inplace=True)"
},
{
"code": null,
"e": 12661,
"s": 11745,
"text": "TermReason is a categorical feature with only a few missing data points. We can impute this data using the mode as this wouldn’t change the distribution of the feature. Furthermore, we can safely assume that a missing TermReason simply means the employee is still active. The remaining features with missing data are what we call “Missing Not At Random” (MNAR). In other words, there is an underlying reason these features are missing. First, the percentages of missing values seem to repeat which gives us a clue that there is a discernible pattern to these missing values. Secondly, we know from the data that roughly 67% of all employees are active and would not have a Termination Date. Lastly, oftentimes employees hired after a recent performance review cycle will not have a date associated with their last performance review date. If you wish to read more about missing values please consider this resource."
},
{
"code": null,
"e": 13317,
"s": 12661,
"text": "Some would argue 67% of missing values effectively renders the feature useless and I’m going to agree with this notion for our “tenure_termed” feature. Imputing this numerical feature would potentially introduce too much error variance/bias into our data. However, features such as “DateofTerm_month”, and “LastPerform_month” are categorical in nature with a definitive pattern underlying their missing data. I want to capture the importance of the missing values by imputing all missing values with the string “missing”. This way we are introducing another value/category to each feature that appropriately captures the pattern behind the missing values."
},
{
"code": null,
"e": 13612,
"s": 13317,
"text": "On the other hand, “days_since_review” is a numeric feature which is MNAR. In other to capture the significance of these missing values we are going to impute an arbitrary number (ie. -9999) and create a new feature that will indicate whether or not an observation was missing for this feature."
},
{
"code": null,
"e": 13641,
"s": 13612,
"text": "TermReason: impute with mode"
},
{
"code": null,
"e": 13706,
"s": 13641,
"text": "DateofTerm_month: impute with ‘missing’ to create a new category"
},
{
"code": null,
"e": 13769,
"s": 13706,
"text": "DateofTerm_day: impute with ‘missing’ to create a new category"
},
{
"code": null,
"e": 13833,
"s": 13769,
"text": "DateofTerm_year: impute with ‘missing’ to create a new category"
},
{
"code": null,
"e": 13900,
"s": 13833,
"text": "DateofTerm_quarter: impute with ‘missing’ to create a new category"
},
{
"code": null,
"e": 13968,
"s": 13900,
"text": "DateofTerm_day_week: impute with ‘missing’ to create a new category"
},
{
"code": null,
"e": 14034,
"s": 13968,
"text": "LastPerform_month: impute with ‘missing’ to create a new category"
},
{
"code": null,
"e": 14098,
"s": 14034,
"text": "LastPerform_day: impute with ‘missing’ to create a new category"
},
{
"code": null,
"e": 14167,
"s": 14098,
"text": "LastPerform_day_week: impute with ‘missing’ to create a new category"
},
{
"code": null,
"e": 14223,
"s": 14167,
"text": "tenure_termed: drop due to large number of missing data"
},
{
"code": null,
"e": 14302,
"s": 14223,
"text": "days_since_review: arbitrary imputation along with a missing indicator feature"
},
{
"code": null,
"e": 14923,
"s": 14302,
"text": "Outliers are another contentious topic which requires some thought. There are a number of ways of dealing with outliers. If you have a very large dataset and a relatively small number of outliers you can simply delete them. I’m usually wary of this method as it changes the distribution of said feature(s) which might cause new values to become outliers. That said, it is an option often utilized. Other methods include adding an indicator feature, rescaling the entire feature using np.log(), and transforming a continuous feature into discrete by applying discretization which will encompass the outliers into one bin."
},
{
"code": null,
"e": 15652,
"s": 14923,
"text": "First, we need to identify if we have any outliers. The most well-known method for identifying outliers is the z-score method which standardizes the feature values to a mean of zero, a standard deviation of one, and any value which falls 3 standard deviations (plus or minus) is considered an outlier. Personally, I believe this method is flaw as the z-score relies on the mean and standard deviation of the feature. Both the mean and standard deviation are highly influenced by existing outliers. Any outlier included in the calculation of the mean and standard deviation will expand the range of the z-scores and potentially omitting existing outliers. This problem can be overcome by utilizing the median instead of the mean."
},
{
"code": null,
"e": 15827,
"s": 15652,
"text": "Let’s utilize a more robust method that relies on the inter-quartile range and the median. You can adjust this method and use (3 * IQR) to identify only the extreme outliers."
},
{
"code": null,
"e": 16197,
"s": 15827,
"text": "def outlier_treatment(feature): sorted(feature) q1,q3 = np.percentile(feature , [25,75]) IQR = q3 - q1 lower_range = q1 - (1.5 * IQR) upper_range = q3 + (1.5 * IQR) return lower_range,upper_rangeoutlier_treatment(df['PayRate'])lower_range, upper_range = outlier_treatment(df['PayRate'])df[(df['PayRate'] < lower_range) | (df['PayRate'] > upper_range)]"
},
{
"code": null,
"e": 16352,
"s": 16197,
"text": "X = df.drop('EngagementSurvey', axis=1)y = df['EngagementSurvey']X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)"
},
{
"code": null,
"e": 18588,
"s": 16352,
"text": "# impute categorical features with more than 5% missing values w/ a new category 'missing'process_pipe = make_pipeline( mdi.CategoricalVariableImputer(variables=['DateofTerm_month', 'DateofTerm_day','DateofTerm_quarter', 'DateofTerm_day_week','LastPerform_month', 'LastPerform_day','LastPerform_day_week', 'DateofTerm_year'], imputation_method='missing'), # Imputing categorical features with less than 5% missing values w/the mode mdi.CategoricalVariableImputer(variables=['TermReason'], imputation_method='frequent'), # Imputing missing values for numerical feature 'days_since_review' with an arbitrary digit mdi.ArbitraryNumberImputer(arbitrary_number = -99999, variables='days_since_review'), # We are adding a feature to indicate (binary indicator) which records were missing mdi.AddMissingIndicator(variables=['days_since_review']), # Encoding rare categories (less than 1% & the feature must have at least 5 categories) ce.RareLabelCategoricalEncoder(tol=0.01, n_categories=5, variables=['State']), # Encoding rare categories (less than 2% & the feature must have at least 5 categories) ce.RareLabelCategoricalEncoder(tol=0.02, n_categories=5, variables=['Position', 'Zip', 'DateofTerm_day', 'LastPerform_day_week', 'DateofTerm_year', 'RaceDesc', 'TermReason', 'RecruitmentSource','DateofHire_day', 'DateofTerm_month', 'LastPerform_day', 'DateofHire_year']), # Encoding rare categories (less than 5% & the feature must have at least 5 categories) ce.RareLabelCategoricalEncoder(tol=0.05, n_categories=5, variables=['ManagerName']), # Target or Mean encoding for categorical features ce.OrdinalCategoricalEncoder(encoding_method='ordered', variables=['FromDiversityJobFairID', 'Termd','Position', 'State','Zip','Sex', 'MaritalDesc','HispanicLatino', 'RaceDesc', 'TermReason','EmploymentStatus', 'Department', 'ManagerName', 'RecruitmentSource', 'DateofHire_month','DateofHire_day', 'DateofHire_day','DateofHire_quarter', 'DateofHire_day_week', 'DateofTerm_month', 'DateofTerm_day','DateofTerm_year', 'DateofTerm_quarter','DateofTerm_day_week', 'LastPerform_month', 'LastPerform_day', 'LastPerform_day_week'] ))"
},
{
"code": null,
"e": 19502,
"s": 18588,
"text": "One topic we haven’t discussed is categorical feature encoding. I typically try and avoid using one-hot encoding due to the fact it has a tendency to greatly expand the feature space. The encoding of “rare” values/categories certainly helps with this issue if we were to use one-hot encoding. That said, I opted to use Target or Mean encoding as it does not expand the feature set. This method replaces the categories with digits from 0 to k-1. We first calculate the mean for the target variable for each category for each categorical feature and then the means are replaced with the aforementioned digits based on the mean size. For example, we have a binary target and the first categorical feature is gender and it has three categories (male, female, and undisclosed). Let’s assume the mean for male is 0.8, female is 0.5, and undisclosed is 0.2. The encoded values will be male=2, female=1 and undisclosed=0."
},
{
"code": null,
"e": 19649,
"s": 19502,
"text": "process_pipe.fit(X_train, y_train)X_train_clean = process_pipe.transform(X_train)X_test_clean = process_pipe.transform(X_test)X_train_clean.head()"
}
] |
Understanding Logistic Regression in Python? | Logistic Regression is a statistical technique to predict the binary outcome. It’s not a new thing as it is currently being applied in areas ranging from finance to medicine to criminology and other social sciences.
In this section we are going to develop logistic regression using python, though you can implement same using other languages like R.
We’re going to use below libraries in our example program,
Numpy: To define the numerical array and matrix
Numpy: To define the numerical array and matrix
Pandas: To handle and operate on data
Pandas: To handle and operate on data
Statsmodels: To handle parameter estimation & statistical testing
Statsmodels: To handle parameter estimation & statistical testing
Pylab: To generate plots
Pylab: To generate plots
You can install above libraries using pip by running below command in CLI.
>pip install numpy pandas statsmodels
To test our logistic regression in python, we are going to use the logit regression data provided by UCLA (Institute for digital research and education). You can access the data from below link in csv format: https://stats.idre.ucla.edu/stat/data/binary.csv
I have saved this csv file in my local machine & will read the data from there, you can do either. With this csv file we are going to identify the various factors that may influence admission into graduate school.
We are going to read the data using pandas library (pandas.read_csv):
import pandas as pd
import statsmodels.api as sm
import pylab as pl
import numpy as np
df = pd.read_csv('binary.csv')
#We can read the data directly from the link \
# df = pd.read_csv(‘https://stats.idre.ucla.edu/stat/data/binary.csv’)
print(df.head())
admit gre gpa rank
0 0 380 3.61 3
1 1 660 3.67 3
2 1 800 4.00 1
3 1 640 3.19 4
4 0 520 2.93 4
As we can see from above output, one column name is ‘rank’, this may create problem since ‘rank’ is also name of the method in pandas dataframe. To avoid any conflict, i’m changing the name of rank column to ‘prestige’. So let’s change the dataset column name:
df.columns = ["admit", "gre", "gpa", "prestige"]
print(df.columns)
Index(['admit', 'gre', 'gpa', 'prestige'], dtype='object')
In [ ]:
Now everything looks ok, we can now look much deeper what our dataset contains.
Using pandas function describe we’ll get a summarized view of everything.
print(df.describe())
admit gre gpa prestige
count 400.000000 400.000000 400.000000 400.00000
mean 0.317500 587.700000 3.389900 2.48500
std 0.466087 115.516536 0.380567 0.94446
min 0.000000 220.000000 2.260000 1.00000
25% 0.000000 520.000000 3.130000 2.00000
50% 0.000000 580.000000 3.395000 2.00000
75% 1.000000 660.000000 3.670000 3.00000
max 1.000000 800.000000 4.000000 4.00000
We can get the standard deviation of each column of our data & the frequency table cutting prestige and whether or not someone was admitted.
# take a look at the standard deviation of each column
print(df.std())
admit 0.466087
gre 115.516536
gpa 0.380567
prestige 0.944460
dtype: float64
# frequency table cutting presitge and whether or not someone was admitted
print(pd.crosstab(df['admit'], df['prestige'], rownames = ['admit']))
prestige 1 2 3 4
admit
0 28 97 93 55
1 33 54 28 12
Let’s plot all the columns of the dataset.
# plot all of the columns
df.hist()
pl.show()
Python pandas library provides great flexibility in how we categorical variables are represented.
# dummify rank
dummy_ranks = pd.get_dummies(df['prestige'], prefix='prestige')
print(dummy_ranks.head())
prestige_1 prestige_2 prestige_3 prestige_4
0 0 0 1 0
1 0 0 1 0
2 1 0 0 0
3 0 0 0 1
4 0 0 0 1
# create a clean data frame for the regression
cols_to_keep = ['admit', 'gre', 'gpa']
data = df[cols_to_keep].join(dummy_ranks.ix[:, 'prestige_2':])
admit gre gpa prestige_2 prestige_3 prestige_4
0 0 380 3.61 0 1 0
1 1 660 3.67 0 1 0
2 1 800 4.00 0 0 0
3 1 640 3.19 0 0 1
4 0 520 2.93 0 0 1
In [ ]:
Now we are going to do logistic regression, which is quite simple. We simply specify the column containing the variable we’re trying to predict followed by the columns that the model should use to make the prediction.
Now we are predicting the admit column based on gre, gpa and prestige dummy variables prestige_2, prestige_3 & prestige_4.
train_cols = data.columns[1:]
# Index([gre, gpa, prestige_2, prestige_3, prestige_4], dtype=object)
logit = sm.Logit(data['admit'], data[train_cols])
# fit the model
result = logit.fit()
Optimization terminated successfully.
Current function value: 0.573147
Iterations 6
Let’s generate the summary output using statsmodels.
print(result.summary2())
Results: Logit
===============================================================
Model: Logit No. Iterations: 6.0000
Dependent Variable: admit Pseudo R-squared: 0.083
Date: 2019-03-03 14:16 AIC: 470.5175
No. Observations: 400 BIC: 494.4663
Df Model: 5 Log-Likelihood: -229.26
Df Residuals: 394 LL-Null: -249.99
Converged: 1.0000 Scale: 1.0000
----------------------------------------------------------------
Coef. Std.Err. z P>|z| [0.025 0.975]
----------------------------------------------------------------
gre 0.0023 0.0011 2.0699 0.0385 0.0001 0.0044
gpa 0.8040 0.3318 2.4231 0.0154 0.1537 1.4544
prestige_2 -0.6754 0.3165 -2.1342 0.0328 -1.2958 -0.0551
prestige_3 -1.3402 0.3453 -3.8812 0.0001 -2.0170 -0.6634
prestige_4 -1.5515 0.4178 -3.7131 0.0002 -2.3704 -0.7325
intercept -3.9900 1.1400 -3.5001 0.0005 -6.2242 -1.7557
==============================================================
The above result object also lets us to isolate and inspect parts of the model output.
#look at the confidence interval of each coeffecient
print(result.conf_int())
0 1
gre 0.000120 0.004409
gpa 0.153684 1.454391
prestige_2 -1.295751 -0.055135
prestige_3 -2.016992 -0.663416
prestige_4 -2.370399 -0.732529
intercept -6.224242 -1.755716
From above output, we can see there is an inverse relationship b/w the probability of being admitted and the prestige of a candidate’s undergraduate school.
So the probability of a candidate to being accepted into a graduate program is higher for students who attended a top ranked undergraduate college(prestige_1= True) as opposed to a lower ranked school (prestige_3 or prestige_4). | [
{
"code": null,
"e": 1278,
"s": 1062,
"text": "Logistic Regression is a statistical technique to predict the binary outcome. It’s not a new thing as it is currently being applied in areas ranging from finance to medicine to criminology and other social sciences."
},
{
"code": null,
"e": 1412,
"s": 1278,
"text": "In this section we are going to develop logistic regression using python, though you can implement same using other languages like R."
},
{
"code": null,
"e": 1471,
"s": 1412,
"text": "We’re going to use below libraries in our example program,"
},
{
"code": null,
"e": 1519,
"s": 1471,
"text": "Numpy: To define the numerical array and matrix"
},
{
"code": null,
"e": 1567,
"s": 1519,
"text": "Numpy: To define the numerical array and matrix"
},
{
"code": null,
"e": 1605,
"s": 1567,
"text": "Pandas: To handle and operate on data"
},
{
"code": null,
"e": 1643,
"s": 1605,
"text": "Pandas: To handle and operate on data"
},
{
"code": null,
"e": 1709,
"s": 1643,
"text": "Statsmodels: To handle parameter estimation & statistical testing"
},
{
"code": null,
"e": 1775,
"s": 1709,
"text": "Statsmodels: To handle parameter estimation & statistical testing"
},
{
"code": null,
"e": 1800,
"s": 1775,
"text": "Pylab: To generate plots"
},
{
"code": null,
"e": 1825,
"s": 1800,
"text": "Pylab: To generate plots"
},
{
"code": null,
"e": 1900,
"s": 1825,
"text": "You can install above libraries using pip by running below command in CLI."
},
{
"code": null,
"e": 1938,
"s": 1900,
"text": ">pip install numpy pandas statsmodels"
},
{
"code": null,
"e": 2196,
"s": 1938,
"text": "To test our logistic regression in python, we are going to use the logit regression data provided by UCLA (Institute for digital research and education). You can access the data from below link in csv format: https://stats.idre.ucla.edu/stat/data/binary.csv"
},
{
"code": null,
"e": 2410,
"s": 2196,
"text": "I have saved this csv file in my local machine & will read the data from there, you can do either. With this csv file we are going to identify the various factors that may influence admission into graduate school."
},
{
"code": null,
"e": 2480,
"s": 2410,
"text": "We are going to read the data using pandas library (pandas.read_csv):"
},
{
"code": null,
"e": 2733,
"s": 2480,
"text": "import pandas as pd\nimport statsmodels.api as sm\nimport pylab as pl\nimport numpy as np\ndf = pd.read_csv('binary.csv')\n#We can read the data directly from the link \\\n# df = pd.read_csv(‘https://stats.idre.ucla.edu/stat/data/binary.csv’)\nprint(df.head())"
},
{
"code": null,
"e": 2851,
"s": 2733,
"text": " admit gre gpa rank\n0 0 380 3.61 3\n1 1 660 3.67 3\n2 1 800 4.00 1\n3 1 640 3.19 4\n4 0 520 2.93 4"
},
{
"code": null,
"e": 3112,
"s": 2851,
"text": "As we can see from above output, one column name is ‘rank’, this may create problem since ‘rank’ is also name of the method in pandas dataframe. To avoid any conflict, i’m changing the name of rank column to ‘prestige’. So let’s change the dataset column name:"
},
{
"code": null,
"e": 3179,
"s": 3112,
"text": "df.columns = [\"admit\", \"gre\", \"gpa\", \"prestige\"]\nprint(df.columns)"
},
{
"code": null,
"e": 3246,
"s": 3179,
"text": "Index(['admit', 'gre', 'gpa', 'prestige'], dtype='object')\nIn [ ]:"
},
{
"code": null,
"e": 3326,
"s": 3246,
"text": "Now everything looks ok, we can now look much deeper what our dataset contains."
},
{
"code": null,
"e": 3400,
"s": 3326,
"text": "Using pandas function describe we’ll get a summarized view of everything."
},
{
"code": null,
"e": 3421,
"s": 3400,
"text": "print(df.describe())"
},
{
"code": null,
"e": 3995,
"s": 3421,
"text": " admit gre gpa prestige\ncount 400.000000 400.000000 400.000000 400.00000\nmean 0.317500 587.700000 3.389900 2.48500\nstd 0.466087 115.516536 0.380567 0.94446\nmin 0.000000 220.000000 2.260000 1.00000\n25% 0.000000 520.000000 3.130000 2.00000\n50% 0.000000 580.000000 3.395000 2.00000\n75% 1.000000 660.000000 3.670000 3.00000\nmax 1.000000 800.000000 4.000000 4.00000"
},
{
"code": null,
"e": 4136,
"s": 3995,
"text": "We can get the standard deviation of each column of our data & the frequency table cutting prestige and whether or not someone was admitted."
},
{
"code": null,
"e": 4207,
"s": 4136,
"text": "# take a look at the standard deviation of each column\nprint(df.std())"
},
{
"code": null,
"e": 4292,
"s": 4207,
"text": "admit 0.466087\ngre 115.516536\ngpa 0.380567\nprestige 0.944460\ndtype: float64"
},
{
"code": null,
"e": 4437,
"s": 4292,
"text": "# frequency table cutting presitge and whether or not someone was admitted\nprint(pd.crosstab(df['admit'], df['prestige'], rownames = ['admit']))"
},
{
"code": null,
"e": 4501,
"s": 4437,
"text": "prestige 1 2 3 4\nadmit\n0 28 97 93 55\n1 33 54 28 12"
},
{
"code": null,
"e": 4544,
"s": 4501,
"text": "Let’s plot all the columns of the dataset."
},
{
"code": null,
"e": 4590,
"s": 4544,
"text": "# plot all of the columns\ndf.hist()\npl.show()"
},
{
"code": null,
"e": 4688,
"s": 4590,
"text": "Python pandas library provides great flexibility in how we categorical variables are represented."
},
{
"code": null,
"e": 4793,
"s": 4688,
"text": "# dummify rank\ndummy_ranks = pd.get_dummies(df['prestige'], prefix='prestige')\nprint(dummy_ranks.head())"
},
{
"code": null,
"e": 5147,
"s": 4793,
"text": " prestige_1 prestige_2 prestige_3 prestige_4\n0 0 0 1 0\n1 0 0 1 0\n2 1 0 0 0\n3 0 0 0 1\n4 0 0 0 1"
},
{
"code": null,
"e": 5296,
"s": 5147,
"text": "# create a clean data frame for the regression\ncols_to_keep = ['admit', 'gre', 'gpa']\ndata = df[cols_to_keep].join(dummy_ranks.ix[:, 'prestige_2':])"
},
{
"code": null,
"e": 5614,
"s": 5296,
"text": " admit gre gpa prestige_2 prestige_3 prestige_4\n0 0 380 3.61 0 1 0\n1 1 660 3.67 0 1 0\n2 1 800 4.00 0 0 0\n3 1 640 3.19 0 0 1\n4 0 520 2.93 0 0 1\nIn [ ]:"
},
{
"code": null,
"e": 5832,
"s": 5614,
"text": "Now we are going to do logistic regression, which is quite simple. We simply specify the column containing the variable we’re trying to predict followed by the columns that the model should use to make the prediction."
},
{
"code": null,
"e": 5955,
"s": 5832,
"text": "Now we are predicting the admit column based on gre, gpa and prestige dummy variables prestige_2, prestige_3 & prestige_4."
},
{
"code": null,
"e": 6144,
"s": 5955,
"text": "train_cols = data.columns[1:]\n# Index([gre, gpa, prestige_2, prestige_3, prestige_4], dtype=object)\n\nlogit = sm.Logit(data['admit'], data[train_cols])\n\n# fit the model\nresult = logit.fit()"
},
{
"code": null,
"e": 6228,
"s": 6144,
"text": "Optimization terminated successfully.\nCurrent function value: 0.573147\nIterations 6"
},
{
"code": null,
"e": 6281,
"s": 6228,
"text": "Let’s generate the summary output using statsmodels."
},
{
"code": null,
"e": 6306,
"s": 6281,
"text": "print(result.summary2())"
},
{
"code": null,
"e": 7387,
"s": 6306,
"text": " Results: Logit\n===============================================================\nModel: Logit No. Iterations: 6.0000\nDependent Variable: admit Pseudo R-squared: 0.083\nDate: 2019-03-03 14:16 AIC: 470.5175\nNo. Observations: 400 BIC: 494.4663\nDf Model: 5 Log-Likelihood: -229.26\nDf Residuals: 394 LL-Null: -249.99\nConverged: 1.0000 Scale: 1.0000\n----------------------------------------------------------------\nCoef. Std.Err. z P>|z| [0.025 0.975]\n----------------------------------------------------------------\ngre 0.0023 0.0011 2.0699 0.0385 0.0001 0.0044\ngpa 0.8040 0.3318 2.4231 0.0154 0.1537 1.4544\nprestige_2 -0.6754 0.3165 -2.1342 0.0328 -1.2958 -0.0551\nprestige_3 -1.3402 0.3453 -3.8812 0.0001 -2.0170 -0.6634\nprestige_4 -1.5515 0.4178 -3.7131 0.0002 -2.3704 -0.7325\nintercept -3.9900 1.1400 -3.5001 0.0005 -6.2242 -1.7557\n=============================================================="
},
{
"code": null,
"e": 7474,
"s": 7387,
"text": "The above result object also lets us to isolate and inspect parts of the model output."
},
{
"code": null,
"e": 7552,
"s": 7474,
"text": "#look at the confidence interval of each coeffecient\nprint(result.conf_int())"
},
{
"code": null,
"e": 7798,
"s": 7552,
"text": " 0 1\ngre 0.000120 0.004409\ngpa 0.153684 1.454391\nprestige_2 -1.295751 -0.055135\nprestige_3 -2.016992 -0.663416\nprestige_4 -2.370399 -0.732529\nintercept -6.224242 -1.755716"
},
{
"code": null,
"e": 7955,
"s": 7798,
"text": "From above output, we can see there is an inverse relationship b/w the probability of being admitted and the prestige of a candidate’s undergraduate school."
},
{
"code": null,
"e": 8184,
"s": 7955,
"text": "So the probability of a candidate to being accepted into a graduate program is higher for students who attended a top ranked undergraduate college(prestige_1= True) as opposed to a lower ranked school (prestige_3 or prestige_4)."
}
] |
Minimum number of distinct elements after removing M items | Set 2 - GeeksforGeeks | 19 May, 2021
Given an array of items, an ith index element denotes the item id’s, and given a number m, the task is to remove m elements such that there should be minimum distinct id’s left. Print the number of distinct id’s.
Examples:
Input: arr[] = { 2, 2, 1, 3, 3, 3} m = 3Output: 1Explanation:Remove 1 and both 2’s.So, only 3 will be left, hence distinct number of element is 1.
Input: arr[] = { 2, 4, 1, 5, 3, 5, 1, 3} m = 2Output: 3Explanation:Remove 2 and 4 completely. So, remaining 1, 3 and 5 i.e. 3 elements.
For O(N*log N) approach please refer to the previous article.
Efficient Approach: The idea is to store the occurrence of each element in a Hash and count the occurrence of each frequency in a hash again. Below are the steps:
Traverse the given array elements and count the occurrences of each number and store it into the hash.Now instead of sorting the frequency, count the occurrences of the frequency into another array say fre_arr[].Calculate the total unique numbers(say ans) as the number of distinct id’s.Now, traverse the freq_arr[] array and if freq_arr[i] > 0 then remove the minimum of m/i and freq_arr[i](say t) from ans and subtract i*t from m to remove the occurrence of any number i from m.
Traverse the given array elements and count the occurrences of each number and store it into the hash.
Now instead of sorting the frequency, count the occurrences of the frequency into another array say fre_arr[].
Calculate the total unique numbers(say ans) as the number of distinct id’s.
Now, traverse the freq_arr[] array and if freq_arr[i] > 0 then remove the minimum of m/i and freq_arr[i](say t) from ans and subtract i*t from m to remove the occurrence of any number i from m.
Below is the implementation of the above approach.
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to return minimum distinct// character after M removalsint distinctNumbers(int arr[], int m, int n){ unordered_map<int, int> count; // Count the occurences of number // and store in count for (int i = 0; i < n; i++) count[arr[i]]++; // Count the occurences of the // frequencies vector<int> fre_arr(n + 1, 0); for (auto it : count) { fre_arr[it.second]++; } // Take answer as total unique numbers // and remove the frequency and // subtract the answer int ans = count.size(); for (int i = 1; i <= n; i++) { int temp = fre_arr[i]; if (temp == 0) continue; // Remove the minimum number // of times int t = min(temp, m / i); ans -= t; m -= i * t; } // Return the answer return ans;} // Driver Codeint main(){ // Initialize array int arr[] = { 2, 4, 1, 5, 3, 5, 1, 3 }; // Size of array int n = sizeof(arr) / sizeof(arr[0]); int m = 2; // Function call cout << distinctNumbers(arr, m, n); return 0;}
// Java program to implement the// above approachimport java.util.*; class GFG{ // Function to return minimum distinct// character after M removalsstatic int distinctNumbers(int arr[], int m, int n){ Map<Integer, Integer> count = new HashMap<Integer, Integer>(); // Count the occurences of number // and store in count for (int i = 0; i < n; i++) count.put(arr[i], count.getOrDefault(arr[i], 0) + 1); // Count the occurences of the // frequencies int[] fre_arr = new int[n + 1]; for(Integer it : count.values()) { fre_arr[it]++; } // Take answer as total unique numbers // and remove the frequency and // subtract the answer int ans = count.size(); for(int i = 1; i <= n; i++) { int temp = fre_arr[i]; if (temp == 0) continue; // Remove the minimum number // of times int t = Math.min(temp, m / i); ans -= t; m -= i * t; } // Return the answer return ans;} // Driver codepublic static void main(String[] args){ // Initialize array int arr[] = { 2, 4, 1, 5, 3, 5, 1, 3 }; // Size of array int n = arr.length; int m = 2; // Function call System.out.println(distinctNumbers(arr, m, n));}} // This code is contributed by offbeat
# Python3 program for the above approach # Function to return minimum distinct# character after M removalsdef distinctNumbers(arr, m, n): count = {} # Count the occurences of number # and store in count for i in range(n): count[arr[i]] = count.get(arr[i], 0) + 1 # Count the occurences of the # frequencies fre_arr = [0] * (n + 1) for it in count: fre_arr[count[it]] += 1 # Take answer as total unique numbers # and remove the frequency and # subtract the answer ans = len(count) for i in range(1, n + 1): temp = fre_arr[i] if (temp == 0): continue # Remove the minimum number # of times t = min(temp, m // i) ans -= t m -= i * t # Return the answer return ans # Driver Codeif __name__ == '__main__': # Initialize array arr = [ 2, 4, 1, 5, 3, 5, 1, 3 ] # Size of array n = len(arr) m = 2 # Function call print(distinctNumbers(arr, m, n)) # This code is contributed by mohit kumar 29
// C# program to implement the// above approachusing System;using System.Collections.Generic;class GFG{ // Function to return minimum distinct// character after M removalsstatic int distinctNumbers(int []arr, int m, int n){ Dictionary<int, int> count = new Dictionary<int, int>(); // Count the occurences of number // and store in count for (int i = 0; i < n; i++) if(count.ContainsKey(arr[i])) { count[arr[i]] = count[arr[i]] + 1; } else { count.Add(arr[i], 1); } // Count the occurences of the // frequencies int[] fre_arr = new int[n + 1]; foreach(int it in count.Values) { fre_arr[it]++; } // Take answer as total unique numbers // and remove the frequency and // subtract the answer int ans = count.Count; for(int i = 1; i <= n; i++) { int temp = fre_arr[i]; if (temp == 0) continue; // Remove the minimum number // of times int t = Math.Min(temp, m / i); ans -= t; m -= i * t; } // Return the answer return ans;} // Driver codepublic static void Main(String[] args){ // Initialize array int []arr = {2, 4, 1, 5, 3, 5, 1, 3}; // Size of array int n = arr.Length; int m = 2; // Function call Console.WriteLine(distinctNumbers(arr, m, n));}} // This code is contributed by Princi Singh
<script> // Javascript program for the above approach // Function to return minimum distinct// character after M removalsfunction distinctNumbers(arr, m, n){ var count = new Map(); // Count the occurences of number // and store in count for (var i = 0; i < n; i++) if(count.has(arr[i])) count.set(arr[i], count.get(arr[i])+1) else count.set(arr[i], 1) // Count the occurences of the // frequencies var fre_arr = Array(n + 1).fill(0); count.forEach((value, key) => { fre_arr[value]++; }); // Take answer as total unique numbers // and remove the frequency and // subtract the answer var ans = count.size; for (var i = 1; i <= n; i++) { var temp = fre_arr[i]; if (temp == 0) continue; // Remove the minimum number // of times var t = Math.min(temp, parseInt(m / i)); ans -= t; m -= i * t; } // Return the answer return ans;} // Driver Code// Initialize arrayvar arr = [2, 4, 1, 5, 3, 5, 1, 3];// Size of arrayvar n = arr.length;var m = 2;// Function calldocument.write( distinctNumbers(arr, m, n)); </script>
3
Time Complexity: O(N)Auxiliary Space: O(N)
mohit kumar 29
offbeat
princi singh
famously
frequency-counting
Hash
Arrays
Greedy
Hash
Arrays
Hash
Greedy
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Multidimensional Arrays in Java
Queue | Set 1 (Introduction and Array Implementation)
Linear Search
Python | Using 2D arrays/lists the right way
Dijkstra's shortest path algorithm | Greedy Algo-7
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Write a program to print all permutations of a given string
Huffman Coding | Greedy Algo-3 | [
{
"code": null,
"e": 24899,
"s": 24871,
"text": "\n19 May, 2021"
},
{
"code": null,
"e": 25112,
"s": 24899,
"text": "Given an array of items, an ith index element denotes the item id’s, and given a number m, the task is to remove m elements such that there should be minimum distinct id’s left. Print the number of distinct id’s."
},
{
"code": null,
"e": 25122,
"s": 25112,
"text": "Examples:"
},
{
"code": null,
"e": 25269,
"s": 25122,
"text": "Input: arr[] = { 2, 2, 1, 3, 3, 3} m = 3Output: 1Explanation:Remove 1 and both 2’s.So, only 3 will be left, hence distinct number of element is 1."
},
{
"code": null,
"e": 25405,
"s": 25269,
"text": "Input: arr[] = { 2, 4, 1, 5, 3, 5, 1, 3} m = 2Output: 3Explanation:Remove 2 and 4 completely. So, remaining 1, 3 and 5 i.e. 3 elements."
},
{
"code": null,
"e": 25467,
"s": 25405,
"text": "For O(N*log N) approach please refer to the previous article."
},
{
"code": null,
"e": 25630,
"s": 25467,
"text": "Efficient Approach: The idea is to store the occurrence of each element in a Hash and count the occurrence of each frequency in a hash again. Below are the steps:"
},
{
"code": null,
"e": 26111,
"s": 25630,
"text": "Traverse the given array elements and count the occurrences of each number and store it into the hash.Now instead of sorting the frequency, count the occurrences of the frequency into another array say fre_arr[].Calculate the total unique numbers(say ans) as the number of distinct id’s.Now, traverse the freq_arr[] array and if freq_arr[i] > 0 then remove the minimum of m/i and freq_arr[i](say t) from ans and subtract i*t from m to remove the occurrence of any number i from m."
},
{
"code": null,
"e": 26214,
"s": 26111,
"text": "Traverse the given array elements and count the occurrences of each number and store it into the hash."
},
{
"code": null,
"e": 26325,
"s": 26214,
"text": "Now instead of sorting the frequency, count the occurrences of the frequency into another array say fre_arr[]."
},
{
"code": null,
"e": 26401,
"s": 26325,
"text": "Calculate the total unique numbers(say ans) as the number of distinct id’s."
},
{
"code": null,
"e": 26595,
"s": 26401,
"text": "Now, traverse the freq_arr[] array and if freq_arr[i] > 0 then remove the minimum of m/i and freq_arr[i](say t) from ans and subtract i*t from m to remove the occurrence of any number i from m."
},
{
"code": null,
"e": 26646,
"s": 26595,
"text": "Below is the implementation of the above approach."
},
{
"code": null,
"e": 26650,
"s": 26646,
"text": "C++"
},
{
"code": null,
"e": 26655,
"s": 26650,
"text": "Java"
},
{
"code": null,
"e": 26663,
"s": 26655,
"text": "Python3"
},
{
"code": null,
"e": 26666,
"s": 26663,
"text": "C#"
},
{
"code": null,
"e": 26677,
"s": 26666,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to return minimum distinct// character after M removalsint distinctNumbers(int arr[], int m, int n){ unordered_map<int, int> count; // Count the occurences of number // and store in count for (int i = 0; i < n; i++) count[arr[i]]++; // Count the occurences of the // frequencies vector<int> fre_arr(n + 1, 0); for (auto it : count) { fre_arr[it.second]++; } // Take answer as total unique numbers // and remove the frequency and // subtract the answer int ans = count.size(); for (int i = 1; i <= n; i++) { int temp = fre_arr[i]; if (temp == 0) continue; // Remove the minimum number // of times int t = min(temp, m / i); ans -= t; m -= i * t; } // Return the answer return ans;} // Driver Codeint main(){ // Initialize array int arr[] = { 2, 4, 1, 5, 3, 5, 1, 3 }; // Size of array int n = sizeof(arr) / sizeof(arr[0]); int m = 2; // Function call cout << distinctNumbers(arr, m, n); return 0;}",
"e": 27843,
"s": 26677,
"text": null
},
{
"code": "// Java program to implement the// above approachimport java.util.*; class GFG{ // Function to return minimum distinct// character after M removalsstatic int distinctNumbers(int arr[], int m, int n){ Map<Integer, Integer> count = new HashMap<Integer, Integer>(); // Count the occurences of number // and store in count for (int i = 0; i < n; i++) count.put(arr[i], count.getOrDefault(arr[i], 0) + 1); // Count the occurences of the // frequencies int[] fre_arr = new int[n + 1]; for(Integer it : count.values()) { fre_arr[it]++; } // Take answer as total unique numbers // and remove the frequency and // subtract the answer int ans = count.size(); for(int i = 1; i <= n; i++) { int temp = fre_arr[i]; if (temp == 0) continue; // Remove the minimum number // of times int t = Math.min(temp, m / i); ans -= t; m -= i * t; } // Return the answer return ans;} // Driver codepublic static void main(String[] args){ // Initialize array int arr[] = { 2, 4, 1, 5, 3, 5, 1, 3 }; // Size of array int n = arr.length; int m = 2; // Function call System.out.println(distinctNumbers(arr, m, n));}} // This code is contributed by offbeat",
"e": 29234,
"s": 27843,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to return minimum distinct# character after M removalsdef distinctNumbers(arr, m, n): count = {} # Count the occurences of number # and store in count for i in range(n): count[arr[i]] = count.get(arr[i], 0) + 1 # Count the occurences of the # frequencies fre_arr = [0] * (n + 1) for it in count: fre_arr[count[it]] += 1 # Take answer as total unique numbers # and remove the frequency and # subtract the answer ans = len(count) for i in range(1, n + 1): temp = fre_arr[i] if (temp == 0): continue # Remove the minimum number # of times t = min(temp, m // i) ans -= t m -= i * t # Return the answer return ans # Driver Codeif __name__ == '__main__': # Initialize array arr = [ 2, 4, 1, 5, 3, 5, 1, 3 ] # Size of array n = len(arr) m = 2 # Function call print(distinctNumbers(arr, m, n)) # This code is contributed by mohit kumar 29",
"e": 30279,
"s": 29234,
"text": null
},
{
"code": "// C# program to implement the// above approachusing System;using System.Collections.Generic;class GFG{ // Function to return minimum distinct// character after M removalsstatic int distinctNumbers(int []arr, int m, int n){ Dictionary<int, int> count = new Dictionary<int, int>(); // Count the occurences of number // and store in count for (int i = 0; i < n; i++) if(count.ContainsKey(arr[i])) { count[arr[i]] = count[arr[i]] + 1; } else { count.Add(arr[i], 1); } // Count the occurences of the // frequencies int[] fre_arr = new int[n + 1]; foreach(int it in count.Values) { fre_arr[it]++; } // Take answer as total unique numbers // and remove the frequency and // subtract the answer int ans = count.Count; for(int i = 1; i <= n; i++) { int temp = fre_arr[i]; if (temp == 0) continue; // Remove the minimum number // of times int t = Math.Min(temp, m / i); ans -= t; m -= i * t; } // Return the answer return ans;} // Driver codepublic static void Main(String[] args){ // Initialize array int []arr = {2, 4, 1, 5, 3, 5, 1, 3}; // Size of array int n = arr.Length; int m = 2; // Function call Console.WriteLine(distinctNumbers(arr, m, n));}} // This code is contributed by Princi Singh",
"e": 31631,
"s": 30279,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function to return minimum distinct// character after M removalsfunction distinctNumbers(arr, m, n){ var count = new Map(); // Count the occurences of number // and store in count for (var i = 0; i < n; i++) if(count.has(arr[i])) count.set(arr[i], count.get(arr[i])+1) else count.set(arr[i], 1) // Count the occurences of the // frequencies var fre_arr = Array(n + 1).fill(0); count.forEach((value, key) => { fre_arr[value]++; }); // Take answer as total unique numbers // and remove the frequency and // subtract the answer var ans = count.size; for (var i = 1; i <= n; i++) { var temp = fre_arr[i]; if (temp == 0) continue; // Remove the minimum number // of times var t = Math.min(temp, parseInt(m / i)); ans -= t; m -= i * t; } // Return the answer return ans;} // Driver Code// Initialize arrayvar arr = [2, 4, 1, 5, 3, 5, 1, 3];// Size of arrayvar n = arr.length;var m = 2;// Function calldocument.write( distinctNumbers(arr, m, n)); </script>",
"e": 32815,
"s": 31631,
"text": null
},
{
"code": null,
"e": 32817,
"s": 32815,
"text": "3"
},
{
"code": null,
"e": 32862,
"s": 32819,
"text": "Time Complexity: O(N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 32877,
"s": 32862,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 32885,
"s": 32877,
"text": "offbeat"
},
{
"code": null,
"e": 32898,
"s": 32885,
"text": "princi singh"
},
{
"code": null,
"e": 32907,
"s": 32898,
"text": "famously"
},
{
"code": null,
"e": 32926,
"s": 32907,
"text": "frequency-counting"
},
{
"code": null,
"e": 32931,
"s": 32926,
"text": "Hash"
},
{
"code": null,
"e": 32938,
"s": 32931,
"text": "Arrays"
},
{
"code": null,
"e": 32945,
"s": 32938,
"text": "Greedy"
},
{
"code": null,
"e": 32950,
"s": 32945,
"text": "Hash"
},
{
"code": null,
"e": 32957,
"s": 32950,
"text": "Arrays"
},
{
"code": null,
"e": 32962,
"s": 32957,
"text": "Hash"
},
{
"code": null,
"e": 32969,
"s": 32962,
"text": "Greedy"
},
{
"code": null,
"e": 33067,
"s": 32969,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33076,
"s": 33067,
"text": "Comments"
},
{
"code": null,
"e": 33089,
"s": 33076,
"text": "Old Comments"
},
{
"code": null,
"e": 33137,
"s": 33089,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 33169,
"s": 33137,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 33223,
"s": 33169,
"text": "Queue | Set 1 (Introduction and Array Implementation)"
},
{
"code": null,
"e": 33237,
"s": 33223,
"text": "Linear Search"
},
{
"code": null,
"e": 33282,
"s": 33237,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 33333,
"s": 33282,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 33384,
"s": 33333,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
},
{
"code": null,
"e": 33442,
"s": 33384,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 33502,
"s": 33442,
"text": "Write a program to print all permutations of a given string"
}
] |
How to filter R dataframe by multiple conditions? - GeeksforGeeks | 23 May, 2021
In R programming Language, dataframe columns can be subjected to constraints, and produce smaller subsets. However, while the conditions are applied, the following properties are maintained :
Rows are considered to be a subset of the input.
Rows in the subset appear in the same order as the original data frame.
Columns remain unmodified.
The number of groups may be reduced, based on conditions.
Data frame attributes are preserved during the data filter.
Row numbers may not be retained in the final output
The data frame rows can be subjected to multiple conditions by combining them using logical operators, like AND (&) , OR (|). The rows returning TRUE are retained in the final output.
Any data frame column in R can be referenced either through its name df$col-name or using its index position in the data frame df[col-index]. The cell values of this column can then be subjected to constraints, logical or comparative conditions, and then data frame subset can be obtained. These conditions are applied to the row index of the data frame so that the satisfied rows are returned. Multiple conditions can also be combined using which() method in R. The which() function in R returns the position of the value which satisfies the given condition.
Syntax: which( vec, arr.ind = F)
Parameter :
vec – The vector to be subjected to conditions
The %in% operator is used to check a value in the vector specified.
Syntax:
val %in% vec
Example:
R
# declaring a data framedata_frame = data.frame(col1 = c("b","b","d","e","d") , col2 = c(0,2,1,4,5), col3= c(TRUE,FALSE,FALSE,TRUE, TRUE)) print ("Original dataframe")print (data_frame) # checking which values of col1 are # equivalent to b or e or the col2 # value is greater than 4data_frame_mod <- data_frame[which(data_frame$col1 %in% c("b","e") | data_frame$col2 > 4),] print ("Modified dataframe")print (data_frame_mod)
Output
[1] "Original dataframe"
col1 col2 col3
1 b 0 TRUE
2 b 2 FALSE
3 d 1 FALSE
4 e 4 TRUE
5 d 5 TRUE
[1] "Modified dataframe"
col1 col2 col3
1 b 0 TRUE
2 b 2 FALSE
4 e 4 TRUE
5 d 5 TRUE
The conditions can be aggregated together, without the use of which method also.
Example:
R
# declaring a data framedata_frame = data.frame(col1 = c("b","b","d","e","d") , col2 = c(0,2,1,4,5), col3= c(TRUE,FALSE,FALSE,TRUE, TRUE)) print ("Original dataframe")print (data_frame) # checking which values of col1 # are equivalent to b or edata_frame_mod <- data_frame[data_frame$col1 %in% c("b","e") & data_frame$col2 > 4,] print ("Modified dataframe")print (data_frame_mod)
Output
[1] "Original dataframe"
col1 col2 col3
1 b 0 TRUE
2 b 2 FALSE
3 d 1 FALSE
4 e 4 TRUE
5 d 5 TRUE
[1] "Modified dataframe"
[1] col1 col2 col3
<0 rows> (or 0-length row.names)
The dplyr library can be installed and loaded into the working space which is used to perform data manipulation. The filter() function is used to produce a subset of the data frame, retaining all rows that satisfy the specified conditions. The filter() method in R can be applied to both grouped and ungrouped data. The expressions include comparison operators (==, >, >= ) , logical operators (&, |, !, xor()) , range operators (between(), near()) as well as NA value check against the column values. The subset data frame has to be retained in a separate variable.
Syntax: filter(df , cond)
Parameter :
df – The data frame object
cond – The condition to filter the data upon
The difference in the application of this approach is that it doesn’t retain the original row numbers of the data frame.
Example:
R
library ("dplyr") # declaring a data framedata_frame = data.frame(col1 = c("b","b","d","e","e") , col2 = c(0,2,1,4,5), col3= c(TRUE,FALSE,FALSE,TRUE, TRUE)) print ("Original dataframe")print (data_frame) # checking which values of col1 are# equivalent to b and col3 is not # TRUEdata_frame_mod <- filter( data_frame,col1 == "b" & col3!=TRUE) print ("Modified dataframe")print (data_frame_mod)
Output
[1] "Original dataframe"
col1 col2 col3
1 b 0 TRUE
2 b 2 FALSE
3 d 1 FALSE
4 e 4 TRUE
5 d 5 TRUE
[1] "Modified dataframe"
col1 col2 col3
1 b 2 FALSE
The subset() method in base R is used to return subsets of vectors, matrices, or data frames which satisfy the applied conditions. The subset() method is concerned with the rows. The row numbers are retained while applying this method.
Syntax: subset(df , cond)
Arguments :
df – The data frame object
cond – The condition to filter the data upon
Example:
R
# declaring a data framedata_frame = data.frame(col1 = c("b","b","d","e","d") , col2 = c(0,2,1,4,5), col3= c(TRUE,FALSE,FALSE,TRUE, TRUE)) print ("Original dataframe")print (data_frame) # checking which values of col1 are# equivalent to b or col2 value is # greater than 4data_frame_mod <- subset(data_frame, col1=="b" | col2 > 4)print ("Modified dataframe")print (data_frame_mod)
Output
[1] "Original dataframe"
col1 col2 col3
1 b 0 TRUE
2 b 2 FALSE
3 d 1 FALSE
4 e 4 TRUE
5 d 5 TRUE
[1] "Modified dataframe"
col1 col2 col3
1 b 0 TRUE
2 b 2 FALSE
5 d 5 TRUE
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Replace specific values in column in R DataFrame ?
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
How to change Row Names of DataFrame in R ?
Printing Output of an R Program
How to Replace specific values in column in R DataFrame ?
How to change Row Names of DataFrame in R ?
Remove rows with NA in one column of R DataFrame
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R | [
{
"code": null,
"e": 25280,
"s": 25252,
"text": "\n23 May, 2021"
},
{
"code": null,
"e": 25472,
"s": 25280,
"text": "In R programming Language, dataframe columns can be subjected to constraints, and produce smaller subsets. However, while the conditions are applied, the following properties are maintained :"
},
{
"code": null,
"e": 25521,
"s": 25472,
"text": "Rows are considered to be a subset of the input."
},
{
"code": null,
"e": 25593,
"s": 25521,
"text": "Rows in the subset appear in the same order as the original data frame."
},
{
"code": null,
"e": 25620,
"s": 25593,
"text": "Columns remain unmodified."
},
{
"code": null,
"e": 25678,
"s": 25620,
"text": "The number of groups may be reduced, based on conditions."
},
{
"code": null,
"e": 25738,
"s": 25678,
"text": "Data frame attributes are preserved during the data filter."
},
{
"code": null,
"e": 25790,
"s": 25738,
"text": "Row numbers may not be retained in the final output"
},
{
"code": null,
"e": 25974,
"s": 25790,
"text": "The data frame rows can be subjected to multiple conditions by combining them using logical operators, like AND (&) , OR (|). The rows returning TRUE are retained in the final output."
},
{
"code": null,
"e": 26534,
"s": 25974,
"text": "Any data frame column in R can be referenced either through its name df$col-name or using its index position in the data frame df[col-index]. The cell values of this column can then be subjected to constraints, logical or comparative conditions, and then data frame subset can be obtained. These conditions are applied to the row index of the data frame so that the satisfied rows are returned. Multiple conditions can also be combined using which() method in R. The which() function in R returns the position of the value which satisfies the given condition."
},
{
"code": null,
"e": 26567,
"s": 26534,
"text": "Syntax: which( vec, arr.ind = F)"
},
{
"code": null,
"e": 26580,
"s": 26567,
"text": "Parameter : "
},
{
"code": null,
"e": 26627,
"s": 26580,
"text": "vec – The vector to be subjected to conditions"
},
{
"code": null,
"e": 26696,
"s": 26627,
"text": "The %in% operator is used to check a value in the vector specified. "
},
{
"code": null,
"e": 26704,
"s": 26696,
"text": "Syntax:"
},
{
"code": null,
"e": 26717,
"s": 26704,
"text": "val %in% vec"
},
{
"code": null,
"e": 26726,
"s": 26717,
"text": "Example:"
},
{
"code": null,
"e": 26728,
"s": 26726,
"text": "R"
},
{
"code": "# declaring a data framedata_frame = data.frame(col1 = c(\"b\",\"b\",\"d\",\"e\",\"d\") , col2 = c(0,2,1,4,5), col3= c(TRUE,FALSE,FALSE,TRUE, TRUE)) print (\"Original dataframe\")print (data_frame) # checking which values of col1 are # equivalent to b or e or the col2 # value is greater than 4data_frame_mod <- data_frame[which(data_frame$col1 %in% c(\"b\",\"e\") | data_frame$col2 > 4),] print (\"Modified dataframe\")print (data_frame_mod)",
"e": 27237,
"s": 26728,
"text": null
},
{
"code": null,
"e": 27244,
"s": 27237,
"text": "Output"
},
{
"code": null,
"e": 27490,
"s": 27244,
"text": "[1] \"Original dataframe\"\n col1 col2 col3\n1 b 0 TRUE\n2 b 2 FALSE\n3 d 1 FALSE\n4 e 4 TRUE\n5 d 5 TRUE\n[1] \"Modified dataframe\"\n col1 col2 col3\n1 b 0 TRUE\n2 b 2 FALSE\n4 e 4 TRUE\n5 d 5 TRUE"
},
{
"code": null,
"e": 27571,
"s": 27490,
"text": "The conditions can be aggregated together, without the use of which method also."
},
{
"code": null,
"e": 27580,
"s": 27571,
"text": "Example:"
},
{
"code": null,
"e": 27582,
"s": 27580,
"text": "R"
},
{
"code": "# declaring a data framedata_frame = data.frame(col1 = c(\"b\",\"b\",\"d\",\"e\",\"d\") , col2 = c(0,2,1,4,5), col3= c(TRUE,FALSE,FALSE,TRUE, TRUE)) print (\"Original dataframe\")print (data_frame) # checking which values of col1 # are equivalent to b or edata_frame_mod <- data_frame[data_frame$col1 %in% c(\"b\",\"e\") & data_frame$col2 > 4,] print (\"Modified dataframe\")print (data_frame_mod)",
"e": 28040,
"s": 27582,
"text": null
},
{
"code": null,
"e": 28047,
"s": 28040,
"text": "Output"
},
{
"code": null,
"e": 28256,
"s": 28047,
"text": "[1] \"Original dataframe\"\n col1 col2 col3\n1 b 0 TRUE\n2 b 2 FALSE\n3 d 1 FALSE\n4 e 4 TRUE\n5 d 5 TRUE\n[1] \"Modified dataframe\"\n[1] col1 col2 col3\n<0 rows> (or 0-length row.names)"
},
{
"code": null,
"e": 28823,
"s": 28256,
"text": "The dplyr library can be installed and loaded into the working space which is used to perform data manipulation. The filter() function is used to produce a subset of the data frame, retaining all rows that satisfy the specified conditions. The filter() method in R can be applied to both grouped and ungrouped data. The expressions include comparison operators (==, >, >= ) , logical operators (&, |, !, xor()) , range operators (between(), near()) as well as NA value check against the column values. The subset data frame has to be retained in a separate variable."
},
{
"code": null,
"e": 28849,
"s": 28823,
"text": "Syntax: filter(df , cond)"
},
{
"code": null,
"e": 28861,
"s": 28849,
"text": "Parameter :"
},
{
"code": null,
"e": 28888,
"s": 28861,
"text": "df – The data frame object"
},
{
"code": null,
"e": 28933,
"s": 28888,
"text": "cond – The condition to filter the data upon"
},
{
"code": null,
"e": 29055,
"s": 28933,
"text": "The difference in the application of this approach is that it doesn’t retain the original row numbers of the data frame. "
},
{
"code": null,
"e": 29064,
"s": 29055,
"text": "Example:"
},
{
"code": null,
"e": 29066,
"s": 29064,
"text": "R"
},
{
"code": "library (\"dplyr\") # declaring a data framedata_frame = data.frame(col1 = c(\"b\",\"b\",\"d\",\"e\",\"e\") , col2 = c(0,2,1,4,5), col3= c(TRUE,FALSE,FALSE,TRUE, TRUE)) print (\"Original dataframe\")print (data_frame) # checking which values of col1 are# equivalent to b and col3 is not # TRUEdata_frame_mod <- filter( data_frame,col1 == \"b\" & col3!=TRUE) print (\"Modified dataframe\")print (data_frame_mod)",
"e": 29512,
"s": 29066,
"text": null
},
{
"code": null,
"e": 29519,
"s": 29512,
"text": "Output"
},
{
"code": null,
"e": 29711,
"s": 29519,
"text": "[1] \"Original dataframe\"\ncol1 col2 col3\n1 b 0 TRUE\n2 b 2 FALSE\n3 d 1 FALSE\n4 e 4 TRUE\n5 d 5 TRUE\n[1] \"Modified dataframe\"\n col1 col2 col3 \n1 b 2 FALSE"
},
{
"code": null,
"e": 29948,
"s": 29711,
"text": "The subset() method in base R is used to return subsets of vectors, matrices, or data frames which satisfy the applied conditions. The subset() method is concerned with the rows. The row numbers are retained while applying this method. "
},
{
"code": null,
"e": 29974,
"s": 29948,
"text": "Syntax: subset(df , cond)"
},
{
"code": null,
"e": 29986,
"s": 29974,
"text": "Arguments :"
},
{
"code": null,
"e": 30013,
"s": 29986,
"text": "df – The data frame object"
},
{
"code": null,
"e": 30058,
"s": 30013,
"text": "cond – The condition to filter the data upon"
},
{
"code": null,
"e": 30067,
"s": 30058,
"text": "Example:"
},
{
"code": null,
"e": 30069,
"s": 30067,
"text": "R"
},
{
"code": "# declaring a data framedata_frame = data.frame(col1 = c(\"b\",\"b\",\"d\",\"e\",\"d\") , col2 = c(0,2,1,4,5), col3= c(TRUE,FALSE,FALSE,TRUE, TRUE)) print (\"Original dataframe\")print (data_frame) # checking which values of col1 are# equivalent to b or col2 value is # greater than 4data_frame_mod <- subset(data_frame, col1==\"b\" | col2 > 4)print (\"Modified dataframe\")print (data_frame_mod)",
"e": 30500,
"s": 30069,
"text": null
},
{
"code": null,
"e": 30507,
"s": 30500,
"text": "Output"
},
{
"code": null,
"e": 30735,
"s": 30507,
"text": "[1] \"Original dataframe\"\n col1 col2 col3\n1 b 0 TRUE\n2 b 2 FALSE\n3 d 1 FALSE\n4 e 4 TRUE\n5 d 5 TRUE\n[1] \"Modified dataframe\"\n col1 col2 col3\n1 b 0 TRUE\n2 b 2 FALSE\n5 d 5 TRUE"
},
{
"code": null,
"e": 30742,
"s": 30735,
"text": "Picked"
},
{
"code": null,
"e": 30763,
"s": 30742,
"text": "R DataFrame-Programs"
},
{
"code": null,
"e": 30775,
"s": 30763,
"text": "R-DataFrame"
},
{
"code": null,
"e": 30786,
"s": 30775,
"text": "R Language"
},
{
"code": null,
"e": 30797,
"s": 30786,
"text": "R Programs"
},
{
"code": null,
"e": 30895,
"s": 30797,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30953,
"s": 30895,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 30985,
"s": 30953,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 31037,
"s": 30985,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 31081,
"s": 31037,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 31113,
"s": 31081,
"text": "Printing Output of an R Program"
},
{
"code": null,
"e": 31171,
"s": 31113,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 31215,
"s": 31171,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 31264,
"s": 31215,
"text": "Remove rows with NA in one column of R DataFrame"
},
{
"code": null,
"e": 31322,
"s": 31264,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
}
] |
Matching Country Information in Python | by Joe T. Santhanavanich | Towards Data Science | In data science projects, you may have a data table that contains country data like country name, country code, etc. But, different data sets usually provide data in different country data formats or attributes; for example, “Germany” can be recorded as “GER”, “Germany”, “DE”, “Federal Republic of Germany”, country code — 276, etc.). This would cause you some difficulties to join tables, data aggregation, data analysis, or data visualization.
This article introduces PyCountry, a Python library for completing the country data from the country database to ready your dataset to be matched or aggregated to others.
Let’s get started~
You can install this library using pip as the following command:
$ pip install pycountry
First, you can create a blank Python file and import the pycountry library.
import pycountry
Then, you can get any information from each country from the following attributes:
Name (e.g. Thailand)
Alpha 2 code (e.g. “TH”)
Alpha 3 code (e.g. “THA”)
Numeric code (e.g. “764”)
Official name (e.g. “Kingdom of Thailand”)
For example, if you have “Alpha 2 code” and you can use countries.get command to get all information:
pycountry.countries.get(alpha_2='TH')>>> Country(alpha_2='TH', alpha_3='THA', name='Thailand', numeric='764', official_name='Kingdom of Thailand')
If you want only the nameoutput, you can do it in a single command as follows:
pycountry.countries.get(alpha_2='TH').name>>> 'Thailand'
The PyCountry library also comes with a “fuzzy” search to help you to find countries without input their types. For example:
pycountry.countries.search_fuzzy('Thailand')>>> [Country(alpha_2='TH', alpha_3='THA', name='Thailand', numeric='764', official_name='Kingdom of Thailand')]
That’s about it. Now, let’s head to try this library in the real-world use case.
Complete country columns in the COVID-19 case report dataset from CSSE.
First, we will use Python to load a raw COVID-19 case dataset from this URL and load it into the Pandas dataframe, as shown in the following scripts. After loading the dataset, you can see that it contains the country name in the “Country_Region” column.
import pycountryimport pandas as pddf = pd.read_csv('https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_daily_reports/12-18-2020.csv')
Then, we can use the apply method to add country information from the PyCountry database to this dataframe. We can also define the PyCountry countries search as a function to avoid the error in case it does not found the input country name.
The following script shows how to apply the “Alpha 2 Code” to the whole dataframe. You can also do the same to add other attributes to the dataframe.
def findCountry (country_name): try: return pycountry.countries.get(name=country_name).alpha_2 except: return ("not founded")df['country_alpha_2'] = df.apply(lambda row: findCountry(row.Country_Region) , axis = 1)
With these add country columns, we can use them as primary keys to aggregated with other data sets easily.
Please Find it here:
This article gives a short overview of how to get country information using the PyCountry library which can help you to merge data with other datasets easily.
I hope you like this article and found it useful for your daily work or projects. Feel free to leave me a message if you have any questions or comments.
About me & Check out all my blog contents: Link
Be Safe and Healthy! 💪
Thank you for Reading. 📚 | [
{
"code": null,
"e": 619,
"s": 172,
"text": "In data science projects, you may have a data table that contains country data like country name, country code, etc. But, different data sets usually provide data in different country data formats or attributes; for example, “Germany” can be recorded as “GER”, “Germany”, “DE”, “Federal Republic of Germany”, country code — 276, etc.). This would cause you some difficulties to join tables, data aggregation, data analysis, or data visualization."
},
{
"code": null,
"e": 790,
"s": 619,
"text": "This article introduces PyCountry, a Python library for completing the country data from the country database to ready your dataset to be matched or aggregated to others."
},
{
"code": null,
"e": 809,
"s": 790,
"text": "Let’s get started~"
},
{
"code": null,
"e": 874,
"s": 809,
"text": "You can install this library using pip as the following command:"
},
{
"code": null,
"e": 898,
"s": 874,
"text": "$ pip install pycountry"
},
{
"code": null,
"e": 974,
"s": 898,
"text": "First, you can create a blank Python file and import the pycountry library."
},
{
"code": null,
"e": 991,
"s": 974,
"text": "import pycountry"
},
{
"code": null,
"e": 1074,
"s": 991,
"text": "Then, you can get any information from each country from the following attributes:"
},
{
"code": null,
"e": 1095,
"s": 1074,
"text": "Name (e.g. Thailand)"
},
{
"code": null,
"e": 1120,
"s": 1095,
"text": "Alpha 2 code (e.g. “TH”)"
},
{
"code": null,
"e": 1146,
"s": 1120,
"text": "Alpha 3 code (e.g. “THA”)"
},
{
"code": null,
"e": 1172,
"s": 1146,
"text": "Numeric code (e.g. “764”)"
},
{
"code": null,
"e": 1215,
"s": 1172,
"text": "Official name (e.g. “Kingdom of Thailand”)"
},
{
"code": null,
"e": 1317,
"s": 1215,
"text": "For example, if you have “Alpha 2 code” and you can use countries.get command to get all information:"
},
{
"code": null,
"e": 1464,
"s": 1317,
"text": "pycountry.countries.get(alpha_2='TH')>>> Country(alpha_2='TH', alpha_3='THA', name='Thailand', numeric='764', official_name='Kingdom of Thailand')"
},
{
"code": null,
"e": 1543,
"s": 1464,
"text": "If you want only the nameoutput, you can do it in a single command as follows:"
},
{
"code": null,
"e": 1600,
"s": 1543,
"text": "pycountry.countries.get(alpha_2='TH').name>>> 'Thailand'"
},
{
"code": null,
"e": 1725,
"s": 1600,
"text": "The PyCountry library also comes with a “fuzzy” search to help you to find countries without input their types. For example:"
},
{
"code": null,
"e": 1881,
"s": 1725,
"text": "pycountry.countries.search_fuzzy('Thailand')>>> [Country(alpha_2='TH', alpha_3='THA', name='Thailand', numeric='764', official_name='Kingdom of Thailand')]"
},
{
"code": null,
"e": 1962,
"s": 1881,
"text": "That’s about it. Now, let’s head to try this library in the real-world use case."
},
{
"code": null,
"e": 2034,
"s": 1962,
"text": "Complete country columns in the COVID-19 case report dataset from CSSE."
},
{
"code": null,
"e": 2289,
"s": 2034,
"text": "First, we will use Python to load a raw COVID-19 case dataset from this URL and load it into the Pandas dataframe, as shown in the following scripts. After loading the dataset, you can see that it contains the country name in the “Country_Region” column."
},
{
"code": null,
"e": 2471,
"s": 2289,
"text": "import pycountryimport pandas as pddf = pd.read_csv('https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_daily_reports/12-18-2020.csv')"
},
{
"code": null,
"e": 2712,
"s": 2471,
"text": "Then, we can use the apply method to add country information from the PyCountry database to this dataframe. We can also define the PyCountry countries search as a function to avoid the error in case it does not found the input country name."
},
{
"code": null,
"e": 2862,
"s": 2712,
"text": "The following script shows how to apply the “Alpha 2 Code” to the whole dataframe. You can also do the same to add other attributes to the dataframe."
},
{
"code": null,
"e": 3096,
"s": 2862,
"text": "def findCountry (country_name): try: return pycountry.countries.get(name=country_name).alpha_2 except: return (\"not founded\")df['country_alpha_2'] = df.apply(lambda row: findCountry(row.Country_Region) , axis = 1)"
},
{
"code": null,
"e": 3203,
"s": 3096,
"text": "With these add country columns, we can use them as primary keys to aggregated with other data sets easily."
},
{
"code": null,
"e": 3224,
"s": 3203,
"text": "Please Find it here:"
},
{
"code": null,
"e": 3383,
"s": 3224,
"text": "This article gives a short overview of how to get country information using the PyCountry library which can help you to merge data with other datasets easily."
},
{
"code": null,
"e": 3536,
"s": 3383,
"text": "I hope you like this article and found it useful for your daily work or projects. Feel free to leave me a message if you have any questions or comments."
},
{
"code": null,
"e": 3584,
"s": 3536,
"text": "About me & Check out all my blog contents: Link"
},
{
"code": null,
"e": 3607,
"s": 3584,
"text": "Be Safe and Healthy! 💪"
}
] |
Print 1 2 3 infinitely using threads in C | 22 Jul, 2019
Print 1 2 3 infinitely using thread. Create three threads viz T1, T2, and T3 such that those should print 1 2 3 sequence infinitely.
Examples :
Output :1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 ......
Prerequisite : Threads in C
Approach :
Start an infinite loop and initialize a variable ‘done’ to 1.
Now, check for the value of done is not equal to 1.
If it is hold wait condition lock, else print n and respectively signal the next consecutive n.
// C code to print 1 2 3 infinitely using pthread#include <stdio.h>#include <pthread.h> // Declaration of thread condition variablespthread_cond_t cond1 = PTHREAD_COND_INITIALIZER;pthread_cond_t cond2 = PTHREAD_COND_INITIALIZER;pthread_cond_t cond3 = PTHREAD_COND_INITIALIZER; // mutex which we are going to// use avoid race condition.pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; // done is a global variable which decides // which waiting thread should be scheduledint done = 1; // Thread functionvoid *foo(void *n){ while(1) { // acquire a lock pthread_mutex_lock(&lock); if (done != (int)*(int*)n) { // value of done and n is not equal, // hold wait lock on condition variable if ((int)*(int*)n == 1) { pthread_cond_wait(&cond1, &lock); } else if ((int)*(int*)n == 2) { pthread_cond_wait(&cond2, &lock); } else { pthread_cond_wait(&cond3, &lock); } } // done is equal to n, then print n printf("%d ", *(int*)n); // Now time to schedule next thread accordingly // using pthread_cond_signal() if (done == 3) { done = 1; pthread_cond_signal(&cond1); } else if(done == 1) { done = 2; pthread_cond_signal(&cond2); } else if (done == 2) { done = 3; pthread_cond_signal(&cond3); } // Finally release mutex pthread_mutex_unlock(&lock); } return NULL;} // Driver codeint main(){ pthread_t tid1, tid2, tid3; int n1 = 1, n2 = 2, n3 = 3; // Create 3 threads pthread_create(&tid1, NULL, foo, (void *)&n1); pthread_create(&tid2, NULL, foo, (void *)&n2); pthread_create(&tid3, NULL, foo, (void *)&n3); // infinite loop to avoid exit of a program/process while(1); return 0;}
Output :
1 2 3 1 2 3 1 2 3 1 2 3 ...
Sacheen
nidhi_biet
cpp-multithreading
Processes & Threads
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Multidimensional Arrays in C / C++
Function Pointer in C
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
std::string class in C++
Unordered Sets in C++ Standard Template Library
rand() and srand() in C/C++
Enumeration (or enum) in C
Memory Layout of C Programs | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n22 Jul, 2019"
},
{
"code": null,
"e": 187,
"s": 54,
"text": "Print 1 2 3 infinitely using thread. Create three threads viz T1, T2, and T3 such that those should print 1 2 3 sequence infinitely."
},
{
"code": null,
"e": 198,
"s": 187,
"text": "Examples :"
},
{
"code": null,
"e": 244,
"s": 198,
"text": "Output :1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 ......\n"
},
{
"code": null,
"e": 272,
"s": 244,
"text": "Prerequisite : Threads in C"
},
{
"code": null,
"e": 283,
"s": 272,
"text": "Approach :"
},
{
"code": null,
"e": 345,
"s": 283,
"text": "Start an infinite loop and initialize a variable ‘done’ to 1."
},
{
"code": null,
"e": 397,
"s": 345,
"text": "Now, check for the value of done is not equal to 1."
},
{
"code": null,
"e": 493,
"s": 397,
"text": "If it is hold wait condition lock, else print n and respectively signal the next consecutive n."
},
{
"code": "// C code to print 1 2 3 infinitely using pthread#include <stdio.h>#include <pthread.h> // Declaration of thread condition variablespthread_cond_t cond1 = PTHREAD_COND_INITIALIZER;pthread_cond_t cond2 = PTHREAD_COND_INITIALIZER;pthread_cond_t cond3 = PTHREAD_COND_INITIALIZER; // mutex which we are going to// use avoid race condition.pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; // done is a global variable which decides // which waiting thread should be scheduledint done = 1; // Thread functionvoid *foo(void *n){ while(1) { // acquire a lock pthread_mutex_lock(&lock); if (done != (int)*(int*)n) { // value of done and n is not equal, // hold wait lock on condition variable if ((int)*(int*)n == 1) { pthread_cond_wait(&cond1, &lock); } else if ((int)*(int*)n == 2) { pthread_cond_wait(&cond2, &lock); } else { pthread_cond_wait(&cond3, &lock); } } // done is equal to n, then print n printf(\"%d \", *(int*)n); // Now time to schedule next thread accordingly // using pthread_cond_signal() if (done == 3) { done = 1; pthread_cond_signal(&cond1); } else if(done == 1) { done = 2; pthread_cond_signal(&cond2); } else if (done == 2) { done = 3; pthread_cond_signal(&cond3); } // Finally release mutex pthread_mutex_unlock(&lock); } return NULL;} // Driver codeint main(){ pthread_t tid1, tid2, tid3; int n1 = 1, n2 = 2, n3 = 3; // Create 3 threads pthread_create(&tid1, NULL, foo, (void *)&n1); pthread_create(&tid2, NULL, foo, (void *)&n2); pthread_create(&tid3, NULL, foo, (void *)&n3); // infinite loop to avoid exit of a program/process while(1); return 0;}",
"e": 2941,
"s": 493,
"text": null
},
{
"code": null,
"e": 2950,
"s": 2941,
"text": "Output :"
},
{
"code": null,
"e": 2979,
"s": 2950,
"text": "1 2 3 1 2 3 1 2 3 1 2 3 ...\n"
},
{
"code": null,
"e": 2987,
"s": 2979,
"text": "Sacheen"
},
{
"code": null,
"e": 2998,
"s": 2987,
"text": "nidhi_biet"
},
{
"code": null,
"e": 3017,
"s": 2998,
"text": "cpp-multithreading"
},
{
"code": null,
"e": 3037,
"s": 3017,
"text": "Processes & Threads"
},
{
"code": null,
"e": 3048,
"s": 3037,
"text": "C Language"
},
{
"code": null,
"e": 3146,
"s": 3048,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3163,
"s": 3146,
"text": "Substring in C++"
},
{
"code": null,
"e": 3198,
"s": 3163,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 3220,
"s": 3198,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 3266,
"s": 3220,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 3311,
"s": 3266,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 3336,
"s": 3311,
"text": "std::string class in C++"
},
{
"code": null,
"e": 3384,
"s": 3336,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 3412,
"s": 3384,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 3439,
"s": 3412,
"text": "Enumeration (or enum) in C"
}
] |
Lua - Tables | Tables are the only data structure available in Lua that helps us create different types like arrays and dictionaries. Lua uses associative arrays and which can be indexed with not only numbers but also with strings except nil. Tables have no fixed size and can grow based on our need.
Lua uses tables in all representations including representation of packages. When we access a method string.format, it means, we are accessing the format function available in the string package.
Tables are called objects and they are neither values nor variables. Lua uses a constructor expression {} to create an empty table. It is to be known that there is no fixed relationship between a variable that holds reference of table and the table itself.
--sample table initialization
mytable = {}
--simple table value assignment
mytable[1]= "Lua"
--removing reference
mytable = nil
-- lua garbage collection will take care of releasing memory
When we have a table a with set of elements and if we assign it to b, both a and b refer to the same memory. No separate memory is allocated separately for b. When a is set to nil, table will be still accessible to b. When there are no reference to a table, then garbage collection in Lua takes care of cleaning up process to make these unreferenced memory to be reused again.
An example is shown below for explaining the above mentioned features of tables.
-- Simple empty table
mytable = {}
print("Type of mytable is ",type(mytable))
mytable[1]= "Lua"
mytable["wow"] = "Tutorial"
print("mytable Element at index 1 is ", mytable[1])
print("mytable Element at index wow is ", mytable["wow"])
-- alternatetable and mytable refers to same table
alternatetable = mytable
print("alternatetable Element at index 1 is ", alternatetable[1])
print("alternatetable Element at index wow is ", alternatetable["wow"])
alternatetable["wow"] = "I changed it"
print("mytable Element at index wow is ", mytable["wow"])
-- only variable released and and not table
alternatetable = nil
print("alternatetable is ", alternatetable)
-- mytable is still accessible
print("mytable Element at index wow is ", mytable["wow"])
mytable = nil
print("mytable is ", mytable)
When we run the above program we will get the following output −
Type of mytable is table
mytable Element at index 1 is Lua
mytable Element at index wow is Tutorial
alternatetable Element at index 1 is Lua
alternatetable Element at index wow is Tutorial
mytable Element at index wow is I changed it
alternatetable is nil
mytable Element at index wow is I changed it
mytable is nil
There are in built functions for table manipulation and they are listed in the following table.
table.concat (table [, sep [, i [, j]]])
Concatenates the strings in the tables based on the parameters given. See example for detail.
table.insert (table, [pos,] value)
Inserts a value into the table at specified position.
table.maxn (table)
Returns the largest numeric index.
table.remove (table [, pos])
Removes the value from the table.
table.sort (table [, comp])
Sorts the table based on optional comparator argument.
Let us see some samples of the above functions.
We can use the concat function to concatenate two tables as shown below −
fruits = {"banana","orange","apple"}
-- returns concatenated string of table
print("Concatenated string ",table.concat(fruits))
--concatenate with a character
print("Concatenated string ",table.concat(fruits,", "))
--concatenate fruits based on index
print("Concatenated string ",table.concat(fruits,", ", 2,3))
When we run the above program we will get the following output −
Concatenated string bananaorangeapple
Concatenated string banana, orange, apple
Concatenated string orange, apple
Insertion and removal of items in tables is most common in table manipulation. It is explained below.
fruits = {"banana","orange","apple"}
-- insert a fruit at the end
table.insert(fruits,"mango")
print("Fruit at index 4 is ",fruits[4])
--insert fruit at index 2
table.insert(fruits,2,"grapes")
print("Fruit at index 2 is ",fruits[2])
print("The maximum elements in table is",table.maxn(fruits))
print("The last element is",fruits[5])
table.remove(fruits)
print("The previous last element is",fruits[5])
When we run the above program, we will get the following output −
Fruit at index 4 is mango
Fruit at index 2 is grapes
The maximum elements in table is 5
The last element is mango
The previous last element is nil
We often require to sort a table in a particular order. The sort functions sort the elements in a table alphabetically. A sample for this is shown below.
fruits = {"banana","orange","apple","grapes"}
for k,v in ipairs(fruits) do
print(k,v)
end
table.sort(fruits)
print("sorted table")
for k,v in ipairs(fruits) do
print(k,v)
end
When we run the above program we will get the following output − | [
{
"code": null,
"e": 2523,
"s": 2237,
"text": "Tables are the only data structure available in Lua that helps us create different types like arrays and dictionaries. Lua uses associative arrays and which can be indexed with not only numbers but also with strings except nil. Tables have no fixed size and can grow based on our need."
},
{
"code": null,
"e": 2719,
"s": 2523,
"text": "Lua uses tables in all representations including representation of packages. When we access a method string.format, it means, we are accessing the format function available in the string package."
},
{
"code": null,
"e": 2976,
"s": 2719,
"text": "Tables are called objects and they are neither values nor variables. Lua uses a constructor expression {} to create an empty table. It is to be known that there is no fixed relationship between a variable that holds reference of table and the table itself."
},
{
"code": null,
"e": 3169,
"s": 2976,
"text": "--sample table initialization\nmytable = {}\n\n--simple table value assignment\nmytable[1]= \"Lua\"\n\n--removing reference\nmytable = nil\n\n-- lua garbage collection will take care of releasing memory\n"
},
{
"code": null,
"e": 3546,
"s": 3169,
"text": "When we have a table a with set of elements and if we assign it to b, both a and b refer to the same memory. No separate memory is allocated separately for b. When a is set to nil, table will be still accessible to b. When there are no reference to a table, then garbage collection in Lua takes care of cleaning up process to make these unreferenced memory to be reused again."
},
{
"code": null,
"e": 3627,
"s": 3546,
"text": "An example is shown below for explaining the above mentioned features of tables."
},
{
"code": null,
"e": 4423,
"s": 3627,
"text": "-- Simple empty table\nmytable = {}\nprint(\"Type of mytable is \",type(mytable))\n\nmytable[1]= \"Lua\"\nmytable[\"wow\"] = \"Tutorial\"\n\nprint(\"mytable Element at index 1 is \", mytable[1])\nprint(\"mytable Element at index wow is \", mytable[\"wow\"])\n\n-- alternatetable and mytable refers to same table\nalternatetable = mytable\n\nprint(\"alternatetable Element at index 1 is \", alternatetable[1])\nprint(\"alternatetable Element at index wow is \", alternatetable[\"wow\"])\n\nalternatetable[\"wow\"] = \"I changed it\"\n\nprint(\"mytable Element at index wow is \", mytable[\"wow\"])\n\n-- only variable released and and not table\nalternatetable = nil\nprint(\"alternatetable is \", alternatetable)\n\n-- mytable is still accessible\nprint(\"mytable Element at index wow is \", mytable[\"wow\"])\n\nmytable = nil\nprint(\"mytable is \", mytable)"
},
{
"code": null,
"e": 4488,
"s": 4423,
"text": "When we run the above program we will get the following output −"
},
{
"code": null,
"e": 4814,
"s": 4488,
"text": "Type of mytable is \ttable\nmytable Element at index 1 is \tLua\nmytable Element at index wow is \tTutorial\nalternatetable Element at index 1 is \tLua\nalternatetable Element at index wow is \tTutorial\nmytable Element at index wow is \tI changed it\nalternatetable is \tnil\nmytable Element at index wow is \tI changed it\nmytable is \tnil\n"
},
{
"code": null,
"e": 4910,
"s": 4814,
"text": "There are in built functions for table manipulation and they are listed in the following table."
},
{
"code": null,
"e": 4951,
"s": 4910,
"text": "table.concat (table [, sep [, i [, j]]])"
},
{
"code": null,
"e": 5045,
"s": 4951,
"text": "Concatenates the strings in the tables based on the parameters given. See example for detail."
},
{
"code": null,
"e": 5080,
"s": 5045,
"text": "table.insert (table, [pos,] value)"
},
{
"code": null,
"e": 5134,
"s": 5080,
"text": "Inserts a value into the table at specified position."
},
{
"code": null,
"e": 5153,
"s": 5134,
"text": "table.maxn (table)"
},
{
"code": null,
"e": 5188,
"s": 5153,
"text": "Returns the largest numeric index."
},
{
"code": null,
"e": 5217,
"s": 5188,
"text": "table.remove (table [, pos])"
},
{
"code": null,
"e": 5251,
"s": 5217,
"text": "Removes the value from the table."
},
{
"code": null,
"e": 5279,
"s": 5251,
"text": "table.sort (table [, comp])"
},
{
"code": null,
"e": 5334,
"s": 5279,
"text": "Sorts the table based on optional comparator argument."
},
{
"code": null,
"e": 5382,
"s": 5334,
"text": "Let us see some samples of the above functions."
},
{
"code": null,
"e": 5456,
"s": 5382,
"text": "We can use the concat function to concatenate two tables as shown below −"
},
{
"code": null,
"e": 5771,
"s": 5456,
"text": "fruits = {\"banana\",\"orange\",\"apple\"}\n\n-- returns concatenated string of table\nprint(\"Concatenated string \",table.concat(fruits))\n\n--concatenate with a character\nprint(\"Concatenated string \",table.concat(fruits,\", \"))\n\n--concatenate fruits based on index\nprint(\"Concatenated string \",table.concat(fruits,\", \", 2,3))"
},
{
"code": null,
"e": 5836,
"s": 5771,
"text": "When we run the above program we will get the following output −"
},
{
"code": null,
"e": 5954,
"s": 5836,
"text": "Concatenated string \tbananaorangeapple\nConcatenated string \tbanana, orange, apple\nConcatenated string \torange, apple\n"
},
{
"code": null,
"e": 6056,
"s": 5954,
"text": "Insertion and removal of items in tables is most common in table manipulation. It is explained below."
},
{
"code": null,
"e": 6463,
"s": 6056,
"text": "fruits = {\"banana\",\"orange\",\"apple\"}\n\n-- insert a fruit at the end\ntable.insert(fruits,\"mango\")\nprint(\"Fruit at index 4 is \",fruits[4])\n\n--insert fruit at index 2\ntable.insert(fruits,2,\"grapes\")\nprint(\"Fruit at index 2 is \",fruits[2])\n\nprint(\"The maximum elements in table is\",table.maxn(fruits))\n\nprint(\"The last element is\",fruits[5])\n\ntable.remove(fruits)\nprint(\"The previous last element is\",fruits[5])"
},
{
"code": null,
"e": 6529,
"s": 6463,
"text": "When we run the above program, we will get the following output −"
},
{
"code": null,
"e": 6679,
"s": 6529,
"text": "Fruit at index 4 is \tmango\nFruit at index 2 is \tgrapes\nThe maximum elements in table is\t5\nThe last element is\tmango\nThe previous last element is\tnil\n"
},
{
"code": null,
"e": 6833,
"s": 6679,
"text": "We often require to sort a table in a particular order. The sort functions sort the elements in a table alphabetically. A sample for this is shown below."
},
{
"code": null,
"e": 7017,
"s": 6833,
"text": "fruits = {\"banana\",\"orange\",\"apple\",\"grapes\"}\n\nfor k,v in ipairs(fruits) do\n print(k,v)\nend\n\ntable.sort(fruits)\nprint(\"sorted table\")\n\nfor k,v in ipairs(fruits) do\n print(k,v)\nend"
}
] |
Python – Uppercase Nth character | 30 Jan, 2020
The problem of capitalizing a string is quite common and has been discussed many times. But sometimes, we might have a problem like this in which we need to convert the Nth character of string to uppercase. Let’s discuss certain ways in which this can be performed.
Method #1 : Using string slicing + upper()This task can easily be performed using the upper method which uppercases the characters provided to it and slicing can be used to add the remaining string after the uppercase Nth character.
# Python3 code to demonstrate working of# Uppercase Nth character# Using upper() + string slicing # initializing string test_str = "GeeksforGeeks" # printing original string print("The original string is : " + str(test_str)) # initializing N N = 4 # Using upper() + string slicing# Uppercase Nth characterres = test_str[:N] + test_str[N].upper() + test_str[N + 1:] # printing result print("The string after uppercasing Nth character : " + str(res))
The original string is : GeeksforGeeks
The string after uppercasing Nth character : GeekSforGeeks
Method #2 : Using lambda + string slicing + upper()The recipe of lambda function has to be added if we need to perform the task of handling None values or empty strings as well, and this becomes essential to handle edge cases.
# Python3 code to demonstrate working of# Uppercase Nth character# Using upper() + string slicing + lambda # initializing string test_str = "GeeksforGeeks" # printing original string print("The original string is : " + str(test_str)) # initializing N N = 4 # Using upper() + string slicing + lambda# Uppercase Nth characterres = lambda test_str: test_str[:N] + test_str[N].upper() + test_str[N + 1:] if test_str else '' # printing result print("The string after uppercasing initial character : " + str(res(test_str)))
The original string is : GeeksforGeeks
The string after uppercasing Nth character : GeekSforGeeks
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Split string into list of characters | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Jan, 2020"
},
{
"code": null,
"e": 294,
"s": 28,
"text": "The problem of capitalizing a string is quite common and has been discussed many times. But sometimes, we might have a problem like this in which we need to convert the Nth character of string to uppercase. Let’s discuss certain ways in which this can be performed."
},
{
"code": null,
"e": 527,
"s": 294,
"text": "Method #1 : Using string slicing + upper()This task can easily be performed using the upper method which uppercases the characters provided to it and slicing can be used to add the remaining string after the uppercase Nth character."
},
{
"code": "# Python3 code to demonstrate working of# Uppercase Nth character# Using upper() + string slicing # initializing string test_str = \"GeeksforGeeks\" # printing original string print(\"The original string is : \" + str(test_str)) # initializing N N = 4 # Using upper() + string slicing# Uppercase Nth characterres = test_str[:N] + test_str[N].upper() + test_str[N + 1:] # printing result print(\"The string after uppercasing Nth character : \" + str(res))",
"e": 981,
"s": 527,
"text": null
},
{
"code": null,
"e": 1080,
"s": 981,
"text": "The original string is : GeeksforGeeks\nThe string after uppercasing Nth character : GeekSforGeeks\n"
},
{
"code": null,
"e": 1309,
"s": 1082,
"text": "Method #2 : Using lambda + string slicing + upper()The recipe of lambda function has to be added if we need to perform the task of handling None values or empty strings as well, and this becomes essential to handle edge cases."
},
{
"code": "# Python3 code to demonstrate working of# Uppercase Nth character# Using upper() + string slicing + lambda # initializing string test_str = \"GeeksforGeeks\" # printing original string print(\"The original string is : \" + str(test_str)) # initializing N N = 4 # Using upper() + string slicing + lambda# Uppercase Nth characterres = lambda test_str: test_str[:N] + test_str[N].upper() + test_str[N + 1:] if test_str else '' # printing result print(\"The string after uppercasing initial character : \" + str(res(test_str)))",
"e": 1832,
"s": 1309,
"text": null
},
{
"code": null,
"e": 1931,
"s": 1832,
"text": "The original string is : GeeksforGeeks\nThe string after uppercasing Nth character : GeekSforGeeks\n"
},
{
"code": null,
"e": 1954,
"s": 1931,
"text": "Python string-programs"
},
{
"code": null,
"e": 1961,
"s": 1954,
"text": "Python"
},
{
"code": null,
"e": 1977,
"s": 1961,
"text": "Python Programs"
},
{
"code": null,
"e": 2075,
"s": 1977,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2093,
"s": 2075,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2135,
"s": 2093,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2157,
"s": 2135,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2183,
"s": 2157,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2215,
"s": 2183,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2237,
"s": 2215,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2276,
"s": 2237,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2314,
"s": 2276,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2351,
"s": 2314,
"text": "Python Program for Fibonacci numbers"
}
] |
Types of Literals in C/C++ with Examples | 19 May, 2022
The values assigned to each constant variable are referred to as the literals. Generally, both terms, constants, and literals are used interchangeably.
For example, “const int = 5;“, is a constant expression and the value 5 is referred to as a constant integer literal. There are 4 types of literal in C and five types of literal in C++.
These are used to represent and store the integer values. Integer literals are expressed in two types i.e.
A) Prefixes: The Prefix of the integer literal indicates the base in which it is to be read.
For Example:
0x10 = 16
Because 0x prefix represents a HexaDecimal base. So 10 in HexaDecimal is 16 in Decimal. Hence the value 16.
There are basically represented in 4 types.
a. Decimal-literal(base 10): A non-zero decimal digit followed by zero or more decimal digits(0, 1, 2, 3, 4, 5, 6, 7, 8, 9).
Example:
56, 78
b. Octal-literal(base 8): a 0 followed by zero or more octal digits(0, 1, 2, 3, 4, 5, 6, 7).
Example:
045, 076, 06210
c. Hex-literal(base 16): 0x or 0X followed by one or more hexadecimal digits(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, A, b, B, c, C, d, D, e, E, f, F).
Example:
0x23A, 0Xb4C, 0xFEA
d. Binary-literal(base 2): 0b or 0B followed by one or more binary digits(0, 1).
Example:
0b101, 0B111
B) Suffixes: The Prefix of the integer literal indicates the type in which it is to be read.
For example:
12345678901234LL
indicates a long long integer value 12345678901234 because of the suffix LL
These are represented in many ways according to their data types.
int: No suffix is required because integer constant is by default assigned as an int data type.
unsigned int: character u or U at the end of an integer constant.
long int: character l or L at the end of an integer constant.
unsigned long int: character ul or UL at the end of an integer constant.
long long int: character ll or LL at the end of an integer constant.
unsigned long long int: character ull or ULL at the end of an integer constant.
Example:
C
C++
#include <stdio.h> int main(){ // constant integer literal const int intVal = 10; printf("Integer Literal:%d \n", intVal); return 0;}
#include <iostream>using namespace std; int main(){ // constant integer literal const int intVal = 10; cout << "Integer Literal: " << intVal << "\n"; return 0;}
Output:
Integer Literal:10
These are used to represent and store real numbers. The real number has an integer part, real part, fractional part, and exponential part. The floating-point literals can be stored either in decimal form or exponential form. While representing the floating-point decimals one must keep two things in mind to produce valid literal:
In the decimal form, one must include the decimal point, exponent part, or both, otherwise, it will lead to an error.
In the exponential form, one must include the integer part, fractional part, or both, otherwise, it will lead to an error.
Few floating-point literal representations are shown below:
Valid Floating Literals:
10.125
1.215-10L
10.5E-3
Invalid Floating Literals:
123E
1250f
0.e879
Example:
C++
C
#include <iostream>using namespace std; int main(){ // Real literal const float floatVal = 4.14; cout << "Floating-point literal: " << floatVal << "\n"; return 0;}
#include <stdio.h> int main(){ // constant float literal const float floatVal = 4.14; printf("Floating point literal: %.2f\n", floatVal); return 0;}
Output:
Floating point literal: 4.14
This refers to the literal that is used to store a single character within a single quote. To store multiple characters, one needs to use a character array. Storing more than one character within a single quote will throw a warning and display just the last character of the literal. It gives rise to the following two representations:
A. char type: This is used to store normal character literal or the narrow-character literals. This is supported by both C and C++.
Example:
// For C
char chr = 'G';
// For C++
char chr = 'G';
B. wchar_t type: This literal is supported only in C++ and not in C. If the character is followed by L, then the literal needs to be stored in wchar_t. This represents a wide-character literal.
Example:
// Not Supported For C
// For C++
wchar_t chr = L'G';
Example:
C
C++
#include <stdio.h> int main(){ // constant char literal const char charVal = 'A'; printf("Character Literal: %c\n", charVal); return 0;}
#include <iostream>using namespace std; int main(){ // constant char literal const char charVal = 'A'; // wide char literal const wchar_t charVal1 = L'A'; cout << "Character Literal: " << charVal << "\n"; cout << "Wide_Character Literal: " << charVal1 << "\n"; return 0;} // output// Character Literal: A// Wide_Character Literal: 65
Output:
Character Literal: A
Escape Sequences: There are various special characters that one can use to perform various operations.
String literals are similar to that character literals, except that they can store multiple characters and uses a double quote to store the same. It can also accommodate the special characters and escape sequences mentioned in the table above.
Example:
// For C
char stringVal[] = "GeeksforGeeks";
// For C++
string stringVal = "GeeksforGeeks"
Example:
C++
C
#include <iostream>using namespace std; int main(){ const string str = "Welcome\nTo\nGeeks\tFor\tGeeks"; cout << str; return 0;}
#include <stdio.h> int main(){ const char str[] = "Welcome\nTo\nGeeks\tFor\tGeeks"; printf("%s", str); return 0;}
Output:
Welcome
To
Geeks For Geeks
This literal is provided only in C++ and not in C. They are used to represent the boolean datatypes. These can carry two values:
true: To represent True value. This must not be considered equal to int 1.
false: To represent False value. This must not be considered equal to int 0.
Example:
C++
// C++ program to show Boolean literals #include <iostream>using namespace std; int main(){ const bool isTrue = true; const bool isFalse = false; cout << "isTrue? " << isTrue << "\n"; cout << "isFalse? " << isFalse << "\n"; return 0;}
Output:
isTrue? 1
isFalse? 0
Related Articles on Constants/Literals in C/C++:
User-Defined Literals.
Raw string literal in C++
Octal literals in C
Compound Literals in C
Type difference of character literals C++.
Akanksha_Rai
sackshamsharmaintern
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Function Pointer in C
Multidimensional Arrays in C / C++
Different Methods to Reverse a String in C++
Left Shift and Right Shift Operators in C/C++
Vector in C++ STL
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++ | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n19 May, 2022"
},
{
"code": null,
"e": 206,
"s": 53,
"text": "The values assigned to each constant variable are referred to as the literals. Generally, both terms, constants, and literals are used interchangeably. "
},
{
"code": null,
"e": 393,
"s": 206,
"text": "For example, “const int = 5;“, is a constant expression and the value 5 is referred to as a constant integer literal. There are 4 types of literal in C and five types of literal in C++. "
},
{
"code": null,
"e": 500,
"s": 393,
"text": "These are used to represent and store the integer values. Integer literals are expressed in two types i.e."
},
{
"code": null,
"e": 593,
"s": 500,
"text": "A) Prefixes: The Prefix of the integer literal indicates the base in which it is to be read."
},
{
"code": null,
"e": 606,
"s": 593,
"text": "For Example:"
},
{
"code": null,
"e": 616,
"s": 606,
"text": "0x10 = 16"
},
{
"code": null,
"e": 725,
"s": 616,
"text": "Because 0x prefix represents a HexaDecimal base. So 10 in HexaDecimal is 16 in Decimal. Hence the value 16. "
},
{
"code": null,
"e": 769,
"s": 725,
"text": "There are basically represented in 4 types."
},
{
"code": null,
"e": 894,
"s": 769,
"text": "a. Decimal-literal(base 10): A non-zero decimal digit followed by zero or more decimal digits(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)."
},
{
"code": null,
"e": 903,
"s": 894,
"text": "Example:"
},
{
"code": null,
"e": 910,
"s": 903,
"text": "56, 78"
},
{
"code": null,
"e": 1003,
"s": 910,
"text": "b. Octal-literal(base 8): a 0 followed by zero or more octal digits(0, 1, 2, 3, 4, 5, 6, 7)."
},
{
"code": null,
"e": 1012,
"s": 1003,
"text": "Example:"
},
{
"code": null,
"e": 1028,
"s": 1012,
"text": "045, 076, 06210"
},
{
"code": null,
"e": 1172,
"s": 1028,
"text": "c. Hex-literal(base 16): 0x or 0X followed by one or more hexadecimal digits(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, A, b, B, c, C, d, D, e, E, f, F)."
},
{
"code": null,
"e": 1181,
"s": 1172,
"text": "Example:"
},
{
"code": null,
"e": 1201,
"s": 1181,
"text": "0x23A, 0Xb4C, 0xFEA"
},
{
"code": null,
"e": 1282,
"s": 1201,
"text": "d. Binary-literal(base 2): 0b or 0B followed by one or more binary digits(0, 1)."
},
{
"code": null,
"e": 1291,
"s": 1282,
"text": "Example:"
},
{
"code": null,
"e": 1304,
"s": 1291,
"text": "0b101, 0B111"
},
{
"code": null,
"e": 1397,
"s": 1304,
"text": "B) Suffixes: The Prefix of the integer literal indicates the type in which it is to be read."
},
{
"code": null,
"e": 1410,
"s": 1397,
"text": "For example:"
},
{
"code": null,
"e": 1428,
"s": 1410,
"text": "12345678901234LL "
},
{
"code": null,
"e": 1504,
"s": 1428,
"text": "indicates a long long integer value 12345678901234 because of the suffix LL"
},
{
"code": null,
"e": 1570,
"s": 1504,
"text": "These are represented in many ways according to their data types."
},
{
"code": null,
"e": 1666,
"s": 1570,
"text": "int: No suffix is required because integer constant is by default assigned as an int data type."
},
{
"code": null,
"e": 1732,
"s": 1666,
"text": "unsigned int: character u or U at the end of an integer constant."
},
{
"code": null,
"e": 1794,
"s": 1732,
"text": "long int: character l or L at the end of an integer constant."
},
{
"code": null,
"e": 1867,
"s": 1794,
"text": "unsigned long int: character ul or UL at the end of an integer constant."
},
{
"code": null,
"e": 1936,
"s": 1867,
"text": "long long int: character ll or LL at the end of an integer constant."
},
{
"code": null,
"e": 2016,
"s": 1936,
"text": "unsigned long long int: character ull or ULL at the end of an integer constant."
},
{
"code": null,
"e": 2025,
"s": 2016,
"text": "Example:"
},
{
"code": null,
"e": 2027,
"s": 2025,
"text": "C"
},
{
"code": null,
"e": 2031,
"s": 2027,
"text": "C++"
},
{
"code": "#include <stdio.h> int main(){ // constant integer literal const int intVal = 10; printf(\"Integer Literal:%d \\n\", intVal); return 0;}",
"e": 2190,
"s": 2031,
"text": null
},
{
"code": "#include <iostream>using namespace std; int main(){ // constant integer literal const int intVal = 10; cout << \"Integer Literal: \" << intVal << \"\\n\"; return 0;}",
"e": 2372,
"s": 2190,
"text": null
},
{
"code": null,
"e": 2380,
"s": 2372,
"text": "Output:"
},
{
"code": null,
"e": 2399,
"s": 2380,
"text": "Integer Literal:10"
},
{
"code": null,
"e": 2730,
"s": 2399,
"text": "These are used to represent and store real numbers. The real number has an integer part, real part, fractional part, and exponential part. The floating-point literals can be stored either in decimal form or exponential form. While representing the floating-point decimals one must keep two things in mind to produce valid literal:"
},
{
"code": null,
"e": 2848,
"s": 2730,
"text": "In the decimal form, one must include the decimal point, exponent part, or both, otherwise, it will lead to an error."
},
{
"code": null,
"e": 2971,
"s": 2848,
"text": "In the exponential form, one must include the integer part, fractional part, or both, otherwise, it will lead to an error."
},
{
"code": null,
"e": 3031,
"s": 2971,
"text": "Few floating-point literal representations are shown below:"
},
{
"code": null,
"e": 3056,
"s": 3031,
"text": "Valid Floating Literals:"
},
{
"code": null,
"e": 3081,
"s": 3056,
"text": "10.125\n1.215-10L\n10.5E-3"
},
{
"code": null,
"e": 3108,
"s": 3081,
"text": "Invalid Floating Literals:"
},
{
"code": null,
"e": 3126,
"s": 3108,
"text": "123E\n1250f\n0.e879"
},
{
"code": null,
"e": 3135,
"s": 3126,
"text": "Example:"
},
{
"code": null,
"e": 3139,
"s": 3135,
"text": "C++"
},
{
"code": null,
"e": 3141,
"s": 3139,
"text": "C"
},
{
"code": "#include <iostream>using namespace std; int main(){ // Real literal const float floatVal = 4.14; cout << \"Floating-point literal: \" << floatVal << \"\\n\"; return 0;}",
"e": 3326,
"s": 3141,
"text": null
},
{
"code": "#include <stdio.h> int main(){ // constant float literal const float floatVal = 4.14; printf(\"Floating point literal: %.2f\\n\", floatVal); return 0;}",
"e": 3495,
"s": 3326,
"text": null
},
{
"code": null,
"e": 3503,
"s": 3495,
"text": "Output:"
},
{
"code": null,
"e": 3532,
"s": 3503,
"text": "Floating point literal: 4.14"
},
{
"code": null,
"e": 3868,
"s": 3532,
"text": "This refers to the literal that is used to store a single character within a single quote. To store multiple characters, one needs to use a character array. Storing more than one character within a single quote will throw a warning and display just the last character of the literal. It gives rise to the following two representations:"
},
{
"code": null,
"e": 4000,
"s": 3868,
"text": "A. char type: This is used to store normal character literal or the narrow-character literals. This is supported by both C and C++."
},
{
"code": null,
"e": 4009,
"s": 4000,
"text": "Example:"
},
{
"code": null,
"e": 4062,
"s": 4009,
"text": "// For C\nchar chr = 'G';\n\n// For C++\nchar chr = 'G';"
},
{
"code": null,
"e": 4256,
"s": 4062,
"text": "B. wchar_t type: This literal is supported only in C++ and not in C. If the character is followed by L, then the literal needs to be stored in wchar_t. This represents a wide-character literal."
},
{
"code": null,
"e": 4265,
"s": 4256,
"text": "Example:"
},
{
"code": null,
"e": 4320,
"s": 4265,
"text": "// Not Supported For C\n\n// For C++\nwchar_t chr = L'G';"
},
{
"code": null,
"e": 4329,
"s": 4320,
"text": "Example:"
},
{
"code": null,
"e": 4331,
"s": 4329,
"text": "C"
},
{
"code": null,
"e": 4335,
"s": 4331,
"text": "C++"
},
{
"code": "#include <stdio.h> int main(){ // constant char literal const char charVal = 'A'; printf(\"Character Literal: %c\\n\", charVal); return 0;}",
"e": 4492,
"s": 4335,
"text": null
},
{
"code": "#include <iostream>using namespace std; int main(){ // constant char literal const char charVal = 'A'; // wide char literal const wchar_t charVal1 = L'A'; cout << \"Character Literal: \" << charVal << \"\\n\"; cout << \"Wide_Character Literal: \" << charVal1 << \"\\n\"; return 0;} // output// Character Literal: A// Wide_Character Literal: 65",
"e": 4874,
"s": 4492,
"text": null
},
{
"code": null,
"e": 4882,
"s": 4874,
"text": "Output:"
},
{
"code": null,
"e": 4903,
"s": 4882,
"text": "Character Literal: A"
},
{
"code": null,
"e": 5006,
"s": 4903,
"text": "Escape Sequences: There are various special characters that one can use to perform various operations."
},
{
"code": null,
"e": 5250,
"s": 5006,
"text": "String literals are similar to that character literals, except that they can store multiple characters and uses a double quote to store the same. It can also accommodate the special characters and escape sequences mentioned in the table above."
},
{
"code": null,
"e": 5259,
"s": 5250,
"text": "Example:"
},
{
"code": null,
"e": 5351,
"s": 5259,
"text": "// For C\nchar stringVal[] = \"GeeksforGeeks\";\n\n// For C++\nstring stringVal = \"GeeksforGeeks\""
},
{
"code": null,
"e": 5360,
"s": 5351,
"text": "Example:"
},
{
"code": null,
"e": 5364,
"s": 5360,
"text": "C++"
},
{
"code": null,
"e": 5366,
"s": 5364,
"text": "C"
},
{
"code": "#include <iostream>using namespace std; int main(){ const string str = \"Welcome\\nTo\\nGeeks\\tFor\\tGeeks\"; cout << str; return 0;}",
"e": 5511,
"s": 5366,
"text": null
},
{
"code": "#include <stdio.h> int main(){ const char str[] = \"Welcome\\nTo\\nGeeks\\tFor\\tGeeks\"; printf(\"%s\", str); return 0;}",
"e": 5641,
"s": 5511,
"text": null
},
{
"code": null,
"e": 5649,
"s": 5641,
"text": "Output:"
},
{
"code": null,
"e": 5682,
"s": 5649,
"text": "Welcome\nTo\nGeeks For Geeks"
},
{
"code": null,
"e": 5811,
"s": 5682,
"text": "This literal is provided only in C++ and not in C. They are used to represent the boolean datatypes. These can carry two values:"
},
{
"code": null,
"e": 5886,
"s": 5811,
"text": "true: To represent True value. This must not be considered equal to int 1."
},
{
"code": null,
"e": 5963,
"s": 5886,
"text": "false: To represent False value. This must not be considered equal to int 0."
},
{
"code": null,
"e": 5972,
"s": 5963,
"text": "Example:"
},
{
"code": null,
"e": 5976,
"s": 5972,
"text": "C++"
},
{
"code": "// C++ program to show Boolean literals #include <iostream>using namespace std; int main(){ const bool isTrue = true; const bool isFalse = false; cout << \"isTrue? \" << isTrue << \"\\n\"; cout << \"isFalse? \" << isFalse << \"\\n\"; return 0;}",
"e": 6242,
"s": 5976,
"text": null
},
{
"code": null,
"e": 6250,
"s": 6242,
"text": "Output:"
},
{
"code": null,
"e": 6271,
"s": 6250,
"text": "isTrue? 1\nisFalse? 0"
},
{
"code": null,
"e": 6320,
"s": 6271,
"text": "Related Articles on Constants/Literals in C/C++:"
},
{
"code": null,
"e": 6343,
"s": 6320,
"text": "User-Defined Literals."
},
{
"code": null,
"e": 6369,
"s": 6343,
"text": "Raw string literal in C++"
},
{
"code": null,
"e": 6389,
"s": 6369,
"text": "Octal literals in C"
},
{
"code": null,
"e": 6412,
"s": 6389,
"text": "Compound Literals in C"
},
{
"code": null,
"e": 6455,
"s": 6412,
"text": "Type difference of character literals C++."
},
{
"code": null,
"e": 6468,
"s": 6455,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 6489,
"s": 6468,
"text": "sackshamsharmaintern"
},
{
"code": null,
"e": 6500,
"s": 6489,
"text": "C Language"
},
{
"code": null,
"e": 6504,
"s": 6500,
"text": "C++"
},
{
"code": null,
"e": 6508,
"s": 6504,
"text": "CPP"
},
{
"code": null,
"e": 6606,
"s": 6508,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6623,
"s": 6606,
"text": "Substring in C++"
},
{
"code": null,
"e": 6645,
"s": 6623,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 6680,
"s": 6645,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 6725,
"s": 6680,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 6771,
"s": 6725,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 6789,
"s": 6771,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 6832,
"s": 6789,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 6878,
"s": 6832,
"text": "Initialize a vector in C++ (7 different ways)"
},
{
"code": null,
"e": 6921,
"s": 6878,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Vue.js | v-html directive | 07 Jun, 2022
The v-html directive is a Vue.js directive used to update a element’s inner HTML with our data. This is what separates it from v-text which means while v-text accepts string and treats it as a string it will accept string and render it into HTML. First, we will create a div element with id as app and let’s apply the v-html directive to this element with data as a message. Now we will create this message by initializing a Vue instance with the data attribute containing our message.
Scoped styles won’t apply to v-html, because Vue doesn’t compile that HTML. In order to apply styles to it try using global styles or some other CSS Modules.
Syntax:
v-html="data"
Parameters: This directive accepts a single parameter which is the data in the form of a string. Example: This example uses VueJS to update the html of a element with v-html.
HTML
<!DOCTYPE html><html> <head> <title> VueJS | v-html directive </title> <!-- Load Vuejs --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"> </script> </script></head> <body> <div style="text-align: center;width: 600px;"> <h1 style="color: green;"> GeeksforGeeks </h1> <b> VueJS | v-html directive </b> </div> <div id="canvas" style="border:1px solid #000000; width: 600px;height: 200px;"> <div v-html="message" id="app"> </div> </div> <script> var app = new Vue({ el: '#app', data: { message: '<h1>HELLO '+ '<span style="color:blue;">'+ 'WORLD</span>'+ '</h1>' } }) </script></body> </html>
Output:
satyamm09
Vue.JS
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
How to append HTML code to a div using JavaScript ?
Difference Between PUT and PATCH Request
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Jun, 2022"
},
{
"code": null,
"e": 514,
"s": 28,
"text": "The v-html directive is a Vue.js directive used to update a element’s inner HTML with our data. This is what separates it from v-text which means while v-text accepts string and treats it as a string it will accept string and render it into HTML. First, we will create a div element with id as app and let’s apply the v-html directive to this element with data as a message. Now we will create this message by initializing a Vue instance with the data attribute containing our message."
},
{
"code": null,
"e": 672,
"s": 514,
"text": "Scoped styles won’t apply to v-html, because Vue doesn’t compile that HTML. In order to apply styles to it try using global styles or some other CSS Modules."
},
{
"code": null,
"e": 680,
"s": 672,
"text": "Syntax:"
},
{
"code": null,
"e": 694,
"s": 680,
"text": "v-html=\"data\""
},
{
"code": null,
"e": 869,
"s": 694,
"text": "Parameters: This directive accepts a single parameter which is the data in the form of a string. Example: This example uses VueJS to update the html of a element with v-html."
},
{
"code": null,
"e": 874,
"s": 869,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title> VueJS | v-html directive </title> <!-- Load Vuejs --> <script src=\"https://cdn.jsdelivr.net/npm/vue/dist/vue.js\"> </script> </script></head> <body> <div style=\"text-align: center;width: 600px;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <b> VueJS | v-html directive </b> </div> <div id=\"canvas\" style=\"border:1px solid #000000; width: 600px;height: 200px;\"> <div v-html=\"message\" id=\"app\"> </div> </div> <script> var app = new Vue({ el: '#app', data: { message: '<h1>HELLO '+ '<span style=\"color:blue;\">'+ 'WORLD</span>'+ '</h1>' } }) </script></body> </html>",
"e": 1754,
"s": 874,
"text": null
},
{
"code": null,
"e": 1762,
"s": 1754,
"text": "Output:"
},
{
"code": null,
"e": 1772,
"s": 1762,
"text": "satyamm09"
},
{
"code": null,
"e": 1779,
"s": 1772,
"text": "Vue.JS"
},
{
"code": null,
"e": 1790,
"s": 1779,
"text": "JavaScript"
},
{
"code": null,
"e": 1807,
"s": 1790,
"text": "Web Technologies"
},
{
"code": null,
"e": 1905,
"s": 1807,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1966,
"s": 1905,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2038,
"s": 1966,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 2078,
"s": 2038,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2130,
"s": 2078,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 2171,
"s": 2130,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 2233,
"s": 2171,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2266,
"s": 2233,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2327,
"s": 2266,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2377,
"s": 2327,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Queue.Contains() Method in C# | 05 Feb, 2021
This method is used to check whether an element is in the Queue. This method performs a linear search, therefore, this method is an O(n) operation, where n is Count. And this method comes under the System.Collections namespace.
Syntax:
public virtual bool Contains(object obj);
Here, obj is the Object to locate in the Queue. The value can be null.
Return Value: The function returns True if the element exists in the Queue and returns False if the element doesn’t exist in the Queue.
Below given are some examples to understand the implementation in a better way:
Example 1:
C#
// C# code to illustrate the// Queue.Contains() Methodusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Queue Queue myQueue = new Queue<int>(); // Inserting the elements into the Queue myQueue.Enqueue(5); myQueue.Enqueue(10); myQueue.Enqueue(15); myQueue.Enqueue(20); myQueue.Enqueue(25); // Checking whether the element is // present in the Queue or not // The function returns True if the // element is present in the Queue, else // returns False Console.WriteLine(myQueue.Contains(7)); }}
False
Example 2:
C#
// C# code to illustrate the// Queue.Contains() Methodusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Queue of strings Queue myQueue = new Queue(); // Inserting the elements into the Queue myQueue.Enqueue("Geeks"); myQueue.Enqueue("Geeks Classes"); myQueue.Enqueue("Noida"); myQueue.Enqueue("Data Structures"); myQueue.Enqueue("GeeksforGeeks"); // Checking whether the element is // present in the Queue or not // The function returns True if the // element is present in the Queue, else // returns False Console.WriteLine(myQueue.Contains("GeeksforGeeks")); }}
True
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.queue.contains?view=netframework-4.7.2
arorakashish0911
CSharp-Collections-Namespace
CSharp-Collections-Queue
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Feb, 2021"
},
{
"code": null,
"e": 256,
"s": 28,
"text": "This method is used to check whether an element is in the Queue. This method performs a linear search, therefore, this method is an O(n) operation, where n is Count. And this method comes under the System.Collections namespace."
},
{
"code": null,
"e": 266,
"s": 256,
"text": "Syntax: "
},
{
"code": null,
"e": 308,
"s": 266,
"text": "public virtual bool Contains(object obj);"
},
{
"code": null,
"e": 379,
"s": 308,
"text": "Here, obj is the Object to locate in the Queue. The value can be null."
},
{
"code": null,
"e": 515,
"s": 379,
"text": "Return Value: The function returns True if the element exists in the Queue and returns False if the element doesn’t exist in the Queue."
},
{
"code": null,
"e": 595,
"s": 515,
"text": "Below given are some examples to understand the implementation in a better way:"
},
{
"code": null,
"e": 607,
"s": 595,
"text": "Example 1: "
},
{
"code": null,
"e": 610,
"s": 607,
"text": "C#"
},
{
"code": "// C# code to illustrate the// Queue.Contains() Methodusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Queue Queue myQueue = new Queue<int>(); // Inserting the elements into the Queue myQueue.Enqueue(5); myQueue.Enqueue(10); myQueue.Enqueue(15); myQueue.Enqueue(20); myQueue.Enqueue(25); // Checking whether the element is // present in the Queue or not // The function returns True if the // element is present in the Queue, else // returns False Console.WriteLine(myQueue.Contains(7)); }}",
"e": 1274,
"s": 610,
"text": null
},
{
"code": null,
"e": 1280,
"s": 1274,
"text": "False"
},
{
"code": null,
"e": 1293,
"s": 1282,
"text": "Example 2:"
},
{
"code": null,
"e": 1296,
"s": 1293,
"text": "C#"
},
{
"code": "// C# code to illustrate the// Queue.Contains() Methodusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Queue of strings Queue myQueue = new Queue(); // Inserting the elements into the Queue myQueue.Enqueue(\"Geeks\"); myQueue.Enqueue(\"Geeks Classes\"); myQueue.Enqueue(\"Noida\"); myQueue.Enqueue(\"Data Structures\"); myQueue.Enqueue(\"GeeksforGeeks\"); // Checking whether the element is // present in the Queue or not // The function returns True if the // element is present in the Queue, else // returns False Console.WriteLine(myQueue.Contains(\"GeeksforGeeks\")); }}",
"e": 2032,
"s": 1296,
"text": null
},
{
"code": null,
"e": 2037,
"s": 2032,
"text": "True"
},
{
"code": null,
"e": 2051,
"s": 2039,
"text": "Reference: "
},
{
"code": null,
"e": 2153,
"s": 2051,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.queue.contains?view=netframework-4.7.2"
},
{
"code": null,
"e": 2172,
"s": 2155,
"text": "arorakashish0911"
},
{
"code": null,
"e": 2201,
"s": 2172,
"text": "CSharp-Collections-Namespace"
},
{
"code": null,
"e": 2226,
"s": 2201,
"text": "CSharp-Collections-Queue"
},
{
"code": null,
"e": 2240,
"s": 2226,
"text": "CSharp-method"
},
{
"code": null,
"e": 2243,
"s": 2240,
"text": "C#"
}
] |
How to Install KaliTorify Tool in Kali Linux? | 06 Oct, 2021
Kalitorify is a free and open-source tool to become anonymous on the Internet while testing the security of a web browser. kalitorify uses ip-tables to create a Transparent Proxy through the Tor Network. kalitorify can move the network of your Kali Linux operating system through the Tor Network using ip-tables. When you run the tool it starts the transparent proxy. After initiating kalitorify you can do all your security testing on the website and become anonymous. This tool can create challenges for the people if they want to trace your IP address.
Kalitorify is an open-source tool.
kalitorify uses ip-tables
kalitorify uses tor proxy
kalitorify uses tor tunnel
Through kalitorify network can redirect through ip tables.
kalitorify is easy to use.
When we want that we would go anonymous through kali Linux There are lots of anatomization tools available on the web such as proxychains, Anonsurf, .all these tools use Tor relay and tor tunnels the reason that we are talking about KaliTorify is, it is another great tool that has different ways of going about it. A transparent proxy is a type of proxy which acts as a bridge between user and internet on this bridge network goes through tor tunnels and the proxy is being changed. Kalitorify intercepts the request from your machine to the internet when a user wants to access any website or any web server then Kalitorify tool intercepts the request of the user and takes the network through tor tunnel and redirects the original IP to different IP using ip-tables. Transparent proxy via Tor means that every network application will make its TCP connections through Tor; no application will be able to reveal your IP address by connecting directly.
Step 1: Open your kali Linux. Open your terminal and move to Desktop directory using the following command.
cd Desktop
Step 2: Create a new directory here name it kalitorify and move in this directory using the following command.
mkdir kalitorify
cd kalitorify
Step 3: Now you are in kalitorify directory here you have to download kalitorify tool from GitHub using the following command.
git clone https://github.com/brainfucksec/kalitorify
Step 4: Kalitorify has been downloaded into your kali Linux now you have to install dependencies.
sudo apt-get update && sudo apt-get dist-upgrade -y
Step 5: Install one more dependency.
sudo apt-get install -y tor curl
Step 6: Now you have to install kalitorify using the following command.
cd kalitorify/
sudo make install
Step 7: Reboot.
Services and programs that use kalitorify (such as iptables) work at the kernel level, at the end of the installation reboot the operating system to avoid conflicts.
Step 8: Now again go to the same directory where you have installed kalitorify .and type the following command. Here h is used for help:
kalitorify -h
Step 9: Now to run kalitorify tool use the following command.
sudo kalitorify -t
Your kalitorify has been installed and running successfully
Cyber-security
how-to-install
Kali-Linux
Linux-Tools
How To
Installation Guide
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Set Git Username and Password in GitBash?
How to Install Jupyter Notebook on MacOS?
How to Install and Use NVM on Windows?
How to Install Python Packages for AWS Lambda Layers?
How to Install Git in VS Code?
Installation of Node.js on Linux
Installation of Node.js on Windows
How to Install Jupyter Notebook on MacOS?
How to Install and Use NVM on Windows?
How to Install Pygame on Windows ? | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n06 Oct, 2021"
},
{
"code": null,
"e": 610,
"s": 53,
"text": "Kalitorify is a free and open-source tool to become anonymous on the Internet while testing the security of a web browser. kalitorify uses ip-tables to create a Transparent Proxy through the Tor Network. kalitorify can move the network of your Kali Linux operating system through the Tor Network using ip-tables. When you run the tool it starts the transparent proxy. After initiating kalitorify you can do all your security testing on the website and become anonymous. This tool can create challenges for the people if they want to trace your IP address. "
},
{
"code": null,
"e": 645,
"s": 610,
"text": "Kalitorify is an open-source tool."
},
{
"code": null,
"e": 671,
"s": 645,
"text": "kalitorify uses ip-tables"
},
{
"code": null,
"e": 697,
"s": 671,
"text": "kalitorify uses tor proxy"
},
{
"code": null,
"e": 724,
"s": 697,
"text": "kalitorify uses tor tunnel"
},
{
"code": null,
"e": 783,
"s": 724,
"text": "Through kalitorify network can redirect through ip tables."
},
{
"code": null,
"e": 810,
"s": 783,
"text": "kalitorify is easy to use."
},
{
"code": null,
"e": 1764,
"s": 810,
"text": "When we want that we would go anonymous through kali Linux There are lots of anatomization tools available on the web such as proxychains, Anonsurf, .all these tools use Tor relay and tor tunnels the reason that we are talking about KaliTorify is, it is another great tool that has different ways of going about it. A transparent proxy is a type of proxy which acts as a bridge between user and internet on this bridge network goes through tor tunnels and the proxy is being changed. Kalitorify intercepts the request from your machine to the internet when a user wants to access any website or any web server then Kalitorify tool intercepts the request of the user and takes the network through tor tunnel and redirects the original IP to different IP using ip-tables. Transparent proxy via Tor means that every network application will make its TCP connections through Tor; no application will be able to reveal your IP address by connecting directly."
},
{
"code": null,
"e": 1872,
"s": 1764,
"text": "Step 1: Open your kali Linux. Open your terminal and move to Desktop directory using the following command."
},
{
"code": null,
"e": 1883,
"s": 1872,
"text": "cd Desktop"
},
{
"code": null,
"e": 1994,
"s": 1883,
"text": "Step 2: Create a new directory here name it kalitorify and move in this directory using the following command."
},
{
"code": null,
"e": 2025,
"s": 1994,
"text": "mkdir kalitorify\ncd kalitorify"
},
{
"code": null,
"e": 2152,
"s": 2025,
"text": "Step 3: Now you are in kalitorify directory here you have to download kalitorify tool from GitHub using the following command."
},
{
"code": null,
"e": 2205,
"s": 2152,
"text": "git clone https://github.com/brainfucksec/kalitorify"
},
{
"code": null,
"e": 2303,
"s": 2205,
"text": "Step 4: Kalitorify has been downloaded into your kali Linux now you have to install dependencies."
},
{
"code": null,
"e": 2355,
"s": 2303,
"text": "sudo apt-get update && sudo apt-get dist-upgrade -y"
},
{
"code": null,
"e": 2392,
"s": 2355,
"text": "Step 5: Install one more dependency."
},
{
"code": null,
"e": 2425,
"s": 2392,
"text": "sudo apt-get install -y tor curl"
},
{
"code": null,
"e": 2497,
"s": 2425,
"text": "Step 6: Now you have to install kalitorify using the following command."
},
{
"code": null,
"e": 2530,
"s": 2497,
"text": "cd kalitorify/\nsudo make install"
},
{
"code": null,
"e": 2546,
"s": 2530,
"text": "Step 7: Reboot."
},
{
"code": null,
"e": 2712,
"s": 2546,
"text": "Services and programs that use kalitorify (such as iptables) work at the kernel level, at the end of the installation reboot the operating system to avoid conflicts."
},
{
"code": null,
"e": 2849,
"s": 2712,
"text": "Step 8: Now again go to the same directory where you have installed kalitorify .and type the following command. Here h is used for help:"
},
{
"code": null,
"e": 2871,
"s": 2849,
"text": "kalitorify -h "
},
{
"code": null,
"e": 2933,
"s": 2871,
"text": "Step 9: Now to run kalitorify tool use the following command."
},
{
"code": null,
"e": 2952,
"s": 2933,
"text": "sudo kalitorify -t"
},
{
"code": null,
"e": 3013,
"s": 2952,
"text": "Your kalitorify has been installed and running successfully "
},
{
"code": null,
"e": 3028,
"s": 3013,
"text": "Cyber-security"
},
{
"code": null,
"e": 3043,
"s": 3028,
"text": "how-to-install"
},
{
"code": null,
"e": 3054,
"s": 3043,
"text": "Kali-Linux"
},
{
"code": null,
"e": 3066,
"s": 3054,
"text": "Linux-Tools"
},
{
"code": null,
"e": 3073,
"s": 3066,
"text": "How To"
},
{
"code": null,
"e": 3092,
"s": 3073,
"text": "Installation Guide"
},
{
"code": null,
"e": 3103,
"s": 3092,
"text": "Linux-Unix"
},
{
"code": null,
"e": 3201,
"s": 3103,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3250,
"s": 3201,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 3292,
"s": 3250,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 3331,
"s": 3292,
"text": "How to Install and Use NVM on Windows?"
},
{
"code": null,
"e": 3385,
"s": 3331,
"text": "How to Install Python Packages for AWS Lambda Layers?"
},
{
"code": null,
"e": 3416,
"s": 3385,
"text": "How to Install Git in VS Code?"
},
{
"code": null,
"e": 3449,
"s": 3416,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3484,
"s": 3449,
"text": "Installation of Node.js on Windows"
},
{
"code": null,
"e": 3526,
"s": 3484,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 3565,
"s": 3526,
"text": "How to Install and Use NVM on Windows?"
}
] |
Data Structures | Stack | Question 5 | 09 Feb, 2013
Following is an incorrect pseudocode for the algorithm which is supposed to determine whether a sequence of parentheses is balanced:
declare a character stack while ( more input is available){ read a character if ( the character is a '(' ) push it on the stack else if ( the character is a ')' and the stack is not empty ) pop a character off the stack else print "unbalanced" and exit } print "balanced"
Which of these unbalanced sequences does the above code think is balanced?
Source: http://www.cs.colorado.edu/~main/questions/chap07q.html(A) ((())(B) ())(()(C) (()()))(D) (()))()Answer: (A)Explanation: At the end of while loop, we must check whether the stack is empty or not. For input ((()), the stack doesn’t remain empty after the loop. See https://www.geeksforgeeks.org/check-for-balanced-parentheses-in-an-expression/ for details.
Data Structures
Data Structures-Stack
Data Structures
Data Structures
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Advantages and Disadvantages of Linked List
Data Structures | Binary Search Trees | Question 8
Data Structures | Array | Question 2
Data Structures | Queue | Question 2
Amazon Interview Experience for SDE-II
Data Structures | Hash | Question 5
Data Structures | Linked List | Question 16
Difference between Singly linked list and Doubly linked list
Data Structures | Binary Trees | Question 1 | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Feb, 2013"
},
{
"code": null,
"e": 161,
"s": 28,
"text": "Following is an incorrect pseudocode for the algorithm which is supposed to determine whether a sequence of parentheses is balanced:"
},
{
"code": "declare a character stack while ( more input is available){ read a character if ( the character is a '(' ) push it on the stack else if ( the character is a ')' and the stack is not empty ) pop a character off the stack else print \"unbalanced\" and exit } print \"balanced\"",
"e": 457,
"s": 161,
"text": null
},
{
"code": null,
"e": 532,
"s": 457,
"text": "Which of these unbalanced sequences does the above code think is balanced?"
},
{
"code": null,
"e": 895,
"s": 532,
"text": "Source: http://www.cs.colorado.edu/~main/questions/chap07q.html(A) ((())(B) ())(()(C) (()()))(D) (()))()Answer: (A)Explanation: At the end of while loop, we must check whether the stack is empty or not. For input ((()), the stack doesn’t remain empty after the loop. See https://www.geeksforgeeks.org/check-for-balanced-parentheses-in-an-expression/ for details."
},
{
"code": null,
"e": 911,
"s": 895,
"text": "Data Structures"
},
{
"code": null,
"e": 933,
"s": 911,
"text": "Data Structures-Stack"
},
{
"code": null,
"e": 949,
"s": 933,
"text": "Data Structures"
},
{
"code": null,
"e": 965,
"s": 949,
"text": "Data Structures"
},
{
"code": null,
"e": 1063,
"s": 965,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1095,
"s": 1063,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 1139,
"s": 1095,
"text": "Advantages and Disadvantages of Linked List"
},
{
"code": null,
"e": 1190,
"s": 1139,
"text": "Data Structures | Binary Search Trees | Question 8"
},
{
"code": null,
"e": 1227,
"s": 1190,
"text": "Data Structures | Array | Question 2"
},
{
"code": null,
"e": 1264,
"s": 1227,
"text": "Data Structures | Queue | Question 2"
},
{
"code": null,
"e": 1303,
"s": 1264,
"text": "Amazon Interview Experience for SDE-II"
},
{
"code": null,
"e": 1339,
"s": 1303,
"text": "Data Structures | Hash | Question 5"
},
{
"code": null,
"e": 1383,
"s": 1339,
"text": "Data Structures | Linked List | Question 16"
},
{
"code": null,
"e": 1444,
"s": 1383,
"text": "Difference between Singly linked list and Doubly linked list"
}
] |
Real time optimized KMP Algorithm for Pattern Searching | 15 Nov, 2021
In the article, we have already discussed the KMP algorithm for pattern searching. In this article, a real-time optimized KMP algorithm is discussed.
From the previous article, it is known that KMP(a.k.a. Knuth-Morris-Pratt) algorithm preprocesses the pattern P and constructs a failure function F(also called as lps[]) to store the length of the longest suffix of the sub-pattern P[1..l], which is also a prefix of P, for l = 0 to m-1. Note that the sub-pattern starts at index 1 because a suffix can be the string itself. After a mismatched occurred at index P[j], we update j to F[j-1].
The original KMP Algorithm has the runtime complexity of O(M + N) and auxiliary space O(M), where N is the size of the input text and M is the size of the pattern. Preprocessing step costs O(M) time. It is hard to achieve runtime complexity better than that but we are still able to eliminate some inefficient shifts.
Inefficiencies of the original KMP algorithm: Consider the following case by using the original KMP algorithm:
Input: T = “cabababcababaca”, P = “ababaca”Output: Found at index 8
The longest proper prefix or lps[] for the above test case is {0, 0, 1, 2, 3, 0, 1}. Lets assume that the red color represents a mismatch occurs, green color represents the checking we skipped. Therefore, the searching process according to the original KMP algorithm occurs as follows:
One thing which can be noticed is that in the third, fourth, and fifth matching, the mismatch occurs at the same location, T[7]. If we can skip the fourth and fifth matching, then the original KMP algorithm can further be optimised to answer the real-time queries.
Real-time Optimization: The term real-time in this case can be interpreted as checking each character in the text T at most once. Our goal in this case is to shift the pattern properly (just like KMP algorithm does), but no need to check the mismatched character again. That is, for the same above example, the optimized KMP algorithm should work in the following way:
Approach: One way to achieve the goal is to modify the preprocessing process.
Let K be the size of the letters of the pattern P. We will construct a failure table to contain K failure functions(i.e. lps[]).
Each failure function in the failure table is mapped to a character(key in the failure table) in the alphabet of the pattern P.
Recall that the original failure function F[l] (or lps[]) stores the length of the longest suffix of P[1..l], which is also a prefix of P, for l = 0 to m-1, where m is the size of the pattern.
If a mismatched occurs at T[i] and P[j], the new value of j would be updated to F[j-1] and the counter ‘i’ would be unchanged.
In our new failure table FT[][], if a failure function F’ is mapped with a character c, F'[l] should store the length of the longest suffix of P[1..l] + c (‘+’ represents appending), which is also a prefix of P, for l = 0 to m-1.
The intuition is to make proper shifts but also depending on the mismatched character. Here the character c, which is also a key in the failure table, is our “guess” about the mismatched character in the text T.
That is, if the mismatched character is c, how should we shift the pattern properly? Since we are constructing the failure table in the preprocessing step, we have to make enough guesses about the mismatched character.
Hence, the number of lps[]’s in the failure table equals to the size of the alphabet of the pattern, and each value, the failure function, should be different with respect to the key, a character in P.
Assume we have already constructed the desired failure table. Let FT[][] be the failure table, T be the text, P be the pattern.
Then, in the matching process, if a mismatch occurs at T[i] and P[j] (i.e. T[i] != P[j]):If T[i] is a character in P, j will be updated to FT[T[i]][j-1], ‘i‘ will be updated to ‘i + 1‘. We are doing this since we are guaranteed that T[i] is matched or skipped.If T[i] is not a character, ‘j’ will be updated to 0, ‘i’ will be updated to ‘i + 1’.
If T[i] is a character in P, j will be updated to FT[T[i]][j-1], ‘i‘ will be updated to ‘i + 1‘. We are doing this since we are guaranteed that T[i] is matched or skipped.If T[i] is not a character, ‘j’ will be updated to 0, ‘i’ will be updated to ‘i + 1’.
If T[i] is a character in P, j will be updated to FT[T[i]][j-1], ‘i‘ will be updated to ‘i + 1‘. We are doing this since we are guaranteed that T[i] is matched or skipped.
If T[i] is not a character, ‘j’ will be updated to 0, ‘i’ will be updated to ‘i + 1’.
Note that if a mismatching does not occur, the behaviour is exactly the same as the original KMP algorithm.
Constructing Failure Table:
To construct the failure table FT[][], we will need the failure function F(or lps[]) from the original KMP algorithm.
Since F[l] tells us the length of the longest suffix of the sub-pattern P[1..l], which is also a prefix of P, the values stored in the failure table is one step beyond it.
That is, for any key t in the failure table FT[][], the values stored in FT[t] is a failure function that satisfies for the character ‘t’ and FT[t][l] stores the length of the longest suffix of a sub-pattern P[1..l] + t(‘+’ means append), which is also a prefix of P, for l from 0 to m-1.
F[l] has already guaranteed that P[0..F[l]-1] is the longest suffix of the sub-pattern P[1..l], so we will need to check if P[F[l]] is t.
If true, then we can assign FT[t][l] to be F[l] + 1, as we are guaranteed that P[0..F[l]] is the longest suffix of the sub-pattern P[1..l] + t.
If false, that indicates P[F[l]] is not t. That is, we fail the matching at character P[F[l]] with the character t, but P[0..F[l]-1] matches a suffix of P[1..l].
By borrowing the idea from KMP algorithm, just like how we compute the failure function in original KMP algorithm, if the mismatch occurs at P[F[l]] with mismatched character t, we would like to update the next matching starting at FT[t][F[l]-1].
That is, we use the idea of the KMP algorithm to compute the failure table. Notice that F[l] – 1 is always less than l, so when we are computing FT[t][l], FT[t][F[l] – 1] is ready for us already.
One special case is that if F[l] is 0 and P[F[l]] is not t, F[l] – 1 has a value of -1, in this case, we will update FT[t][l] to 0. (i.e. there is no suffix of P[1..l] + t exists such that it is a prefix of P.)
As a conclusion of failure table construction, when we are computing FT[t][l], for any key t and l from 0 to m-1, we will check:If P[F[l]] is t,
if yes:
FT[t][l] <- F[l] + 1;
if no:
check if F[l] is 0,
if yes:
FT[t][l] <- 0;
if no:
FT[t][l] <- FT[t][F[t] - 1];
If P[F[l]] is t,
if yes:
FT[t][l] <- F[l] + 1;
if no:
check if F[l] is 0,
if yes:
FT[t][l] <- 0;
if no:
FT[t][l] <- FT[t][F[t] - 1];
Here are the desired outputs of the above example, outputs include the failure table for better illustration.
Examples:
Input: T = “cabababcababaca”, P = “ababaca”Output: Failure Table:Key Value‘a’ [1 1 1 3 1 1 1]‘b’ [0 0 2 0 4 0 2]‘c’ [0 0 0 0 0 0 0]Found pattern at index 8
Below is the implementation of the above approach:
C++
// C++ program to implement a// real time optimized KMP// algorithm for pattern searching #include <iostream>#include <set>#include <string>#include <unordered_map> using std::string;using std::unordered_map;using std::set;using std::cout; // Function to print// an array of length lenvoid printArr(int* F, int len, char name){ cout << '(' << name << ')' << "contain: ["; // Loop to iterate through // and print the array for (int i = 0; i < len; i++) { cout << F[i] << " "; } cout << "]\n";} // Function to print a table.// len is the length of each array// in the map.void printTable( unordered_map<char, int*>& FT, int len){ cout << "Failure Table: {\n"; // Iterating through the table // and printing it for (auto& pair : FT) { printArr(pair.second, len, pair.first); } cout << "}\n";} // Function to construct// the failure function// corresponding to the patternvoid constructFailureFunction( string& P, int* F){ // P is the pattern, // F is the FailureFunction // assume F has length m, // where m is the size of P int len = P.size(); // F[0] must have the value 0 F[0] = 0; // The index, we are parsing P[1..j] int j = 1; int l = 0; // Loop to iterate through the // pattern while (j < len) { // Computing the failure function or // lps[] similar to KMP Algorithm if (P[j] == P[l]) { l++; F[j] = l; j++; } else if (l > 0) { l = F[l - 1]; } else { F[j] = 0; j++; } }} // Function to construct the failure table.// P is the pattern, F is the original// failure function. The table is stored in// FT[][]void constructFailureTable( string& P, set<char>& pattern_alphabet, int* F, unordered_map<char, int*>& FT){ int len = P.size(); // T is the char where we mismatched for (char t : pattern_alphabet) { // Allocate an array FT[t] = new int[len]; int l = 0; while (l < len) { if (P[F[l]] == t) // Old failure function gives // a good shifting FT[t][l] = F[l] + 1; else { // Move to the next char if // the entry in the failure // function is 0 if (F[l] == 0) FT[t][l] = 0; // Fill the table if F[l] > 0 else FT[t][l] = FT[t][F[l] - 1]; } l++; } }} // Function to implement the realtime// optimized KMP algorithm for// pattern searching. T is the text// we are searching on and// P is the pattern we are searching forvoid KMP(string& T, string& P, set<char>& pattern_alphabet){ // Size of the pattern int m = P.size(); // Size of the text int n = T.size(); // Initialize the Failure Function int F[m]; // Constructing the failure function // using KMP algorithm constructFailureFunction(P, F); printArr(F, m, 'F'); unordered_map<char, int*> FT; // Construct the failure table and // store it in FT[][] constructFailureTable( P, pattern_alphabet, F, FT); printTable(FT, m); // The starting index will be when // the first match occurs int found_index = -1; // Variable to iterate over the // indices in Text T int i = 0; // Variable to iterate over the // indices in Pattern P int j = 0; // Loop to iterate over the text while (i < n) { if (P[j] == T[i]) { // Matched the last character in P if (j == m - 1) { found_index = i - m + 1; break; } else { i++; j++; } } else { if (j > 0) { // T[i] is not in P's alphabet if (FT.find(T[i]) == FT.end()) // Begin a new // matching process j = 0; else j = FT[T[i]][j - 1]; // Update 'j' to be the length of // the longest suffix of P[1..j] // which is also a prefix of P i++; } else i++; } } // Printing the index at which // the pattern is found if (found_index != -1) cout << "Found at index " << found_index << '\n'; else cout << "Not Found \n"; for (char t : pattern_alphabet) // Deallocate the arrays in FT delete[] FT[t]; return;} // Driver codeint main(){ string T = "cabababcababaca"; string P = "ababaca"; set<char> pattern_alphabet = { 'a', 'b', 'c' }; KMP(T, P, pattern_alphabet);}
(F)contain: [0 0 1 2 3 0 1 ]
Failure Table: {
(c)contain: [0 0 0 0 0 0 0 ]
(a)contain: [1 1 1 3 1 1 1 ]
(b)contain: [0 0 2 0 4 0 2 ]
}
Found at index 8
Note: The above source code will find the first occurrence of the pattern. With slight modification, it can be used to find all the occurrences.
Time Complexity:
The new preprocessing step has a running time complexity of O(, where is the alphabet set of pattern P, M is the size of P.
The whole modified KMP algorithm has a running time complexity of O(). The auxiliary space usage of O().
The running time and space usage look like “worse” than the original KMP algorithm. However, if we are searching for the same pattern in multiple texts or the alphabet set of the pattern is small, as the preprocessing step only needs to be done once and each character in the text will be compared at most once (real-time). So, it is more efficient than the original KMP algorithm and good in practice.
Algorithms
Data Structures
Pattern Searching
Searching
Strings
Data Structures
Searching
Strings
Pattern Searching
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is Hashing | A Complete Tutorial
Find if there is a path between two vertices in an undirected graph
How to Start Learning DSA?
Complete Roadmap To Learn DSA From Scratch
Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
Introduction to Data Structures
What is Hashing | A Complete Tutorial
Doubly Linked List | Set 1 (Introduction and Insertion)
Introduction to Tree Data Structure
Find if there is a path between two vertices in an undirected graph | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n15 Nov, 2021"
},
{
"code": null,
"e": 202,
"s": 52,
"text": "In the article, we have already discussed the KMP algorithm for pattern searching. In this article, a real-time optimized KMP algorithm is discussed."
},
{
"code": null,
"e": 642,
"s": 202,
"text": "From the previous article, it is known that KMP(a.k.a. Knuth-Morris-Pratt) algorithm preprocesses the pattern P and constructs a failure function F(also called as lps[]) to store the length of the longest suffix of the sub-pattern P[1..l], which is also a prefix of P, for l = 0 to m-1. Note that the sub-pattern starts at index 1 because a suffix can be the string itself. After a mismatched occurred at index P[j], we update j to F[j-1]."
},
{
"code": null,
"e": 960,
"s": 642,
"text": "The original KMP Algorithm has the runtime complexity of O(M + N) and auxiliary space O(M), where N is the size of the input text and M is the size of the pattern. Preprocessing step costs O(M) time. It is hard to achieve runtime complexity better than that but we are still able to eliminate some inefficient shifts."
},
{
"code": null,
"e": 1071,
"s": 960,
"text": "Inefficiencies of the original KMP algorithm: Consider the following case by using the original KMP algorithm:"
},
{
"code": null,
"e": 1139,
"s": 1071,
"text": "Input: T = “cabababcababaca”, P = “ababaca”Output: Found at index 8"
},
{
"code": null,
"e": 1425,
"s": 1139,
"text": "The longest proper prefix or lps[] for the above test case is {0, 0, 1, 2, 3, 0, 1}. Lets assume that the red color represents a mismatch occurs, green color represents the checking we skipped. Therefore, the searching process according to the original KMP algorithm occurs as follows:"
},
{
"code": null,
"e": 1690,
"s": 1425,
"text": "One thing which can be noticed is that in the third, fourth, and fifth matching, the mismatch occurs at the same location, T[7]. If we can skip the fourth and fifth matching, then the original KMP algorithm can further be optimised to answer the real-time queries."
},
{
"code": null,
"e": 2059,
"s": 1690,
"text": "Real-time Optimization: The term real-time in this case can be interpreted as checking each character in the text T at most once. Our goal in this case is to shift the pattern properly (just like KMP algorithm does), but no need to check the mismatched character again. That is, for the same above example, the optimized KMP algorithm should work in the following way:"
},
{
"code": null,
"e": 2137,
"s": 2059,
"text": "Approach: One way to achieve the goal is to modify the preprocessing process."
},
{
"code": null,
"e": 2266,
"s": 2137,
"text": "Let K be the size of the letters of the pattern P. We will construct a failure table to contain K failure functions(i.e. lps[])."
},
{
"code": null,
"e": 2394,
"s": 2266,
"text": "Each failure function in the failure table is mapped to a character(key in the failure table) in the alphabet of the pattern P."
},
{
"code": null,
"e": 2587,
"s": 2394,
"text": "Recall that the original failure function F[l] (or lps[]) stores the length of the longest suffix of P[1..l], which is also a prefix of P, for l = 0 to m-1, where m is the size of the pattern."
},
{
"code": null,
"e": 2714,
"s": 2587,
"text": "If a mismatched occurs at T[i] and P[j], the new value of j would be updated to F[j-1] and the counter ‘i’ would be unchanged."
},
{
"code": null,
"e": 2944,
"s": 2714,
"text": "In our new failure table FT[][], if a failure function F’ is mapped with a character c, F'[l] should store the length of the longest suffix of P[1..l] + c (‘+’ represents appending), which is also a prefix of P, for l = 0 to m-1."
},
{
"code": null,
"e": 3156,
"s": 2944,
"text": "The intuition is to make proper shifts but also depending on the mismatched character. Here the character c, which is also a key in the failure table, is our “guess” about the mismatched character in the text T."
},
{
"code": null,
"e": 3375,
"s": 3156,
"text": "That is, if the mismatched character is c, how should we shift the pattern properly? Since we are constructing the failure table in the preprocessing step, we have to make enough guesses about the mismatched character."
},
{
"code": null,
"e": 3577,
"s": 3375,
"text": "Hence, the number of lps[]’s in the failure table equals to the size of the alphabet of the pattern, and each value, the failure function, should be different with respect to the key, a character in P."
},
{
"code": null,
"e": 3705,
"s": 3577,
"text": "Assume we have already constructed the desired failure table. Let FT[][] be the failure table, T be the text, P be the pattern."
},
{
"code": null,
"e": 4051,
"s": 3705,
"text": "Then, in the matching process, if a mismatch occurs at T[i] and P[j] (i.e. T[i] != P[j]):If T[i] is a character in P, j will be updated to FT[T[i]][j-1], ‘i‘ will be updated to ‘i + 1‘. We are doing this since we are guaranteed that T[i] is matched or skipped.If T[i] is not a character, ‘j’ will be updated to 0, ‘i’ will be updated to ‘i + 1’."
},
{
"code": null,
"e": 4308,
"s": 4051,
"text": "If T[i] is a character in P, j will be updated to FT[T[i]][j-1], ‘i‘ will be updated to ‘i + 1‘. We are doing this since we are guaranteed that T[i] is matched or skipped.If T[i] is not a character, ‘j’ will be updated to 0, ‘i’ will be updated to ‘i + 1’."
},
{
"code": null,
"e": 4480,
"s": 4308,
"text": "If T[i] is a character in P, j will be updated to FT[T[i]][j-1], ‘i‘ will be updated to ‘i + 1‘. We are doing this since we are guaranteed that T[i] is matched or skipped."
},
{
"code": null,
"e": 4566,
"s": 4480,
"text": "If T[i] is not a character, ‘j’ will be updated to 0, ‘i’ will be updated to ‘i + 1’."
},
{
"code": null,
"e": 4674,
"s": 4566,
"text": "Note that if a mismatching does not occur, the behaviour is exactly the same as the original KMP algorithm."
},
{
"code": null,
"e": 4702,
"s": 4674,
"text": "Constructing Failure Table:"
},
{
"code": null,
"e": 4820,
"s": 4702,
"text": "To construct the failure table FT[][], we will need the failure function F(or lps[]) from the original KMP algorithm."
},
{
"code": null,
"e": 4992,
"s": 4820,
"text": "Since F[l] tells us the length of the longest suffix of the sub-pattern P[1..l], which is also a prefix of P, the values stored in the failure table is one step beyond it."
},
{
"code": null,
"e": 5281,
"s": 4992,
"text": "That is, for any key t in the failure table FT[][], the values stored in FT[t] is a failure function that satisfies for the character ‘t’ and FT[t][l] stores the length of the longest suffix of a sub-pattern P[1..l] + t(‘+’ means append), which is also a prefix of P, for l from 0 to m-1."
},
{
"code": null,
"e": 5419,
"s": 5281,
"text": "F[l] has already guaranteed that P[0..F[l]-1] is the longest suffix of the sub-pattern P[1..l], so we will need to check if P[F[l]] is t."
},
{
"code": null,
"e": 5563,
"s": 5419,
"text": "If true, then we can assign FT[t][l] to be F[l] + 1, as we are guaranteed that P[0..F[l]] is the longest suffix of the sub-pattern P[1..l] + t."
},
{
"code": null,
"e": 5725,
"s": 5563,
"text": "If false, that indicates P[F[l]] is not t. That is, we fail the matching at character P[F[l]] with the character t, but P[0..F[l]-1] matches a suffix of P[1..l]."
},
{
"code": null,
"e": 5972,
"s": 5725,
"text": "By borrowing the idea from KMP algorithm, just like how we compute the failure function in original KMP algorithm, if the mismatch occurs at P[F[l]] with mismatched character t, we would like to update the next matching starting at FT[t][F[l]-1]."
},
{
"code": null,
"e": 6168,
"s": 5972,
"text": "That is, we use the idea of the KMP algorithm to compute the failure table. Notice that F[l] – 1 is always less than l, so when we are computing FT[t][l], FT[t][F[l] – 1] is ready for us already."
},
{
"code": null,
"e": 6379,
"s": 6168,
"text": "One special case is that if F[l] is 0 and P[F[l]] is not t, F[l] – 1 has a value of -1, in this case, we will update FT[t][l] to 0. (i.e. there is no suffix of P[1..l] + t exists such that it is a prefix of P.)"
},
{
"code": null,
"e": 6682,
"s": 6379,
"text": "As a conclusion of failure table construction, when we are computing FT[t][l], for any key t and l from 0 to m-1, we will check:If P[F[l]] is t,\n if yes:\n FT[t][l] <- F[l] + 1;\n if no: \n check if F[l] is 0,\n if yes:\n FT[t][l] <- 0;\n if no:\n FT[t][l] <- FT[t][F[t] - 1];\n"
},
{
"code": null,
"e": 6857,
"s": 6682,
"text": "If P[F[l]] is t,\n if yes:\n FT[t][l] <- F[l] + 1;\n if no: \n check if F[l] is 0,\n if yes:\n FT[t][l] <- 0;\n if no:\n FT[t][l] <- FT[t][F[t] - 1];\n"
},
{
"code": null,
"e": 6967,
"s": 6857,
"text": "Here are the desired outputs of the above example, outputs include the failure table for better illustration."
},
{
"code": null,
"e": 6977,
"s": 6967,
"text": "Examples:"
},
{
"code": null,
"e": 7133,
"s": 6977,
"text": "Input: T = “cabababcababaca”, P = “ababaca”Output: Failure Table:Key Value‘a’ [1 1 1 3 1 1 1]‘b’ [0 0 2 0 4 0 2]‘c’ [0 0 0 0 0 0 0]Found pattern at index 8"
},
{
"code": null,
"e": 7184,
"s": 7133,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 7188,
"s": 7184,
"text": "C++"
},
{
"code": "// C++ program to implement a// real time optimized KMP// algorithm for pattern searching #include <iostream>#include <set>#include <string>#include <unordered_map> using std::string;using std::unordered_map;using std::set;using std::cout; // Function to print// an array of length lenvoid printArr(int* F, int len, char name){ cout << '(' << name << ')' << \"contain: [\"; // Loop to iterate through // and print the array for (int i = 0; i < len; i++) { cout << F[i] << \" \"; } cout << \"]\\n\";} // Function to print a table.// len is the length of each array// in the map.void printTable( unordered_map<char, int*>& FT, int len){ cout << \"Failure Table: {\\n\"; // Iterating through the table // and printing it for (auto& pair : FT) { printArr(pair.second, len, pair.first); } cout << \"}\\n\";} // Function to construct// the failure function// corresponding to the patternvoid constructFailureFunction( string& P, int* F){ // P is the pattern, // F is the FailureFunction // assume F has length m, // where m is the size of P int len = P.size(); // F[0] must have the value 0 F[0] = 0; // The index, we are parsing P[1..j] int j = 1; int l = 0; // Loop to iterate through the // pattern while (j < len) { // Computing the failure function or // lps[] similar to KMP Algorithm if (P[j] == P[l]) { l++; F[j] = l; j++; } else if (l > 0) { l = F[l - 1]; } else { F[j] = 0; j++; } }} // Function to construct the failure table.// P is the pattern, F is the original// failure function. The table is stored in// FT[][]void constructFailureTable( string& P, set<char>& pattern_alphabet, int* F, unordered_map<char, int*>& FT){ int len = P.size(); // T is the char where we mismatched for (char t : pattern_alphabet) { // Allocate an array FT[t] = new int[len]; int l = 0; while (l < len) { if (P[F[l]] == t) // Old failure function gives // a good shifting FT[t][l] = F[l] + 1; else { // Move to the next char if // the entry in the failure // function is 0 if (F[l] == 0) FT[t][l] = 0; // Fill the table if F[l] > 0 else FT[t][l] = FT[t][F[l] - 1]; } l++; } }} // Function to implement the realtime// optimized KMP algorithm for// pattern searching. T is the text// we are searching on and// P is the pattern we are searching forvoid KMP(string& T, string& P, set<char>& pattern_alphabet){ // Size of the pattern int m = P.size(); // Size of the text int n = T.size(); // Initialize the Failure Function int F[m]; // Constructing the failure function // using KMP algorithm constructFailureFunction(P, F); printArr(F, m, 'F'); unordered_map<char, int*> FT; // Construct the failure table and // store it in FT[][] constructFailureTable( P, pattern_alphabet, F, FT); printTable(FT, m); // The starting index will be when // the first match occurs int found_index = -1; // Variable to iterate over the // indices in Text T int i = 0; // Variable to iterate over the // indices in Pattern P int j = 0; // Loop to iterate over the text while (i < n) { if (P[j] == T[i]) { // Matched the last character in P if (j == m - 1) { found_index = i - m + 1; break; } else { i++; j++; } } else { if (j > 0) { // T[i] is not in P's alphabet if (FT.find(T[i]) == FT.end()) // Begin a new // matching process j = 0; else j = FT[T[i]][j - 1]; // Update 'j' to be the length of // the longest suffix of P[1..j] // which is also a prefix of P i++; } else i++; } } // Printing the index at which // the pattern is found if (found_index != -1) cout << \"Found at index \" << found_index << '\\n'; else cout << \"Not Found \\n\"; for (char t : pattern_alphabet) // Deallocate the arrays in FT delete[] FT[t]; return;} // Driver codeint main(){ string T = \"cabababcababaca\"; string P = \"ababaca\"; set<char> pattern_alphabet = { 'a', 'b', 'c' }; KMP(T, P, pattern_alphabet);}",
"e": 12096,
"s": 7188,
"text": null
},
{
"code": null,
"e": 12249,
"s": 12096,
"text": "(F)contain: [0 0 1 2 3 0 1 ]\nFailure Table: {\n(c)contain: [0 0 0 0 0 0 0 ]\n(a)contain: [1 1 1 3 1 1 1 ]\n(b)contain: [0 0 2 0 4 0 2 ]\n}\nFound at index 8\n"
},
{
"code": null,
"e": 12394,
"s": 12249,
"text": "Note: The above source code will find the first occurrence of the pattern. With slight modification, it can be used to find all the occurrences."
},
{
"code": null,
"e": 12411,
"s": 12394,
"text": "Time Complexity:"
},
{
"code": null,
"e": 12536,
"s": 12411,
"text": "The new preprocessing step has a running time complexity of O(, where is the alphabet set of pattern P, M is the size of P."
},
{
"code": null,
"e": 12641,
"s": 12536,
"text": "The whole modified KMP algorithm has a running time complexity of O(). The auxiliary space usage of O()."
},
{
"code": null,
"e": 13044,
"s": 12641,
"text": "The running time and space usage look like “worse” than the original KMP algorithm. However, if we are searching for the same pattern in multiple texts or the alphabet set of the pattern is small, as the preprocessing step only needs to be done once and each character in the text will be compared at most once (real-time). So, it is more efficient than the original KMP algorithm and good in practice."
},
{
"code": null,
"e": 13055,
"s": 13044,
"text": "Algorithms"
},
{
"code": null,
"e": 13071,
"s": 13055,
"text": "Data Structures"
},
{
"code": null,
"e": 13089,
"s": 13071,
"text": "Pattern Searching"
},
{
"code": null,
"e": 13099,
"s": 13089,
"text": "Searching"
},
{
"code": null,
"e": 13107,
"s": 13099,
"text": "Strings"
},
{
"code": null,
"e": 13123,
"s": 13107,
"text": "Data Structures"
},
{
"code": null,
"e": 13133,
"s": 13123,
"text": "Searching"
},
{
"code": null,
"e": 13141,
"s": 13133,
"text": "Strings"
},
{
"code": null,
"e": 13159,
"s": 13141,
"text": "Pattern Searching"
},
{
"code": null,
"e": 13170,
"s": 13159,
"text": "Algorithms"
},
{
"code": null,
"e": 13268,
"s": 13170,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 13306,
"s": 13268,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 13374,
"s": 13306,
"text": "Find if there is a path between two vertices in an undirected graph"
},
{
"code": null,
"e": 13401,
"s": 13374,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 13444,
"s": 13401,
"text": "Complete Roadmap To Learn DSA From Scratch"
},
{
"code": null,
"e": 13511,
"s": 13444,
"text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete"
},
{
"code": null,
"e": 13543,
"s": 13511,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 13581,
"s": 13543,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 13637,
"s": 13581,
"text": "Doubly Linked List | Set 1 (Introduction and Insertion)"
},
{
"code": null,
"e": 13673,
"s": 13637,
"text": "Introduction to Tree Data Structure"
}
] |
Inserting variables to database table using Python | 02 Jul, 2021
In this article, we will see how one can insert the user data using variables. Here, we are using the sqlite module to work on a database but before that, we need to import that package.
import sqlite3
To see the operation on a database level just download the SQLite browser database.Note: For the demonstration, we have used certain values but you can take input instead of those sample values.Steps to create and Insert variables in databaseCode #1: Create the database
Python3
conn = sqlite3.connect('pythonDB.db')c = conn.cursor()
Explanation: We have initialised the database pythonDB.py. This instruction will create the database if the database doesn’t exist. If the database having the same name as defined exist than it will move further. In the second statement, we use a method of sqlite3 named cursor(), this help you to initiate the database as active.Cursors are created by the connection cursor() method, they are bound to the connection for the entire lifetime and all the commands are executed in the context of the database session wrapped by the connection. Code #2: Create table
Python3
def create_table(): c.execute('CREATE TABLE IF NOT EXISTS RecordONE (Number REAL, Name TEXT)')
Explanation: We have created a function create_table. This will help you to create table if not exist, as written in the query for SQLite database. As we have initiated the table name by RecordONE. After that we pass as many parameters as we want, we just need to give an attribute name along with its type, here, we use REAL and Text. Code #3: Inserting into table
Python3
def data_entry(): number = 1234 name = "GeeksforGeeks" c.execute("INSERT INTO RecordONE (Number, Name) VALUES(?, ?)", (number, name)) conn.commit()
Explanation: Another function called data_entry. We are trying to add the values into the database with the help of user input or by variables. We use the execute() method to execute the query. Then use the commit() method to save the changes you have done above. Code #4: Method calling and Close the connection.
Python3
create_table()data_entry() c.close()conn.close()
Explanation: We normally use the method call, also remember to close the connection and database for the next use if we want to write error-free code because without closing we can’t open the connection again.Let’s see the complete example now. Example:
Python3
import sqlite3 conn = sqlite3.connect('pythonDB.db')c = conn.cursor() def create_table(): c.execute('CREATE TABLE IF NOT EXISTS RecordONE (Number REAL, Name TEXT)') def data_entry(): number = 1234 name = "GeeksforGeeks" c.execute("INSERT INTO RecordONE (Number, Name) VALUES(?, ?)", (number, name)) conn.commit() create_table()data_entry() c.close()conn.close()
Output:
Inserting one more value using data_entry() method.
Python3
def data_entry(): number = 4321 name = "Author" c.execute("INSERT INTO RecordONE (Number, Name) VALUES(?, ?)", (number, name)) conn.commit()
Output:
anikaseth98
Python-database
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n02 Jul, 2021"
},
{
"code": null,
"e": 243,
"s": 54,
"text": "In this article, we will see how one can insert the user data using variables. Here, we are using the sqlite module to work on a database but before that, we need to import that package. "
},
{
"code": null,
"e": 258,
"s": 243,
"text": "import sqlite3"
},
{
"code": null,
"e": 530,
"s": 258,
"text": "To see the operation on a database level just download the SQLite browser database.Note: For the demonstration, we have used certain values but you can take input instead of those sample values.Steps to create and Insert variables in databaseCode #1: Create the database "
},
{
"code": null,
"e": 538,
"s": 530,
"text": "Python3"
},
{
"code": "conn = sqlite3.connect('pythonDB.db')c = conn.cursor()",
"e": 593,
"s": 538,
"text": null
},
{
"code": null,
"e": 1159,
"s": 593,
"text": "Explanation: We have initialised the database pythonDB.py. This instruction will create the database if the database doesn’t exist. If the database having the same name as defined exist than it will move further. In the second statement, we use a method of sqlite3 named cursor(), this help you to initiate the database as active.Cursors are created by the connection cursor() method, they are bound to the connection for the entire lifetime and all the commands are executed in the context of the database session wrapped by the connection. Code #2: Create table "
},
{
"code": null,
"e": 1167,
"s": 1159,
"text": "Python3"
},
{
"code": "def create_table(): c.execute('CREATE TABLE IF NOT EXISTS RecordONE (Number REAL, Name TEXT)')",
"e": 1265,
"s": 1167,
"text": null
},
{
"code": null,
"e": 1633,
"s": 1265,
"text": "Explanation: We have created a function create_table. This will help you to create table if not exist, as written in the query for SQLite database. As we have initiated the table name by RecordONE. After that we pass as many parameters as we want, we just need to give an attribute name along with its type, here, we use REAL and Text. Code #3: Inserting into table "
},
{
"code": null,
"e": 1641,
"s": 1633,
"text": "Python3"
},
{
"code": "def data_entry(): number = 1234 name = \"GeeksforGeeks\" c.execute(\"INSERT INTO RecordONE (Number, Name) VALUES(?, ?)\", (number, name)) conn.commit()",
"e": 1851,
"s": 1641,
"text": null
},
{
"code": null,
"e": 2167,
"s": 1851,
"text": "Explanation: Another function called data_entry. We are trying to add the values into the database with the help of user input or by variables. We use the execute() method to execute the query. Then use the commit() method to save the changes you have done above. Code #4: Method calling and Close the connection. "
},
{
"code": null,
"e": 2175,
"s": 2167,
"text": "Python3"
},
{
"code": "create_table()data_entry() c.close()conn.close()",
"e": 2224,
"s": 2175,
"text": null
},
{
"code": null,
"e": 2479,
"s": 2224,
"text": "Explanation: We normally use the method call, also remember to close the connection and database for the next use if we want to write error-free code because without closing we can’t open the connection again.Let’s see the complete example now. Example: "
},
{
"code": null,
"e": 2487,
"s": 2479,
"text": "Python3"
},
{
"code": "import sqlite3 conn = sqlite3.connect('pythonDB.db')c = conn.cursor() def create_table(): c.execute('CREATE TABLE IF NOT EXISTS RecordONE (Number REAL, Name TEXT)') def data_entry(): number = 1234 name = \"GeeksforGeeks\" c.execute(\"INSERT INTO RecordONE (Number, Name) VALUES(?, ?)\", (number, name)) conn.commit() create_table()data_entry() c.close()conn.close()",
"e": 2864,
"s": 2487,
"text": null
},
{
"code": null,
"e": 2874,
"s": 2864,
"text": "Output: "
},
{
"code": null,
"e": 2928,
"s": 2874,
"text": "Inserting one more value using data_entry() method. "
},
{
"code": null,
"e": 2936,
"s": 2928,
"text": "Python3"
},
{
"code": "def data_entry(): number = 4321 name = \"Author\" c.execute(\"INSERT INTO RecordONE (Number, Name) VALUES(?, ?)\", (number, name)) conn.commit()",
"e": 3089,
"s": 2936,
"text": null
},
{
"code": null,
"e": 3099,
"s": 3089,
"text": "Output: "
},
{
"code": null,
"e": 3113,
"s": 3101,
"text": "anikaseth98"
},
{
"code": null,
"e": 3129,
"s": 3113,
"text": "Python-database"
},
{
"code": null,
"e": 3136,
"s": 3129,
"text": "Python"
},
{
"code": null,
"e": 3234,
"s": 3136,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3276,
"s": 3234,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3298,
"s": 3276,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3324,
"s": 3298,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3356,
"s": 3324,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3385,
"s": 3356,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3412,
"s": 3385,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3433,
"s": 3412,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3469,
"s": 3433,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 3492,
"s": 3469,
"text": "Introduction To PYTHON"
}
] |
JavaScript Number valueOf( ) Method | 22 Dec, 2021
Below is the example of the Number valueOf( ) Method.
Example: <script type="text/javascript"> var num=NaN; document.write("Output : " + num.valueOf()); </script>
<script type="text/javascript"> var num=NaN; document.write("Output : " + num.valueOf()); </script>
OUTPUT:Output : NaN
Output : NaN
The valueof() method in JavaScript is used to return the primitive value of a number.This method is usually called internally by JavaScript and not explicitly in web code.
Syntax:
number.valueOf()
Return Value:The valueof() method in JavaScript returns a number representing the primitive value of the specified Number object.
What is Primitive Value?Primitive values are the type of values that a variable can hold. A primitive value is stored directly in the location that the variable accesses. Primitive values are data that are stored on the stack.Primitive types include Undefined, Null, Boolean, Number, or String.
Examples:
Input : 213
Output : 213
Input : -213
Output :-213
Input : 0
Output : 0
Input : 0/0
Output : NaN
Passing a positive number as an argument in the valueOf() method.<script type="text/javascript"> var num=213; document.write("Output : " + num.valueOf()); </script>OUTPUT:Output : 213Passing a negative number as an argument in the valueOf() method.<script type="text/javascript"> var num=-213; document.write("Output : " + num.valueOf()); </script>OUTPUT:Output : -213Passing a zero as an argument in the valueOf() method.<script type="text/javascript"> var num=0; document.write("Output : " + num.valueOf()); </script>OUTPUT:Output : 0Passing an equation(equating to infinite value) as an argument in the valueOf() method.<script type="text/javascript"> var num=0/0; document.write("Output : " + num.valueOf()); </script>OUTPUT:Output : Nan
Passing a positive number as an argument in the valueOf() method.<script type="text/javascript"> var num=213; document.write("Output : " + num.valueOf()); </script>OUTPUT:Output : 213
<script type="text/javascript"> var num=213; document.write("Output : " + num.valueOf()); </script>
OUTPUT:
Output : 213
Passing a negative number as an argument in the valueOf() method.<script type="text/javascript"> var num=-213; document.write("Output : " + num.valueOf()); </script>OUTPUT:Output : -213
<script type="text/javascript"> var num=-213; document.write("Output : " + num.valueOf()); </script>
OUTPUT:
Output : -213
Passing a zero as an argument in the valueOf() method.<script type="text/javascript"> var num=0; document.write("Output : " + num.valueOf()); </script>OUTPUT:Output : 0
<script type="text/javascript"> var num=0; document.write("Output : " + num.valueOf()); </script>
OUTPUT:
Output : 0
Passing an equation(equating to infinite value) as an argument in the valueOf() method.<script type="text/javascript"> var num=0/0; document.write("Output : " + num.valueOf()); </script>OUTPUT:Output : Nan
<script type="text/javascript"> var num=0/0; document.write("Output : " + num.valueOf()); </script>
OUTPUT:
Output : Nan
Supported Browsers:
Google Chrome 1 and above
Internet Explorer 4 and above
Firefox 1 and above
Apple Safari 1 and above
Opera 3 and above
ysachin2314
javascript-math
JavaScript-Numbers
JavaScript
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
How to append HTML code to a div using JavaScript ?
Difference Between PUT and PATCH Request
How to Open URL in New Tab using JavaScript ?
How to get character array from string in JavaScript?
Roadmap to Learn JavaScript For Beginners
How do you run JavaScript script through the Terminal?
Node.js | fs.writeFileSync() Method | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Dec, 2021"
},
{
"code": null,
"e": 82,
"s": 28,
"text": "Below is the example of the Number valueOf( ) Method."
},
{
"code": null,
"e": 215,
"s": 82,
"text": "Example: <script type=\"text/javascript\"> var num=NaN; document.write(\"Output : \" + num.valueOf()); </script> "
},
{
"code": " <script type=\"text/javascript\"> var num=NaN; document.write(\"Output : \" + num.valueOf()); </script> ",
"e": 340,
"s": 215,
"text": null
},
{
"code": null,
"e": 360,
"s": 340,
"text": "OUTPUT:Output : NaN"
},
{
"code": null,
"e": 373,
"s": 360,
"text": "Output : NaN"
},
{
"code": null,
"e": 545,
"s": 373,
"text": "The valueof() method in JavaScript is used to return the primitive value of a number.This method is usually called internally by JavaScript and not explicitly in web code."
},
{
"code": null,
"e": 553,
"s": 545,
"text": "Syntax:"
},
{
"code": null,
"e": 570,
"s": 553,
"text": "number.valueOf()"
},
{
"code": null,
"e": 700,
"s": 570,
"text": "Return Value:The valueof() method in JavaScript returns a number representing the primitive value of the specified Number object."
},
{
"code": null,
"e": 995,
"s": 700,
"text": "What is Primitive Value?Primitive values are the type of values that a variable can hold. A primitive value is stored directly in the location that the variable accesses. Primitive values are data that are stored on the stack.Primitive types include Undefined, Null, Boolean, Number, or String."
},
{
"code": null,
"e": 1005,
"s": 995,
"text": "Examples:"
},
{
"code": null,
"e": 1114,
"s": 1005,
"text": "Input : 213\nOutput : 213\n \nInput : -213\nOutput :-213\n\nInput : 0\nOutput : 0\n\nInput : 0/0\nOutput : NaN\n"
},
{
"code": null,
"e": 1908,
"s": 1114,
"text": "Passing a positive number as an argument in the valueOf() method.<script type=\"text/javascript\"> var num=213; document.write(\"Output : \" + num.valueOf()); </script>OUTPUT:Output : 213Passing a negative number as an argument in the valueOf() method.<script type=\"text/javascript\"> var num=-213; document.write(\"Output : \" + num.valueOf()); </script>OUTPUT:Output : -213Passing a zero as an argument in the valueOf() method.<script type=\"text/javascript\"> var num=0; document.write(\"Output : \" + num.valueOf()); </script>OUTPUT:Output : 0Passing an equation(equating to infinite value) as an argument in the valueOf() method.<script type=\"text/javascript\"> var num=0/0; document.write(\"Output : \" + num.valueOf()); </script>OUTPUT:Output : Nan"
},
{
"code": null,
"e": 2105,
"s": 1908,
"text": "Passing a positive number as an argument in the valueOf() method.<script type=\"text/javascript\"> var num=213; document.write(\"Output : \" + num.valueOf()); </script>OUTPUT:Output : 213"
},
{
"code": "<script type=\"text/javascript\"> var num=213; document.write(\"Output : \" + num.valueOf()); </script>",
"e": 2218,
"s": 2105,
"text": null
},
{
"code": null,
"e": 2226,
"s": 2218,
"text": "OUTPUT:"
},
{
"code": null,
"e": 2239,
"s": 2226,
"text": "Output : 213"
},
{
"code": null,
"e": 2438,
"s": 2239,
"text": "Passing a negative number as an argument in the valueOf() method.<script type=\"text/javascript\"> var num=-213; document.write(\"Output : \" + num.valueOf()); </script>OUTPUT:Output : -213"
},
{
"code": "<script type=\"text/javascript\"> var num=-213; document.write(\"Output : \" + num.valueOf()); </script>",
"e": 2552,
"s": 2438,
"text": null
},
{
"code": null,
"e": 2560,
"s": 2552,
"text": "OUTPUT:"
},
{
"code": null,
"e": 2574,
"s": 2560,
"text": "Output : -213"
},
{
"code": null,
"e": 2756,
"s": 2574,
"text": "Passing a zero as an argument in the valueOf() method.<script type=\"text/javascript\"> var num=0; document.write(\"Output : \" + num.valueOf()); </script>OUTPUT:Output : 0"
},
{
"code": "<script type=\"text/javascript\"> var num=0; document.write(\"Output : \" + num.valueOf()); </script>",
"e": 2867,
"s": 2756,
"text": null
},
{
"code": null,
"e": 2875,
"s": 2867,
"text": "OUTPUT:"
},
{
"code": null,
"e": 2886,
"s": 2875,
"text": "Output : 0"
},
{
"code": null,
"e": 3105,
"s": 2886,
"text": "Passing an equation(equating to infinite value) as an argument in the valueOf() method.<script type=\"text/javascript\"> var num=0/0; document.write(\"Output : \" + num.valueOf()); </script>OUTPUT:Output : Nan"
},
{
"code": "<script type=\"text/javascript\"> var num=0/0; document.write(\"Output : \" + num.valueOf()); </script>",
"e": 3218,
"s": 3105,
"text": null
},
{
"code": null,
"e": 3226,
"s": 3218,
"text": "OUTPUT:"
},
{
"code": null,
"e": 3239,
"s": 3226,
"text": "Output : Nan"
},
{
"code": null,
"e": 3259,
"s": 3239,
"text": "Supported Browsers:"
},
{
"code": null,
"e": 3285,
"s": 3259,
"text": "Google Chrome 1 and above"
},
{
"code": null,
"e": 3315,
"s": 3285,
"text": "Internet Explorer 4 and above"
},
{
"code": null,
"e": 3335,
"s": 3315,
"text": "Firefox 1 and above"
},
{
"code": null,
"e": 3360,
"s": 3335,
"text": "Apple Safari 1 and above"
},
{
"code": null,
"e": 3378,
"s": 3360,
"text": "Opera 3 and above"
},
{
"code": null,
"e": 3390,
"s": 3378,
"text": "ysachin2314"
},
{
"code": null,
"e": 3406,
"s": 3390,
"text": "javascript-math"
},
{
"code": null,
"e": 3425,
"s": 3406,
"text": "JavaScript-Numbers"
},
{
"code": null,
"e": 3436,
"s": 3425,
"text": "JavaScript"
},
{
"code": null,
"e": 3534,
"s": 3436,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3595,
"s": 3534,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3667,
"s": 3595,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 3707,
"s": 3667,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 3759,
"s": 3707,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 3800,
"s": 3759,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 3846,
"s": 3800,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 3900,
"s": 3846,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 3942,
"s": 3900,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 3997,
"s": 3942,
"text": "How do you run JavaScript script through the Terminal?"
}
] |
HTML | Change Background color using onmouseover property | 31 Jul, 2018
In this post, the working of onmouseover event is shown by changing the colours of a paragraph by taking the mouse over a particular colour.
Syntax:
document.bgColor = 'nameOfColor'
HTML code that will change the colour of the background when the mouse is moved over a particular colour. Background colour property specifies the background colour of an element.
<html> <p> <!-- when mouse is move over the colour name, colour change --> <a onmouseover="document.bgColor='greem'">Bright Green</a><br> <a onmouseover="document.bgColor='red'">Red</a><br> <a onmouseover="document.bgColor='magenta'">Magenta</a><br> <a onmouseover="document.bgColor='purple'">Purple</a><br> <a onmouseover="document.bgColor='blue'">Blue</a><br> <a onmouseover="document.bgColor='yellow'">Yellow</a><br> <a onmouseover="document.bgColor='black'">Black</a><br> <a onmouseover="document.bgColor='orange'">Orange</a><br> </p></html>
Output:Initially, the background colour is white-
When the mouse is moved over the “Bright Green” color-
When the mouse is moved over the “Red” colour-
When the mouse is moved over the “magenta” colour-
When the mouse is moved over the “purple” colour-
When the mouse is moved over the “blue” colour-
When the mouse is moved over the “black” colour-
When the mouse is moved over the “orange” colour-
When the mouse is moved over “yellow” colour-
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
HTTP headers | Content-Type
How to Insert Form Data into Database using PHP ?
How to position a div at the bottom of its container using CSS?
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n31 Jul, 2018"
},
{
"code": null,
"e": 195,
"s": 54,
"text": "In this post, the working of onmouseover event is shown by changing the colours of a paragraph by taking the mouse over a particular colour."
},
{
"code": null,
"e": 203,
"s": 195,
"text": "Syntax:"
},
{
"code": null,
"e": 237,
"s": 203,
"text": "document.bgColor = 'nameOfColor'\n"
},
{
"code": null,
"e": 417,
"s": 237,
"text": "HTML code that will change the colour of the background when the mouse is moved over a particular colour. Background colour property specifies the background colour of an element."
},
{
"code": "<html> <p> <!-- when mouse is move over the colour name, colour change --> <a onmouseover=\"document.bgColor='greem'\">Bright Green</a><br> <a onmouseover=\"document.bgColor='red'\">Red</a><br> <a onmouseover=\"document.bgColor='magenta'\">Magenta</a><br> <a onmouseover=\"document.bgColor='purple'\">Purple</a><br> <a onmouseover=\"document.bgColor='blue'\">Blue</a><br> <a onmouseover=\"document.bgColor='yellow'\">Yellow</a><br> <a onmouseover=\"document.bgColor='black'\">Black</a><br> <a onmouseover=\"document.bgColor='orange'\">Orange</a><br> </p></html>",
"e": 992,
"s": 417,
"text": null
},
{
"code": null,
"e": 1042,
"s": 992,
"text": "Output:Initially, the background colour is white-"
},
{
"code": null,
"e": 1097,
"s": 1042,
"text": "When the mouse is moved over the “Bright Green” color-"
},
{
"code": null,
"e": 1144,
"s": 1097,
"text": "When the mouse is moved over the “Red” colour-"
},
{
"code": null,
"e": 1195,
"s": 1144,
"text": "When the mouse is moved over the “magenta” colour-"
},
{
"code": null,
"e": 1245,
"s": 1195,
"text": "When the mouse is moved over the “purple” colour-"
},
{
"code": null,
"e": 1293,
"s": 1245,
"text": "When the mouse is moved over the “blue” colour-"
},
{
"code": null,
"e": 1342,
"s": 1293,
"text": "When the mouse is moved over the “black” colour-"
},
{
"code": null,
"e": 1392,
"s": 1342,
"text": "When the mouse is moved over the “orange” colour-"
},
{
"code": null,
"e": 1438,
"s": 1392,
"text": "When the mouse is moved over “yellow” colour-"
},
{
"code": null,
"e": 1443,
"s": 1438,
"text": "HTML"
},
{
"code": null,
"e": 1460,
"s": 1443,
"text": "Web Technologies"
},
{
"code": null,
"e": 1465,
"s": 1460,
"text": "HTML"
},
{
"code": null,
"e": 1563,
"s": 1465,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1587,
"s": 1563,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 1626,
"s": 1587,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 1654,
"s": 1626,
"text": "HTTP headers | Content-Type"
},
{
"code": null,
"e": 1704,
"s": 1654,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 1768,
"s": 1704,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 1801,
"s": 1768,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1862,
"s": 1801,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1905,
"s": 1862,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 1977,
"s": 1905,
"text": "Differences between Functional Components and Class Components in React"
}
] |
Toggle first and last bits of a number | 06 Jul, 2022
Given a number n, the task is to toggle only first and last bits of a numberExamples :
Input : 10
Output : 3
Binary representation of 10 is
1010. After toggling first and
last bits, we get 0011.
Input : 15
Output : 6
Prerequisite : Find MSB of given number.1) Generate a number which contains first and last bit as set. We need to change all middle bits to 0 and keep corner bits as 1.2) Answer is XOR of generated number and original number.
C++
Java
Python3
C#
PHP
Javascript
// CPP program to toggle first and last// bits of a number#include <iostream>using namespace std; // Returns a number which has same bit// count as n and has only first and last// bits as set.int takeLandFsetbits(int n){ // set all the bit of the number n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // Adding one to n now unsets // all bits and moves MSB to // one place. Now we shift // the number by 1 and add 1. return ((n + 1) >> 1) + 1;} int toggleFandLbits(int n){ // if number is 1 if (n == 1) return 0; // take XOR with first and // last set bit number return n ^ takeLandFsetbits(n);} // Driver codeint main(){ int n = 10; cout << toggleFandLbits(n); return 0;}
// Java program to toggle first and last// bits of a numberimport java.io.*; class GFG { // Returns a number which has same bit // count as n and has only first and last // bits as set. static int takeLandFsetbits(int n) { // set all the bit of the number n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // Adding one to n now unsets // all bits and moves MSB to // one place. Now we shift // the number by 1 and add 1. return ((n + 1) >> 1) + 1; } static int toggleFandLbits(int n) { // if number is 1 if (n == 1) return 0; // take XOR with first and // last set bit number return n ^ takeLandFsetbits(n); } // Driver code public static void main(String args[]) { int n = 10; System.out.println(toggleFandLbits(n)); }} /*This code is contributed by Nikita Tiwari.*/
# Python 3 program to toggle first# and last bits of a number. # Returns a number which has same bit# count as n and has only first and last# bits as set.def takeLandFsetbits(n) : # set all the bit of the number n = n | n >> 1 n = n | n >> 2 n = n | n >> 4 n = n | n >> 8 n = n | n >> 16 # Adding one to n now unsets # all bits and moves MSB to # one place. Now we shift # the number by 1 and add 1. return ((n + 1) >> 1) + 1 def toggleFandLbits(n) : # if number is 1 if (n == 1) : return 0 # take XOR with first and # last set bit number return n ^ takeLandFsetbits(n) # Driver coden = 10print(toggleFandLbits(n)) # This code is contributed by Nikita Tiwari.
// C# program to toggle first and last// bits of a numberusing System; class GFG { // Returns a number which has same bit // count as n and has only first and last // bits as set. static int takeLandFsetbits(int n) { // set all the bit of the number n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // Adding one to n now unsets // all bits and moves MSB to // one place. Now we shift // the number by 1 and add 1. return ((n + 1) >> 1) + 1; } static int toggleFandLbits(int n) { // if number is 1 if (n == 1) return 0; // take XOR with first and // last set bit number return n ^ takeLandFsetbits(n); } // Driver code public static void Main() { int n = 10; Console.WriteLine(toggleFandLbits(n)); }} // This code is contributed by Anant Agarwal.
<?php// PHP program to toggle first and last// bits of a number // Returns a number which has same bit// count as n and has only first and last// bits as set.function takeLandFsetbits($n){ // set all the bit of the number $n |= $n >> 1; $n |= $n >> 2; $n |= $n >> 4; $n |= $n >> 8; $n |= $n >> 16; // Adding one to n now unsets // all bits and moves MSB to // one place. Now we shift // the number by 1 and add 1. return (($n + 1) >> 1) + 1;} function toggleFandLbits(int $n){ // if number is 1 if ($n == 1) return 0; // take XOR with first and // last set bit number return $n ^ takeLandFsetbits($n);} // Driver code$n = 10;echo toggleFandLbits($n); // This code is contributed by mits?>
<script> // JavaScript program to toggle first and last// bits of a number // Returns a number which has same bit // count as n and has only first and last // bits as set. function takeLandFsetbits(n) { // set all the bit of the number n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // Adding one to n now unsets // all bits and moves MSB to // one place. Now we shift // the number by 1 and add 1. return ((n + 1) >> 1) + 1; } function toggleFandLbits(n) { // if number is 1 if (n == 1) return 0; // take XOR with first and // last set bit number return n ^ takeLandFsetbits(n); } // Driver code let n = 10; document.write(toggleFandLbits(n)); </script>
3
Time Complexity: O(1).Auxiliary Space: O(1).
Another Approach:
We can do this in two steps by:
To generate an bit mask for n, where only the last and first bits are set, we need to calculate 2log2n + 20
Then, just take the XOR of the mask and n.
C++
Java
Python3
C#
Javascript
// CPP program to toggle first and last// bits of a number#include <bits/stdc++.h>using namespace std; //function to toggle first and last bits//of a numberint toggleFandLbits(int n){ //calculating mask int mask = pow(2, (int)log2(n)) + 1; //taking xor of mask and n return mask ^ n;} // Driver codeint main(){ int n = 10; //function call cout << toggleFandLbits(n); return 0;} //this code is contributed by phasing17
// Java program to toggle first and last// bits of a numberclass GFG{ // function to toggle first and last bits // of a number static int toggleFandLbits(int n) { // calculating mask int mask = (int)Math.pow( 2, (int)(Math.log(n) / Math.log(2))) + 1; // taking xor of mask and n return mask ^ n; } // Driver code public static void main(String[] args) { int n = 10; // Function call System.out.println(toggleFandLbits(n)); }} // this code is contributed by phasing17
# Python3 program to toggle first and last# bits of a numberfrom math import log # Function to toggle first and last bits# of a numberdef toggleFandLbits(n): # calculating mask mask = 2 ** (int(log(n, 2))) + 1 # taking xor of mask and n return mask ^ n # Driver coden = 10 # Function callprint(toggleFandLbits(n)) # This code is contributed by phasing17
// C# program to toggle first and last// bits of a numberusing System; class GFG { // function to toggle first and last bits // of a number static int toggleFandLbits(int n) { // calculating mask int mask = (int)Math.Pow( 2, (int)(Math.Log(n) / Math.Log(2))) + 1; // taking xor of mask and n return mask ^ n; } // Driver code public static void Main(string[] args) { int n = 10; // Function call Console.WriteLine(toggleFandLbits(n)); }} // This code is contributed by phasing17
// JavaScript program to toggle first and last// bits of a number // function to toggle first and last bits// of a numberfunction toggleFandLbits(n){ // calculating mask let mask = Math.pow(2, Math.floor(Math.log2(n))) + 1; // taking xor of mask and n return mask ^ n;} // Driver codelet n = 10; // function callconsole.log(toggleFandLbits(n)); // This code is contributed by phasing17
3
Time Complexity: O(1).Auxiliary Space: O(1).
Mithun Kumar
susmitakundugoaldanga
ranjanrohit840
phasing17
Bitwise-XOR
Bit Magic
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to find whether a given number is power of 2
Little and Big Endian Mystery
Bits manipulation (Important tactics)
Binary representation of a given number
Josephus problem | Set 1 (A O(n) Solution)
Divide two integers without using multiplication, division and mod operator
Bit Fields in C
Find the element that appears once
Add two numbers without using arithmetic operators
C++ bitset and its application | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n06 Jul, 2022"
},
{
"code": null,
"e": 143,
"s": 54,
"text": "Given a number n, the task is to toggle only first and last bits of a numberExamples : "
},
{
"code": null,
"e": 274,
"s": 143,
"text": "Input : 10\nOutput : 3\nBinary representation of 10 is\n1010. After toggling first and\nlast bits, we get 0011.\n\nInput : 15\nOutput : 6"
},
{
"code": null,
"e": 504,
"s": 276,
"text": "Prerequisite : Find MSB of given number.1) Generate a number which contains first and last bit as set. We need to change all middle bits to 0 and keep corner bits as 1.2) Answer is XOR of generated number and original number. "
},
{
"code": null,
"e": 508,
"s": 504,
"text": "C++"
},
{
"code": null,
"e": 513,
"s": 508,
"text": "Java"
},
{
"code": null,
"e": 521,
"s": 513,
"text": "Python3"
},
{
"code": null,
"e": 524,
"s": 521,
"text": "C#"
},
{
"code": null,
"e": 528,
"s": 524,
"text": "PHP"
},
{
"code": null,
"e": 539,
"s": 528,
"text": "Javascript"
},
{
"code": "// CPP program to toggle first and last// bits of a number#include <iostream>using namespace std; // Returns a number which has same bit// count as n and has only first and last// bits as set.int takeLandFsetbits(int n){ // set all the bit of the number n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // Adding one to n now unsets // all bits and moves MSB to // one place. Now we shift // the number by 1 and add 1. return ((n + 1) >> 1) + 1;} int toggleFandLbits(int n){ // if number is 1 if (n == 1) return 0; // take XOR with first and // last set bit number return n ^ takeLandFsetbits(n);} // Driver codeint main(){ int n = 10; cout << toggleFandLbits(n); return 0;}",
"e": 1297,
"s": 539,
"text": null
},
{
"code": "// Java program to toggle first and last// bits of a numberimport java.io.*; class GFG { // Returns a number which has same bit // count as n and has only first and last // bits as set. static int takeLandFsetbits(int n) { // set all the bit of the number n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // Adding one to n now unsets // all bits and moves MSB to // one place. Now we shift // the number by 1 and add 1. return ((n + 1) >> 1) + 1; } static int toggleFandLbits(int n) { // if number is 1 if (n == 1) return 0; // take XOR with first and // last set bit number return n ^ takeLandFsetbits(n); } // Driver code public static void main(String args[]) { int n = 10; System.out.println(toggleFandLbits(n)); }} /*This code is contributed by Nikita Tiwari.*/",
"e": 2283,
"s": 1297,
"text": null
},
{
"code": "# Python 3 program to toggle first# and last bits of a number. # Returns a number which has same bit# count as n and has only first and last# bits as set.def takeLandFsetbits(n) : # set all the bit of the number n = n | n >> 1 n = n | n >> 2 n = n | n >> 4 n = n | n >> 8 n = n | n >> 16 # Adding one to n now unsets # all bits and moves MSB to # one place. Now we shift # the number by 1 and add 1. return ((n + 1) >> 1) + 1 def toggleFandLbits(n) : # if number is 1 if (n == 1) : return 0 # take XOR with first and # last set bit number return n ^ takeLandFsetbits(n) # Driver coden = 10print(toggleFandLbits(n)) # This code is contributed by Nikita Tiwari.",
"e": 3006,
"s": 2283,
"text": null
},
{
"code": "// C# program to toggle first and last// bits of a numberusing System; class GFG { // Returns a number which has same bit // count as n and has only first and last // bits as set. static int takeLandFsetbits(int n) { // set all the bit of the number n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // Adding one to n now unsets // all bits and moves MSB to // one place. Now we shift // the number by 1 and add 1. return ((n + 1) >> 1) + 1; } static int toggleFandLbits(int n) { // if number is 1 if (n == 1) return 0; // take XOR with first and // last set bit number return n ^ takeLandFsetbits(n); } // Driver code public static void Main() { int n = 10; Console.WriteLine(toggleFandLbits(n)); }} // This code is contributed by Anant Agarwal.",
"e": 4008,
"s": 3006,
"text": null
},
{
"code": "<?php// PHP program to toggle first and last// bits of a number // Returns a number which has same bit// count as n and has only first and last// bits as set.function takeLandFsetbits($n){ // set all the bit of the number $n |= $n >> 1; $n |= $n >> 2; $n |= $n >> 4; $n |= $n >> 8; $n |= $n >> 16; // Adding one to n now unsets // all bits and moves MSB to // one place. Now we shift // the number by 1 and add 1. return (($n + 1) >> 1) + 1;} function toggleFandLbits(int $n){ // if number is 1 if ($n == 1) return 0; // take XOR with first and // last set bit number return $n ^ takeLandFsetbits($n);} // Driver code$n = 10;echo toggleFandLbits($n); // This code is contributed by mits?>",
"e": 4754,
"s": 4008,
"text": null
},
{
"code": "<script> // JavaScript program to toggle first and last// bits of a number // Returns a number which has same bit // count as n and has only first and last // bits as set. function takeLandFsetbits(n) { // set all the bit of the number n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // Adding one to n now unsets // all bits and moves MSB to // one place. Now we shift // the number by 1 and add 1. return ((n + 1) >> 1) + 1; } function toggleFandLbits(n) { // if number is 1 if (n == 1) return 0; // take XOR with first and // last set bit number return n ^ takeLandFsetbits(n); } // Driver code let n = 10; document.write(toggleFandLbits(n)); </script>",
"e": 5618,
"s": 4754,
"text": null
},
{
"code": null,
"e": 5620,
"s": 5618,
"text": "3"
},
{
"code": null,
"e": 5666,
"s": 5620,
"text": "Time Complexity: O(1).Auxiliary Space: O(1). "
},
{
"code": null,
"e": 5684,
"s": 5666,
"text": "Another Approach:"
},
{
"code": null,
"e": 5716,
"s": 5684,
"text": "We can do this in two steps by:"
},
{
"code": null,
"e": 5824,
"s": 5716,
"text": "To generate an bit mask for n, where only the last and first bits are set, we need to calculate 2log2n + 20"
},
{
"code": null,
"e": 5867,
"s": 5824,
"text": "Then, just take the XOR of the mask and n."
},
{
"code": null,
"e": 5871,
"s": 5867,
"text": "C++"
},
{
"code": null,
"e": 5876,
"s": 5871,
"text": "Java"
},
{
"code": null,
"e": 5884,
"s": 5876,
"text": "Python3"
},
{
"code": null,
"e": 5887,
"s": 5884,
"text": "C#"
},
{
"code": null,
"e": 5898,
"s": 5887,
"text": "Javascript"
},
{
"code": "// CPP program to toggle first and last// bits of a number#include <bits/stdc++.h>using namespace std; //function to toggle first and last bits//of a numberint toggleFandLbits(int n){ //calculating mask int mask = pow(2, (int)log2(n)) + 1; //taking xor of mask and n return mask ^ n;} // Driver codeint main(){ int n = 10; //function call cout << toggleFandLbits(n); return 0;} //this code is contributed by phasing17",
"e": 6341,
"s": 5898,
"text": null
},
{
"code": "// Java program to toggle first and last// bits of a numberclass GFG{ // function to toggle first and last bits // of a number static int toggleFandLbits(int n) { // calculating mask int mask = (int)Math.pow( 2, (int)(Math.log(n) / Math.log(2))) + 1; // taking xor of mask and n return mask ^ n; } // Driver code public static void main(String[] args) { int n = 10; // Function call System.out.println(toggleFandLbits(n)); }} // this code is contributed by phasing17",
"e": 6930,
"s": 6341,
"text": null
},
{
"code": "# Python3 program to toggle first and last# bits of a numberfrom math import log # Function to toggle first and last bits# of a numberdef toggleFandLbits(n): # calculating mask mask = 2 ** (int(log(n, 2))) + 1 # taking xor of mask and n return mask ^ n # Driver coden = 10 # Function callprint(toggleFandLbits(n)) # This code is contributed by phasing17",
"e": 7302,
"s": 6930,
"text": null
},
{
"code": "// C# program to toggle first and last// bits of a numberusing System; class GFG { // function to toggle first and last bits // of a number static int toggleFandLbits(int n) { // calculating mask int mask = (int)Math.Pow( 2, (int)(Math.Log(n) / Math.Log(2))) + 1; // taking xor of mask and n return mask ^ n; } // Driver code public static void Main(string[] args) { int n = 10; // Function call Console.WriteLine(toggleFandLbits(n)); }} // This code is contributed by phasing17",
"e": 7825,
"s": 7302,
"text": null
},
{
"code": "// JavaScript program to toggle first and last// bits of a number // function to toggle first and last bits// of a numberfunction toggleFandLbits(n){ // calculating mask let mask = Math.pow(2, Math.floor(Math.log2(n))) + 1; // taking xor of mask and n return mask ^ n;} // Driver codelet n = 10; // function callconsole.log(toggleFandLbits(n)); // This code is contributed by phasing17",
"e": 8234,
"s": 7825,
"text": null
},
{
"code": null,
"e": 8236,
"s": 8234,
"text": "3"
},
{
"code": null,
"e": 8282,
"s": 8236,
"text": "Time Complexity: O(1).Auxiliary Space: O(1). "
},
{
"code": null,
"e": 8295,
"s": 8282,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 8317,
"s": 8295,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 8332,
"s": 8317,
"text": "ranjanrohit840"
},
{
"code": null,
"e": 8342,
"s": 8332,
"text": "phasing17"
},
{
"code": null,
"e": 8354,
"s": 8342,
"text": "Bitwise-XOR"
},
{
"code": null,
"e": 8364,
"s": 8354,
"text": "Bit Magic"
},
{
"code": null,
"e": 8374,
"s": 8364,
"text": "Bit Magic"
},
{
"code": null,
"e": 8472,
"s": 8374,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8525,
"s": 8472,
"text": "Program to find whether a given number is power of 2"
},
{
"code": null,
"e": 8555,
"s": 8525,
"text": "Little and Big Endian Mystery"
},
{
"code": null,
"e": 8593,
"s": 8555,
"text": "Bits manipulation (Important tactics)"
},
{
"code": null,
"e": 8633,
"s": 8593,
"text": "Binary representation of a given number"
},
{
"code": null,
"e": 8676,
"s": 8633,
"text": "Josephus problem | Set 1 (A O(n) Solution)"
},
{
"code": null,
"e": 8752,
"s": 8676,
"text": "Divide two integers without using multiplication, division and mod operator"
},
{
"code": null,
"e": 8768,
"s": 8752,
"text": "Bit Fields in C"
},
{
"code": null,
"e": 8803,
"s": 8768,
"text": "Find the element that appears once"
},
{
"code": null,
"e": 8854,
"s": 8803,
"text": "Add two numbers without using arithmetic operators"
}
] |
HTML | <caption> align Attribute | 22 Feb, 2022
The HTML <caption> align Attribute is used to specify the alignment of the <caption> Element. It is used to align the caption to the left, right, top and Bottom of a table.This attribute is not supported in HTML5.
Note: By default , the table caption is aligned to center.
Syntax:
<caption align="left | right | top | bottom>
Attribute Values
left: It sets the left-align caption of the table.
right: It sets the right-align caption of the Table
Top: It sets the top-align caption of the table. It is a default value.
Bottom: It sets the bottom-align caption of the table.
Example:
<!-- HTML code to show the working of caption tag --><!DOCTYPE html><html> <head> <style> table, th, td { border: 1px solid black; } #GFG { font-size: 25px; color: green; } </style></head> <body> <h1 style="color:green;font-size:35px;"> GeeksForGeeks </h1> <h2>HTML Caption align Attribute</h2> <table> <!-- Adding caption to the table --> <caption id="GFG" align="top"> Students </caption> <tr> <th>Firstname</th> <th>Lastname</th> <th>Age</th> </tr> <tr> <td>Priya</td> <td>Sharma</td> <td>24</td> </tr> <tr> <td>Arun</td> <td>Singh</td> <td>32</td> </tr> <tr> <td>Sam</td> <td>Watson</td> <td>41</td> </tr> </table><br><br> <table> <!-- Adding caption to the table --> <caption id="GFG" align="bottom"> Students </caption> <tr> <th>Firstname</th> <th>Lastname</th> <th>Age</th> </tr> <tr> <td>Priya</td> <td>Sharma</td> <td>24</td> </tr> <tr> <td>Arun</td> <td>Singh</td> <td>32</td> </tr> <tr> <td>Sam</td> <td>Watson</td> <td>41</td> </tr> </table></body> </html>
Output :
Supported Browsers: The browsers supported by HTML <caption> align Attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Apple Safari
Opera
hritikbhatnagar2182
chhabradhanvi
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Angular File Upload
Form validation using jQuery
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Feb, 2022"
},
{
"code": null,
"e": 242,
"s": 28,
"text": "The HTML <caption> align Attribute is used to specify the alignment of the <caption> Element. It is used to align the caption to the left, right, top and Bottom of a table.This attribute is not supported in HTML5."
},
{
"code": null,
"e": 301,
"s": 242,
"text": "Note: By default , the table caption is aligned to center."
},
{
"code": null,
"e": 309,
"s": 301,
"text": "Syntax:"
},
{
"code": null,
"e": 355,
"s": 309,
"text": "<caption align=\"left | right | top | bottom> "
},
{
"code": null,
"e": 372,
"s": 355,
"text": "Attribute Values"
},
{
"code": null,
"e": 423,
"s": 372,
"text": "left: It sets the left-align caption of the table."
},
{
"code": null,
"e": 475,
"s": 423,
"text": "right: It sets the right-align caption of the Table"
},
{
"code": null,
"e": 547,
"s": 475,
"text": "Top: It sets the top-align caption of the table. It is a default value."
},
{
"code": null,
"e": 602,
"s": 547,
"text": "Bottom: It sets the bottom-align caption of the table."
},
{
"code": null,
"e": 611,
"s": 602,
"text": "Example:"
},
{
"code": "<!-- HTML code to show the working of caption tag --><!DOCTYPE html><html> <head> <style> table, th, td { border: 1px solid black; } #GFG { font-size: 25px; color: green; } </style></head> <body> <h1 style=\"color:green;font-size:35px;\"> GeeksForGeeks </h1> <h2>HTML Caption align Attribute</h2> <table> <!-- Adding caption to the table --> <caption id=\"GFG\" align=\"top\"> Students </caption> <tr> <th>Firstname</th> <th>Lastname</th> <th>Age</th> </tr> <tr> <td>Priya</td> <td>Sharma</td> <td>24</td> </tr> <tr> <td>Arun</td> <td>Singh</td> <td>32</td> </tr> <tr> <td>Sam</td> <td>Watson</td> <td>41</td> </tr> </table><br><br> <table> <!-- Adding caption to the table --> <caption id=\"GFG\" align=\"bottom\"> Students </caption> <tr> <th>Firstname</th> <th>Lastname</th> <th>Age</th> </tr> <tr> <td>Priya</td> <td>Sharma</td> <td>24</td> </tr> <tr> <td>Arun</td> <td>Singh</td> <td>32</td> </tr> <tr> <td>Sam</td> <td>Watson</td> <td>41</td> </tr> </table></body> </html>",
"e": 2167,
"s": 611,
"text": null
},
{
"code": null,
"e": 2176,
"s": 2167,
"text": "Output :"
},
{
"code": null,
"e": 2271,
"s": 2176,
"text": "Supported Browsers: The browsers supported by HTML <caption> align Attribute are listed below:"
},
{
"code": null,
"e": 2285,
"s": 2271,
"text": "Google Chrome"
},
{
"code": null,
"e": 2303,
"s": 2285,
"text": "Internet Explorer"
},
{
"code": null,
"e": 2311,
"s": 2303,
"text": "Firefox"
},
{
"code": null,
"e": 2324,
"s": 2311,
"text": "Apple Safari"
},
{
"code": null,
"e": 2330,
"s": 2324,
"text": "Opera"
},
{
"code": null,
"e": 2350,
"s": 2330,
"text": "hritikbhatnagar2182"
},
{
"code": null,
"e": 2364,
"s": 2350,
"text": "chhabradhanvi"
},
{
"code": null,
"e": 2380,
"s": 2364,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 2385,
"s": 2380,
"text": "HTML"
},
{
"code": null,
"e": 2402,
"s": 2385,
"text": "Web Technologies"
},
{
"code": null,
"e": 2407,
"s": 2402,
"text": "HTML"
},
{
"code": null,
"e": 2505,
"s": 2407,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2529,
"s": 2505,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 2568,
"s": 2529,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 2607,
"s": 2568,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 2627,
"s": 2607,
"text": "Angular File Upload"
},
{
"code": null,
"e": 2656,
"s": 2627,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 2689,
"s": 2656,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2750,
"s": 2689,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2793,
"s": 2750,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 2865,
"s": 2793,
"text": "Differences between Functional Components and Class Components in React"
}
] |
Excel VBA Concatenation Operators | 19 Jul, 2021
VBA in Excel stands for Visual Basic for Applications which is Microsoft’s programming language. To optimize the performance and reduce the time in Excel we need Macros and VBA is the tool used in the backend. Concatenation means to join two or more data into a single data. There are various ways we can perform concatenation in Excel using built-in functions, operators, etc.
Some helpful links to get more insights about concatenate and using VBA in Excel :
Record Macros in ExcelCONCATENATE in ExcelHow to Create a Macro in Excel?
Record Macros in Excel
CONCATENATE in Excel
How to Create a Macro in Excel?
In this article, we are going to see about concatenate operators and how to use VBA to concatenate strings as well as numbers.
In the Microsoft Excel tabs, select the Developer Tab. Initially, the Developer Tab may not be available.
The Developer Tab can be enabled easily by a two-step process :
Right-click on any of the existing tabs at the top of the Excel window.
Now select Customize the Ribbon from the pop-down menu.
In the Excel Options Box, check the box Developer to enable it and click on OK.
Now, the Developer Tab is visible.
Now, we need to open the Visual Basic Editor. There are two ways :
Go to Developer and directly click on the Visual Basic tab.
Go to the Insert tab and then click on the Command button. Drag and insert the command button in any cell of the Excel sheet.
Now, double-click on this command button. This will open the Visual Basic Application Editor tab, and we can write the code. The benefit of this command button is that just by clicking on the button we can see the result of concatenation, and also we don’t need to make any extra Macro in Excel to write the code.
Another way is by right-clicking on the command button and then select View Code as shown below :
To concatenate operator mostly used in Excel is “&” for numbers as well as strings. But for strings, we can also use “+” operator to concatenate two or more strings.
The syntax to concatenate using formula is :
cell_number1 & cell_number2 ; without space in between
cell_number1 & " " & cell_number2; with space in between
cell_number1 & "Any_Symbol" & cell_number2 ; with any symbol in between
cell_number(s) & "string text" ; concatenate cell values and strings
"string_text" & cell_number(s) ; concatenate cell values and strings
Example 1: Take any two numbers as input and concatenate into a single number.
The code to concatenate two numbers in Excel is :
Private Sub CommandButton1_Click()
'Inserting the number num1 and num2
Dim num1 As Integer: num1 = 10
Dim num2 As Integer: num2 = 50
'Declare a variable c to concatenate num1 and num2
Dim c As Integer
'Concatenate the numbers
c = num1 & num2
MsgBox ("The result after concatenating two numbers are: " & c)
End Sub
Run the above code in VBA and the output will be shown in the message box.
Output :
The result after concatenating two numbers are: 1050
You can also click on the command button and the same message will be displayed.
Example 2: Say, now we take two numbers from the cells of the Excel Sheet and store the result back in the Excel sheet. This time we are not going to use the command button.
Step 1: Open the VB editor from the Developer Tab.
Developer -> Visual Basic -> Tools -> Macros
Step 2: The editor is now ready where we can write the code and syntax for concatenation.
Now write the following code and run it.
Sub Concatenate_Numbers()
'Taking two variables to fetch the two numbers and to store
Dim num1 As Integer
Dim num2 As Integer
'Fetching the numbers from Excel cells num1 from A2 and num2 from B2
num1 = Range("A2").Value
num2 = Range("B2").Value
'Find the concatenate and store in cell number C2
Range("C2").Value = num1 & num2
End Sub
CONCATENATED
We can use either “+” operator or “&” operator.
Example 1: Let’s concatenate the strings “Geeks”, “for”, “Geeks”.
Repeat Step 1 as discussed in the previous section to create a new VBA module of name “Concatenate_Strings”
Now write either of the following codes and run it to concatenate two or more strings.
Sub Concatenate_Strings()
'Taking three variables to fetch three strings and to store
Dim str1 As String
Dim str2 As String
Dim str3 As String
'Fetching the strings from Excel cells
str1 = Range("A2").Value
str2 = Range("B2").Value
str3 = Range("C2").Value
'Find the concatenate and store in cell number D2
Range("D2").Value = str1 + str2 + str3
End Sub
Sub Concatenate_Strings()
'Taking three variables to fetch three strings and to store
Dim str1 As String
Dim str2 As String
Dim str3 As String
'Fetching the strings from Excel cells
str1 = Range("A2").Value
str2 = Range("B2").Value
str3 = Range("C2").Value
'Find the concatenate and store in cell number D2
Range("D2").Value = str1 & str2 & str3
End Sub
CONCATENATED
Example 2: Let’s concatenate three strings and add in different lines and display them in a message box this time.
Create a new module and write the code. The keyword used for adding the string in the next line is vbNewLine.
The code is :
Sub Concatenate_DifferentLines()
'Taking three variables to store
Dim str1 As String
Dim str2 As String
Dim str3 As String
'Initialize the strings
str1 = "The best platform to learn any programming is"
str2 = "none other than GeeksforGeeks"
str3 = "Join today for best contents"
'Display the concatenated result in a message box
MsgBox (str1 & vbNewLine & str2 & vbNewLine & str3)
End Sub
Example 3: Let’s concatenate two strings with space in between by taking an example of the full name of a person which contains First Name and Last Name.
Create a new module Concatenate_Strings_Space and write the following code :
Sub Concatenate_Strings_Space()
'Taking two variables to fetch two strings and to store
Dim fname As String
Dim lname As String
'Fetching the strings from Excel cells
fname = Range("A2").Value
lname = Range("B2").Value
'Find the concatenate and store in cell number C2
Range("C2").Value = fname & " " & lname
End Sub
Picked
Excel
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Delete Blank Columns in Excel?
How to Normalize Data in Excel?
How to Get Length of Array in Excel VBA?
How to Find the Last Used Row and Column in Excel VBA?
How to Use Solver in Excel?
How to make a 3 Axis Graph using Excel?
Introduction to Excel Spreadsheet
Macros in Excel
How to Show Percentages in Stacked Column Chart in Excel?
How to Create a Macro in Excel? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Jul, 2021"
},
{
"code": null,
"e": 406,
"s": 28,
"text": "VBA in Excel stands for Visual Basic for Applications which is Microsoft’s programming language. To optimize the performance and reduce the time in Excel we need Macros and VBA is the tool used in the backend. Concatenation means to join two or more data into a single data. There are various ways we can perform concatenation in Excel using built-in functions, operators, etc."
},
{
"code": null,
"e": 489,
"s": 406,
"text": "Some helpful links to get more insights about concatenate and using VBA in Excel :"
},
{
"code": null,
"e": 563,
"s": 489,
"text": "Record Macros in ExcelCONCATENATE in ExcelHow to Create a Macro in Excel?"
},
{
"code": null,
"e": 586,
"s": 563,
"text": "Record Macros in Excel"
},
{
"code": null,
"e": 607,
"s": 586,
"text": "CONCATENATE in Excel"
},
{
"code": null,
"e": 639,
"s": 607,
"text": "How to Create a Macro in Excel?"
},
{
"code": null,
"e": 766,
"s": 639,
"text": "In this article, we are going to see about concatenate operators and how to use VBA to concatenate strings as well as numbers."
},
{
"code": null,
"e": 873,
"s": 766,
"text": "In the Microsoft Excel tabs, select the Developer Tab. Initially, the Developer Tab may not be available. "
},
{
"code": null,
"e": 937,
"s": 873,
"text": "The Developer Tab can be enabled easily by a two-step process :"
},
{
"code": null,
"e": 1009,
"s": 937,
"text": "Right-click on any of the existing tabs at the top of the Excel window."
},
{
"code": null,
"e": 1065,
"s": 1009,
"text": "Now select Customize the Ribbon from the pop-down menu."
},
{
"code": null,
"e": 1145,
"s": 1065,
"text": "In the Excel Options Box, check the box Developer to enable it and click on OK."
},
{
"code": null,
"e": 1180,
"s": 1145,
"text": "Now, the Developer Tab is visible."
},
{
"code": null,
"e": 1247,
"s": 1180,
"text": "Now, we need to open the Visual Basic Editor. There are two ways :"
},
{
"code": null,
"e": 1307,
"s": 1247,
"text": "Go to Developer and directly click on the Visual Basic tab."
},
{
"code": null,
"e": 1433,
"s": 1307,
"text": "Go to the Insert tab and then click on the Command button. Drag and insert the command button in any cell of the Excel sheet."
},
{
"code": null,
"e": 1747,
"s": 1433,
"text": "Now, double-click on this command button. This will open the Visual Basic Application Editor tab, and we can write the code. The benefit of this command button is that just by clicking on the button we can see the result of concatenation, and also we don’t need to make any extra Macro in Excel to write the code."
},
{
"code": null,
"e": 1845,
"s": 1747,
"text": "Another way is by right-clicking on the command button and then select View Code as shown below :"
},
{
"code": null,
"e": 2011,
"s": 1845,
"text": "To concatenate operator mostly used in Excel is “&” for numbers as well as strings. But for strings, we can also use “+” operator to concatenate two or more strings."
},
{
"code": null,
"e": 2056,
"s": 2011,
"text": "The syntax to concatenate using formula is :"
},
{
"code": null,
"e": 2383,
"s": 2056,
"text": "cell_number1 & cell_number2 ; without space in between\n\ncell_number1 & \" \" & cell_number2; with space in between\n\ncell_number1 & \"Any_Symbol\" & cell_number2 ; with any symbol in between\n\ncell_number(s) & \"string text\" ; concatenate cell values and strings\n\n\"string_text\" & cell_number(s) ; concatenate cell values and strings"
},
{
"code": null,
"e": 2462,
"s": 2383,
"text": "Example 1: Take any two numbers as input and concatenate into a single number."
},
{
"code": null,
"e": 2512,
"s": 2462,
"text": "The code to concatenate two numbers in Excel is :"
},
{
"code": null,
"e": 2827,
"s": 2512,
"text": "Private Sub CommandButton1_Click()\n'Inserting the number num1 and num2 \nDim num1 As Integer: num1 = 10\nDim num2 As Integer: num2 = 50\n'Declare a variable c to concatenate num1 and num2\nDim c As Integer\n'Concatenate the numbers\nc = num1 & num2\nMsgBox (\"The result after concatenating two numbers are: \" & c)\nEnd Sub"
},
{
"code": null,
"e": 2902,
"s": 2827,
"text": "Run the above code in VBA and the output will be shown in the message box."
},
{
"code": null,
"e": 2911,
"s": 2902,
"text": "Output :"
},
{
"code": null,
"e": 2964,
"s": 2911,
"text": "The result after concatenating two numbers are: 1050"
},
{
"code": null,
"e": 3046,
"s": 2964,
"text": "You can also click on the command button and the same message will be displayed. "
},
{
"code": null,
"e": 3220,
"s": 3046,
"text": "Example 2: Say, now we take two numbers from the cells of the Excel Sheet and store the result back in the Excel sheet. This time we are not going to use the command button."
},
{
"code": null,
"e": 3271,
"s": 3220,
"text": "Step 1: Open the VB editor from the Developer Tab."
},
{
"code": null,
"e": 3317,
"s": 3271,
"text": "Developer -> Visual Basic -> Tools -> Macros"
},
{
"code": null,
"e": 3407,
"s": 3317,
"text": "Step 2: The editor is now ready where we can write the code and syntax for concatenation."
},
{
"code": null,
"e": 3448,
"s": 3407,
"text": "Now write the following code and run it."
},
{
"code": null,
"e": 3783,
"s": 3448,
"text": "Sub Concatenate_Numbers()\n'Taking two variables to fetch the two numbers and to store\nDim num1 As Integer\nDim num2 As Integer\n'Fetching the numbers from Excel cells num1 from A2 and num2 from B2\nnum1 = Range(\"A2\").Value\nnum2 = Range(\"B2\").Value\n'Find the concatenate and store in cell number C2\nRange(\"C2\").Value = num1 & num2\nEnd Sub"
},
{
"code": null,
"e": 3796,
"s": 3783,
"text": "CONCATENATED"
},
{
"code": null,
"e": 3844,
"s": 3796,
"text": "We can use either “+” operator or “&” operator."
},
{
"code": null,
"e": 3910,
"s": 3844,
"text": "Example 1: Let’s concatenate the strings “Geeks”, “for”, “Geeks”."
},
{
"code": null,
"e": 4018,
"s": 3910,
"text": "Repeat Step 1 as discussed in the previous section to create a new VBA module of name “Concatenate_Strings”"
},
{
"code": null,
"e": 4105,
"s": 4018,
"text": "Now write either of the following codes and run it to concatenate two or more strings."
},
{
"code": null,
"e": 4459,
"s": 4105,
"text": "Sub Concatenate_Strings()\n'Taking three variables to fetch three strings and to store\nDim str1 As String\nDim str2 As String\nDim str3 As String\n'Fetching the strings from Excel cells\nstr1 = Range(\"A2\").Value\nstr2 = Range(\"B2\").Value\nstr3 = Range(\"C2\").Value\n'Find the concatenate and store in cell number D2\nRange(\"D2\").Value = str1 + str2 + str3\nEnd Sub"
},
{
"code": null,
"e": 4813,
"s": 4459,
"text": "Sub Concatenate_Strings()\n'Taking three variables to fetch three strings and to store\nDim str1 As String\nDim str2 As String\nDim str3 As String\n'Fetching the strings from Excel cells\nstr1 = Range(\"A2\").Value\nstr2 = Range(\"B2\").Value\nstr3 = Range(\"C2\").Value\n'Find the concatenate and store in cell number D2\nRange(\"D2\").Value = str1 & str2 & str3\nEnd Sub"
},
{
"code": null,
"e": 4826,
"s": 4813,
"text": "CONCATENATED"
},
{
"code": null,
"e": 4941,
"s": 4826,
"text": "Example 2: Let’s concatenate three strings and add in different lines and display them in a message box this time."
},
{
"code": null,
"e": 5052,
"s": 4941,
"text": "Create a new module and write the code. The keyword used for adding the string in the next line is vbNewLine. "
},
{
"code": null,
"e": 5066,
"s": 5052,
"text": "The code is :"
},
{
"code": null,
"e": 5455,
"s": 5066,
"text": "Sub Concatenate_DifferentLines()\n'Taking three variables to store\nDim str1 As String\nDim str2 As String\nDim str3 As String\n'Initialize the strings\nstr1 = \"The best platform to learn any programming is\"\nstr2 = \"none other than GeeksforGeeks\"\nstr3 = \"Join today for best contents\"\n'Display the concatenated result in a message box\nMsgBox (str1 & vbNewLine & str2 & vbNewLine & str3)\nEnd Sub"
},
{
"code": null,
"e": 5609,
"s": 5455,
"text": "Example 3: Let’s concatenate two strings with space in between by taking an example of the full name of a person which contains First Name and Last Name."
},
{
"code": null,
"e": 5686,
"s": 5609,
"text": "Create a new module Concatenate_Strings_Space and write the following code :"
},
{
"code": null,
"e": 6003,
"s": 5686,
"text": "Sub Concatenate_Strings_Space()\n'Taking two variables to fetch two strings and to store\nDim fname As String\nDim lname As String\n'Fetching the strings from Excel cells\nfname = Range(\"A2\").Value\nlname = Range(\"B2\").Value\n'Find the concatenate and store in cell number C2\nRange(\"C2\").Value = fname & \" \" & lname\nEnd Sub"
},
{
"code": null,
"e": 6010,
"s": 6003,
"text": "Picked"
},
{
"code": null,
"e": 6016,
"s": 6010,
"text": "Excel"
},
{
"code": null,
"e": 6114,
"s": 6016,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6152,
"s": 6114,
"text": "How to Delete Blank Columns in Excel?"
},
{
"code": null,
"e": 6184,
"s": 6152,
"text": "How to Normalize Data in Excel?"
},
{
"code": null,
"e": 6225,
"s": 6184,
"text": "How to Get Length of Array in Excel VBA?"
},
{
"code": null,
"e": 6280,
"s": 6225,
"text": "How to Find the Last Used Row and Column in Excel VBA?"
},
{
"code": null,
"e": 6308,
"s": 6280,
"text": "How to Use Solver in Excel?"
},
{
"code": null,
"e": 6348,
"s": 6308,
"text": "How to make a 3 Axis Graph using Excel?"
},
{
"code": null,
"e": 6382,
"s": 6348,
"text": "Introduction to Excel Spreadsheet"
},
{
"code": null,
"e": 6398,
"s": 6382,
"text": "Macros in Excel"
},
{
"code": null,
"e": 6456,
"s": 6398,
"text": "How to Show Percentages in Stacked Column Chart in Excel?"
}
] |
How to Install Code Blocks for C++ on MacOS? | 29 Oct, 2021
Code::Blocks is a free and open-source IDE that supports a plethora of C++ compilers like GCC, Clang, and Visual C++. It is written in C++ and makes use of wxWidgets as the GUI toolkit. Code::Blocks is focused on C, C++, and Fortran development. It has a custom build system and optional Make support. In this article, we will discuss methods using which we can install Code Blocks on MacOS.:
Cross-Platform: Works on MacOS, Linux and Windows.
Multiple C++ Compilers: It supports GCC, MinGW, Digital Mars, Microsoft Visual C++, Borland C++, LLVM Clang, Watcom, LCC, and the Intel C++ compiler.
On MacOS, Code::Blocks relies on the Xcode distribution for its compiler. So, first, install Xcode from App Store and then continue with the following steps :
Step 1: Go to the official SourceForge of CodeBlocks project using this link, to download the application package. Click on the Download button.
Code::Blocks on SourceForge.com
Step 2: Open the downloaded file to initiate installation.
Package extraction begins.
Step 3: Drag the CodeBlocks icon to the application folder to begin copying Codeblocks to the application folder.
Step 5: Open the Code::Blocks app. The following prompt is displayed.
Step 5: Go to System Preferences -> Security and Privacy. Click the padlock in the lower-left corner of the dialog box, and then enter your system password when prompted, to allow changes.
Step 6: Select the option Allow Applications Downloaded from: App Store and identified developers. Close the Prompt appeared in Step 5.
Click on the Open Anyway button in the Security & Privacy dialog box.
Step 7: Another Dialog box appears. On this dialog box, click on Open to start Code::Blocks.
Step 8: Go to File -> New -> Project. On the New from template dialog, select Console Application and click Go.
Step 9: Select the C++ option and click Next. Keep clicking Next and then click Finish to create your first C++ project.
Step 9: On the menu bar, go to Settings -> Environment. Change the text in the field “Terminal to launch console programs” to:
osascript -e 'tell app "Terminal"' -e 'activate' -e 'do script "$SCRIPT"' -e 'end tell'
Step 10: Open the main.cpp file from the left project pane. It contains Hello World program by default. Go to Build-> Build and Run. The program should run successfully on a terminal.
how-to-install
Picked
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Set Git Username and Password in GitBash?
How to Install and Use NVM on Windows?
How to Install Jupyter Notebook on MacOS?
How to Permanently Disable Swap in Linux?
How to Import JSON Data into SQL Server?
Installation of Node.js on Linux
Installation of Node.js on Windows
How to Install Jupyter Notebook on MacOS?
How to Install and Use NVM on Windows?
How to Add External JAR File to an IntelliJ IDEA Project? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Oct, 2021"
},
{
"code": null,
"e": 421,
"s": 28,
"text": "Code::Blocks is a free and open-source IDE that supports a plethora of C++ compilers like GCC, Clang, and Visual C++. It is written in C++ and makes use of wxWidgets as the GUI toolkit. Code::Blocks is focused on C, C++, and Fortran development. It has a custom build system and optional Make support. In this article, we will discuss methods using which we can install Code Blocks on MacOS.:"
},
{
"code": null,
"e": 472,
"s": 421,
"text": "Cross-Platform: Works on MacOS, Linux and Windows."
},
{
"code": null,
"e": 623,
"s": 472,
"text": "Multiple C++ Compilers: It supports GCC, MinGW, Digital Mars, Microsoft Visual C++, Borland C++, LLVM Clang, Watcom, LCC, and the Intel C++ compiler. "
},
{
"code": null,
"e": 782,
"s": 623,
"text": "On MacOS, Code::Blocks relies on the Xcode distribution for its compiler. So, first, install Xcode from App Store and then continue with the following steps :"
},
{
"code": null,
"e": 927,
"s": 782,
"text": "Step 1: Go to the official SourceForge of CodeBlocks project using this link, to download the application package. Click on the Download button."
},
{
"code": null,
"e": 959,
"s": 927,
"text": "Code::Blocks on SourceForge.com"
},
{
"code": null,
"e": 1018,
"s": 959,
"text": "Step 2: Open the downloaded file to initiate installation."
},
{
"code": null,
"e": 1045,
"s": 1018,
"text": "Package extraction begins."
},
{
"code": null,
"e": 1159,
"s": 1045,
"text": "Step 3: Drag the CodeBlocks icon to the application folder to begin copying Codeblocks to the application folder."
},
{
"code": null,
"e": 1229,
"s": 1159,
"text": "Step 5: Open the Code::Blocks app. The following prompt is displayed."
},
{
"code": null,
"e": 1418,
"s": 1229,
"text": "Step 5: Go to System Preferences -> Security and Privacy. Click the padlock in the lower-left corner of the dialog box, and then enter your system password when prompted, to allow changes."
},
{
"code": null,
"e": 1554,
"s": 1418,
"text": "Step 6: Select the option Allow Applications Downloaded from: App Store and identified developers. Close the Prompt appeared in Step 5."
},
{
"code": null,
"e": 1625,
"s": 1554,
"text": "Click on the Open Anyway button in the Security & Privacy dialog box. "
},
{
"code": null,
"e": 1718,
"s": 1625,
"text": "Step 7: Another Dialog box appears. On this dialog box, click on Open to start Code::Blocks."
},
{
"code": null,
"e": 1830,
"s": 1718,
"text": "Step 8: Go to File -> New -> Project. On the New from template dialog, select Console Application and click Go."
},
{
"code": null,
"e": 1951,
"s": 1830,
"text": "Step 9: Select the C++ option and click Next. Keep clicking Next and then click Finish to create your first C++ project."
},
{
"code": null,
"e": 2078,
"s": 1951,
"text": "Step 9: On the menu bar, go to Settings -> Environment. Change the text in the field “Terminal to launch console programs” to:"
},
{
"code": null,
"e": 2166,
"s": 2078,
"text": "osascript -e 'tell app \"Terminal\"' -e 'activate' -e 'do script \"$SCRIPT\"' -e 'end tell'"
},
{
"code": null,
"e": 2350,
"s": 2166,
"text": "Step 10: Open the main.cpp file from the left project pane. It contains Hello World program by default. Go to Build-> Build and Run. The program should run successfully on a terminal."
},
{
"code": null,
"e": 2365,
"s": 2350,
"text": "how-to-install"
},
{
"code": null,
"e": 2372,
"s": 2365,
"text": "Picked"
},
{
"code": null,
"e": 2379,
"s": 2372,
"text": "How To"
},
{
"code": null,
"e": 2398,
"s": 2379,
"text": "Installation Guide"
},
{
"code": null,
"e": 2496,
"s": 2398,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2545,
"s": 2496,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 2584,
"s": 2545,
"text": "How to Install and Use NVM on Windows?"
},
{
"code": null,
"e": 2626,
"s": 2584,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 2668,
"s": 2626,
"text": "How to Permanently Disable Swap in Linux?"
},
{
"code": null,
"e": 2709,
"s": 2668,
"text": "How to Import JSON Data into SQL Server?"
},
{
"code": null,
"e": 2742,
"s": 2709,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2777,
"s": 2742,
"text": "Installation of Node.js on Windows"
},
{
"code": null,
"e": 2819,
"s": 2777,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 2858,
"s": 2819,
"text": "How to Install and Use NVM on Windows?"
}
] |
Save and load models in Tensorflow | 07 Mar, 2022
The development of the model can be saved both before and after testing. As a result, a model will pick up where it left off to eliminate lengthy training periods. You can still share your model and have others replicate it if you save it. Most machine learning professionals share the following when publishing test models and techniques:
Code to create the model
The trained weights for the model
Sharing this information allows others to better understand how the model operates and to test it with new data.
Aside from that, teaching the machine learning models will take a lot of time and effort. Shutting down the notebook or machine, though, causes all of those weights and more to disappear as the memory is flushed. It’s important to save the models to optimize reusability in order to get the most out of your time.
As soon as we are done evaluating our model, we can move forward with saving it.
Ways we can save and load our machine learning model are as follows:
Using the inbuilt function model.save()
Using the inbuilt function model.save_weights()
Now we can save our model just by calling the save() method and passing in the filepath as the argument. This will save the model’s
Model Architecture
Model Weights
Model optimizer state (To resume from where we left off)
Syntax: tensorflow.keras.X.save(location/model_name)
Here X refers to Sequential, Functional Model, or Model subclass. All of them have the save() method.
The location along with the model name is passed as a parameter in this method. If only the model name is passed then the model is saved in the same location as that of the Python file.
We can load the model which was saved using the load_model() method present in the tensorflow module.
Syntax: tensorflow.keras.models.load_model(location/model_name)
The location along with the model name is passed as a parameter in this method.
NOTE: If we specify “.h5”, the model will be saved in hdf5 format; if no extension is specified, the model will be saved in TensorFlow native format.
Now you can simply save the weights of all the layers using the save_weights() method. It saves the weights of the layers contained in the model. It is advised to use the save() method to save h5 models instead of save_weights() method for saving a model using tensorflow. However, h5 models can also be saved using save_weights() method.
Syntax: tensorflow.keras.Model.save_weights(location/weights_name)
The location along with the weights name is passed as a parameter in this method. If only the weights name is passed then it is saved in the same location as that of the Python file.
Below is a program where we save weights of an initial model:
Python3
# import moduleimport tensorflow # create objectmodel=tensorflow.keras.Model() # assign locationpath='Weights_folder/Weights' # savemodel.save_weights(path)
It will create a new folder called the weights folder and save all the weights as my weights in Tensorflow native format. There will be three folders in all.
checkpoint: It’s a human-readable file with the following text,
model_checkpoint_path: "Weights"
all_model_checkpoint_paths: "Weights"
data-00000-of-00001: This file contains the actual weights from the model.
index: This file tells TensorFlow which weights are stored where.
We can load the model which was saved using the load_weights() method.
Syntax:
tensorflow.keras.Model.load_weights(location/weights_name)
The location along with the weights name is passed as a parameter in this method.
Note: When loading weights for a model, we must first ensure that the model’s design is correct. We can not load the weights of a model(having 2 dense layers) to a sequential model with 1 Dense layer, as both are not congruous.
Below is an example that depicts all the above methods to save and load the model. Here we develop a model and train it using an inbuilt dataset and finally save and load the model again in various ways.
Import the modules.
Python3
# import required modulesimport tensorflow as tfimport numpy as npimport matplotlib.pyplot as pltfrom tensorflow.keras.layers import Input, Conv2D, Dense, Flatten, Dropoutfrom tensorflow.keras.layers import GlobalMaxPooling2D, MaxPooling2Dfrom tensorflow.keras.layers import BatchNormalizationfrom tensorflow.keras.models import Modelfrom tensorflow.keras.models import load_model
Load and split the dataset and then change some attributes of the data.
Python3
# Load in the datacifar10 = tf.keras.datasets.cifar10 # Distribute it to train and test set(x_train, y_train), (x_test, y_test) = cifar10.load_data()print(x_train.shape, y_train.shape, x_test.shape, y_test.shape) # Reduce pixel valuesx_train, x_test = x_train / 255.0, x_test / 255.0 # flatten the label valuesy_train, y_test = y_train.flatten(), y_test.flatten()
Output:
Develop the model by adding layers.
Python3
# number of classesK = len(set(y_train))# calculate total number of classes for output layerprint("number of classes:", K) # Build the model using the functional API# input layeri = Input(shape=x_train[0].shape)x = Conv2D(32, (3, 3), activation='relu', padding='same')(i)x = BatchNormalization()(x)x = Conv2D(32, (3, 3), activation='relu', padding='same')(x)x = BatchNormalization()(x)x = MaxPooling2D((2, 2))(x) x = Conv2D(64, (3, 3), activation='relu', padding='same')(x)x = BatchNormalization()(x)x = Conv2D(64, (3, 3), activation='relu', padding='same')(x)x = BatchNormalization()(x)x = MaxPooling2D((2, 2))(x) x = Conv2D(128, (3, 3), activation='relu', padding='same')(x)x = BatchNormalization()(x)x = Conv2D(128, (3, 3), activation='relu', padding='same')(x)x = BatchNormalization()(x)x = MaxPooling2D((2, 2))(x) x = Flatten()(x)x = Dropout(0.2)(x) # Hidden layerx = Dense(1024, activation='relu')(x)x = Dropout(0.2)(x) # last hidden layer i.e.. output layerx = Dense(K, activation='softmax')(x) model = Model(i, x)model.summary()
Output:
Save the model in h5 format using the save() method.
Python3
# saving and loading the .h5 model # save modelmodel.save('gfgModel.h5')print('Model Saved!') # load modelsavedModel=load_model('gfgModel.h5')savedModel.summary()
Output:
Save the model weights using the save_weights() method.
Python3
# saving and loading the model weights # save modelmodel.save_weights('gfgModelWeights')print('Model Saved!') # load modelsavedModel = model.load_weights('gfgModelWeights')print('Model Loaded!')
Output:
Save the model in h5 format model using the save_weights() method.
Python3
# saving and loading the .h5 model # save modelmodel.save_weights('gfgModelWeights.h5')print('Model Saved!') # load modelsavedModel = model.load_weights('gfgModelWeights.h5')print('Model Loaded!')
Output:
The above model was developed in Google colab. So on saving the models, they are stored temporarily and can be downloaded. Below are the models and weights saved:
sooda367
saurabh1990aror
sagartomar9927
abhishek0719kadiyan
o9d4xe3fblrnk9bolxvgx1rycjjvhks747vuhh6a
Picked
Python-Tensorflow
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Reinforcement learning
Supervised and Unsupervised learning
Decision Tree Introduction with example
Getting started with Machine Learning
Read JSON file using Python
Python map() function
Adding new column to existing DataFrame in Pandas
Python Dictionary
How to get column names in Pandas dataframe | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n07 Mar, 2022"
},
{
"code": null,
"e": 393,
"s": 53,
"text": "The development of the model can be saved both before and after testing. As a result, a model will pick up where it left off to eliminate lengthy training periods. You can still share your model and have others replicate it if you save it. Most machine learning professionals share the following when publishing test models and techniques:"
},
{
"code": null,
"e": 418,
"s": 393,
"text": "Code to create the model"
},
{
"code": null,
"e": 452,
"s": 418,
"text": "The trained weights for the model"
},
{
"code": null,
"e": 565,
"s": 452,
"text": "Sharing this information allows others to better understand how the model operates and to test it with new data."
},
{
"code": null,
"e": 879,
"s": 565,
"text": "Aside from that, teaching the machine learning models will take a lot of time and effort. Shutting down the notebook or machine, though, causes all of those weights and more to disappear as the memory is flushed. It’s important to save the models to optimize reusability in order to get the most out of your time."
},
{
"code": null,
"e": 960,
"s": 879,
"text": "As soon as we are done evaluating our model, we can move forward with saving it."
},
{
"code": null,
"e": 1029,
"s": 960,
"text": "Ways we can save and load our machine learning model are as follows:"
},
{
"code": null,
"e": 1069,
"s": 1029,
"text": "Using the inbuilt function model.save()"
},
{
"code": null,
"e": 1117,
"s": 1069,
"text": "Using the inbuilt function model.save_weights()"
},
{
"code": null,
"e": 1249,
"s": 1117,
"text": "Now we can save our model just by calling the save() method and passing in the filepath as the argument. This will save the model’s"
},
{
"code": null,
"e": 1268,
"s": 1249,
"text": "Model Architecture"
},
{
"code": null,
"e": 1282,
"s": 1268,
"text": "Model Weights"
},
{
"code": null,
"e": 1339,
"s": 1282,
"text": "Model optimizer state (To resume from where we left off)"
},
{
"code": null,
"e": 1392,
"s": 1339,
"text": "Syntax: tensorflow.keras.X.save(location/model_name)"
},
{
"code": null,
"e": 1494,
"s": 1392,
"text": "Here X refers to Sequential, Functional Model, or Model subclass. All of them have the save() method."
},
{
"code": null,
"e": 1680,
"s": 1494,
"text": "The location along with the model name is passed as a parameter in this method. If only the model name is passed then the model is saved in the same location as that of the Python file."
},
{
"code": null,
"e": 1782,
"s": 1680,
"text": "We can load the model which was saved using the load_model() method present in the tensorflow module."
},
{
"code": null,
"e": 1846,
"s": 1782,
"text": "Syntax: tensorflow.keras.models.load_model(location/model_name)"
},
{
"code": null,
"e": 1926,
"s": 1846,
"text": "The location along with the model name is passed as a parameter in this method."
},
{
"code": null,
"e": 2076,
"s": 1926,
"text": "NOTE: If we specify “.h5”, the model will be saved in hdf5 format; if no extension is specified, the model will be saved in TensorFlow native format."
},
{
"code": null,
"e": 2415,
"s": 2076,
"text": "Now you can simply save the weights of all the layers using the save_weights() method. It saves the weights of the layers contained in the model. It is advised to use the save() method to save h5 models instead of save_weights() method for saving a model using tensorflow. However, h5 models can also be saved using save_weights() method."
},
{
"code": null,
"e": 2482,
"s": 2415,
"text": "Syntax: tensorflow.keras.Model.save_weights(location/weights_name)"
},
{
"code": null,
"e": 2665,
"s": 2482,
"text": "The location along with the weights name is passed as a parameter in this method. If only the weights name is passed then it is saved in the same location as that of the Python file."
},
{
"code": null,
"e": 2727,
"s": 2665,
"text": "Below is a program where we save weights of an initial model:"
},
{
"code": null,
"e": 2735,
"s": 2727,
"text": "Python3"
},
{
"code": "# import moduleimport tensorflow # create objectmodel=tensorflow.keras.Model() # assign locationpath='Weights_folder/Weights' # savemodel.save_weights(path)",
"e": 2892,
"s": 2735,
"text": null
},
{
"code": null,
"e": 3050,
"s": 2892,
"text": "It will create a new folder called the weights folder and save all the weights as my weights in Tensorflow native format. There will be three folders in all."
},
{
"code": null,
"e": 3114,
"s": 3050,
"text": "checkpoint: It’s a human-readable file with the following text,"
},
{
"code": null,
"e": 3185,
"s": 3114,
"text": "model_checkpoint_path: \"Weights\"\nall_model_checkpoint_paths: \"Weights\""
},
{
"code": null,
"e": 3260,
"s": 3185,
"text": "data-00000-of-00001: This file contains the actual weights from the model."
},
{
"code": null,
"e": 3326,
"s": 3260,
"text": "index: This file tells TensorFlow which weights are stored where."
},
{
"code": null,
"e": 3397,
"s": 3326,
"text": "We can load the model which was saved using the load_weights() method."
},
{
"code": null,
"e": 3405,
"s": 3397,
"text": "Syntax:"
},
{
"code": null,
"e": 3464,
"s": 3405,
"text": "tensorflow.keras.Model.load_weights(location/weights_name)"
},
{
"code": null,
"e": 3546,
"s": 3464,
"text": "The location along with the weights name is passed as a parameter in this method."
},
{
"code": null,
"e": 3774,
"s": 3546,
"text": "Note: When loading weights for a model, we must first ensure that the model’s design is correct. We can not load the weights of a model(having 2 dense layers) to a sequential model with 1 Dense layer, as both are not congruous."
},
{
"code": null,
"e": 3978,
"s": 3774,
"text": "Below is an example that depicts all the above methods to save and load the model. Here we develop a model and train it using an inbuilt dataset and finally save and load the model again in various ways."
},
{
"code": null,
"e": 3998,
"s": 3978,
"text": "Import the modules."
},
{
"code": null,
"e": 4006,
"s": 3998,
"text": "Python3"
},
{
"code": "# import required modulesimport tensorflow as tfimport numpy as npimport matplotlib.pyplot as pltfrom tensorflow.keras.layers import Input, Conv2D, Dense, Flatten, Dropoutfrom tensorflow.keras.layers import GlobalMaxPooling2D, MaxPooling2Dfrom tensorflow.keras.layers import BatchNormalizationfrom tensorflow.keras.models import Modelfrom tensorflow.keras.models import load_model",
"e": 4387,
"s": 4006,
"text": null
},
{
"code": null,
"e": 4460,
"s": 4387,
"text": "Load and split the dataset and then change some attributes of the data. "
},
{
"code": null,
"e": 4468,
"s": 4460,
"text": "Python3"
},
{
"code": "# Load in the datacifar10 = tf.keras.datasets.cifar10 # Distribute it to train and test set(x_train, y_train), (x_test, y_test) = cifar10.load_data()print(x_train.shape, y_train.shape, x_test.shape, y_test.shape) # Reduce pixel valuesx_train, x_test = x_train / 255.0, x_test / 255.0 # flatten the label valuesy_train, y_test = y_train.flatten(), y_test.flatten()",
"e": 4832,
"s": 4468,
"text": null
},
{
"code": null,
"e": 4840,
"s": 4832,
"text": "Output:"
},
{
"code": null,
"e": 4876,
"s": 4840,
"text": "Develop the model by adding layers."
},
{
"code": null,
"e": 4884,
"s": 4876,
"text": "Python3"
},
{
"code": "# number of classesK = len(set(y_train))# calculate total number of classes for output layerprint(\"number of classes:\", K) # Build the model using the functional API# input layeri = Input(shape=x_train[0].shape)x = Conv2D(32, (3, 3), activation='relu', padding='same')(i)x = BatchNormalization()(x)x = Conv2D(32, (3, 3), activation='relu', padding='same')(x)x = BatchNormalization()(x)x = MaxPooling2D((2, 2))(x) x = Conv2D(64, (3, 3), activation='relu', padding='same')(x)x = BatchNormalization()(x)x = Conv2D(64, (3, 3), activation='relu', padding='same')(x)x = BatchNormalization()(x)x = MaxPooling2D((2, 2))(x) x = Conv2D(128, (3, 3), activation='relu', padding='same')(x)x = BatchNormalization()(x)x = Conv2D(128, (3, 3), activation='relu', padding='same')(x)x = BatchNormalization()(x)x = MaxPooling2D((2, 2))(x) x = Flatten()(x)x = Dropout(0.2)(x) # Hidden layerx = Dense(1024, activation='relu')(x)x = Dropout(0.2)(x) # last hidden layer i.e.. output layerx = Dense(K, activation='softmax')(x) model = Model(i, x)model.summary()",
"e": 5921,
"s": 4884,
"text": null
},
{
"code": null,
"e": 5929,
"s": 5921,
"text": "Output:"
},
{
"code": null,
"e": 5982,
"s": 5929,
"text": "Save the model in h5 format using the save() method."
},
{
"code": null,
"e": 5990,
"s": 5982,
"text": "Python3"
},
{
"code": "# saving and loading the .h5 model # save modelmodel.save('gfgModel.h5')print('Model Saved!') # load modelsavedModel=load_model('gfgModel.h5')savedModel.summary()",
"e": 6153,
"s": 5990,
"text": null
},
{
"code": null,
"e": 6163,
"s": 6153,
"text": " Output: "
},
{
"code": null,
"e": 6221,
"s": 6163,
"text": " Save the model weights using the save_weights() method. "
},
{
"code": null,
"e": 6229,
"s": 6221,
"text": "Python3"
},
{
"code": "# saving and loading the model weights # save modelmodel.save_weights('gfgModelWeights')print('Model Saved!') # load modelsavedModel = model.load_weights('gfgModelWeights')print('Model Loaded!')",
"e": 6424,
"s": 6229,
"text": null
},
{
"code": null,
"e": 6432,
"s": 6424,
"text": "Output:"
},
{
"code": null,
"e": 6499,
"s": 6432,
"text": "Save the model in h5 format model using the save_weights() method."
},
{
"code": null,
"e": 6507,
"s": 6499,
"text": "Python3"
},
{
"code": "# saving and loading the .h5 model # save modelmodel.save_weights('gfgModelWeights.h5')print('Model Saved!') # load modelsavedModel = model.load_weights('gfgModelWeights.h5')print('Model Loaded!')",
"e": 6704,
"s": 6507,
"text": null
},
{
"code": null,
"e": 6712,
"s": 6704,
"text": "Output:"
},
{
"code": null,
"e": 6875,
"s": 6712,
"text": "The above model was developed in Google colab. So on saving the models, they are stored temporarily and can be downloaded. Below are the models and weights saved:"
},
{
"code": null,
"e": 6884,
"s": 6875,
"text": "sooda367"
},
{
"code": null,
"e": 6900,
"s": 6884,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 6915,
"s": 6900,
"text": "sagartomar9927"
},
{
"code": null,
"e": 6935,
"s": 6915,
"text": "abhishek0719kadiyan"
},
{
"code": null,
"e": 6976,
"s": 6935,
"text": "o9d4xe3fblrnk9bolxvgx1rycjjvhks747vuhh6a"
},
{
"code": null,
"e": 6983,
"s": 6976,
"text": "Picked"
},
{
"code": null,
"e": 7001,
"s": 6983,
"text": "Python-Tensorflow"
},
{
"code": null,
"e": 7018,
"s": 7001,
"text": "Machine Learning"
},
{
"code": null,
"e": 7025,
"s": 7018,
"text": "Python"
},
{
"code": null,
"e": 7042,
"s": 7025,
"text": "Machine Learning"
},
{
"code": null,
"e": 7140,
"s": 7042,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7163,
"s": 7140,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 7186,
"s": 7163,
"text": "Reinforcement learning"
},
{
"code": null,
"e": 7223,
"s": 7186,
"text": "Supervised and Unsupervised learning"
},
{
"code": null,
"e": 7263,
"s": 7223,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 7301,
"s": 7263,
"text": "Getting started with Machine Learning"
},
{
"code": null,
"e": 7329,
"s": 7301,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 7351,
"s": 7329,
"text": "Python map() function"
},
{
"code": null,
"e": 7401,
"s": 7351,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 7419,
"s": 7401,
"text": "Python Dictionary"
}
] |
Tailwind CSS Display | 23 Mar, 2022
This class accepts more than one value in tailwind CSS. All the properties are covered as in class form. It is the alternative to the CSS display property. This class is used to define how the components (div, hyperlink, heading, etc) are going to be placed on the web page. As the name suggests, this property is used to define the display of the different parts of a web page.
Display Classes:
block: It is used to display an element as a block element.
inline-block: It is used to display an element as an inline-level block container.
inline: It is used to display an element as an inline element.
flex: It is used to display an element as a block-level flex container.
inline-flex: It is used to display an element as an inline-level flex container.
table: It is used to set the behavior as <table> for all elements.
table-caption: It is used to set the behavior as <caption> for all elements.
table-cell: It is used to set the behavior as <td> for all elements.
table-column: It is used to set the behavior as <col> for all elements.
table-column-group: It is used to set the behavior as <column> for all elements.
table-footer-group: It is used to set the behavior as <footer> for all elements.
table-header-group: It is used to set the behavior as <header> for all elements.
table-row-group: It is used to set the behavior as <row> for all elements.
table-row: It is used to set the behavior as <tr> for all elements.
flow-root: It is used to set the default value.
grid: It is used to display an element as a block-level grid container.
inline-grid: It is used to display an element as an inline-level grid container.
contents: It is used to disappear the container.
hidden: It is used to remove the element.
block: It is used to display an element as a block-level element. This class is used as the default property of div. This class places the div one after another vertically. The height and width of the div can be changed using the block class if the width is not mentioned, then the div under block class will take up the width of the container.
Syntax:
<element display="block">...</element>
Example 1:
HTML
<!DOCTYPE html> <head> <link href= "https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center"> <center> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS block Class</b> <div class="bg-green-200 p-4 mx-16 space-y-4"> <span class="block h-12 bg-green-500 rounded-lg">1</span> <span class="block h-12 bg-green-500 rounded-lg">2</span> <span class="block h-12 bg-green-500 rounded-lg">3</span> </div> </center></body> </html>
Output:
inline-block: It is used to display an element as an inline-level block container. This feature uses both properties mentioned above, block and inline. So, this class aligns the div inline but the difference is it can edit the height and the width of the block. Basically, this will align the div both in the block and inline fashion.
Syntax:
<element display="inline-block">...</element>
Example 2:
HTML
<!DOCTYPE html> <head> <link href= "https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center"> <center> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS inline-block Class</b> <div class="bg-green-200 p-4 mx-16 space-y-4"> <span class="inline-block w-32 h-12 bg-green-500 rounded-lg">1</span> <span class="inline-block w-32 h-12 bg-green-500 rounded-lg">2</span> <span class="inline-block w-32 h-12 bg-green-500 rounded-lg">3</span> </div> </center></body> </html>
Output:
inline: It is used to display an element as an inline element. This class is the default property of anchor tags. This is used to place the div inline i.e. in a horizontal manner. The inline display property ignores the height and the width set by the user.
Syntax:
<element display="inline">...</element>
Example 3:
HTML
<!DOCTYPE html> <head> <link href= "https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center"> <center> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS inline Class</b> <div class="bg-green-200 p-4 mx-16 space-y-4"> <span class="inline bg-green-500 rounded-lg">1</span> <span class="inline bg-green-500 rounded-lg">2</span> <span class="inline bg-green-500 rounded-lg">3</span> </div> </center></body> </html>
Output:
flex: The flex class is much responsive and mobile-friendly. It is easy to position child elements and the main container. The margin doesn’t collapse with the content margins. The order of any element can be easily changed without editing the HTML section.
Syntax:
<element display="flex">...</element>
Example 4:
HTML
<!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center"> <center> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS flex Class</b> <div class="flex bg-green-200 p-4 mx-16 "> <div class="flex-1 bg-green-500 rounded-lg">1</div> <div class="flex-1 bg-green-500 rounded-lg">2</div> <div class="flex-1 bg-green-500 rounded-lg">3</div> </div> </center></body> </html>
Output:
Tailwind CSS
Tailwind-Layout
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
REST API (Introduction)
Node.js fs.readFileSync() Method
How to set the default value for an HTML <select> element ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Mar, 2022"
},
{
"code": null,
"e": 407,
"s": 28,
"text": "This class accepts more than one value in tailwind CSS. All the properties are covered as in class form. It is the alternative to the CSS display property. This class is used to define how the components (div, hyperlink, heading, etc) are going to be placed on the web page. As the name suggests, this property is used to define the display of the different parts of a web page."
},
{
"code": null,
"e": 424,
"s": 407,
"text": "Display Classes:"
},
{
"code": null,
"e": 484,
"s": 424,
"text": "block: It is used to display an element as a block element."
},
{
"code": null,
"e": 567,
"s": 484,
"text": "inline-block: It is used to display an element as an inline-level block container."
},
{
"code": null,
"e": 630,
"s": 567,
"text": "inline: It is used to display an element as an inline element."
},
{
"code": null,
"e": 702,
"s": 630,
"text": "flex: It is used to display an element as a block-level flex container."
},
{
"code": null,
"e": 783,
"s": 702,
"text": "inline-flex: It is used to display an element as an inline-level flex container."
},
{
"code": null,
"e": 850,
"s": 783,
"text": "table: It is used to set the behavior as <table> for all elements."
},
{
"code": null,
"e": 928,
"s": 850,
"text": "table-caption: It is used to set the behavior as <caption> for all elements."
},
{
"code": null,
"e": 997,
"s": 928,
"text": "table-cell: It is used to set the behavior as <td> for all elements."
},
{
"code": null,
"e": 1069,
"s": 997,
"text": "table-column: It is used to set the behavior as <col> for all elements."
},
{
"code": null,
"e": 1150,
"s": 1069,
"text": "table-column-group: It is used to set the behavior as <column> for all elements."
},
{
"code": null,
"e": 1231,
"s": 1150,
"text": "table-footer-group: It is used to set the behavior as <footer> for all elements."
},
{
"code": null,
"e": 1312,
"s": 1231,
"text": "table-header-group: It is used to set the behavior as <header> for all elements."
},
{
"code": null,
"e": 1387,
"s": 1312,
"text": "table-row-group: It is used to set the behavior as <row> for all elements."
},
{
"code": null,
"e": 1455,
"s": 1387,
"text": "table-row: It is used to set the behavior as <tr> for all elements."
},
{
"code": null,
"e": 1503,
"s": 1455,
"text": "flow-root: It is used to set the default value."
},
{
"code": null,
"e": 1575,
"s": 1503,
"text": "grid: It is used to display an element as a block-level grid container."
},
{
"code": null,
"e": 1656,
"s": 1575,
"text": "inline-grid: It is used to display an element as an inline-level grid container."
},
{
"code": null,
"e": 1705,
"s": 1656,
"text": "contents: It is used to disappear the container."
},
{
"code": null,
"e": 1747,
"s": 1705,
"text": "hidden: It is used to remove the element."
},
{
"code": null,
"e": 2092,
"s": 1747,
"text": "block: It is used to display an element as a block-level element. This class is used as the default property of div. This class places the div one after another vertically. The height and width of the div can be changed using the block class if the width is not mentioned, then the div under block class will take up the width of the container."
},
{
"code": null,
"e": 2100,
"s": 2092,
"text": "Syntax:"
},
{
"code": null,
"e": 2139,
"s": 2100,
"text": "<element display=\"block\">...</element>"
},
{
"code": null,
"e": 2150,
"s": 2139,
"text": "Example 1:"
},
{
"code": null,
"e": 2155,
"s": 2150,
"text": "HTML"
},
{
"code": "<!DOCTYPE html> <head> <link href= \"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center\"> <center> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS block Class</b> <div class=\"bg-green-200 p-4 mx-16 space-y-4\"> <span class=\"block h-12 bg-green-500 rounded-lg\">1</span> <span class=\"block h-12 bg-green-500 rounded-lg\">2</span> <span class=\"block h-12 bg-green-500 rounded-lg\">3</span> </div> </center></body> </html>",
"e": 2728,
"s": 2155,
"text": null
},
{
"code": null,
"e": 2736,
"s": 2728,
"text": "Output:"
},
{
"code": null,
"e": 3071,
"s": 2736,
"text": "inline-block: It is used to display an element as an inline-level block container. This feature uses both properties mentioned above, block and inline. So, this class aligns the div inline but the difference is it can edit the height and the width of the block. Basically, this will align the div both in the block and inline fashion."
},
{
"code": null,
"e": 3079,
"s": 3071,
"text": "Syntax:"
},
{
"code": null,
"e": 3125,
"s": 3079,
"text": "<element display=\"inline-block\">...</element>"
},
{
"code": null,
"e": 3137,
"s": 3125,
"text": "Example 2: "
},
{
"code": null,
"e": 3142,
"s": 3137,
"text": "HTML"
},
{
"code": "<!DOCTYPE html> <head> <link href= \"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center\"> <center> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS inline-block Class</b> <div class=\"bg-green-200 p-4 mx-16 space-y-4\"> <span class=\"inline-block w-32 h-12 bg-green-500 rounded-lg\">1</span> <span class=\"inline-block w-32 h-12 bg-green-500 rounded-lg\">2</span> <span class=\"inline-block w-32 h-12 bg-green-500 rounded-lg\">3</span> </div> </center></body> </html>",
"e": 3758,
"s": 3142,
"text": null
},
{
"code": null,
"e": 3766,
"s": 3758,
"text": "Output:"
},
{
"code": null,
"e": 4024,
"s": 3766,
"text": "inline: It is used to display an element as an inline element. This class is the default property of anchor tags. This is used to place the div inline i.e. in a horizontal manner. The inline display property ignores the height and the width set by the user."
},
{
"code": null,
"e": 4032,
"s": 4024,
"text": "Syntax:"
},
{
"code": null,
"e": 4072,
"s": 4032,
"text": "<element display=\"inline\">...</element>"
},
{
"code": null,
"e": 4083,
"s": 4072,
"text": "Example 3:"
},
{
"code": null,
"e": 4088,
"s": 4083,
"text": "HTML"
},
{
"code": "<!DOCTYPE html> <head> <link href= \"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center\"> <center> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS inline Class</b> <div class=\"bg-green-200 p-4 mx-16 space-y-4\"> <span class=\"inline bg-green-500 rounded-lg\">1</span> <span class=\"inline bg-green-500 rounded-lg\">2</span> <span class=\"inline bg-green-500 rounded-lg\">3</span> </div> </center></body> </html>",
"e": 4650,
"s": 4088,
"text": null
},
{
"code": null,
"e": 4658,
"s": 4650,
"text": "Output:"
},
{
"code": null,
"e": 4916,
"s": 4658,
"text": "flex: The flex class is much responsive and mobile-friendly. It is easy to position child elements and the main container. The margin doesn’t collapse with the content margins. The order of any element can be easily changed without editing the HTML section."
},
{
"code": null,
"e": 4924,
"s": 4916,
"text": "Syntax:"
},
{
"code": null,
"e": 4962,
"s": 4924,
"text": "<element display=\"flex\">...</element>"
},
{
"code": null,
"e": 4974,
"s": 4962,
"text": "Example 4: "
},
{
"code": null,
"e": 4979,
"s": 4974,
"text": "HTML"
},
{
"code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center\"> <center> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS flex Class</b> <div class=\"flex bg-green-200 p-4 mx-16 \"> <div class=\"flex-1 bg-green-500 rounded-lg\">1</div> <div class=\"flex-1 bg-green-500 rounded-lg\">2</div> <div class=\"flex-1 bg-green-500 rounded-lg\">3</div> </div> </center></body> </html>",
"e": 5532,
"s": 4979,
"text": null
},
{
"code": null,
"e": 5540,
"s": 5532,
"text": "Output:"
},
{
"code": null,
"e": 5553,
"s": 5540,
"text": "Tailwind CSS"
},
{
"code": null,
"e": 5569,
"s": 5553,
"text": "Tailwind-Layout"
},
{
"code": null,
"e": 5586,
"s": 5569,
"text": "Web Technologies"
},
{
"code": null,
"e": 5684,
"s": 5586,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5746,
"s": 5684,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 5779,
"s": 5746,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 5840,
"s": 5779,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 5890,
"s": 5840,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 5933,
"s": 5890,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 6005,
"s": 5933,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 6045,
"s": 6005,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 6069,
"s": 6045,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 6102,
"s": 6069,
"text": "Node.js fs.readFileSync() Method"
}
] |
Shortest path in a directed graph by Dijkstra’s algorithm | 06 Aug, 2021
Given a directed graph and a source vertex in the graph, the task is to find the shortest distance and path from source to target vertex in the given graph where edges are weighted (non-negative) and directed from parent vertex to source vertices.
Approach:
Mark all vertices unvisited. Create a set of all unvisited vertices.
Assign zero distance value to source vertex and infinity distance value to all other vertices.
Set the source vertex as current vertex
For current vertex, consider all of its unvisited children and calculate their tentative distances through the current. (distance of current + weight of the corresponding edge) Compare the newly calculated distance to the current assigned value (can be infinity for some vertices) and assign the smaller one.
After considering all the unvisited children of the current vertex, mark the current as visited and remove it from the unvisited set.
Similarly, continue for all the vertex until all the nodes are visited.
Below is the implementation of the above approach:
C++
Java
Python3
C#
// C++ implementation to find the// shortest path in a directed// graph from source vertex to// the destination vertex #include <bits/stdc++.h>#define infi 1000000000using namespace std; // Class of the nodeclass Node {public: int vertexNumber; // Adjacency list that shows the // vertexNumber of child vertex // and the weight of the edge vector<pair<int, int> > children; Node(int vertexNumber) { this->vertexNumber = vertexNumber; } // Function to add the child for // the given node void add_child(int vNumber, int length) { pair<int, int> p; p.first = vNumber; p.second = length; children.push_back(p); }}; // Function to find the distance of// the node from the given source// vertex to the destination vertexvector<int> dijkstraDist( vector<Node*> g, int s, vector<int>& path){ // Stores distance of each // vertex from source vertex vector<int> dist(g.size()); // Boolean array that shows // whether the vertex 'i' // is visited or not bool visited[g.size()]; for (int i = 0; i < g.size(); i++) { visited[i] = false; path[i] = -1; dist[i] = infi; } dist[s] = 0; path[s] = -1; int current = s; // Set of vertices that has // a parent (one or more) // marked as visited unordered_set<int> sett; while (true) { // Mark current as visited visited[current] = true; for (int i = 0; i < g[current]->children.size(); i++) { int v = g[current]->children[i].first; if (visited[v]) continue; // Inserting into the // visited vertex sett.insert(v); int alt = dist[current] + g[current]->children[i].second; // Condition to check the distance // is correct and update it // if it is minimum from the previous // computed distance if (alt < dist[v]) { dist[v] = alt; path[v] = current; } } sett.erase(current); if (sett.empty()) break; // The new current int minDist = infi; int index = 0; // Loop to update the distance // of the vertices of the graph for (int a: sett) { if (dist[a] < minDist) { minDist = dist[a]; index = a; } } current = index; } return dist;} // Function to print the path// from the source vertex to// the destination vertexvoid printPath(vector<int> path, int i, int s){ if (i != s) { // Condition to check if // there is no path between // the vertices if (path[i] == -1) { cout << "Path not found!!"; return; } printPath(path, path[i], s); cout << path[i] << " "; }} // Driver Codeint main(){ vector<Node*> v; int n = 4, s = 0, e = 5; // Loop to create the nodes for (int i = 0; i < n; i++) { Node* a = new Node(i); v.push_back(a); } // Creating directed // weighted edges v[0]->add_child(1, 1); v[0]->add_child(2, 4); v[1]->add_child(2, 2); v[1]->add_child(3, 6); v[2]->add_child(3, 3); vector<int> path(v.size()); vector<int> dist = dijkstraDist(v, s, path); // Loop to print the distance of // every node from source vertex for (int i = 0; i < dist.size(); i++) { if (dist[i] == infi) { cout << i << " and " << s << " are not connected" << endl; continue; } cout << "Distance of " << i << "th vertex from source vertex " << s << " is: " << dist[i] << endl; } return 0;}
// Java implementation to find the// shortest path in a directed// graph from source vertex to// the destination verteximport java.util.ArrayList;import java.util.HashSet;import java.util.List;import java.util.Set; class Pair{ int first, second; public Pair(int first, int second) { this.first = first; this.second = second; }} class GFG{ static final int infi = 1000000000; // Class of the nodestatic class Node{ int vertexNumber; // Adjacency list that shows the // vertexNumber of child vertex // and the weight of the edge List<Pair> children; Node(int vertexNumber) { this.vertexNumber = vertexNumber; children = new ArrayList<>(); } // Function to add the child for // the given node void add_child(int vNumber, int length) { Pair p = new Pair(vNumber, length); children.add(p); }} // Function to find the distance of// the node from the given source// vertex to the destination vertexstatic int[] dijkstraDist(List<Node> g, int s, int[] path){ // Stores distance of each // vertex from source vertex int[] dist = new int[g.size()]; // Boolean array that shows // whether the vertex 'i' // is visited or not boolean[] visited = new boolean[g.size()]; for(int i = 0; i < g.size(); i++) { visited[i] = false; path[i] = -1; dist[i] = infi; } dist[s] = 0; path[s] = -1; int current = s; // Set of vertices that has // a parent (one or more) // marked as visited Set<Integer> sett = new HashSet<>(); while (true) { // Mark current as visited visited[current] = true; for(int i = 0; i < g.get(current).children.size(); i++) { int v = g.get(current).children.get(i).first; if (visited[v]) continue; // Inserting into the // visited vertex sett.add(v); int alt = dist[current] + g.get(current).children.get(i).second; // Condition to check the distance // is correct and update it // if it is minimum from the previous // computed distance if (alt < dist[v]) { dist[v] = alt; path[v] = current; } } sett.remove(current); if (sett.isEmpty()) break; // The new current int minDist = infi; int index = 0; // Loop to update the distance // of the vertices of the graph for(int a : sett) { if (dist[a] < minDist) { minDist = dist[a]; index = a; } } current = index; } return dist;} // Function to print the path// from the source vertex to// the destination vertexvoid printPath(int[] path, int i, int s){ if (i != s) { // Condition to check if // there is no path between // the vertices if (path[i] == -1) { System.out.println("Path not found!!"); return; } printPath(path, path[i], s); System.out.print(path[i] + " "); }} // Driver Codepublic static void main(String[] args){ List<Node> v = new ArrayList<>(); int n = 4, s = 0, e = 5; // Loop to create the nodes for(int i = 0; i < n; i++) { Node a = new Node(i); v.add(a); } // Creating directed // weighted edges v.get(0).add_child(1, 1); v.get(0).add_child(2, 4); v.get(1).add_child(2, 2); v.get(1).add_child(3, 6); v.get(2).add_child(3, 3); int[] path = new int[v.size()]; int[] dist = dijkstraDist(v, s, path); // Loop to print the distance of // every node from source vertex for(int i = 0; i < dist.length; i++) { if (dist[i] == infi) { System.out.printf("%d and %d are not " + "connected\n", i, s); continue; } System.out.printf("Distance of %dth vertex " + "from source vertex %d is: %d\n", i, s, dist[i]); }}} // This code is contributed by sanjeev2552
# Python3 implementation to find the# shortest path in a directed# graph from source vertex to# the destination vertexclass Pair: def __init__(self, first, second): self.first = first self.second = secondinfi = 1000000000; # Class of the nodeclass Node: # Adjacency list that shows the # vertexNumber of child vertex # and the weight of the edge def __init__(self, vertexNumber): self.vertexNumber = vertexNumber self.children = [] # Function to add the child for # the given node def Add_child(self, vNumber, length): p = Pair(vNumber, length); self.children.append(p); # Function to find the distance of# the node from the given source# vertex to the destination vertexdef dijkstraDist(g, s, path): # Stores distance of each # vertex from source vertex dist = [infi for i in range(len(g))] # bool array that shows # whether the vertex 'i' # is visited or not visited = [False for i in range(len(g))] for i in range(len(g)): path[i] = -1 dist[s] = 0; path[s] = -1; current = s; # Set of vertices that has # a parent (one or more) # marked as visited sett = set() while (True): # Mark current as visited visited[current] = True; for i in range(len(g[current].children)): v = g[current].children[i].first; if (visited[v]): continue; # Inserting into the # visited vertex sett.add(v); alt = dist[current] + g[current].children[i].second; # Condition to check the distance # is correct and update it # if it is minimum from the previous # computed distance if (alt < dist[v]): dist[v] = alt; path[v] = current; if current in sett: sett.remove(current); if (len(sett) == 0): break; # The new current minDist = infi; index = 0; # Loop to update the distance # of the vertices of the graph for a in sett: if (dist[a] < minDist): minDist = dist[a]; index = a; current = index; return dist; # Function to print the path# from the source vertex to# the destination vertexdef printPath(path, i, s): if (i != s): # Condition to check if # there is no path between # the vertices if (path[i] == -1): print("Path not found!!"); return; printPath(path, path[i], s); print(path[i] + " "); # Driver Codeif __name__=='__main__': v = [] n = 4 s = 0; # Loop to create the nodes for i in range(n): a = Node(i); v.append(a); # Creating directed # weighted edges v[0].Add_child(1, 1); v[0].Add_child(2, 4); v[1].Add_child(2, 2); v[1].Add_child(3, 6); v[2].Add_child(3, 3); path = [0 for i in range(len(v))]; dist = dijkstraDist(v, s, path); # Loop to print the distance of # every node from source vertex for i in range(len(dist)): if (dist[i] == infi): print("{0} and {1} are not " + "connected".format(i, s)); continue; print("Distance of {}th vertex from source vertex {} is: {}".format( i, s, dist[i])); # This code is contributed by pratham76
// C# implementation to find the// shortest path in a directed// graph from source vertex to// the destination vertexusing System;using System.Collections;using System.Collections.Generic; class Pair{ public int first, second; public Pair(int first, int second) { this.first = first; this.second = second; }} class GFG{ static int infi = 1000000000; // Class of the nodeclass Node{ public int vertexNumber; // Adjacency list that shows the // vertexNumber of child vertex // and the weight of the edge public List<Pair> children; public Node(int vertexNumber) { this.vertexNumber = vertexNumber; children = new List<Pair>(); } // Function to Add the child for // the given node public void Add_child(int vNumber, int length) { Pair p = new Pair(vNumber, length); children.Add(p); }} // Function to find the distance of// the node from the given source// vertex to the destination vertexstatic int[] dijkstraDist(List<Node> g, int s, int[] path){ // Stores distance of each // vertex from source vertex int[] dist = new int[g.Count]; // bool array that shows // whether the vertex 'i' // is visited or not bool[] visited = new bool[g.Count]; for(int i = 0; i < g.Count; i++) { visited[i] = false; path[i] = -1; dist[i] = infi; } dist[s] = 0; path[s] = -1; int current = s; // Set of vertices that has // a parent (one or more) // marked as visited HashSet<int> sett = new HashSet<int>(); while (true) { // Mark current as visited visited[current] = true; for(int i = 0; i < g[current].children.Count; i++) { int v = g[current].children[i].first; if (visited[v]) continue; // Inserting into the // visited vertex sett.Add(v); int alt = dist[current] + g[current].children[i].second; // Condition to check the distance // is correct and update it // if it is minimum from the previous // computed distance if (alt < dist[v]) { dist[v] = alt; path[v] = current; } } sett.Remove(current); if (sett.Count == 0) break; // The new current int minDist = infi; int index = 0; // Loop to update the distance // of the vertices of the graph foreach(int a in sett) { if (dist[a] < minDist) { minDist = dist[a]; index = a; } } current = index; } return dist;} // Function to print the path// from the source vertex to// the destination vertexvoid printPath(int[] path, int i, int s){ if (i != s) { // Condition to check if // there is no path between // the vertices if (path[i] == -1) { Console.WriteLine("Path not found!!"); return; } printPath(path, path[i], s); Console.WriteLine(path[i] + " "); }} // Driver Codepublic static void Main(string[] args){ List<Node> v = new List<Node>(); int n = 4, s = 0; // Loop to create the nodes for(int i = 0; i < n; i++) { Node a = new Node(i); v.Add(a); } // Creating directed // weighted edges v[0].Add_child(1, 1); v[0].Add_child(2, 4); v[1].Add_child(2, 2); v[1].Add_child(3, 6); v[2].Add_child(3, 3); int[] path = new int[v.Count]; int[] dist = dijkstraDist(v, s, path); // Loop to print the distance of // every node from source vertex for(int i = 0; i < dist.Length; i++) { if (dist[i] == infi) { Console.Write("{0} and {1} are not " + "connected\n", i, s); continue; } Console.Write("Distance of {0}th vertex " + "from source vertex {1} is: {2}\n", i, s, dist[i]); }}} // This code is contributed by rutvik_56
Time Complexity: Auxiliary Space: O(V + E)Related articles: We have already discussed the shortest path in directed graph using Topological Sorting, in this article: Shortest path in Directed Acyclic graph
sanjeev2552
rutvik_56
pratham76
pankajsharmagfg
Algorithms-Graph Shortest Paths Quiz
Dijkstra
Algorithms
Competitive Programming
Data Structures
Graph
Greedy
Sorting
Tree
Data Structures
Greedy
Sorting
Graph
Tree
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
SDE SHEET - A Complete Guide for SDE Preparation
What is Hashing | A Complete Tutorial
CPU Scheduling in Operating Systems
Understanding Time Complexity with Simple Examples
Competitive Programming - A Complete Guide
Practice for cracking any coding interview
Arrow operator -> in C/C++ with Examples
Modulo 10^9+7 (1000000007)
Prefix Sum Array - Implementation and Applications in Competitive Programming | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n06 Aug, 2021"
},
{
"code": null,
"e": 300,
"s": 52,
"text": "Given a directed graph and a source vertex in the graph, the task is to find the shortest distance and path from source to target vertex in the given graph where edges are weighted (non-negative) and directed from parent vertex to source vertices."
},
{
"code": null,
"e": 311,
"s": 300,
"text": "Approach: "
},
{
"code": null,
"e": 380,
"s": 311,
"text": "Mark all vertices unvisited. Create a set of all unvisited vertices."
},
{
"code": null,
"e": 475,
"s": 380,
"text": "Assign zero distance value to source vertex and infinity distance value to all other vertices."
},
{
"code": null,
"e": 515,
"s": 475,
"text": "Set the source vertex as current vertex"
},
{
"code": null,
"e": 824,
"s": 515,
"text": "For current vertex, consider all of its unvisited children and calculate their tentative distances through the current. (distance of current + weight of the corresponding edge) Compare the newly calculated distance to the current assigned value (can be infinity for some vertices) and assign the smaller one."
},
{
"code": null,
"e": 958,
"s": 824,
"text": "After considering all the unvisited children of the current vertex, mark the current as visited and remove it from the unvisited set."
},
{
"code": null,
"e": 1030,
"s": 958,
"text": "Similarly, continue for all the vertex until all the nodes are visited."
},
{
"code": null,
"e": 1081,
"s": 1030,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1085,
"s": 1081,
"text": "C++"
},
{
"code": null,
"e": 1090,
"s": 1085,
"text": "Java"
},
{
"code": null,
"e": 1098,
"s": 1090,
"text": "Python3"
},
{
"code": null,
"e": 1101,
"s": 1098,
"text": "C#"
},
{
"code": "// C++ implementation to find the// shortest path in a directed// graph from source vertex to// the destination vertex #include <bits/stdc++.h>#define infi 1000000000using namespace std; // Class of the nodeclass Node {public: int vertexNumber; // Adjacency list that shows the // vertexNumber of child vertex // and the weight of the edge vector<pair<int, int> > children; Node(int vertexNumber) { this->vertexNumber = vertexNumber; } // Function to add the child for // the given node void add_child(int vNumber, int length) { pair<int, int> p; p.first = vNumber; p.second = length; children.push_back(p); }}; // Function to find the distance of// the node from the given source// vertex to the destination vertexvector<int> dijkstraDist( vector<Node*> g, int s, vector<int>& path){ // Stores distance of each // vertex from source vertex vector<int> dist(g.size()); // Boolean array that shows // whether the vertex 'i' // is visited or not bool visited[g.size()]; for (int i = 0; i < g.size(); i++) { visited[i] = false; path[i] = -1; dist[i] = infi; } dist[s] = 0; path[s] = -1; int current = s; // Set of vertices that has // a parent (one or more) // marked as visited unordered_set<int> sett; while (true) { // Mark current as visited visited[current] = true; for (int i = 0; i < g[current]->children.size(); i++) { int v = g[current]->children[i].first; if (visited[v]) continue; // Inserting into the // visited vertex sett.insert(v); int alt = dist[current] + g[current]->children[i].second; // Condition to check the distance // is correct and update it // if it is minimum from the previous // computed distance if (alt < dist[v]) { dist[v] = alt; path[v] = current; } } sett.erase(current); if (sett.empty()) break; // The new current int minDist = infi; int index = 0; // Loop to update the distance // of the vertices of the graph for (int a: sett) { if (dist[a] < minDist) { minDist = dist[a]; index = a; } } current = index; } return dist;} // Function to print the path// from the source vertex to// the destination vertexvoid printPath(vector<int> path, int i, int s){ if (i != s) { // Condition to check if // there is no path between // the vertices if (path[i] == -1) { cout << \"Path not found!!\"; return; } printPath(path, path[i], s); cout << path[i] << \" \"; }} // Driver Codeint main(){ vector<Node*> v; int n = 4, s = 0, e = 5; // Loop to create the nodes for (int i = 0; i < n; i++) { Node* a = new Node(i); v.push_back(a); } // Creating directed // weighted edges v[0]->add_child(1, 1); v[0]->add_child(2, 4); v[1]->add_child(2, 2); v[1]->add_child(3, 6); v[2]->add_child(3, 3); vector<int> path(v.size()); vector<int> dist = dijkstraDist(v, s, path); // Loop to print the distance of // every node from source vertex for (int i = 0; i < dist.size(); i++) { if (dist[i] == infi) { cout << i << \" and \" << s << \" are not connected\" << endl; continue; } cout << \"Distance of \" << i << \"th vertex from source vertex \" << s << \" is: \" << dist[i] << endl; } return 0;}",
"e": 4940,
"s": 1101,
"text": null
},
{
"code": "// Java implementation to find the// shortest path in a directed// graph from source vertex to// the destination verteximport java.util.ArrayList;import java.util.HashSet;import java.util.List;import java.util.Set; class Pair{ int first, second; public Pair(int first, int second) { this.first = first; this.second = second; }} class GFG{ static final int infi = 1000000000; // Class of the nodestatic class Node{ int vertexNumber; // Adjacency list that shows the // vertexNumber of child vertex // and the weight of the edge List<Pair> children; Node(int vertexNumber) { this.vertexNumber = vertexNumber; children = new ArrayList<>(); } // Function to add the child for // the given node void add_child(int vNumber, int length) { Pair p = new Pair(vNumber, length); children.add(p); }} // Function to find the distance of// the node from the given source// vertex to the destination vertexstatic int[] dijkstraDist(List<Node> g, int s, int[] path){ // Stores distance of each // vertex from source vertex int[] dist = new int[g.size()]; // Boolean array that shows // whether the vertex 'i' // is visited or not boolean[] visited = new boolean[g.size()]; for(int i = 0; i < g.size(); i++) { visited[i] = false; path[i] = -1; dist[i] = infi; } dist[s] = 0; path[s] = -1; int current = s; // Set of vertices that has // a parent (one or more) // marked as visited Set<Integer> sett = new HashSet<>(); while (true) { // Mark current as visited visited[current] = true; for(int i = 0; i < g.get(current).children.size(); i++) { int v = g.get(current).children.get(i).first; if (visited[v]) continue; // Inserting into the // visited vertex sett.add(v); int alt = dist[current] + g.get(current).children.get(i).second; // Condition to check the distance // is correct and update it // if it is minimum from the previous // computed distance if (alt < dist[v]) { dist[v] = alt; path[v] = current; } } sett.remove(current); if (sett.isEmpty()) break; // The new current int minDist = infi; int index = 0; // Loop to update the distance // of the vertices of the graph for(int a : sett) { if (dist[a] < minDist) { minDist = dist[a]; index = a; } } current = index; } return dist;} // Function to print the path// from the source vertex to// the destination vertexvoid printPath(int[] path, int i, int s){ if (i != s) { // Condition to check if // there is no path between // the vertices if (path[i] == -1) { System.out.println(\"Path not found!!\"); return; } printPath(path, path[i], s); System.out.print(path[i] + \" \"); }} // Driver Codepublic static void main(String[] args){ List<Node> v = new ArrayList<>(); int n = 4, s = 0, e = 5; // Loop to create the nodes for(int i = 0; i < n; i++) { Node a = new Node(i); v.add(a); } // Creating directed // weighted edges v.get(0).add_child(1, 1); v.get(0).add_child(2, 4); v.get(1).add_child(2, 2); v.get(1).add_child(3, 6); v.get(2).add_child(3, 3); int[] path = new int[v.size()]; int[] dist = dijkstraDist(v, s, path); // Loop to print the distance of // every node from source vertex for(int i = 0; i < dist.length; i++) { if (dist[i] == infi) { System.out.printf(\"%d and %d are not \" + \"connected\\n\", i, s); continue; } System.out.printf(\"Distance of %dth vertex \" + \"from source vertex %d is: %d\\n\", i, s, dist[i]); }}} // This code is contributed by sanjeev2552",
"e": 9224,
"s": 4940,
"text": null
},
{
"code": "# Python3 implementation to find the# shortest path in a directed# graph from source vertex to# the destination vertexclass Pair: def __init__(self, first, second): self.first = first self.second = secondinfi = 1000000000; # Class of the nodeclass Node: # Adjacency list that shows the # vertexNumber of child vertex # and the weight of the edge def __init__(self, vertexNumber): self.vertexNumber = vertexNumber self.children = [] # Function to add the child for # the given node def Add_child(self, vNumber, length): p = Pair(vNumber, length); self.children.append(p); # Function to find the distance of# the node from the given source# vertex to the destination vertexdef dijkstraDist(g, s, path): # Stores distance of each # vertex from source vertex dist = [infi for i in range(len(g))] # bool array that shows # whether the vertex 'i' # is visited or not visited = [False for i in range(len(g))] for i in range(len(g)): path[i] = -1 dist[s] = 0; path[s] = -1; current = s; # Set of vertices that has # a parent (one or more) # marked as visited sett = set() while (True): # Mark current as visited visited[current] = True; for i in range(len(g[current].children)): v = g[current].children[i].first; if (visited[v]): continue; # Inserting into the # visited vertex sett.add(v); alt = dist[current] + g[current].children[i].second; # Condition to check the distance # is correct and update it # if it is minimum from the previous # computed distance if (alt < dist[v]): dist[v] = alt; path[v] = current; if current in sett: sett.remove(current); if (len(sett) == 0): break; # The new current minDist = infi; index = 0; # Loop to update the distance # of the vertices of the graph for a in sett: if (dist[a] < minDist): minDist = dist[a]; index = a; current = index; return dist; # Function to print the path# from the source vertex to# the destination vertexdef printPath(path, i, s): if (i != s): # Condition to check if # there is no path between # the vertices if (path[i] == -1): print(\"Path not found!!\"); return; printPath(path, path[i], s); print(path[i] + \" \"); # Driver Codeif __name__=='__main__': v = [] n = 4 s = 0; # Loop to create the nodes for i in range(n): a = Node(i); v.append(a); # Creating directed # weighted edges v[0].Add_child(1, 1); v[0].Add_child(2, 4); v[1].Add_child(2, 2); v[1].Add_child(3, 6); v[2].Add_child(3, 3); path = [0 for i in range(len(v))]; dist = dijkstraDist(v, s, path); # Loop to print the distance of # every node from source vertex for i in range(len(dist)): if (dist[i] == infi): print(\"{0} and {1} are not \" + \"connected\".format(i, s)); continue; print(\"Distance of {}th vertex from source vertex {} is: {}\".format( i, s, dist[i])); # This code is contributed by pratham76",
"e": 12830,
"s": 9224,
"text": null
},
{
"code": "// C# implementation to find the// shortest path in a directed// graph from source vertex to// the destination vertexusing System;using System.Collections;using System.Collections.Generic; class Pair{ public int first, second; public Pair(int first, int second) { this.first = first; this.second = second; }} class GFG{ static int infi = 1000000000; // Class of the nodeclass Node{ public int vertexNumber; // Adjacency list that shows the // vertexNumber of child vertex // and the weight of the edge public List<Pair> children; public Node(int vertexNumber) { this.vertexNumber = vertexNumber; children = new List<Pair>(); } // Function to Add the child for // the given node public void Add_child(int vNumber, int length) { Pair p = new Pair(vNumber, length); children.Add(p); }} // Function to find the distance of// the node from the given source// vertex to the destination vertexstatic int[] dijkstraDist(List<Node> g, int s, int[] path){ // Stores distance of each // vertex from source vertex int[] dist = new int[g.Count]; // bool array that shows // whether the vertex 'i' // is visited or not bool[] visited = new bool[g.Count]; for(int i = 0; i < g.Count; i++) { visited[i] = false; path[i] = -1; dist[i] = infi; } dist[s] = 0; path[s] = -1; int current = s; // Set of vertices that has // a parent (one or more) // marked as visited HashSet<int> sett = new HashSet<int>(); while (true) { // Mark current as visited visited[current] = true; for(int i = 0; i < g[current].children.Count; i++) { int v = g[current].children[i].first; if (visited[v]) continue; // Inserting into the // visited vertex sett.Add(v); int alt = dist[current] + g[current].children[i].second; // Condition to check the distance // is correct and update it // if it is minimum from the previous // computed distance if (alt < dist[v]) { dist[v] = alt; path[v] = current; } } sett.Remove(current); if (sett.Count == 0) break; // The new current int minDist = infi; int index = 0; // Loop to update the distance // of the vertices of the graph foreach(int a in sett) { if (dist[a] < minDist) { minDist = dist[a]; index = a; } } current = index; } return dist;} // Function to print the path// from the source vertex to// the destination vertexvoid printPath(int[] path, int i, int s){ if (i != s) { // Condition to check if // there is no path between // the vertices if (path[i] == -1) { Console.WriteLine(\"Path not found!!\"); return; } printPath(path, path[i], s); Console.WriteLine(path[i] + \" \"); }} // Driver Codepublic static void Main(string[] args){ List<Node> v = new List<Node>(); int n = 4, s = 0; // Loop to create the nodes for(int i = 0; i < n; i++) { Node a = new Node(i); v.Add(a); } // Creating directed // weighted edges v[0].Add_child(1, 1); v[0].Add_child(2, 4); v[1].Add_child(2, 2); v[1].Add_child(3, 6); v[2].Add_child(3, 3); int[] path = new int[v.Count]; int[] dist = dijkstraDist(v, s, path); // Loop to print the distance of // every node from source vertex for(int i = 0; i < dist.Length; i++) { if (dist[i] == infi) { Console.Write(\"{0} and {1} are not \" + \"connected\\n\", i, s); continue; } Console.Write(\"Distance of {0}th vertex \" + \"from source vertex {1} is: {2}\\n\", i, s, dist[i]); }}} // This code is contributed by rutvik_56",
"e": 17079,
"s": 12830,
"text": null
},
{
"code": null,
"e": 17286,
"s": 17079,
"text": "Time Complexity: Auxiliary Space: O(V + E)Related articles: We have already discussed the shortest path in directed graph using Topological Sorting, in this article: Shortest path in Directed Acyclic graph "
},
{
"code": null,
"e": 17298,
"s": 17286,
"text": "sanjeev2552"
},
{
"code": null,
"e": 17308,
"s": 17298,
"text": "rutvik_56"
},
{
"code": null,
"e": 17318,
"s": 17308,
"text": "pratham76"
},
{
"code": null,
"e": 17334,
"s": 17318,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 17371,
"s": 17334,
"text": "Algorithms-Graph Shortest Paths Quiz"
},
{
"code": null,
"e": 17380,
"s": 17371,
"text": "Dijkstra"
},
{
"code": null,
"e": 17391,
"s": 17380,
"text": "Algorithms"
},
{
"code": null,
"e": 17415,
"s": 17391,
"text": "Competitive Programming"
},
{
"code": null,
"e": 17431,
"s": 17415,
"text": "Data Structures"
},
{
"code": null,
"e": 17437,
"s": 17431,
"text": "Graph"
},
{
"code": null,
"e": 17444,
"s": 17437,
"text": "Greedy"
},
{
"code": null,
"e": 17452,
"s": 17444,
"text": "Sorting"
},
{
"code": null,
"e": 17457,
"s": 17452,
"text": "Tree"
},
{
"code": null,
"e": 17473,
"s": 17457,
"text": "Data Structures"
},
{
"code": null,
"e": 17480,
"s": 17473,
"text": "Greedy"
},
{
"code": null,
"e": 17488,
"s": 17480,
"text": "Sorting"
},
{
"code": null,
"e": 17494,
"s": 17488,
"text": "Graph"
},
{
"code": null,
"e": 17499,
"s": 17494,
"text": "Tree"
},
{
"code": null,
"e": 17510,
"s": 17499,
"text": "Algorithms"
},
{
"code": null,
"e": 17608,
"s": 17510,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 17633,
"s": 17608,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 17682,
"s": 17633,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 17720,
"s": 17682,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 17756,
"s": 17720,
"text": "CPU Scheduling in Operating Systems"
},
{
"code": null,
"e": 17807,
"s": 17756,
"text": "Understanding Time Complexity with Simple Examples"
},
{
"code": null,
"e": 17850,
"s": 17807,
"text": "Competitive Programming - A Complete Guide"
},
{
"code": null,
"e": 17893,
"s": 17850,
"text": "Practice for cracking any coding interview"
},
{
"code": null,
"e": 17934,
"s": 17893,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 17961,
"s": 17934,
"text": "Modulo 10^9+7 (1000000007)"
}
] |
How to print maximum number of A’s using given four keys | 28 Feb, 2022
This is a famous interview question asked in Google, Paytm and many other company interviews. Below is the problem statement.
Imagine you have a special keyboard with the following keys:
Key 1: Prints 'A' on screen
Key 2: (Ctrl-A): Select screen
Key 3: (Ctrl-C): Copy selection to buffer
Key 4: (Ctrl-V): Print buffer on screen appending it
after what has already been printed.
If you can only press the keyboard for N times (with the above four
keys), write a program to produce maximum numbers of A's. That is to
say, the input parameter is N (No. of keys that you can press), the
output is M (No. of As that you can produce).
Examples:
Input: N = 3
Output: 3
We can at most get 3 A's on screen by pressing
following key sequence.
A, A, A
Input: N = 7
Output: 9
We can at most get 9 A's on screen by pressing
following key sequence.
A, A, A, Ctrl A, Ctrl C, Ctrl V, Ctrl V
Input: N = 11
Output: 27
We can at most get 27 A's on screen by pressing
following key sequence.
A, A, A, Ctrl A, Ctrl C, Ctrl V, Ctrl V, Ctrl A,
Ctrl C, Ctrl V, Ctrl V
Below are few important points to note.a) For N < 7, the output is N itself. b) Ctrl V can be used multiple times to print current buffer (See last two examples above). The idea is to compute the optimal string length for N keystrokes by using a simple insight. The sequence of N keystrokes which produces an optimal string length will end with a suffix of Ctrl-A, a Ctrl-C, followed by only Ctrl-V’s . (For N > 6)The task is to find out the break=point after which we get the above suffix of keystrokes. Definition of a breakpoint is that instance after which we need to only press Ctrl-A, Ctrl-C once and the only Ctrl-V’s afterward to generate the optimal length. If we loop from N-3 to 1 and choose each of these values for the break-point, and compute that optimal string they would produce. Once the loop ends, we will have the maximum of the optimal lengths for various breakpoints, thereby giving us the optimal length for N keystrokes.
Below is implementation based on above idea.
C++14
C
Java
Python3
C#
PHP
Javascript
/* A recursive C++ program to print maximum number of A's usingfollowing four keys */#include <bits/stdc++.h>using namespace std; // A recursive function that returns the optimal length string// for N keystrokesint findoptimal(int N){ // The optimal string length is N when N is smaller than 7 if (N <= 6) return N; // Initialize result int max = 0; // TRY ALL POSSIBLE BREAK-POINTS // For any keystroke N, we need to loop from N-3 keystrokes // back to 1 keystroke to find a breakpoint 'b' after which we // will have Ctrl-A, Ctrl-C and then only Ctrl-V all the way. int b; for (b = N - 3; b >= 1; b--) { // If the breakpoint is s at b'th keystroke then // the optimal string would have length // (n-b-1)*screen[b-1]; int curr = (N - b - 1) * findoptimal(b); if (curr > max) max = curr; } return max;} // Driver programint main(){ int N; // for the rest of the array we will reply on the previous // entries to compute new ones for (N = 1; N <= 20; N++) cout << "Maximum Number of A's with " << N << " keystrokes is " << findoptimal(N) << endl;} // This code is contributed by shubhamsingh10
/* A recursive C program to print maximum number of A's using following four keys */#include <stdio.h> // A recursive function that returns the optimal length string// for N keystrokesint findoptimal(int N){ // The optimal string length is N when N is smaller than 7 if (N <= 6) return N; // Initialize result int max = 0; // TRY ALL POSSIBLE BREAK-POINTS // For any keystroke N, we need to loop from N-3 keystrokes // back to 1 keystroke to find a breakpoint 'b' after which we // will have Ctrl-A, Ctrl-C and then only Ctrl-V all the way. int b; for (b = N - 3; b >= 1; b--) { // If the breakpoint is s at b'th keystroke then // the optimal string would have length // (n-b-1)*screen[b-1]; int curr = (N - b - 1) * findoptimal(b); if (curr > max) max = curr; } return max;} // Driver programint main(){ int N; // for the rest of the array we will reply on the previous // entries to compute new ones for (N = 1; N <= 20; N++) printf("Maximum Number of A's with %d keystrokes is %d\n", N, findoptimal(N));}
/* A recursive Java program to print maximum number of A's using following four keys */import java.io.*; class GFG { // A recursive function that returns // the optimal length string for N keystrokes static int findoptimal(int N) { // The optimal string length is N // when N is smaller than 7 if (N <= 6) return N; // Initialize result int max = 0; // TRY ALL POSSIBLE BREAK-POINTS // For any keystroke N, we need to // loop from N-3 keystrokes back to // 1 keystroke to find a breakpoint // 'b' after which we will have Ctrl-A, // Ctrl-C and then only Ctrl-V all the way. int b; for (b = N - 3; b >= 1; b--) { // If the breakpoint is s at b'th // keystroke then the optimal string // would have length // (n-b-1)*screen[b-1]; int curr = (N - b - 1) * findoptimal(b); if (curr > max) max = curr; } return max; } // Driver program public static void main(String[] args) { int N; // for the rest of the array we // will reply on the previous // entries to compute new ones for (N = 1; N <= 20; N++) System.out.println("Maximum Number of A's with keystrokes is " + N + findoptimal(N)); }} // This code is contributed by vt_m.
# A recursive Python3 program to print maximum# number of A's using following four keys # A recursive function that returns# the optimal length string for N keystrokes def findoptimal(N): # The optimal string length is # N when N is smaller than if N<= 6: return N # Initialize result maxi = 0 # TRY ALL POSSIBLE BREAK-POINTS # For any keystroke N, we need # to loop from N-3 keystrokes # back to 1 keystroke to find # a breakpoint 'b' after which we # will have Ctrl-A, Ctrl-C and then # only Ctrl-V all the way. for b in range(N-3, 0, -1): curr =(N-b-1)*findoptimal(b) if curr>maxi: maxi = curr return maxi# Driver programif __name__=='__main__': # for the rest of the array we will# reply on the previous# entries to compute new ones for n in range(1, 21): print('Maximum Number of As with ', n, 'keystrokes is ', findoptimal(n)) # this code is contributed by sahilshelangia
/* A recursive C# programto print maximum numberof A's using followingfour keys */using System; class GFG { // A recursive function that // returns the optimal length // string for N keystrokes static int findoptimal(int N) { // The optimal string length // is N when N is smaller than 7 if (N <= 6) return N; // Initialize result int max = 0; // TRY ALL POSSIBLE BREAK-POINTS // For any keystroke N, we need // to loop from N-3 keystrokes // back to 1 keystroke to find // a breakpoint 'b' after which // we will have Ctrl-A, Ctrl-C // and then only Ctrl-V all the way. int b; for (b = N - 3; b >= 1; b--) { // If the breakpoint is s // at b'th keystroke then // the optimal string would // have length (n-b-1)*screen[b-1]; int curr = (N - b - 1) * findoptimal(b); if (curr > max) max = curr; } return max; } // Driver code static void Main() { int N; // for the rest of the array // we will reply on the // previous entries to compute // new ones for (N = 1; N <= 20; N++) Console.WriteLine("Maximum Number of A's with " + N + " keystrokes is " + findoptimal(N)); }} // This code is contributed by Sam007
<?php/* A recursive PHP program to print maximum number of A's usingfollowing four keys */ // A recursive function that returns the optimal// length string for N keystrokesfunction findoptimal($N){ // The optimal string length is // N when N is smaller than 7 if ($N <= 6) return $N; // Initialize result $max = 0; // TRY ALL POSSIBLE BREAK-POINTS // For any keystroke N, we need to loop from N-3 keystrokes // back to 1 keystroke to find a breakpoint 'b' after which we // will have Ctrl-A, Ctrl-C and then only Ctrl-V all the way. $b; for ($b = $N - 3; $b >= 1; $b -= 1) { // If the breakpoint is s at b'th keystroke then // the optimal string would have length // (n-b-1)*screen[b-1]; $curr = ($N - $b - 1) * findoptimal($b); if ($curr > $max) $max = $curr; } return $max;} // Driver code$N; // for the rest of the array we will reply on the previous// entries to compute new onesfor ($N = 1; $N <= 20; $N += 1) echo("Maximum Number of A's with" .$N."keystrokes is ".findoptimal($N)."\n"); // This code is contributed by aman neekhara?>
<script> // A recursive Javascript program to print// maximum number of A's using// following four keys // A recursive function that returns the// optimal length string for N keystrokesfunction findoptimal(N){ // The optimal string length is N // when N is smaller than 7 if (N <= 6) return N; // Initialize result let max = 0; // TRY ALL POSSIBLE BREAK-POINTS // For any keystroke N, we need to // loop from N-3 keystrokes back to // 1 keystroke to find a breakpoint // 'b' after which we will have Ctrl-A, // Ctrl-C and then only Ctrl-V all the way. let b; for(b = N - 3; b >= 1; b--) { // If the breakpoint is s at b'th // keystroke then the optimal string // would have length // (n-b-1)*screen[b-1]; let curr = (N - b - 1) * findoptimal(b); if (curr > max) max = curr; } return max;} // Driver codelet N; // For the rest of the array we// will reply on the previous// entries to compute new onesfor(N = 1; N <= 20; N++) document.write("Maximum Number of A's with "+ N + " keystrokes is " + findoptimal(N) + "<br>"); // This code is contributed by avanitrachhadiya2155 </script>
Output:
Maximum Number of A's with 1 keystrokes is 1
Maximum Number of A's with 2 keystrokes is 2
Maximum Number of A's with 3 keystrokes is 3
Maximum Number of A's with 4 keystrokes is 4
Maximum Number of A's with 5 keystrokes is 5
Maximum Number of A's with 6 keystrokes is 6
Maximum Number of A's with 7 keystrokes is 9
Maximum Number of A's with 8 keystrokes is 12
Maximum Number of A's with 9 keystrokes is 16
Maximum Number of A's with 10 keystrokes is 20
Maximum Number of A's with 11 keystrokes is 27
Maximum Number of A's with 12 keystrokes is 36
Maximum Number of A's with 13 keystrokes is 48
Maximum Number of A's with 14 keystrokes is 64
Maximum Number of A's with 15 keystrokes is 81
Maximum Number of A's with 16 keystrokes is 108
Maximum Number of A's with 17 keystrokes is 144
Maximum Number of A's with 18 keystrokes is 192
Maximum Number of A's with 19 keystrokes is 256
Maximum Number of A's with 20 keystrokes is 324
The above function computes the same subproblems again and again. Recomputations of same subproblems can be avoided by storing the solutions to subproblems and solving problems in a bottom-up manner.
Below is Dynamic Programming based C implementation where an auxiliary array screen[N] is used to store result of subproblems.
C++
C
Java
Python3
C#
Javascript
/* A Dynamic Programming based C program to find maximum number of A'sthat can be printed using four keys */#include <iostream>using namespace std; // this function returns the optimal length string for N keystrokesint findoptimal(int N){ // The optimal string length is N when N is smaller than 7 if (N <= 6) return N; // An array to store result of subproblems int screen[N]; int b; // To pick a breakpoint // Initializing the optimal lengths array for until 6 input // strokes. int n; for (n = 1; n <= 6; n++) screen[n - 1] = n; // Solve all subproblems in bottom manner for (n = 7; n <= N; n++) { // Initialize length of optimal string for n keystrokes screen[n - 1] = 0; // For any keystroke n, we need to loop from n-3 keystrokes // back to 1 keystroke to find a breakpoint 'b' after which we // will have ctrl-a, ctrl-c and then only ctrl-v all the way. for (b = n - 3; b >= 1; b--) { // if the breakpoint is at b'th keystroke then // the optimal string would have length // (n-b-1)*screen[b-1]; int curr = (n - b - 1) * screen[b - 1]; if (curr > screen[n - 1]) screen[n - 1] = curr; } } return screen[N - 1];} // Driver programint main(){ int N; // for the rest of the array we will reply on the previous // entries to compute new ones for (N = 1; N <= 20; N++) cout << "Maximum Number of A's with "<<N<<" keystrokes is " << findoptimal(N) << endl;} //This is contributed by shubhamsingh10
/* A Dynamic Programming based C program to find maximum number of A's that can be printed using four keys */#include <stdio.h> // this function returns the optimal length string for N keystrokesint findoptimal(int N){ // The optimal string length is N when N is smaller than 7 if (N <= 6) return N; // An array to store result of subproblems int screen[N]; int b; // To pick a breakpoint // Initializing the optimal lengths array for until 6 input // strokes. int n; for (n = 1; n <= 6; n++) screen[n - 1] = n; // Solve all subproblems in bottom manner for (n = 7; n <= N; n++) { // Initialize length of optimal string for n keystrokes screen[n - 1] = 0; // For any keystroke n, we need to loop from n-3 keystrokes // back to 1 keystroke to find a breakpoint 'b' after which we // will have ctrl-a, ctrl-c and then only ctrl-v all the way. for (b = n - 3; b >= 1; b--) { // if the breakpoint is at b'th keystroke then // the optimal string would have length // (n-b-1)*screen[b-1]; int curr = (n - b - 1) * screen[b - 1]; if (curr > screen[n - 1]) screen[n - 1] = curr; } } return screen[N - 1];} // Driver programint main(){ int N; // for the rest of the array we will reply on the previous // entries to compute new ones for (N = 1; N <= 20; N++) printf("Maximum Number of A's with %d keystrokes is %d\n", N, findoptimal(N));}
/* A Dynamic Programming based C program to find maximum number of A's that can be printed using four keys */import java.io.*; class GFG { // this function returns the optimal // length string for N keystrokes static int findoptimal(int N) { // The optimal string length is N // when N is smaller than 7 if (N <= 6) return N; // An array to store result // of subproblems int screen[] = new int[N]; int b; // To pick a breakpoint // Initializing the optimal lengths // array for until 6 input strokes int n; for (n = 1; n <= 6; n++) screen[n - 1] = n; // Solve all subproblems in bottom manner for (n = 7; n <= N; n++) { // Initialize length of optimal // string for n keystrokes screen[n - 1] = 0; // For any keystroke n, we need // to loop from n-3 keystrokes // back to 1 keystroke to find // a breakpoint 'b' after which we // will have ctrl-a, ctrl-c and // then only ctrl-v all the way. for (b = n - 3; b >= 1; b--) { // if the breakpoint is // at b'th keystroke then // the optimal string would // have length // (n-b-1)*screen[b-1]; int curr = (n - b - 1) * screen[b - 1]; if (curr > screen[n - 1]) screen[n - 1] = curr; } } return screen[N - 1]; } // Driver program public static void main(String[] args) { int N; // for the rest of the array we will reply on the previous // entries to compute new ones for (N = 1; N <= 20; N++) System.out.println("Maximum Number of A's with keystrokes is " + N + findoptimal(N)); }} // This article is contributed by vt_m.
# A Dynamic Programming based Python program# to find maximum number of A's# that can be printed using four keys # this function returns the optimal# length string for N keystrokesdef findoptimal(N): # The optimal string length is # N when N is smaller than 7 if (N <= 6): return N # An array to store result of # subproblems screen = [0]*N # Initializing the optimal lengths # array for until 6 input # strokes. for n in range(1, 7): screen[n-1] = n # Solve all subproblems in bottom manner for n in range(7, N + 1): # Initialize length of optimal # string for n keystrokes screen[n-1] = 0 # For any keystroke n, we need to # loop from n-3 keystrokes # back to 1 keystroke to find a breakpoint # 'b' after which we # will have ctrl-a, ctrl-c and then only # ctrl-v all the way. for b in range(n-3, 0, -1): # if the breakpoint is at b'th keystroke then # the optimal string would have length # (n-b-1)*screen[b-1]; curr = (n-b-1)*screen[b-1] if (curr > screen[n-1]): screen[n-1] = curr return screen[N-1] # Driver programif __name__ == "__main__": # for the rest of the array we # will reply on the previous # entries to compute new ones for N in range(1, 21): print("Maximum Number of A's with ", N, " keystrokes is ", findoptimal(N)) # this code is contributed by# ChitraNayal
/* A Dynamic Programming based C#program to find maximum numberof A's that can be printed usingfour keys */using System;public class GFG { // this function returns the optimal // length string for N keystrokes static int findoptimal(int N) { // The optimal string length is N // when N is smaller than 7 if (N <= 6) return N; // An array to store result // of subproblems int[] screen = new int[N]; int b; // To pick a breakpoint // Initializing the optimal lengths // array for until 6 input strokes int n; for (n = 1; n <= 6; n++) screen[n - 1] = n; // Solve all subproblems in bottom manner for (n = 7; n <= N; n++) { // Initialize length of optimal // string for n keystrokes screen[n - 1] = 0; // For any keystroke n, we need // to loop from n-3 keystrokes // back to 1 keystroke to find // a breakpoint 'b' after which we // will have ctrl-a, ctrl-c and // then only ctrl-v all the way. for (b = n - 3; b >= 1; b--) { // if the breakpoint is // at b'th keystroke then // the optimal string would // have length // (n-b-1)*screen[b-1]; int curr = (n - b - 1) * screen[b - 1]; if (curr > screen[n - 1]) screen[n - 1] = curr; } } return screen[N - 1]; } // Driver program public static void Main(String[] args) { int N; // for the rest of the array we will reply on the previous // entries to compute new ones for (N = 1; N <= 20; N++) Console.WriteLine("Maximum Number of A's with {0} keystrokes is {1}\n", N, findoptimal(N)); }} // This code is contributed by PrinciRaj1992
<script> // A Dynamic Programming based javascript// program to find maximum number// of A's that can be printed using// four keys // This function returns the optimal// length string for N keystrokes function findoptimal(N){ // The optimal string length is N // when N is smaller than 7 if (N <= 6) return N; // An array to store result // of subproblems let screen = new Array(N); for(let i = 0; i < N; i++) { screen[i] = 0; } // To pick a breakpoint let b; // Initializing the optimal lengths // array for until 6 input strokes let n; for(n = 1; n <= 6; n++) screen[n - 1] = n; // Solve all subproblems in bottom manner for(n = 7; n <= N; n++) { // Initialize length of optimal // string for n keystrokes screen[n - 1] = 0; // For any keystroke n, we need // to loop from n-3 keystrokes // back to 1 keystroke to find // a breakpoint 'b' after which we // will have ctrl-a, ctrl-c and // then only ctrl-v all the way. for(b = n - 3; b >= 1; b--) { // If the breakpoint is // at b'th keystroke then // the optimal string would // have length // (n-b-1)*screen[b-1]; let curr = (n - b - 1) * screen[b - 1]; if (curr > screen[n - 1]) screen[n - 1] = curr; } } return screen[N - 1];} // Driver codelet N;for(N = 1; N <= 20; N++) document.write("Maximum Number of A's with " + N + " keystrokes is " + findoptimal(N) + "<br>"); // This code is contributed by rag2127 </script>
Output:
Maximum Number of A's with 1 keystrokes is 1
Maximum Number of A's with 2 keystrokes is 2
Maximum Number of A's with 3 keystrokes is 3
Maximum Number of A's with 4 keystrokes is 4
Maximum Number of A's with 5 keystrokes is 5
Maximum Number of A's with 6 keystrokes is 6
Maximum Number of A's with 7 keystrokes is 9
Maximum Number of A's with 8 keystrokes is 12
Maximum Number of A's with 9 keystrokes is 16
Maximum Number of A's with 10 keystrokes is 20
Maximum Number of A's with 11 keystrokes is 27
Maximum Number of A's with 12 keystrokes is 36
Maximum Number of A's with 13 keystrokes is 48
Maximum Number of A's with 14 keystrokes is 64
Maximum Number of A's with 15 keystrokes is 81
Maximum Number of A's with 16 keystrokes is 108
Maximum Number of A's with 17 keystrokes is 144
Maximum Number of A's with 18 keystrokes is 192
Maximum Number of A's with 19 keystrokes is 256
Maximum Number of A's with 20 keystrokes is 324
Thanks to Gaurav Saxena for providing the above approach to solve this problem.As the number of A’s become large, the effect of pressing Ctrl-V more than 3 times starts to become insubstantial as compared to just pressing Ctrl-A, Ctrl-C and Ctrl-V again. So, the above code can be made more efficient by checking the effect of pressing Ctrl-V for 1, 2, and 3 times only.
C++
Java
Python3
C#
Javascript
// A Dynamic Programming based C++ program to find maximum// number of A's that can be printed using four keys #include <bits/stdc++.h>using namespace std; // This function returns the optimal length string for N keystrokesint findoptimal(int N){ // The optimal string length is N when N is smaller than 7 if (N <= 6) return N; // An array to store result of subproblems int screen[N]; int b; // To pick a breakpoint // Initializing the optimal lengths array for until 6 input // strokes. int n; for (n = 1; n <= 6; n++) screen[n - 1] = n; // Solve all subproblems in bottom-up manner for (n = 7; n <= N; n++) { // for any keystroke n, we will need to choose between:- // 1. pressing Ctrl-V once after copying the // A's obtained by n-3 keystrokes. // 2. pressing Ctrl-V twice after copying the A's // obtained by n-4 keystrokes. // 3. pressing Ctrl-V thrice after copying the A's // obtained by n-5 keystrokes. screen[n - 1] = max(2 * screen[n - 4], max(3 * screen[n - 5],4 * screen[n - 6])); } return screen[N - 1];} // Driver programint main(){ int N; // for the rest of the array we will reply on the previous // entries to compute new ones for (N = 1; N <= 20; N++) printf("Maximum Number of A's with %d keystrokes is %d\n", N, findoptimal(N));}
// A Dynamic Programming based Java program// to find maximum number of A's that// can be printed using four keysclass GFG{ // This function returns the optimal length// string for N keystrokesstatic int findoptimal(int N){ // The optimal string length is N // when N is smaller than 7 if (N <= 6) return N; // An array to store result of subproblems int []screen = new int[N]; int b; // To pick a breakpoint // Initializing the optimal lengths array // for uptil 6 input strokes. int n; for (n = 1; n <= 6; n++) screen[n - 1] = n; // Solve all subproblems in bottom-up manner for (n = 7; n <= N; n++) { // for any keystroke n, we will need to choose between:- // 1. pressing Ctrl-V once after copying the // A's obtained by n-3 keystrokes. // 2. pressing Ctrl-V twice after copying the A's // obtained by n-4 keystrokes. // 3. pressing Ctrl-V thrice after copying the A's // obtained by n-5 keystrokes. screen[n - 1] = Math.max(2 * screen[n - 4], Math.max(3 * screen[n - 5], 4 * screen[n - 6])); } return screen[N - 1];} // Driver Codepublic static void main(String[] args){ int N; // for the rest of the array we will reply // on the previous entries to compute new ones for (N = 1; N <= 20; N++) System.out.printf("Maximum Number of A's with" + " %d keystrokes is %d\n", N, findoptimal(N)); }} // This code is contributed by Princi Singh
# A Dynamic Programming based Python3 program# to find maximum number of A's# that can be printed using four keys # this function returns the optimal# length string for N keystrokesdef findoptimal(N): # The optimal string length is # N when N is smaller than 7 if (N <= 6): return N # An array to store result of # subproblems screen = [0] * N # Initializing the optimal lengths # array for until 6 input # strokes. for n in range(1, 7): screen[n - 1] = n # Solve all subproblems in bottom manner for n in range(7, N + 1): # for any keystroke n, we will need to choose between:- # 1. pressing Ctrl-V once after copying the # A's obtained by n-3 keystrokes. # 2. pressing Ctrl-V twice after copying the A's # obtained by n-4 keystrokes. # 3. pressing Ctrl-V thrice after copying the A's # obtained by n-5 keystrokes. screen[n - 1] = max(2 * screen[n - 4], max(3 * screen[n - 5], 4 * screen[n - 6])); return screen[N - 1] # Driver Codeif __name__ == "__main__": # for the rest of the array we # will reply on the previous # entries to compute new ones for N in range(1, 21): print("Maximum Number of A's with ", N, " keystrokes is ", findoptimal(N)) # This code is contributed by ashutosh450
// A Dynamic Programming based C# program// to find maximum number of A's that// can be printed using four keysusing System; class GFG{ // This function returns the optimal length// string for N keystrokesstatic int findoptimal(int N){ // The optimal string length is N // when N is smaller than 7 if (N <= 6) return N; // An array to store result of subproblems int []screen = new int[N]; // Initializing the optimal lengths array // for uptil 6 input strokes. int n; for (n = 1; n <= 6; n++) screen[n - 1] = n; // Solve all subproblems in bottom-up manner for (n = 7; n <= N; n++) { // for any keystroke n, we will need to choose between:- // 1. pressing Ctrl-V once after copying the // A's obtained by n-3 keystrokes. // 2. pressing Ctrl-V twice after copying the A's // obtained by n-4 keystrokes. // 3. pressing Ctrl-V thrice after copying the A's // obtained by n-5 keystrokes. screen[n - 1] = Math.Max(2 * screen[n - 4], Math.Max(3 * screen[n - 5], 4 * screen[n - 6])); } return screen[N - 1];} // Driver Codepublic static void Main(String[] args){ int N; // for the rest of the array we will reply // on the previous entries to compute new ones for (N = 1; N <= 20; N++) Console.Write("Maximum Number of A's with" + " {0} keystrokes is {1}\n", N, findoptimal(N)); }} // This code is contributed by PrinciRaj1992
<script> // A Dynamic Programming based// JavaScript program to find maximum// number of A's that can be printed// using four keys // This function returns the optimal// length string for N keystrokesfunction findoptimal(N){ // The optimal string length is N // when N is smaller than 7 if (N <= 6) return N; // An array to store result // of subproblems let screen = []; let b; // To pick a breakpoint // Initializing the optimal lengths // array for until 6 input // strokes. let n; for (n = 1; n <= 6; n++) screen[n - 1] = n; // Solve all subproblems in bottom-up manner for (n = 7; n <= N; n++) { // for any keystroke n, we will // need to choose between:- // 1. pressing Ctrl-V once // after copying the // A's obtained by n-3 keystrokes. // 2. pressing Ctrl-V twice after // copying the A's // obtained by n-4 keystrokes. // 3. pressing Ctrl-V thrice // after copying the A's // obtained by n-5 keystrokes. screen[n - 1] = Math.max(2 * screen[n - 4], Math.max(3 * screen[n - 5],4 * screen[n - 6])); } return screen[N - 1];} // Driver programlet N;// for the rest of the array we will reply on the previous// entries to compute new onesfor (N = 1; N <= 20; N++) document.write( "Maximum Number of A's with "+ N +" keystrokes is " +findoptimal(N)+"<br>" ); </script>
Output:
Maximum Number of A's with 1 keystrokes is 1
Maximum Number of A's with 2 keystrokes is 2
Maximum Number of A's with 3 keystrokes is 3
Maximum Number of A's with 4 keystrokes is 4
Maximum Number of A's with 5 keystrokes is 5
Maximum Number of A's with 6 keystrokes is 6
Maximum Number of A's with 7 keystrokes is 9
Maximum Number of A's with 8 keystrokes is 12
Maximum Number of A's with 9 keystrokes is 16
Maximum Number of A's with 10 keystrokes is 20
Maximum Number of A's with 11 keystrokes is 27
Maximum Number of A's with 12 keystrokes is 36
Maximum Number of A's with 13 keystrokes is 48
Maximum Number of A's with 14 keystrokes is 64
Maximum Number of A's with 15 keystrokes is 81
Maximum Number of A's with 16 keystrokes is 108
Maximum Number of A's with 17 keystrokes is 144
Maximum Number of A's with 18 keystrokes is 192
Maximum Number of A's with 19 keystrokes is 256
Maximum Number of A's with 20 keystrokes is 324
Thanks to Sahil for providing the above approach to solve this problem.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Sam007
sahilshelangia
ukasp
princiraj1992
aman neekhara
SahilSingh3
princi singh
ashutosh450
SHUBHAMSINGH10
avanitrachhadiya2155
rag2127
rohitsingh07052
surinderdawra388
kk9826225
Amazon
Google
Paytm
Dynamic Programming
Recursion
Paytm
Amazon
Google
Dynamic Programming
Recursion
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Find if there is a path between two vertices in an undirected graph
Count number of binary strings without consecutive 1's
Optimal Substructure Property in Dynamic Programming | DP-2
Unique paths in a Grid with Obstacles
How to solve a Dynamic Programming Problem ?
Write a program to print all permutations of a given string
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Recursion
Program for Tower of Hanoi
Backtracking | Introduction | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 Feb, 2022"
},
{
"code": null,
"e": 178,
"s": 52,
"text": "This is a famous interview question asked in Google, Paytm and many other company interviews. Below is the problem statement."
},
{
"code": null,
"e": 703,
"s": 178,
"text": "Imagine you have a special keyboard with the following keys: \nKey 1: Prints 'A' on screen\nKey 2: (Ctrl-A): Select screen\nKey 3: (Ctrl-C): Copy selection to buffer\nKey 4: (Ctrl-V): Print buffer on screen appending it\n after what has already been printed. \n\nIf you can only press the keyboard for N times (with the above four\nkeys), write a program to produce maximum numbers of A's. That is to\nsay, the input parameter is N (No. of keys that you can press), the \noutput is M (No. of As that you can produce)."
},
{
"code": null,
"e": 714,
"s": 703,
"text": "Examples: "
},
{
"code": null,
"e": 1128,
"s": 714,
"text": "Input: N = 3\nOutput: 3\nWe can at most get 3 A's on screen by pressing \nfollowing key sequence.\nA, A, A\n\nInput: N = 7\nOutput: 9\nWe can at most get 9 A's on screen by pressing \nfollowing key sequence.\nA, A, A, Ctrl A, Ctrl C, Ctrl V, Ctrl V\n\nInput: N = 11\nOutput: 27\nWe can at most get 27 A's on screen by pressing \nfollowing key sequence.\nA, A, A, Ctrl A, Ctrl C, Ctrl V, Ctrl V, Ctrl A, \nCtrl C, Ctrl V, Ctrl V"
},
{
"code": null,
"e": 2073,
"s": 1128,
"text": "Below are few important points to note.a) For N < 7, the output is N itself. b) Ctrl V can be used multiple times to print current buffer (See last two examples above). The idea is to compute the optimal string length for N keystrokes by using a simple insight. The sequence of N keystrokes which produces an optimal string length will end with a suffix of Ctrl-A, a Ctrl-C, followed by only Ctrl-V’s . (For N > 6)The task is to find out the break=point after which we get the above suffix of keystrokes. Definition of a breakpoint is that instance after which we need to only press Ctrl-A, Ctrl-C once and the only Ctrl-V’s afterward to generate the optimal length. If we loop from N-3 to 1 and choose each of these values for the break-point, and compute that optimal string they would produce. Once the loop ends, we will have the maximum of the optimal lengths for various breakpoints, thereby giving us the optimal length for N keystrokes."
},
{
"code": null,
"e": 2120,
"s": 2073,
"text": "Below is implementation based on above idea. "
},
{
"code": null,
"e": 2126,
"s": 2120,
"text": "C++14"
},
{
"code": null,
"e": 2128,
"s": 2126,
"text": "C"
},
{
"code": null,
"e": 2133,
"s": 2128,
"text": "Java"
},
{
"code": null,
"e": 2141,
"s": 2133,
"text": "Python3"
},
{
"code": null,
"e": 2144,
"s": 2141,
"text": "C#"
},
{
"code": null,
"e": 2148,
"s": 2144,
"text": "PHP"
},
{
"code": null,
"e": 2159,
"s": 2148,
"text": "Javascript"
},
{
"code": "/* A recursive C++ program to print maximum number of A's usingfollowing four keys */#include <bits/stdc++.h>using namespace std; // A recursive function that returns the optimal length string// for N keystrokesint findoptimal(int N){ // The optimal string length is N when N is smaller than 7 if (N <= 6) return N; // Initialize result int max = 0; // TRY ALL POSSIBLE BREAK-POINTS // For any keystroke N, we need to loop from N-3 keystrokes // back to 1 keystroke to find a breakpoint 'b' after which we // will have Ctrl-A, Ctrl-C and then only Ctrl-V all the way. int b; for (b = N - 3; b >= 1; b--) { // If the breakpoint is s at b'th keystroke then // the optimal string would have length // (n-b-1)*screen[b-1]; int curr = (N - b - 1) * findoptimal(b); if (curr > max) max = curr; } return max;} // Driver programint main(){ int N; // for the rest of the array we will reply on the previous // entries to compute new ones for (N = 1; N <= 20; N++) cout << \"Maximum Number of A's with \" << N << \" keystrokes is \" << findoptimal(N) << endl;} // This code is contributed by shubhamsingh10",
"e": 3371,
"s": 2159,
"text": null
},
{
"code": "/* A recursive C program to print maximum number of A's using following four keys */#include <stdio.h> // A recursive function that returns the optimal length string// for N keystrokesint findoptimal(int N){ // The optimal string length is N when N is smaller than 7 if (N <= 6) return N; // Initialize result int max = 0; // TRY ALL POSSIBLE BREAK-POINTS // For any keystroke N, we need to loop from N-3 keystrokes // back to 1 keystroke to find a breakpoint 'b' after which we // will have Ctrl-A, Ctrl-C and then only Ctrl-V all the way. int b; for (b = N - 3; b >= 1; b--) { // If the breakpoint is s at b'th keystroke then // the optimal string would have length // (n-b-1)*screen[b-1]; int curr = (N - b - 1) * findoptimal(b); if (curr > max) max = curr; } return max;} // Driver programint main(){ int N; // for the rest of the array we will reply on the previous // entries to compute new ones for (N = 1; N <= 20; N++) printf(\"Maximum Number of A's with %d keystrokes is %d\\n\", N, findoptimal(N));}",
"e": 4506,
"s": 3371,
"text": null
},
{
"code": "/* A recursive Java program to print maximum number of A's using following four keys */import java.io.*; class GFG { // A recursive function that returns // the optimal length string for N keystrokes static int findoptimal(int N) { // The optimal string length is N // when N is smaller than 7 if (N <= 6) return N; // Initialize result int max = 0; // TRY ALL POSSIBLE BREAK-POINTS // For any keystroke N, we need to // loop from N-3 keystrokes back to // 1 keystroke to find a breakpoint // 'b' after which we will have Ctrl-A, // Ctrl-C and then only Ctrl-V all the way. int b; for (b = N - 3; b >= 1; b--) { // If the breakpoint is s at b'th // keystroke then the optimal string // would have length // (n-b-1)*screen[b-1]; int curr = (N - b - 1) * findoptimal(b); if (curr > max) max = curr; } return max; } // Driver program public static void main(String[] args) { int N; // for the rest of the array we // will reply on the previous // entries to compute new ones for (N = 1; N <= 20; N++) System.out.println(\"Maximum Number of A's with keystrokes is \" + N + findoptimal(N)); }} // This code is contributed by vt_m.",
"e": 5908,
"s": 4506,
"text": null
},
{
"code": "# A recursive Python3 program to print maximum# number of A's using following four keys # A recursive function that returns# the optimal length string for N keystrokes def findoptimal(N): # The optimal string length is # N when N is smaller than if N<= 6: return N # Initialize result maxi = 0 # TRY ALL POSSIBLE BREAK-POINTS # For any keystroke N, we need # to loop from N-3 keystrokes # back to 1 keystroke to find # a breakpoint 'b' after which we # will have Ctrl-A, Ctrl-C and then # only Ctrl-V all the way. for b in range(N-3, 0, -1): curr =(N-b-1)*findoptimal(b) if curr>maxi: maxi = curr return maxi# Driver programif __name__=='__main__': # for the rest of the array we will# reply on the previous# entries to compute new ones for n in range(1, 21): print('Maximum Number of As with ', n, 'keystrokes is ', findoptimal(n)) # this code is contributed by sahilshelangia",
"e": 6894,
"s": 5908,
"text": null
},
{
"code": "/* A recursive C# programto print maximum numberof A's using followingfour keys */using System; class GFG { // A recursive function that // returns the optimal length // string for N keystrokes static int findoptimal(int N) { // The optimal string length // is N when N is smaller than 7 if (N <= 6) return N; // Initialize result int max = 0; // TRY ALL POSSIBLE BREAK-POINTS // For any keystroke N, we need // to loop from N-3 keystrokes // back to 1 keystroke to find // a breakpoint 'b' after which // we will have Ctrl-A, Ctrl-C // and then only Ctrl-V all the way. int b; for (b = N - 3; b >= 1; b--) { // If the breakpoint is s // at b'th keystroke then // the optimal string would // have length (n-b-1)*screen[b-1]; int curr = (N - b - 1) * findoptimal(b); if (curr > max) max = curr; } return max; } // Driver code static void Main() { int N; // for the rest of the array // we will reply on the // previous entries to compute // new ones for (N = 1; N <= 20; N++) Console.WriteLine(\"Maximum Number of A's with \" + N + \" keystrokes is \" + findoptimal(N)); }} // This code is contributed by Sam007",
"e": 8292,
"s": 6894,
"text": null
},
{
"code": "<?php/* A recursive PHP program to print maximum number of A's usingfollowing four keys */ // A recursive function that returns the optimal// length string for N keystrokesfunction findoptimal($N){ // The optimal string length is // N when N is smaller than 7 if ($N <= 6) return $N; // Initialize result $max = 0; // TRY ALL POSSIBLE BREAK-POINTS // For any keystroke N, we need to loop from N-3 keystrokes // back to 1 keystroke to find a breakpoint 'b' after which we // will have Ctrl-A, Ctrl-C and then only Ctrl-V all the way. $b; for ($b = $N - 3; $b >= 1; $b -= 1) { // If the breakpoint is s at b'th keystroke then // the optimal string would have length // (n-b-1)*screen[b-1]; $curr = ($N - $b - 1) * findoptimal($b); if ($curr > $max) $max = $curr; } return $max;} // Driver code$N; // for the rest of the array we will reply on the previous// entries to compute new onesfor ($N = 1; $N <= 20; $N += 1) echo(\"Maximum Number of A's with\" .$N.\"keystrokes is \".findoptimal($N).\"\\n\"); // This code is contributed by aman neekhara?>",
"e": 9464,
"s": 8292,
"text": null
},
{
"code": "<script> // A recursive Javascript program to print// maximum number of A's using// following four keys // A recursive function that returns the// optimal length string for N keystrokesfunction findoptimal(N){ // The optimal string length is N // when N is smaller than 7 if (N <= 6) return N; // Initialize result let max = 0; // TRY ALL POSSIBLE BREAK-POINTS // For any keystroke N, we need to // loop from N-3 keystrokes back to // 1 keystroke to find a breakpoint // 'b' after which we will have Ctrl-A, // Ctrl-C and then only Ctrl-V all the way. let b; for(b = N - 3; b >= 1; b--) { // If the breakpoint is s at b'th // keystroke then the optimal string // would have length // (n-b-1)*screen[b-1]; let curr = (N - b - 1) * findoptimal(b); if (curr > max) max = curr; } return max;} // Driver codelet N; // For the rest of the array we// will reply on the previous// entries to compute new onesfor(N = 1; N <= 20; N++) document.write(\"Maximum Number of A's with \"+ N + \" keystrokes is \" + findoptimal(N) + \"<br>\"); // This code is contributed by avanitrachhadiya2155 </script>",
"e": 10733,
"s": 9464,
"text": null
},
{
"code": null,
"e": 10742,
"s": 10733,
"text": "Output: "
},
{
"code": null,
"e": 11671,
"s": 10742,
"text": "Maximum Number of A's with 1 keystrokes is 1\nMaximum Number of A's with 2 keystrokes is 2\nMaximum Number of A's with 3 keystrokes is 3\nMaximum Number of A's with 4 keystrokes is 4\nMaximum Number of A's with 5 keystrokes is 5\nMaximum Number of A's with 6 keystrokes is 6\nMaximum Number of A's with 7 keystrokes is 9\nMaximum Number of A's with 8 keystrokes is 12\nMaximum Number of A's with 9 keystrokes is 16\nMaximum Number of A's with 10 keystrokes is 20\nMaximum Number of A's with 11 keystrokes is 27\nMaximum Number of A's with 12 keystrokes is 36\nMaximum Number of A's with 13 keystrokes is 48\nMaximum Number of A's with 14 keystrokes is 64\nMaximum Number of A's with 15 keystrokes is 81\nMaximum Number of A's with 16 keystrokes is 108\nMaximum Number of A's with 17 keystrokes is 144\nMaximum Number of A's with 18 keystrokes is 192\nMaximum Number of A's with 19 keystrokes is 256\nMaximum Number of A's with 20 keystrokes is 324"
},
{
"code": null,
"e": 11872,
"s": 11671,
"text": "The above function computes the same subproblems again and again. Recomputations of same subproblems can be avoided by storing the solutions to subproblems and solving problems in a bottom-up manner. "
},
{
"code": null,
"e": 12000,
"s": 11872,
"text": "Below is Dynamic Programming based C implementation where an auxiliary array screen[N] is used to store result of subproblems. "
},
{
"code": null,
"e": 12004,
"s": 12000,
"text": "C++"
},
{
"code": null,
"e": 12006,
"s": 12004,
"text": "C"
},
{
"code": null,
"e": 12011,
"s": 12006,
"text": "Java"
},
{
"code": null,
"e": 12019,
"s": 12011,
"text": "Python3"
},
{
"code": null,
"e": 12022,
"s": 12019,
"text": "C#"
},
{
"code": null,
"e": 12033,
"s": 12022,
"text": "Javascript"
},
{
"code": "/* A Dynamic Programming based C program to find maximum number of A'sthat can be printed using four keys */#include <iostream>using namespace std; // this function returns the optimal length string for N keystrokesint findoptimal(int N){ // The optimal string length is N when N is smaller than 7 if (N <= 6) return N; // An array to store result of subproblems int screen[N]; int b; // To pick a breakpoint // Initializing the optimal lengths array for until 6 input // strokes. int n; for (n = 1; n <= 6; n++) screen[n - 1] = n; // Solve all subproblems in bottom manner for (n = 7; n <= N; n++) { // Initialize length of optimal string for n keystrokes screen[n - 1] = 0; // For any keystroke n, we need to loop from n-3 keystrokes // back to 1 keystroke to find a breakpoint 'b' after which we // will have ctrl-a, ctrl-c and then only ctrl-v all the way. for (b = n - 3; b >= 1; b--) { // if the breakpoint is at b'th keystroke then // the optimal string would have length // (n-b-1)*screen[b-1]; int curr = (n - b - 1) * screen[b - 1]; if (curr > screen[n - 1]) screen[n - 1] = curr; } } return screen[N - 1];} // Driver programint main(){ int N; // for the rest of the array we will reply on the previous // entries to compute new ones for (N = 1; N <= 20; N++) cout << \"Maximum Number of A's with \"<<N<<\" keystrokes is \" << findoptimal(N) << endl;} //This is contributed by shubhamsingh10",
"e": 13637,
"s": 12033,
"text": null
},
{
"code": "/* A Dynamic Programming based C program to find maximum number of A's that can be printed using four keys */#include <stdio.h> // this function returns the optimal length string for N keystrokesint findoptimal(int N){ // The optimal string length is N when N is smaller than 7 if (N <= 6) return N; // An array to store result of subproblems int screen[N]; int b; // To pick a breakpoint // Initializing the optimal lengths array for until 6 input // strokes. int n; for (n = 1; n <= 6; n++) screen[n - 1] = n; // Solve all subproblems in bottom manner for (n = 7; n <= N; n++) { // Initialize length of optimal string for n keystrokes screen[n - 1] = 0; // For any keystroke n, we need to loop from n-3 keystrokes // back to 1 keystroke to find a breakpoint 'b' after which we // will have ctrl-a, ctrl-c and then only ctrl-v all the way. for (b = n - 3; b >= 1; b--) { // if the breakpoint is at b'th keystroke then // the optimal string would have length // (n-b-1)*screen[b-1]; int curr = (n - b - 1) * screen[b - 1]; if (curr > screen[n - 1]) screen[n - 1] = curr; } } return screen[N - 1];} // Driver programint main(){ int N; // for the rest of the array we will reply on the previous // entries to compute new ones for (N = 1; N <= 20; N++) printf(\"Maximum Number of A's with %d keystrokes is %d\\n\", N, findoptimal(N));}",
"e": 15181,
"s": 13637,
"text": null
},
{
"code": "/* A Dynamic Programming based C program to find maximum number of A's that can be printed using four keys */import java.io.*; class GFG { // this function returns the optimal // length string for N keystrokes static int findoptimal(int N) { // The optimal string length is N // when N is smaller than 7 if (N <= 6) return N; // An array to store result // of subproblems int screen[] = new int[N]; int b; // To pick a breakpoint // Initializing the optimal lengths // array for until 6 input strokes int n; for (n = 1; n <= 6; n++) screen[n - 1] = n; // Solve all subproblems in bottom manner for (n = 7; n <= N; n++) { // Initialize length of optimal // string for n keystrokes screen[n - 1] = 0; // For any keystroke n, we need // to loop from n-3 keystrokes // back to 1 keystroke to find // a breakpoint 'b' after which we // will have ctrl-a, ctrl-c and // then only ctrl-v all the way. for (b = n - 3; b >= 1; b--) { // if the breakpoint is // at b'th keystroke then // the optimal string would // have length // (n-b-1)*screen[b-1]; int curr = (n - b - 1) * screen[b - 1]; if (curr > screen[n - 1]) screen[n - 1] = curr; } } return screen[N - 1]; } // Driver program public static void main(String[] args) { int N; // for the rest of the array we will reply on the previous // entries to compute new ones for (N = 1; N <= 20; N++) System.out.println(\"Maximum Number of A's with keystrokes is \" + N + findoptimal(N)); }} // This article is contributed by vt_m.",
"e": 17102,
"s": 15181,
"text": null
},
{
"code": "# A Dynamic Programming based Python program# to find maximum number of A's# that can be printed using four keys # this function returns the optimal# length string for N keystrokesdef findoptimal(N): # The optimal string length is # N when N is smaller than 7 if (N <= 6): return N # An array to store result of # subproblems screen = [0]*N # Initializing the optimal lengths # array for until 6 input # strokes. for n in range(1, 7): screen[n-1] = n # Solve all subproblems in bottom manner for n in range(7, N + 1): # Initialize length of optimal # string for n keystrokes screen[n-1] = 0 # For any keystroke n, we need to # loop from n-3 keystrokes # back to 1 keystroke to find a breakpoint # 'b' after which we # will have ctrl-a, ctrl-c and then only # ctrl-v all the way. for b in range(n-3, 0, -1): # if the breakpoint is at b'th keystroke then # the optimal string would have length # (n-b-1)*screen[b-1]; curr = (n-b-1)*screen[b-1] if (curr > screen[n-1]): screen[n-1] = curr return screen[N-1] # Driver programif __name__ == \"__main__\": # for the rest of the array we # will reply on the previous # entries to compute new ones for N in range(1, 21): print(\"Maximum Number of A's with \", N, \" keystrokes is \", findoptimal(N)) # this code is contributed by# ChitraNayal",
"e": 18642,
"s": 17102,
"text": null
},
{
"code": "/* A Dynamic Programming based C#program to find maximum numberof A's that can be printed usingfour keys */using System;public class GFG { // this function returns the optimal // length string for N keystrokes static int findoptimal(int N) { // The optimal string length is N // when N is smaller than 7 if (N <= 6) return N; // An array to store result // of subproblems int[] screen = new int[N]; int b; // To pick a breakpoint // Initializing the optimal lengths // array for until 6 input strokes int n; for (n = 1; n <= 6; n++) screen[n - 1] = n; // Solve all subproblems in bottom manner for (n = 7; n <= N; n++) { // Initialize length of optimal // string for n keystrokes screen[n - 1] = 0; // For any keystroke n, we need // to loop from n-3 keystrokes // back to 1 keystroke to find // a breakpoint 'b' after which we // will have ctrl-a, ctrl-c and // then only ctrl-v all the way. for (b = n - 3; b >= 1; b--) { // if the breakpoint is // at b'th keystroke then // the optimal string would // have length // (n-b-1)*screen[b-1]; int curr = (n - b - 1) * screen[b - 1]; if (curr > screen[n - 1]) screen[n - 1] = curr; } } return screen[N - 1]; } // Driver program public static void Main(String[] args) { int N; // for the rest of the array we will reply on the previous // entries to compute new ones for (N = 1; N <= 20; N++) Console.WriteLine(\"Maximum Number of A's with {0} keystrokes is {1}\\n\", N, findoptimal(N)); }} // This code is contributed by PrinciRaj1992",
"e": 20597,
"s": 18642,
"text": null
},
{
"code": "<script> // A Dynamic Programming based javascript// program to find maximum number// of A's that can be printed using// four keys // This function returns the optimal// length string for N keystrokes function findoptimal(N){ // The optimal string length is N // when N is smaller than 7 if (N <= 6) return N; // An array to store result // of subproblems let screen = new Array(N); for(let i = 0; i < N; i++) { screen[i] = 0; } // To pick a breakpoint let b; // Initializing the optimal lengths // array for until 6 input strokes let n; for(n = 1; n <= 6; n++) screen[n - 1] = n; // Solve all subproblems in bottom manner for(n = 7; n <= N; n++) { // Initialize length of optimal // string for n keystrokes screen[n - 1] = 0; // For any keystroke n, we need // to loop from n-3 keystrokes // back to 1 keystroke to find // a breakpoint 'b' after which we // will have ctrl-a, ctrl-c and // then only ctrl-v all the way. for(b = n - 3; b >= 1; b--) { // If the breakpoint is // at b'th keystroke then // the optimal string would // have length // (n-b-1)*screen[b-1]; let curr = (n - b - 1) * screen[b - 1]; if (curr > screen[n - 1]) screen[n - 1] = curr; } } return screen[N - 1];} // Driver codelet N;for(N = 1; N <= 20; N++) document.write(\"Maximum Number of A's with \" + N + \" keystrokes is \" + findoptimal(N) + \"<br>\"); // This code is contributed by rag2127 </script>",
"e": 22317,
"s": 20597,
"text": null
},
{
"code": null,
"e": 22326,
"s": 22317,
"text": "Output: "
},
{
"code": null,
"e": 23255,
"s": 22326,
"text": "Maximum Number of A's with 1 keystrokes is 1\nMaximum Number of A's with 2 keystrokes is 2\nMaximum Number of A's with 3 keystrokes is 3\nMaximum Number of A's with 4 keystrokes is 4\nMaximum Number of A's with 5 keystrokes is 5\nMaximum Number of A's with 6 keystrokes is 6\nMaximum Number of A's with 7 keystrokes is 9\nMaximum Number of A's with 8 keystrokes is 12\nMaximum Number of A's with 9 keystrokes is 16\nMaximum Number of A's with 10 keystrokes is 20\nMaximum Number of A's with 11 keystrokes is 27\nMaximum Number of A's with 12 keystrokes is 36\nMaximum Number of A's with 13 keystrokes is 48\nMaximum Number of A's with 14 keystrokes is 64\nMaximum Number of A's with 15 keystrokes is 81\nMaximum Number of A's with 16 keystrokes is 108\nMaximum Number of A's with 17 keystrokes is 144\nMaximum Number of A's with 18 keystrokes is 192\nMaximum Number of A's with 19 keystrokes is 256\nMaximum Number of A's with 20 keystrokes is 324"
},
{
"code": null,
"e": 23626,
"s": 23255,
"text": "Thanks to Gaurav Saxena for providing the above approach to solve this problem.As the number of A’s become large, the effect of pressing Ctrl-V more than 3 times starts to become insubstantial as compared to just pressing Ctrl-A, Ctrl-C and Ctrl-V again. So, the above code can be made more efficient by checking the effect of pressing Ctrl-V for 1, 2, and 3 times only."
},
{
"code": null,
"e": 23630,
"s": 23626,
"text": "C++"
},
{
"code": null,
"e": 23635,
"s": 23630,
"text": "Java"
},
{
"code": null,
"e": 23643,
"s": 23635,
"text": "Python3"
},
{
"code": null,
"e": 23646,
"s": 23643,
"text": "C#"
},
{
"code": null,
"e": 23657,
"s": 23646,
"text": "Javascript"
},
{
"code": "// A Dynamic Programming based C++ program to find maximum// number of A's that can be printed using four keys #include <bits/stdc++.h>using namespace std; // This function returns the optimal length string for N keystrokesint findoptimal(int N){ // The optimal string length is N when N is smaller than 7 if (N <= 6) return N; // An array to store result of subproblems int screen[N]; int b; // To pick a breakpoint // Initializing the optimal lengths array for until 6 input // strokes. int n; for (n = 1; n <= 6; n++) screen[n - 1] = n; // Solve all subproblems in bottom-up manner for (n = 7; n <= N; n++) { // for any keystroke n, we will need to choose between:- // 1. pressing Ctrl-V once after copying the // A's obtained by n-3 keystrokes. // 2. pressing Ctrl-V twice after copying the A's // obtained by n-4 keystrokes. // 3. pressing Ctrl-V thrice after copying the A's // obtained by n-5 keystrokes. screen[n - 1] = max(2 * screen[n - 4], max(3 * screen[n - 5],4 * screen[n - 6])); } return screen[N - 1];} // Driver programint main(){ int N; // for the rest of the array we will reply on the previous // entries to compute new ones for (N = 1; N <= 20; N++) printf(\"Maximum Number of A's with %d keystrokes is %d\\n\", N, findoptimal(N));}",
"e": 25086,
"s": 23657,
"text": null
},
{
"code": "// A Dynamic Programming based Java program// to find maximum number of A's that// can be printed using four keysclass GFG{ // This function returns the optimal length// string for N keystrokesstatic int findoptimal(int N){ // The optimal string length is N // when N is smaller than 7 if (N <= 6) return N; // An array to store result of subproblems int []screen = new int[N]; int b; // To pick a breakpoint // Initializing the optimal lengths array // for uptil 6 input strokes. int n; for (n = 1; n <= 6; n++) screen[n - 1] = n; // Solve all subproblems in bottom-up manner for (n = 7; n <= N; n++) { // for any keystroke n, we will need to choose between:- // 1. pressing Ctrl-V once after copying the // A's obtained by n-3 keystrokes. // 2. pressing Ctrl-V twice after copying the A's // obtained by n-4 keystrokes. // 3. pressing Ctrl-V thrice after copying the A's // obtained by n-5 keystrokes. screen[n - 1] = Math.max(2 * screen[n - 4], Math.max(3 * screen[n - 5], 4 * screen[n - 6])); } return screen[N - 1];} // Driver Codepublic static void main(String[] args){ int N; // for the rest of the array we will reply // on the previous entries to compute new ones for (N = 1; N <= 20; N++) System.out.printf(\"Maximum Number of A's with\" + \" %d keystrokes is %d\\n\", N, findoptimal(N)); }} // This code is contributed by Princi Singh",
"e": 26693,
"s": 25086,
"text": null
},
{
"code": "# A Dynamic Programming based Python3 program# to find maximum number of A's# that can be printed using four keys # this function returns the optimal# length string for N keystrokesdef findoptimal(N): # The optimal string length is # N when N is smaller than 7 if (N <= 6): return N # An array to store result of # subproblems screen = [0] * N # Initializing the optimal lengths # array for until 6 input # strokes. for n in range(1, 7): screen[n - 1] = n # Solve all subproblems in bottom manner for n in range(7, N + 1): # for any keystroke n, we will need to choose between:- # 1. pressing Ctrl-V once after copying the # A's obtained by n-3 keystrokes. # 2. pressing Ctrl-V twice after copying the A's # obtained by n-4 keystrokes. # 3. pressing Ctrl-V thrice after copying the A's # obtained by n-5 keystrokes. screen[n - 1] = max(2 * screen[n - 4], max(3 * screen[n - 5], 4 * screen[n - 6])); return screen[N - 1] # Driver Codeif __name__ == \"__main__\": # for the rest of the array we # will reply on the previous # entries to compute new ones for N in range(1, 21): print(\"Maximum Number of A's with \", N, \" keystrokes is \", findoptimal(N)) # This code is contributed by ashutosh450",
"e": 28104,
"s": 26693,
"text": null
},
{
"code": "// A Dynamic Programming based C# program// to find maximum number of A's that// can be printed using four keysusing System; class GFG{ // This function returns the optimal length// string for N keystrokesstatic int findoptimal(int N){ // The optimal string length is N // when N is smaller than 7 if (N <= 6) return N; // An array to store result of subproblems int []screen = new int[N]; // Initializing the optimal lengths array // for uptil 6 input strokes. int n; for (n = 1; n <= 6; n++) screen[n - 1] = n; // Solve all subproblems in bottom-up manner for (n = 7; n <= N; n++) { // for any keystroke n, we will need to choose between:- // 1. pressing Ctrl-V once after copying the // A's obtained by n-3 keystrokes. // 2. pressing Ctrl-V twice after copying the A's // obtained by n-4 keystrokes. // 3. pressing Ctrl-V thrice after copying the A's // obtained by n-5 keystrokes. screen[n - 1] = Math.Max(2 * screen[n - 4], Math.Max(3 * screen[n - 5], 4 * screen[n - 6])); } return screen[N - 1];} // Driver Codepublic static void Main(String[] args){ int N; // for the rest of the array we will reply // on the previous entries to compute new ones for (N = 1; N <= 20; N++) Console.Write(\"Maximum Number of A's with\" + \" {0} keystrokes is {1}\\n\", N, findoptimal(N)); }} // This code is contributed by PrinciRaj1992",
"e": 29682,
"s": 28104,
"text": null
},
{
"code": "<script> // A Dynamic Programming based// JavaScript program to find maximum// number of A's that can be printed// using four keys // This function returns the optimal// length string for N keystrokesfunction findoptimal(N){ // The optimal string length is N // when N is smaller than 7 if (N <= 6) return N; // An array to store result // of subproblems let screen = []; let b; // To pick a breakpoint // Initializing the optimal lengths // array for until 6 input // strokes. let n; for (n = 1; n <= 6; n++) screen[n - 1] = n; // Solve all subproblems in bottom-up manner for (n = 7; n <= N; n++) { // for any keystroke n, we will // need to choose between:- // 1. pressing Ctrl-V once // after copying the // A's obtained by n-3 keystrokes. // 2. pressing Ctrl-V twice after // copying the A's // obtained by n-4 keystrokes. // 3. pressing Ctrl-V thrice // after copying the A's // obtained by n-5 keystrokes. screen[n - 1] = Math.max(2 * screen[n - 4], Math.max(3 * screen[n - 5],4 * screen[n - 6])); } return screen[N - 1];} // Driver programlet N;// for the rest of the array we will reply on the previous// entries to compute new onesfor (N = 1; N <= 20; N++) document.write( \"Maximum Number of A's with \"+ N +\" keystrokes is \" +findoptimal(N)+\"<br>\" ); </script>",
"e": 31142,
"s": 29682,
"text": null
},
{
"code": null,
"e": 31151,
"s": 31142,
"text": "Output: "
},
{
"code": null,
"e": 32080,
"s": 31151,
"text": "Maximum Number of A's with 1 keystrokes is 1\nMaximum Number of A's with 2 keystrokes is 2\nMaximum Number of A's with 3 keystrokes is 3\nMaximum Number of A's with 4 keystrokes is 4\nMaximum Number of A's with 5 keystrokes is 5\nMaximum Number of A's with 6 keystrokes is 6\nMaximum Number of A's with 7 keystrokes is 9\nMaximum Number of A's with 8 keystrokes is 12\nMaximum Number of A's with 9 keystrokes is 16\nMaximum Number of A's with 10 keystrokes is 20\nMaximum Number of A's with 11 keystrokes is 27\nMaximum Number of A's with 12 keystrokes is 36\nMaximum Number of A's with 13 keystrokes is 48\nMaximum Number of A's with 14 keystrokes is 64\nMaximum Number of A's with 15 keystrokes is 81\nMaximum Number of A's with 16 keystrokes is 108\nMaximum Number of A's with 17 keystrokes is 144\nMaximum Number of A's with 18 keystrokes is 192\nMaximum Number of A's with 19 keystrokes is 256\nMaximum Number of A's with 20 keystrokes is 324"
},
{
"code": null,
"e": 32276,
"s": 32080,
"text": "Thanks to Sahil for providing the above approach to solve this problem.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 32283,
"s": 32276,
"text": "Sam007"
},
{
"code": null,
"e": 32298,
"s": 32283,
"text": "sahilshelangia"
},
{
"code": null,
"e": 32304,
"s": 32298,
"text": "ukasp"
},
{
"code": null,
"e": 32318,
"s": 32304,
"text": "princiraj1992"
},
{
"code": null,
"e": 32332,
"s": 32318,
"text": "aman neekhara"
},
{
"code": null,
"e": 32344,
"s": 32332,
"text": "SahilSingh3"
},
{
"code": null,
"e": 32357,
"s": 32344,
"text": "princi singh"
},
{
"code": null,
"e": 32369,
"s": 32357,
"text": "ashutosh450"
},
{
"code": null,
"e": 32384,
"s": 32369,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 32405,
"s": 32384,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 32413,
"s": 32405,
"text": "rag2127"
},
{
"code": null,
"e": 32429,
"s": 32413,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 32446,
"s": 32429,
"text": "surinderdawra388"
},
{
"code": null,
"e": 32456,
"s": 32446,
"text": "kk9826225"
},
{
"code": null,
"e": 32463,
"s": 32456,
"text": "Amazon"
},
{
"code": null,
"e": 32470,
"s": 32463,
"text": "Google"
},
{
"code": null,
"e": 32476,
"s": 32470,
"text": "Paytm"
},
{
"code": null,
"e": 32496,
"s": 32476,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 32506,
"s": 32496,
"text": "Recursion"
},
{
"code": null,
"e": 32512,
"s": 32506,
"text": "Paytm"
},
{
"code": null,
"e": 32519,
"s": 32512,
"text": "Amazon"
},
{
"code": null,
"e": 32526,
"s": 32519,
"text": "Google"
},
{
"code": null,
"e": 32546,
"s": 32526,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 32556,
"s": 32546,
"text": "Recursion"
},
{
"code": null,
"e": 32654,
"s": 32556,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32722,
"s": 32654,
"text": "Find if there is a path between two vertices in an undirected graph"
},
{
"code": null,
"e": 32777,
"s": 32722,
"text": "Count number of binary strings without consecutive 1's"
},
{
"code": null,
"e": 32837,
"s": 32777,
"text": "Optimal Substructure Property in Dynamic Programming | DP-2"
},
{
"code": null,
"e": 32875,
"s": 32837,
"text": "Unique paths in a Grid with Obstacles"
},
{
"code": null,
"e": 32920,
"s": 32875,
"text": "How to solve a Dynamic Programming Problem ?"
},
{
"code": null,
"e": 32980,
"s": 32920,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 33065,
"s": 32980,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 33075,
"s": 33065,
"text": "Recursion"
},
{
"code": null,
"e": 33102,
"s": 33075,
"text": "Program for Tower of Hanoi"
}
] |
Sum of the nodes of a Singly Linked List in C Program | A singly linked list is a data structure in which an element has two parts one is the value and other is the link to the next element. So to find the sum of all elements of the singly linked list, we have to navigate to each node of the linked list and add the element's value to a sum variable.
For example
Suppose we have a linked list: 2 -> 27 -> 32 -> 1 -> 5
sum = 2 + 27 + 32 + 1 + 5 = 67.
This can be done by using two methods :
Method 1 - Using a loop that loops over all the values of the linked list and finds the sum.
The loop runs till the end of the linked list i.e. when the pointer of an element points to null, this loop will run and find the sum of values of each element.
#include <iostream>
using namespace std;
struct Node {
int data;
struct Node* next;
};
void push(struct Node** nodeH, int nodeval) {
struct Node* new_node = new Node;
new_node->data = nodeval;
new_node->next = (*nodeH);
(*nodeH) = new_node;
}
int main() {
struct Node* head = NULL;
int sum = 0;
push(&head, 95);
push(&head, 60);
push(&head, 87);
push(&head, 6);
push(&head, 12);
struct Node* ptr = head;
while (ptr != NULL) {
sum += ptr->data;
ptr = ptr->next;
}
cout << "Sum of nodes = "<< sum;
return 0;
}
Sum of nodes = 260
Method 2 - Using a recursive function that calls itself until the linked list has elements. The recursive function calls itself again and again. The call to the recursive function sends the next node values as a parameter along with the sum address location.
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node* next;
};
void push(struct Node** head_ref, int new_data) {
struct Node* new_node = new Node;
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void nodesum(struct Node* head, int* sum) {
if (!head)
return;
nodesum(head->next, sum);
*sum = *sum + head->data;
}
int main() {
struct Node* head = NULL;
int sum= 0;
push(&head, 95);
push(&head, 60);
push(&head, 87);
push(&head, 6);
push(&head, 12);
nodesum(head,&sum);
cout << "Sum of nodes = "<<sum;
return 0;
}
Sum of nodes = 260 | [
{
"code": null,
"e": 1483,
"s": 1187,
"text": "A singly linked list is a data structure in which an element has two parts one is the value and other is the link to the next element. So to find the sum of all elements of the singly linked list, we have to navigate to each node of the linked list and add the element's value to a sum variable."
},
{
"code": null,
"e": 1495,
"s": 1483,
"text": "For example"
},
{
"code": null,
"e": 1582,
"s": 1495,
"text": "Suppose we have a linked list: 2 -> 27 -> 32 -> 1 -> 5\nsum = 2 + 27 + 32 + 1 + 5 = 67."
},
{
"code": null,
"e": 1622,
"s": 1582,
"text": "This can be done by using two methods :"
},
{
"code": null,
"e": 1715,
"s": 1622,
"text": "Method 1 - Using a loop that loops over all the values of the linked list and finds the sum."
},
{
"code": null,
"e": 1876,
"s": 1715,
"text": "The loop runs till the end of the linked list i.e. when the pointer of an element points to null, this loop will run and find the sum of values of each element."
},
{
"code": null,
"e": 2450,
"s": 1876,
"text": "#include <iostream>\nusing namespace std;\nstruct Node {\n int data;\n struct Node* next;\n};\nvoid push(struct Node** nodeH, int nodeval) {\n struct Node* new_node = new Node;\n new_node->data = nodeval;\n new_node->next = (*nodeH);\n (*nodeH) = new_node;\n}\nint main() {\n struct Node* head = NULL;\n int sum = 0;\n push(&head, 95);\n push(&head, 60);\n push(&head, 87);\n push(&head, 6);\n push(&head, 12);\n struct Node* ptr = head;\n while (ptr != NULL) {\n sum += ptr->data;\n ptr = ptr->next;\n }\n cout << \"Sum of nodes = \"<< sum;\n return 0;\n}"
},
{
"code": null,
"e": 2469,
"s": 2450,
"text": "Sum of nodes = 260"
},
{
"code": null,
"e": 2728,
"s": 2469,
"text": "Method 2 - Using a recursive function that calls itself until the linked list has elements. The recursive function calls itself again and again. The call to the recursive function sends the next node values as a parameter along with the sum address location."
},
{
"code": null,
"e": 3366,
"s": 2728,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nstruct Node {\n int data;\n struct Node* next;\n};\nvoid push(struct Node** head_ref, int new_data) {\n struct Node* new_node = new Node;\n new_node->data = new_data;\n new_node->next = (*head_ref);\n (*head_ref) = new_node;\n}\nvoid nodesum(struct Node* head, int* sum) {\n if (!head)\n return;\n nodesum(head->next, sum);\n *sum = *sum + head->data;\n}\nint main() {\n struct Node* head = NULL;\n int sum= 0;\n push(&head, 95);\n push(&head, 60);\n push(&head, 87);\n push(&head, 6);\n push(&head, 12);\n nodesum(head,&sum);\n cout << \"Sum of nodes = \"<<sum;\n return 0;\n}"
},
{
"code": null,
"e": 3385,
"s": 3366,
"text": "Sum of nodes = 260"
}
] |
timetuple() Function Of Datetime.date Class In Python | 23 Aug, 2021
timetuple() method returns a time.struct time object which is a named tuple. A named tuple object has attributes that may be accessed by an index or a name. The struct time object has properties for both the date and time fields, as well as a flag that specifies whether or not Daylight Saving Time is in effect. The year, month, and day fields of the named tuple provided by the timetuple() method will be set according to the date object, but the hour, minutes, and seconds values will be set to zero. The DST flag on the returned object will be set to -1. The characteristics of the time.struct time object may be accessed by index or attribute name. The struct time object contains attributes for expressing both date and time fields, which are kept in tuples :
Example 1: timetuple() with current date.
Here we are going demonstrate timetuple() of the current date. The current date is allocated to the DateTime object, and the timetuple() function is used to retrieve the properties of the object in tuples, which are then shown. A loop may also be used to display the characteristics of object.
Python3
import datetime # creating current date objectcurrentDate = datetime.datetime.today() # datetime instance's attributes# are returned as a tuple.currentDateTimeTuple = currentDate.timetuple() # showing the object's tuplesprint(currentDateTimeTuple)print()print("Using a for loop, output the tuple values :") for value in currentDateTimeTuple: print(value)
Output:
time.struct_time(tm_year=2021, tm_mon=8, tm_mday=2, tm_hour=18, tm_min=32, tm_sec=56, tm_wday=0, tm_yday=214, tm_isdst=-1)
Using a for loop, output the tuple values :
2021
8
2
18
32
56
0
214
-1
Example 2: timetuple() with a specific date.
Consider another scenario in which we utilize a Christmas date. The DateTime object Christmas is created, and then the index of the tuple displays each property of that object.
Python3
import datetime # creating xmas date objectxmas = datetime.datetime(2021, 12, 25) # datetime instance's attributes# are returned as a tuple.xmasTimeTuple = xmas.timetuple() # showing the object's tuplesprint(xmasTimeTuple)
Output:
time.struct_time(tm_year=2021, tm_mon=12, tm_mday=25, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=359, tm_isdst=-1)
Picked
Python-datetime
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
Introduction To PYTHON
Python OOPs Concepts
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
Create a directory in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Aug, 2021"
},
{
"code": null,
"e": 794,
"s": 28,
"text": "timetuple() method returns a time.struct time object which is a named tuple. A named tuple object has attributes that may be accessed by an index or a name. The struct time object has properties for both the date and time fields, as well as a flag that specifies whether or not Daylight Saving Time is in effect. The year, month, and day fields of the named tuple provided by the timetuple() method will be set according to the date object, but the hour, minutes, and seconds values will be set to zero. The DST flag on the returned object will be set to -1. The characteristics of the time.struct time object may be accessed by index or attribute name. The struct time object contains attributes for expressing both date and time fields, which are kept in tuples :"
},
{
"code": null,
"e": 836,
"s": 794,
"text": "Example 1: timetuple() with current date."
},
{
"code": null,
"e": 1130,
"s": 836,
"text": "Here we are going demonstrate timetuple() of the current date. The current date is allocated to the DateTime object, and the timetuple() function is used to retrieve the properties of the object in tuples, which are then shown. A loop may also be used to display the characteristics of object."
},
{
"code": null,
"e": 1138,
"s": 1130,
"text": "Python3"
},
{
"code": "import datetime # creating current date objectcurrentDate = datetime.datetime.today() # datetime instance's attributes# are returned as a tuple.currentDateTimeTuple = currentDate.timetuple() # showing the object's tuplesprint(currentDateTimeTuple)print()print(\"Using a for loop, output the tuple values :\") for value in currentDateTimeTuple: print(value)",
"e": 1504,
"s": 1138,
"text": null
},
{
"code": null,
"e": 1512,
"s": 1504,
"text": "Output:"
},
{
"code": null,
"e": 1635,
"s": 1512,
"text": "time.struct_time(tm_year=2021, tm_mon=8, tm_mday=2, tm_hour=18, tm_min=32, tm_sec=56, tm_wday=0, tm_yday=214, tm_isdst=-1)"
},
{
"code": null,
"e": 1679,
"s": 1635,
"text": "Using a for loop, output the tuple values :"
},
{
"code": null,
"e": 1684,
"s": 1679,
"text": "2021"
},
{
"code": null,
"e": 1686,
"s": 1684,
"text": "8"
},
{
"code": null,
"e": 1688,
"s": 1686,
"text": "2"
},
{
"code": null,
"e": 1691,
"s": 1688,
"text": "18"
},
{
"code": null,
"e": 1694,
"s": 1691,
"text": "32"
},
{
"code": null,
"e": 1697,
"s": 1694,
"text": "56"
},
{
"code": null,
"e": 1699,
"s": 1697,
"text": "0"
},
{
"code": null,
"e": 1703,
"s": 1699,
"text": "214"
},
{
"code": null,
"e": 1706,
"s": 1703,
"text": "-1"
},
{
"code": null,
"e": 1751,
"s": 1706,
"text": "Example 2: timetuple() with a specific date."
},
{
"code": null,
"e": 1928,
"s": 1751,
"text": "Consider another scenario in which we utilize a Christmas date. The DateTime object Christmas is created, and then the index of the tuple displays each property of that object."
},
{
"code": null,
"e": 1936,
"s": 1928,
"text": "Python3"
},
{
"code": "import datetime # creating xmas date objectxmas = datetime.datetime(2021, 12, 25) # datetime instance's attributes# are returned as a tuple.xmasTimeTuple = xmas.timetuple() # showing the object's tuplesprint(xmasTimeTuple)",
"e": 2166,
"s": 1936,
"text": null
},
{
"code": null,
"e": 2174,
"s": 2166,
"text": "Output:"
},
{
"code": null,
"e": 2296,
"s": 2174,
"text": "time.struct_time(tm_year=2021, tm_mon=12, tm_mday=25, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=359, tm_isdst=-1)"
},
{
"code": null,
"e": 2303,
"s": 2296,
"text": "Picked"
},
{
"code": null,
"e": 2319,
"s": 2303,
"text": "Python-datetime"
},
{
"code": null,
"e": 2326,
"s": 2319,
"text": "Python"
},
{
"code": null,
"e": 2424,
"s": 2326,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2456,
"s": 2424,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2483,
"s": 2456,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2514,
"s": 2483,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2537,
"s": 2514,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2558,
"s": 2537,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2614,
"s": 2558,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2656,
"s": 2614,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2698,
"s": 2656,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2737,
"s": 2698,
"text": "Python | Get unique values from a list"
}
] |
interview-series-juspay | Practice | GeeksforGeeks | 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.
Some of the functionality of this site might not work properly if you have enabled AdBlocker or a similar extension.
Contest Home
Quiz
Coding Problems
Time Left :
:
:
:
Finish
Test
Contest Home
Quiz
Coding Problems
Finish Test
Error
Error
Reminder
Click on the menu '' button to finish the test.
* All fields are mandatory.
Instructions
Leaderboard
Summary
0
QUIZSCORE
Coding problem score has been deducted due to plagiarism.
CODING SCORE
0
RANK
You need to submit each quiz question after selecting the
option(s).
All Problems
Coding Score :
0
Solution Accepted
Solution Accepted
Wrong Answer
Wrong Answer
Submissions
Problem
Submissions
Expected Outcome - runs the test cases against the code of Online Judge.
My Output - runs the test cases against your code. | [
{
"code": null,
"e": 83,
"s": 20,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 268,
"s": 83,
"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": 552,
"s": 268,
"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": 698,
"s": 552,
"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": 775,
"s": 698,
"text": "You can view the solutions submitted by other users from the submission tab."
},
{
"code": null,
"e": 816,
"s": 775,
"text": "Make sure you are not using ad-blockers."
},
{
"code": null,
"e": 844,
"s": 816,
"text": "Disable browser extensions."
},
{
"code": null,
"e": 915,
"s": 844,
"text": "We recommend using latest version of your browser for best experience."
},
{
"code": null,
"e": 1102,
"s": 915,
"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."
},
{
"code": null,
"e": 1398,
"s": 1102,
"text": "Passing the Sample/Custom Test cases in coding problems does not guarantee the \n correctness of code. On submission, your code is tested against multiple test cases\n consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 1515,
"s": 1398,
"text": "Some of the functionality of this site might not work properly if you have enabled AdBlocker or a similar extension."
},
{
"code": null,
"e": 1574,
"s": 1515,
"text": "\n Contest Home\n "
},
{
"code": null,
"e": 1625,
"s": 1574,
"text": "\n Quiz\n "
},
{
"code": null,
"e": 1687,
"s": 1625,
"text": "\n Coding Problems\n "
},
{
"code": null,
"e": 1721,
"s": 1687,
"text": "\n Time Left :\n\n\n : \n\n : \n\n : \n\n\n\n"
},
{
"code": null,
"e": 1767,
"s": 1721,
"text": "\nFinish\n Test\n"
},
{
"code": null,
"e": 1826,
"s": 1767,
"text": "\n Contest Home\n "
},
{
"code": null,
"e": 1885,
"s": 1826,
"text": "\n Quiz\n "
},
{
"code": null,
"e": 1955,
"s": 1885,
"text": "\n Coding Problems\n "
},
{
"code": null,
"e": 1969,
"s": 1955,
"text": "\nFinish Test\n"
},
{
"code": null,
"e": 1975,
"s": 1969,
"text": "Error"
},
{
"code": null,
"e": 1981,
"s": 1975,
"text": "Error"
},
{
"code": null,
"e": 1990,
"s": 1981,
"text": "Reminder"
},
{
"code": null,
"e": 2038,
"s": 1990,
"text": "Click on the menu '' button to finish the test."
},
{
"code": null,
"e": 2066,
"s": 2038,
"text": "* All fields are mandatory."
},
{
"code": null,
"e": 2117,
"s": 2066,
"text": "\n Instructions\n "
},
{
"code": null,
"e": 2167,
"s": 2117,
"text": "\n Leaderboard\n "
},
{
"code": null,
"e": 2213,
"s": 2167,
"text": "\n Summary\n "
},
{
"code": null,
"e": 2219,
"s": 2217,
"text": "0"
},
{
"code": null,
"e": 2230,
"s": 2219,
"text": " QUIZSCORE"
},
{
"code": null,
"e": 2290,
"s": 2232,
"text": "Coding problem score has been deducted due to plagiarism."
},
{
"code": null,
"e": 2303,
"s": 2290,
"text": "CODING SCORE"
},
{
"code": null,
"e": 2305,
"s": 2303,
"text": "0"
},
{
"code": null,
"e": 2310,
"s": 2305,
"text": "RANK"
},
{
"code": null,
"e": 2411,
"s": 2314,
"text": "You need to submit each quiz question after selecting the\n option(s)."
},
{
"code": null,
"e": 2454,
"s": 2411,
"text": "\n All Problems\n "
},
{
"code": null,
"e": 2471,
"s": 2454,
"text": " Coding Score :"
},
{
"code": null,
"e": 2473,
"s": 2471,
"text": "0"
},
{
"code": null,
"e": 2495,
"s": 2473,
"text": "\n\n Solution Accepted\n"
},
{
"code": null,
"e": 2514,
"s": 2495,
"text": " Solution Accepted"
},
{
"code": null,
"e": 2531,
"s": 2514,
"text": "\n\n Wrong Answer\n"
},
{
"code": null,
"e": 2545,
"s": 2531,
"text": " Wrong Answer"
},
{
"code": null,
"e": 2557,
"s": 2545,
"text": "Submissions"
},
{
"code": null,
"e": 2567,
"s": 2557,
"text": "\nProblem\n"
},
{
"code": null,
"e": 2584,
"s": 2567,
"text": "\n Submissions \n"
},
{
"code": null,
"e": 2657,
"s": 2584,
"text": "Expected Outcome - runs the test cases against the code of Online Judge."
}
] |
Flutter – Wrap Widget | 27 May, 2021
Wrap widget aligns the widgets in a horizontal and vertical manner. Generally, we use Rows and Columns to do that but if we have some widgets which are not able to fit in the Row/Column then it will give us Overflow Message ( for ex: Right Overflowed by 570 pixels).
Wrap({Key key,
Axis direction,
WrapAlignment alignment,
double spacing,
WrapAlignment runAlignment,
double runSpacing,
WrapCrossAlignment crossAxisAlignment,
TextDirection textDirection,
VerticalDirection verticalDirection,
List<Widget> children})
direction: By default, the axis is horizontal but we can make it vertical by changing the axis from Axis.horizontal to Axis.vertical.
alignment: We can set the alignment property to align widgets. (for ex : alignment : WrapAlignment.center).
spacing: We can give space between the children.
runAlignment: It shows how runs themselves should be placed in the cross axis. By default, we have runAlignment as WrapAlignment.start.
runSpacing: We can give runSpacing between the runs. (ex: runSpacing:5.0).
crossAxisAlignment: We can align the children relative to each other in cross Axis.
textDirection : We can arrange children in a row using textDirection (for ex : textDirection: TextDirection.rtl to arrange from right to left).
clipBehaviour: This property takes in Clip enum as the object to decide whether the content inside the Wrap widget will be clipped or not.
children: The children property takes in a list of widgets as the object to show inside the Wrap widget or below the Wrap widget in the widget tree.
verticalDirection: This property takes in VerticalDirection enum as the object to. This property decides the order in which each children widget will be painted on the screen in a vertical sense.
runtimeType: Type class is the object given to the runtimeType property. It determines the type of the Wrap widget at the run time.
key: This property decides how one widget will replace another widget on the screen.
haskCode: This property takes in an int value as the object which represents the state of the widget.
main.dart
Dart
import 'package:flutter/material.dart';void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp( title: "GFG", theme: new ThemeData( primarySwatch: Colors.green ), debugShowCheckedModeBanner: false, home: WrapW() ); }} class WrapW extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar:AppBar( title: Text("GeeksForGeeks"), ), body: Wrap( // direction: Axis.vertical, // alignment: WrapAlignment.center, // spacing:8.0, // runAlignment:WrapAlignment.center, // runSpacing: 8.0, // crossAxisAlignment: WrapCrossAlignment.center, // textDirection: TextDirection.rtl, // verticalDirection: VerticalDirection.up, children: <Widget>[ Container( color: Colors.blue, width: 100, height: 100, child:Center(child: Text("W1",textScaleFactor: 2.5,)) ), Container( color: Colors.red, width: 100, height: 100, child:Center(child: Text("W2",textScaleFactor: 2.5,)) ), Container( color: Colors.teal, width: 100, height: 100, child:Center(child: Text("W3",textScaleFactor: 2.5,)) ), Container( color: Colors.indigo, width: 100, height: 100, child:Center(child: Text("W4",textScaleFactor: 2.5,)) ), Container( color: Colors.orange, width: 100, height: 100, child:Center(child: Text("W5",textScaleFactor: 2.5,)) ), ], ), ); }}
direction: Axis.horizontal // default
Output:
direction: Axis.vertical
Output:
alignment: WrapAlignment.center
Output:
alignment: WrapAlignment.center,
spacing:8.0,
Output:
alignment: WrapAlignment.center,
spacing:8.0,
runSpacing: 8.0,
Output:
spacing:8.0,
runSpacing: 8.0,
textDirection: TextDirection.rtl,
Output:
spacing:8.0,
runSpacing: 8.0,
verticalDirection: VerticalDirection.up,
Output:
singh_teekam
ankit_kumar_
simmytarika5
Flutter
Dart
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n27 May, 2021"
},
{
"code": null,
"e": 322,
"s": 54,
"text": "Wrap widget aligns the widgets in a horizontal and vertical manner. Generally, we use Rows and Columns to do that but if we have some widgets which are not able to fit in the Row/Column then it will give us Overflow Message ( for ex: Right Overflowed by 570 pixels). "
},
{
"code": null,
"e": 579,
"s": 322,
"text": "Wrap({Key key, \nAxis direction, \nWrapAlignment alignment, \ndouble spacing, \nWrapAlignment runAlignment, \ndouble runSpacing, \nWrapCrossAlignment crossAxisAlignment, \nTextDirection textDirection, \nVerticalDirection verticalDirection, \nList<Widget> children})"
},
{
"code": null,
"e": 713,
"s": 579,
"text": "direction: By default, the axis is horizontal but we can make it vertical by changing the axis from Axis.horizontal to Axis.vertical."
},
{
"code": null,
"e": 821,
"s": 713,
"text": "alignment: We can set the alignment property to align widgets. (for ex : alignment : WrapAlignment.center)."
},
{
"code": null,
"e": 870,
"s": 821,
"text": "spacing: We can give space between the children."
},
{
"code": null,
"e": 1006,
"s": 870,
"text": "runAlignment: It shows how runs themselves should be placed in the cross axis. By default, we have runAlignment as WrapAlignment.start."
},
{
"code": null,
"e": 1081,
"s": 1006,
"text": "runSpacing: We can give runSpacing between the runs. (ex: runSpacing:5.0)."
},
{
"code": null,
"e": 1165,
"s": 1081,
"text": "crossAxisAlignment: We can align the children relative to each other in cross Axis."
},
{
"code": null,
"e": 1309,
"s": 1165,
"text": "textDirection : We can arrange children in a row using textDirection (for ex : textDirection: TextDirection.rtl to arrange from right to left)."
},
{
"code": null,
"e": 1448,
"s": 1309,
"text": "clipBehaviour: This property takes in Clip enum as the object to decide whether the content inside the Wrap widget will be clipped or not."
},
{
"code": null,
"e": 1597,
"s": 1448,
"text": "children: The children property takes in a list of widgets as the object to show inside the Wrap widget or below the Wrap widget in the widget tree."
},
{
"code": null,
"e": 1793,
"s": 1597,
"text": "verticalDirection: This property takes in VerticalDirection enum as the object to. This property decides the order in which each children widget will be painted on the screen in a vertical sense."
},
{
"code": null,
"e": 1925,
"s": 1793,
"text": "runtimeType: Type class is the object given to the runtimeType property. It determines the type of the Wrap widget at the run time."
},
{
"code": null,
"e": 2010,
"s": 1925,
"text": "key: This property decides how one widget will replace another widget on the screen."
},
{
"code": null,
"e": 2112,
"s": 2010,
"text": "haskCode: This property takes in an int value as the object which represents the state of the widget."
},
{
"code": null,
"e": 2122,
"s": 2112,
"text": "main.dart"
},
{
"code": null,
"e": 2127,
"s": 2122,
"text": "Dart"
},
{
"code": "import 'package:flutter/material.dart';void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp( title: \"GFG\", theme: new ThemeData( primarySwatch: Colors.green ), debugShowCheckedModeBanner: false, home: WrapW() ); }} class WrapW extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar:AppBar( title: Text(\"GeeksForGeeks\"), ), body: Wrap( // direction: Axis.vertical, // alignment: WrapAlignment.center, // spacing:8.0, // runAlignment:WrapAlignment.center, // runSpacing: 8.0, // crossAxisAlignment: WrapCrossAlignment.center, // textDirection: TextDirection.rtl, // verticalDirection: VerticalDirection.up, children: <Widget>[ Container( color: Colors.blue, width: 100, height: 100, child:Center(child: Text(\"W1\",textScaleFactor: 2.5,)) ), Container( color: Colors.red, width: 100, height: 100, child:Center(child: Text(\"W2\",textScaleFactor: 2.5,)) ), Container( color: Colors.teal, width: 100, height: 100, child:Center(child: Text(\"W3\",textScaleFactor: 2.5,)) ), Container( color: Colors.indigo, width: 100, height: 100, child:Center(child: Text(\"W4\",textScaleFactor: 2.5,)) ), Container( color: Colors.orange, width: 100, height: 100, child:Center(child: Text(\"W5\",textScaleFactor: 2.5,)) ), ], ), ); }}",
"e": 3920,
"s": 2127,
"text": null
},
{
"code": null,
"e": 3958,
"s": 3920,
"text": "direction: Axis.horizontal // default"
},
{
"code": null,
"e": 3967,
"s": 3958,
"text": "Output: "
},
{
"code": null,
"e": 3992,
"s": 3967,
"text": "direction: Axis.vertical"
},
{
"code": null,
"e": 4001,
"s": 3992,
"text": "Output: "
},
{
"code": null,
"e": 4033,
"s": 4001,
"text": "alignment: WrapAlignment.center"
},
{
"code": null,
"e": 4042,
"s": 4033,
"text": "Output: "
},
{
"code": null,
"e": 4088,
"s": 4042,
"text": "alignment: WrapAlignment.center,\nspacing:8.0,"
},
{
"code": null,
"e": 4097,
"s": 4088,
"text": "Output: "
},
{
"code": null,
"e": 4160,
"s": 4097,
"text": "alignment: WrapAlignment.center,\nspacing:8.0,\nrunSpacing: 8.0,"
},
{
"code": null,
"e": 4169,
"s": 4160,
"text": "Output: "
},
{
"code": null,
"e": 4233,
"s": 4169,
"text": "spacing:8.0,\nrunSpacing: 8.0,\ntextDirection: TextDirection.rtl,"
},
{
"code": null,
"e": 4241,
"s": 4233,
"text": "Output:"
},
{
"code": null,
"e": 4312,
"s": 4241,
"text": "spacing:8.0,\nrunSpacing: 8.0,\nverticalDirection: VerticalDirection.up,"
},
{
"code": null,
"e": 4320,
"s": 4312,
"text": "Output:"
},
{
"code": null,
"e": 4333,
"s": 4320,
"text": "singh_teekam"
},
{
"code": null,
"e": 4346,
"s": 4333,
"text": "ankit_kumar_"
},
{
"code": null,
"e": 4359,
"s": 4346,
"text": "simmytarika5"
},
{
"code": null,
"e": 4367,
"s": 4359,
"text": "Flutter"
},
{
"code": null,
"e": 4372,
"s": 4367,
"text": "Dart"
}
] |
PHP | max( ) Function | 07 Mar, 2018
The max() function of PHP is used to find the numerically maximum value in an array or the numerically maximum value of several specified values. The max() function can take an array or several numbers as an argument and return the numerically maximum value among the passed parameters. The return type is not fixed, it can be an integer value or a float value based on input.
Syntax:
max(array_values)
or
max(value1, value2, ...)
Parameters: This function accepts two different types of arguments which are explained below:
array_values : It specifies an array containing the values.value1, value2, ... : It specifies two or more than two values to be compared.
array_values : It specifies an array containing the values.
value1, value2, ... : It specifies two or more than two values to be compared.
Return Value: The max() function returns the numerically maximum value.
Examples:
Input : max(12, 4, 62, 97, 26)
Output : 97
Input : max(array(28, 36, 87, 12))
Output : 87
Below programs illustrate the working of max() in PHP:
Program 1:
<?php echo (max(12, 4, 62, 97, 26)); ?>
Output:
97
Program 2:
<?php echo (max(array(28, 36, 87, 12)). "<br>"); ?>
Output:
87
Important points to note :
max() function is used to find the numerically maximum number.
max() function can be used on two or more than two values or it can be used on an array.
The value returned is of mixed data type.
Reference:http://php.net/manual/en/function.max.php
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
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": "\n07 Mar, 2018"
},
{
"code": null,
"e": 405,
"s": 28,
"text": "The max() function of PHP is used to find the numerically maximum value in an array or the numerically maximum value of several specified values. The max() function can take an array or several numbers as an argument and return the numerically maximum value among the passed parameters. The return type is not fixed, it can be an integer value or a float value based on input."
},
{
"code": null,
"e": 413,
"s": 405,
"text": "Syntax:"
},
{
"code": null,
"e": 464,
"s": 413,
"text": "max(array_values) \n\nor\n\nmax(value1, value2, ...)\n"
},
{
"code": null,
"e": 558,
"s": 464,
"text": "Parameters: This function accepts two different types of arguments which are explained below:"
},
{
"code": null,
"e": 696,
"s": 558,
"text": "array_values : It specifies an array containing the values.value1, value2, ... : It specifies two or more than two values to be compared."
},
{
"code": null,
"e": 756,
"s": 696,
"text": "array_values : It specifies an array containing the values."
},
{
"code": null,
"e": 835,
"s": 756,
"text": "value1, value2, ... : It specifies two or more than two values to be compared."
},
{
"code": null,
"e": 907,
"s": 835,
"text": "Return Value: The max() function returns the numerically maximum value."
},
{
"code": null,
"e": 917,
"s": 907,
"text": "Examples:"
},
{
"code": null,
"e": 1009,
"s": 917,
"text": "Input : max(12, 4, 62, 97, 26)\nOutput : 97\n\nInput : max(array(28, 36, 87, 12))\nOutput : 87\n"
},
{
"code": null,
"e": 1064,
"s": 1009,
"text": "Below programs illustrate the working of max() in PHP:"
},
{
"code": null,
"e": 1075,
"s": 1064,
"text": "Program 1:"
},
{
"code": "<?php echo (max(12, 4, 62, 97, 26)); ?>",
"e": 1117,
"s": 1075,
"text": null
},
{
"code": null,
"e": 1125,
"s": 1117,
"text": "Output:"
},
{
"code": null,
"e": 1128,
"s": 1125,
"text": "97"
},
{
"code": null,
"e": 1139,
"s": 1128,
"text": "Program 2:"
},
{
"code": "<?php echo (max(array(28, 36, 87, 12)). \"<br>\"); ?>",
"e": 1193,
"s": 1139,
"text": null
},
{
"code": null,
"e": 1201,
"s": 1193,
"text": "Output:"
},
{
"code": null,
"e": 1204,
"s": 1201,
"text": "87"
},
{
"code": null,
"e": 1231,
"s": 1204,
"text": "Important points to note :"
},
{
"code": null,
"e": 1294,
"s": 1231,
"text": "max() function is used to find the numerically maximum number."
},
{
"code": null,
"e": 1383,
"s": 1294,
"text": "max() function can be used on two or more than two values or it can be used on an array."
},
{
"code": null,
"e": 1425,
"s": 1383,
"text": "The value returned is of mixed data type."
},
{
"code": null,
"e": 1477,
"s": 1425,
"text": "Reference:http://php.net/manual/en/function.max.php"
},
{
"code": null,
"e": 1490,
"s": 1477,
"text": "PHP-function"
},
{
"code": null,
"e": 1494,
"s": 1490,
"text": "PHP"
},
{
"code": null,
"e": 1511,
"s": 1494,
"text": "Web Technologies"
},
{
"code": null,
"e": 1515,
"s": 1511,
"text": "PHP"
},
{
"code": null,
"e": 1613,
"s": 1515,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1663,
"s": 1613,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 1703,
"s": 1663,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 1764,
"s": 1703,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 1814,
"s": 1764,
"text": "How to check whether an array is empty using PHP?"
},
{
"code": null,
"e": 1859,
"s": 1814,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 1892,
"s": 1859,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1954,
"s": 1892,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2015,
"s": 1954,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2065,
"s": 2015,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Python Bin | Count total bits in a number | 01 Sep, 2020
Given a positive number n, count total bit in it.
Examples:
Input : 13
Output : 4
Binary representation of 13 is 1101
Input : 183
Output : 8
Input : 4096
Output : 13
We have existing solution for this problem please refer Count total bits in a number link. We can solve this problem quickly in Python using bin() function. Convert number into it’s binary using bin() function and remove starting two characters ‘0b’ of output binary string because bin function appends ‘0b’ as prefix in output string. Now print length of binary string that will be the count of bits in binary representation of input number.
Python3
# Function to count total bits in a number def countTotalBits(num): # convert number into it's binary and # remove first two characters 0b. binary = bin(num)[2:] print(len(binary)) # Driver programif __name__ == "__main__": num = 13 countTotalBits(num)
Output:
4
jk06
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n01 Sep, 2020"
},
{
"code": null,
"e": 104,
"s": 53,
"text": "Given a positive number n, count total bit in it. "
},
{
"code": null,
"e": 116,
"s": 104,
"text": "Examples: "
},
{
"code": null,
"e": 229,
"s": 116,
"text": "Input : 13\nOutput : 4\nBinary representation of 13 is 1101\n\nInput : 183\nOutput : 8\n\nInput : 4096\nOutput : 13\n\n\n"
},
{
"code": null,
"e": 675,
"s": 231,
"text": "We have existing solution for this problem please refer Count total bits in a number link. We can solve this problem quickly in Python using bin() function. Convert number into it’s binary using bin() function and remove starting two characters ‘0b’ of output binary string because bin function appends ‘0b’ as prefix in output string. Now print length of binary string that will be the count of bits in binary representation of input number. "
},
{
"code": null,
"e": 683,
"s": 675,
"text": "Python3"
},
{
"code": "# Function to count total bits in a number def countTotalBits(num): # convert number into it's binary and # remove first two characters 0b. binary = bin(num)[2:] print(len(binary)) # Driver programif __name__ == \"__main__\": num = 13 countTotalBits(num)",
"e": 963,
"s": 683,
"text": null
},
{
"code": null,
"e": 973,
"s": 963,
"text": "Output: "
},
{
"code": null,
"e": 978,
"s": 973,
"text": "4\n\n\n"
},
{
"code": null,
"e": 985,
"s": 980,
"text": "jk06"
},
{
"code": null,
"e": 992,
"s": 985,
"text": "Python"
},
{
"code": null,
"e": 1090,
"s": 992,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1108,
"s": 1090,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1150,
"s": 1108,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1172,
"s": 1150,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1207,
"s": 1172,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1233,
"s": 1207,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1265,
"s": 1233,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1294,
"s": 1265,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1321,
"s": 1294,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1351,
"s": 1321,
"text": "Iterate over a list in Python"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.