title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
What do you mean by static memory allocation in C programming?
|
Memory can be allocated in the following two ways −
Static variable defines in one block of allocated space, of a fixed size. Once it is allocated, it can never be freed.
Memory is allocated for the declared variable in the program.
The address can be obtained by using ‘&’ operator and can be assigned to a pointer.
The address can be obtained by using ‘&’ operator and can be assigned to a pointer.
The memory is allocated during compile time.
The memory is allocated during compile time.
It uses stack for maintaining the static allocation of memory.
It uses stack for maintaining the static allocation of memory.
In this allocation, once the memory is allocated, the memory size cannot change.
In this allocation, once the memory is allocated, the memory size cannot change.
It is less efficient.
It is less efficient.
The final size of a variable is decided before running the program, it will be called as static memory allocation. It is also called compile-time memory allocation.
We can't change the size of a variable which is allocated at compile-time.
Static memory allocation is generally used for an array. Let’s take an example program on arrays −
Live Demo
#include<stdio.h>
main (){
int a[5] = {10,20,30,40,50};
int i;
printf (“Elements of the array are”);
for ( i=0; i<5; i++)
printf (“%d, a[i]);
}
Elements of the array are
1020304050
Let’s consider another example to calculate sum and product of all elements in an array −
Live Demo
#include<stdio.h>
void main(){
//Declaring the array - run time//
int array[5]={10,20,30,40,50};
int i,sum=0,product=1;
//Reading elements into the array//
//For loop//
for(i=0;i<5;i++){
//Calculating sum and product, printing output//
sum=sum+array[i];
product=product*array[i];
}
//Displaying sum and product//
printf("Sum of elements in the array is : %d\n",sum);
printf("Product of elements in the array is : %d\n",product);
}
Sum of elements in the array is : 150
Product of elements in the array is : 12000000
|
[
{
"code": null,
"e": 1114,
"s": 1062,
"text": "Memory can be allocated in the following two ways −"
},
{
"code": null,
"e": 1233,
"s": 1114,
"text": "Static variable defines in one block of allocated space, of a fixed size. Once it is allocated, it can never be freed."
},
{
"code": null,
"e": 1295,
"s": 1233,
"text": "Memory is allocated for the declared variable in the program."
},
{
"code": null,
"e": 1379,
"s": 1295,
"text": "The address can be obtained by using ‘&’ operator and can be assigned to a pointer."
},
{
"code": null,
"e": 1463,
"s": 1379,
"text": "The address can be obtained by using ‘&’ operator and can be assigned to a pointer."
},
{
"code": null,
"e": 1508,
"s": 1463,
"text": "The memory is allocated during compile time."
},
{
"code": null,
"e": 1553,
"s": 1508,
"text": "The memory is allocated during compile time."
},
{
"code": null,
"e": 1616,
"s": 1553,
"text": "It uses stack for maintaining the static allocation of memory."
},
{
"code": null,
"e": 1679,
"s": 1616,
"text": "It uses stack for maintaining the static allocation of memory."
},
{
"code": null,
"e": 1760,
"s": 1679,
"text": "In this allocation, once the memory is allocated, the memory size cannot change."
},
{
"code": null,
"e": 1841,
"s": 1760,
"text": "In this allocation, once the memory is allocated, the memory size cannot change."
},
{
"code": null,
"e": 1863,
"s": 1841,
"text": "It is less efficient."
},
{
"code": null,
"e": 1885,
"s": 1863,
"text": "It is less efficient."
},
{
"code": null,
"e": 2050,
"s": 1885,
"text": "The final size of a variable is decided before running the program, it will be called as static memory allocation. It is also called compile-time memory allocation."
},
{
"code": null,
"e": 2125,
"s": 2050,
"text": "We can't change the size of a variable which is allocated at compile-time."
},
{
"code": null,
"e": 2224,
"s": 2125,
"text": "Static memory allocation is generally used for an array. Let’s take an example program on arrays −"
},
{
"code": null,
"e": 2235,
"s": 2224,
"text": " Live Demo"
},
{
"code": null,
"e": 2397,
"s": 2235,
"text": "#include<stdio.h>\nmain (){\n int a[5] = {10,20,30,40,50};\n int i;\n printf (“Elements of the array are”);\n for ( i=0; i<5; i++)\n printf (“%d, a[i]);\n}"
},
{
"code": null,
"e": 2434,
"s": 2397,
"text": "Elements of the array are\n1020304050"
},
{
"code": null,
"e": 2524,
"s": 2434,
"text": "Let’s consider another example to calculate sum and product of all elements in an array −"
},
{
"code": null,
"e": 2535,
"s": 2524,
"text": " Live Demo"
},
{
"code": null,
"e": 3014,
"s": 2535,
"text": "#include<stdio.h>\nvoid main(){\n //Declaring the array - run time//\n int array[5]={10,20,30,40,50};\n int i,sum=0,product=1;\n //Reading elements into the array//\n //For loop//\n for(i=0;i<5;i++){\n //Calculating sum and product, printing output//\n sum=sum+array[i];\n product=product*array[i];\n }\n //Displaying sum and product//\n printf(\"Sum of elements in the array is : %d\\n\",sum);\n printf(\"Product of elements in the array is : %d\\n\",product);\n}"
},
{
"code": null,
"e": 3099,
"s": 3014,
"text": "Sum of elements in the array is : 150\nProduct of elements in the array is : 12000000"
}
] |
Maximum sum of absolute difference of any permutation - GeeksforGeeks
|
24 May, 2021
Given an array, we need to find the maximum sum of absolute difference of any permutation of the given array.Examples:
Input : { 1, 2, 4, 8 }
Output : 18
Explanation : For the given array there are
several sequence possible
like : {2, 1, 4, 8}
{4, 2, 1, 8} and some more.
Now, the absolute difference of an array sequence will be
like for this array sequence {1, 2, 4, 8}, the absolute
difference sum is
= |1-2| + |2-4| + |4-8| + |8-1|
= 14
For the given array, we get the maximum value for
the sequence {1, 8, 2, 4}
= |1-8| + |8-2| + |2-4| + |4-1|
= 18
To solve this problem, we have to think greedily that how can we maximize the difference value of the elements so that we can have a maximum sum. This is possible only if we calculate the difference between some very high values and some very low values like (highest – smallest). This is the idea which we have to use to solve this problem. Let us see the above example, we will have maximum difference possible for sequence {1, 8, 2, 4} because in this sequence we will get some high difference values, ( |1-8| = 7, |8-2| = 6 .. ). Here, by placing 8(highest element) in place of 1 and 2 we get two high difference values. Similarly, for the other values, we will place next highest values in between other, as we have only one left i.e 4 which is placed at last. Algorithm: To get the maximum sum, we should have a sequence in which small and large elements comes alternate. This is done to get maximum difference.For the implementation of the above algorithm -> 1. We will sort the array. 2. Calculate the final sequence by taking one smallest element and largest element from the sorted array and make one vector array of this final sequence. 3. Finally, calculate the sum of absolute difference between the elements of the array.Below is the implementation of above idea :
C++
Java
Python3
C#
PHP
Javascript
// CPP implementation of// above algorithm#include <bits/stdc++.h>using namespace std; int MaxSumDifference(int a[], int n){ // final sequence stored in the vector vector<int> finalSequence; // sort the original array // so that we can retrieve // the large elements from // the end of array elements sort(a, a + n); // In this loop first we will insert // one smallest element not entered // till that time in final sequence // and then enter a highest element // (not entered till that time) in // final sequence so that we // have large difference value. This // process is repeated till all array // has completely entered in sequence. // Here, we have loop till n/2 because // we are inserting two elements at a // time in loop. for (int i = 0; i < n / 2; ++i) { finalSequence.push_back(a[i]); finalSequence.push_back(a[n - i - 1]); } // If there are odd elements, push the // middle element at the end. if (n % 2 != 0) finalSequence.push_back(a[n/2]); // variable to store the // maximum sum of absolute // difference int MaximumSum = 0; // In this loop absolute difference // of elements for the final sequence // is calculated. for (int i = 0; i < n - 1; ++i) { MaximumSum = MaximumSum + abs(finalSequence[i] - finalSequence[i + 1]); } // absolute difference of last element // and 1st element MaximumSum = MaximumSum + abs(finalSequence[n - 1] - finalSequence[0]); // return the value return MaximumSum;} // Driver functionint main(){ int a[] = { 1, 2, 4, 8 }; int n = sizeof(a) / sizeof(a[0]); cout << MaxSumDifference(a, n) << endl;}
// Java implementation of// above algorithmimport java.io.*;import java.util.*; public class GFG { static int MaxSumDifference(Integer []a, int n) { // final sequence stored in the vector List<Integer> finalSequence = new ArrayList<Integer>(); // sort the original array // so that we can retrieve // the large elements from // the end of array elements Arrays.sort(a); // In this loop first we will insert // one smallest element not entered // till that time in final sequence // and then enter a highest element // (not entered till that time) in // final sequence so that we // have large difference value. This // process is repeated till all array // has completely entered in sequence. // Here, we have loop till n/2 because // we are inserting two elements at a // time in loop. for (int i = 0; i < n / 2; ++i) { finalSequence.add(a[i]); finalSequence.add(a[n - i - 1]); } // If there are odd elements, push the // middle element at the end. if (n % 2 != 0) finalSequence.add(a[n/2]); // variable to store the // maximum sum of absolute // difference int MaximumSum = 0; // In this loop absolute difference // of elements for the final sequence // is calculated. for (int i = 0; i < n - 1; ++i) { MaximumSum = MaximumSum + Math.abs(finalSequence.get(i) - finalSequence.get(i + 1)); } // absolute difference of last element // and 1st element MaximumSum = MaximumSum + Math.abs(finalSequence.get(n - 1) - finalSequence.get(0)); // return the value return MaximumSum; } // Driver Code public static void main(String args[]) { Integer []a = { 1, 2, 4, 8 }; int n = a.length; System.out.print(MaxSumDifference(a, n)); }} // This code is contributed by// Manish Shaw (manishshaw1)
import numpy as npclass GFG: def MaxSumDifference(a,n): # sort the original array # so that we can retrieve # the large elements from # the end of array elements np.sort(a); # In this loop first we will # insert one smallest element # not entered till that time # in final sequence and then # enter a highest element(not # entered till that time) in # final sequence so that we # have large difference value. # This process is repeated till # all array has completely # entered in sequence. Here, # we have loop till n/2 because # we are inserting two elements # at a time in loop. j = 0 finalSequence = [0 for x in range(n)] for i in range(0, int(n / 2)): finalSequence[j] = a[i] finalSequence[j + 1] = a[n - i - 1] j = j + 2 # If there are odd elements, push the # middle element at the end. if (n % 2 != 0): finalSequence[n-1] = a[n//2 + 1] # variable to store the # maximum sum of absolute # difference MaximumSum = 0 # In this loop absolute # difference of elements # for the final sequence # is calculated. for i in range(0, n - 1): MaximumSum = (MaximumSum + abs(finalSequence[i] - finalSequence[i + 1])) # absolute difference of last # element and 1st element MaximumSum = (MaximumSum + abs(finalSequence[n - 1] - finalSequence[0])); # return the value print (MaximumSum) # Driver Codea = [ 1, 2, 4, 8 ]n = len(a)GFG.MaxSumDifference(a, n); # This code is contributed# by Prateek Bajaj
// C# implementation of// above algorithmusing System;using System.Collections.Generic;class GFG { static int MaxSumDifference(int []a, int n) { // final sequence stored in the vector List<int> finalSequence = new List<int>(); // sort the original array // so that we can retrieve // the large elements from // the end of array elements Array.Sort(a); // In this loop first we will insert // one smallest element not entered // till that time in final sequence // and then enter a highest element // (not entered till that time) in // final sequence so that we // have large difference value. This // process is repeated till all array // has completely entered in sequence. // Here, we have loop till n/2 because // we are inserting two elements at a // time in loop. for (int i = 0; i < n / 2; ++i) { finalSequence.Add(a[i]); finalSequence.Add(a[n - i - 1]); } // If there are odd elements, push the // middle element at the end. if (n % 2 != 0) finalSequence.Add(a[n/2]); // variable to store the // maximum sum of absolute // difference int MaximumSum = 0; // In this loop absolute difference // of elements for the final sequence // is calculated. for (int i = 0; i < n - 1; ++i) { MaximumSum = MaximumSum + Math.Abs(finalSequence[i] - finalSequence[i + 1]); } // absolute difference of last element // and 1st element MaximumSum = MaximumSum + Math.Abs(finalSequence[n - 1] - finalSequence[0]); // return the value return MaximumSum; } // Driver Code public static void Main() { int []a = { 1, 2, 4, 8 }; int n = a.Length; Console.WriteLine(MaxSumDifference(a, n)); }} // This code is contributed by// Manish Shaw (manishshaw1)
<?php// PHP implementation of above algorithm function MaxSumDifference(&$a, $n){ // final sequence stored in the vector $finalSequence = array(); // sort the original array so that we // can retrieve the large elements from // the end of array elements sort($a); // In this loop first we will insert one // smallest element not entered till that // time in final sequence and then enter // a highest element (not entered till // that time) in final sequence so that we // have large difference value. This process // is repeated till all array has completely // entered in sequence. // Here, we have loop till n/2 because // we are inserting two elements at a // time in loop. for ($i = 0; $i < $n / 2; ++$i) { array_push($finalSequence, $a[$i]); array_push($finalSequence, $a[$n - $i - 1]); } // If there are odd elements, push the // middle element at the end. if ($n % 2 != 0) array_push($finalSequence, $a[$n-1]); // variable to store the maximum sum // of absolute difference $MaximumSum = 0; // In this loop absolute difference // of elements for the final sequence // is calculated. for ($i = 0; $i < $n - 1; ++$i) { $MaximumSum = $MaximumSum + abs($finalSequence[$i] - $finalSequence[$i + 1]); } // absolute difference of last element // and 1st element $MaximumSum = $MaximumSum + abs($finalSequence[$n - 1] - $finalSequence[0]); // return the value return $MaximumSum;} // Driver Code$a = array(1, 2, 4, 8 );$n = sizeof($a);echo MaxSumDifference($a, $n) . "\n"; // This code is contributed by ita_c?>
<script>// Javascript implementation of// above algorithm function MaxSumDifference(a,n) { // final sequence stored in the vector let finalSequence = []; // sort the original array // so that we can retrieve // the large elements from // the end of array elements a.sort(function(a,b){return a-b;}); // In this loop first we will insert // one smallest element not entered // till that time in final sequence // and then enter a highest element // (not entered till that time) in // final sequence so that we // have large difference value. This // process is repeated till all array // has completely entered in sequence. // Here, we have loop till n/2 because // we are inserting two elements at a // time in loop. for (let i = 0; i < n / 2; ++i) { finalSequence.push(a[i]); finalSequence.push(a[n - i - 1]); } // If there are odd elements, push the // middle element at the end. if (n % 2 != 0) finalSequence.push(a[Math.floor(n/2)]); // variable to store the // maximum sum of absolute // difference let MaximumSum = 0; // In this loop absolute difference // of elements for the final sequence // is calculated. for (let i = 0; i < n - 1; ++i) { MaximumSum = MaximumSum + Math.abs(finalSequence[i] - finalSequence[i+1]); } // absolute difference of last element // and 1st element MaximumSum = MaximumSum + Math.abs(finalSequence[n-1] - finalSequence[0]); // return the value return MaximumSum; } // Driver Code let a=[1, 2, 4, 8 ]; let n = a.length; document.write(MaxSumDifference(a, n)); // This code is contributed by rag2127</script>
Output :
18
manishshaw1
Prateek Bajaj
ukasp
yash_singh
rag2127
ritikraushan
Arrays
Greedy
Sorting
Arrays
Greedy
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Dijkstra's shortest path algorithm | Greedy Algo-7
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Huffman Coding | Greedy Algo-3
Write a program to print all permutations of a given string
|
[
{
"code": null,
"e": 24513,
"s": 24485,
"text": "\n24 May, 2021"
},
{
"code": null,
"e": 24634,
"s": 24513,
"text": "Given an array, we need to find the maximum sum of absolute difference of any permutation of the given array.Examples: "
},
{
"code": null,
"e": 25078,
"s": 24634,
"text": "Input : { 1, 2, 4, 8 }\nOutput : 18\nExplanation : For the given array there are \nseveral sequence possible\nlike : {2, 1, 4, 8}\n {4, 2, 1, 8} and some more.\nNow, the absolute difference of an array sequence will be\nlike for this array sequence {1, 2, 4, 8}, the absolute\ndifference sum is \n= |1-2| + |2-4| + |4-8| + |8-1|\n= 14\nFor the given array, we get the maximum value for\nthe sequence {1, 8, 2, 4}\n= |1-8| + |8-2| + |2-4| + |4-1|\n= 18"
},
{
"code": null,
"e": 26359,
"s": 25078,
"text": "To solve this problem, we have to think greedily that how can we maximize the difference value of the elements so that we can have a maximum sum. This is possible only if we calculate the difference between some very high values and some very low values like (highest – smallest). This is the idea which we have to use to solve this problem. Let us see the above example, we will have maximum difference possible for sequence {1, 8, 2, 4} because in this sequence we will get some high difference values, ( |1-8| = 7, |8-2| = 6 .. ). Here, by placing 8(highest element) in place of 1 and 2 we get two high difference values. Similarly, for the other values, we will place next highest values in between other, as we have only one left i.e 4 which is placed at last. Algorithm: To get the maximum sum, we should have a sequence in which small and large elements comes alternate. This is done to get maximum difference.For the implementation of the above algorithm -> 1. We will sort the array. 2. Calculate the final sequence by taking one smallest element and largest element from the sorted array and make one vector array of this final sequence. 3. Finally, calculate the sum of absolute difference between the elements of the array.Below is the implementation of above idea : "
},
{
"code": null,
"e": 26363,
"s": 26359,
"text": "C++"
},
{
"code": null,
"e": 26368,
"s": 26363,
"text": "Java"
},
{
"code": null,
"e": 26376,
"s": 26368,
"text": "Python3"
},
{
"code": null,
"e": 26379,
"s": 26376,
"text": "C#"
},
{
"code": null,
"e": 26383,
"s": 26379,
"text": "PHP"
},
{
"code": null,
"e": 26394,
"s": 26383,
"text": "Javascript"
},
{
"code": "// CPP implementation of// above algorithm#include <bits/stdc++.h>using namespace std; int MaxSumDifference(int a[], int n){ // final sequence stored in the vector vector<int> finalSequence; // sort the original array // so that we can retrieve // the large elements from // the end of array elements sort(a, a + n); // In this loop first we will insert // one smallest element not entered // till that time in final sequence // and then enter a highest element // (not entered till that time) in // final sequence so that we // have large difference value. This // process is repeated till all array // has completely entered in sequence. // Here, we have loop till n/2 because // we are inserting two elements at a // time in loop. for (int i = 0; i < n / 2; ++i) { finalSequence.push_back(a[i]); finalSequence.push_back(a[n - i - 1]); } // If there are odd elements, push the // middle element at the end. if (n % 2 != 0) finalSequence.push_back(a[n/2]); // variable to store the // maximum sum of absolute // difference int MaximumSum = 0; // In this loop absolute difference // of elements for the final sequence // is calculated. for (int i = 0; i < n - 1; ++i) { MaximumSum = MaximumSum + abs(finalSequence[i] - finalSequence[i + 1]); } // absolute difference of last element // and 1st element MaximumSum = MaximumSum + abs(finalSequence[n - 1] - finalSequence[0]); // return the value return MaximumSum;} // Driver functionint main(){ int a[] = { 1, 2, 4, 8 }; int n = sizeof(a) / sizeof(a[0]); cout << MaxSumDifference(a, n) << endl;}",
"e": 28168,
"s": 26394,
"text": null
},
{
"code": "// Java implementation of// above algorithmimport java.io.*;import java.util.*; public class GFG { static int MaxSumDifference(Integer []a, int n) { // final sequence stored in the vector List<Integer> finalSequence = new ArrayList<Integer>(); // sort the original array // so that we can retrieve // the large elements from // the end of array elements Arrays.sort(a); // In this loop first we will insert // one smallest element not entered // till that time in final sequence // and then enter a highest element // (not entered till that time) in // final sequence so that we // have large difference value. This // process is repeated till all array // has completely entered in sequence. // Here, we have loop till n/2 because // we are inserting two elements at a // time in loop. for (int i = 0; i < n / 2; ++i) { finalSequence.add(a[i]); finalSequence.add(a[n - i - 1]); } // If there are odd elements, push the // middle element at the end. if (n % 2 != 0) finalSequence.add(a[n/2]); // variable to store the // maximum sum of absolute // difference int MaximumSum = 0; // In this loop absolute difference // of elements for the final sequence // is calculated. for (int i = 0; i < n - 1; ++i) { MaximumSum = MaximumSum + Math.abs(finalSequence.get(i) - finalSequence.get(i + 1)); } // absolute difference of last element // and 1st element MaximumSum = MaximumSum + Math.abs(finalSequence.get(n - 1) - finalSequence.get(0)); // return the value return MaximumSum; } // Driver Code public static void main(String args[]) { Integer []a = { 1, 2, 4, 8 }; int n = a.length; System.out.print(MaxSumDifference(a, n)); }} // This code is contributed by// Manish Shaw (manishshaw1)",
"e": 30348,
"s": 28168,
"text": null
},
{
"code": "import numpy as npclass GFG: def MaxSumDifference(a,n): # sort the original array # so that we can retrieve # the large elements from # the end of array elements np.sort(a); # In this loop first we will # insert one smallest element # not entered till that time # in final sequence and then # enter a highest element(not # entered till that time) in # final sequence so that we # have large difference value. # This process is repeated till # all array has completely # entered in sequence. Here, # we have loop till n/2 because # we are inserting two elements # at a time in loop. j = 0 finalSequence = [0 for x in range(n)] for i in range(0, int(n / 2)): finalSequence[j] = a[i] finalSequence[j + 1] = a[n - i - 1] j = j + 2 # If there are odd elements, push the # middle element at the end. if (n % 2 != 0): finalSequence[n-1] = a[n//2 + 1] # variable to store the # maximum sum of absolute # difference MaximumSum = 0 # In this loop absolute # difference of elements # for the final sequence # is calculated. for i in range(0, n - 1): MaximumSum = (MaximumSum + abs(finalSequence[i] - finalSequence[i + 1])) # absolute difference of last # element and 1st element MaximumSum = (MaximumSum + abs(finalSequence[n - 1] - finalSequence[0])); # return the value print (MaximumSum) # Driver Codea = [ 1, 2, 4, 8 ]n = len(a)GFG.MaxSumDifference(a, n); # This code is contributed# by Prateek Bajaj",
"e": 32206,
"s": 30348,
"text": null
},
{
"code": "// C# implementation of// above algorithmusing System;using System.Collections.Generic;class GFG { static int MaxSumDifference(int []a, int n) { // final sequence stored in the vector List<int> finalSequence = new List<int>(); // sort the original array // so that we can retrieve // the large elements from // the end of array elements Array.Sort(a); // In this loop first we will insert // one smallest element not entered // till that time in final sequence // and then enter a highest element // (not entered till that time) in // final sequence so that we // have large difference value. This // process is repeated till all array // has completely entered in sequence. // Here, we have loop till n/2 because // we are inserting two elements at a // time in loop. for (int i = 0; i < n / 2; ++i) { finalSequence.Add(a[i]); finalSequence.Add(a[n - i - 1]); } // If there are odd elements, push the // middle element at the end. if (n % 2 != 0) finalSequence.Add(a[n/2]); // variable to store the // maximum sum of absolute // difference int MaximumSum = 0; // In this loop absolute difference // of elements for the final sequence // is calculated. for (int i = 0; i < n - 1; ++i) { MaximumSum = MaximumSum + Math.Abs(finalSequence[i] - finalSequence[i + 1]); } // absolute difference of last element // and 1st element MaximumSum = MaximumSum + Math.Abs(finalSequence[n - 1] - finalSequence[0]); // return the value return MaximumSum; } // Driver Code public static void Main() { int []a = { 1, 2, 4, 8 }; int n = a.Length; Console.WriteLine(MaxSumDifference(a, n)); }} // This code is contributed by// Manish Shaw (manishshaw1)",
"e": 34321,
"s": 32206,
"text": null
},
{
"code": "<?php// PHP implementation of above algorithm function MaxSumDifference(&$a, $n){ // final sequence stored in the vector $finalSequence = array(); // sort the original array so that we // can retrieve the large elements from // the end of array elements sort($a); // In this loop first we will insert one // smallest element not entered till that // time in final sequence and then enter // a highest element (not entered till // that time) in final sequence so that we // have large difference value. This process // is repeated till all array has completely // entered in sequence. // Here, we have loop till n/2 because // we are inserting two elements at a // time in loop. for ($i = 0; $i < $n / 2; ++$i) { array_push($finalSequence, $a[$i]); array_push($finalSequence, $a[$n - $i - 1]); } // If there are odd elements, push the // middle element at the end. if ($n % 2 != 0) array_push($finalSequence, $a[$n-1]); // variable to store the maximum sum // of absolute difference $MaximumSum = 0; // In this loop absolute difference // of elements for the final sequence // is calculated. for ($i = 0; $i < $n - 1; ++$i) { $MaximumSum = $MaximumSum + abs($finalSequence[$i] - $finalSequence[$i + 1]); } // absolute difference of last element // and 1st element $MaximumSum = $MaximumSum + abs($finalSequence[$n - 1] - $finalSequence[0]); // return the value return $MaximumSum;} // Driver Code$a = array(1, 2, 4, 8 );$n = sizeof($a);echo MaxSumDifference($a, $n) . \"\\n\"; // This code is contributed by ita_c?>",
"e": 36057,
"s": 34321,
"text": null
},
{
"code": "<script>// Javascript implementation of// above algorithm function MaxSumDifference(a,n) { // final sequence stored in the vector let finalSequence = []; // sort the original array // so that we can retrieve // the large elements from // the end of array elements a.sort(function(a,b){return a-b;}); // In this loop first we will insert // one smallest element not entered // till that time in final sequence // and then enter a highest element // (not entered till that time) in // final sequence so that we // have large difference value. This // process is repeated till all array // has completely entered in sequence. // Here, we have loop till n/2 because // we are inserting two elements at a // time in loop. for (let i = 0; i < n / 2; ++i) { finalSequence.push(a[i]); finalSequence.push(a[n - i - 1]); } // If there are odd elements, push the // middle element at the end. if (n % 2 != 0) finalSequence.push(a[Math.floor(n/2)]); // variable to store the // maximum sum of absolute // difference let MaximumSum = 0; // In this loop absolute difference // of elements for the final sequence // is calculated. for (let i = 0; i < n - 1; ++i) { MaximumSum = MaximumSum + Math.abs(finalSequence[i] - finalSequence[i+1]); } // absolute difference of last element // and 1st element MaximumSum = MaximumSum + Math.abs(finalSequence[n-1] - finalSequence[0]); // return the value return MaximumSum; } // Driver Code let a=[1, 2, 4, 8 ]; let n = a.length; document.write(MaxSumDifference(a, n)); // This code is contributed by rag2127</script>",
"e": 38068,
"s": 36057,
"text": null
},
{
"code": null,
"e": 38078,
"s": 38068,
"text": "Output : "
},
{
"code": null,
"e": 38081,
"s": 38078,
"text": "18"
},
{
"code": null,
"e": 38093,
"s": 38081,
"text": "manishshaw1"
},
{
"code": null,
"e": 38107,
"s": 38093,
"text": "Prateek Bajaj"
},
{
"code": null,
"e": 38113,
"s": 38107,
"text": "ukasp"
},
{
"code": null,
"e": 38124,
"s": 38113,
"text": "yash_singh"
},
{
"code": null,
"e": 38132,
"s": 38124,
"text": "rag2127"
},
{
"code": null,
"e": 38145,
"s": 38132,
"text": "ritikraushan"
},
{
"code": null,
"e": 38152,
"s": 38145,
"text": "Arrays"
},
{
"code": null,
"e": 38159,
"s": 38152,
"text": "Greedy"
},
{
"code": null,
"e": 38167,
"s": 38159,
"text": "Sorting"
},
{
"code": null,
"e": 38174,
"s": 38167,
"text": "Arrays"
},
{
"code": null,
"e": 38181,
"s": 38174,
"text": "Greedy"
},
{
"code": null,
"e": 38189,
"s": 38181,
"text": "Sorting"
},
{
"code": null,
"e": 38287,
"s": 38189,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38296,
"s": 38287,
"text": "Comments"
},
{
"code": null,
"e": 38309,
"s": 38296,
"text": "Old Comments"
},
{
"code": null,
"e": 38357,
"s": 38309,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 38401,
"s": 38357,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 38424,
"s": 38401,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 38456,
"s": 38424,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 38470,
"s": 38456,
"text": "Linear Search"
},
{
"code": null,
"e": 38521,
"s": 38470,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 38572,
"s": 38521,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
},
{
"code": null,
"e": 38630,
"s": 38572,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 38661,
"s": 38630,
"text": "Huffman Coding | Greedy Algo-3"
}
] |
16 Must-Know Bash Commands for Data Scientists | by Giorgos Myrianthous | Towards Data Science
|
It is very important for Data Scientists to have a basic understanding around bash and its commands. Often referred to as the terminal, console or command line, Bash is a Unix shell that can help you navigate within your machine and perform certain tasks.
In today’s article, we are going to explore a few of the most commonly used bash commands that every Data Scientist must know.
The ls (list) command is used to list directories or files. By default (i.e. running ls with no options at all) the command will return the directories and files of the current directory, excluding any hidden files. Some of the most useful options are:
ls -a: List all the files in the current directory including hidden files too
ls -l: Long listing of all the files and their size in the current directory
ls [OPTIONS] [FILES]
$ ls -la
The cd (change directory) command is used to navigate in the directory tree structure.
cd [OPTIONS] directory
The command can take only two options-L to specify if symbolic links should be followed or P to specify that they shouldn’t.
$ cd myproject
rm (remove) command is used to delete files, directories or even symbolic links from your file system. Some of the most useful options are:
rm -i: Remove all the files in the directory but let user confirm before deleting it
rm -r: Remove non-empty directories including all the files within them
rm -f: Remove files or directories without prompting even if they are write-protected — f stands for force.
rm [OPTIONS]... FILE...
$ rm -rf directoryName
mv (move) command is used to move one or more directories or files from one location in the file system to another.
mv [OPTIONS] SOURCE DESTINATION
SOURCE can be one ore more directories or files
DESTINATION can be a file (used for renaming files) or a directory (used for moving files and directories into other directories.
# Rename file$ mv file1.txt file2.txt# Move a file into a different directory$ mv file1.txt anotherDir/
cp is a utility that lets you copy files or directories within the file system. Some of the most useful options are:
cp -u file1.txt file1_final.txt: Copy the content of file1.txt into file1_final.txt only if the former (source) is newer than the latter (destination)
cp -R myDir/ myDir_BACKUP: Copy directories
cp -p file1.txt file1_final.txt: Copy file1.txt and preserve ownership
cp [OPTIONS] SOURCE... DESTINATION
SOURCE may contain one or more directories or files
DESTINATION must be a single directory or file
# Copy files$ cp file1.txt file1_final.txt# Copy directories (and preserve ownership)$ cp -Rp myDir/ myDirBackup
The mkdir command is useful when it comes to creating new directories in the file system.
mkdir [OPTION] [DIRECTORY]
DIRECTORY can be one or more directories
# Create new directory with name myNewDir$ mkdir myNewDir
The pwd (print working directory) command can be used to report the absolute path of the current working directory.
$ pwd/Users/administrator
The touch command allows you to create new empty files or update the timestamp on existing files or directories. If you use touch with files that already exist, then the command will just update their timestamps. If the files do not exist then this command will simply create them.
Some of the most useful options are:
touch -c file1.txt: If file file1.txt already exists then this command will update the file’s timestamps otherwise it will do nothing.
touch -a file1.txt: Update only the access timestamp of the file
touch -m file1.txt: Update only the modify time of the file
touch [OPTIONS] [FILES]
# Create a new file (file1.txt does not exist)touch file1.txt# Update the access time of the file (file1.txt already exists)touch -a file1.txt
cat is a very commonly used command that allows users to read concatenate or write file contents to the standard output.
Some of the most useful options are:
cat -n file1.txt: Display the contents of the file file1.txt along with line numbers.
cat -T file1.txt: Display the contents of the file file1.txt and distinguish tabs and spaces (tabs will be displayed as ^I in the output)
cat [OPTIONS] [FILE_NAMES]
FILE_NAMES can be none or more file names
# Display the content of file $HOME/.pip/pip.confcat $HOME/.pip/pip.conf# Append the content of file1.txt to file2.txtcat file1.txt >> file2.txt
The less command lets you display the contents of a file one page at a time. less won’t read the entire file when it is being called and thus it leads to way faster load times.
Some of the most useful options are:
less -N file1.txt: Display the content (first page) of the file file1.txt and show line numbers.
less -X file1.txt: By default when you exit less the content of the file will be cleared from the command line. If you want to exit but also keep the content of the file on the screen use the -X option.
less [OPTIONS] filename
# Display the content of file $HOME/.pip/pip.confless $HOME/.pip/pip.conf
more command can also be used for displaying the content of a file in the command line. In contrast to less, more command loads the entire file at once and this is why less seems to be faster.
Some of the most useful options are:
more -p file1.txt: Clear the command line screen and then display the content of file1.txt
more +100 file1.txt: Display the content of file1.txt starting from the 100th line onwards.
more [OPTION] filename
# Display the content of file $HOME/.pip/pip.confmore $HOME/.pip/pip.conf
The grep (global regular expression) command is useful when you wish to search for a particular string in files.
Some of the most useful options are:
grep -v Andrew employees.txt: Invert match Andrew in employees.txt. In other words, display all the lines that do not match the pattern Andrew
grep -r Andrew dirName/: Recursuvely search for pattern Andrew in all files in the specified directory dirName
grep -i ANdrEW employees.txt: Perform a case insensitive search
grep [OPTIONS] PATTERN [FILE...]
PATTERN is the search pattern
FILE can be non to more input file names
# Search for `export` (case insensitive) in user profile$ grep -i export ~/.bash_profile
The curl command is used to download or upload data using protocols such as FTP, SFTP, HTTP and HTTPS.
curl [OPTIONS] [URL...]
$ curl -L google.com
which command is used to identify and report the location of the provided executable. For instance, you may wish to see the location of the executable when calling python3.
which [OPTIONS] FILE_NAME
$ which python3/usr/local/bin/python3
top command can help you monitor running processes and the resources (such as memory) they are currently using.
Some of the most useful options are:
top -u myuser: Display processes for the user myuser
history command displays the history of the commands that you’ve recently run.
Some of the most useful options are:
history -5: Display the last 5 commands
history -c: Clear the history list
history -d 10 20: Delete lines 10–20 from history list
$ history | grep python3
In this article, we explored only a small subset of some of the most commonly used bash commands. It is very important for Data Scientists to be able to use the command line as this will definitely help them perform basic tasks easily and most importantly efficiently.
Although it’s not mandatory for Data Scientists to become gurus of bash, it’s a very important skill that you may want to consider mastering. At the end of the day, bash is fun :)
|
[
{
"code": null,
"e": 428,
"s": 172,
"text": "It is very important for Data Scientists to have a basic understanding around bash and its commands. Often referred to as the terminal, console or command line, Bash is a Unix shell that can help you navigate within your machine and perform certain tasks."
},
{
"code": null,
"e": 555,
"s": 428,
"text": "In today’s article, we are going to explore a few of the most commonly used bash commands that every Data Scientist must know."
},
{
"code": null,
"e": 808,
"s": 555,
"text": "The ls (list) command is used to list directories or files. By default (i.e. running ls with no options at all) the command will return the directories and files of the current directory, excluding any hidden files. Some of the most useful options are:"
},
{
"code": null,
"e": 886,
"s": 808,
"text": "ls -a: List all the files in the current directory including hidden files too"
},
{
"code": null,
"e": 963,
"s": 886,
"text": "ls -l: Long listing of all the files and their size in the current directory"
},
{
"code": null,
"e": 984,
"s": 963,
"text": "ls [OPTIONS] [FILES]"
},
{
"code": null,
"e": 994,
"s": 984,
"text": "$ ls -la "
},
{
"code": null,
"e": 1081,
"s": 994,
"text": "The cd (change directory) command is used to navigate in the directory tree structure."
},
{
"code": null,
"e": 1104,
"s": 1081,
"text": "cd [OPTIONS] directory"
},
{
"code": null,
"e": 1229,
"s": 1104,
"text": "The command can take only two options-L to specify if symbolic links should be followed or P to specify that they shouldn’t."
},
{
"code": null,
"e": 1244,
"s": 1229,
"text": "$ cd myproject"
},
{
"code": null,
"e": 1384,
"s": 1244,
"text": "rm (remove) command is used to delete files, directories or even symbolic links from your file system. Some of the most useful options are:"
},
{
"code": null,
"e": 1469,
"s": 1384,
"text": "rm -i: Remove all the files in the directory but let user confirm before deleting it"
},
{
"code": null,
"e": 1541,
"s": 1469,
"text": "rm -r: Remove non-empty directories including all the files within them"
},
{
"code": null,
"e": 1649,
"s": 1541,
"text": "rm -f: Remove files or directories without prompting even if they are write-protected — f stands for force."
},
{
"code": null,
"e": 1673,
"s": 1649,
"text": "rm [OPTIONS]... FILE..."
},
{
"code": null,
"e": 1696,
"s": 1673,
"text": "$ rm -rf directoryName"
},
{
"code": null,
"e": 1812,
"s": 1696,
"text": "mv (move) command is used to move one or more directories or files from one location in the file system to another."
},
{
"code": null,
"e": 1844,
"s": 1812,
"text": "mv [OPTIONS] SOURCE DESTINATION"
},
{
"code": null,
"e": 1892,
"s": 1844,
"text": "SOURCE can be one ore more directories or files"
},
{
"code": null,
"e": 2022,
"s": 1892,
"text": "DESTINATION can be a file (used for renaming files) or a directory (used for moving files and directories into other directories."
},
{
"code": null,
"e": 2126,
"s": 2022,
"text": "# Rename file$ mv file1.txt file2.txt# Move a file into a different directory$ mv file1.txt anotherDir/"
},
{
"code": null,
"e": 2243,
"s": 2126,
"text": "cp is a utility that lets you copy files or directories within the file system. Some of the most useful options are:"
},
{
"code": null,
"e": 2394,
"s": 2243,
"text": "cp -u file1.txt file1_final.txt: Copy the content of file1.txt into file1_final.txt only if the former (source) is newer than the latter (destination)"
},
{
"code": null,
"e": 2438,
"s": 2394,
"text": "cp -R myDir/ myDir_BACKUP: Copy directories"
},
{
"code": null,
"e": 2509,
"s": 2438,
"text": "cp -p file1.txt file1_final.txt: Copy file1.txt and preserve ownership"
},
{
"code": null,
"e": 2544,
"s": 2509,
"text": "cp [OPTIONS] SOURCE... DESTINATION"
},
{
"code": null,
"e": 2596,
"s": 2544,
"text": "SOURCE may contain one or more directories or files"
},
{
"code": null,
"e": 2643,
"s": 2596,
"text": "DESTINATION must be a single directory or file"
},
{
"code": null,
"e": 2756,
"s": 2643,
"text": "# Copy files$ cp file1.txt file1_final.txt# Copy directories (and preserve ownership)$ cp -Rp myDir/ myDirBackup"
},
{
"code": null,
"e": 2846,
"s": 2756,
"text": "The mkdir command is useful when it comes to creating new directories in the file system."
},
{
"code": null,
"e": 2873,
"s": 2846,
"text": "mkdir [OPTION] [DIRECTORY]"
},
{
"code": null,
"e": 2914,
"s": 2873,
"text": "DIRECTORY can be one or more directories"
},
{
"code": null,
"e": 2972,
"s": 2914,
"text": "# Create new directory with name myNewDir$ mkdir myNewDir"
},
{
"code": null,
"e": 3088,
"s": 2972,
"text": "The pwd (print working directory) command can be used to report the absolute path of the current working directory."
},
{
"code": null,
"e": 3114,
"s": 3088,
"text": "$ pwd/Users/administrator"
},
{
"code": null,
"e": 3396,
"s": 3114,
"text": "The touch command allows you to create new empty files or update the timestamp on existing files or directories. If you use touch with files that already exist, then the command will just update their timestamps. If the files do not exist then this command will simply create them."
},
{
"code": null,
"e": 3433,
"s": 3396,
"text": "Some of the most useful options are:"
},
{
"code": null,
"e": 3568,
"s": 3433,
"text": "touch -c file1.txt: If file file1.txt already exists then this command will update the file’s timestamps otherwise it will do nothing."
},
{
"code": null,
"e": 3633,
"s": 3568,
"text": "touch -a file1.txt: Update only the access timestamp of the file"
},
{
"code": null,
"e": 3693,
"s": 3633,
"text": "touch -m file1.txt: Update only the modify time of the file"
},
{
"code": null,
"e": 3717,
"s": 3693,
"text": "touch [OPTIONS] [FILES]"
},
{
"code": null,
"e": 3860,
"s": 3717,
"text": "# Create a new file (file1.txt does not exist)touch file1.txt# Update the access time of the file (file1.txt already exists)touch -a file1.txt"
},
{
"code": null,
"e": 3981,
"s": 3860,
"text": "cat is a very commonly used command that allows users to read concatenate or write file contents to the standard output."
},
{
"code": null,
"e": 4018,
"s": 3981,
"text": "Some of the most useful options are:"
},
{
"code": null,
"e": 4104,
"s": 4018,
"text": "cat -n file1.txt: Display the contents of the file file1.txt along with line numbers."
},
{
"code": null,
"e": 4242,
"s": 4104,
"text": "cat -T file1.txt: Display the contents of the file file1.txt and distinguish tabs and spaces (tabs will be displayed as ^I in the output)"
},
{
"code": null,
"e": 4269,
"s": 4242,
"text": "cat [OPTIONS] [FILE_NAMES]"
},
{
"code": null,
"e": 4311,
"s": 4269,
"text": "FILE_NAMES can be none or more file names"
},
{
"code": null,
"e": 4456,
"s": 4311,
"text": "# Display the content of file $HOME/.pip/pip.confcat $HOME/.pip/pip.conf# Append the content of file1.txt to file2.txtcat file1.txt >> file2.txt"
},
{
"code": null,
"e": 4633,
"s": 4456,
"text": "The less command lets you display the contents of a file one page at a time. less won’t read the entire file when it is being called and thus it leads to way faster load times."
},
{
"code": null,
"e": 4670,
"s": 4633,
"text": "Some of the most useful options are:"
},
{
"code": null,
"e": 4767,
"s": 4670,
"text": "less -N file1.txt: Display the content (first page) of the file file1.txt and show line numbers."
},
{
"code": null,
"e": 4970,
"s": 4767,
"text": "less -X file1.txt: By default when you exit less the content of the file will be cleared from the command line. If you want to exit but also keep the content of the file on the screen use the -X option."
},
{
"code": null,
"e": 4994,
"s": 4970,
"text": "less [OPTIONS] filename"
},
{
"code": null,
"e": 5068,
"s": 4994,
"text": "# Display the content of file $HOME/.pip/pip.confless $HOME/.pip/pip.conf"
},
{
"code": null,
"e": 5261,
"s": 5068,
"text": "more command can also be used for displaying the content of a file in the command line. In contrast to less, more command loads the entire file at once and this is why less seems to be faster."
},
{
"code": null,
"e": 5298,
"s": 5261,
"text": "Some of the most useful options are:"
},
{
"code": null,
"e": 5389,
"s": 5298,
"text": "more -p file1.txt: Clear the command line screen and then display the content of file1.txt"
},
{
"code": null,
"e": 5481,
"s": 5389,
"text": "more +100 file1.txt: Display the content of file1.txt starting from the 100th line onwards."
},
{
"code": null,
"e": 5504,
"s": 5481,
"text": "more [OPTION] filename"
},
{
"code": null,
"e": 5578,
"s": 5504,
"text": "# Display the content of file $HOME/.pip/pip.confmore $HOME/.pip/pip.conf"
},
{
"code": null,
"e": 5691,
"s": 5578,
"text": "The grep (global regular expression) command is useful when you wish to search for a particular string in files."
},
{
"code": null,
"e": 5728,
"s": 5691,
"text": "Some of the most useful options are:"
},
{
"code": null,
"e": 5871,
"s": 5728,
"text": "grep -v Andrew employees.txt: Invert match Andrew in employees.txt. In other words, display all the lines that do not match the pattern Andrew"
},
{
"code": null,
"e": 5982,
"s": 5871,
"text": "grep -r Andrew dirName/: Recursuvely search for pattern Andrew in all files in the specified directory dirName"
},
{
"code": null,
"e": 6046,
"s": 5982,
"text": "grep -i ANdrEW employees.txt: Perform a case insensitive search"
},
{
"code": null,
"e": 6079,
"s": 6046,
"text": "grep [OPTIONS] PATTERN [FILE...]"
},
{
"code": null,
"e": 6109,
"s": 6079,
"text": "PATTERN is the search pattern"
},
{
"code": null,
"e": 6150,
"s": 6109,
"text": "FILE can be non to more input file names"
},
{
"code": null,
"e": 6239,
"s": 6150,
"text": "# Search for `export` (case insensitive) in user profile$ grep -i export ~/.bash_profile"
},
{
"code": null,
"e": 6342,
"s": 6239,
"text": "The curl command is used to download or upload data using protocols such as FTP, SFTP, HTTP and HTTPS."
},
{
"code": null,
"e": 6366,
"s": 6342,
"text": "curl [OPTIONS] [URL...]"
},
{
"code": null,
"e": 6387,
"s": 6366,
"text": "$ curl -L google.com"
},
{
"code": null,
"e": 6560,
"s": 6387,
"text": "which command is used to identify and report the location of the provided executable. For instance, you may wish to see the location of the executable when calling python3."
},
{
"code": null,
"e": 6586,
"s": 6560,
"text": "which [OPTIONS] FILE_NAME"
},
{
"code": null,
"e": 6624,
"s": 6586,
"text": "$ which python3/usr/local/bin/python3"
},
{
"code": null,
"e": 6736,
"s": 6624,
"text": "top command can help you monitor running processes and the resources (such as memory) they are currently using."
},
{
"code": null,
"e": 6773,
"s": 6736,
"text": "Some of the most useful options are:"
},
{
"code": null,
"e": 6826,
"s": 6773,
"text": "top -u myuser: Display processes for the user myuser"
},
{
"code": null,
"e": 6905,
"s": 6826,
"text": "history command displays the history of the commands that you’ve recently run."
},
{
"code": null,
"e": 6942,
"s": 6905,
"text": "Some of the most useful options are:"
},
{
"code": null,
"e": 6982,
"s": 6942,
"text": "history -5: Display the last 5 commands"
},
{
"code": null,
"e": 7017,
"s": 6982,
"text": "history -c: Clear the history list"
},
{
"code": null,
"e": 7072,
"s": 7017,
"text": "history -d 10 20: Delete lines 10–20 from history list"
},
{
"code": null,
"e": 7098,
"s": 7072,
"text": "$ history | grep python3"
},
{
"code": null,
"e": 7367,
"s": 7098,
"text": "In this article, we explored only a small subset of some of the most commonly used bash commands. It is very important for Data Scientists to be able to use the command line as this will definitely help them perform basic tasks easily and most importantly efficiently."
}
] |
Machine Learning ‘on the rocks’ 🥃 [Whiskey Dataset] | by Gerasimos Plegas | Towards Data Science
|
“Always carry a flagon of whisky in case of snakebite, and furthermore, always carry a small snake.” | W.C. Fields
Apparently, the project’s domain relies on the most popular liquor in the world — Whiskey. A dark spirit coming from a great variety of grains, distilled throughout the world and arriving at quite a number of styles (Irish, Scotch, Bourbon etc) [1]. Scotland, Ireland, Canada & Japan are among the famous exporters and on an international scale, the global production almost reaches the level of $95m revenue [2].
The main scope, hereof, is to introduce in a... ‘companionable’ way, how helpful can the Clustering Algorithms prove to be, anytime we need to find patterns in a (large) dataset. Actually, it might be considered as a powerful expansion of the standard Exploratory Data Analysis (EDA), which is often very beneficial to try, before using Supervised Machine Learning (ML) models. A predictive case of the latter (Logistic Regression) is also implemented at the end.
After successfully tuning a music playlist ‘the-Python-way’, the Data Corp I work for, accepted a new project: assisting a renowned Whiskey Vendor to diversify. That is, to bring into light which whiskey varieties are better sold and with that in mind, make the appropriate mergers/acquisitions, to boost sales contextually. The main handicap, though, is that the Vendor does not possess any Sales data from the competitors (aka prospective acquisition targets). But:
How about using whiskey-related data including any attributes (i.e. age, taste, type, price and so on), categorising them in a meaningful way for the Vendor and finally guide them on what specific bottles they should invest in?
In order to better communicate the outcomes, a number of assumptions were made:
#1: To define an adequate set of data for our analysis, I used a pertinent dataset from Kaggle — a remarkable source for almost any kind of data.
#2: The liquor attributes I used are: the name, category, rating & description of whiskies, while developing a couple of new ones (see Section 2).
#3: In lieu of any sales-related data, the only way to accomplish our mission is to uncover potential ‘underlying’ patterns that may lead the Vendor to increase the sales volume, artfully. Id est, preserve the merchandable variety and not just sell the most expensive or highly-rated bottles.
Set up the environment to run the code.Perform EDA using Numpy, Pandas & a number of additional Python libraries.Reveal additional data patterns, by fitting a K-Means Clustering algorithm to the dataset.Using the now labeled dataset (clusters = labels), implement a Multiclassification technique — Logistic Regression — to make predictions on new listings (whiskies).
Set up the environment to run the code.
Perform EDA using Numpy, Pandas & a number of additional Python libraries.
Reveal additional data patterns, by fitting a K-Means Clustering algorithm to the dataset.
Using the now labeled dataset (clusters = labels), implement a Multiclassification technique — Logistic Regression — to make predictions on new listings (whiskies).
In this section, we are going to set up the environment needed, in order to apply the analysis techniques.
Install Jupyter Notebook — an open-source web application used to create/share documents containing live code, equations, visualizations and narrative text. You may follow the steps here.
Install Requests /BeautifulSoup— a Python module for addressing the API and pulling data out of HTML and XML files, respectively. You can either use a CLI (Command Line Interface) or a Jupyter notebook, to run the following commands:
Import the necessary libraries:
The very first section includes reading the data into a DataFrame object, df_init.
Next, we take a series of necessary actions to get it ready for further analysis. Most importantly, we:
Check for nulls (no nulls) / Drop redundant columns (Unnamed: and currency).
Convert price to float type.
Check for duplicates concerning the name column and replace those listings with their mean values [category , rating, price].
Extract new features age and alcohol from the name column, by using specific RegEx.
In the vein of reducing cluttering, I do not include the data visualisation code herein, but it is available on the GitHub repository.
First things first, we inspect the dataset to confirm any obvious inferences. The variables (excl. description) are quantitative, while also belonging to the ratio scale of measurement. Therefore, a Box-and-Whisker plot could effectively depict each feature’s individual distribution and along with a table of the descriptive statistics (via the pandas.DataFrame.describe method), might provide us with a good visual intuition about the proportion of values that fall under each specific quartile (price has a large value range, thus plotted separately).
The rating variable begins from 70% (quite skewed, thus there are no bad whiskeys, as quoted!) and the Mean review is around 87%.
As expected (for a whiskey), the age and the alcohol begin from 3 years old and 40%, respectively, with the former noting an average value of 20 years old.
Taking into account the price feature, the average (yellow ▲) Scotch goes for 700 US $, while the Median (red line) is at 108 $. This is a clear indication that the distribution is right-skewed. Yet, what is highlighted is the range from 10 to 157.000 $!
As per the Assumption #3 (see above), no Sales data are available and inevitably, we have to manipulate the existent features. We build-up to the following ‘mechanism’:
The Vendor is interested in increasing the profit margin, thus opening the [price-cost] gap. Besides being right-skewed, the price itself cannot be used as a decision factor for the Vendor, since selling extra expensive bottles, also means extra procurement cost.
Finding #1: We should not follow the price as a decision factor. Eventually, we have to capture any interrelation among the features that may reveal which force drives the sales (and profit) upwards.
By inspecting the variables ‘pair-wisely’, we may capture useful relationships between them. A Scatter Plot Matrix is capable to visualize bivariate relationships between combinations of variables.
Interpreting the matrix with the Pearson’s correlation coefficients, the most profound findings we get are the following:
The most exciting finding is that a good rating to do not necessarily come with high a price (cor = 0.12). In other words, there is much potential to enjoy Scotch of high quality by spending less dollars — a clear bargain.
There is, also, a decent relationship between the age and rating (cor = 0,32).
The highest interrelation (cor = 0,33) is noted between the price and age; the extra expensive bottles belong to the mature liquors. But, evidently, if the Vendor opts to acquire a firm which produces extra mature whiskies, they will conceivably result to sell extremely expensive liquors, biasing that way their variety distribution:
186 60000.0739 60000.0182 60000.082 30000.0699 27620.029 26650.0102 25899.0397 25899.0103 25899.0816 25899.0Name: price, dtype: float64
So, apart from excluding price (Finding #1) we should also rule out the age and alcohol, too.
Finding #2: Consequently, we should concentrate on the rating feature, which is expected to have a great effect on the Vendor’s profit (more popular whiskies means higher sales).
Seeking a pattern that may enlight the Vendor on what bottles to promote mostly (in order to get higher profit), we are going to analyse the ‘kava’ by the category attribute, while also ‘illuminating’ the rating feature.
The Blended Malt takes the lead in rating, with the simple Blended coming next — the former’s Mean is by 0,23% (88,11–87,88) higher. It is noteworthy, that the Blended Malt's Median is quite above the 2nd quartile (Mean), hence more than 50% of the bottles are rated above the average (88%). This is a decent insight, we may provide the Vendor with...
Finding #3: The Vendor may choose to boost the sales of the Blended Malts. That way, they may achieve bigger sales, due to the popularity of this whiskey type and as a result enjoy higher profits.
⚠️ But, we still violate Condition #3 (preserve the whiskies variety) — a problem we haven’t yet tackled properly. So, instead of recommending Blended (and only) bottles and in an effort to guarantee the variety to the customers, we proceed to a new, more comprehensive way of clustering.
In Unsupervised Learning, we’re finding patterns in data, as opposed to the Supervised ML where we make predictions. Within this context, Clustering Algorithms are capable to group together similar rows, when more than one (invisible) groups may exist. These groups form the clusters we may look at and start to better understand the structure of the data. K-Means Clustering is a popular centroid-based clustering algorithm.
The k refers to the # of clusters we want to segment our data and must be declared, upfront. Among the available approaches to estimate it, we are going to use the Elbow Method, according to which:
We run the algorithm for various k (here from 1–10).For each iteration, we compute the Within-Cluster Sum of Squares (WCSS) and store it in a respective list.We plot the WCSS~# clusters k relationship.We locate the ‘elbow’ — the close area after which the line declines smoother (the source Python library called kneed is useful to that).
We run the algorithm for various k (here from 1–10).
For each iteration, we compute the Within-Cluster Sum of Squares (WCSS) and store it in a respective list.
We plot the WCSS~# clusters k relationship.
We locate the ‘elbow’ — the close area after which the line declines smoother (the source Python library called kneed is useful to that).
After switching to a new dataframe free of nulls (df_no_nulls), comprised of 1.355 whiskies, we plot the WCCS line.
The optimal number of clusters is 3 and we are ready to to implement the K-Means clustering.
The model showcased the following clusters and {num of bottles}, respectively: Cluster 0 {# 353}, Cluster 1{# 363} & Cluster 2{# 639}. Inspecting the pertinent Box Plots along with with those of Section 3, we deduce the following...
✔️ Clustering reveals a clearer indication of what whiskey types foster the rating (and sales, as well). See how the new Clusters distinguish themselves, as compared to the categories of previous analysis.
✔️ Cluster #1 is way better when it comes to terms of rating. Not only the Mean gets ahead of the rest, but its Median is located to the rightmost, meaning that at least half of the cluster’s bottles overtake even that remarkable value (89,33%).
✔️ At the same time, Cluster #1 includes Single Malt Scotch {#321}, Blended Scotch Whisky {#33} and Blended Malt Scotch Whisky {#9} — thus, variety guaranteed!
✔️ The analysis, hitherto, takes into account more features (rating, alcohol, age) than the previously attempted (rating), proving the point that clustering promotes a more comprehensive separation of data, deriving from signals of more components.
Bringing all of them to the same space, we can visualise a 3D Scatter Plot. Actually, we are marginally able to do so, because for >3 variables a Dimensionality Reduction Process (like PCA etc) is necessary to be prior executed.
It is quite prominent that Cluster #1 (red) ‘occupies’ the higher area of y-axis (rating). Additionally, should we normalise the data, we can render a Radar Plot. This one can further assist the results interpretation, by illustrating how better the red polygon ‘concers’ almost all of the features.
Supervised ML picks up the torch, now that our dataset is labelled (clusters). We aim at training a model that given the 3 features [rating, alcohol, age] of a new listing (whiskey), it will predict its label (aka cluster). That way, the Vendor will be capable to directly categorise it and deduct whether or not it has ‘potential’ to be commercialised!
A Multiclassification problem, like this one, can be tackled with a Logistic Regression model [3], after a couple of tweaks are firstly applied. Particularly, we will implement the one-versus-all method, where we choose a single category (ie Cluster #1) as the Positive case and group the rest as the False case, iteratively. Each of the product models is a binary classification one, that will return a probability [0-1]. When applying on new data, we choose the label corresponding to the model that predicted the highest probability.
An accuracy of 98.9% was achieved, meaning that almost 98 out of 100 new liquor entries may be successfully categorised to 1 of the 3 clusters, we developed.
Eventually, we reached our destination; from the apparent to the well-rounded insights of what ‘type’ of whiskies may foster the Vendor’s entrepreneurship.
Starting from a dataset of Kaggle, we gradually developed from plain EDA to an Unsupervised ML model (K-Means). That way, we revealed insightful patterns, which helped us better identify what it really takes to boost the Whiskey Sales, artfully. Finally, we fitted a Logistic Regression model on the labelled dataset, predicting with high accuracy the Cluster into which a new bottle may be registered.
I dedicate this post to my good friends Kostas and Panos; we used to taste new malts on Fridays, before the pandemic... Actually, beyond the quantitative ‘realm’, it’s not the price but the good company that makes whiskey tastier...So, cheers to our next ‘review session’ folks!
Thank you for reading. The repo is flavoured and ready to run 🥃 !
|
[
{
"code": null,
"e": 287,
"s": 172,
"text": "“Always carry a flagon of whisky in case of snakebite, and furthermore, always carry a small snake.” | W.C. Fields"
},
{
"code": null,
"e": 701,
"s": 287,
"text": "Apparently, the project’s domain relies on the most popular liquor in the world — Whiskey. A dark spirit coming from a great variety of grains, distilled throughout the world and arriving at quite a number of styles (Irish, Scotch, Bourbon etc) [1]. Scotland, Ireland, Canada & Japan are among the famous exporters and on an international scale, the global production almost reaches the level of $95m revenue [2]."
},
{
"code": null,
"e": 1165,
"s": 701,
"text": "The main scope, hereof, is to introduce in a... ‘companionable’ way, how helpful can the Clustering Algorithms prove to be, anytime we need to find patterns in a (large) dataset. Actually, it might be considered as a powerful expansion of the standard Exploratory Data Analysis (EDA), which is often very beneficial to try, before using Supervised Machine Learning (ML) models. A predictive case of the latter (Logistic Regression) is also implemented at the end."
},
{
"code": null,
"e": 1633,
"s": 1165,
"text": "After successfully tuning a music playlist ‘the-Python-way’, the Data Corp I work for, accepted a new project: assisting a renowned Whiskey Vendor to diversify. That is, to bring into light which whiskey varieties are better sold and with that in mind, make the appropriate mergers/acquisitions, to boost sales contextually. The main handicap, though, is that the Vendor does not possess any Sales data from the competitors (aka prospective acquisition targets). But:"
},
{
"code": null,
"e": 1861,
"s": 1633,
"text": "How about using whiskey-related data including any attributes (i.e. age, taste, type, price and so on), categorising them in a meaningful way for the Vendor and finally guide them on what specific bottles they should invest in?"
},
{
"code": null,
"e": 1941,
"s": 1861,
"text": "In order to better communicate the outcomes, a number of assumptions were made:"
},
{
"code": null,
"e": 2087,
"s": 1941,
"text": "#1: To define an adequate set of data for our analysis, I used a pertinent dataset from Kaggle — a remarkable source for almost any kind of data."
},
{
"code": null,
"e": 2234,
"s": 2087,
"text": "#2: The liquor attributes I used are: the name, category, rating & description of whiskies, while developing a couple of new ones (see Section 2)."
},
{
"code": null,
"e": 2527,
"s": 2234,
"text": "#3: In lieu of any sales-related data, the only way to accomplish our mission is to uncover potential ‘underlying’ patterns that may lead the Vendor to increase the sales volume, artfully. Id est, preserve the merchandable variety and not just sell the most expensive or highly-rated bottles."
},
{
"code": null,
"e": 2895,
"s": 2527,
"text": "Set up the environment to run the code.Perform EDA using Numpy, Pandas & a number of additional Python libraries.Reveal additional data patterns, by fitting a K-Means Clustering algorithm to the dataset.Using the now labeled dataset (clusters = labels), implement a Multiclassification technique — Logistic Regression — to make predictions on new listings (whiskies)."
},
{
"code": null,
"e": 2935,
"s": 2895,
"text": "Set up the environment to run the code."
},
{
"code": null,
"e": 3010,
"s": 2935,
"text": "Perform EDA using Numpy, Pandas & a number of additional Python libraries."
},
{
"code": null,
"e": 3101,
"s": 3010,
"text": "Reveal additional data patterns, by fitting a K-Means Clustering algorithm to the dataset."
},
{
"code": null,
"e": 3266,
"s": 3101,
"text": "Using the now labeled dataset (clusters = labels), implement a Multiclassification technique — Logistic Regression — to make predictions on new listings (whiskies)."
},
{
"code": null,
"e": 3373,
"s": 3266,
"text": "In this section, we are going to set up the environment needed, in order to apply the analysis techniques."
},
{
"code": null,
"e": 3561,
"s": 3373,
"text": "Install Jupyter Notebook — an open-source web application used to create/share documents containing live code, equations, visualizations and narrative text. You may follow the steps here."
},
{
"code": null,
"e": 3795,
"s": 3561,
"text": "Install Requests /BeautifulSoup— a Python module for addressing the API and pulling data out of HTML and XML files, respectively. You can either use a CLI (Command Line Interface) or a Jupyter notebook, to run the following commands:"
},
{
"code": null,
"e": 3827,
"s": 3795,
"text": "Import the necessary libraries:"
},
{
"code": null,
"e": 3910,
"s": 3827,
"text": "The very first section includes reading the data into a DataFrame object, df_init."
},
{
"code": null,
"e": 4014,
"s": 3910,
"text": "Next, we take a series of necessary actions to get it ready for further analysis. Most importantly, we:"
},
{
"code": null,
"e": 4091,
"s": 4014,
"text": "Check for nulls (no nulls) / Drop redundant columns (Unnamed: and currency)."
},
{
"code": null,
"e": 4120,
"s": 4091,
"text": "Convert price to float type."
},
{
"code": null,
"e": 4246,
"s": 4120,
"text": "Check for duplicates concerning the name column and replace those listings with their mean values [category , rating, price]."
},
{
"code": null,
"e": 4330,
"s": 4246,
"text": "Extract new features age and alcohol from the name column, by using specific RegEx."
},
{
"code": null,
"e": 4465,
"s": 4330,
"text": "In the vein of reducing cluttering, I do not include the data visualisation code herein, but it is available on the GitHub repository."
},
{
"code": null,
"e": 5020,
"s": 4465,
"text": "First things first, we inspect the dataset to confirm any obvious inferences. The variables (excl. description) are quantitative, while also belonging to the ratio scale of measurement. Therefore, a Box-and-Whisker plot could effectively depict each feature’s individual distribution and along with a table of the descriptive statistics (via the pandas.DataFrame.describe method), might provide us with a good visual intuition about the proportion of values that fall under each specific quartile (price has a large value range, thus plotted separately)."
},
{
"code": null,
"e": 5150,
"s": 5020,
"text": "The rating variable begins from 70% (quite skewed, thus there are no bad whiskeys, as quoted!) and the Mean review is around 87%."
},
{
"code": null,
"e": 5306,
"s": 5150,
"text": "As expected (for a whiskey), the age and the alcohol begin from 3 years old and 40%, respectively, with the former noting an average value of 20 years old."
},
{
"code": null,
"e": 5561,
"s": 5306,
"text": "Taking into account the price feature, the average (yellow ▲) Scotch goes for 700 US $, while the Median (red line) is at 108 $. This is a clear indication that the distribution is right-skewed. Yet, what is highlighted is the range from 10 to 157.000 $!"
},
{
"code": null,
"e": 5730,
"s": 5561,
"text": "As per the Assumption #3 (see above), no Sales data are available and inevitably, we have to manipulate the existent features. We build-up to the following ‘mechanism’:"
},
{
"code": null,
"e": 5994,
"s": 5730,
"text": "The Vendor is interested in increasing the profit margin, thus opening the [price-cost] gap. Besides being right-skewed, the price itself cannot be used as a decision factor for the Vendor, since selling extra expensive bottles, also means extra procurement cost."
},
{
"code": null,
"e": 6194,
"s": 5994,
"text": "Finding #1: We should not follow the price as a decision factor. Eventually, we have to capture any interrelation among the features that may reveal which force drives the sales (and profit) upwards."
},
{
"code": null,
"e": 6392,
"s": 6194,
"text": "By inspecting the variables ‘pair-wisely’, we may capture useful relationships between them. A Scatter Plot Matrix is capable to visualize bivariate relationships between combinations of variables."
},
{
"code": null,
"e": 6514,
"s": 6392,
"text": "Interpreting the matrix with the Pearson’s correlation coefficients, the most profound findings we get are the following:"
},
{
"code": null,
"e": 6737,
"s": 6514,
"text": "The most exciting finding is that a good rating to do not necessarily come with high a price (cor = 0.12). In other words, there is much potential to enjoy Scotch of high quality by spending less dollars — a clear bargain."
},
{
"code": null,
"e": 6816,
"s": 6737,
"text": "There is, also, a decent relationship between the age and rating (cor = 0,32)."
},
{
"code": null,
"e": 7151,
"s": 6816,
"text": "The highest interrelation (cor = 0,33) is noted between the price and age; the extra expensive bottles belong to the mature liquors. But, evidently, if the Vendor opts to acquire a firm which produces extra mature whiskies, they will conceivably result to sell extremely expensive liquors, biasing that way their variety distribution:"
},
{
"code": null,
"e": 7319,
"s": 7151,
"text": "186 60000.0739 60000.0182 60000.082 30000.0699 27620.029 26650.0102 25899.0397 25899.0103 25899.0816 25899.0Name: price, dtype: float64"
},
{
"code": null,
"e": 7413,
"s": 7319,
"text": "So, apart from excluding price (Finding #1) we should also rule out the age and alcohol, too."
},
{
"code": null,
"e": 7592,
"s": 7413,
"text": "Finding #2: Consequently, we should concentrate on the rating feature, which is expected to have a great effect on the Vendor’s profit (more popular whiskies means higher sales)."
},
{
"code": null,
"e": 7813,
"s": 7592,
"text": "Seeking a pattern that may enlight the Vendor on what bottles to promote mostly (in order to get higher profit), we are going to analyse the ‘kava’ by the category attribute, while also ‘illuminating’ the rating feature."
},
{
"code": null,
"e": 8165,
"s": 7813,
"text": "The Blended Malt takes the lead in rating, with the simple Blended coming next — the former’s Mean is by 0,23% (88,11–87,88) higher. It is noteworthy, that the Blended Malt's Median is quite above the 2nd quartile (Mean), hence more than 50% of the bottles are rated above the average (88%). This is a decent insight, we may provide the Vendor with..."
},
{
"code": null,
"e": 8362,
"s": 8165,
"text": "Finding #3: The Vendor may choose to boost the sales of the Blended Malts. That way, they may achieve bigger sales, due to the popularity of this whiskey type and as a result enjoy higher profits."
},
{
"code": null,
"e": 8651,
"s": 8362,
"text": "⚠️ But, we still violate Condition #3 (preserve the whiskies variety) — a problem we haven’t yet tackled properly. So, instead of recommending Blended (and only) bottles and in an effort to guarantee the variety to the customers, we proceed to a new, more comprehensive way of clustering."
},
{
"code": null,
"e": 9077,
"s": 8651,
"text": "In Unsupervised Learning, we’re finding patterns in data, as opposed to the Supervised ML where we make predictions. Within this context, Clustering Algorithms are capable to group together similar rows, when more than one (invisible) groups may exist. These groups form the clusters we may look at and start to better understand the structure of the data. K-Means Clustering is a popular centroid-based clustering algorithm."
},
{
"code": null,
"e": 9275,
"s": 9077,
"text": "The k refers to the # of clusters we want to segment our data and must be declared, upfront. Among the available approaches to estimate it, we are going to use the Elbow Method, according to which:"
},
{
"code": null,
"e": 9614,
"s": 9275,
"text": "We run the algorithm for various k (here from 1–10).For each iteration, we compute the Within-Cluster Sum of Squares (WCSS) and store it in a respective list.We plot the WCSS~# clusters k relationship.We locate the ‘elbow’ — the close area after which the line declines smoother (the source Python library called kneed is useful to that)."
},
{
"code": null,
"e": 9667,
"s": 9614,
"text": "We run the algorithm for various k (here from 1–10)."
},
{
"code": null,
"e": 9774,
"s": 9667,
"text": "For each iteration, we compute the Within-Cluster Sum of Squares (WCSS) and store it in a respective list."
},
{
"code": null,
"e": 9818,
"s": 9774,
"text": "We plot the WCSS~# clusters k relationship."
},
{
"code": null,
"e": 9956,
"s": 9818,
"text": "We locate the ‘elbow’ — the close area after which the line declines smoother (the source Python library called kneed is useful to that)."
},
{
"code": null,
"e": 10072,
"s": 9956,
"text": "After switching to a new dataframe free of nulls (df_no_nulls), comprised of 1.355 whiskies, we plot the WCCS line."
},
{
"code": null,
"e": 10165,
"s": 10072,
"text": "The optimal number of clusters is 3 and we are ready to to implement the K-Means clustering."
},
{
"code": null,
"e": 10398,
"s": 10165,
"text": "The model showcased the following clusters and {num of bottles}, respectively: Cluster 0 {# 353}, Cluster 1{# 363} & Cluster 2{# 639}. Inspecting the pertinent Box Plots along with with those of Section 3, we deduce the following..."
},
{
"code": null,
"e": 10604,
"s": 10398,
"text": "✔️ Clustering reveals a clearer indication of what whiskey types foster the rating (and sales, as well). See how the new Clusters distinguish themselves, as compared to the categories of previous analysis."
},
{
"code": null,
"e": 10850,
"s": 10604,
"text": "✔️ Cluster #1 is way better when it comes to terms of rating. Not only the Mean gets ahead of the rest, but its Median is located to the rightmost, meaning that at least half of the cluster’s bottles overtake even that remarkable value (89,33%)."
},
{
"code": null,
"e": 11010,
"s": 10850,
"text": "✔️ At the same time, Cluster #1 includes Single Malt Scotch {#321}, Blended Scotch Whisky {#33} and Blended Malt Scotch Whisky {#9} — thus, variety guaranteed!"
},
{
"code": null,
"e": 11259,
"s": 11010,
"text": "✔️ The analysis, hitherto, takes into account more features (rating, alcohol, age) than the previously attempted (rating), proving the point that clustering promotes a more comprehensive separation of data, deriving from signals of more components."
},
{
"code": null,
"e": 11488,
"s": 11259,
"text": "Bringing all of them to the same space, we can visualise a 3D Scatter Plot. Actually, we are marginally able to do so, because for >3 variables a Dimensionality Reduction Process (like PCA etc) is necessary to be prior executed."
},
{
"code": null,
"e": 11788,
"s": 11488,
"text": "It is quite prominent that Cluster #1 (red) ‘occupies’ the higher area of y-axis (rating). Additionally, should we normalise the data, we can render a Radar Plot. This one can further assist the results interpretation, by illustrating how better the red polygon ‘concers’ almost all of the features."
},
{
"code": null,
"e": 12142,
"s": 11788,
"text": "Supervised ML picks up the torch, now that our dataset is labelled (clusters). We aim at training a model that given the 3 features [rating, alcohol, age] of a new listing (whiskey), it will predict its label (aka cluster). That way, the Vendor will be capable to directly categorise it and deduct whether or not it has ‘potential’ to be commercialised!"
},
{
"code": null,
"e": 12679,
"s": 12142,
"text": "A Multiclassification problem, like this one, can be tackled with a Logistic Regression model [3], after a couple of tweaks are firstly applied. Particularly, we will implement the one-versus-all method, where we choose a single category (ie Cluster #1) as the Positive case and group the rest as the False case, iteratively. Each of the product models is a binary classification one, that will return a probability [0-1]. When applying on new data, we choose the label corresponding to the model that predicted the highest probability."
},
{
"code": null,
"e": 12837,
"s": 12679,
"text": "An accuracy of 98.9% was achieved, meaning that almost 98 out of 100 new liquor entries may be successfully categorised to 1 of the 3 clusters, we developed."
},
{
"code": null,
"e": 12993,
"s": 12837,
"text": "Eventually, we reached our destination; from the apparent to the well-rounded insights of what ‘type’ of whiskies may foster the Vendor’s entrepreneurship."
},
{
"code": null,
"e": 13396,
"s": 12993,
"text": "Starting from a dataset of Kaggle, we gradually developed from plain EDA to an Unsupervised ML model (K-Means). That way, we revealed insightful patterns, which helped us better identify what it really takes to boost the Whiskey Sales, artfully. Finally, we fitted a Logistic Regression model on the labelled dataset, predicting with high accuracy the Cluster into which a new bottle may be registered."
},
{
"code": null,
"e": 13675,
"s": 13396,
"text": "I dedicate this post to my good friends Kostas and Panos; we used to taste new malts on Fridays, before the pandemic... Actually, beyond the quantitative ‘realm’, it’s not the price but the good company that makes whiskey tastier...So, cheers to our next ‘review session’ folks!"
}
] |
PL/SQL | User Input - GeeksforGeeks
|
03 Oct, 2018
Prerequisite – PL/SQL IntroductionIn PL/SQL, user can be prompted to input a value using & character. & can be used to prompt input for different data types. Consider, following table:
Following queries will create a new table named GFG in the database.
SQL> create table GFG (id number(4), author varchar2(50),
likes number(4))
Table created.
SQL> insert into GFG values(1, 'sam', 10);
1 row created.
SQL> insert into GFG values(2, 'maria', 30);
1 row created.
SQL> insert into GFG values(3, 'ria', 40);
1 row created.
SQL> select * from GFG;
1. Numeric value –& is used to input numeric values from the user.
Syntax:
&value
Example-1: Consider, the table GFG. Let us select a record with a given id. (Here, id is a numeric value)
SQL> select * from GFG where id=&id;
Enter value for id: 2
old 1: select * from GFG where id=&id
new 1: select * from GFG where id=2
Example-2: Let us update a record with a given id. (Here, id is a numeric value)
SQL> update GFG set likes=50 where id=&id;
Enter value for id: 1
old 1: update GFG set likes=50 where id=&id
new 1: update GFG set likes=50 where id=1
1 row updated.
SQL> select * from GFG;
2. Text Value –& can also be used to input text values from the user.
Syntax:
'&value'
Example-1: Consider, the table GFG. Let us select a record with a given author. (Here, author is a text value)
SQL> select * from GFG where author='&author';
Enter value for author: maria
old 1: select * from GFG where author='&author'
new 1: select * from GFG where author='maria'
Example-2: Let us update a record with a given author. (Here, author is a text value)
SQL> update GFG set likes=10 where author='&author';
Enter value for author: sam
old 1: update GFG set likes=10 where author='&author'
new 1: update GFG set likes=10 where author='sam'
1 row updated.
SQL> select * from GFG;
DBMS-SQL
SQL-PL/SQL
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between Clustered and Non-clustered index
CTE in SQL
SQL | Views
Difference between DELETE, DROP and TRUNCATE
Difference between Primary Key and Foreign Key
SQL | DDL, DQL, DML, DCL and TCL Commands
How to find Nth highest salary from a table
SQL | ALTER (RENAME)
CTE in SQL
SQL | Views
|
[
{
"code": null,
"e": 23973,
"s": 23945,
"text": "\n03 Oct, 2018"
},
{
"code": null,
"e": 24158,
"s": 23973,
"text": "Prerequisite – PL/SQL IntroductionIn PL/SQL, user can be prompted to input a value using & character. & can be used to prompt input for different data types. Consider, following table:"
},
{
"code": null,
"e": 24227,
"s": 24158,
"text": "Following queries will create a new table named GFG in the database."
},
{
"code": null,
"e": 24346,
"s": 24227,
"text": "SQL> create table GFG (id number(4), author varchar2(50), \n likes number(4)) "
},
{
"code": null,
"e": 24538,
"s": 24346,
"text": "Table created.\nSQL> insert into GFG values(1, 'sam', 10);\n1 row created.\nSQL> insert into GFG values(2, 'maria', 30);\n1 row created.\nSQL> insert into GFG values(3, 'ria', 40);\n1 row created. "
},
{
"code": null,
"e": 24562,
"s": 24538,
"text": "SQL> select * from GFG;"
},
{
"code": null,
"e": 24629,
"s": 24562,
"text": "1. Numeric value –& is used to input numeric values from the user."
},
{
"code": null,
"e": 24637,
"s": 24629,
"text": "Syntax:"
},
{
"code": null,
"e": 24645,
"s": 24637,
"text": "&value "
},
{
"code": null,
"e": 24751,
"s": 24645,
"text": "Example-1: Consider, the table GFG. Let us select a record with a given id. (Here, id is a numeric value)"
},
{
"code": null,
"e": 24885,
"s": 24751,
"text": "SQL> select * from GFG where id=&id;\nEnter value for id: 2\nold 1: select * from GFG where id=&id\nnew 1: select * from GFG where id=2 "
},
{
"code": null,
"e": 24966,
"s": 24885,
"text": "Example-2: Let us update a record with a given id. (Here, id is a numeric value)"
},
{
"code": null,
"e": 25133,
"s": 24966,
"text": "SQL> update GFG set likes=50 where id=&id;\nEnter value for id: 1\nold 1: update GFG set likes=50 where id=&id\nnew 1: update GFG set likes=50 where id=1\n1 row updated. "
},
{
"code": null,
"e": 25158,
"s": 25133,
"text": "SQL> select * from GFG; "
},
{
"code": null,
"e": 25228,
"s": 25158,
"text": "2. Text Value –& can also be used to input text values from the user."
},
{
"code": null,
"e": 25236,
"s": 25228,
"text": "Syntax:"
},
{
"code": null,
"e": 25246,
"s": 25236,
"text": "'&value' "
},
{
"code": null,
"e": 25357,
"s": 25246,
"text": "Example-1: Consider, the table GFG. Let us select a record with a given author. (Here, author is a text value)"
},
{
"code": null,
"e": 25529,
"s": 25357,
"text": "SQL> select * from GFG where author='&author';\nEnter value for author: maria\nold 1: select * from GFG where author='&author'\nnew 1: select * from GFG where author='maria' "
},
{
"code": null,
"e": 25615,
"s": 25529,
"text": "Example-2: Let us update a record with a given author. (Here, author is a text value)"
},
{
"code": null,
"e": 25817,
"s": 25615,
"text": "SQL> update GFG set likes=10 where author='&author';\nEnter value for author: sam\nold 1: update GFG set likes=10 where author='&author'\nnew 1: update GFG set likes=10 where author='sam' \n1 row updated. "
},
{
"code": null,
"e": 25842,
"s": 25817,
"text": "SQL> select * from GFG; "
},
{
"code": null,
"e": 25851,
"s": 25842,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 25862,
"s": 25851,
"text": "SQL-PL/SQL"
},
{
"code": null,
"e": 25867,
"s": 25862,
"text": "DBMS"
},
{
"code": null,
"e": 25871,
"s": 25867,
"text": "SQL"
},
{
"code": null,
"e": 25876,
"s": 25871,
"text": "DBMS"
},
{
"code": null,
"e": 25880,
"s": 25876,
"text": "SQL"
},
{
"code": null,
"e": 25978,
"s": 25880,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25987,
"s": 25978,
"text": "Comments"
},
{
"code": null,
"e": 26000,
"s": 25987,
"text": "Old Comments"
},
{
"code": null,
"e": 26053,
"s": 26000,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 26064,
"s": 26053,
"text": "CTE in SQL"
},
{
"code": null,
"e": 26076,
"s": 26064,
"text": "SQL | Views"
},
{
"code": null,
"e": 26121,
"s": 26076,
"text": "Difference between DELETE, DROP and TRUNCATE"
},
{
"code": null,
"e": 26168,
"s": 26121,
"text": "Difference between Primary Key and Foreign Key"
},
{
"code": null,
"e": 26210,
"s": 26168,
"text": "SQL | DDL, DQL, DML, DCL and TCL Commands"
},
{
"code": null,
"e": 26254,
"s": 26210,
"text": "How to find Nth highest salary from a table"
},
{
"code": null,
"e": 26275,
"s": 26254,
"text": "SQL | ALTER (RENAME)"
},
{
"code": null,
"e": 26286,
"s": 26275,
"text": "CTE in SQL"
}
] |
Natural Language Toolkit - Word Replacement
|
Stemming and lemmatization can be considered as a kind of linguistic compression. In the same sense, word replacement can be thought of as text normalization or error correction.
But why we needed word replacement? Suppose if we talk about tokenization, then it is having issues with contractions (like can’t, won’t, etc.). So, to handle such issues we need word replacement. For example, we can replace contractions with their expanded forms.
First, we are going to replace words that matches the regular expression. But for this we must have a basic understanding of regular expressions as well as python re module. In the example below, we will be replacing contraction with their expanded forms (e.g. “can’t” will be replaced with “cannot”), all that by using regular expressions.
First, import the necessary package re to work with regular expressions.
import re
from nltk.corpus import wordnet
Next, define the replacement patterns of your choice as follows −
R_patterns = [
(r'won\'t', 'will not'),
(r'can\'t', 'cannot'),
(r'i\'m', 'i am'),
r'(\w+)\'ll', '\g<1> will'),
(r'(\w+)n\'t', '\g<1> not'),
(r'(\w+)\'ve', '\g<1> have'),
(r'(\w+)\'s', '\g<1> is'),
(r'(\w+)\'re', '\g<1> are'),
]
Now, create a class that can be used for replacing words −
class REReplacer(object):
def __init__(self, pattern = R_patterns):
self.pattern = [(re.compile(regex), repl) for (regex, repl) in patterns]
def replace(self, text):
s = text
for (pattern, repl) in self.pattern:
s = re.sub(pattern, repl, s)
return s
Save this python program (say repRE.py) and run it from python command prompt. After running it, import REReplacer class when you want to replace words. Let us see how.
from repRE import REReplacer
rep_word = REReplacer()
rep_word.replace("I won't do it")
Output:
'I will not do it'
rep_word.replace("I can’t do it")
Output:
'I cannot do it'
import re
from nltk.corpus import wordnet
R_patterns = [
(r'won\'t', 'will not'),
(r'can\'t', 'cannot'),
(r'i\'m', 'i am'),
r'(\w+)\'ll', '\g<1> will'),
(r'(\w+)n\'t', '\g<1> not'),
(r'(\w+)\'ve', '\g<1> have'),
(r'(\w+)\'s', '\g<1> is'),
(r'(\w+)\'re', '\g<1> are'),
]
class REReplacer(object):
def __init__(self, patterns=R_patterns):
self.patterns = [(re.compile(regex), repl) for (regex, repl) in patterns]
def replace(self, text):
s = text
for (pattern, repl) in self.patterns:
s = re.sub(pattern, repl, s)
return s
Now once you saved the above program and run it, you can import the class and use it as follows −
from replacerRE import REReplacer
rep_word = REReplacer()
rep_word.replace("I won't do it")
'I will not do it'
One of the common practices while working with natural language processing (NLP) is to clean up the text before text processing. In this concern we can also use our REReplacer class created above in previous example, as a preliminary step before text processing i.e. tokenization.
from nltk.tokenize import word_tokenize
from replacerRE import REReplacer
rep_word = REReplacer()
word_tokenize("I won't be able to do this now")
Output:
['I', 'wo', "n't", 'be', 'able', 'to', 'do', 'this', 'now']
word_tokenize(rep_word.replace("I won't be able to do this now"))
Output:
['I', 'will', 'not', 'be', 'able', 'to', 'do', 'this', 'now']
In the above Python recipe, we can easily understand the difference between the output of word tokenizer without and with using regular expression replace.
Do we strictly grammatical in our everyday language? No, we are not. For example, sometimes we write ‘Hiiiiiiiiiiii Mohan’ in order to emphasize the word ‘Hi’. But computer system does not know that ‘Hiiiiiiiiiiii’ is a variation of the word “Hi”. In the example below, we will be creating a class named rep_word_removal which can be used for removing the repeating words.
First, import the necessary package re to work with regular expressions
import re
from nltk.corpus import wordnet
Now, create a class that can be used for removing the repeating words −
class Rep_word_removal(object):
def __init__(self):
self.repeat_regexp = re.compile(r'(\w*)(\w)\2(\w*)')
self.repl = r'\1\2\3'
def replace(self, word):
if wordnet.synsets(word):
return word
repl_word = self.repeat_regexp.sub(self.repl, word)
if repl_word != word:
return self.replace(repl_word)
else:
return repl_word
Save this python program (say removalrepeat.py) and run it from python command prompt. After running it, import Rep_word_removal class when you want to remove the repeating words. Let us see how?
from removalrepeat import Rep_word_removal
rep_word = Rep_word_removal()
rep_word.replace ("Hiiiiiiiiiiiiiiiiiiiii")
Output:
'Hi'
rep_word.replace("Hellooooooooooooooo")
Output:
'Hello'
import re
from nltk.corpus import wordnet
class Rep_word_removal(object):
def __init__(self):
self.repeat_regexp = re.compile(r'(\w*)(\w)\2(\w*)')
self.repl = r'\1\2\3'
def replace(self, word):
if wordnet.synsets(word):
return word
replace_word = self.repeat_regexp.sub(self.repl, word)
if replace_word != word:
return self.replace(replace_word)
else:
return replace_word
Now once you saved the above program and run it, you can import the class and use it as follows −
from removalrepeat import Rep_word_removal
rep_word = Rep_word_removal()
rep_word.replace ("Hiiiiiiiiiiiiiiiiiiiii")
'Hi'
59 Lectures
2.5 hours
Mike West
17 Lectures
1 hours
Pranjal Srivastava
6 Lectures
1 hours
Prabh Kirpa Classes
12 Lectures
1 hours
Stone River ELearning
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2563,
"s": 2384,
"text": "Stemming and lemmatization can be considered as a kind of linguistic compression. In the same sense, word replacement can be thought of as text normalization or error correction."
},
{
"code": null,
"e": 2828,
"s": 2563,
"text": "But why we needed word replacement? Suppose if we talk about tokenization, then it is having issues with contractions (like can’t, won’t, etc.). So, to handle such issues we need word replacement. For example, we can replace contractions with their expanded forms."
},
{
"code": null,
"e": 3169,
"s": 2828,
"text": "First, we are going to replace words that matches the regular expression. But for this we must have a basic understanding of regular expressions as well as python re module. In the example below, we will be replacing contraction with their expanded forms (e.g. “can’t” will be replaced with “cannot”), all that by using regular expressions."
},
{
"code": null,
"e": 3242,
"s": 3169,
"text": "First, import the necessary package re to work with regular expressions."
},
{
"code": null,
"e": 3284,
"s": 3242,
"text": "import re\nfrom nltk.corpus import wordnet"
},
{
"code": null,
"e": 3350,
"s": 3284,
"text": "Next, define the replacement patterns of your choice as follows −"
},
{
"code": null,
"e": 3602,
"s": 3350,
"text": "R_patterns = [\n (r'won\\'t', 'will not'),\n (r'can\\'t', 'cannot'),\n (r'i\\'m', 'i am'),\n r'(\\w+)\\'ll', '\\g<1> will'),\n (r'(\\w+)n\\'t', '\\g<1> not'),\n (r'(\\w+)\\'ve', '\\g<1> have'),\n (r'(\\w+)\\'s', '\\g<1> is'),\n (r'(\\w+)\\'re', '\\g<1> are'),\n]"
},
{
"code": null,
"e": 3661,
"s": 3602,
"text": "Now, create a class that can be used for replacing words −"
},
{
"code": null,
"e": 3950,
"s": 3661,
"text": "class REReplacer(object):\n def __init__(self, pattern = R_patterns):\n self.pattern = [(re.compile(regex), repl) for (regex, repl) in patterns]\n def replace(self, text):\n s = text\n for (pattern, repl) in self.pattern:\n s = re.sub(pattern, repl, s)\n return s"
},
{
"code": null,
"e": 4119,
"s": 3950,
"text": "Save this python program (say repRE.py) and run it from python command prompt. After running it, import REReplacer class when you want to replace words. Let us see how."
},
{
"code": null,
"e": 4292,
"s": 4119,
"text": "from repRE import REReplacer\nrep_word = REReplacer()\nrep_word.replace(\"I won't do it\")\nOutput:\n'I will not do it'\nrep_word.replace(\"I can’t do it\")\nOutput:\n'I cannot do it'"
},
{
"code": null,
"e": 4855,
"s": 4292,
"text": "import re\nfrom nltk.corpus import wordnet\nR_patterns = [\n (r'won\\'t', 'will not'),\n (r'can\\'t', 'cannot'),\n (r'i\\'m', 'i am'),\n r'(\\w+)\\'ll', '\\g<1> will'),\n (r'(\\w+)n\\'t', '\\g<1> not'),\n (r'(\\w+)\\'ve', '\\g<1> have'),\n (r'(\\w+)\\'s', '\\g<1> is'),\n (r'(\\w+)\\'re', '\\g<1> are'),\n]\nclass REReplacer(object):\ndef __init__(self, patterns=R_patterns):\n self.patterns = [(re.compile(regex), repl) for (regex, repl) in patterns]\ndef replace(self, text):\n s = text\n for (pattern, repl) in self.patterns:\n s = re.sub(pattern, repl, s)\n return s"
},
{
"code": null,
"e": 4953,
"s": 4855,
"text": "Now once you saved the above program and run it, you can import the class and use it as follows −"
},
{
"code": null,
"e": 5045,
"s": 4953,
"text": "from replacerRE import REReplacer\nrep_word = REReplacer()\nrep_word.replace(\"I won't do it\")"
},
{
"code": null,
"e": 5065,
"s": 5045,
"text": "'I will not do it'\n"
},
{
"code": null,
"e": 5346,
"s": 5065,
"text": "One of the common practices while working with natural language processing (NLP) is to clean up the text before text processing. In this concern we can also use our REReplacer class created above in previous example, as a preliminary step before text processing i.e. tokenization."
},
{
"code": null,
"e": 5696,
"s": 5346,
"text": "from nltk.tokenize import word_tokenize\nfrom replacerRE import REReplacer\nrep_word = REReplacer()\nword_tokenize(\"I won't be able to do this now\")\nOutput:\n['I', 'wo', \"n't\", 'be', 'able', 'to', 'do', 'this', 'now']\nword_tokenize(rep_word.replace(\"I won't be able to do this now\"))\nOutput:\n['I', 'will', 'not', 'be', 'able', 'to', 'do', 'this', 'now']"
},
{
"code": null,
"e": 5852,
"s": 5696,
"text": "In the above Python recipe, we can easily understand the difference between the output of word tokenizer without and with using regular expression replace."
},
{
"code": null,
"e": 6225,
"s": 5852,
"text": "Do we strictly grammatical in our everyday language? No, we are not. For example, sometimes we write ‘Hiiiiiiiiiiii Mohan’ in order to emphasize the word ‘Hi’. But computer system does not know that ‘Hiiiiiiiiiiii’ is a variation of the word “Hi”. In the example below, we will be creating a class named rep_word_removal which can be used for removing the repeating words."
},
{
"code": null,
"e": 6297,
"s": 6225,
"text": "First, import the necessary package re to work with regular expressions"
},
{
"code": null,
"e": 6339,
"s": 6297,
"text": "import re\nfrom nltk.corpus import wordnet"
},
{
"code": null,
"e": 6411,
"s": 6339,
"text": "Now, create a class that can be used for removing the repeating words −"
},
{
"code": null,
"e": 6780,
"s": 6411,
"text": "class Rep_word_removal(object):\n def __init__(self):\n self.repeat_regexp = re.compile(r'(\\w*)(\\w)\\2(\\w*)')\n self.repl = r'\\1\\2\\3'\n def replace(self, word):\n if wordnet.synsets(word):\n return word\n repl_word = self.repeat_regexp.sub(self.repl, word)\n if repl_word != word:\n return self.replace(repl_word)\n else:\n return repl_word"
},
{
"code": null,
"e": 6976,
"s": 6780,
"text": "Save this python program (say removalrepeat.py) and run it from python command prompt. After running it, import Rep_word_removal class when you want to remove the repeating words. Let us see how?"
},
{
"code": null,
"e": 7162,
"s": 6976,
"text": "from removalrepeat import Rep_word_removal\nrep_word = Rep_word_removal()\nrep_word.replace (\"Hiiiiiiiiiiiiiiiiiiiii\")\nOutput:\n'Hi'\nrep_word.replace(\"Hellooooooooooooooo\")\nOutput:\n'Hello'"
},
{
"code": null,
"e": 7588,
"s": 7162,
"text": "import re\nfrom nltk.corpus import wordnet\nclass Rep_word_removal(object):\n def __init__(self):\n self.repeat_regexp = re.compile(r'(\\w*)(\\w)\\2(\\w*)')\n self.repl = r'\\1\\2\\3'\n def replace(self, word):\n if wordnet.synsets(word):\n return word\n replace_word = self.repeat_regexp.sub(self.repl, word)\n if replace_word != word:\n return self.replace(replace_word)\n else:\n return replace_word"
},
{
"code": null,
"e": 7686,
"s": 7588,
"text": "Now once you saved the above program and run it, you can import the class and use it as follows −"
},
{
"code": null,
"e": 7803,
"s": 7686,
"text": "from removalrepeat import Rep_word_removal\nrep_word = Rep_word_removal()\nrep_word.replace (\"Hiiiiiiiiiiiiiiiiiiiii\")"
},
{
"code": null,
"e": 7809,
"s": 7803,
"text": "'Hi'\n"
},
{
"code": null,
"e": 7844,
"s": 7809,
"text": "\n 59 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7855,
"s": 7844,
"text": " Mike West"
},
{
"code": null,
"e": 7888,
"s": 7855,
"text": "\n 17 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 7908,
"s": 7888,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 7940,
"s": 7908,
"text": "\n 6 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 7961,
"s": 7940,
"text": " Prabh Kirpa Classes"
},
{
"code": null,
"e": 7994,
"s": 7961,
"text": "\n 12 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8017,
"s": 7994,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 8024,
"s": 8017,
"text": " Print"
},
{
"code": null,
"e": 8035,
"s": 8024,
"text": " Add Notes"
}
] |
How to create a function in MATLAB ? - GeeksforGeeks
|
26 May, 2021
A function is a block of statements that intend to perform a specific task. Functions allow the users to reuse the code frequently. MATLAB has several predefined functions which are ready to use such as sin(), fact(), cos() etc. MATLAB also allows the users to define their own functions.
Syntax:
function output_params = function_name(iput_params)
% Statements
end
The function starts with the keyword function.
Returning variables of the function are defined in output_params
function_name specifies the name of the function
input_params are input arguments to the function
Below are some examples that depict how to use functions in MATLAB:
Example 1: Function with one output
The function calculates the mean of the input vector
Matlab
% Input vectorvalues = [12, 4, 8.9, 6, 3]; % function return mean of vector cfunction m = stat(x) n = length(x); m = sum(x)/n;end mean = stat(values)
Output :
mean = 6.7800
Example 2: Function with multiple outputs
The function calculates both nCr and nPr of inputs n and r.
Matlab
% Inputx = 3;y = 2; % Function return p = nPr and c = nCrfunction [p,c] = perm(n,r) p = factorial(n)/factorial(n-r); c = p*factorial(r);end [p,c] = perm(x,y)
Output :
p = 6
c = 12
Example 3: Multiple functions in a file
stat2() function calculates the standard deviation of the input vector.
stat1() calculates the mean of the input vector.
Matlab
values = [12, 4, 8.9, 6, 3]; % Function returns standard deviation of vector xfunction sd = stat2(x) m = stat1(x); n = length(x) sd = sqrt(sum((x-m).^2/n));end % Function returns mean of vector xfunction m = stat1(x) n = length(x); m = sum(x)/n;end stat2(values)
Output :
n = 5
ans = 3.2975
Example 4: Function with no input_params
In this program, we will create the sin_plot() function that plots the sin() function
Matlab
% Plotting sin(x) functionfunction sin_plot() x = linspace(0,2*pi,100); y = sin(x); plot(x,y);end sin_plot()
Output :
saurabh1990aror
Picked
MATLAB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between Convolution VS Correlation
Boundary Extraction of image using MATLAB
How to Remove Noise from Digital Image in Frequency Domain Using MATLAB?
Laplacian of Gaussian Filter in MATLAB
How to Solve Histogram Equalization Numerical Problem in MATLAB?
Forward and Inverse Fourier Transform of an Image in MATLAB
Differential or Derivatives in MATLAB
MATLAB Syntax
How to Remove Salt and Pepper Noise from Image Using MATLAB?
How to Normalize a Histogram in MATLAB?
|
[
{
"code": null,
"e": 24468,
"s": 24440,
"text": "\n26 May, 2021"
},
{
"code": null,
"e": 24757,
"s": 24468,
"text": "A function is a block of statements that intend to perform a specific task. Functions allow the users to reuse the code frequently. MATLAB has several predefined functions which are ready to use such as sin(), fact(), cos() etc. MATLAB also allows the users to define their own functions."
},
{
"code": null,
"e": 24765,
"s": 24757,
"text": "Syntax:"
},
{
"code": null,
"e": 24817,
"s": 24765,
"text": "function output_params = function_name(iput_params)"
},
{
"code": null,
"e": 24837,
"s": 24817,
"text": " % Statements"
},
{
"code": null,
"e": 24841,
"s": 24837,
"text": "end"
},
{
"code": null,
"e": 24888,
"s": 24841,
"text": "The function starts with the keyword function."
},
{
"code": null,
"e": 24953,
"s": 24888,
"text": "Returning variables of the function are defined in output_params"
},
{
"code": null,
"e": 25002,
"s": 24953,
"text": "function_name specifies the name of the function"
},
{
"code": null,
"e": 25051,
"s": 25002,
"text": "input_params are input arguments to the function"
},
{
"code": null,
"e": 25119,
"s": 25051,
"text": "Below are some examples that depict how to use functions in MATLAB:"
},
{
"code": null,
"e": 25155,
"s": 25119,
"text": "Example 1: Function with one output"
},
{
"code": null,
"e": 25208,
"s": 25155,
"text": "The function calculates the mean of the input vector"
},
{
"code": null,
"e": 25215,
"s": 25208,
"text": "Matlab"
},
{
"code": "% Input vectorvalues = [12, 4, 8.9, 6, 3]; % function return mean of vector cfunction m = stat(x) n = length(x); m = sum(x)/n;end mean = stat(values)",
"e": 25371,
"s": 25215,
"text": null
},
{
"code": null,
"e": 25384,
"s": 25375,
"text": "Output :"
},
{
"code": null,
"e": 25400,
"s": 25386,
"text": "mean = 6.7800"
},
{
"code": null,
"e": 25444,
"s": 25402,
"text": "Example 2: Function with multiple outputs"
},
{
"code": null,
"e": 25506,
"s": 25446,
"text": "The function calculates both nCr and nPr of inputs n and r."
},
{
"code": null,
"e": 25515,
"s": 25508,
"text": "Matlab"
},
{
"code": "% Inputx = 3;y = 2; % Function return p = nPr and c = nCrfunction [p,c] = perm(n,r) p = factorial(n)/factorial(n-r); c = p*factorial(r);end [p,c] = perm(x,y)",
"e": 25679,
"s": 25515,
"text": null
},
{
"code": null,
"e": 25692,
"s": 25683,
"text": "Output :"
},
{
"code": null,
"e": 25707,
"s": 25694,
"text": "p = 6\nc = 12"
},
{
"code": null,
"e": 25749,
"s": 25709,
"text": "Example 3: Multiple functions in a file"
},
{
"code": null,
"e": 25823,
"s": 25751,
"text": "stat2() function calculates the standard deviation of the input vector."
},
{
"code": null,
"e": 25872,
"s": 25823,
"text": "stat1() calculates the mean of the input vector."
},
{
"code": null,
"e": 25881,
"s": 25874,
"text": "Matlab"
},
{
"code": "values = [12, 4, 8.9, 6, 3]; % Function returns standard deviation of vector xfunction sd = stat2(x) m = stat1(x); n = length(x) sd = sqrt(sum((x-m).^2/n));end % Function returns mean of vector xfunction m = stat1(x) n = length(x); m = sum(x)/n;end stat2(values)",
"e": 26159,
"s": 25881,
"text": null
},
{
"code": null,
"e": 26168,
"s": 26159,
"text": "Output :"
},
{
"code": null,
"e": 26187,
"s": 26168,
"text": "n = 5\nans = 3.2975"
},
{
"code": null,
"e": 26228,
"s": 26187,
"text": "Example 4: Function with no input_params"
},
{
"code": null,
"e": 26314,
"s": 26228,
"text": "In this program, we will create the sin_plot() function that plots the sin() function"
},
{
"code": null,
"e": 26321,
"s": 26314,
"text": "Matlab"
},
{
"code": "% Plotting sin(x) functionfunction sin_plot() x = linspace(0,2*pi,100); y = sin(x); plot(x,y);end sin_plot()",
"e": 26441,
"s": 26321,
"text": null
},
{
"code": null,
"e": 26454,
"s": 26445,
"text": "Output :"
},
{
"code": null,
"e": 26474,
"s": 26458,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 26481,
"s": 26474,
"text": "Picked"
},
{
"code": null,
"e": 26488,
"s": 26481,
"text": "MATLAB"
},
{
"code": null,
"e": 26586,
"s": 26488,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26595,
"s": 26586,
"text": "Comments"
},
{
"code": null,
"e": 26608,
"s": 26595,
"text": "Old Comments"
},
{
"code": null,
"e": 26654,
"s": 26608,
"text": "Difference between Convolution VS Correlation"
},
{
"code": null,
"e": 26696,
"s": 26654,
"text": "Boundary Extraction of image using MATLAB"
},
{
"code": null,
"e": 26769,
"s": 26696,
"text": "How to Remove Noise from Digital Image in Frequency Domain Using MATLAB?"
},
{
"code": null,
"e": 26808,
"s": 26769,
"text": "Laplacian of Gaussian Filter in MATLAB"
},
{
"code": null,
"e": 26873,
"s": 26808,
"text": "How to Solve Histogram Equalization Numerical Problem in MATLAB?"
},
{
"code": null,
"e": 26933,
"s": 26873,
"text": "Forward and Inverse Fourier Transform of an Image in MATLAB"
},
{
"code": null,
"e": 26971,
"s": 26933,
"text": "Differential or Derivatives in MATLAB"
},
{
"code": null,
"e": 26985,
"s": 26971,
"text": "MATLAB Syntax"
},
{
"code": null,
"e": 27046,
"s": 26985,
"text": "How to Remove Salt and Pepper Noise from Image Using MATLAB?"
}
] |
Fast I/O for Competitive Programming - GeeksforGeeks
|
08 Nov, 2021
In competitive programming, it is important to read input as fast as possible so we save valuable time.
You must have seen various problem statements saying: “Warning: Large I/O data, be careful with certain languages (though most should be OK if the algorithm is well designed)”. The key for such problems is to use Faster I/O techniques.
It is often recommended to use scanf/printf instead of cin/cout for fast input and output. However, you can still use cin/cout and achieve the same speed as scanf/printf by including the following two lines in your main() function:
ios_base::sync_with_stdio(false);
It toggles on or off the synchronization of all the C++ standard streams with their corresponding standard C streams if it is called before the program performs its first input or output operation. Adding ios_base::sync_with_stdio (false); (which is true by default) before any I/O operation avoids this synchronization. It is a static member of the function of std::ios_base.
cin.tie(NULL);
tie() is a method that simply guarantees the flushing of std::cout before std::cin accepts an input. This is useful for interactive console programs which require the console to be updated constantly but also slows down the program for large I/O. The NULL part just returns a NULL pointer.
Moreover, you can include the standard template library (STL) with a single include:
#include <bits/stdc++.h>
So your template for competitive programming could look like this:
#include <bits/stdc++.h>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
return 0;
}
It is recommended to use cout << “\n”; instead of cout << endl;. endl is slower because it forces a flushing stream, which is usually unnecessary (See this for details). (You’d need to flush if you were writing, say, an interactive progress bar, but not when writing a million lines of data.) Write ‘\n instead of endl.
We can test our input and output methods on the problem INTEST – Enormous Input Teston SPOJ. Before further reading, I would suggest you solve the problem first.Solution in C++ 4.9.2
Normal I/O: The code below uses cin and cout. The solution gets accepted with a runtime of 2.17 seconds.
C++
// A normal IO example code#include <bits/stdc++.h>using namespace std;int main(){ int n, k, t; int cnt = 0; cin >> n >> k; for (int i=0; i<n; i++) { cin >> t; if (t % k == 0) cnt++; } cout << cnt << "\n"; return 0;}
Fast I/O However, we can do better and reduce the runtime a lot by adding two lines. The program below gets accepted with a runtime of 0.41 seconds.
C++
// A fast IO program#include <bits/stdc++.h>using namespace std; int main(){ // added the two lines below ios_base::sync_with_stdio(false); cin.tie(NULL); int n, k, t; int cnt = 0; cin >> n >> k; for (int i=0; i<n; i++) { cin >> t; if (t % k == 0) cnt++; } cout << cnt << "\n"; return 0;}
Now, talking about competitive contests like ACM ICPC, Google CodeJam, TopCoder Open, here is an exclusive code to read integers in the fastest way.
C++
void fastscan(int &number){ //variable to indicate sign of input number bool negative = false; register int c; number = 0; // extract current character from buffer c = getchar(); if (c=='-') { // number is negative negative = true; // extract the next character from the buffer c = getchar(); } // Keep on extracting characters if they are integers // i.e ASCII Value lies from '0'(48) to '9' (57) for (; (c>47 && c<58); c=getchar()) number = number *10 + c - 48; // if scanned input has a negative sign, negate the // value of the input number if (negative) number *= -1;} // Function Callint main(){ int number; fastscan(number); cout << number << "\n"; return 0;}
getchar_unlocked() for faster input in C for competitive programming
YouTubeGeeksforGeeks501K subscribersFast Input/Output | Sample Video for C++ Productivity Hacks | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:48•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=DhPMRStOU7o" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Vinay Garg. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
pujasingg43
C++
Competitive Programming
GBlog
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Socket Programming in C/C++
C++ Classes and Objects
Operator Overloading in C++
Multidimensional Arrays in C / C++
Virtual Function in C++
Practice for cracking any coding interview
Arrow operator -> in C/C++ with Examples
Competitive Programming - A Complete Guide
Modulo 10^9+7 (1000000007)
Top 10 Algorithms and Data Structures for Competitive Programming
|
[
{
"code": null,
"e": 24750,
"s": 24722,
"text": "\n08 Nov, 2021"
},
{
"code": null,
"e": 24854,
"s": 24750,
"text": "In competitive programming, it is important to read input as fast as possible so we save valuable time."
},
{
"code": null,
"e": 25091,
"s": 24854,
"text": "You must have seen various problem statements saying: “Warning: Large I/O data, be careful with certain languages (though most should be OK if the algorithm is well designed)”. The key for such problems is to use Faster I/O techniques. "
},
{
"code": null,
"e": 25323,
"s": 25091,
"text": "It is often recommended to use scanf/printf instead of cin/cout for fast input and output. However, you can still use cin/cout and achieve the same speed as scanf/printf by including the following two lines in your main() function:"
},
{
"code": null,
"e": 25361,
"s": 25323,
"text": " ios_base::sync_with_stdio(false);"
},
{
"code": null,
"e": 25739,
"s": 25361,
"text": "It toggles on or off the synchronization of all the C++ standard streams with their corresponding standard C streams if it is called before the program performs its first input or output operation. Adding ios_base::sync_with_stdio (false); (which is true by default) before any I/O operation avoids this synchronization. It is a static member of the function of std::ios_base. "
},
{
"code": null,
"e": 25758,
"s": 25739,
"text": " cin.tie(NULL);"
},
{
"code": null,
"e": 26048,
"s": 25758,
"text": "tie() is a method that simply guarantees the flushing of std::cout before std::cin accepts an input. This is useful for interactive console programs which require the console to be updated constantly but also slows down the program for large I/O. The NULL part just returns a NULL pointer."
},
{
"code": null,
"e": 26135,
"s": 26048,
"text": "Moreover, you can include the standard template library (STL) with a single include: "
},
{
"code": null,
"e": 26164,
"s": 26135,
"text": " #include <bits/stdc++.h>"
},
{
"code": null,
"e": 26233,
"s": 26164,
"text": "So your template for competitive programming could look like this: "
},
{
"code": null,
"e": 26366,
"s": 26233,
"text": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n ios_base::sync_with_stdio(false);\n cin.tie(NULL);\n return 0;\n}"
},
{
"code": null,
"e": 26686,
"s": 26366,
"text": "It is recommended to use cout << “\\n”; instead of cout << endl;. endl is slower because it forces a flushing stream, which is usually unnecessary (See this for details). (You’d need to flush if you were writing, say, an interactive progress bar, but not when writing a million lines of data.) Write ‘\\n instead of endl."
},
{
"code": null,
"e": 26869,
"s": 26686,
"text": "We can test our input and output methods on the problem INTEST – Enormous Input Teston SPOJ. Before further reading, I would suggest you solve the problem first.Solution in C++ 4.9.2"
},
{
"code": null,
"e": 26975,
"s": 26869,
"text": "Normal I/O: The code below uses cin and cout. The solution gets accepted with a runtime of 2.17 seconds. "
},
{
"code": null,
"e": 26979,
"s": 26975,
"text": "C++"
},
{
"code": "// A normal IO example code#include <bits/stdc++.h>using namespace std;int main(){ int n, k, t; int cnt = 0; cin >> n >> k; for (int i=0; i<n; i++) { cin >> t; if (t % k == 0) cnt++; } cout << cnt << \"\\n\"; return 0;}",
"e": 27245,
"s": 26979,
"text": null
},
{
"code": null,
"e": 27394,
"s": 27245,
"text": "Fast I/O However, we can do better and reduce the runtime a lot by adding two lines. The program below gets accepted with a runtime of 0.41 seconds."
},
{
"code": null,
"e": 27398,
"s": 27394,
"text": "C++"
},
{
"code": "// A fast IO program#include <bits/stdc++.h>using namespace std; int main(){ // added the two lines below ios_base::sync_with_stdio(false); cin.tie(NULL); int n, k, t; int cnt = 0; cin >> n >> k; for (int i=0; i<n; i++) { cin >> t; if (t % k == 0) cnt++; } cout << cnt << \"\\n\"; return 0;}",
"e": 27752,
"s": 27398,
"text": null
},
{
"code": null,
"e": 27901,
"s": 27752,
"text": "Now, talking about competitive contests like ACM ICPC, Google CodeJam, TopCoder Open, here is an exclusive code to read integers in the fastest way."
},
{
"code": null,
"e": 27905,
"s": 27901,
"text": "C++"
},
{
"code": "void fastscan(int &number){ //variable to indicate sign of input number bool negative = false; register int c; number = 0; // extract current character from buffer c = getchar(); if (c=='-') { // number is negative negative = true; // extract the next character from the buffer c = getchar(); } // Keep on extracting characters if they are integers // i.e ASCII Value lies from '0'(48) to '9' (57) for (; (c>47 && c<58); c=getchar()) number = number *10 + c - 48; // if scanned input has a negative sign, negate the // value of the input number if (negative) number *= -1;} // Function Callint main(){ int number; fastscan(number); cout << number << \"\\n\"; return 0;}",
"e": 28676,
"s": 27905,
"text": null
},
{
"code": null,
"e": 28747,
"s": 28676,
"text": "getchar_unlocked() for faster input in C for competitive programming "
},
{
"code": null,
"e": 29605,
"s": 28747,
"text": "YouTubeGeeksforGeeks501K subscribersFast Input/Output | Sample Video for C++ Productivity Hacks | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:48•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=DhPMRStOU7o\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 29994,
"s": 29605,
"text": "This article is contributed by Vinay Garg. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 30006,
"s": 29994,
"text": "pujasingg43"
},
{
"code": null,
"e": 30010,
"s": 30006,
"text": "C++"
},
{
"code": null,
"e": 30034,
"s": 30010,
"text": "Competitive Programming"
},
{
"code": null,
"e": 30040,
"s": 30034,
"text": "GBlog"
},
{
"code": null,
"e": 30044,
"s": 30040,
"text": "CPP"
},
{
"code": null,
"e": 30142,
"s": 30044,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30151,
"s": 30142,
"text": "Comments"
},
{
"code": null,
"e": 30164,
"s": 30151,
"text": "Old Comments"
},
{
"code": null,
"e": 30192,
"s": 30164,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 30216,
"s": 30192,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 30244,
"s": 30216,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 30279,
"s": 30244,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 30303,
"s": 30279,
"text": "Virtual Function in C++"
},
{
"code": null,
"e": 30346,
"s": 30303,
"text": "Practice for cracking any coding interview"
},
{
"code": null,
"e": 30387,
"s": 30346,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 30430,
"s": 30387,
"text": "Competitive Programming - A Complete Guide"
},
{
"code": null,
"e": 30457,
"s": 30430,
"text": "Modulo 10^9+7 (1000000007)"
}
] |
How to Change Colours in Command Prompt in Windows? - GeeksforGeeks
|
23 Mar, 2020
Command Prompt is a neat command-line interpreter that comes in-built with the Windows operating system. Command prompt is still used for performing various functions such as, collecting information on the network state of the computer, troubleshooting the system, deleting files, formatting computers, etc.Customizing the Command Prompt according to your needs may end up resulting in your productivity and if you are a young learner who started learning about Command Prompt recently, you will want to check this out! First, it’s important to know for reference how a default Command Prompt terminal looks like, it looks something like this:
Here, we are going to change the color text and also the background color of cmd. Assume 2 variable x & y which are associated with specific colors.
color xy
‘x‘ represents the color of the Terminal’s background, whereas,‘y‘ represents the color of the font on the Command Prompt Terminal.
Following the HEX values of the colors supported by Command Prompt:
0 = Black 8 = Gray
1 = Blue 9 = Light Blue
2 = Green A = Light Green
3 = Aqua B = Light Aqua
4 = Red C = Light Red
5 = Purple D = Light Purple
6 = Yellow E = Light Yellow
7 = White F = Bright White
Example 1: Suppose we want a white background, so after referring to the color table above we will type, ‘f’ in place of ‘x’. Similarly, if we want a light purple colored font, we will type ‘d’ in place of ‘y’.(x & y are the variables we had assumed earlier).
color fd
Example 2: ‘0’ specifies the black color attribute, and since its typed at the place of ‘x’ i.e. it will be applied to background. ‘a’ specifies the light green color attribute, and since its typed at the place of ‘y’ i.e light green attribute will be applied to the font color.
color 0a
Note: To get all the related information on using color command in Command Prompt you can use the following command
color /?
TechTips
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Add External JAR File to an IntelliJ IDEA Project?
Difference between RUN vs CMD vs ENTRYPOINT Docker Commands
How to Delete Temporary Files in Windows 10?
How to Convert Kotlin Code to Java Code in Android Studio?
How to Clone Android Project from GitHub in Android Studio?
How to Install Flutter on Windows?
How to Install Z Shell(zsh) on Linux?
Top 10 VS Code Extensions For Angular Developers
Autorun a Python script on windows startup
How to Access Localhost on Mobile Browsers?
|
[
{
"code": null,
"e": 24964,
"s": 24936,
"text": "\n23 Mar, 2020"
},
{
"code": null,
"e": 25608,
"s": 24964,
"text": "Command Prompt is a neat command-line interpreter that comes in-built with the Windows operating system. Command prompt is still used for performing various functions such as, collecting information on the network state of the computer, troubleshooting the system, deleting files, formatting computers, etc.Customizing the Command Prompt according to your needs may end up resulting in your productivity and if you are a young learner who started learning about Command Prompt recently, you will want to check this out! First, it’s important to know for reference how a default Command Prompt terminal looks like, it looks something like this:"
},
{
"code": null,
"e": 25757,
"s": 25608,
"text": "Here, we are going to change the color text and also the background color of cmd. Assume 2 variable x & y which are associated with specific colors."
},
{
"code": null,
"e": 25766,
"s": 25757,
"text": "color xy"
},
{
"code": null,
"e": 25898,
"s": 25766,
"text": "‘x‘ represents the color of the Terminal’s background, whereas,‘y‘ represents the color of the font on the Command Prompt Terminal."
},
{
"code": null,
"e": 25966,
"s": 25898,
"text": "Following the HEX values of the colors supported by Command Prompt:"
},
{
"code": null,
"e": 26247,
"s": 25966,
"text": " 0 = Black 8 = Gray\n 1 = Blue 9 = Light Blue\n 2 = Green A = Light Green\n 3 = Aqua B = Light Aqua\n 4 = Red C = Light Red\n 5 = Purple D = Light Purple\n 6 = Yellow E = Light Yellow\n 7 = White F = Bright White\n"
},
{
"code": null,
"e": 26507,
"s": 26247,
"text": "Example 1: Suppose we want a white background, so after referring to the color table above we will type, ‘f’ in place of ‘x’. Similarly, if we want a light purple colored font, we will type ‘d’ in place of ‘y’.(x & y are the variables we had assumed earlier)."
},
{
"code": null,
"e": 26516,
"s": 26507,
"text": "color fd"
},
{
"code": null,
"e": 26795,
"s": 26516,
"text": "Example 2: ‘0’ specifies the black color attribute, and since its typed at the place of ‘x’ i.e. it will be applied to background. ‘a’ specifies the light green color attribute, and since its typed at the place of ‘y’ i.e light green attribute will be applied to the font color."
},
{
"code": null,
"e": 26804,
"s": 26795,
"text": "color 0a"
},
{
"code": null,
"e": 26920,
"s": 26804,
"text": "Note: To get all the related information on using color command in Command Prompt you can use the following command"
},
{
"code": null,
"e": 26929,
"s": 26920,
"text": "color /?"
},
{
"code": null,
"e": 26938,
"s": 26929,
"text": "TechTips"
},
{
"code": null,
"e": 27036,
"s": 26938,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27045,
"s": 27036,
"text": "Comments"
},
{
"code": null,
"e": 27058,
"s": 27045,
"text": "Old Comments"
},
{
"code": null,
"e": 27116,
"s": 27058,
"text": "How to Add External JAR File to an IntelliJ IDEA Project?"
},
{
"code": null,
"e": 27176,
"s": 27116,
"text": "Difference between RUN vs CMD vs ENTRYPOINT Docker Commands"
},
{
"code": null,
"e": 27221,
"s": 27176,
"text": "How to Delete Temporary Files in Windows 10?"
},
{
"code": null,
"e": 27280,
"s": 27221,
"text": "How to Convert Kotlin Code to Java Code in Android Studio?"
},
{
"code": null,
"e": 27340,
"s": 27280,
"text": "How to Clone Android Project from GitHub in Android Studio?"
},
{
"code": null,
"e": 27375,
"s": 27340,
"text": "How to Install Flutter on Windows?"
},
{
"code": null,
"e": 27413,
"s": 27375,
"text": "How to Install Z Shell(zsh) on Linux?"
},
{
"code": null,
"e": 27462,
"s": 27413,
"text": "Top 10 VS Code Extensions For Angular Developers"
},
{
"code": null,
"e": 27505,
"s": 27462,
"text": "Autorun a Python script on windows startup"
}
] |
4 Ways To Replace Items In Python Lists | by AnBento | Towards Data Science
|
Update: Many of you contacted me asking for valuable resources to nail Python coding interviews. Below I share 4 courses that I strongly recommend to keep exercising after practicing the algorithms in this post:
LeetCode In Python: 50 Algorithms Coding Interview Questions → Best For Coding Rounds Prep!
Python advanced Coding Problems (StrataScratch)→ Best platform I found to prepare Python & SQL coding interviews so far! Better and cheaper than LeetCode!
Practicing Coding Interview Questions In Python (60+Problems)
Python Data Engineering Nanodegree→ High Quality Course If You Have More Time To Commit. **UP TO 75% DISCOUNT ON UDACITY COURSES IN March 2022**
Hope you’ll find them useful too! Now enjoy the article :D
towardsdatascience.com
While preparing for your next Python coding round, you might have noticed that algorithms requiring to manipulate one or more lists appear rather frequently. Sooner or later, you should expect to encounter one of them during your interviews as well.
Algorithms requiring to manipulate one or more lists appear rather frequently. Sooner or later, you should expect to encounter one of them during your interviews as well.
In order to help you in the process of mastering this data structure and improve your coding skills, below I present 4 methods to replace an item in Python lists as well as four simple algorithms for you to test your skills.
Most of the classic interview questions can be solved with multiple approaches, so for each problem, try to come up with your solution first, before looking at the one I provided. Similarly to other skills, algorithmic interview is one area where you can greatly improve with consistent practice.
The most straightforward way to replace an item in a list is to use indexing, as it allows you to select an item or range of items in an list and then change the value at a specific position, using the assignment operator:
For example let’s suppose you were working with the following list including six integers:
lst = [10, 7, 12, 56, 3, 14]
and you were asked to add 10 to the third integer from the left. Since lists are indexed starting from zero, you could use one of the following syntaxes to change the element with index = 2 that in our case in the number 12:
#Option 1lst[2]= lst[2] + 10#Option 2lst[2]+= 10 #no need to repeat "lst[2]" then more elegant#Option 3lst[2] = 22 #that is 12 + 10
Now try to practice this first method solving the following problem:
Given a non-empty list including integers ( between 1 and 9) , treat it as it was representing a non-negative unique integer and increment it by one. Return the updated list.
In the result, the digits has to be stored such that the first digit of the number obtained by the sum, is at the head of the list, and each element in the list contains a single digit. You may assume the integer does not contain any leading zero, except the number 0 itself.
Note that our input list is made up of four non-negative integers that together represent the integer 9999. This in an edge case, because by adding 1 to this number, you will obtain an integer with 5 digits (instead of the original 4) and a leading 1.
To account for these type of situations, the solution takes advantage of two conditional statements that start evaluating the digits from last to first (using reverse() to flip the order of the indexes). If not equal to 9, ONLY the last digit is incremented by 1 through the now familiar syntax digits += 1 and the amended list is immediately returned, without evaluating the remaining indexes.
Alternatively, if the last digit is a 9, it is replaced by a 0 and the following (second-to-last) digit is evaluated. If this is not equal to 9, then 1 is added and the amended list returned. Otherwise, if each one of following digits is a 9, then the function will return an list with a leading 1 and as many 0s as the number of the elements in the original list.
anbento4.medium.com
In the problem above, the goal was to just replace the last integer in the list, incrementing it by 1, whereas iteration was just used to cover the edge cases.However, what if we wanted to replace multiple elements in the list at the same time?
In this instances, using a for loop will work fine as it can be employed to iterate over the items of an list. To show how it works, let’s go back to original list and multiply all the integers by 2:
lst = [10, 7, 12, 56, 3, 14]for i in range(len(lst)): lst[i] = lst[i] * 2print(lst)Output: [20, 14, 24, 112, 6, 28]
The example above was elementary, but what if you were asked to apply a slightly more complex logic while replacing items in a list?
Consider a list of integers. If the number is odd increment it by 1, if it is even increment it by 2.
Note that, instead of range(len(nums)), this solution uses the enumerate() method to iterate over all the elements of the list, check if the integers are odd or even - through the modulo operator - and replace them by adding 1 or 2 respectively.
Enumerate is a built-in function in Python and can be used to add an automatic counter while looping through an iterable object. When the optional start parameter is not specified, the counter begins from 0, behaving like it was an actual index.
For this reason, it is very common to use enumerate() to solve algorithms that require you to manipulate a list based on a condition applied to either the index or to (like in this case) the list values.
The list comprehension syntax is a more elegant method to loop through the elements of a list and apply some form of manipulation. This is because comprehensions allow you to create a new list in-line, making your code appear very clean and compact.
You can convert the for loop in the example above to a comprehension as follows:
lst = [10, 7, 12, 56, 3, 14]lst = [lst[i] * 2 for i in range(len(lst))]print(lst)Output: [20, 14, 24, 112, 6, 28]
In order to populate the new list, you are also allowed to specify basic conditions as part of list comprehension syntax. This is exactly what you’ll need to do to solve the following algorithm:
Given a list of integers, sorted in ascending order, return a list also sorted in ascending order including:- the square of the integer, if divisible by 3- the original integer, if not divisible by 3
In this case, the if condition is specified before the for loop because of the presence of an else statement. However when the else is not required, you can simply follow the syntax:
output = [ expression for element in list_1 if condition ]
At times, in coding interviews, you could be asked to re-arrange the items in a list so that they appear in a different order. This can be achieved through slicing and shuffling.
For example if you wished to swap the first 3 and last 3 elements in your initial list, you could write:
lst = [10, 7, 12, 56, 3, 14]lst = lst[3:] + lst[:3]print(lst)Output: [56, 3, 14, 10, 7, 12]
Perhaps, in this case, talking about a replacement is a bit of a stretch as you are in fact just changing the elements’ position in the list. Nonetheless, this method is quite effective and could help you solve the following problem.
Given the list of nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn]. Return the array in the form [x1,y1,x2,y2,...,xn,yn].
The exercise provides you with the index to use for slicing (in this case n=3) and requires you to shuffle the input list, by creating new integer pairs.
The integers belonging to each pair, should be the ones sharing the same index, if we sliced the original list in two sub-lists( nums[:n] and nums[n:]) This result can easily be achieved using zip() to pair together the elements included in the sub-lists and recursively add them to a new shuffled list.
In this article, I walked you through 4 methods to replace items in a Python list that are indexing, for loops, list comprehensions and slicing-shuffling.
Each operation is straightforward per se, but you should be able to master them by choosing the most appropriate and efficient method while solving more complex challenges, in preparation for your next coding round.
For this reason, I also presented and shared the solution of 4 algorithms (one for each method) that are representative of the level of complexity you will find while interviewing for junior and mid-level data roles.
Also note that the problems presented in this post are slight reinterpretations of problems available on Leetcode. Each problem admits multiple solutions, therefore mines are just indicative ones.
This post includes affiliate links for which I may make a small commission at no extra cost to you, should you make a purchase.
Stop Using range() in Your Python for Loops | by Jonathan Hsu | Better Programming
How To Iterate Over Two (or More) Lists at the Same Time | by Jonathan Hsu | Better Programming
Replace Item in List in Python: A Complete Guide: A Complete Guide (careerkarma.com)
|
[
{
"code": null,
"e": 258,
"s": 46,
"text": "Update: Many of you contacted me asking for valuable resources to nail Python coding interviews. Below I share 4 courses that I strongly recommend to keep exercising after practicing the algorithms in this post:"
},
{
"code": null,
"e": 350,
"s": 258,
"text": "LeetCode In Python: 50 Algorithms Coding Interview Questions → Best For Coding Rounds Prep!"
},
{
"code": null,
"e": 505,
"s": 350,
"text": "Python advanced Coding Problems (StrataScratch)→ Best platform I found to prepare Python & SQL coding interviews so far! Better and cheaper than LeetCode!"
},
{
"code": null,
"e": 567,
"s": 505,
"text": "Practicing Coding Interview Questions In Python (60+Problems)"
},
{
"code": null,
"e": 712,
"s": 567,
"text": "Python Data Engineering Nanodegree→ High Quality Course If You Have More Time To Commit. **UP TO 75% DISCOUNT ON UDACITY COURSES IN March 2022**"
},
{
"code": null,
"e": 771,
"s": 712,
"text": "Hope you’ll find them useful too! Now enjoy the article :D"
},
{
"code": null,
"e": 794,
"s": 771,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1044,
"s": 794,
"text": "While preparing for your next Python coding round, you might have noticed that algorithms requiring to manipulate one or more lists appear rather frequently. Sooner or later, you should expect to encounter one of them during your interviews as well."
},
{
"code": null,
"e": 1215,
"s": 1044,
"text": "Algorithms requiring to manipulate one or more lists appear rather frequently. Sooner or later, you should expect to encounter one of them during your interviews as well."
},
{
"code": null,
"e": 1440,
"s": 1215,
"text": "In order to help you in the process of mastering this data structure and improve your coding skills, below I present 4 methods to replace an item in Python lists as well as four simple algorithms for you to test your skills."
},
{
"code": null,
"e": 1737,
"s": 1440,
"text": "Most of the classic interview questions can be solved with multiple approaches, so for each problem, try to come up with your solution first, before looking at the one I provided. Similarly to other skills, algorithmic interview is one area where you can greatly improve with consistent practice."
},
{
"code": null,
"e": 1960,
"s": 1737,
"text": "The most straightforward way to replace an item in a list is to use indexing, as it allows you to select an item or range of items in an list and then change the value at a specific position, using the assignment operator:"
},
{
"code": null,
"e": 2051,
"s": 1960,
"text": "For example let’s suppose you were working with the following list including six integers:"
},
{
"code": null,
"e": 2080,
"s": 2051,
"text": "lst = [10, 7, 12, 56, 3, 14]"
},
{
"code": null,
"e": 2305,
"s": 2080,
"text": "and you were asked to add 10 to the third integer from the left. Since lists are indexed starting from zero, you could use one of the following syntaxes to change the element with index = 2 that in our case in the number 12:"
},
{
"code": null,
"e": 2437,
"s": 2305,
"text": "#Option 1lst[2]= lst[2] + 10#Option 2lst[2]+= 10 #no need to repeat \"lst[2]\" then more elegant#Option 3lst[2] = 22 #that is 12 + 10"
},
{
"code": null,
"e": 2506,
"s": 2437,
"text": "Now try to practice this first method solving the following problem:"
},
{
"code": null,
"e": 2681,
"s": 2506,
"text": "Given a non-empty list including integers ( between 1 and 9) , treat it as it was representing a non-negative unique integer and increment it by one. Return the updated list."
},
{
"code": null,
"e": 2957,
"s": 2681,
"text": "In the result, the digits has to be stored such that the first digit of the number obtained by the sum, is at the head of the list, and each element in the list contains a single digit. You may assume the integer does not contain any leading zero, except the number 0 itself."
},
{
"code": null,
"e": 3209,
"s": 2957,
"text": "Note that our input list is made up of four non-negative integers that together represent the integer 9999. This in an edge case, because by adding 1 to this number, you will obtain an integer with 5 digits (instead of the original 4) and a leading 1."
},
{
"code": null,
"e": 3604,
"s": 3209,
"text": "To account for these type of situations, the solution takes advantage of two conditional statements that start evaluating the digits from last to first (using reverse() to flip the order of the indexes). If not equal to 9, ONLY the last digit is incremented by 1 through the now familiar syntax digits += 1 and the amended list is immediately returned, without evaluating the remaining indexes."
},
{
"code": null,
"e": 3969,
"s": 3604,
"text": "Alternatively, if the last digit is a 9, it is replaced by a 0 and the following (second-to-last) digit is evaluated. If this is not equal to 9, then 1 is added and the amended list returned. Otherwise, if each one of following digits is a 9, then the function will return an list with a leading 1 and as many 0s as the number of the elements in the original list."
},
{
"code": null,
"e": 3989,
"s": 3969,
"text": "anbento4.medium.com"
},
{
"code": null,
"e": 4234,
"s": 3989,
"text": "In the problem above, the goal was to just replace the last integer in the list, incrementing it by 1, whereas iteration was just used to cover the edge cases.However, what if we wanted to replace multiple elements in the list at the same time?"
},
{
"code": null,
"e": 4434,
"s": 4234,
"text": "In this instances, using a for loop will work fine as it can be employed to iterate over the items of an list. To show how it works, let’s go back to original list and multiply all the integers by 2:"
},
{
"code": null,
"e": 4553,
"s": 4434,
"text": "lst = [10, 7, 12, 56, 3, 14]for i in range(len(lst)): lst[i] = lst[i] * 2print(lst)Output: [20, 14, 24, 112, 6, 28]"
},
{
"code": null,
"e": 4686,
"s": 4553,
"text": "The example above was elementary, but what if you were asked to apply a slightly more complex logic while replacing items in a list?"
},
{
"code": null,
"e": 4788,
"s": 4686,
"text": "Consider a list of integers. If the number is odd increment it by 1, if it is even increment it by 2."
},
{
"code": null,
"e": 5034,
"s": 4788,
"text": "Note that, instead of range(len(nums)), this solution uses the enumerate() method to iterate over all the elements of the list, check if the integers are odd or even - through the modulo operator - and replace them by adding 1 or 2 respectively."
},
{
"code": null,
"e": 5280,
"s": 5034,
"text": "Enumerate is a built-in function in Python and can be used to add an automatic counter while looping through an iterable object. When the optional start parameter is not specified, the counter begins from 0, behaving like it was an actual index."
},
{
"code": null,
"e": 5484,
"s": 5280,
"text": "For this reason, it is very common to use enumerate() to solve algorithms that require you to manipulate a list based on a condition applied to either the index or to (like in this case) the list values."
},
{
"code": null,
"e": 5734,
"s": 5484,
"text": "The list comprehension syntax is a more elegant method to loop through the elements of a list and apply some form of manipulation. This is because comprehensions allow you to create a new list in-line, making your code appear very clean and compact."
},
{
"code": null,
"e": 5815,
"s": 5734,
"text": "You can convert the for loop in the example above to a comprehension as follows:"
},
{
"code": null,
"e": 5929,
"s": 5815,
"text": "lst = [10, 7, 12, 56, 3, 14]lst = [lst[i] * 2 for i in range(len(lst))]print(lst)Output: [20, 14, 24, 112, 6, 28]"
},
{
"code": null,
"e": 6124,
"s": 5929,
"text": "In order to populate the new list, you are also allowed to specify basic conditions as part of list comprehension syntax. This is exactly what you’ll need to do to solve the following algorithm:"
},
{
"code": null,
"e": 6324,
"s": 6124,
"text": "Given a list of integers, sorted in ascending order, return a list also sorted in ascending order including:- the square of the integer, if divisible by 3- the original integer, if not divisible by 3"
},
{
"code": null,
"e": 6507,
"s": 6324,
"text": "In this case, the if condition is specified before the for loop because of the presence of an else statement. However when the else is not required, you can simply follow the syntax:"
},
{
"code": null,
"e": 6566,
"s": 6507,
"text": "output = [ expression for element in list_1 if condition ]"
},
{
"code": null,
"e": 6745,
"s": 6566,
"text": "At times, in coding interviews, you could be asked to re-arrange the items in a list so that they appear in a different order. This can be achieved through slicing and shuffling."
},
{
"code": null,
"e": 6850,
"s": 6745,
"text": "For example if you wished to swap the first 3 and last 3 elements in your initial list, you could write:"
},
{
"code": null,
"e": 6942,
"s": 6850,
"text": "lst = [10, 7, 12, 56, 3, 14]lst = lst[3:] + lst[:3]print(lst)Output: [56, 3, 14, 10, 7, 12]"
},
{
"code": null,
"e": 7176,
"s": 6942,
"text": "Perhaps, in this case, talking about a replacement is a bit of a stretch as you are in fact just changing the elements’ position in the list. Nonetheless, this method is quite effective and could help you solve the following problem."
},
{
"code": null,
"e": 7320,
"s": 7176,
"text": "Given the list of nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn]. Return the array in the form [x1,y1,x2,y2,...,xn,yn]."
},
{
"code": null,
"e": 7474,
"s": 7320,
"text": "The exercise provides you with the index to use for slicing (in this case n=3) and requires you to shuffle the input list, by creating new integer pairs."
},
{
"code": null,
"e": 7778,
"s": 7474,
"text": "The integers belonging to each pair, should be the ones sharing the same index, if we sliced the original list in two sub-lists( nums[:n] and nums[n:]) This result can easily be achieved using zip() to pair together the elements included in the sub-lists and recursively add them to a new shuffled list."
},
{
"code": null,
"e": 7933,
"s": 7778,
"text": "In this article, I walked you through 4 methods to replace items in a Python list that are indexing, for loops, list comprehensions and slicing-shuffling."
},
{
"code": null,
"e": 8149,
"s": 7933,
"text": "Each operation is straightforward per se, but you should be able to master them by choosing the most appropriate and efficient method while solving more complex challenges, in preparation for your next coding round."
},
{
"code": null,
"e": 8366,
"s": 8149,
"text": "For this reason, I also presented and shared the solution of 4 algorithms (one for each method) that are representative of the level of complexity you will find while interviewing for junior and mid-level data roles."
},
{
"code": null,
"e": 8563,
"s": 8366,
"text": "Also note that the problems presented in this post are slight reinterpretations of problems available on Leetcode. Each problem admits multiple solutions, therefore mines are just indicative ones."
},
{
"code": null,
"e": 8691,
"s": 8563,
"text": "This post includes affiliate links for which I may make a small commission at no extra cost to you, should you make a purchase."
},
{
"code": null,
"e": 8774,
"s": 8691,
"text": "Stop Using range() in Your Python for Loops | by Jonathan Hsu | Better Programming"
},
{
"code": null,
"e": 8870,
"s": 8774,
"text": "How To Iterate Over Two (or More) Lists at the Same Time | by Jonathan Hsu | Better Programming"
}
] |
11 Dimensionality reduction techniques you should know in 2021 | by Rukshan Pramoditha | Towards Data Science
|
In both Statistics and Machine Learning, the number of attributes, features or input variables of a dataset is referred to as its dimensionality. For example, let’s take a very simple dataset containing 2 attributes called Height and Weight. This is a 2-dimensional dataset and any observation of this dataset can be plotted in a 2D plot.
If we add another dimension called Age to the same dataset, it becomes a 3-dimensional dataset and any observation lies in the 3-dimensional space.
Likewise, real-world datasets have many attributes. The observations of those datasets lie in high-dimensional space which is hard to imagine. The following is a general geometric interpretation of a dataset related to dimensionality considered by data scientists, statisticians and machine learning engineers.
In a tabular dataset containing rows and columns, the columns represent the dimensions of the n-dimensional feature space and the rows are the data points lying in that space.
Dimensionality reduction simply refers to the process of reducing the number of attributes in a dataset while keeping as much of the variation in the original dataset as possible. It is a data preprocessing step meaning that we perform dimensionality reduction before training the model. In this article, we will discuss 11 such dimensionality reduction techniques and implement them with real-world datasets using Python and Scikit-learn libraries.
When we reduce the dimensionality of a dataset, we lose some percentage (usually 1%-15% depending on the number of components or features that we keep) of the variability in the original data. But, don’t worry about losing that much percentage of the variability in the original data because dimensionality reduction will lead to the following advantages.
A lower number of dimensions in data means less training time and less computational resources and increases the overall performance of machine learning algorithms — Machine learning problems that involve many features make training extremely slow. Most data points in high-dimensional space are very close to the border of that space. This is because there’s plenty of space in high dimensions. In a high-dimensional dataset, most data points are likely to be far away from each other. Therefore, the algorithms cannot effectively and efficiently train on the high-dimensional data. In machine learning, that kind of problem is referred to as the curse of dimensionality — this is just a technical term that you do not need to worry about!
Dimensionality reduction avoids the problem of overfitting — When there are many features in the data, the models become more complex and tend to overfit on the training data. To see this in action, read my “How to Mitigate Overfitting with Dimensionality Reduction” article.
Dimensionality reduction is extremely useful for data visualization — When we reduce the dimensionality of higher dimensional data into two or three components, then the data can easily be plotted on a 2D or 3D plot. To see this in action, read my “Principal Component Analysis (PCA) with Scikit-learn” article.
Dimensionality reduction takes care of multicollinearity — In regression, multicollinearity occurs when an independent variable is highly correlated with one or more of the other independent variables. Dimensionality reduction takes advantage of this and combines those highly correlated variables into a set of uncorrelated variables. This will address the problem of multicollinearity. To see this in action, read my “How do you apply PCA to Logistic Regression to remove Multicollinearity?” article.
Dimensionality reduction is very useful for factor analysis — This is a useful approach to find latent variables which are not directly measured in a single variable but rather inferred from other variables in the dataset. These latent variables are called factors. To see this in action, read my “Factor Analysis on Women Track Records Data with R and Python” article.
Dimensionality reduction removes noise in the data — By keeping only the most important features and removing the redundant features, dimensionality reduction removes noise in the data. This will improve the model accuracy.
Dimensionality reduction can be used for image compression — image compression is a technique that minimizes the size in bytes of an image while keeping as much of the quality of the image as possible. The pixels which make the image can be considered as dimensions (columns/variables) of the image data. We perform PCA to keep an optimum number of components that balance the explained variability in the image data and the image quality. To see this in action, read my “Image Compression Using Principal Component Analysis (PCA)” article.
Dimensionality reduction can be used to transform non-linear data into a linearly-separable form — Read the Kernel PCA section of this article to see this in action!
There are several dimensionality reduction methods that can be used with different types of data for different requirements. The following chart summarizes those dimensionality reduction methods.
There are mainly two types of dimensionality reduction methods. Both methods reduce the number of dimensions but in different ways. It is very important to distinguish between those two types of methods. One type of method only keeps the most important features in the dataset and removes the redundant features. There is no transformation applied to the set of features. Backward elimination, Forward selection and Random forests are examples of this method. The other method finds a combination of new features. An appropriate transformation is applied to the set of features. The new set of features contains different values instead of the original values. This method can be further divided into Linear methods and Non-linear methods. Non-linear methods are well known as Manifold learning. Principal Component Analysis (PCA), Factor Analysis (FA), Linear Discriminant Analysis (LDA) and Truncated Singular Value Decomposition (SVD) are examples of linear dimensionality reduction methods. Kernel PCA, t-distributed Stochastic Neighbor Embedding (t-SNE), Multidimensional Scaling (MDS) and Isometric mapping (Isomap) are examples of non-linear dimensionality reduction methods.
Let’s discuss each method in detail. Please note that, for PCA and FA, I include the links to the contents of my previous work which best describe the theory and implementation of those two methods. For all other methods, I’ll include the theory, Python code and visualizations within this article.
Linear methods involve linearly projecting the original data onto a low-dimensional space. We’ll discuss PCA, FA, LDA and Truncated SVD under linear methods. These methods can be applied to linear data and do not perform well on non-linear data.
PCA is one of my favorite machine learning algorithms. PCA is a linear dimensionality reduction technique (algorithm) that transforms a set of correlated variables (p) into a smaller k (k<p) number of uncorrelated variables called principal components while retaining as much of the variation in the original dataset as possible. In the context of Machine Learning (ML), PCA is an unsupervised machine learning algorithm that is used for dimensionality reduction.
As this is one of my favorite algorithms, I have previously written several contents for PCA. If you’re interested to learn more about the theory behind PCA and its Scikit-learn implementation, you may read the following contents written by me.
Principal Component Analysis (PCA) with Scikit-learn
Statistical and Mathematical Concepts behind PCA
Principal Component Analysis for Breast Cancer Data with R and Python
Image Compression Using Principal Component Analysis (PCA)
Factor Analysis (FA) and Principal Component Analysis (PCA) are both dimensionality reduction techniques. The main objective of Factor Analysis is not to just reduce the dimensionality of the data. Factor Analysis is a useful approach to find latent variables which are not directly measured in a single variable but rather inferred from other variables in the dataset. These latent variables are called factors.
If you’re interested to learn more about the theory behind FA and its Scikit-learn implementation, you may read the following content written by me.
Factor Analysis on “Women Track Records” Data with R and Python
LDA is typically used for multi-class classification. It can also be used as a dimensionality reduction technique. LDA best separates or discriminates (hence the name LDA) training instances by their classes. The major difference between LDA and PCA is that LDA finds a linear combination of input features that optimizes class separability while PCA attempts to find a set of uncorrelated components of maximum variance in a dataset. Another key difference between the two is that PCA is an unsupervised algorithm whereas LDA is a supervised algorithm where it takes class labels into account.
There are some limitations of LDA. To apply LDA, the data should be normally distributed. The dataset should also contain known class labels. The maximum number of components that LDA can find is the number of classes minus 1. If there are only 3 class labels in your dataset, LDA can find only 2 (3–1) components in dimensionality reduction. It is not needed to perform feature scaling to apply LDA. On the other hand, PCA needs scaled data. However, class labels are not needed for PCA. The maximum number of components that PCA can find is the number of input features in the original dataset.
LDA for dimensionality reduction should not be confused with LDA for multi-class classification. Both cases can be implemented using the Scikit-learn LinearDiscriminantAnalysis() function. After fitting the model using fit(X, y), we use the predict(X) method of the LDA object for multi-class classification. This will assign new instances to the classes in the original dataset. We can use the transform(X) method of the LDA object for dimensionality reduction. This will find a linear combination of new features that optimizes class separability.
The following Python code describes the implementation of LDA and PCA techniques to the Iris dataset and shows the difference between the two. The original Iris dataset has four features. LDA and PCA reduce that number of features into two and enable a 2D visualization.
This method performs linear dimensionality reduction by means of truncated singular value decomposition (SVD). It works well with sparse data in which many of the row values are zero. In contrast, PCA works well with dense data. Truncated SVD can also be used with dense data. Another key difference between truncated SVD and PCA is that factorization for SVD is done on the data matrix while factorization for PCA is done on the covariance matrix.
The Scikit-learn implementation of truncated SVD is much easy. It can be done using the TruncatedSVD() function. The following Python code describes the implementation of truncated SVD and PCA techniques to the Iris dataset.
If we’re dealing with non-linear data which are frequently used in real-world applications, linear methods discussed so far do not perform well for dimensionality reduction. In this section, we’ll discuss four non-linear dimensionality reduction methods that can be used with non-linear data.
Kernel PCA is a non-linear dimensionality reduction technique that uses kernels. It can also be considered as the non-linear form of normal PCA. Kernel PCA works well with non-linear datasets where normal PCA cannot be used efficiently.
The intuition behind Kernel PCA is something interesting. The data is first run through a kernel function and temporarily projects them into a new higher-dimensional feature space where the classes become linearly separable (classes can be divided by drawing a straight line). Then the algorithm uses the normal PCA to project the data back onto a lower-dimensional space. In this way, Kernel PCA transforms non-linear data into a lower-dimensional space of data which can be used with linear classifiers.
In the Kernel PCA, we need to specify 3 important hyperparameters — the number of components we want to keep, the type of kernel and the kernel coefficient (also known as the gamma). For the type of kernel, we can use ‘linear’, ‘poly’, ‘rbf’, ‘sigmoid’, ‘cosine’. The rbf kernel which is known as the radial basis function kernel is the most popular one.
Now, we are going to implement an RBF kernel PCA to non-linear data which can be generated by using the Scikit-learn make_moons() function.
We can clearly see that the two classes of the above non-linear data cannot be separated by drawing a straight line.
Let’s perform both PCA and Kernel PCA on the above data and see what will happen!
As you can see in the above graphs, the normal PCA cannot be able to transform non-linear data into a linear form. After applying Kernel PCA to the same data, the two classes are linearly well separated (now, classes can be divided by drawing a vertical straight line).
Here, the original data has a dimension of 2 and the plotted data also has a dimension of 2. So, has Kernel PCA actually reduced the dimensionality of data? The answer is ‘Yes’ because the RBF kernel function temporarily projects the 2-dimensional data into a new higher-dimensional feature space where the classes become linearly separable and then the algorithm projects that higher-dimensional data back into the 2-dimensional data which can be plotted in a 2D plot. The dimensionality reduction process has happened behind the scenes while classes become linearly separable.
One limitation of using the Kernel PCA for dimensionality reduction is that we have to specify a value for the gamma hyperparameter before running the algorithm. It requires implementing a hyperparameter tuning technique such as Grid Search to find an optimal value for the gamma. It is beyond the scope of this article. But you can get help with the hyperparameter tuning process by reading my “k-fold cross-validation explained in plain English”.
This is also a non-linear dimensionality reduction method mostly used for data visualization. In addition to that, it is widely used in image processing and NLP. The Scikit-learn documentation recommends you to use PCA or Truncated SVD before t-SNE if the number of features in the dataset is more than 50. The following is the general syntax to perform t-SNE after PCA. Also, note that feature scaling is required before PCA.
from sklearn.decomposition import PCAfrom sklearn.manifold import TSNEfrom sklearn.preprocessing import StandardScalersc = StandardScaler()X_scaled = sc.fit_transform(X)pca = PCA()X_pca = pca.fit_transform(X_scaled)tsne = TSNE()X_tsne = tsne.fit_transform(X_pca)
The above code can be simplified using a Scikit-learn pipeline.
from sklearn.pipeline import Pipelinefrom sklearn.decomposition import PCAfrom sklearn.manifold import TSNEfrom sklearn.preprocessing import StandardScalersc = StandardScaler()pca = PCA()tsne = TSNE()tsne_after_pca = Pipeline([ ('std_scaler', sc), ('pca', pca), ('tsne', tsne)])X_tsne = tsne_after_pca.fit_transform(X)
Now, we apply t-SNE to the Iris dataset. It has only 4 features. Therefore, we do not need to run PCA before t-SNE.
MDA is another non-linear dimensionality reduction technique that tries to preserve the distances between instances while reducing the dimensionality of non-linear data. There are two types of MDS algorithms: Metric and Non-metric. The MDS() class in the Scikit-learn implements both by setting the metric hyperparameter to True (for Metric type) or False (for Non-metric type).
The following code implements the MDS to the Iris dataset.
This method performs non-linear dimensionality reduction through Isometric mapping. It is an extension of MDS or Kernel PCA. It connects each instance by calculating the curved or geodesic distance to its nearest neighbors and reduces dimensionality. The number of neighbors to consider for each point can be specified through the n_neighbors hyperparameter of the Isomap() class which implements the Isomap algorithm in the Scikit-learn.
The following code implements the Isomap to the Iris dataset.
Under this category, we’ll discuss 3 methods. Those methods only keep the most important features in the dataset and remove the redundant features. So, they are mainly used for feature selection. But, dimensionality reduction happens automatically while selecting the best features! Therefore, they can also be considered dimensionality reduction methods. These methods will improve models’ accuracy scores or boost performance on very high-dimensional datasets.
This method eliminates (removes) features from a dataset through a recursive feature elimination (RFE) process. The algorithm first attempts to train the model on the initial set of features in the dataset and calculates the performance of the model (usually, accuracy score for a classification model and RMSE for a regression model). Then, the algorithm drops one feature (variable) at a time, trains the model on the remaining features and calculates the performance scores. The algorithm repeats eliminating features until it detects a small (or no) change in the performance score of the model and stops there!
In the Scikit-learn, backward elimination can be implemented by using the RFE() class which is in the sklearn.feature_selection module. The first parameter of that class should be a supervised learning estimator with a fit() method and a coef_ or feature_importances_ attribute. The second one should be the number of features to select. According to the Scikit-learn documentation, half of the features are selected if we do not specify the number of features to select (n_features_to_select parameter). A major limitation of this method is that we do not know the number of features to select. In those situations, it is better to run this algorithm multiple times by specifying different values for n_features_to_select.
Now, we train a Logistic Regression model on the Iris data and identify the most important features through backward feature elimination.
From the output, we can see that the recursive feature elimination (RFE) algorithm has eliminated the sepal length (cm) from the logistic regression model. sepal length (cm) is the least important feature. The remaining features contain the original values as in the initial dataset. As the plot shows, it is better to keep the other 3 features in the model.
This method can be considered as the opposite process of backward elimination. Instead of eliminating features recursively, the algorithm attempts to train the model on a single feature in the dataset and calculates the performance of the model (usually, accuracy score for a classification model and RMSE for a regression model). Then, the algorithm adds (selects) one feature (variable) at a time, trains the model on those features and calculates the performance scores. The algorithm repeats adding features until it detects a small (or no) change in the performance score of the model and stops there!
In Scikit-learn, there is no direct function for forward feature selection. Instead, we can use f_regression (for regression tasks) and f_classif (for classification tasks) classes together with the SelectKBest class. f_regression returns F-value between label/feature for regression tasks. f_classif returns ANOVA F-value between label/feature for classification tasks. Those F-values can be used in the feature selection process. The SelectKBest automatically selects features according to the highest scores based on the F-values of features. The score_func parameter of SelectKBest should be specified to f_classif or f_regression. The k parameter defines the number of top features to select.
Let’s perform forward feature selection on the Iris data and identify the most important features.
From the output, we can see that the forward feature selection process has selected the sepal length (cm), petal length (cm) and petal width (cm) which have higher F-values.
To define the value for the k parameter based on a cut-off F-value, we can use the following two lines of code.
F_values = f_classif(X,y)[0]k = len([num for num in F_values if num > 50])
This will calculate the number of F-values greater than 50 and assign it to k. This is exactly the same as the above implementation.
Random forests is a tree-based model which is widely used for regression and classification tasks on non-linear data. It can also be used for feature selection with its built-in feature_importances_ attribute which calculates feature importance scores for each feature based on the ‘gini’ criterion (a measure of the quality of a split of internal nodes) while training the model. If you’re interested to learn more about how random forests make predictions, you can read my “Random forests — An ensemble of decision trees” article.
The following Python code implements a Random Forest Classifier to the Iris data, calculates and visualizes the feature importances.
By looking at the feature importance, we can decide to drop the sepal width (cm) feature because it does not contribute enough to making the model. Let’s see how!
Scikit-learn SelectFromModel selects only the features whose importance is greater or equal to the specified threshold value. The values returned by SelectFromModel can be used as the new input X for the Random Forest Classifier which is now trained only on the selected features!
rf = RandomForestClassifier(n_estimators=100, max_depth=3, bootstrap=True, n_jobs=-1, random_state=0)rf.fit(features_important, y)
This is the end of today’s post. My readers can sign up for a membership through the following link to get full access to every story I write and I will receive a portion of your membership fee.
Sign-up link: https://rukshanpramoditha.medium.com/membership
Thank you so much for your continuous support! See you in the next story. Happy learning to everyone!
Special credit goes to Nika Benedictova on Unsplash, who provides me with a nice cover image for this post.
|
[
{
"code": null,
"e": 386,
"s": 47,
"text": "In both Statistics and Machine Learning, the number of attributes, features or input variables of a dataset is referred to as its dimensionality. For example, let’s take a very simple dataset containing 2 attributes called Height and Weight. This is a 2-dimensional dataset and any observation of this dataset can be plotted in a 2D plot."
},
{
"code": null,
"e": 534,
"s": 386,
"text": "If we add another dimension called Age to the same dataset, it becomes a 3-dimensional dataset and any observation lies in the 3-dimensional space."
},
{
"code": null,
"e": 845,
"s": 534,
"text": "Likewise, real-world datasets have many attributes. The observations of those datasets lie in high-dimensional space which is hard to imagine. The following is a general geometric interpretation of a dataset related to dimensionality considered by data scientists, statisticians and machine learning engineers."
},
{
"code": null,
"e": 1021,
"s": 845,
"text": "In a tabular dataset containing rows and columns, the columns represent the dimensions of the n-dimensional feature space and the rows are the data points lying in that space."
},
{
"code": null,
"e": 1471,
"s": 1021,
"text": "Dimensionality reduction simply refers to the process of reducing the number of attributes in a dataset while keeping as much of the variation in the original dataset as possible. It is a data preprocessing step meaning that we perform dimensionality reduction before training the model. In this article, we will discuss 11 such dimensionality reduction techniques and implement them with real-world datasets using Python and Scikit-learn libraries."
},
{
"code": null,
"e": 1827,
"s": 1471,
"text": "When we reduce the dimensionality of a dataset, we lose some percentage (usually 1%-15% depending on the number of components or features that we keep) of the variability in the original data. But, don’t worry about losing that much percentage of the variability in the original data because dimensionality reduction will lead to the following advantages."
},
{
"code": null,
"e": 2568,
"s": 1827,
"text": "A lower number of dimensions in data means less training time and less computational resources and increases the overall performance of machine learning algorithms — Machine learning problems that involve many features make training extremely slow. Most data points in high-dimensional space are very close to the border of that space. This is because there’s plenty of space in high dimensions. In a high-dimensional dataset, most data points are likely to be far away from each other. Therefore, the algorithms cannot effectively and efficiently train on the high-dimensional data. In machine learning, that kind of problem is referred to as the curse of dimensionality — this is just a technical term that you do not need to worry about!"
},
{
"code": null,
"e": 2844,
"s": 2568,
"text": "Dimensionality reduction avoids the problem of overfitting — When there are many features in the data, the models become more complex and tend to overfit on the training data. To see this in action, read my “How to Mitigate Overfitting with Dimensionality Reduction” article."
},
{
"code": null,
"e": 3156,
"s": 2844,
"text": "Dimensionality reduction is extremely useful for data visualization — When we reduce the dimensionality of higher dimensional data into two or three components, then the data can easily be plotted on a 2D or 3D plot. To see this in action, read my “Principal Component Analysis (PCA) with Scikit-learn” article."
},
{
"code": null,
"e": 3659,
"s": 3156,
"text": "Dimensionality reduction takes care of multicollinearity — In regression, multicollinearity occurs when an independent variable is highly correlated with one or more of the other independent variables. Dimensionality reduction takes advantage of this and combines those highly correlated variables into a set of uncorrelated variables. This will address the problem of multicollinearity. To see this in action, read my “How do you apply PCA to Logistic Regression to remove Multicollinearity?” article."
},
{
"code": null,
"e": 4029,
"s": 3659,
"text": "Dimensionality reduction is very useful for factor analysis — This is a useful approach to find latent variables which are not directly measured in a single variable but rather inferred from other variables in the dataset. These latent variables are called factors. To see this in action, read my “Factor Analysis on Women Track Records Data with R and Python” article."
},
{
"code": null,
"e": 4253,
"s": 4029,
"text": "Dimensionality reduction removes noise in the data — By keeping only the most important features and removing the redundant features, dimensionality reduction removes noise in the data. This will improve the model accuracy."
},
{
"code": null,
"e": 4794,
"s": 4253,
"text": "Dimensionality reduction can be used for image compression — image compression is a technique that minimizes the size in bytes of an image while keeping as much of the quality of the image as possible. The pixels which make the image can be considered as dimensions (columns/variables) of the image data. We perform PCA to keep an optimum number of components that balance the explained variability in the image data and the image quality. To see this in action, read my “Image Compression Using Principal Component Analysis (PCA)” article."
},
{
"code": null,
"e": 4960,
"s": 4794,
"text": "Dimensionality reduction can be used to transform non-linear data into a linearly-separable form — Read the Kernel PCA section of this article to see this in action!"
},
{
"code": null,
"e": 5156,
"s": 4960,
"text": "There are several dimensionality reduction methods that can be used with different types of data for different requirements. The following chart summarizes those dimensionality reduction methods."
},
{
"code": null,
"e": 6339,
"s": 5156,
"text": "There are mainly two types of dimensionality reduction methods. Both methods reduce the number of dimensions but in different ways. It is very important to distinguish between those two types of methods. One type of method only keeps the most important features in the dataset and removes the redundant features. There is no transformation applied to the set of features. Backward elimination, Forward selection and Random forests are examples of this method. The other method finds a combination of new features. An appropriate transformation is applied to the set of features. The new set of features contains different values instead of the original values. This method can be further divided into Linear methods and Non-linear methods. Non-linear methods are well known as Manifold learning. Principal Component Analysis (PCA), Factor Analysis (FA), Linear Discriminant Analysis (LDA) and Truncated Singular Value Decomposition (SVD) are examples of linear dimensionality reduction methods. Kernel PCA, t-distributed Stochastic Neighbor Embedding (t-SNE), Multidimensional Scaling (MDS) and Isometric mapping (Isomap) are examples of non-linear dimensionality reduction methods."
},
{
"code": null,
"e": 6638,
"s": 6339,
"text": "Let’s discuss each method in detail. Please note that, for PCA and FA, I include the links to the contents of my previous work which best describe the theory and implementation of those two methods. For all other methods, I’ll include the theory, Python code and visualizations within this article."
},
{
"code": null,
"e": 6884,
"s": 6638,
"text": "Linear methods involve linearly projecting the original data onto a low-dimensional space. We’ll discuss PCA, FA, LDA and Truncated SVD under linear methods. These methods can be applied to linear data and do not perform well on non-linear data."
},
{
"code": null,
"e": 7348,
"s": 6884,
"text": "PCA is one of my favorite machine learning algorithms. PCA is a linear dimensionality reduction technique (algorithm) that transforms a set of correlated variables (p) into a smaller k (k<p) number of uncorrelated variables called principal components while retaining as much of the variation in the original dataset as possible. In the context of Machine Learning (ML), PCA is an unsupervised machine learning algorithm that is used for dimensionality reduction."
},
{
"code": null,
"e": 7593,
"s": 7348,
"text": "As this is one of my favorite algorithms, I have previously written several contents for PCA. If you’re interested to learn more about the theory behind PCA and its Scikit-learn implementation, you may read the following contents written by me."
},
{
"code": null,
"e": 7646,
"s": 7593,
"text": "Principal Component Analysis (PCA) with Scikit-learn"
},
{
"code": null,
"e": 7695,
"s": 7646,
"text": "Statistical and Mathematical Concepts behind PCA"
},
{
"code": null,
"e": 7765,
"s": 7695,
"text": "Principal Component Analysis for Breast Cancer Data with R and Python"
},
{
"code": null,
"e": 7824,
"s": 7765,
"text": "Image Compression Using Principal Component Analysis (PCA)"
},
{
"code": null,
"e": 8237,
"s": 7824,
"text": "Factor Analysis (FA) and Principal Component Analysis (PCA) are both dimensionality reduction techniques. The main objective of Factor Analysis is not to just reduce the dimensionality of the data. Factor Analysis is a useful approach to find latent variables which are not directly measured in a single variable but rather inferred from other variables in the dataset. These latent variables are called factors."
},
{
"code": null,
"e": 8386,
"s": 8237,
"text": "If you’re interested to learn more about the theory behind FA and its Scikit-learn implementation, you may read the following content written by me."
},
{
"code": null,
"e": 8450,
"s": 8386,
"text": "Factor Analysis on “Women Track Records” Data with R and Python"
},
{
"code": null,
"e": 9045,
"s": 8450,
"text": "LDA is typically used for multi-class classification. It can also be used as a dimensionality reduction technique. LDA best separates or discriminates (hence the name LDA) training instances by their classes. The major difference between LDA and PCA is that LDA finds a linear combination of input features that optimizes class separability while PCA attempts to find a set of uncorrelated components of maximum variance in a dataset. Another key difference between the two is that PCA is an unsupervised algorithm whereas LDA is a supervised algorithm where it takes class labels into account."
},
{
"code": null,
"e": 9642,
"s": 9045,
"text": "There are some limitations of LDA. To apply LDA, the data should be normally distributed. The dataset should also contain known class labels. The maximum number of components that LDA can find is the number of classes minus 1. If there are only 3 class labels in your dataset, LDA can find only 2 (3–1) components in dimensionality reduction. It is not needed to perform feature scaling to apply LDA. On the other hand, PCA needs scaled data. However, class labels are not needed for PCA. The maximum number of components that PCA can find is the number of input features in the original dataset."
},
{
"code": null,
"e": 10192,
"s": 9642,
"text": "LDA for dimensionality reduction should not be confused with LDA for multi-class classification. Both cases can be implemented using the Scikit-learn LinearDiscriminantAnalysis() function. After fitting the model using fit(X, y), we use the predict(X) method of the LDA object for multi-class classification. This will assign new instances to the classes in the original dataset. We can use the transform(X) method of the LDA object for dimensionality reduction. This will find a linear combination of new features that optimizes class separability."
},
{
"code": null,
"e": 10463,
"s": 10192,
"text": "The following Python code describes the implementation of LDA and PCA techniques to the Iris dataset and shows the difference between the two. The original Iris dataset has four features. LDA and PCA reduce that number of features into two and enable a 2D visualization."
},
{
"code": null,
"e": 10912,
"s": 10463,
"text": "This method performs linear dimensionality reduction by means of truncated singular value decomposition (SVD). It works well with sparse data in which many of the row values are zero. In contrast, PCA works well with dense data. Truncated SVD can also be used with dense data. Another key difference between truncated SVD and PCA is that factorization for SVD is done on the data matrix while factorization for PCA is done on the covariance matrix."
},
{
"code": null,
"e": 11137,
"s": 10912,
"text": "The Scikit-learn implementation of truncated SVD is much easy. It can be done using the TruncatedSVD() function. The following Python code describes the implementation of truncated SVD and PCA techniques to the Iris dataset."
},
{
"code": null,
"e": 11430,
"s": 11137,
"text": "If we’re dealing with non-linear data which are frequently used in real-world applications, linear methods discussed so far do not perform well for dimensionality reduction. In this section, we’ll discuss four non-linear dimensionality reduction methods that can be used with non-linear data."
},
{
"code": null,
"e": 11667,
"s": 11430,
"text": "Kernel PCA is a non-linear dimensionality reduction technique that uses kernels. It can also be considered as the non-linear form of normal PCA. Kernel PCA works well with non-linear datasets where normal PCA cannot be used efficiently."
},
{
"code": null,
"e": 12173,
"s": 11667,
"text": "The intuition behind Kernel PCA is something interesting. The data is first run through a kernel function and temporarily projects them into a new higher-dimensional feature space where the classes become linearly separable (classes can be divided by drawing a straight line). Then the algorithm uses the normal PCA to project the data back onto a lower-dimensional space. In this way, Kernel PCA transforms non-linear data into a lower-dimensional space of data which can be used with linear classifiers."
},
{
"code": null,
"e": 12528,
"s": 12173,
"text": "In the Kernel PCA, we need to specify 3 important hyperparameters — the number of components we want to keep, the type of kernel and the kernel coefficient (also known as the gamma). For the type of kernel, we can use ‘linear’, ‘poly’, ‘rbf’, ‘sigmoid’, ‘cosine’. The rbf kernel which is known as the radial basis function kernel is the most popular one."
},
{
"code": null,
"e": 12668,
"s": 12528,
"text": "Now, we are going to implement an RBF kernel PCA to non-linear data which can be generated by using the Scikit-learn make_moons() function."
},
{
"code": null,
"e": 12785,
"s": 12668,
"text": "We can clearly see that the two classes of the above non-linear data cannot be separated by drawing a straight line."
},
{
"code": null,
"e": 12867,
"s": 12785,
"text": "Let’s perform both PCA and Kernel PCA on the above data and see what will happen!"
},
{
"code": null,
"e": 13137,
"s": 12867,
"text": "As you can see in the above graphs, the normal PCA cannot be able to transform non-linear data into a linear form. After applying Kernel PCA to the same data, the two classes are linearly well separated (now, classes can be divided by drawing a vertical straight line)."
},
{
"code": null,
"e": 13716,
"s": 13137,
"text": "Here, the original data has a dimension of 2 and the plotted data also has a dimension of 2. So, has Kernel PCA actually reduced the dimensionality of data? The answer is ‘Yes’ because the RBF kernel function temporarily projects the 2-dimensional data into a new higher-dimensional feature space where the classes become linearly separable and then the algorithm projects that higher-dimensional data back into the 2-dimensional data which can be plotted in a 2D plot. The dimensionality reduction process has happened behind the scenes while classes become linearly separable."
},
{
"code": null,
"e": 14165,
"s": 13716,
"text": "One limitation of using the Kernel PCA for dimensionality reduction is that we have to specify a value for the gamma hyperparameter before running the algorithm. It requires implementing a hyperparameter tuning technique such as Grid Search to find an optimal value for the gamma. It is beyond the scope of this article. But you can get help with the hyperparameter tuning process by reading my “k-fold cross-validation explained in plain English”."
},
{
"code": null,
"e": 14592,
"s": 14165,
"text": "This is also a non-linear dimensionality reduction method mostly used for data visualization. In addition to that, it is widely used in image processing and NLP. The Scikit-learn documentation recommends you to use PCA or Truncated SVD before t-SNE if the number of features in the dataset is more than 50. The following is the general syntax to perform t-SNE after PCA. Also, note that feature scaling is required before PCA."
},
{
"code": null,
"e": 14855,
"s": 14592,
"text": "from sklearn.decomposition import PCAfrom sklearn.manifold import TSNEfrom sklearn.preprocessing import StandardScalersc = StandardScaler()X_scaled = sc.fit_transform(X)pca = PCA()X_pca = pca.fit_transform(X_scaled)tsne = TSNE()X_tsne = tsne.fit_transform(X_pca)"
},
{
"code": null,
"e": 14919,
"s": 14855,
"text": "The above code can be simplified using a Scikit-learn pipeline."
},
{
"code": null,
"e": 15247,
"s": 14919,
"text": "from sklearn.pipeline import Pipelinefrom sklearn.decomposition import PCAfrom sklearn.manifold import TSNEfrom sklearn.preprocessing import StandardScalersc = StandardScaler()pca = PCA()tsne = TSNE()tsne_after_pca = Pipeline([ ('std_scaler', sc), ('pca', pca), ('tsne', tsne)])X_tsne = tsne_after_pca.fit_transform(X)"
},
{
"code": null,
"e": 15363,
"s": 15247,
"text": "Now, we apply t-SNE to the Iris dataset. It has only 4 features. Therefore, we do not need to run PCA before t-SNE."
},
{
"code": null,
"e": 15742,
"s": 15363,
"text": "MDA is another non-linear dimensionality reduction technique that tries to preserve the distances between instances while reducing the dimensionality of non-linear data. There are two types of MDS algorithms: Metric and Non-metric. The MDS() class in the Scikit-learn implements both by setting the metric hyperparameter to True (for Metric type) or False (for Non-metric type)."
},
{
"code": null,
"e": 15801,
"s": 15742,
"text": "The following code implements the MDS to the Iris dataset."
},
{
"code": null,
"e": 16240,
"s": 15801,
"text": "This method performs non-linear dimensionality reduction through Isometric mapping. It is an extension of MDS or Kernel PCA. It connects each instance by calculating the curved or geodesic distance to its nearest neighbors and reduces dimensionality. The number of neighbors to consider for each point can be specified through the n_neighbors hyperparameter of the Isomap() class which implements the Isomap algorithm in the Scikit-learn."
},
{
"code": null,
"e": 16302,
"s": 16240,
"text": "The following code implements the Isomap to the Iris dataset."
},
{
"code": null,
"e": 16765,
"s": 16302,
"text": "Under this category, we’ll discuss 3 methods. Those methods only keep the most important features in the dataset and remove the redundant features. So, they are mainly used for feature selection. But, dimensionality reduction happens automatically while selecting the best features! Therefore, they can also be considered dimensionality reduction methods. These methods will improve models’ accuracy scores or boost performance on very high-dimensional datasets."
},
{
"code": null,
"e": 17381,
"s": 16765,
"text": "This method eliminates (removes) features from a dataset through a recursive feature elimination (RFE) process. The algorithm first attempts to train the model on the initial set of features in the dataset and calculates the performance of the model (usually, accuracy score for a classification model and RMSE for a regression model). Then, the algorithm drops one feature (variable) at a time, trains the model on the remaining features and calculates the performance scores. The algorithm repeats eliminating features until it detects a small (or no) change in the performance score of the model and stops there!"
},
{
"code": null,
"e": 18105,
"s": 17381,
"text": "In the Scikit-learn, backward elimination can be implemented by using the RFE() class which is in the sklearn.feature_selection module. The first parameter of that class should be a supervised learning estimator with a fit() method and a coef_ or feature_importances_ attribute. The second one should be the number of features to select. According to the Scikit-learn documentation, half of the features are selected if we do not specify the number of features to select (n_features_to_select parameter). A major limitation of this method is that we do not know the number of features to select. In those situations, it is better to run this algorithm multiple times by specifying different values for n_features_to_select."
},
{
"code": null,
"e": 18243,
"s": 18105,
"text": "Now, we train a Logistic Regression model on the Iris data and identify the most important features through backward feature elimination."
},
{
"code": null,
"e": 18602,
"s": 18243,
"text": "From the output, we can see that the recursive feature elimination (RFE) algorithm has eliminated the sepal length (cm) from the logistic regression model. sepal length (cm) is the least important feature. The remaining features contain the original values as in the initial dataset. As the plot shows, it is better to keep the other 3 features in the model."
},
{
"code": null,
"e": 19209,
"s": 18602,
"text": "This method can be considered as the opposite process of backward elimination. Instead of eliminating features recursively, the algorithm attempts to train the model on a single feature in the dataset and calculates the performance of the model (usually, accuracy score for a classification model and RMSE for a regression model). Then, the algorithm adds (selects) one feature (variable) at a time, trains the model on those features and calculates the performance scores. The algorithm repeats adding features until it detects a small (or no) change in the performance score of the model and stops there!"
},
{
"code": null,
"e": 19907,
"s": 19209,
"text": "In Scikit-learn, there is no direct function for forward feature selection. Instead, we can use f_regression (for regression tasks) and f_classif (for classification tasks) classes together with the SelectKBest class. f_regression returns F-value between label/feature for regression tasks. f_classif returns ANOVA F-value between label/feature for classification tasks. Those F-values can be used in the feature selection process. The SelectKBest automatically selects features according to the highest scores based on the F-values of features. The score_func parameter of SelectKBest should be specified to f_classif or f_regression. The k parameter defines the number of top features to select."
},
{
"code": null,
"e": 20006,
"s": 19907,
"text": "Let’s perform forward feature selection on the Iris data and identify the most important features."
},
{
"code": null,
"e": 20180,
"s": 20006,
"text": "From the output, we can see that the forward feature selection process has selected the sepal length (cm), petal length (cm) and petal width (cm) which have higher F-values."
},
{
"code": null,
"e": 20292,
"s": 20180,
"text": "To define the value for the k parameter based on a cut-off F-value, we can use the following two lines of code."
},
{
"code": null,
"e": 20367,
"s": 20292,
"text": "F_values = f_classif(X,y)[0]k = len([num for num in F_values if num > 50])"
},
{
"code": null,
"e": 20500,
"s": 20367,
"text": "This will calculate the number of F-values greater than 50 and assign it to k. This is exactly the same as the above implementation."
},
{
"code": null,
"e": 21033,
"s": 20500,
"text": "Random forests is a tree-based model which is widely used for regression and classification tasks on non-linear data. It can also be used for feature selection with its built-in feature_importances_ attribute which calculates feature importance scores for each feature based on the ‘gini’ criterion (a measure of the quality of a split of internal nodes) while training the model. If you’re interested to learn more about how random forests make predictions, you can read my “Random forests — An ensemble of decision trees” article."
},
{
"code": null,
"e": 21166,
"s": 21033,
"text": "The following Python code implements a Random Forest Classifier to the Iris data, calculates and visualizes the feature importances."
},
{
"code": null,
"e": 21329,
"s": 21166,
"text": "By looking at the feature importance, we can decide to drop the sepal width (cm) feature because it does not contribute enough to making the model. Let’s see how!"
},
{
"code": null,
"e": 21610,
"s": 21329,
"text": "Scikit-learn SelectFromModel selects only the features whose importance is greater or equal to the specified threshold value. The values returned by SelectFromModel can be used as the new input X for the Random Forest Classifier which is now trained only on the selected features!"
},
{
"code": null,
"e": 21795,
"s": 21610,
"text": "rf = RandomForestClassifier(n_estimators=100, max_depth=3, bootstrap=True, n_jobs=-1, random_state=0)rf.fit(features_important, y)"
},
{
"code": null,
"e": 21990,
"s": 21795,
"text": "This is the end of today’s post. My readers can sign up for a membership through the following link to get full access to every story I write and I will receive a portion of your membership fee."
},
{
"code": null,
"e": 22052,
"s": 21990,
"text": "Sign-up link: https://rukshanpramoditha.medium.com/membership"
},
{
"code": null,
"e": 22154,
"s": 22052,
"text": "Thank you so much for your continuous support! See you in the next story. Happy learning to everyone!"
}
] |
Environments in R Programming - GeeksforGeeks
|
05 Aug, 2020
The environment is a virtual space that is triggered when an interpreter of a programming language is launched. Simply, the environment is a collection of all the objects, variables, and functions. Or, Environment can be assumed as a top-level object that contains the set of names/variables associated with some values. In this article, let us discuss creating a new environment in R programming, list all environments, removing a variable from the environment, searching for a variable or function among environments and function environments with the help of examples.
Every object in an environment has a name.
The environment has a parent environment.
Environments follow reference semantics.
An environment in R programming can be created using new.env() function. Further, the variables can be accessed using $ or [[ ]] operator. But, each variable is stored in different memory locations. There are four special environments: globalenv(), baseenv(), emptyenv() and environment()
Syntax: new.env(hash = TRUE)
Parameters: hash: indicates logical value. If TRUE, environments uses a hash table
To know about more optional parameters, use below command in console: help(“new.env”)
Example:
R
# R program to illustrate# Environments in R # Create new environmentnewEnv <- new.env() # Assigning variablesnewEnv$x <- 1newEnv$y <- "GFG"newEnv$z <- 1:10 # Printprint(newEnv$z)
Output:
[1] 1 2 3 4 5 6 7 8 9 10
Every environment has a parent environment but there is an empty environment that does not have any parent environment. All the environments can be listed using ls() function and search() function. ls() function also list out all the bindings of the variables in a particular environment.
Syntax:
ls() search()
Parameters:These functions need no argument
Example:
R
# R program to illustrate# Environments in R # Prints all the bindings and environments # attached to Global Environmentls() # Prints bindings of newEnvls(newEnv) # Lists all the environments of the parent environmentsearch()
Output:
[1] "al" "e" "e1" "f" "newEnv" "pts" "x" "y"
[9] "z"
[1] "x" "y" "z"
[1] ".GlobalEnv" "package:stats" "package:graphics"
[4] "package:grDevices" "package:utils" "package:datasets"
[7] "package:methods" "Autoloads" "package:base"
A variable in an environment is deleted using rm() function. It is different from deleting entries from lists as entries in lists are set as NULL to be deleted. But, using rm() function, bindings are removed from the environment.
Syntax: rm(...)
Parameters: ...: indicates list of objects
Example:
R
# R program to illustrate# Environments in R # Remove newEnvrm(newEnv) # Listls()
Output:
[1] "al" "e" "e1" "f" "pts" "x" "y" "z"
A variable or a function can be searched in R programming by using where() function among all the environments and packages present. where() function is present in pryr package. This function takes only two arguments, the name of the object to search for and the environment from where to start the search.
Syntax: where(name)
Parameters: name: indicates object to look for
Example:
R
# R program to illustrate# Environments in R # Install pryr packageinstall.packages("pryr") # Load the packagelibrary(pryr) # Searchwhere("x") where("mode")
Output:
<environment: R_GlobalEnv>
<environment: base>
R-basics
R-Objects
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change column name of a given DataFrame in R
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Adding elements in a vector in R programming - append() method
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 ?
Convert Factor to Numeric and Numeric to Factor in R Programming
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
|
[
{
"code": null,
"e": 29044,
"s": 29016,
"text": "\n05 Aug, 2020"
},
{
"code": null,
"e": 29616,
"s": 29044,
"text": "The environment is a virtual space that is triggered when an interpreter of a programming language is launched. Simply, the environment is a collection of all the objects, variables, and functions. Or, Environment can be assumed as a top-level object that contains the set of names/variables associated with some values. In this article, let us discuss creating a new environment in R programming, list all environments, removing a variable from the environment, searching for a variable or function among environments and function environments with the help of examples."
},
{
"code": null,
"e": 29659,
"s": 29616,
"text": "Every object in an environment has a name."
},
{
"code": null,
"e": 29701,
"s": 29659,
"text": "The environment has a parent environment."
},
{
"code": null,
"e": 29742,
"s": 29701,
"text": "Environments follow reference semantics."
},
{
"code": null,
"e": 30031,
"s": 29742,
"text": "An environment in R programming can be created using new.env() function. Further, the variables can be accessed using $ or [[ ]] operator. But, each variable is stored in different memory locations. There are four special environments: globalenv(), baseenv(), emptyenv() and environment()"
},
{
"code": null,
"e": 30060,
"s": 30031,
"text": "Syntax: new.env(hash = TRUE)"
},
{
"code": null,
"e": 30143,
"s": 30060,
"text": "Parameters: hash: indicates logical value. If TRUE, environments uses a hash table"
},
{
"code": null,
"e": 30230,
"s": 30143,
"text": "To know about more optional parameters, use below command in console: help(“new.env”) "
},
{
"code": null,
"e": 30239,
"s": 30230,
"text": "Example:"
},
{
"code": null,
"e": 30241,
"s": 30239,
"text": "R"
},
{
"code": "# R program to illustrate# Environments in R # Create new environmentnewEnv <- new.env() # Assigning variablesnewEnv$x <- 1newEnv$y <- \"GFG\"newEnv$z <- 1:10 # Printprint(newEnv$z)",
"e": 30424,
"s": 30241,
"text": null
},
{
"code": null,
"e": 30433,
"s": 30424,
"text": "Output: "
},
{
"code": null,
"e": 30468,
"s": 30433,
"text": " [1] 1 2 3 4 5 6 7 8 9 10"
},
{
"code": null,
"e": 30759,
"s": 30468,
"text": "Every environment has a parent environment but there is an empty environment that does not have any parent environment. All the environments can be listed using ls() function and search() function. ls() function also list out all the bindings of the variables in a particular environment. "
},
{
"code": null,
"e": 30768,
"s": 30759,
"text": "Syntax: "
},
{
"code": null,
"e": 30783,
"s": 30768,
"text": "ls() search() "
},
{
"code": null,
"e": 30827,
"s": 30783,
"text": "Parameters:These functions need no argument"
},
{
"code": null,
"e": 30837,
"s": 30827,
"text": "Example: "
},
{
"code": null,
"e": 30839,
"s": 30837,
"text": "R"
},
{
"code": "# R program to illustrate# Environments in R # Prints all the bindings and environments # attached to Global Environmentls() # Prints bindings of newEnvls(newEnv) # Lists all the environments of the parent environmentsearch()",
"e": 31068,
"s": 30839,
"text": null
},
{
"code": null,
"e": 31077,
"s": 31068,
"text": "Output: "
},
{
"code": null,
"e": 31368,
"s": 31077,
"text": "[1] \"al\" \"e\" \"e1\" \"f\" \"newEnv\" \"pts\" \"x\" \"y\" \n[9] \"z\"\n\n[1] \"x\" \"y\" \"z\"\n\n[1] \".GlobalEnv\" \"package:stats\" \"package:graphics\" \n[4] \"package:grDevices\" \"package:utils\" \"package:datasets\" \n[7] \"package:methods\" \"Autoloads\" \"package:base\" \n"
},
{
"code": null,
"e": 31599,
"s": 31368,
"text": "A variable in an environment is deleted using rm() function. It is different from deleting entries from lists as entries in lists are set as NULL to be deleted. But, using rm() function, bindings are removed from the environment. "
},
{
"code": null,
"e": 31616,
"s": 31599,
"text": "Syntax: rm(...) "
},
{
"code": null,
"e": 31660,
"s": 31616,
"text": "Parameters: ...: indicates list of objects "
},
{
"code": null,
"e": 31670,
"s": 31660,
"text": "Example: "
},
{
"code": null,
"e": 31672,
"s": 31670,
"text": "R"
},
{
"code": "# R program to illustrate# Environments in R # Remove newEnvrm(newEnv) # Listls()",
"e": 31756,
"s": 31672,
"text": null
},
{
"code": null,
"e": 31765,
"s": 31756,
"text": "Output: "
},
{
"code": null,
"e": 31816,
"s": 31765,
"text": "[1] \"al\" \"e\" \"e1\" \"f\" \"pts\" \"x\" \"y\" \"z\"\n"
},
{
"code": null,
"e": 32123,
"s": 31816,
"text": "A variable or a function can be searched in R programming by using where() function among all the environments and packages present. where() function is present in pryr package. This function takes only two arguments, the name of the object to search for and the environment from where to start the search."
},
{
"code": null,
"e": 32144,
"s": 32123,
"text": "Syntax: where(name) "
},
{
"code": null,
"e": 32192,
"s": 32144,
"text": "Parameters: name: indicates object to look for "
},
{
"code": null,
"e": 32202,
"s": 32192,
"text": "Example: "
},
{
"code": null,
"e": 32204,
"s": 32202,
"text": "R"
},
{
"code": "# R program to illustrate# Environments in R # Install pryr packageinstall.packages(\"pryr\") # Load the packagelibrary(pryr) # Searchwhere(\"x\") where(\"mode\")",
"e": 32365,
"s": 32204,
"text": null
},
{
"code": null,
"e": 32374,
"s": 32365,
"text": "Output: "
},
{
"code": null,
"e": 32422,
"s": 32374,
"text": "<environment: R_GlobalEnv>\n<environment: base>\n"
},
{
"code": null,
"e": 32431,
"s": 32422,
"text": "R-basics"
},
{
"code": null,
"e": 32441,
"s": 32431,
"text": "R-Objects"
},
{
"code": null,
"e": 32452,
"s": 32441,
"text": "R Language"
},
{
"code": null,
"e": 32550,
"s": 32452,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32595,
"s": 32550,
"text": "Change column name of a given DataFrame in R"
},
{
"code": null,
"e": 32653,
"s": 32595,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 32705,
"s": 32653,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 32768,
"s": 32705,
"text": "Adding elements in a vector in R programming - append() method"
},
{
"code": null,
"e": 32800,
"s": 32768,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 32852,
"s": 32800,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 32896,
"s": 32852,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 32961,
"s": 32896,
"text": "Convert Factor to Numeric and Numeric to Factor in R Programming"
},
{
"code": null,
"e": 32999,
"s": 32961,
"text": "How to Change Axis Scales in R Plots?"
}
] |
Exploring Pathfinding Graph Algorithms | by Tomaz Bratanic | Towards Data Science
|
In the first part of the series, we constructed a knowledge graph of monuments located in Spain from WikiData API. Now we’ll put on our graph data science goggles and explore various pathfinding algorithms available in the Neo4j Graph Data Science library. To top it off, we’ll look at a brute force solution for a Santa Claus problem. Now, you might wonder what a Santa Claus problem is. It is a variation of the traveling salesman problem, except we don’t require the solution to end in the same city as it started. This is because of the Santa Claus’ ability to bend the time-space continuum and instantly fly back to the North Pole once he’s finished with delivering goodies.
Infer spatial network of monumentsLoad the in-memory projected graph with cypher projectionWeakly connected component algorithmShortest path algorithmYen’s k-shortest path algorithmSingle source shortest paths algorithmMinimum spanning tree algorithmRandom walk algorithmTraveling salesman problemConclusion
Infer spatial network of monuments
Load the in-memory projected graph with cypher projection
Weakly connected component algorithm
Shortest path algorithm
Yen’s k-shortest path algorithm
Single source shortest paths algorithm
Minimum spanning tree algorithm
Random walk algorithm
Traveling salesman problem
Conclusion
Currently, we have no direct relationships between the monuments in our graph. We do, however, have their GPS locations, which allows us to identify which monuments are nearby. This way, we can infer a spatial network of monuments.
The process is very similar to inferring a similarity network. We usually don’t want to end up with a complete graph, where each node is connected to all the other ones. It would defeat the purpose of demonstrating pathfinding algorithms as the shortest path between any two nodes would always be a straight line, which would be represented as a direct relationship between the two nodes. In our case, we will connect each monument to the five closest monuments that are less than 100 kilometers away. These two numbers are entirely arbitrary. You can pick any other depending on your scenario.
MATCH (m1:Monument),(m2:Monument) WHERE id(m1) > id(m2) WITH m1,m2, distance(m1.location_point,m2.location_point) as distance ORDER BY distance ASCWHERE distance < 100000WITH m1,collect({node:m2,distance:distance})[..5] as nearest UNWIND nearest as near WITH m1, near, near.node as nearest_node MERGE (m1)-[m:NEAR]-(nearest_node) SET m.distance = near.distance
Let’s just quickly refresh how does the GDS library work.
The graph analytics pipeline consists of three parts. In the first part, the graph loader reads the stored graph from Neo4j and loads it as an in-memory projected graph. We can use either native projection or cypher projection to load the projected graph. In the second step, we execute the graph algorithms in sequence. We can use the results of one graph algorithm as an input to another. Last but not least, we store or stream the results back to Neo4j.
Here, we will use the cypher projection to load the in-memory graph. I suggest you take a look at the official documentation for more details regarding how it works. In the node statement, we will describe all monuments in our graph and add their architecture style as a node label. Adding a custom node label will allow us to filter nodes by architectural style at algorithm execution time. In the relationship statement, we will describe all the links between monuments and include the distance property, that we will use as a relationship weight.
CALL gds.graph.create.cypher('monuments', 'MATCH (m:Monument)-[:ARCHITECTURE]->(a) RETURN id(m) as id, collect(a.name) as labels', 'MATCH (m1:Monument)-[r:NEAR]-(m2:Monument) RETURN id(m1) as source, id(m2) as target, r.distance as distance')
Even though the weakly connected component algorithm is not a pathfinding algorithm, it is part of almost every graph analysis. It is used to find disconnected components or islands within our graph. We’ll begin by running the stats mode of the algorithm.
CALL gds.wcc.stats('monuments') YIELD componentCount, componentDistribution
Results
There are six separate components within our monuments network. The results are typical for a real-world dataset. We have a single super component that contains 98% of all nodes and a couple of tiny islands floating around. Let’s examine the smaller components.
CALL gds.wcc.stream('monuments')YIELD nodeId, componentId WITH componentId, gds.util.asNode(nodeId) as nodeOPTIONAL MATCH (node)-[:IS_IN*2..2]->(state)RETURN componentId, count(*) as component_size, collect(node.name) as monuments, collect(distinct state.id) as stateORDER BY component_size DESC SKIP 1
Results
Three of the five smaller components are located in the Canaries archipelago, and one is located in the Balearic Islands, specifically on Majorca. With the Neomap application, developed by Estelle Scifo, we can visualize the Canaries archipelago components on a map.
One component spans over two monuments on Fuerteventura and Lanzarote. The second one consists of a couple of monuments located on Tenerife and Gran Canaria. On the left, there is a single monument on El Hierro Island. They are separate components because there is no link between them. The absence of a connection between the components implies that there are more than 100 kilometers away because that is the threshold we chose when we inferred the spatial network.
P.s. If you like any water activities, I highly recommend visiting the Canaries.
The first pathfinding graph algorithm we will use is the Shortest Path algorithm. It finds the shortest weighted path between two nodes. We define the start node and the end node and specify which relationship weight property should the algorithm take into consideration when calculating the shortest path.
MATCH (s:Monument{name:'Iglesia de Santo Domingo'}), (e:Monument{name:'Colegiata de Santa María de Piasca'})CALL gds.alpha.shortestPath.stream('monuments',{ startNode:s, endNode:e, relationshipWeightProperty:'distance'})YIELD nodeId, costRETURN gds.util.asNode(nodeId).name as monument, cost
Results
The cost is expressed as the distance in meters. We can visualize the shortest path with a slightly modified version of Neomap. I have customized the popup of the monuments to include its image and the architectural style.
You might observe that we skip the Santa Cruz de Cangas de Onís monument, which is located in the middle right of the image. A slight detour will result in a longer path than just traversing in a straight line from Iglesia de San Emeterio to Santo Toribio de Liébana.
What if we wanted to plan a trip for an architectural class and visit only monuments that were influenced by either Gothic or Romanesque architecture along the way? Planning such a trip is very easy with the GDS library, as we can filter which nodes can the algorithm visit with the nodeLabels parameter.
MATCH (s:Monument{name:'Iglesia de Santo Domingo'}), (t:Monument{name:'Colegiata de Santa María de Piasca'})CALL gds.alpha.shortestPath.stream('monuments',{ startNode:s, endNode:t, relationshipWeightProperty:'distance', nodeLabels:['Gothic architecture','Romanesque architecture']}) YIELD nodeId, costRETURN gds.util.asNode(nodeId).name as monument, cost
Results
The route is a bit different this time as the algorithm can only visit monuments that were influenced by Gothic or Romanesque architecture style.
We have learned how to calculate the shortest weighted path between a pair of nodes. What if we were more cautious tourists and wanted to find the top three shortest paths? Having a backup plan if something unexpected might happen along the way is always a good idea. In this scenario, we could use the Yen’s k-shortest path algorithm. The syntax is almost identical to the Shortest Path algorithm, except for the added k parameter, which defines how many shortest paths we would like to find.
MATCH (s:Monument{name:'Iglesia de Santo Domingo'}), (t:Monument{name:'Colegiata de Santa María de Piasca'})CALL gds.alpha.kShortestPaths.stream('monuments',{ startNode:s, endNode:t, k:3, relationshipWeightProperty:'distance'}) YIELD index,nodeIds,costsRETURN index,[nodeId in nodeIds | gds.util.asNode(nodeId).name] as monuments,apoc.coll.sum(costs) as total_cost
Results
The three paths are almost the same length, just a couple hundred meters of difference. If you look closely, only the second stop is different among the three variants. Such a small difference can be attributed to the nature of our spatial network and the example pair of nodes.
With the Single Source Shortest Path algorithm, we define the start node and search for the shortest weighted path to all the other nodes in the network. We’ll inspect one of the Canaries components to limit the number of shortest paths to a reasonable number.
We’ll examine the Tenerife — Gran Canaria component and choose the Cathedral of La Laguna as the starting node. The algorithm tries to find the shortest paths to all the other nodes in the network, and if no such way exists, it returns Infinity value as a result. We will filter out the unreachable nodes with the gds.util.isFinite procedure.
MATCH (start:Monument{name:’Cathedral of La Laguna’})CALL gds.alpha.shortestPaths.stream(‘monuments’, {startNode:start, relationshipWeightProperty:’distance’})YIELD nodeId, distanceWHERE gds.util.isFinite(distance) = TrueRETURN gds.util.asNode(nodeId).name as monument,distanceORDER BY distance ASC
Results
The closest monument to the Cathedral of La Laguna is the Iglesia de la Concepción, which is just 420 meters away. It seems that there are two Iglesia de la Concepción on Tenerife Island as we can observe that it shows up twice in our results. The farthest reachable monument in our network from the Cathedral of La Laguna is Basilica of San Juan Bautista.
If we wanted to find the cost of the shortest path to all the reachable neoclassical monuments from the Cathedral of La Laguna, we could effortlessly achieve this with the nodeLabels parameter.
MATCH (start:Monument{name:'Cathedral of La Laguna'})CALL gds.alpha.shortestPaths.stream('monuments', {startNode:start, relationshipWeightProperty:'distance', nodeLabels:['Neoclassical architecture']})YIELD nodeId, distanceWHERE gds.util.isFinite(distance) = TrueRETURN gds.util.asNode(nodeId).name as monument, distanceORDER BY distance ASC
Results
It seems there are only four neoclassical monuments on Tenerife and Gran Canaria islands.
The Minimum Weight Spanning Tree algorithm starts from a given node and calculates a spanning tree connecting all reachable nodes with the minimum possible sum of relationship weights. For example, if we wanted to connect all the monuments in Tenerife and Gran Canaria with an optical or electric cable, we would use the Minimum Weight Spanning Tree algorithm.
MATCH (start:Monument{name:’Cathedral of La Laguna’})CALL gds.alpha.spanningTree.minimum.write(‘monuments’,{ startNodeId:id(start), relationshipWeightProperty:’distance’, weightWriteProperty:’cost’})YIELD effectiveNodeCountRETURN effectiveNodeCount
Results
Currently, only the write mode of the algorithm is available. We can visualize our potential cable route with Neomap.
We can imagine the Random Walk algorithm trying to mimic a drunk crowd traversing the network. They might go left, or right, take two steps forward, one step back, we never really know. It depends on how drunk the crowd is. We can use this algorithm to provide random trip recommendations. Imagine we have just visited the University of Barcelona historical building and are not sure which monuments we should take a look at next.
MATCH (m:Monument{name:"University of Barcelona historical building"})CALL gds.alpha.randomWalk.stream('monuments', {start:id(m), walks:3, steps:5})YIELD nodeIdsRETURN [nodeId in nodeIds | gds.util.asNode(nodeId).name] as result
Results
Remember, we mentioned that the Random Walk algorithm tries to mimic a drunk person traversing the network. Well, an intoxicated person might visit the same monument twice and not care. For example, in the first and third suggestions, a single monument shows up twice. Luckily, we have some options to influence how the algorithm should traverse the network in the node2vec mode with the following two parameters:
return: This parameter controls the likelihood of immediately revisiting a node in a walk. Setting it to a high value (> max(inOut, 1)) ensures that we are less likely to sample an already visited node in the following two steps.
inOut: This parameter allows the search to differentiate between “inward” and “outward” nodes. If inOut > 1, the random walk is biased towards nodes close to node t. In contrast, if inOut < 1, the walk is more inclined to visit nodes that are further away from the node t.
The definition of the two parameters is summarized from the original Node2vec paper.
We want to recommend monuments close to our starting point, so we choose the inOut parameter to be greater than 1. And we definitely would like to avoid revisiting an already visited node during the walk, so we choose the return parameter to be greater than the inOut parameter.
MATCH (m:Monument{name:"University of Barcelona historical building"})CALL gds.alpha.randomWalk.stream('monuments', {start:id(m), walks:3, steps:5, mode:'node2vec', inOut:5, return:10})YIELD nodeIdsRETURN [nodeId in nodeIds | gds.util.asNode(nodeId).name] as result
Results
Unfortunately, the return parameter ensures that we are less likely to sample an already visited node in the following two steps. This means that we can’t be sure that duplicates won’t show up later during our walk. In our example, Casa Batlló appears twice in the first suggestion. We can circumnavigate this problem by creating longer walk suggestions and filtering out duplicates before showing the results to the user. In the following query, we calculate nine steps long walks, filter out duplicates, and return only the first five results.
MATCH (m:Monument{name:"University of Barcelona historical building"})CALL gds.alpha.randomWalk.stream('monuments', {start:id(m), walks:3, steps:9, mode:'node2vec', inOut:5, return:10})YIELD nodeIdsRETURN apoc.coll.toSet([nodeId in nodeIds | gds.util.asNode(nodeId).name])[..5] as result
Results
This way, we make sure the results never contain duplicates. Now we can visualize the results with our trip recommendation application.
To top it off, we will solve the Santa Claus variation of the traveling salesman problem. As mentioned, the only difference is that we omit the requirement to end up in the same location as we started. I found the inspiration for this problem in the Gaming the Christmas Market post written by David Barton. I give all the credits to David Barton for conjuring up the solution. My contribution is to update it to work with Neo4j 4.0 and the GDS library.
Say we want to find the optimal route between this monuments:
:param selection => ["Castell de Santa Pau","Castell de Sant Jaume","Castell de Vilaüt","Castell de Sarraí","Castell de Solius","Portal d'Albanyà","Castell de Sant Gregori","Casa Frigola"]
We split the solution into two steps. First, we calculate the shortest path between all pairs of selected monuments with the gds.alpha.shortestPath algorithm and store the results as the SHORTEST_ROUTE_TO relationship between the given pair of nodes. We save the total cost and all the intermediate nodes along the shortest path as the properties of the SHORTEST_ROUTE_TO relationship.
WITH $selection as selectionMATCH (c:Monument)WHERE c.name in selectionWITH collect(c) as monumentsUNWIND monuments as c1WITH c1, [c in monuments where c.name > c1.name | c] as c2s, monumentsUNWIND c2s as c2CALL gds.alpha.shortestPath.stream('monuments',{startNode:c1,endNode:c2,relationshipWeightProperty:'distance'})YIELD nodeId, costWITH c1, c2, max(cost) as totalCost, collect(nodeId) as shortestHopNodeIdsMERGE (c1) -[r:SHORTEST_ROUTE_TO]- (c2)SET r.cost = totalCost, r.shortestHopNodeIds = shortestHopNodeIds
After completing the first step, we have created a complete graph of SHORTEST_ROUTE_TO relationships between the selected monuments.
In the second step, we will use the apoc.path.expandConfig procedure. It enables us to perform variable-length path traversals with fine-grained control over the traversals. Check out the documentation for more details.
We allow the procedure to traverse only SHORTEST_ROUTE_TO relationships with the relationshipFilter parameter and visit only the selected monuments with the whitelistNodes parameter. We ensure that all selected nodes must be visited exactly once by defining the number of hops or levels traversed (minLevel and maxLevel) and with the uniqueness parameter. I know it is a lot to comprehend, and if you need some help, I would suggest asking questions on the Neo4j community site. We then select the path with the minimum sum of relationship weights as the solution. Because we calculate all the possible routes between the chosen monuments, this is a brute-force solution of the traveling salesman problem.
WITH $selection as selectionMATCH (c:Monument) WHERE c.name in selectionWITH collect(c) as monumentsUNWIND monuments as c1WITH c1, [c in monuments where c.name > c1.name | c] as c2s, monuments, (size(monuments) - 1) as levelUNWIND c2s as c2CALL apoc.path.expandConfig(c1, { relationshipFilter: 'SHORTEST_ROUTE_TO', minLevel: level, maxLevel: level, whitelistNodes: monuments, terminatorNodes: [c2], uniqueness: 'NODE_PATH'}) YIELD pathWITH path, reduce(cost = 0, x in relationships(path) | cost + x.cost) as totalCostORDER BY totalCost LIMIT 1WITH path, totalCost, apoc.coll.flatten([r in relationships(path) | r.shortestHopNodeIds]) as intermediate_stops, [n in nodes(path) | id(n)] as node_idsRETURN [n in nodes(path) | n.name] as path, round(totalCost) as total_distance, [optional in intermediate_stops where not optional in node_ids | gds.util.asNode(optional).name] as optional_stops
Results
In the path column of the results, we have an ordered array of selected monuments to visit. Our travel would start with Castell de Sant Jaume and continue to Castell de Vilaüt and so on. We could dub this the Spanish castle-visiting trip as we selected six castles, and we have an option to see four more along the way. The total air distance of the path is 126 kilometers. Let’s visualize the results with our trip recommendation application.
Red markers are the selected monuments, and the blue markers are the optional stops along the way.
We have demonstrated most of the pathfinding algorithm available in the Neo4j Graph Data Science library with some real world use cases. The only puzzle left in this series is to finish the trip recommendation application. I have a plan to show off the application in the part three of the series. Till then, I encourage you to play around with various GDS library algorithm or try to recreate this series on a Neo4j sandbox instance. If you have any further questions, there are a bunch of Neo4j experts ready to help you on Neo4j community site.
As always, the code is available on GitHub.
|
[
{
"code": null,
"e": 852,
"s": 172,
"text": "In the first part of the series, we constructed a knowledge graph of monuments located in Spain from WikiData API. Now we’ll put on our graph data science goggles and explore various pathfinding algorithms available in the Neo4j Graph Data Science library. To top it off, we’ll look at a brute force solution for a Santa Claus problem. Now, you might wonder what a Santa Claus problem is. It is a variation of the traveling salesman problem, except we don’t require the solution to end in the same city as it started. This is because of the Santa Claus’ ability to bend the time-space continuum and instantly fly back to the North Pole once he’s finished with delivering goodies."
},
{
"code": null,
"e": 1160,
"s": 852,
"text": "Infer spatial network of monumentsLoad the in-memory projected graph with cypher projectionWeakly connected component algorithmShortest path algorithmYen’s k-shortest path algorithmSingle source shortest paths algorithmMinimum spanning tree algorithmRandom walk algorithmTraveling salesman problemConclusion"
},
{
"code": null,
"e": 1195,
"s": 1160,
"text": "Infer spatial network of monuments"
},
{
"code": null,
"e": 1253,
"s": 1195,
"text": "Load the in-memory projected graph with cypher projection"
},
{
"code": null,
"e": 1290,
"s": 1253,
"text": "Weakly connected component algorithm"
},
{
"code": null,
"e": 1314,
"s": 1290,
"text": "Shortest path algorithm"
},
{
"code": null,
"e": 1346,
"s": 1314,
"text": "Yen’s k-shortest path algorithm"
},
{
"code": null,
"e": 1385,
"s": 1346,
"text": "Single source shortest paths algorithm"
},
{
"code": null,
"e": 1417,
"s": 1385,
"text": "Minimum spanning tree algorithm"
},
{
"code": null,
"e": 1439,
"s": 1417,
"text": "Random walk algorithm"
},
{
"code": null,
"e": 1466,
"s": 1439,
"text": "Traveling salesman problem"
},
{
"code": null,
"e": 1477,
"s": 1466,
"text": "Conclusion"
},
{
"code": null,
"e": 1709,
"s": 1477,
"text": "Currently, we have no direct relationships between the monuments in our graph. We do, however, have their GPS locations, which allows us to identify which monuments are nearby. This way, we can infer a spatial network of monuments."
},
{
"code": null,
"e": 2304,
"s": 1709,
"text": "The process is very similar to inferring a similarity network. We usually don’t want to end up with a complete graph, where each node is connected to all the other ones. It would defeat the purpose of demonstrating pathfinding algorithms as the shortest path between any two nodes would always be a straight line, which would be represented as a direct relationship between the two nodes. In our case, we will connect each monument to the five closest monuments that are less than 100 kilometers away. These two numbers are entirely arbitrary. You can pick any other depending on your scenario."
},
{
"code": null,
"e": 2665,
"s": 2304,
"text": "MATCH (m1:Monument),(m2:Monument) WHERE id(m1) > id(m2) WITH m1,m2, distance(m1.location_point,m2.location_point) as distance ORDER BY distance ASCWHERE distance < 100000WITH m1,collect({node:m2,distance:distance})[..5] as nearest UNWIND nearest as near WITH m1, near, near.node as nearest_node MERGE (m1)-[m:NEAR]-(nearest_node) SET m.distance = near.distance"
},
{
"code": null,
"e": 2723,
"s": 2665,
"text": "Let’s just quickly refresh how does the GDS library work."
},
{
"code": null,
"e": 3180,
"s": 2723,
"text": "The graph analytics pipeline consists of three parts. In the first part, the graph loader reads the stored graph from Neo4j and loads it as an in-memory projected graph. We can use either native projection or cypher projection to load the projected graph. In the second step, we execute the graph algorithms in sequence. We can use the results of one graph algorithm as an input to another. Last but not least, we store or stream the results back to Neo4j."
},
{
"code": null,
"e": 3730,
"s": 3180,
"text": "Here, we will use the cypher projection to load the in-memory graph. I suggest you take a look at the official documentation for more details regarding how it works. In the node statement, we will describe all monuments in our graph and add their architecture style as a node label. Adding a custom node label will allow us to filter nodes by architectural style at algorithm execution time. In the relationship statement, we will describe all the links between monuments and include the distance property, that we will use as a relationship weight."
},
{
"code": null,
"e": 3981,
"s": 3730,
"text": "CALL gds.graph.create.cypher('monuments', 'MATCH (m:Monument)-[:ARCHITECTURE]->(a) RETURN id(m) as id, collect(a.name) as labels', 'MATCH (m1:Monument)-[r:NEAR]-(m2:Monument) RETURN id(m1) as source, id(m2) as target, r.distance as distance')"
},
{
"code": null,
"e": 4237,
"s": 3981,
"text": "Even though the weakly connected component algorithm is not a pathfinding algorithm, it is part of almost every graph analysis. It is used to find disconnected components or islands within our graph. We’ll begin by running the stats mode of the algorithm."
},
{
"code": null,
"e": 4313,
"s": 4237,
"text": "CALL gds.wcc.stats('monuments') YIELD componentCount, componentDistribution"
},
{
"code": null,
"e": 4321,
"s": 4313,
"text": "Results"
},
{
"code": null,
"e": 4583,
"s": 4321,
"text": "There are six separate components within our monuments network. The results are typical for a real-world dataset. We have a single super component that contains 98% of all nodes and a couple of tiny islands floating around. Let’s examine the smaller components."
},
{
"code": null,
"e": 4906,
"s": 4583,
"text": "CALL gds.wcc.stream('monuments')YIELD nodeId, componentId WITH componentId, gds.util.asNode(nodeId) as nodeOPTIONAL MATCH (node)-[:IS_IN*2..2]->(state)RETURN componentId, count(*) as component_size, collect(node.name) as monuments, collect(distinct state.id) as stateORDER BY component_size DESC SKIP 1"
},
{
"code": null,
"e": 4914,
"s": 4906,
"text": "Results"
},
{
"code": null,
"e": 5181,
"s": 4914,
"text": "Three of the five smaller components are located in the Canaries archipelago, and one is located in the Balearic Islands, specifically on Majorca. With the Neomap application, developed by Estelle Scifo, we can visualize the Canaries archipelago components on a map."
},
{
"code": null,
"e": 5649,
"s": 5181,
"text": "One component spans over two monuments on Fuerteventura and Lanzarote. The second one consists of a couple of monuments located on Tenerife and Gran Canaria. On the left, there is a single monument on El Hierro Island. They are separate components because there is no link between them. The absence of a connection between the components implies that there are more than 100 kilometers away because that is the threshold we chose when we inferred the spatial network."
},
{
"code": null,
"e": 5730,
"s": 5649,
"text": "P.s. If you like any water activities, I highly recommend visiting the Canaries."
},
{
"code": null,
"e": 6037,
"s": 5730,
"text": "The first pathfinding graph algorithm we will use is the Shortest Path algorithm. It finds the shortest weighted path between two nodes. We define the start node and the end node and specify which relationship weight property should the algorithm take into consideration when calculating the shortest path."
},
{
"code": null,
"e": 6340,
"s": 6037,
"text": "MATCH (s:Monument{name:'Iglesia de Santo Domingo'}), (e:Monument{name:'Colegiata de Santa María de Piasca'})CALL gds.alpha.shortestPath.stream('monuments',{ startNode:s, endNode:e, relationshipWeightProperty:'distance'})YIELD nodeId, costRETURN gds.util.asNode(nodeId).name as monument, cost"
},
{
"code": null,
"e": 6348,
"s": 6340,
"text": "Results"
},
{
"code": null,
"e": 6571,
"s": 6348,
"text": "The cost is expressed as the distance in meters. We can visualize the shortest path with a slightly modified version of Neomap. I have customized the popup of the monuments to include its image and the architectural style."
},
{
"code": null,
"e": 6841,
"s": 6571,
"text": "You might observe that we skip the Santa Cruz de Cangas de Onís monument, which is located in the middle right of the image. A slight detour will result in a longer path than just traversing in a straight line from Iglesia de San Emeterio to Santo Toribio de Liébana."
},
{
"code": null,
"e": 7146,
"s": 6841,
"text": "What if we wanted to plan a trip for an architectural class and visit only monuments that were influenced by either Gothic or Romanesque architecture along the way? Planning such a trip is very easy with the GDS library, as we can filter which nodes can the algorithm visit with the nodeLabels parameter."
},
{
"code": null,
"e": 7513,
"s": 7146,
"text": "MATCH (s:Monument{name:'Iglesia de Santo Domingo'}), (t:Monument{name:'Colegiata de Santa María de Piasca'})CALL gds.alpha.shortestPath.stream('monuments',{ startNode:s, endNode:t, relationshipWeightProperty:'distance', nodeLabels:['Gothic architecture','Romanesque architecture']}) YIELD nodeId, costRETURN gds.util.asNode(nodeId).name as monument, cost"
},
{
"code": null,
"e": 7521,
"s": 7513,
"text": "Results"
},
{
"code": null,
"e": 7667,
"s": 7521,
"text": "The route is a bit different this time as the algorithm can only visit monuments that were influenced by Gothic or Romanesque architecture style."
},
{
"code": null,
"e": 8161,
"s": 7667,
"text": "We have learned how to calculate the shortest weighted path between a pair of nodes. What if we were more cautious tourists and wanted to find the top three shortest paths? Having a backup plan if something unexpected might happen along the way is always a good idea. In this scenario, we could use the Yen’s k-shortest path algorithm. The syntax is almost identical to the Shortest Path algorithm, except for the added k parameter, which defines how many shortest paths we would like to find."
},
{
"code": null,
"e": 8536,
"s": 8161,
"text": "MATCH (s:Monument{name:'Iglesia de Santo Domingo'}), (t:Monument{name:'Colegiata de Santa María de Piasca'})CALL gds.alpha.kShortestPaths.stream('monuments',{ startNode:s, endNode:t, k:3, relationshipWeightProperty:'distance'}) YIELD index,nodeIds,costsRETURN index,[nodeId in nodeIds | gds.util.asNode(nodeId).name] as monuments,apoc.coll.sum(costs) as total_cost"
},
{
"code": null,
"e": 8544,
"s": 8536,
"text": "Results"
},
{
"code": null,
"e": 8823,
"s": 8544,
"text": "The three paths are almost the same length, just a couple hundred meters of difference. If you look closely, only the second stop is different among the three variants. Such a small difference can be attributed to the nature of our spatial network and the example pair of nodes."
},
{
"code": null,
"e": 9084,
"s": 8823,
"text": "With the Single Source Shortest Path algorithm, we define the start node and search for the shortest weighted path to all the other nodes in the network. We’ll inspect one of the Canaries components to limit the number of shortest paths to a reasonable number."
},
{
"code": null,
"e": 9427,
"s": 9084,
"text": "We’ll examine the Tenerife — Gran Canaria component and choose the Cathedral of La Laguna as the starting node. The algorithm tries to find the shortest paths to all the other nodes in the network, and if no such way exists, it returns Infinity value as a result. We will filter out the unreachable nodes with the gds.util.isFinite procedure."
},
{
"code": null,
"e": 9726,
"s": 9427,
"text": "MATCH (start:Monument{name:’Cathedral of La Laguna’})CALL gds.alpha.shortestPaths.stream(‘monuments’, {startNode:start, relationshipWeightProperty:’distance’})YIELD nodeId, distanceWHERE gds.util.isFinite(distance) = TrueRETURN gds.util.asNode(nodeId).name as monument,distanceORDER BY distance ASC"
},
{
"code": null,
"e": 9734,
"s": 9726,
"text": "Results"
},
{
"code": null,
"e": 10093,
"s": 9734,
"text": "The closest monument to the Cathedral of La Laguna is the Iglesia de la Concepción, which is just 420 meters away. It seems that there are two Iglesia de la Concepción on Tenerife Island as we can observe that it shows up twice in our results. The farthest reachable monument in our network from the Cathedral of La Laguna is Basilica of San Juan Bautista."
},
{
"code": null,
"e": 10287,
"s": 10093,
"text": "If we wanted to find the cost of the shortest path to all the reachable neoclassical monuments from the Cathedral of La Laguna, we could effortlessly achieve this with the nodeLabels parameter."
},
{
"code": null,
"e": 10634,
"s": 10287,
"text": "MATCH (start:Monument{name:'Cathedral of La Laguna'})CALL gds.alpha.shortestPaths.stream('monuments', {startNode:start, relationshipWeightProperty:'distance', nodeLabels:['Neoclassical architecture']})YIELD nodeId, distanceWHERE gds.util.isFinite(distance) = TrueRETURN gds.util.asNode(nodeId).name as monument, distanceORDER BY distance ASC"
},
{
"code": null,
"e": 10642,
"s": 10634,
"text": "Results"
},
{
"code": null,
"e": 10732,
"s": 10642,
"text": "It seems there are only four neoclassical monuments on Tenerife and Gran Canaria islands."
},
{
"code": null,
"e": 11093,
"s": 10732,
"text": "The Minimum Weight Spanning Tree algorithm starts from a given node and calculates a spanning tree connecting all reachable nodes with the minimum possible sum of relationship weights. For example, if we wanted to connect all the monuments in Tenerife and Gran Canaria with an optical or electric cable, we would use the Minimum Weight Spanning Tree algorithm."
},
{
"code": null,
"e": 11342,
"s": 11093,
"text": "MATCH (start:Monument{name:’Cathedral of La Laguna’})CALL gds.alpha.spanningTree.minimum.write(‘monuments’,{ startNodeId:id(start), relationshipWeightProperty:’distance’, weightWriteProperty:’cost’})YIELD effectiveNodeCountRETURN effectiveNodeCount"
},
{
"code": null,
"e": 11350,
"s": 11342,
"text": "Results"
},
{
"code": null,
"e": 11468,
"s": 11350,
"text": "Currently, only the write mode of the algorithm is available. We can visualize our potential cable route with Neomap."
},
{
"code": null,
"e": 11899,
"s": 11468,
"text": "We can imagine the Random Walk algorithm trying to mimic a drunk crowd traversing the network. They might go left, or right, take two steps forward, one step back, we never really know. It depends on how drunk the crowd is. We can use this algorithm to provide random trip recommendations. Imagine we have just visited the University of Barcelona historical building and are not sure which monuments we should take a look at next."
},
{
"code": null,
"e": 12129,
"s": 11899,
"text": "MATCH (m:Monument{name:\"University of Barcelona historical building\"})CALL gds.alpha.randomWalk.stream('monuments', {start:id(m), walks:3, steps:5})YIELD nodeIdsRETURN [nodeId in nodeIds | gds.util.asNode(nodeId).name] as result"
},
{
"code": null,
"e": 12137,
"s": 12129,
"text": "Results"
},
{
"code": null,
"e": 12551,
"s": 12137,
"text": "Remember, we mentioned that the Random Walk algorithm tries to mimic a drunk person traversing the network. Well, an intoxicated person might visit the same monument twice and not care. For example, in the first and third suggestions, a single monument shows up twice. Luckily, we have some options to influence how the algorithm should traverse the network in the node2vec mode with the following two parameters:"
},
{
"code": null,
"e": 12781,
"s": 12551,
"text": "return: This parameter controls the likelihood of immediately revisiting a node in a walk. Setting it to a high value (> max(inOut, 1)) ensures that we are less likely to sample an already visited node in the following two steps."
},
{
"code": null,
"e": 13054,
"s": 12781,
"text": "inOut: This parameter allows the search to differentiate between “inward” and “outward” nodes. If inOut > 1, the random walk is biased towards nodes close to node t. In contrast, if inOut < 1, the walk is more inclined to visit nodes that are further away from the node t."
},
{
"code": null,
"e": 13139,
"s": 13054,
"text": "The definition of the two parameters is summarized from the original Node2vec paper."
},
{
"code": null,
"e": 13418,
"s": 13139,
"text": "We want to recommend monuments close to our starting point, so we choose the inOut parameter to be greater than 1. And we definitely would like to avoid revisiting an already visited node during the walk, so we choose the return parameter to be greater than the inOut parameter."
},
{
"code": null,
"e": 13688,
"s": 13418,
"text": "MATCH (m:Monument{name:\"University of Barcelona historical building\"})CALL gds.alpha.randomWalk.stream('monuments', {start:id(m), walks:3, steps:5, mode:'node2vec', inOut:5, return:10})YIELD nodeIdsRETURN [nodeId in nodeIds | gds.util.asNode(nodeId).name] as result"
},
{
"code": null,
"e": 13696,
"s": 13688,
"text": "Results"
},
{
"code": null,
"e": 14243,
"s": 13696,
"text": "Unfortunately, the return parameter ensures that we are less likely to sample an already visited node in the following two steps. This means that we can’t be sure that duplicates won’t show up later during our walk. In our example, Casa Batlló appears twice in the first suggestion. We can circumnavigate this problem by creating longer walk suggestions and filtering out duplicates before showing the results to the user. In the following query, we calculate nine steps long walks, filter out duplicates, and return only the first five results."
},
{
"code": null,
"e": 14535,
"s": 14243,
"text": "MATCH (m:Monument{name:\"University of Barcelona historical building\"})CALL gds.alpha.randomWalk.stream('monuments', {start:id(m), walks:3, steps:9, mode:'node2vec', inOut:5, return:10})YIELD nodeIdsRETURN apoc.coll.toSet([nodeId in nodeIds | gds.util.asNode(nodeId).name])[..5] as result"
},
{
"code": null,
"e": 14543,
"s": 14535,
"text": "Results"
},
{
"code": null,
"e": 14679,
"s": 14543,
"text": "This way, we make sure the results never contain duplicates. Now we can visualize the results with our trip recommendation application."
},
{
"code": null,
"e": 15133,
"s": 14679,
"text": "To top it off, we will solve the Santa Claus variation of the traveling salesman problem. As mentioned, the only difference is that we omit the requirement to end up in the same location as we started. I found the inspiration for this problem in the Gaming the Christmas Market post written by David Barton. I give all the credits to David Barton for conjuring up the solution. My contribution is to update it to work with Neo4j 4.0 and the GDS library."
},
{
"code": null,
"e": 15195,
"s": 15133,
"text": "Say we want to find the optimal route between this monuments:"
},
{
"code": null,
"e": 15387,
"s": 15195,
"text": ":param selection => [\"Castell de Santa Pau\",\"Castell de Sant Jaume\",\"Castell de Vilaüt\",\"Castell de Sarraí\",\"Castell de Solius\",\"Portal d'Albanyà\",\"Castell de Sant Gregori\",\"Casa Frigola\"]"
},
{
"code": null,
"e": 15773,
"s": 15387,
"text": "We split the solution into two steps. First, we calculate the shortest path between all pairs of selected monuments with the gds.alpha.shortestPath algorithm and store the results as the SHORTEST_ROUTE_TO relationship between the given pair of nodes. We save the total cost and all the intermediate nodes along the shortest path as the properties of the SHORTEST_ROUTE_TO relationship."
},
{
"code": null,
"e": 16309,
"s": 15773,
"text": "WITH $selection as selectionMATCH (c:Monument)WHERE c.name in selectionWITH collect(c) as monumentsUNWIND monuments as c1WITH c1, [c in monuments where c.name > c1.name | c] as c2s, monumentsUNWIND c2s as c2CALL gds.alpha.shortestPath.stream('monuments',{startNode:c1,endNode:c2,relationshipWeightProperty:'distance'})YIELD nodeId, costWITH c1, c2, max(cost) as totalCost, collect(nodeId) as shortestHopNodeIdsMERGE (c1) -[r:SHORTEST_ROUTE_TO]- (c2)SET r.cost = totalCost, r.shortestHopNodeIds = shortestHopNodeIds"
},
{
"code": null,
"e": 16442,
"s": 16309,
"text": "After completing the first step, we have created a complete graph of SHORTEST_ROUTE_TO relationships between the selected monuments."
},
{
"code": null,
"e": 16662,
"s": 16442,
"text": "In the second step, we will use the apoc.path.expandConfig procedure. It enables us to perform variable-length path traversals with fine-grained control over the traversals. Check out the documentation for more details."
},
{
"code": null,
"e": 17368,
"s": 16662,
"text": "We allow the procedure to traverse only SHORTEST_ROUTE_TO relationships with the relationshipFilter parameter and visit only the selected monuments with the whitelistNodes parameter. We ensure that all selected nodes must be visited exactly once by defining the number of hops or levels traversed (minLevel and maxLevel) and with the uniqueness parameter. I know it is a lot to comprehend, and if you need some help, I would suggest asking questions on the Neo4j community site. We then select the path with the minimum sum of relationship weights as the solution. Because we calculate all the possible routes between the chosen monuments, this is a brute-force solution of the traveling salesman problem."
},
{
"code": null,
"e": 18303,
"s": 17368,
"text": "WITH $selection as selectionMATCH (c:Monument) WHERE c.name in selectionWITH collect(c) as monumentsUNWIND monuments as c1WITH c1, [c in monuments where c.name > c1.name | c] as c2s, monuments, (size(monuments) - 1) as levelUNWIND c2s as c2CALL apoc.path.expandConfig(c1, { relationshipFilter: 'SHORTEST_ROUTE_TO', minLevel: level, maxLevel: level, whitelistNodes: monuments, terminatorNodes: [c2], uniqueness: 'NODE_PATH'}) YIELD pathWITH path, reduce(cost = 0, x in relationships(path) | cost + x.cost) as totalCostORDER BY totalCost LIMIT 1WITH path, totalCost, apoc.coll.flatten([r in relationships(path) | r.shortestHopNodeIds]) as intermediate_stops, [n in nodes(path) | id(n)] as node_idsRETURN [n in nodes(path) | n.name] as path, round(totalCost) as total_distance, [optional in intermediate_stops where not optional in node_ids | gds.util.asNode(optional).name] as optional_stops"
},
{
"code": null,
"e": 18311,
"s": 18303,
"text": "Results"
},
{
"code": null,
"e": 18756,
"s": 18311,
"text": "In the path column of the results, we have an ordered array of selected monuments to visit. Our travel would start with Castell de Sant Jaume and continue to Castell de Vilaüt and so on. We could dub this the Spanish castle-visiting trip as we selected six castles, and we have an option to see four more along the way. The total air distance of the path is 126 kilometers. Let’s visualize the results with our trip recommendation application."
},
{
"code": null,
"e": 18855,
"s": 18756,
"text": "Red markers are the selected monuments, and the blue markers are the optional stops along the way."
},
{
"code": null,
"e": 19403,
"s": 18855,
"text": "We have demonstrated most of the pathfinding algorithm available in the Neo4j Graph Data Science library with some real world use cases. The only puzzle left in this series is to finish the trip recommendation application. I have a plan to show off the application in the part three of the series. Till then, I encourage you to play around with various GDS library algorithm or try to recreate this series on a Neo4j sandbox instance. If you have any further questions, there are a bunch of Neo4j experts ready to help you on Neo4j community site."
}
] |
Learn Bayes Theorem by Detecting SPAM | by GreekDataGuy | Towards Data Science
|
This tutorial has 2 parts:1. Deriving Bayes theorem from conditional probability2. Predicting if an SMS message is a spam
I covered conditional probability in more depth here.
Conditional probability tells us the probability of an event occurring, given another event.
P(A|B) = P(A ∩ B) / P(B) is the probability A occurs, in cases where we knowB occurs. It’s calculated as the probability that both A and B occur, divided by the probability that B occurs.
But what if we wanted to find the reverse, the probability of B, in cases where A occurs?
Sometimes conditional probability works great for that to. But sometimes it’s easier to use Bayes theorem.
Wikipedia says,
In probability theory and statistics, Bayes’s theorem (alternatively Bayes’s law or Bayes’s rule) describes the probability of an event, based on prior knowledge of conditions that might be related to the event.
We start with the formula for conditional probability which can be written either, “A given B” or “B given A”.
Note that intuitively, P(A∩B) and P(B∩A) are the same (see below). This means we can use them interchangeably. Keep this in mind for later.
We’ll start with the 1st formula, P(A|B)= P(A∩B) / P(B).
Multiple both sides by P(B). This will cancel out the P(B) denominator on the right, leaving us with below.
What we can now see (more easily if we swapped the left and right sides) is that P(A∩B)= P(A|B) * P(B) . We’ll plug this back into our 2nd original formula (original below).
To get this formula (modified below).
Which is Bayes theorem.
We’ll now use Bayes theorem to try and predict spam in SMS messages.
Bayesian inference has a long history in spam detection. We’ll get into the basics here with some real data.
In our case, the probability an SMS is spam, given some word, is equal to the probability of the word, given it is in a spam SMS, multiplied by the probability of spam, all divided by the probability of the word.
Download the dataset from Kaggle, and inspect it in a dataframe.
import pandas as pddf = pd.read_csv('sms-spam.csv', encoding='ISO-8859-1')df.head(3)
The columns in the original CSV don’t make sense. So we’ll move the useful information into 2 new columns, one of which is a boolean indicating if the SMS is spam.
FYI, “ham” means “not spam”.
import numpy as npdf['sms'] = df['v2']df['spam'] = np.where(df['v1'] == 'spam', 1, 0)df.head(3)
Now drop the old columns.
df = df[['sms','spam']]df.head()
Much better.
Check the number of records.
len(df)#=> 5572
That’s a lot. Let’s work with a sample of 25% of the original data.
sample_df = df.sample(frac=0.25)len(sample_df)#=> 1393
That’s better.
Now split the data into 2 separate dataframes, one for spam and one for ham.
spam_df = sample_df.loc[df['spam'] == 1]ham_df = sample_df.loc[df['spam'] == 0]print(len(spam_df))print(len(ham_df))#=> 180#=> 1213
We’ll use sklearn’s TFIDF vectorizer to eyeball some words important in the spam messages, and pick one to plug into our formula.
from sklearn.feature_extraction.text import TfidfVectorizervectorizer_spam = TfidfVectorizer(stop_words='english', max_features=30)vectorizer_spam.fit(spam_df['sms'])vectorizer_spam.vocabulary_
We need to pick a word to use in our formula so I’m going to choose the word “win”, though it would be interesting to try this for other words as well.
Now we need to calculate the different parts of our formula.
P(W|S) = probability of the word “win” being in a spam messageP(S) = probability of a spam message overallP(W) = probability of the word “win” in a message overall
Set our word.
word = 'win'
Calculate P(W|S).
word = 'win'spam_count = 0spam_with_word_count = 0for idx,row in spam_df.iterrows(): spam_count += 1 if word in row.sms: spam_with_word_count += 1probability_of_word_given_spam = spam_count / spam_with_word_countprint(probability_of_word_given_spam)#=> 10.0
Calculate P(S).
probability_of_spam = len(spam_df) / (len(sample_df))print(probability_of_spam)#=> 0.12921751615218952
Calculate P(W).
sms_count = 0word_in_sms_count = 0for idx,row in sample_df.iterrows(): sms_count += 1 if word in row.sms: word_in_sms_count += 1probability_of_word = word_in_sms_count / sms_countprint(probability_of_word)#=> 0.022254127781765973
Now putting it all together.
(probability_of_word_given_spam * probability_of_spam) / probability_of_word#=> 58.064516129032256
Boom. What this tells us is that if an SMS contains the word “win”, there is a 58% probability that the message is spam.
In a production spam detection system, we would need to do the above calculation for every word in our corpus, then combine the probabilities.
We may also want to include other features like combinations of words, message length, punctuation, etc.
That would turn this into a really long post.
If you’re interested, there is a PDF article here, explaining a couple approaches to combining results of multiple words.
I hope this gave you some insight and practical experience using Bayes theorem, even if we just scratched the surface.
|
[
{
"code": null,
"e": 293,
"s": 171,
"text": "This tutorial has 2 parts:1. Deriving Bayes theorem from conditional probability2. Predicting if an SMS message is a spam"
},
{
"code": null,
"e": 347,
"s": 293,
"text": "I covered conditional probability in more depth here."
},
{
"code": null,
"e": 440,
"s": 347,
"text": "Conditional probability tells us the probability of an event occurring, given another event."
},
{
"code": null,
"e": 628,
"s": 440,
"text": "P(A|B) = P(A ∩ B) / P(B) is the probability A occurs, in cases where we knowB occurs. It’s calculated as the probability that both A and B occur, divided by the probability that B occurs."
},
{
"code": null,
"e": 718,
"s": 628,
"text": "But what if we wanted to find the reverse, the probability of B, in cases where A occurs?"
},
{
"code": null,
"e": 825,
"s": 718,
"text": "Sometimes conditional probability works great for that to. But sometimes it’s easier to use Bayes theorem."
},
{
"code": null,
"e": 841,
"s": 825,
"text": "Wikipedia says,"
},
{
"code": null,
"e": 1053,
"s": 841,
"text": "In probability theory and statistics, Bayes’s theorem (alternatively Bayes’s law or Bayes’s rule) describes the probability of an event, based on prior knowledge of conditions that might be related to the event."
},
{
"code": null,
"e": 1164,
"s": 1053,
"text": "We start with the formula for conditional probability which can be written either, “A given B” or “B given A”."
},
{
"code": null,
"e": 1304,
"s": 1164,
"text": "Note that intuitively, P(A∩B) and P(B∩A) are the same (see below). This means we can use them interchangeably. Keep this in mind for later."
},
{
"code": null,
"e": 1361,
"s": 1304,
"text": "We’ll start with the 1st formula, P(A|B)= P(A∩B) / P(B)."
},
{
"code": null,
"e": 1469,
"s": 1361,
"text": "Multiple both sides by P(B). This will cancel out the P(B) denominator on the right, leaving us with below."
},
{
"code": null,
"e": 1643,
"s": 1469,
"text": "What we can now see (more easily if we swapped the left and right sides) is that P(A∩B)= P(A|B) * P(B) . We’ll plug this back into our 2nd original formula (original below)."
},
{
"code": null,
"e": 1681,
"s": 1643,
"text": "To get this formula (modified below)."
},
{
"code": null,
"e": 1705,
"s": 1681,
"text": "Which is Bayes theorem."
},
{
"code": null,
"e": 1774,
"s": 1705,
"text": "We’ll now use Bayes theorem to try and predict spam in SMS messages."
},
{
"code": null,
"e": 1883,
"s": 1774,
"text": "Bayesian inference has a long history in spam detection. We’ll get into the basics here with some real data."
},
{
"code": null,
"e": 2096,
"s": 1883,
"text": "In our case, the probability an SMS is spam, given some word, is equal to the probability of the word, given it is in a spam SMS, multiplied by the probability of spam, all divided by the probability of the word."
},
{
"code": null,
"e": 2161,
"s": 2096,
"text": "Download the dataset from Kaggle, and inspect it in a dataframe."
},
{
"code": null,
"e": 2246,
"s": 2161,
"text": "import pandas as pddf = pd.read_csv('sms-spam.csv', encoding='ISO-8859-1')df.head(3)"
},
{
"code": null,
"e": 2410,
"s": 2246,
"text": "The columns in the original CSV don’t make sense. So we’ll move the useful information into 2 new columns, one of which is a boolean indicating if the SMS is spam."
},
{
"code": null,
"e": 2439,
"s": 2410,
"text": "FYI, “ham” means “not spam”."
},
{
"code": null,
"e": 2535,
"s": 2439,
"text": "import numpy as npdf['sms'] = df['v2']df['spam'] = np.where(df['v1'] == 'spam', 1, 0)df.head(3)"
},
{
"code": null,
"e": 2561,
"s": 2535,
"text": "Now drop the old columns."
},
{
"code": null,
"e": 2594,
"s": 2561,
"text": "df = df[['sms','spam']]df.head()"
},
{
"code": null,
"e": 2607,
"s": 2594,
"text": "Much better."
},
{
"code": null,
"e": 2636,
"s": 2607,
"text": "Check the number of records."
},
{
"code": null,
"e": 2652,
"s": 2636,
"text": "len(df)#=> 5572"
},
{
"code": null,
"e": 2720,
"s": 2652,
"text": "That’s a lot. Let’s work with a sample of 25% of the original data."
},
{
"code": null,
"e": 2775,
"s": 2720,
"text": "sample_df = df.sample(frac=0.25)len(sample_df)#=> 1393"
},
{
"code": null,
"e": 2790,
"s": 2775,
"text": "That’s better."
},
{
"code": null,
"e": 2867,
"s": 2790,
"text": "Now split the data into 2 separate dataframes, one for spam and one for ham."
},
{
"code": null,
"e": 2999,
"s": 2867,
"text": "spam_df = sample_df.loc[df['spam'] == 1]ham_df = sample_df.loc[df['spam'] == 0]print(len(spam_df))print(len(ham_df))#=> 180#=> 1213"
},
{
"code": null,
"e": 3129,
"s": 2999,
"text": "We’ll use sklearn’s TFIDF vectorizer to eyeball some words important in the spam messages, and pick one to plug into our formula."
},
{
"code": null,
"e": 3323,
"s": 3129,
"text": "from sklearn.feature_extraction.text import TfidfVectorizervectorizer_spam = TfidfVectorizer(stop_words='english', max_features=30)vectorizer_spam.fit(spam_df['sms'])vectorizer_spam.vocabulary_"
},
{
"code": null,
"e": 3475,
"s": 3323,
"text": "We need to pick a word to use in our formula so I’m going to choose the word “win”, though it would be interesting to try this for other words as well."
},
{
"code": null,
"e": 3536,
"s": 3475,
"text": "Now we need to calculate the different parts of our formula."
},
{
"code": null,
"e": 3700,
"s": 3536,
"text": "P(W|S) = probability of the word “win” being in a spam messageP(S) = probability of a spam message overallP(W) = probability of the word “win” in a message overall"
},
{
"code": null,
"e": 3714,
"s": 3700,
"text": "Set our word."
},
{
"code": null,
"e": 3727,
"s": 3714,
"text": "word = 'win'"
},
{
"code": null,
"e": 3745,
"s": 3727,
"text": "Calculate P(W|S)."
},
{
"code": null,
"e": 4020,
"s": 3745,
"text": "word = 'win'spam_count = 0spam_with_word_count = 0for idx,row in spam_df.iterrows(): spam_count += 1 if word in row.sms: spam_with_word_count += 1probability_of_word_given_spam = spam_count / spam_with_word_countprint(probability_of_word_given_spam)#=> 10.0"
},
{
"code": null,
"e": 4036,
"s": 4020,
"text": "Calculate P(S)."
},
{
"code": null,
"e": 4139,
"s": 4036,
"text": "probability_of_spam = len(spam_df) / (len(sample_df))print(probability_of_spam)#=> 0.12921751615218952"
},
{
"code": null,
"e": 4155,
"s": 4139,
"text": "Calculate P(W)."
},
{
"code": null,
"e": 4402,
"s": 4155,
"text": "sms_count = 0word_in_sms_count = 0for idx,row in sample_df.iterrows(): sms_count += 1 if word in row.sms: word_in_sms_count += 1probability_of_word = word_in_sms_count / sms_countprint(probability_of_word)#=> 0.022254127781765973"
},
{
"code": null,
"e": 4431,
"s": 4402,
"text": "Now putting it all together."
},
{
"code": null,
"e": 4530,
"s": 4431,
"text": "(probability_of_word_given_spam * probability_of_spam) / probability_of_word#=> 58.064516129032256"
},
{
"code": null,
"e": 4651,
"s": 4530,
"text": "Boom. What this tells us is that if an SMS contains the word “win”, there is a 58% probability that the message is spam."
},
{
"code": null,
"e": 4794,
"s": 4651,
"text": "In a production spam detection system, we would need to do the above calculation for every word in our corpus, then combine the probabilities."
},
{
"code": null,
"e": 4899,
"s": 4794,
"text": "We may also want to include other features like combinations of words, message length, punctuation, etc."
},
{
"code": null,
"e": 4945,
"s": 4899,
"text": "That would turn this into a really long post."
},
{
"code": null,
"e": 5067,
"s": 4945,
"text": "If you’re interested, there is a PDF article here, explaining a couple approaches to combining results of multiple words."
}
] |
Python | Convert a list of lists into tree-like dict - GeeksforGeeks
|
18 Feb, 2019
Given a list of lists, write a Python program to convert the given list of lists into a tree-like dictionary.
Examples:
Input : [[1], [2, 1], [3, 1], [4, 2, 1], [5, 2, 1], [6, 3, 1], [7, 3, 1]]
Output : {1: {2: {4: {}, 5: {}}, 3: {6: {}, 7: {}}}}
Input : [['A'], ['B', 'A'], ['C', 'A'], ['D', 'C', 'A']]
Output : {'A': {'C': {'D': {}}, 'B': {}}}
Method #1 : Naive MethodThis is a Naive approach in which we use two for loops to traverse the list of lists. We initialize the empty dictionary ‘tree’ to currTree and each time we check if the key (list of list’s item) is included in the currTree or not. If not, include it in the currTree, otherwise do nothing. Finally, assign the currTree[key] to currTree.
# Python3 program to Convert a list# of lists into Dictionary (Tree form) def formTree(list): tree = {} for item in list: currTree = tree for key in item[::-1]: if key not in currTree: currTree[key] = {} currTree = currTree[key] return tree # Driver Codelst = [['A'], ['B', 'A'], ['C', 'A'], ['D', 'C', 'A']]print(formTree(lst))
{'A': {'B': {}, 'C': {'D': {}}}}
Method #2 : Using reduce()The reduce() function is used to apply a particular function passed in its argument to all of the list elements mentioned in the sequence passed along. We will use reduce() to traverse the dictionary and reuse getTree() to find the location to store the value for setTree(). All but the last element in mapList is needed to find the ‘parent’ dictionary to add the value to, then use the last element to set the value to the right key.
# Python3 program to Convert a list# of lists into Dictionary (Tree form) from functools import reducefrom operator import getitem def getTree(tree, mappings): return reduce(getitem, mappings, tree) def setTree(tree, mappings): getTree(tree, mappings[:-1])[mappings[-1]] = dict() # Driver Codelst = [['A'], ['B', 'A'], ['C', 'A'], ['D', 'C', 'A']]tree ={}for item in lst: setTree(tree, item[::-1]) print(tree)
{'A': {'B': {}, 'C': {'D': {}}}}
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Box Plot in Python using Matplotlib
Bar Plot in Matplotlib
Python | Get dictionary keys as a list
Python | Convert set into a list
Ways to filter Pandas DataFrame by column values
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python program to check whether a number is Prime or not
Python | Convert a list to dictionary
|
[
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n18 Feb, 2019"
},
{
"code": null,
"e": 24011,
"s": 23901,
"text": "Given a list of lists, write a Python program to convert the given list of lists into a tree-like dictionary."
},
{
"code": null,
"e": 24021,
"s": 24011,
"text": "Examples:"
},
{
"code": null,
"e": 24249,
"s": 24021,
"text": "Input : [[1], [2, 1], [3, 1], [4, 2, 1], [5, 2, 1], [6, 3, 1], [7, 3, 1]]\nOutput : {1: {2: {4: {}, 5: {}}, 3: {6: {}, 7: {}}}}\n\nInput : [['A'], ['B', 'A'], ['C', 'A'], ['D', 'C', 'A']]\nOutput : {'A': {'C': {'D': {}}, 'B': {}}}\n"
},
{
"code": null,
"e": 24611,
"s": 24249,
"text": " Method #1 : Naive MethodThis is a Naive approach in which we use two for loops to traverse the list of lists. We initialize the empty dictionary ‘tree’ to currTree and each time we check if the key (list of list’s item) is included in the currTree or not. If not, include it in the currTree, otherwise do nothing. Finally, assign the currTree[key] to currTree."
},
{
"code": "# Python3 program to Convert a list# of lists into Dictionary (Tree form) def formTree(list): tree = {} for item in list: currTree = tree for key in item[::-1]: if key not in currTree: currTree[key] = {} currTree = currTree[key] return tree # Driver Codelst = [['A'], ['B', 'A'], ['C', 'A'], ['D', 'C', 'A']]print(formTree(lst))",
"e": 25018,
"s": 24611,
"text": null
},
{
"code": null,
"e": 25052,
"s": 25018,
"text": "{'A': {'B': {}, 'C': {'D': {}}}}\n"
},
{
"code": null,
"e": 25514,
"s": 25052,
"text": " Method #2 : Using reduce()The reduce() function is used to apply a particular function passed in its argument to all of the list elements mentioned in the sequence passed along. We will use reduce() to traverse the dictionary and reuse getTree() to find the location to store the value for setTree(). All but the last element in mapList is needed to find the ‘parent’ dictionary to add the value to, then use the last element to set the value to the right key."
},
{
"code": "# Python3 program to Convert a list# of lists into Dictionary (Tree form) from functools import reducefrom operator import getitem def getTree(tree, mappings): return reduce(getitem, mappings, tree) def setTree(tree, mappings): getTree(tree, mappings[:-1])[mappings[-1]] = dict() # Driver Codelst = [['A'], ['B', 'A'], ['C', 'A'], ['D', 'C', 'A']]tree ={}for item in lst: setTree(tree, item[::-1]) print(tree)",
"e": 25942,
"s": 25514,
"text": null
},
{
"code": null,
"e": 25976,
"s": 25942,
"text": "{'A': {'B': {}, 'C': {'D': {}}}}\n"
},
{
"code": null,
"e": 26003,
"s": 25976,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 26010,
"s": 26003,
"text": "Python"
},
{
"code": null,
"e": 26026,
"s": 26010,
"text": "Python Programs"
},
{
"code": null,
"e": 26124,
"s": 26026,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26133,
"s": 26124,
"text": "Comments"
},
{
"code": null,
"e": 26146,
"s": 26133,
"text": "Old Comments"
},
{
"code": null,
"e": 26182,
"s": 26146,
"text": "Box Plot in Python using Matplotlib"
},
{
"code": null,
"e": 26205,
"s": 26182,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 26244,
"s": 26205,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 26277,
"s": 26244,
"text": "Python | Convert set into a list"
},
{
"code": null,
"e": 26326,
"s": 26277,
"text": "Ways to filter Pandas DataFrame by column values"
},
{
"code": null,
"e": 26348,
"s": 26326,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26387,
"s": 26348,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 26433,
"s": 26387,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 26490,
"s": 26433,
"text": "Python program to check whether a number is Prime or not"
}
] |
Connecting to SQL Database using SQLAlchemy in Python
|
19 Dec, 2021
In this article, we will see how to connect to an SQL database using SQLAlchemy in Python.
To connect to a SQL database using SQLAlchemy we will require the sqlalchemy library installed in our python environment. It can be installed using pip –
$ pip install sqlalchemy
The create_engine() method of sqlalchemy library takes in the connection URL and returns a sqlalchemy engine that references both a Dialect and a Pool, which together interpret the DBAPI’s module functions as well as the behavior of the database.
Syntax: sqlalchemy.create_engine(url, **kwargs)
Parameters:
url: str
The connection URL to the database of type “dialect+driver://username:password@host:port/database”.
In this example, we have successfully created a connection to the MySQL database. Please note that we have created the database named ‘GeekForGeeks’ in the local instance of mySQL server with the password set as ‘password’. The dialect and driver for establishing the connection to MySQL database are MySQL and pymysql respectively.
Python
# IMPORT THE SQALCHEMY LIBRARY's CREATE_ENGINE METHODfrom sqlalchemy import create_engine # DEFINE THE DATABASE CREDENTIALSuser = 'root'password = 'password'host = '127.0.0.1'port = 3306database = 'GeeksForGeeks' # PYTHON FUNCTION TO CONNECT TO THE MYSQL DATABASE AND# RETURN THE SQLACHEMY ENGINE OBJECTdef get_connection(): return create_engine( url="mysql+pymysql://{0}:{1}@{2}:{3}/{4}".format( user, password, host, port, database ) ) if __name__ == '__main__': try: # GET THE CONNECTION OBJECT (ENGINE) FOR THE DATABASE engine = get_connection() print( f"Connection to the {host} for user {user} created successfully.") except Exception as ex: print("Connection could not be made due to the following error: \n", ex)
Output:
$ Connection to the 127.0.0.1 for user root created successfully.
In this example, a sqlalchemy engine connection has been established with the PostgreSQL database. Please note that we have used the pre-existing database named ‘postgres’ that comes within the local instance of postgresql server. The dialect and driver for establishing the connection to MySQL database is postgres.
Python
# IMPORT THE SQALCHEMY LIBRARY's CREATE_ENGINE METHODfrom sqlalchemy import create_engine # DEFINE THE DATABASE CREDENTIALSuser = 'root'password = 'password'host = '127.0.0.1'port = 5432database = 'postgres' # PYTHON FUNCTION TO CONNECT TO THE POSTGRESQL DATABASE AND# RETURN THE SQLACHEMY ENGINE OBJECTdef get_connection(): return create_engine( url="postgresql://{0}:{1}@{2}:{3}/{4}".format( user, password, host, port, database ) ) if __name__ == '__main__': try: # GET THE CONNECTION OBJECT (ENGINE) FOR THE DATABASE engine = get_connection() print( f"Connection to the {host} for user {user} created successfully.") except Exception as ex: print("Connection could not be made due to the following error: \n", ex)
Output:
$ Connection to the 127.0.0.1 for user root created successfully.
Picked
Python-SQLAlchemy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Dec, 2021"
},
{
"code": null,
"e": 119,
"s": 28,
"text": "In this article, we will see how to connect to an SQL database using SQLAlchemy in Python."
},
{
"code": null,
"e": 273,
"s": 119,
"text": "To connect to a SQL database using SQLAlchemy we will require the sqlalchemy library installed in our python environment. It can be installed using pip –"
},
{
"code": null,
"e": 298,
"s": 273,
"text": "$ pip install sqlalchemy"
},
{
"code": null,
"e": 545,
"s": 298,
"text": "The create_engine() method of sqlalchemy library takes in the connection URL and returns a sqlalchemy engine that references both a Dialect and a Pool, which together interpret the DBAPI’s module functions as well as the behavior of the database."
},
{
"code": null,
"e": 593,
"s": 545,
"text": "Syntax: sqlalchemy.create_engine(url, **kwargs)"
},
{
"code": null,
"e": 605,
"s": 593,
"text": "Parameters:"
},
{
"code": null,
"e": 614,
"s": 605,
"text": "url: str"
},
{
"code": null,
"e": 714,
"s": 614,
"text": "The connection URL to the database of type “dialect+driver://username:password@host:port/database”."
},
{
"code": null,
"e": 1048,
"s": 714,
"text": "In this example, we have successfully created a connection to the MySQL database. Please note that we have created the database named ‘GeekForGeeks’ in the local instance of mySQL server with the password set as ‘password’. The dialect and driver for establishing the connection to MySQL database are MySQL and pymysql respectively."
},
{
"code": null,
"e": 1055,
"s": 1048,
"text": "Python"
},
{
"code": "# IMPORT THE SQALCHEMY LIBRARY's CREATE_ENGINE METHODfrom sqlalchemy import create_engine # DEFINE THE DATABASE CREDENTIALSuser = 'root'password = 'password'host = '127.0.0.1'port = 3306database = 'GeeksForGeeks' # PYTHON FUNCTION TO CONNECT TO THE MYSQL DATABASE AND# RETURN THE SQLACHEMY ENGINE OBJECTdef get_connection(): return create_engine( url=\"mysql+pymysql://{0}:{1}@{2}:{3}/{4}\".format( user, password, host, port, database ) ) if __name__ == '__main__': try: # GET THE CONNECTION OBJECT (ENGINE) FOR THE DATABASE engine = get_connection() print( f\"Connection to the {host} for user {user} created successfully.\") except Exception as ex: print(\"Connection could not be made due to the following error: \\n\", ex)",
"e": 1867,
"s": 1055,
"text": null
},
{
"code": null,
"e": 1875,
"s": 1867,
"text": "Output:"
},
{
"code": null,
"e": 1941,
"s": 1875,
"text": "$ Connection to the 127.0.0.1 for user root created successfully."
},
{
"code": null,
"e": 2258,
"s": 1941,
"text": "In this example, a sqlalchemy engine connection has been established with the PostgreSQL database. Please note that we have used the pre-existing database named ‘postgres’ that comes within the local instance of postgresql server. The dialect and driver for establishing the connection to MySQL database is postgres."
},
{
"code": null,
"e": 2265,
"s": 2258,
"text": "Python"
},
{
"code": "# IMPORT THE SQALCHEMY LIBRARY's CREATE_ENGINE METHODfrom sqlalchemy import create_engine # DEFINE THE DATABASE CREDENTIALSuser = 'root'password = 'password'host = '127.0.0.1'port = 5432database = 'postgres' # PYTHON FUNCTION TO CONNECT TO THE POSTGRESQL DATABASE AND# RETURN THE SQLACHEMY ENGINE OBJECTdef get_connection(): return create_engine( url=\"postgresql://{0}:{1}@{2}:{3}/{4}\".format( user, password, host, port, database ) ) if __name__ == '__main__': try: # GET THE CONNECTION OBJECT (ENGINE) FOR THE DATABASE engine = get_connection() print( f\"Connection to the {host} for user {user} created successfully.\") except Exception as ex: print(\"Connection could not be made due to the following error: \\n\", ex)",
"e": 3066,
"s": 2265,
"text": null
},
{
"code": null,
"e": 3074,
"s": 3066,
"text": "Output:"
},
{
"code": null,
"e": 3140,
"s": 3074,
"text": "$ Connection to the 127.0.0.1 for user root created successfully."
},
{
"code": null,
"e": 3147,
"s": 3140,
"text": "Picked"
},
{
"code": null,
"e": 3165,
"s": 3147,
"text": "Python-SQLAlchemy"
},
{
"code": null,
"e": 3172,
"s": 3165,
"text": "Python"
},
{
"code": null,
"e": 3270,
"s": 3172,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3302,
"s": 3270,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3329,
"s": 3302,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3350,
"s": 3329,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3373,
"s": 3350,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3404,
"s": 3373,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 3460,
"s": 3404,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 3502,
"s": 3460,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 3544,
"s": 3502,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 3583,
"s": 3544,
"text": "Python | Get unique values from a list"
}
] |
Delete alternate nodes of a Linked List
|
03 Jul, 2022
Given a Singly Linked List, starting from the second node delete all alternate nodes of it. For example, if the given linked list is 1->2->3->4->5 then your function should convert it to 1->3->5, and if the given linked list is 1->2->3->4 then convert it to 1->3.
Method 1 (Iterative) Keep track of previous of the node to be deleted. First, change the next link of the previous node and iteratively move to the next node.
C++
C
Java
Python3
C#
Javascript
// C++ program to remove alternate // nodes of a linked list #include <bits/stdc++.h>using namespace std; /* A linked list node */class Node { public: int data; Node *next; }; /* deletes alternate nodes of a list starting with head */void deleteAlt(Node *head) { if (head == NULL) return; /* Initialize prev and node to be deleted */ Node *prev = head; Node *node = head->next; while (prev != NULL && node != NULL) { /* Change next link of previous node */ prev->next = node->next; delete(node); // delete the node /* Update prev and node */ prev = prev->next; if (prev != NULL) node = prev->next; } } /* UTILITY FUNCTIONS TO TEST fun1() and fun2() *//* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */void push(Node** head_ref, int new_data) { /* allocate node */ Node* new_node = new Node(); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } /* Function to print nodes in a given linked list */void printList(Node *node) { while (node != NULL) { cout<< node->data<<" "; node = node->next; } } /* Driver code */int main() { /* Start with the empty list */ Node* head = NULL; /* Using push() to construct below list 1->2->3->4->5 */ push(&head, 5); push(&head, 4); push(&head, 3); push(&head, 2); push(&head, 1); cout<<"List before calling deleteAlt() \n"; printList(head); deleteAlt(head); cout<<"\nList after calling deleteAlt() \n"; printList(head); return 0; } // This code is contributed by rathbhupendra
// C program to remove alternate nodes of a linked list#include<stdio.h>#include<stdlib.h> /* A linked list node */struct Node{ int data; struct Node *next;}; /* deletes alternate nodes of a list starting with head */void deleteAlt(struct Node *head){ if (head == NULL) return; /* Initialize prev and node to be deleted */ struct Node *prev = head; struct Node *node = head->next; while (prev != NULL && node != NULL) { /* Change next link of previous node */ prev->next = node->next; /* Free memory */ free(node); /* Update prev and node */ prev = prev->next; if (prev != NULL) node = prev->next; }} /* UTILITY FUNCTIONS TO TEST fun1() and fun2() *//* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print nodes in a given linked list */void printList(struct Node *node){ while (node != NULL) { printf("%d ", node->data); node = node->next; }} /* Driver program to test above functions */int main(){ /* Start with the empty list */ struct Node* head = NULL; /* Using push() to construct below list 1->2->3->4->5 */ push(&head, 5); push(&head, 4); push(&head, 3); push(&head, 2); push(&head, 1); printf("\nList before calling deleteAlt() \n"); printList(head); deleteAlt(head); printf("\nList after calling deleteAlt() \n"); printList(head); return 0;}
// Java program to delete alternate nodes of a linked listclass LinkedList { Node head; // head of list /* Linked list Node*/ class Node { int data; Node next; Node(int d) { data = d; next = null; } } void deleteAlt() { if (head == null) return; Node node = head; while (node != null && node.next != null) { /* Change next link of next node */ node.next = node.next.next; /*Update ref node to new alternate node */ node = node.next; } } /* Utility functions */ /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Function to print linked list */ void printList() { Node temp = head; while (temp != null) { System.out.print(temp.data + " "); temp = temp.next; } System.out.println(); } /* Driver program to test above functions */ public static void main(String args[]) { LinkedList llist = new LinkedList(); /* Constructed Linked List is 1->2->3->4->5->null */ llist.push(5); llist.push(4); llist.push(3); llist.push(2); llist.push(1); System.out.println( "Linked List before calling deleteAlt() "); llist.printList(); llist.deleteAlt(); System.out.println( "Linked List after calling deleteAlt() "); llist.printList(); }}/* This code is contributed by Rajat Mishra */
# Python3 program to remove alternate # nodes of a linked list import math # A linked list node class Node: def __init__(self, data): self.data = data self.next = None # deletes alternate nodes # of a list starting with head def deleteAlt(head): if (head == None): return # Initialize prev and node to be deleted prev = head now = head.next while (prev != None and now != None): # Change next link of previous node prev.next = now.next # Free memory now = None # Update prev and node prev = prev.next if (prev != None): now = prev.next # UTILITY FUNCTIONS TO TEST fun1() and fun2() # Given a reference (pointer to pointer) to the head # of a list and an , push a new node on the front # of the list. def push(head_ref, new_data): # allocate node new_node = Node(new_data) # put in the data new_node.data = new_data # link the old list off the new node new_node.next = head_ref # move the head to point to the new node head_ref = new_node return head_ref # Function to print nodes in a given linked list def printList(node): while (node != None): print(node.data, end = " ") node = node.next # Driver code if __name__=='__main__': # Start with the empty list head = None # Using head=push() to construct below list # 1.2.3.4.5 head = push(head, 5) head = push(head, 4) head = push(head, 3) head = push(head, 2) head = push(head, 1) print("List before calling deleteAlt() ") printList(head) deleteAlt(head) print("\nList after calling deleteAlt() ") printList(head) # This code is contributed by Srathore
// C# program to delete alternate// nodes of a linked listusing System; public class LinkedList{ Node head; // head of list /* Linked list Node*/ public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } void deleteAlt() { if (head == null) return; Node prev = head; Node now = head.next; while (prev != null && now != null) { /* Change next link of previous node */ prev.next = now.next; /* Free node */ now = null; /*Update prev and now */ prev = prev.next; if (prev != null) now = prev.next; } } /* Utility functions */ /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Function to print linked list */ void printList() { Node temp = head; while(temp != null) { Console.Write(temp.data+" "); temp = temp.next; } Console.WriteLine(); } /* Driver code*/ public static void Main(String []args) { LinkedList llist = new LinkedList(); /* Constructed Linked List is 1->2->3->4->5->null */ llist.push(5); llist.push(4); llist.push(3); llist.push(2); llist.push(1); Console.WriteLine("Linked List before" + "calling deleteAlt() "); llist.printList(); llist.deleteAlt(); Console.WriteLine("Linked List after" + "calling deleteAlt() "); llist.printList(); }} // This code has been contributed // by 29AjayKumar
<script> // Javascript program to delete alternate// nodes of a linked listvar head; // head of list /* Linked list Node */ class Node { constructor(val) { this.data = val; this.next = null; } } function deleteAlt() { if (head == null) return; var prev = head; var now = head.next; while (prev != null && now != null) { /* Change next link of previous node */ prev.next = now.next; /* Free node */ now = null; /* Update prev and now */ prev = prev.next; if (prev != null) now = prev.next; } } /* Utility functions */ /* Inserts a new Node at front of the list. */ function push(new_data) { /* * 1 & 2: Allocate the Node & Put in the data */ var new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Function to print linked list */ function printList() { var temp = head; while (temp != null) { document.write(temp.data + " "); temp = temp.next; } document.write("<br/>"); } /* Driver program to test above functions */ /* Constructed Linked List is 1->2->3->4->5->null */ push(5); push(4); push(3); push(2); push(1); document.write( "Linked List before calling deleteAlt() <br/>" ); printList(); deleteAlt(); document.write( "Linked List after calling deleteAlt()<br/> " ); printList(); // This code contributed by gauravrajput1 </script>
List before calling deleteAlt()
1 2 3 4 5
List after calling deleteAlt()
1 3 5
Time Complexity: O(n)
where n is the number of nodes in the given Linked List.
Auxiliary Space: O(1)
As constant extra space is used.
Method 2 (Recursive) Recursive code uses the same approach as method 1. The recursive code is simple and short but causes O(n) recursive function calls for a linked list of size n.
C++
C
Java
Python3
C#
Javascript
/* deletes alternate nodes of a list starting with head */void deleteAlt(Node *head) { if (head == NULL) return; Node *node = head->next; if (node == NULL) return; /* Change the next link of head */ head->next = node->next; /* free memory allocated for node */ free(node); /* Recursively call for the new next of head */ deleteAlt(head->next); } // This code is contributed by rathbhupendra
/* deletes alternate nodes of a list starting with head */void deleteAlt(struct Node *head){ if (head == NULL) return; struct Node *node = head->next; if (node == NULL) return; /* Change the next link of head */ head->next = node->next; /* free memory allocated for node */ free(node); /* Recursively call for the new next of head */ deleteAlt(head->next);}
/* deletes alternate nodes of a liststarting with head */static Node deleteAlt(Node head) { if (head == null) return; Node node = head.next; if (node == null) return; /* Change the next link of head */ head.next = node.next; /* Recursively call for the new next of head */ head.next = deleteAlt(head.next); } // This code is contributed by Arnab Kundu
# deletes alternate nodes of a list starting with head def deleteAlt(head): if (head == None): return node = head.next if (node == None): return # Change the next link of head head.next = node.next # free memory allocated for node #free(node) # Recursively call for the new next of head deleteAlt(head.next) # This code is contributed by Srathore
/* deletes alternate nodes of a liststarting with head */static Node deleteAlt(Node head) { if (head == null) return; Node node = head.next; if (node == null) return; /* Change the next link of head */ head.next = node.next; /* Recursively call for the new next of head */ head.next = deleteAlt(head.next); } // This code is contributed by Arnab Kundu
<script>/* deletes alternate nodes of a liststarting with head */function deleteAlt(head) { if (head == null) return; var node = head.next; if (node == null) return; /* Change the next link of head */ head.next = node.next; /* Recursively call for the new next of head */ head.next = deleteAlt(head.next); } // This code contributed by aashish1995 </script>
Time Complexity: O(n)
Auxiliary Space: O(1)
As this is a tail recursive function no function call stack is required thus the extra space used is constant.
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Please write comments if you find the above code/algorithm incorrect, or find better ways to solve the same problem.
29AjayKumar
rathbhupendra
andrew1234
sapnasingh4991
Akanksha_Rai
nidhi_biet
arorakashish0911
GauravRajput1
aashish1995
simmytarika5
surindertarika1234
surinderdawra388
ashwinaditya21
abhijeet19403
Morgan Stanley
Python-Data-Structures
Linked List
Morgan Stanley
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
What is Data Structure: Types, Classifications and Applications
Implementing a Linked List in Java using Class
Find Length of a Linked List (Iterative and Recursive)
Remove duplicates from an unsorted linked list
Write a function to get the intersection point of two Linked Lists
Queue - Linked List Implementation
Function to check if a singly linked list is palindrome
Circular Linked List | Set 1 (Introduction and Applications)
Implement a stack using singly linked list
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n03 Jul, 2022"
},
{
"code": null,
"e": 317,
"s": 52,
"text": "Given a Singly Linked List, starting from the second node delete all alternate nodes of it. For example, if the given linked list is 1->2->3->4->5 then your function should convert it to 1->3->5, and if the given linked list is 1->2->3->4 then convert it to 1->3. "
},
{
"code": null,
"e": 479,
"s": 317,
"text": "Method 1 (Iterative) Keep track of previous of the node to be deleted. First, change the next link of the previous node and iteratively move to the next node. "
},
{
"code": null,
"e": 483,
"s": 479,
"text": "C++"
},
{
"code": null,
"e": 485,
"s": 483,
"text": "C"
},
{
"code": null,
"e": 490,
"s": 485,
"text": "Java"
},
{
"code": null,
"e": 498,
"s": 490,
"text": "Python3"
},
{
"code": null,
"e": 501,
"s": 498,
"text": "C#"
},
{
"code": null,
"e": 512,
"s": 501,
"text": "Javascript"
},
{
"code": "// C++ program to remove alternate // nodes of a linked list #include <bits/stdc++.h>using namespace std; /* A linked list node */class Node { public: int data; Node *next; }; /* deletes alternate nodes of a list starting with head */void deleteAlt(Node *head) { if (head == NULL) return; /* Initialize prev and node to be deleted */ Node *prev = head; Node *node = head->next; while (prev != NULL && node != NULL) { /* Change next link of previous node */ prev->next = node->next; delete(node); // delete the node /* Update prev and node */ prev = prev->next; if (prev != NULL) node = prev->next; } } /* UTILITY FUNCTIONS TO TEST fun1() and fun2() *//* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */void push(Node** head_ref, int new_data) { /* allocate node */ Node* new_node = new Node(); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } /* Function to print nodes in a given linked list */void printList(Node *node) { while (node != NULL) { cout<< node->data<<\" \"; node = node->next; } } /* Driver code */int main() { /* Start with the empty list */ Node* head = NULL; /* Using push() to construct below list 1->2->3->4->5 */ push(&head, 5); push(&head, 4); push(&head, 3); push(&head, 2); push(&head, 1); cout<<\"List before calling deleteAlt() \\n\"; printList(head); deleteAlt(head); cout<<\"\\nList after calling deleteAlt() \\n\"; printList(head); return 0; } // This code is contributed by rathbhupendra",
"e": 2379,
"s": 512,
"text": null
},
{
"code": "// C program to remove alternate nodes of a linked list#include<stdio.h>#include<stdlib.h> /* A linked list node */struct Node{ int data; struct Node *next;}; /* deletes alternate nodes of a list starting with head */void deleteAlt(struct Node *head){ if (head == NULL) return; /* Initialize prev and node to be deleted */ struct Node *prev = head; struct Node *node = head->next; while (prev != NULL && node != NULL) { /* Change next link of previous node */ prev->next = node->next; /* Free memory */ free(node); /* Update prev and node */ prev = prev->next; if (prev != NULL) node = prev->next; }} /* UTILITY FUNCTIONS TO TEST fun1() and fun2() *//* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print nodes in a given linked list */void printList(struct Node *node){ while (node != NULL) { printf(\"%d \", node->data); node = node->next; }} /* Driver program to test above functions */int main(){ /* Start with the empty list */ struct Node* head = NULL; /* Using push() to construct below list 1->2->3->4->5 */ push(&head, 5); push(&head, 4); push(&head, 3); push(&head, 2); push(&head, 1); printf(\"\\nList before calling deleteAlt() \\n\"); printList(head); deleteAlt(head); printf(\"\\nList after calling deleteAlt() \\n\"); printList(head); return 0;}",
"e": 4275,
"s": 2379,
"text": null
},
{
"code": "// Java program to delete alternate nodes of a linked listclass LinkedList { Node head; // head of list /* Linked list Node*/ class Node { int data; Node next; Node(int d) { data = d; next = null; } } void deleteAlt() { if (head == null) return; Node node = head; while (node != null && node.next != null) { /* Change next link of next node */ node.next = node.next.next; /*Update ref node to new alternate node */ node = node.next; } } /* Utility functions */ /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Function to print linked list */ void printList() { Node temp = head; while (temp != null) { System.out.print(temp.data + \" \"); temp = temp.next; } System.out.println(); } /* Driver program to test above functions */ public static void main(String args[]) { LinkedList llist = new LinkedList(); /* Constructed Linked List is 1->2->3->4->5->null */ llist.push(5); llist.push(4); llist.push(3); llist.push(2); llist.push(1); System.out.println( \"Linked List before calling deleteAlt() \"); llist.printList(); llist.deleteAlt(); System.out.println( \"Linked List after calling deleteAlt() \"); llist.printList(); }}/* This code is contributed by Rajat Mishra */",
"e": 6128,
"s": 4275,
"text": null
},
{
"code": "# Python3 program to remove alternate # nodes of a linked list import math # A linked list node class Node: def __init__(self, data): self.data = data self.next = None # deletes alternate nodes # of a list starting with head def deleteAlt(head): if (head == None): return # Initialize prev and node to be deleted prev = head now = head.next while (prev != None and now != None): # Change next link of previous node prev.next = now.next # Free memory now = None # Update prev and node prev = prev.next if (prev != None): now = prev.next # UTILITY FUNCTIONS TO TEST fun1() and fun2() # Given a reference (pointer to pointer) to the head # of a list and an , push a new node on the front # of the list. def push(head_ref, new_data): # allocate node new_node = Node(new_data) # put in the data new_node.data = new_data # link the old list off the new node new_node.next = head_ref # move the head to point to the new node head_ref = new_node return head_ref # Function to print nodes in a given linked list def printList(node): while (node != None): print(node.data, end = \" \") node = node.next # Driver code if __name__=='__main__': # Start with the empty list head = None # Using head=push() to construct below list # 1.2.3.4.5 head = push(head, 5) head = push(head, 4) head = push(head, 3) head = push(head, 2) head = push(head, 1) print(\"List before calling deleteAlt() \") printList(head) deleteAlt(head) print(\"\\nList after calling deleteAlt() \") printList(head) # This code is contributed by Srathore",
"e": 7918,
"s": 6128,
"text": null
},
{
"code": "// C# program to delete alternate// nodes of a linked listusing System; public class LinkedList{ Node head; // head of list /* Linked list Node*/ public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } void deleteAlt() { if (head == null) return; Node prev = head; Node now = head.next; while (prev != null && now != null) { /* Change next link of previous node */ prev.next = now.next; /* Free node */ now = null; /*Update prev and now */ prev = prev.next; if (prev != null) now = prev.next; } } /* Utility functions */ /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Function to print linked list */ void printList() { Node temp = head; while(temp != null) { Console.Write(temp.data+\" \"); temp = temp.next; } Console.WriteLine(); } /* Driver code*/ public static void Main(String []args) { LinkedList llist = new LinkedList(); /* Constructed Linked List is 1->2->3->4->5->null */ llist.push(5); llist.push(4); llist.push(3); llist.push(2); llist.push(1); Console.WriteLine(\"Linked List before\" + \"calling deleteAlt() \"); llist.printList(); llist.deleteAlt(); Console.WriteLine(\"Linked List after\" + \"calling deleteAlt() \"); llist.printList(); }} // This code has been contributed // by 29AjayKumar",
"e": 10049,
"s": 7918,
"text": null
},
{
"code": "<script> // Javascript program to delete alternate// nodes of a linked listvar head; // head of list /* Linked list Node */ class Node { constructor(val) { this.data = val; this.next = null; } } function deleteAlt() { if (head == null) return; var prev = head; var now = head.next; while (prev != null && now != null) { /* Change next link of previous node */ prev.next = now.next; /* Free node */ now = null; /* Update prev and now */ prev = prev.next; if (prev != null) now = prev.next; } } /* Utility functions */ /* Inserts a new Node at front of the list. */ function push(new_data) { /* * 1 & 2: Allocate the Node & Put in the data */ var new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Function to print linked list */ function printList() { var temp = head; while (temp != null) { document.write(temp.data + \" \"); temp = temp.next; } document.write(\"<br/>\"); } /* Driver program to test above functions */ /* Constructed Linked List is 1->2->3->4->5->null */ push(5); push(4); push(3); push(2); push(1); document.write( \"Linked List before calling deleteAlt() <br/>\" ); printList(); deleteAlt(); document.write( \"Linked List after calling deleteAlt()<br/> \" ); printList(); // This code contributed by gauravrajput1 </script>",
"e": 11890,
"s": 10049,
"text": null
},
{
"code": null,
"e": 11973,
"s": 11890,
"text": "List before calling deleteAlt() \n1 2 3 4 5 \nList after calling deleteAlt() \n1 3 5 "
},
{
"code": null,
"e": 11996,
"s": 11973,
"text": "Time Complexity: O(n) "
},
{
"code": null,
"e": 12053,
"s": 11996,
"text": "where n is the number of nodes in the given Linked List."
},
{
"code": null,
"e": 12075,
"s": 12053,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 12108,
"s": 12075,
"text": "As constant extra space is used."
},
{
"code": null,
"e": 12291,
"s": 12108,
"text": "Method 2 (Recursive) Recursive code uses the same approach as method 1. The recursive code is simple and short but causes O(n) recursive function calls for a linked list of size n. "
},
{
"code": null,
"e": 12295,
"s": 12291,
"text": "C++"
},
{
"code": null,
"e": 12297,
"s": 12295,
"text": "C"
},
{
"code": null,
"e": 12302,
"s": 12297,
"text": "Java"
},
{
"code": null,
"e": 12310,
"s": 12302,
"text": "Python3"
},
{
"code": null,
"e": 12313,
"s": 12310,
"text": "C#"
},
{
"code": null,
"e": 12324,
"s": 12313,
"text": "Javascript"
},
{
"code": "/* deletes alternate nodes of a list starting with head */void deleteAlt(Node *head) { if (head == NULL) return; Node *node = head->next; if (node == NULL) return; /* Change the next link of head */ head->next = node->next; /* free memory allocated for node */ free(node); /* Recursively call for the new next of head */ deleteAlt(head->next); } // This code is contributed by rathbhupendra",
"e": 12776,
"s": 12324,
"text": null
},
{
"code": "/* deletes alternate nodes of a list starting with head */void deleteAlt(struct Node *head){ if (head == NULL) return; struct Node *node = head->next; if (node == NULL) return; /* Change the next link of head */ head->next = node->next; /* free memory allocated for node */ free(node); /* Recursively call for the new next of head */ deleteAlt(head->next);}",
"e": 13185,
"s": 12776,
"text": null
},
{
"code": "/* deletes alternate nodes of a liststarting with head */static Node deleteAlt(Node head) { if (head == null) return; Node node = head.next; if (node == null) return; /* Change the next link of head */ head.next = node.next; /* Recursively call for the new next of head */ head.next = deleteAlt(head.next); } // This code is contributed by Arnab Kundu",
"e": 13591,
"s": 13185,
"text": null
},
{
"code": "# deletes alternate nodes of a list starting with head def deleteAlt(head): if (head == None): return node = head.next if (node == None): return # Change the next link of head head.next = node.next # free memory allocated for node #free(node) # Recursively call for the new next of head deleteAlt(head.next) # This code is contributed by Srathore",
"e": 13998,
"s": 13591,
"text": null
},
{
"code": "/* deletes alternate nodes of a liststarting with head */static Node deleteAlt(Node head) { if (head == null) return; Node node = head.next; if (node == null) return; /* Change the next link of head */ head.next = node.next; /* Recursively call for the new next of head */ head.next = deleteAlt(head.next); } // This code is contributed by Arnab Kundu",
"e": 14404,
"s": 13998,
"text": null
},
{
"code": "<script>/* deletes alternate nodes of a liststarting with head */function deleteAlt(head) { if (head == null) return; var node = head.next; if (node == null) return; /* Change the next link of head */ head.next = node.next; /* Recursively call for the new next of head */ head.next = deleteAlt(head.next); } // This code contributed by aashish1995 </script>",
"e": 14813,
"s": 14404,
"text": null
},
{
"code": null,
"e": 14835,
"s": 14813,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 14857,
"s": 14835,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 14969,
"s": 14857,
"text": "As this is a tail recursive function no function call stack is required thus the extra space used is constant. "
},
{
"code": null,
"e": 14978,
"s": 14969,
"text": "Chapters"
},
{
"code": null,
"e": 15005,
"s": 14978,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 15055,
"s": 15005,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 15078,
"s": 15055,
"text": "captions off, selected"
},
{
"code": null,
"e": 15086,
"s": 15078,
"text": "English"
},
{
"code": null,
"e": 15110,
"s": 15086,
"text": "This is a modal window."
},
{
"code": null,
"e": 15179,
"s": 15110,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 15201,
"s": 15179,
"text": "End of dialog window."
},
{
"code": null,
"e": 15319,
"s": 15201,
"text": "Please write comments if you find the above code/algorithm incorrect, or find better ways to solve the same problem. "
},
{
"code": null,
"e": 15331,
"s": 15319,
"text": "29AjayKumar"
},
{
"code": null,
"e": 15345,
"s": 15331,
"text": "rathbhupendra"
},
{
"code": null,
"e": 15356,
"s": 15345,
"text": "andrew1234"
},
{
"code": null,
"e": 15371,
"s": 15356,
"text": "sapnasingh4991"
},
{
"code": null,
"e": 15384,
"s": 15371,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 15395,
"s": 15384,
"text": "nidhi_biet"
},
{
"code": null,
"e": 15412,
"s": 15395,
"text": "arorakashish0911"
},
{
"code": null,
"e": 15426,
"s": 15412,
"text": "GauravRajput1"
},
{
"code": null,
"e": 15438,
"s": 15426,
"text": "aashish1995"
},
{
"code": null,
"e": 15451,
"s": 15438,
"text": "simmytarika5"
},
{
"code": null,
"e": 15470,
"s": 15451,
"text": "surindertarika1234"
},
{
"code": null,
"e": 15487,
"s": 15470,
"text": "surinderdawra388"
},
{
"code": null,
"e": 15502,
"s": 15487,
"text": "ashwinaditya21"
},
{
"code": null,
"e": 15516,
"s": 15502,
"text": "abhijeet19403"
},
{
"code": null,
"e": 15531,
"s": 15516,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 15554,
"s": 15531,
"text": "Python-Data-Structures"
},
{
"code": null,
"e": 15566,
"s": 15554,
"text": "Linked List"
},
{
"code": null,
"e": 15581,
"s": 15566,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 15593,
"s": 15581,
"text": "Linked List"
},
{
"code": null,
"e": 15691,
"s": 15593,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 15723,
"s": 15691,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 15787,
"s": 15723,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 15834,
"s": 15787,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 15889,
"s": 15834,
"text": "Find Length of a Linked List (Iterative and Recursive)"
},
{
"code": null,
"e": 15936,
"s": 15889,
"text": "Remove duplicates from an unsorted linked list"
},
{
"code": null,
"e": 16003,
"s": 15936,
"text": "Write a function to get the intersection point of two Linked Lists"
},
{
"code": null,
"e": 16038,
"s": 16003,
"text": "Queue - Linked List Implementation"
},
{
"code": null,
"e": 16094,
"s": 16038,
"text": "Function to check if a singly linked list is palindrome"
},
{
"code": null,
"e": 16155,
"s": 16094,
"text": "Circular Linked List | Set 1 (Introduction and Applications)"
}
] |
SortedMap Interface in Java with Examples
|
20 Aug, 2020
SortedMap is an interface in the collection framework. This interface extends the Map interface and provides a total ordering of its elements (elements can be traversed in sorted order of keys). The class that implements this interface is TreeMap.
The main characteristic of a SortedMap is that it orders the keys by their natural ordering, or by a specified comparator. So consider using a TreeMap when you want a map that satisfies the following criteria:
null key or null value is not permitted.
The keys are sorted either by natural ordering or by a specified comparator.
Type Parameters:
K – the type of keys maintained by this map
V – the type of mapped values
The parent interface of SortedMap is Map<K, V>.
The subInterfaces of SortedMap are ConcurrentNavigableMap<K, V>, NavigableMap<K, V>.
SortedMap is implemented by ConcurrentSkipListMap, TreeMap.
Declaration:
public interface SortedMap<K, V> extends Map<K, V>
{
Comparator comparator();
SortedMap subMap(K fromKey, K toKey);
SortedMap headMap(K toKey);
SortedMap tailMap(K fromKey);
K firstKey();
K lastKey();
}
Example:
Java
// Java code to demonstrate SortedMap Interfaceimport java.util.Iterator;import java.util.Map;import java.util.Set;import java.util.SortedMap;import java.util.TreeMap; public class SortedMapExample { public static void main(String[] args) { SortedMap<Integer, String> sm = new TreeMap<Integer, String>(); sm.put(new Integer(2), "practice"); sm.put(new Integer(3), "quiz"); sm.put(new Integer(5), "code"); sm.put(new Integer(4), "contribute"); sm.put(new Integer(1), "geeksforgeeks"); Set s = sm.entrySet(); // Using iterator in SortedMap Iterator i = s.iterator(); // Traversing map. Note that the traversal // produced sorted (by keys) output . while (i.hasNext()) { Map.Entry m = (Map.Entry)i.next(); int key = (Integer)m.getKey(); String value = (String)m.getValue(); System.out.println("Key : " + key + " value : " + value); } }}
Output:
Key : 1 value : geeksforgeeks
Key : 2 value : practice
Key : 3 value : quiz
Key : 4 value : contribute
Key : 5 value : code
Creating SortedMap Objects
Since SortedMap is an interface, objects cannot be created of the type SortedMap. We always need a class that extends this list in order to create an object. And also, after the introduction of Generics in Java 1.5, it is possible to restrict the type of object that can be stored in the SortedMap. This type-safe map can be defined as:
// Obj1, Obj2 are the type of the object to be stored in SortedMap
SortedMap<Obj1, Obj2> set = new TreeMap<Obj1, Obj2> ();
Since SortedMap is an interface, it can be used only with a class that implements this interface. TreeMap is the class that implements the SortedMap interface. Now, let’s see how to perform a few frequently used operations on the TreeMap.
1. Adding Elements: In order to add an element to the SortedMap, we can use the put() method. However, the insertion order is not retained in the TreeMap. Internally, for every element, the keys are compared and sorted in the ascending order.
Java
// Java program add the elements in the SortedMapimport java.io.*;import java.util.*;class GFG { // Main Method public static void main(String args[]) { // Default Initialization of a // SortedMap SortedMap tm1 = new TreeMap(); // Initialization of a SortedMap // using Generics SortedMap<Integer, String> tm2 = new TreeMap<Integer, String>(); // Inserting the Elements tm1.put(3, "Geeks"); tm1.put(2, "For"); tm1.put(1, "Geeks"); tm2.put(new Integer(3), "Geeks"); tm2.put(new Integer(2), "For"); tm2.put(new Integer(1), "Geeks"); System.out.println(tm1); System.out.println(tm2); }}
Output:
{1=Geeks, 2=For, 3=Geeks}
{1=Geeks, 2=For, 3=Geeks}
2. Changing Elements: After adding the elements if we wish to change the element, it can be done by again adding the element with the put() method. Since the elements in the SortedMap are indexed using the keys, the value of the key can be changed by simply inserting the updated value for the key for which we wish to change.
Java
// Java program to change// the elements in SortedMapimport java.io.*;import java.util.*;class GFG { // Main Method public static void main(String args[]) { // Initialization of a SortedMap // using Generics SortedMap<Integer, String> tm = new TreeMap<Integer, String>(); // Inserting the Elements tm.put(3, "Geeks"); tm.put(2, "Geeks"); tm.put(1, "Geeks"); System.out.println(tm); tm.put(2, "For"); System.out.println(tm); }}
Output:
{1=Geeks, 2=Geeks, 3=Geeks}
{1=Geeks, 2=For, 3=Geeks}
3. Removing Element: In order to remove an element from the SortedMap, we can use the remove() method. This method takes the key value and removes the mapping for the key from this SortedMap if it is present in the map.
Java
// Java program to remove the // elements from SortedMapimport java.io.*;import java.util.*; class GFG { // Main Method public static void main(String args[]) { // Initialization of a SortedMap // using Generics SortedMap<Integer, String> tm = new TreeMap<Integer, String>(); // Inserting the Elements tm.put(3, "Geeks"); tm.put(2, "Geeks"); tm.put(1, "Geeks"); tm.put(4, "For"); System.out.println(tm); tm.remove(4); System.out.println(tm); }}
Output:
{1=Geeks, 2=Geeks, 3=Geeks, 4=For}
{1=Geeks, 2=Geeks, 3=Geeks}
4. Iterating through the SortedMap: There are multiple ways to iterate through the Map. The most famous way is to use an enhanced for loop and get the keys. The value of the key is found by using the getValue() method.
Java
// Java program to iterate through SortedMapimport java.util.*; class GFG { // Main Method public static void main(String args[]) { // Initialization of a SortedMap // using Generics SortedMap<Integer, String> tm = new TreeMap<Integer, String>(); // Inserting the Elements tm.put(3, "Geeks"); tm.put(2, "For"); tm.put(1, "Geeks"); for (Map.Entry mapElement : tm.entrySet()) { int key = (int)mapElement.getKey(); // Finding the value String value = (String)mapElement.getValue(); System.out.println(key + " : " + value); } }}
Output:
1 : Geeks
2 : For
3 : Geeks
The class which implements the SortedMap interface is TreeMap.
TreeMap class which is implemented in the collections framework is an implementation of the SortedMap Interface and SortedMap extends Map Interface. It behaves like a simple map with the exception that it stores keys in a sorted format. TreeMap uses a tree data structure for storage. Objects are stored in sorted, ascending order. But we can also store in descending order by passing a comparator. Let’s see how to create a SortedMap object using this class.
Java
// Java program to demonstrate the// creation of SortedMap object using// the TreeMap class import java.util.*; class GFG { public static void main(String[] args) { SortedMap<String, String> tm = new TreeMap<String, String>(new Comparator<String>() { public int compare(String a, String b) { return b.compareTo(a); } }); // Adding elements into the TreeMap // using put() tm.put("India", "1"); tm.put("Australia", "2"); tm.put("South Africa", "3"); // Displaying the TreeMap System.out.println(tm); // Removing items from TreeMap // using remove() tm.remove("Australia"); System.out.println("Map after removing " + "Australia:" + tm); }}
Output:
{South Africa=3, India=1, Australia=2}
Map after removing Australia:{South Africa=3, India=1}
This method is used to check whether a particular key is being mapped into the Map or not.
It takes the key element as a parameter and returns True if that element is mapped in the map.
This method is used to check whether a particular value is being mapped by a single or more than one key in the Map.
It takes the value as a parameter and returns True if that value is mapped by any of the key in the map.
This method is used to create a set out of the same elements contained in the map. It basically returns a set view of the map or we can create a new set and store the map elements into them.
This method is used to check for equality between two maps. It verifies whether the elements of one map passed as a parameter is equal to the elements of this map or not.
This method is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key.
This method is used to return a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa.
This method is used to create a collection out of the values of the map. It basically returns a Collection view of the values in the HashMap.
This article is contributed by Pratik Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
1rajarshimondal
Ganeshchowdharysadanala
Java - util package
Java-Collections
java-map
Java-SortedMap
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Split() String method in Java with examples
Arrays.sort() in Java with examples
Reverse a string in Java
How to iterate any Map in Java
Stream In Java
Initializing a List in Java
Singleton Class in Java
Initialize an ArrayList in Java
Generics in Java
Java Programming Examples
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n20 Aug, 2020"
},
{
"code": null,
"e": 303,
"s": 54,
"text": "SortedMap is an interface in the collection framework. This interface extends the Map interface and provides a total ordering of its elements (elements can be traversed in sorted order of keys). The class that implements this interface is TreeMap. "
},
{
"code": null,
"e": 514,
"s": 303,
"text": "The main characteristic of a SortedMap is that it orders the keys by their natural ordering, or by a specified comparator. So consider using a TreeMap when you want a map that satisfies the following criteria: "
},
{
"code": null,
"e": 555,
"s": 514,
"text": "null key or null value is not permitted."
},
{
"code": null,
"e": 632,
"s": 555,
"text": "The keys are sorted either by natural ordering or by a specified comparator."
},
{
"code": null,
"e": 649,
"s": 632,
"text": "Type Parameters:"
},
{
"code": null,
"e": 693,
"s": 649,
"text": "K – the type of keys maintained by this map"
},
{
"code": null,
"e": 723,
"s": 693,
"text": "V – the type of mapped values"
},
{
"code": null,
"e": 773,
"s": 723,
"text": "The parent interface of SortedMap is Map<K, V>. "
},
{
"code": null,
"e": 858,
"s": 773,
"text": "The subInterfaces of SortedMap are ConcurrentNavigableMap<K, V>, NavigableMap<K, V>."
},
{
"code": null,
"e": 918,
"s": 858,
"text": "SortedMap is implemented by ConcurrentSkipListMap, TreeMap."
},
{
"code": null,
"e": 931,
"s": 918,
"text": "Declaration:"
},
{
"code": null,
"e": 1159,
"s": 931,
"text": "public interface SortedMap<K, V> extends Map<K, V>\n{\n Comparator comparator();\n SortedMap subMap(K fromKey, K toKey);\n SortedMap headMap(K toKey);\n SortedMap tailMap(K fromKey);\n K firstKey();\n K lastKey();\n}\n"
},
{
"code": null,
"e": 1169,
"s": 1159,
"text": " Example:"
},
{
"code": null,
"e": 1174,
"s": 1169,
"text": "Java"
},
{
"code": "// Java code to demonstrate SortedMap Interfaceimport java.util.Iterator;import java.util.Map;import java.util.Set;import java.util.SortedMap;import java.util.TreeMap; public class SortedMapExample { public static void main(String[] args) { SortedMap<Integer, String> sm = new TreeMap<Integer, String>(); sm.put(new Integer(2), \"practice\"); sm.put(new Integer(3), \"quiz\"); sm.put(new Integer(5), \"code\"); sm.put(new Integer(4), \"contribute\"); sm.put(new Integer(1), \"geeksforgeeks\"); Set s = sm.entrySet(); // Using iterator in SortedMap Iterator i = s.iterator(); // Traversing map. Note that the traversal // produced sorted (by keys) output . while (i.hasNext()) { Map.Entry m = (Map.Entry)i.next(); int key = (Integer)m.getKey(); String value = (String)m.getValue(); System.out.println(\"Key : \" + key + \" value : \" + value); } }}",
"e": 2203,
"s": 1174,
"text": null
},
{
"code": null,
"e": 2215,
"s": 2205,
"text": "Output: "
},
{
"code": null,
"e": 2345,
"s": 2215,
"text": "Key : 1 value : geeksforgeeks\nKey : 2 value : practice\nKey : 3 value : quiz\nKey : 4 value : contribute\nKey : 5 value : code\n"
},
{
"code": null,
"e": 2372,
"s": 2345,
"text": "Creating SortedMap Objects"
},
{
"code": null,
"e": 2709,
"s": 2372,
"text": "Since SortedMap is an interface, objects cannot be created of the type SortedMap. We always need a class that extends this list in order to create an object. And also, after the introduction of Generics in Java 1.5, it is possible to restrict the type of object that can be stored in the SortedMap. This type-safe map can be defined as:"
},
{
"code": null,
"e": 2776,
"s": 2709,
"text": "// Obj1, Obj2 are the type of the object to be stored in SortedMap"
},
{
"code": null,
"e": 2832,
"s": 2776,
"text": "SortedMap<Obj1, Obj2> set = new TreeMap<Obj1, Obj2> ();"
},
{
"code": null,
"e": 3071,
"s": 2832,
"text": "Since SortedMap is an interface, it can be used only with a class that implements this interface. TreeMap is the class that implements the SortedMap interface. Now, let’s see how to perform a few frequently used operations on the TreeMap."
},
{
"code": null,
"e": 3314,
"s": 3071,
"text": "1. Adding Elements: In order to add an element to the SortedMap, we can use the put() method. However, the insertion order is not retained in the TreeMap. Internally, for every element, the keys are compared and sorted in the ascending order."
},
{
"code": null,
"e": 3319,
"s": 3314,
"text": "Java"
},
{
"code": "// Java program add the elements in the SortedMapimport java.io.*;import java.util.*;class GFG { // Main Method public static void main(String args[]) { // Default Initialization of a // SortedMap SortedMap tm1 = new TreeMap(); // Initialization of a SortedMap // using Generics SortedMap<Integer, String> tm2 = new TreeMap<Integer, String>(); // Inserting the Elements tm1.put(3, \"Geeks\"); tm1.put(2, \"For\"); tm1.put(1, \"Geeks\"); tm2.put(new Integer(3), \"Geeks\"); tm2.put(new Integer(2), \"For\"); tm2.put(new Integer(1), \"Geeks\"); System.out.println(tm1); System.out.println(tm2); }}",
"e": 4041,
"s": 3319,
"text": null
},
{
"code": null,
"e": 4049,
"s": 4041,
"text": "Output:"
},
{
"code": null,
"e": 4102,
"s": 4049,
"text": "{1=Geeks, 2=For, 3=Geeks}\n{1=Geeks, 2=For, 3=Geeks}\n"
},
{
"code": null,
"e": 4429,
"s": 4102,
"text": "2. Changing Elements: After adding the elements if we wish to change the element, it can be done by again adding the element with the put() method. Since the elements in the SortedMap are indexed using the keys, the value of the key can be changed by simply inserting the updated value for the key for which we wish to change."
},
{
"code": null,
"e": 4434,
"s": 4429,
"text": "Java"
},
{
"code": "// Java program to change// the elements in SortedMapimport java.io.*;import java.util.*;class GFG { // Main Method public static void main(String args[]) { // Initialization of a SortedMap // using Generics SortedMap<Integer, String> tm = new TreeMap<Integer, String>(); // Inserting the Elements tm.put(3, \"Geeks\"); tm.put(2, \"Geeks\"); tm.put(1, \"Geeks\"); System.out.println(tm); tm.put(2, \"For\"); System.out.println(tm); }}",
"e": 4968,
"s": 4434,
"text": null
},
{
"code": null,
"e": 4976,
"s": 4968,
"text": "Output:"
},
{
"code": null,
"e": 5030,
"s": 4976,
"text": "{1=Geeks, 2=Geeks, 3=Geeks}\n{1=Geeks, 2=For, 3=Geeks}"
},
{
"code": null,
"e": 5250,
"s": 5030,
"text": "3. Removing Element: In order to remove an element from the SortedMap, we can use the remove() method. This method takes the key value and removes the mapping for the key from this SortedMap if it is present in the map."
},
{
"code": null,
"e": 5255,
"s": 5250,
"text": "Java"
},
{
"code": "// Java program to remove the // elements from SortedMapimport java.io.*;import java.util.*; class GFG { // Main Method public static void main(String args[]) { // Initialization of a SortedMap // using Generics SortedMap<Integer, String> tm = new TreeMap<Integer, String>(); // Inserting the Elements tm.put(3, \"Geeks\"); tm.put(2, \"Geeks\"); tm.put(1, \"Geeks\"); tm.put(4, \"For\"); System.out.println(tm); tm.remove(4); System.out.println(tm); }}",
"e": 5815,
"s": 5255,
"text": null
},
{
"code": null,
"e": 5823,
"s": 5815,
"text": "Output:"
},
{
"code": null,
"e": 5886,
"s": 5823,
"text": "{1=Geeks, 2=Geeks, 3=Geeks, 4=For}\n{1=Geeks, 2=Geeks, 3=Geeks}"
},
{
"code": null,
"e": 6105,
"s": 5886,
"text": "4. Iterating through the SortedMap: There are multiple ways to iterate through the Map. The most famous way is to use an enhanced for loop and get the keys. The value of the key is found by using the getValue() method."
},
{
"code": null,
"e": 6110,
"s": 6105,
"text": "Java"
},
{
"code": "// Java program to iterate through SortedMapimport java.util.*; class GFG { // Main Method public static void main(String args[]) { // Initialization of a SortedMap // using Generics SortedMap<Integer, String> tm = new TreeMap<Integer, String>(); // Inserting the Elements tm.put(3, \"Geeks\"); tm.put(2, \"For\"); tm.put(1, \"Geeks\"); for (Map.Entry mapElement : tm.entrySet()) { int key = (int)mapElement.getKey(); // Finding the value String value = (String)mapElement.getValue(); System.out.println(key + \" : \" + value); } }}",
"e": 6780,
"s": 6110,
"text": null
},
{
"code": null,
"e": 6788,
"s": 6780,
"text": "Output:"
},
{
"code": null,
"e": 6816,
"s": 6788,
"text": "1 : Geeks\n2 : For\n3 : Geeks"
},
{
"code": null,
"e": 6879,
"s": 6816,
"text": "The class which implements the SortedMap interface is TreeMap."
},
{
"code": null,
"e": 7339,
"s": 6879,
"text": "TreeMap class which is implemented in the collections framework is an implementation of the SortedMap Interface and SortedMap extends Map Interface. It behaves like a simple map with the exception that it stores keys in a sorted format. TreeMap uses a tree data structure for storage. Objects are stored in sorted, ascending order. But we can also store in descending order by passing a comparator. Let’s see how to create a SortedMap object using this class."
},
{
"code": null,
"e": 7344,
"s": 7339,
"text": "Java"
},
{
"code": "// Java program to demonstrate the// creation of SortedMap object using// the TreeMap class import java.util.*; class GFG { public static void main(String[] args) { SortedMap<String, String> tm = new TreeMap<String, String>(new Comparator<String>() { public int compare(String a, String b) { return b.compareTo(a); } }); // Adding elements into the TreeMap // using put() tm.put(\"India\", \"1\"); tm.put(\"Australia\", \"2\"); tm.put(\"South Africa\", \"3\"); // Displaying the TreeMap System.out.println(tm); // Removing items from TreeMap // using remove() tm.remove(\"Australia\"); System.out.println(\"Map after removing \" + \"Australia:\" + tm); }}",
"e": 8207,
"s": 7344,
"text": null
},
{
"code": null,
"e": 8215,
"s": 8207,
"text": "Output:"
},
{
"code": null,
"e": 8309,
"s": 8215,
"text": "{South Africa=3, India=1, Australia=2}\nMap after removing Australia:{South Africa=3, India=1}"
},
{
"code": null,
"e": 8400,
"s": 8309,
"text": "This method is used to check whether a particular key is being mapped into the Map or not."
},
{
"code": null,
"e": 8496,
"s": 8400,
"text": " It takes the key element as a parameter and returns True if that element is mapped in the map."
},
{
"code": null,
"e": 8614,
"s": 8496,
"text": "This method is used to check whether a particular value is being mapped by a single or more than one key in the Map. "
},
{
"code": null,
"e": 8719,
"s": 8614,
"text": "It takes the value as a parameter and returns True if that value is mapped by any of the key in the map."
},
{
"code": null,
"e": 8910,
"s": 8719,
"text": "This method is used to create a set out of the same elements contained in the map. It basically returns a set view of the map or we can create a new set and store the map elements into them."
},
{
"code": null,
"e": 9081,
"s": 8910,
"text": "This method is used to check for equality between two maps. It verifies whether the elements of one map passed as a parameter is equal to the elements of this map or not."
},
{
"code": null,
"e": 9254,
"s": 9081,
"text": "This method is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key."
},
{
"code": null,
"e": 9424,
"s": 9254,
"text": "This method is used to return a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa."
},
{
"code": null,
"e": 9566,
"s": 9424,
"text": "This method is used to create a collection out of the values of the map. It basically returns a Collection view of the values in the HashMap."
},
{
"code": null,
"e": 9993,
"s": 9566,
"text": "This article is contributed by Pratik Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 10009,
"s": 9993,
"text": "1rajarshimondal"
},
{
"code": null,
"e": 10033,
"s": 10009,
"text": "Ganeshchowdharysadanala"
},
{
"code": null,
"e": 10053,
"s": 10033,
"text": "Java - util package"
},
{
"code": null,
"e": 10070,
"s": 10053,
"text": "Java-Collections"
},
{
"code": null,
"e": 10079,
"s": 10070,
"text": "java-map"
},
{
"code": null,
"e": 10094,
"s": 10079,
"text": "Java-SortedMap"
},
{
"code": null,
"e": 10099,
"s": 10094,
"text": "Java"
},
{
"code": null,
"e": 10104,
"s": 10099,
"text": "Java"
},
{
"code": null,
"e": 10121,
"s": 10104,
"text": "Java-Collections"
},
{
"code": null,
"e": 10219,
"s": 10121,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10263,
"s": 10219,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 10299,
"s": 10263,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 10324,
"s": 10299,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 10355,
"s": 10324,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 10370,
"s": 10355,
"text": "Stream In Java"
},
{
"code": null,
"e": 10398,
"s": 10370,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 10422,
"s": 10398,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 10454,
"s": 10422,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 10471,
"s": 10454,
"text": "Generics in Java"
}
] |
Matplotlib.axes.Axes.text() in Python
|
13 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.text() function in axes module of matplotlib library is also used to add the text s to the axes at location x, y in data coordinates.
Syntax:
Axes.text(self, x, y, s, fontdict=None, withdash=, **kwargs)
Parameters: This method accept the following parameters that are described below:
s: This parameter is the text to be add.
xy: This parameter is the point (x, y) where text is to be placed.
fontdict: This parameter is an optional parameter and a dictionary to override the default text properties.
withdash: This parameter is also an optional parameter and creates a TextWithDash instance instead of a Text instance.
Returns: This method returns the text which is a created text instance..
Below examples illustrate the matplotlib.axes.Axes.text() function in matplotlib.axes:
Example-1:
# Implementation of matplotlib functionimport matplotlib.pyplot as plt fig, ax = plt.subplots()ax.text(3, 4, 'GeeksforGeeks', style ='italic', fontsize = 30, color ="green") ax.set(xlim =(0, 8), ylim =(0, 8))ax.set_title('matplotlib.axes.Axes.text() Example', fontsize = 14, fontweight ='bold') plt.show()
Output:
Example-2:
# Implementation of matplotlib functionimport matplotlib.pyplot as plt fig, ax = plt.subplots()ax.set_xlabel('xlabel')ax.set_ylabel('ylabel') ax.text(3, 8, 'GeeksforGeeks', style ='italic', fontsize = 30, bbox ={'facecolor':'green', 'alpha':0.6, 'pad':20}) ax.text(3.5, 6, 'Python matplotlib Module', fontsize = 15) ax.text(3.5, 3, 'Axes Class - Text Function') ax.text(0, 0, 'by-Shubham Singh', verticalalignment ='bottom', horizontalalignment ='left', transform = ax.transAxes, color ='green', fontsize = 5) ax.set(xlim =(0, 10), ylim =(0, 10))ax.set_title('matplotlib.axes.Axes.text() Example', fontsize = 14, fontweight ='bold')plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Apr, 2020"
},
{
"code": null,
"e": 328,
"s": 28,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute."
},
{
"code": null,
"e": 471,
"s": 328,
"text": "The Axes.text() function in axes module of matplotlib library is also used to add the text s to the axes at location x, y in data coordinates."
},
{
"code": null,
"e": 479,
"s": 471,
"text": "Syntax:"
},
{
"code": null,
"e": 541,
"s": 479,
"text": "Axes.text(self, x, y, s, fontdict=None, withdash=, **kwargs)\n"
},
{
"code": null,
"e": 623,
"s": 541,
"text": "Parameters: This method accept the following parameters that are described below:"
},
{
"code": null,
"e": 664,
"s": 623,
"text": "s: This parameter is the text to be add."
},
{
"code": null,
"e": 731,
"s": 664,
"text": "xy: This parameter is the point (x, y) where text is to be placed."
},
{
"code": null,
"e": 839,
"s": 731,
"text": "fontdict: This parameter is an optional parameter and a dictionary to override the default text properties."
},
{
"code": null,
"e": 958,
"s": 839,
"text": "withdash: This parameter is also an optional parameter and creates a TextWithDash instance instead of a Text instance."
},
{
"code": null,
"e": 1031,
"s": 958,
"text": "Returns: This method returns the text which is a created text instance.."
},
{
"code": null,
"e": 1118,
"s": 1031,
"text": "Below examples illustrate the matplotlib.axes.Axes.text() function in matplotlib.axes:"
},
{
"code": null,
"e": 1129,
"s": 1118,
"text": "Example-1:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlib.pyplot as plt fig, ax = plt.subplots()ax.text(3, 4, 'GeeksforGeeks', style ='italic', fontsize = 30, color =\"green\") ax.set(xlim =(0, 8), ylim =(0, 8))ax.set_title('matplotlib.axes.Axes.text() Example', fontsize = 14, fontweight ='bold') plt.show()",
"e": 1457,
"s": 1129,
"text": null
},
{
"code": null,
"e": 1465,
"s": 1457,
"text": "Output:"
},
{
"code": null,
"e": 1476,
"s": 1465,
"text": "Example-2:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlib.pyplot as plt fig, ax = plt.subplots()ax.set_xlabel('xlabel')ax.set_ylabel('ylabel') ax.text(3, 8, 'GeeksforGeeks', style ='italic', fontsize = 30, bbox ={'facecolor':'green', 'alpha':0.6, 'pad':20}) ax.text(3.5, 6, 'Python matplotlib Module', fontsize = 15) ax.text(3.5, 3, 'Axes Class - Text Function') ax.text(0, 0, 'by-Shubham Singh', verticalalignment ='bottom', horizontalalignment ='left', transform = ax.transAxes, color ='green', fontsize = 5) ax.set(xlim =(0, 10), ylim =(0, 10))ax.set_title('matplotlib.axes.Axes.text() Example', fontsize = 14, fontweight ='bold')plt.show()",
"e": 2212,
"s": 1476,
"text": null
},
{
"code": null,
"e": 2220,
"s": 2212,
"text": "Output:"
},
{
"code": null,
"e": 2238,
"s": 2220,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 2245,
"s": 2238,
"text": "Python"
}
] |
How to use Glob() function to find files recursively in Python?
|
To use Glob() to find files recursively, you need Python 3.5+. The glob module supports the "**" directive(which is parsed only if you pass recursive flag) which tells python to look recursively in the directories.
import glob
for filename in glob.iglob('src/**/*', recursive=True):
print(filename)
You can check the filename using whatever condition you want using an if statement. For older Python versions, you can use os.walk to recursively walk the directory and search the files.
import os, re, os.path
pattern = "^your_regex_here$"
mypath = "my_folder"
for root, dirs, files in os.walk(mypath):
for file in filter(lambda x: re.match(pattern, x), files):
print(file)
This will match the file name to the regex you specify and print their names.
|
[
{
"code": null,
"e": 1403,
"s": 1187,
"text": "To use Glob() to find files recursively, you need Python 3.5+. The glob module supports the \"**\" directive(which is parsed only if you pass recursive flag) which tells python to look recursively in the directories. "
},
{
"code": null,
"e": 1491,
"s": 1403,
"text": "import glob\nfor filename in glob.iglob('src/**/*', recursive=True):\n print(filename)"
},
{
"code": null,
"e": 1679,
"s": 1491,
"text": "You can check the filename using whatever condition you want using an if statement. For older Python versions, you can use os.walk to recursively walk the directory and search the files. "
},
{
"code": null,
"e": 1878,
"s": 1679,
"text": "import os, re, os.path\npattern = \"^your_regex_here$\"\nmypath = \"my_folder\"\nfor root, dirs, files in os.walk(mypath):\n for file in filter(lambda x: re.match(pattern, x), files):\n print(file)"
},
{
"code": null,
"e": 1956,
"s": 1878,
"text": "This will match the file name to the regex you specify and print their names."
}
] |
Docker – LABEL Instruction
|
28 Oct, 2020
Labels are used in Dockerfile to help organize your Docker Images. Labels are key-value pairs and simply adds custom metadata to your Docker Images. Some key points associated with the LABEL instructions are as follows:
To include spaces inside a label, you can use quotes.
For multi line labels, you can use backslashes.
You can use more than one labels in a Docker Image.
Docker allows you to specify multiple labels in a single line.
Labels from parent Images are inherited to your Image.
If labels with same names exist even though they have different values, the last one overrides.
General syntax of LABEL instruction is as follows:
Syntax: LABEL <key-string>=<value-string> <key-string>=<value-string> ...
In this article, we will look at different ways to use Label instruction through a simple example. To do so follow the below steps:
Look at the template for the Dockerfile below:
FROM ubuntu:latest
LABEL "website.name"="geeksforgeeks website"
LABEL "website.tutorial-name"="docker"
LABEL website="geeksforgeeks"
LABEL desc="This is docker tutorial with \
geeksforgeeks website"
LABEL tutorial1="Docker" tutorial2="LABEL INSTRUCTION"
In the above Dockerfile, we have shown different ways to use LABEL instruction.
sudo docker build -t label-demo .
sudo docker run -it label-demo bash
To check the labels of a particular Image, you can use the Docker Inspect command.
Start the Docker Container.
sudo docker start <container-id>
Execute the Inspect Command.
sudo docker inspect <container-id>
Inside the LABELS object, you can find all the labels associated with the image that you have specified inside your Dockerfile.
To conclude, in this article, we discussed how to use the LABEL instruction in your Dockerfile and create your Image. We also saw the different ways using which you can specify the LABEL Instruction. Finally, we built and ran the Docker Image and Inspected the Container.
Docker Container
linux
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Oct, 2020"
},
{
"code": null,
"e": 248,
"s": 28,
"text": "Labels are used in Dockerfile to help organize your Docker Images. Labels are key-value pairs and simply adds custom metadata to your Docker Images. Some key points associated with the LABEL instructions are as follows:"
},
{
"code": null,
"e": 302,
"s": 248,
"text": "To include spaces inside a label, you can use quotes."
},
{
"code": null,
"e": 350,
"s": 302,
"text": "For multi line labels, you can use backslashes."
},
{
"code": null,
"e": 402,
"s": 350,
"text": "You can use more than one labels in a Docker Image."
},
{
"code": null,
"e": 465,
"s": 402,
"text": "Docker allows you to specify multiple labels in a single line."
},
{
"code": null,
"e": 520,
"s": 465,
"text": "Labels from parent Images are inherited to your Image."
},
{
"code": null,
"e": 616,
"s": 520,
"text": "If labels with same names exist even though they have different values, the last one overrides."
},
{
"code": null,
"e": 667,
"s": 616,
"text": "General syntax of LABEL instruction is as follows:"
},
{
"code": null,
"e": 742,
"s": 667,
"text": "Syntax: LABEL <key-string>=<value-string> <key-string>=<value-string> ...\n"
},
{
"code": null,
"e": 874,
"s": 742,
"text": "In this article, we will look at different ways to use Label instruction through a simple example. To do so follow the below steps:"
},
{
"code": null,
"e": 921,
"s": 874,
"text": "Look at the template for the Dockerfile below:"
},
{
"code": null,
"e": 1176,
"s": 921,
"text": "FROM ubuntu:latest\nLABEL \"website.name\"=\"geeksforgeeks website\"\nLABEL \"website.tutorial-name\"=\"docker\"\nLABEL website=\"geeksforgeeks\"\nLABEL desc=\"This is docker tutorial with \\\ngeeksforgeeks website\"\nLABEL tutorial1=\"Docker\" tutorial2=\"LABEL INSTRUCTION\"\n"
},
{
"code": null,
"e": 1256,
"s": 1176,
"text": "In the above Dockerfile, we have shown different ways to use LABEL instruction."
},
{
"code": null,
"e": 1291,
"s": 1256,
"text": "sudo docker build -t label-demo .\n"
},
{
"code": null,
"e": 1328,
"s": 1291,
"text": "sudo docker run -it label-demo bash\n"
},
{
"code": null,
"e": 1411,
"s": 1328,
"text": "To check the labels of a particular Image, you can use the Docker Inspect command."
},
{
"code": null,
"e": 1439,
"s": 1411,
"text": "Start the Docker Container."
},
{
"code": null,
"e": 1473,
"s": 1439,
"text": "sudo docker start <container-id>\n"
},
{
"code": null,
"e": 1502,
"s": 1473,
"text": "Execute the Inspect Command."
},
{
"code": null,
"e": 1538,
"s": 1502,
"text": "sudo docker inspect <container-id>\n"
},
{
"code": null,
"e": 1666,
"s": 1538,
"text": "Inside the LABELS object, you can find all the labels associated with the image that you have specified inside your Dockerfile."
},
{
"code": null,
"e": 1938,
"s": 1666,
"text": "To conclude, in this article, we discussed how to use the LABEL instruction in your Dockerfile and create your Image. We also saw the different ways using which you can specify the LABEL Instruction. Finally, we built and ran the Docker Image and Inspected the Container."
},
{
"code": null,
"e": 1955,
"s": 1938,
"text": "Docker Container"
},
{
"code": null,
"e": 1961,
"s": 1955,
"text": "linux"
},
{
"code": null,
"e": 1987,
"s": 1961,
"text": "Advanced Computer Subject"
}
] |
Sort an array of strings based on count of distinct characters
|
18 Dec, 2020
Given a string array arr[] as input, the task is to print the words sorted by number of distinct characters that occur in the word, followed by length of word.
Note:
If two words have same number of distinct characters, the word with more total characters comes first.
If two words have same number of distinct characters and same length, the word that occurs earlier in the sentence must be printed first.
Examples:
Input: arr[] = {“Bananas”, “do”, “not”, “grow”, “in”, “Mississippi”}Output: do in not Mississippi Bananas growExplanation:After sorting by the number of unique characters and the length the output will be, do in not Mississippi Bananas grow.
Input: arr[] = {“thank”, “you”, “geeks”, “world”}Output: you geeks thank world Explanation:After sorting by the number of unique characters and the length the output will be, you geeks thank world.
Approach: The idea is to use Sorting.
Initialize a map data structure to count all the possible distinct characters from each string of the given array.
Then sort the array by passing the comparator function, where sorting is done by the number of unique character in word and length of word.
After sorting is done, print the strings of the array.
For example s = “Bananas do not grow in Mississippi”
Word Number of unique character Length of Word
do 2 2
in 2 2
not 3 3
Bananas 4 7
grow 4 4
Mississippi 4 11
Below is the implementation of the above approach:
C++
Java
Python3
C#
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to return no of// unique character in a wordint countDistinct(string s){ // Initialize map unordered_map<char, int> m; for (int i = 0; i < s.length(); i++) { // Count distinct characters m[s[i]]++; } return m.size();} // Function to perform sortingbool compare(string& s1, string& s2){ if (countDistinct(s1) == countDistinct(s2)) { // Check if size of string 1 // is same as string 2 then // return false because s1 should // not be placed before s2 if (s1.size() == s2.size()) { return false; } return s1.size() > s2.size(); } return countDistinct(s1) < countDistinct(s2);} // Function to print the sorted array of stringvoid printArraystring(string str[], int n){ for (int i = 0; i < n; i++) cout << str[i] << " ";} // Driver Codeint main(){ string arr[] = { "Bananas", "do", "not", "grow", "in", "Mississippi" }; int n = sizeof(arr) / sizeof(arr[0]); // Function call sort(arr, arr + n, compare); // Print result printArraystring(arr, n); return 0;}
// Java program for the above approachimport java.util.*; class GFG{ // Function to return no of// unique character in a wordstatic int countDistinct(String s){ // Initialize map Map<Character, Integer> m = new HashMap<>(); for(int i = 0; i < s.length(); i++) { // Count distinct characters if (m.containsKey(s.charAt(i))) { m.put(s.charAt(i), m.get(s.charAt(i)) + 1); } else { m.put(s.charAt(i), 1); } } return m.size();} // Function to print the sorted// array of stringstatic void printArraystring(String[] str, int n){ for(int i = 0; i < n; i++) { System.out.print(str[i] + " "); }} // Driver codepublic static void main(String[] args){ String[] arr = { "Bananas", "do", "not", "grow", "in", "Mississippi" }; int n = arr.length; // Function call Arrays.sort(arr, new Comparator<String>() { public int compare(String a, String b) { if (countDistinct(a) == countDistinct(b)) { // Check if size of string 1 // is same as string 2 then // return false because s1 should // not be placed before s2 return (b.length() - a.length()); } else { return (countDistinct(a) - countDistinct(b)); } } }); // Print result printArraystring(arr, n);}} // This code is contributed by offbeat
# Python3 program of the above approachimport functools # Function to return no of# unique character in a worddef countDistinct(s): # Initialize dictionary m = {} for i in range(len(s)): # Count distinct characters if s[i] not in m: m[s[i]] = 1 else: m[s[i]] += 1 return len(m) # Function to perform sortingdef compare(a, b): if (countDistinct(a) == countDistinct(b)): # Check if size of string 1 # is same as string 2 then # return false because s1 should # not be placed before s2 return (len(b) - len(a)) else: return (countDistinct(a) - countDistinct(b)) # Driver Codearr = [ "Bananas", "do", "not", "grow", "in","Mississippi" ] n = len(arr) # Print resultprint(*sorted( arr, key = functools.cmp_to_key(compare)), sep = ' ') # This code is contributed by avanitrachhadiya2155
// C# program of the above approachusing System;using System.Collections;using System.Collections.Generic; class GFG{ // Function to return no of// unique character in a wordstatic int countDistinct(string s){ // Initialize map Dictionary<char, int> m = new Dictionary<char, int>(); for(int i = 0; i < s.Length; i++) { // Count distinct characters if (m.ContainsKey(s[i])) { m[s[i]]++; } else { m[s[i]] = 1; } } return m.Count;} static int compare(string s1, string s2){ if (countDistinct(s1) == countDistinct(s2)) { // Check if size of string 1 // is same as string 2 then // return false because s1 should // not be placed before s2 return s2.Length - s1.Length; } else { return (countDistinct(s1) - countDistinct(s2)); }} // Function to print the sorted array of stringstatic void printArraystring(string []str, int n){ for(int i = 0; i < n; i++) { Console.Write(str[i] + " "); }} // Driver Codepublic static void Main(string[] args){ string []arr = { "Bananas", "do", "not", "grow", "in", "Mississippi" }; int n = arr.Length; // Function call Array.Sort(arr, compare); // Print result printArraystring(arr, n);}} // This code is contributed by rutvik_56
do in not Mississippi Bananas grow
Time Complexity: O(n * log n)
Auxiliary Space: O(n)
rutvik_56
offbeat
avanitrachhadiya2155
Arrays
Sorting
Strings
Arrays
Strings
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count of subarrays with average K
Introduction to Data Structures
Window Sliding Technique
Find subarray with given sum | Set 1 (Nonnegative Numbers)
Next Greater Element
Merge Sort
Bubble Sort Algorithm
QuickSort
Insertion Sort
Selection Sort Algorithm
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n18 Dec, 2020"
},
{
"code": null,
"e": 213,
"s": 52,
"text": "Given a string array arr[] as input, the task is to print the words sorted by number of distinct characters that occur in the word, followed by length of word. "
},
{
"code": null,
"e": 220,
"s": 213,
"text": "Note: "
},
{
"code": null,
"e": 324,
"s": 220,
"text": "If two words have same number of distinct characters, the word with more total characters comes first. "
},
{
"code": null,
"e": 462,
"s": 324,
"text": "If two words have same number of distinct characters and same length, the word that occurs earlier in the sentence must be printed first."
},
{
"code": null,
"e": 472,
"s": 462,
"text": "Examples:"
},
{
"code": null,
"e": 714,
"s": 472,
"text": "Input: arr[] = {“Bananas”, “do”, “not”, “grow”, “in”, “Mississippi”}Output: do in not Mississippi Bananas growExplanation:After sorting by the number of unique characters and the length the output will be, do in not Mississippi Bananas grow."
},
{
"code": null,
"e": 912,
"s": 714,
"text": "Input: arr[] = {“thank”, “you”, “geeks”, “world”}Output: you geeks thank world Explanation:After sorting by the number of unique characters and the length the output will be, you geeks thank world."
},
{
"code": null,
"e": 951,
"s": 912,
"text": "Approach: The idea is to use Sorting. "
},
{
"code": null,
"e": 1066,
"s": 951,
"text": "Initialize a map data structure to count all the possible distinct characters from each string of the given array."
},
{
"code": null,
"e": 1206,
"s": 1066,
"text": "Then sort the array by passing the comparator function, where sorting is done by the number of unique character in word and length of word."
},
{
"code": null,
"e": 1261,
"s": 1206,
"text": "After sorting is done, print the strings of the array."
},
{
"code": null,
"e": 1314,
"s": 1261,
"text": "For example s = “Bananas do not grow in Mississippi”"
},
{
"code": null,
"e": 1389,
"s": 1314,
"text": "Word Number of unique character Length of Word"
},
{
"code": null,
"e": 1479,
"s": 1389,
"text": "do 2 2"
},
{
"code": null,
"e": 1570,
"s": 1479,
"text": " in 2 2"
},
{
"code": null,
"e": 1659,
"s": 1570,
"text": " not 3 3"
},
{
"code": null,
"e": 1742,
"s": 1659,
"text": " Bananas 4 7"
},
{
"code": null,
"e": 1827,
"s": 1742,
"text": " grow 4 4"
},
{
"code": null,
"e": 1909,
"s": 1827,
"text": " Mississippi 4 11"
},
{
"code": null,
"e": 1960,
"s": 1909,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1964,
"s": 1960,
"text": "C++"
},
{
"code": null,
"e": 1969,
"s": 1964,
"text": "Java"
},
{
"code": null,
"e": 1977,
"s": 1969,
"text": "Python3"
},
{
"code": null,
"e": 1980,
"s": 1977,
"text": "C#"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to return no of// unique character in a wordint countDistinct(string s){ // Initialize map unordered_map<char, int> m; for (int i = 0; i < s.length(); i++) { // Count distinct characters m[s[i]]++; } return m.size();} // Function to perform sortingbool compare(string& s1, string& s2){ if (countDistinct(s1) == countDistinct(s2)) { // Check if size of string 1 // is same as string 2 then // return false because s1 should // not be placed before s2 if (s1.size() == s2.size()) { return false; } return s1.size() > s2.size(); } return countDistinct(s1) < countDistinct(s2);} // Function to print the sorted array of stringvoid printArraystring(string str[], int n){ for (int i = 0; i < n; i++) cout << str[i] << \" \";} // Driver Codeint main(){ string arr[] = { \"Bananas\", \"do\", \"not\", \"grow\", \"in\", \"Mississippi\" }; int n = sizeof(arr) / sizeof(arr[0]); // Function call sort(arr, arr + n, compare); // Print result printArraystring(arr, n); return 0;}",
"e": 3212,
"s": 1980,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*; class GFG{ // Function to return no of// unique character in a wordstatic int countDistinct(String s){ // Initialize map Map<Character, Integer> m = new HashMap<>(); for(int i = 0; i < s.length(); i++) { // Count distinct characters if (m.containsKey(s.charAt(i))) { m.put(s.charAt(i), m.get(s.charAt(i)) + 1); } else { m.put(s.charAt(i), 1); } } return m.size();} // Function to print the sorted// array of stringstatic void printArraystring(String[] str, int n){ for(int i = 0; i < n; i++) { System.out.print(str[i] + \" \"); }} // Driver codepublic static void main(String[] args){ String[] arr = { \"Bananas\", \"do\", \"not\", \"grow\", \"in\", \"Mississippi\" }; int n = arr.length; // Function call Arrays.sort(arr, new Comparator<String>() { public int compare(String a, String b) { if (countDistinct(a) == countDistinct(b)) { // Check if size of string 1 // is same as string 2 then // return false because s1 should // not be placed before s2 return (b.length() - a.length()); } else { return (countDistinct(a) - countDistinct(b)); } } }); // Print result printArraystring(arr, n);}} // This code is contributed by offbeat",
"e": 4850,
"s": 3212,
"text": null
},
{
"code": "# Python3 program of the above approachimport functools # Function to return no of# unique character in a worddef countDistinct(s): # Initialize dictionary m = {} for i in range(len(s)): # Count distinct characters if s[i] not in m: m[s[i]] = 1 else: m[s[i]] += 1 return len(m) # Function to perform sortingdef compare(a, b): if (countDistinct(a) == countDistinct(b)): # Check if size of string 1 # is same as string 2 then # return false because s1 should # not be placed before s2 return (len(b) - len(a)) else: return (countDistinct(a) - countDistinct(b)) # Driver Codearr = [ \"Bananas\", \"do\", \"not\", \"grow\", \"in\",\"Mississippi\" ] n = len(arr) # Print resultprint(*sorted( arr, key = functools.cmp_to_key(compare)), sep = ' ') # This code is contributed by avanitrachhadiya2155",
"e": 5761,
"s": 4850,
"text": null
},
{
"code": "// C# program of the above approachusing System;using System.Collections;using System.Collections.Generic; class GFG{ // Function to return no of// unique character in a wordstatic int countDistinct(string s){ // Initialize map Dictionary<char, int> m = new Dictionary<char, int>(); for(int i = 0; i < s.Length; i++) { // Count distinct characters if (m.ContainsKey(s[i])) { m[s[i]]++; } else { m[s[i]] = 1; } } return m.Count;} static int compare(string s1, string s2){ if (countDistinct(s1) == countDistinct(s2)) { // Check if size of string 1 // is same as string 2 then // return false because s1 should // not be placed before s2 return s2.Length - s1.Length; } else { return (countDistinct(s1) - countDistinct(s2)); }} // Function to print the sorted array of stringstatic void printArraystring(string []str, int n){ for(int i = 0; i < n; i++) { Console.Write(str[i] + \" \"); }} // Driver Codepublic static void Main(string[] args){ string []arr = { \"Bananas\", \"do\", \"not\", \"grow\", \"in\", \"Mississippi\" }; int n = arr.Length; // Function call Array.Sort(arr, compare); // Print result printArraystring(arr, n);}} // This code is contributed by rutvik_56",
"e": 7243,
"s": 5761,
"text": null
},
{
"code": null,
"e": 7278,
"s": 7243,
"text": "do in not Mississippi Bananas grow"
},
{
"code": null,
"e": 7310,
"s": 7280,
"text": "Time Complexity: O(n * log n)"
},
{
"code": null,
"e": 7332,
"s": 7310,
"text": "Auxiliary Space: O(n)"
},
{
"code": null,
"e": 7342,
"s": 7332,
"text": "rutvik_56"
},
{
"code": null,
"e": 7350,
"s": 7342,
"text": "offbeat"
},
{
"code": null,
"e": 7371,
"s": 7350,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 7378,
"s": 7371,
"text": "Arrays"
},
{
"code": null,
"e": 7386,
"s": 7378,
"text": "Sorting"
},
{
"code": null,
"e": 7394,
"s": 7386,
"text": "Strings"
},
{
"code": null,
"e": 7401,
"s": 7394,
"text": "Arrays"
},
{
"code": null,
"e": 7409,
"s": 7401,
"text": "Strings"
},
{
"code": null,
"e": 7417,
"s": 7409,
"text": "Sorting"
},
{
"code": null,
"e": 7515,
"s": 7417,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7549,
"s": 7515,
"text": "Count of subarrays with average K"
},
{
"code": null,
"e": 7581,
"s": 7549,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 7606,
"s": 7581,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 7665,
"s": 7606,
"text": "Find subarray with given sum | Set 1 (Nonnegative Numbers)"
},
{
"code": null,
"e": 7686,
"s": 7665,
"text": "Next Greater Element"
},
{
"code": null,
"e": 7697,
"s": 7686,
"text": "Merge Sort"
},
{
"code": null,
"e": 7719,
"s": 7697,
"text": "Bubble Sort Algorithm"
},
{
"code": null,
"e": 7729,
"s": 7719,
"text": "QuickSort"
},
{
"code": null,
"e": 7744,
"s": 7729,
"text": "Insertion Sort"
}
] |
How to create responsive stacked cards hover effect using CSS ?
|
25 Aug, 2021
Introduction: Cards are a very important part of any website. It is used to display some important information in short to viewers. In this article, we will create responsive stackend cards hover effect using HTML and CSS. In order to achieve a multi-layer stacking effect, you have to follow certain steps which are given below.
Note: Through hover on cards, we can achieve various directions or effects on cards like top-left, bottom-right, diagonal, rotate, etc.
Approach: First, we will design a simple card structure in HTM. Now we will use some CSS properties to build the basic design of the card and to create a stack effect, we will define the ::before and ::after pseudo-elements and absolutely position them relative to the parent card. Now we will have to move the div with class “card-inner” away from its original position by using the transform property. Finally, added a hover effect on a stack of cards by using a transform that can translate the card before and after the hover effect.
Let’s see the implementation of the above approach.
Example 1: In this example, we will see when the user will hover over the card Top Card will translate over X-axis and Y-axis, here (5px-X-axis, 5px-Y-axis) bottom-right direction and below stacked card will translate (-X)-axis and (-Y)-axis i.e opposite to bottom-right direction which will create multiple stacked-bottom-right effects will the help of before and after Pseudo element.
HTML
<!DOCTYPE html><html> <head> <title> stackened cards hover effect </title> <style> body { color: #FDFAF6; background: #50CB93; } .card { position: relative; width: 400px; margin: 60px auto; } .card::before, .card::after { content: ""; position: absolute; top: 0; left: 0; width: 100%; height: 100%; } .card::before, .card::after, .card .card-inner { background-color: #423F3E; border: 1px solid #01937C; transition: transform 0.5s; } .card::before, .card-inner { z-index: 1; } .card-inner { position: relative; padding: 4rem; } /* Position the stacked cards in different position */ .cards:hover { transform: translate(5px, 5px); } .cards:hover::before { transform: translate(-5px, -5px); } .cards:hover::after { transform: translate(-10px, -10px); } </style></head> <body> <center> <h1>Welcome to GeeksforGeeks</h1> <div class="card-container"> <div class="card cards"> <div class="card-inner"> <h1>Down-Right</h1> <h3 class="card-title"> GeeksforGeeks </h3> <div class="card-body"> A Complete Portal for Geeks. </div> </div> </div> </div> </center></body> </html>
Output:
Example 2: In this example, we will see stacked-diagonal-left and stacked-rotate-left using the same approach as explained above.
Stacked-Rotate-left:
Top Card will translate only over X-axis , here ( translate(2.5px, 0) ) left direction, and rotate at certain angle, here its 2.5 degree ( rotate(2.5deg) ) .thenBelow stacked card will also translate and rotate in the same direction but with double pixel to create a stacked multi-layer effect with the help of before and after Pseudo element.
Top Card will translate only over X-axis , here ( translate(2.5px, 0) ) left direction, and rotate at certain angle, here its 2.5 degree ( rotate(2.5deg) ) .then
Below stacked card will also translate and rotate in the same direction but with double pixel to create a stacked multi-layer effect with the help of before and after Pseudo element.
Stacked-diagonal-left:
In diagonal-left, Initially multi-layer stack card is positioned in opposite direction to the directional-left ( translate(-16px, -16px) ) using transform:translate property and thenWhen the user hovers over the card, stacked multi-layer card will translate to diagonal-left direction using same value i.e ( translate(16px, 16px) ) but opposite sign so that stacked multi-layer cards can cover equal direction.
In diagonal-left, Initially multi-layer stack card is positioned in opposite direction to the directional-left ( translate(-16px, -16px) ) using transform:translate property and then
When the user hovers over the card, stacked multi-layer card will translate to diagonal-left direction using same value i.e ( translate(16px, 16px) ) but opposite sign so that stacked multi-layer cards can cover equal direction.
HTML
<!DOCTYPE html><html> <head> <style> body { color: #FDFAF6; background: #50CB93; } :root { --offset-before: 8px; --offset-after: 16px; } .card { position: relative; width: 400px; margin: 60px auto; } .card::before, .card::after { content: ""; position: absolute; top: 0; left: 0; width: 100%; height: 100%; } .card::before, .card::after, .card .card-inner { background-color: #423F3E; border: 1px solid #01937C; transition: transform 0.5s; } .card::before, .card-inner { z-index: 1; } .card-inner { position: relative; padding: 4rem; } /*Diagonal => Left*/ .cards-diagonal::before { transform: translate(calc(-1 * 8px), calc(-1 * 8px)); } .cards-diagonal::after { transform: translate(calc(-1 * 16px), calc(-1 * 16px)); } .cards-diagonal:hover::before { transform: translate(8px, 8px); } .cards-diagonal:hover::after { transform: translate(16px, 16px); } /*Rotate => Left */ .cards-rotate::before, .cards-rotate::after { transform-origin: 50% 100%; } .cards-rotate:hover { transform: translate(2.5px, 0) rotate(2.5deg); } .cards-rotate:hover::before { transform: translate(2.5px, 0) rotate(2.5deg); } .cards-rotate:hover::after { transform: translate(5px, 0) rotate(5deg); } } </style></head> <body> <center> <h1>Welcome to GeeksforGeeks</h1> <div class="card-container"> <div class="card cards-diagonal"> <div class="card-inner"> <h1>Diagonal-Left</h1> <h3 class="card-title">GeeksforGeeks</h3> <div class="card-body"> A Complete Portal for Geeks. </div> </div> </div> </div> <div class="card-container"> <div class="card cards-rotate"> <div class="card-inner"> <h1>Rotate-Left</h1> <h3 class="card-title">GeeksforGeeks</h3> <div class="card-body"> A Complete Portal for Geeks. </div> </div> </div> </div> </center></body> </html>
Output:
Example 3: In this example, we will see stacked-Up and stacked-Right effects using the same approach as explained above.
Stacked-Up:
Top Card will translate only in negative Y-axis , here (translate(0, -5px)) Up direction, thenbelow stacked card will translate positive Y-axis i.e opposite to Up direction and it will also scale along Y-axis which will create multiple stacked-Up effects with the help of before and after Pseudo element.
Top Card will translate only in negative Y-axis , here (translate(0, -5px)) Up direction, then
below stacked card will translate positive Y-axis i.e opposite to Up direction and it will also scale along Y-axis which will create multiple stacked-Up effects with the help of before and after Pseudo element.
Stacked-Right:
Top Card will translate only in positive X-axis , here ( translate(5px, 0) ) Right direction, thenbelow stacked card will translate negative X-axis ( translate(-10px, 0) ) i.e opposite to right direction and it will also scale along negative X-axis which will create multiple stacked-Up effects with the help of before and after Pseudo element.
Top Card will translate only in positive X-axis , here ( translate(5px, 0) ) Right direction, then
below stacked card will translate negative X-axis ( translate(-10px, 0) ) i.e opposite to right direction and it will also scale along negative X-axis which will create multiple stacked-Up effects with the help of before and after Pseudo element.
HTML
<!DOCTYPE html><html> <head> <style> body { color: #FDFAF6; background: #50CB93; } :root { --offset-before: 8px; --offset-after: 16px; } .card { position: relative; width: 400px; margin: 60px auto; } .card::before, .card::after { content: ""; position: absolute; top: 0; left: 0; width: 100%; height: 100%; } .card::before, .card::after, .card .card-inner { background-color: #423F3E; border: 1px solid #01937C; transition: transform 0.5s; } .card::before, .card-inner { z-index: 1; } .card-inner { position: relative; padding: 4rem; } /*Stacked => Up*/ .cards-up::before, .cards-up::after { transform-origin: center bottom; } .cards-up:hover { transform: translate(0, -5px); } .cards-up:hover::before { transform: translate(0, 5px) scale(0.95); } .cards-up:hover::after { transform: translate(0, 10px) scale(0.90); } /*Stacked => Right */ .cards-right::before, .cards-right::after { transform-origin: left center; } .cards-right:hover { transform: translate(5px, 0); } .cards-right:hover::before { transform: translate(-10px, 0) scale(0.95); } } .cards-right:hover::after { transform: translate(-10px, 0) scale(0.90); } } </style></head> <body> <center> <h1>Welcome to GeeksforGeeks</h1> <div class="card-container"> <div class="card cards-up"> <div class="card-inner"> <h1>Stacked-Up</h1> <h3 class="card-title">GeeksforGeeks</h3> <div class="card-body"> A Complete Portal for Geeks. </div> </div> </div> </div> <div class="card-container"> <div class="card cards-right"> <div class="card-inner"> <h1>Stacked-Right</h1> <h3 class="card-title">GeeksforGeeks</h3> <div class="card-body"> A Complete Portal for Geeks. </div> </div> </div> </div> </center></body> </html>
Output:
CSS-Properties
CSS-Questions
HTML-Attributes
HTML-Questions
HTML-Tags
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
Build a Survey Form using HTML and CSS
Form validation using jQuery
Design a web page using HTML and CSS
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
HTTP headers | Content-Type
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Aug, 2021"
},
{
"code": null,
"e": 358,
"s": 28,
"text": "Introduction: Cards are a very important part of any website. It is used to display some important information in short to viewers. In this article, we will create responsive stackend cards hover effect using HTML and CSS. In order to achieve a multi-layer stacking effect, you have to follow certain steps which are given below."
},
{
"code": null,
"e": 494,
"s": 358,
"text": "Note: Through hover on cards, we can achieve various directions or effects on cards like top-left, bottom-right, diagonal, rotate, etc."
},
{
"code": null,
"e": 1033,
"s": 494,
"text": "Approach: First, we will design a simple card structure in HTM. Now we will use some CSS properties to build the basic design of the card and to create a stack effect, we will define the ::before and ::after pseudo-elements and absolutely position them relative to the parent card. Now we will have to move the div with class “card-inner” away from its original position by using the transform property. Finally, added a hover effect on a stack of cards by using a transform that can translate the card before and after the hover effect."
},
{
"code": null,
"e": 1085,
"s": 1033,
"text": "Let’s see the implementation of the above approach."
},
{
"code": null,
"e": 1473,
"s": 1085,
"text": "Example 1: In this example, we will see when the user will hover over the card Top Card will translate over X-axis and Y-axis, here (5px-X-axis, 5px-Y-axis) bottom-right direction and below stacked card will translate (-X)-axis and (-Y)-axis i.e opposite to bottom-right direction which will create multiple stacked-bottom-right effects will the help of before and after Pseudo element."
},
{
"code": null,
"e": 1478,
"s": 1473,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title> stackened cards hover effect </title> <style> body { color: #FDFAF6; background: #50CB93; } .card { position: relative; width: 400px; margin: 60px auto; } .card::before, .card::after { content: \"\"; position: absolute; top: 0; left: 0; width: 100%; height: 100%; } .card::before, .card::after, .card .card-inner { background-color: #423F3E; border: 1px solid #01937C; transition: transform 0.5s; } .card::before, .card-inner { z-index: 1; } .card-inner { position: relative; padding: 4rem; } /* Position the stacked cards in different position */ .cards:hover { transform: translate(5px, 5px); } .cards:hover::before { transform: translate(-5px, -5px); } .cards:hover::after { transform: translate(-10px, -10px); } </style></head> <body> <center> <h1>Welcome to GeeksforGeeks</h1> <div class=\"card-container\"> <div class=\"card cards\"> <div class=\"card-inner\"> <h1>Down-Right</h1> <h3 class=\"card-title\"> GeeksforGeeks </h3> <div class=\"card-body\"> A Complete Portal for Geeks. </div> </div> </div> </div> </center></body> </html>",
"e": 3181,
"s": 1478,
"text": null
},
{
"code": null,
"e": 3189,
"s": 3181,
"text": "Output:"
},
{
"code": null,
"e": 3319,
"s": 3189,
"text": "Example 2: In this example, we will see stacked-diagonal-left and stacked-rotate-left using the same approach as explained above."
},
{
"code": null,
"e": 3340,
"s": 3319,
"text": "Stacked-Rotate-left:"
},
{
"code": null,
"e": 3684,
"s": 3340,
"text": "Top Card will translate only over X-axis , here ( translate(2.5px, 0) ) left direction, and rotate at certain angle, here its 2.5 degree ( rotate(2.5deg) ) .thenBelow stacked card will also translate and rotate in the same direction but with double pixel to create a stacked multi-layer effect with the help of before and after Pseudo element."
},
{
"code": null,
"e": 3846,
"s": 3684,
"text": "Top Card will translate only over X-axis , here ( translate(2.5px, 0) ) left direction, and rotate at certain angle, here its 2.5 degree ( rotate(2.5deg) ) .then"
},
{
"code": null,
"e": 4029,
"s": 3846,
"text": "Below stacked card will also translate and rotate in the same direction but with double pixel to create a stacked multi-layer effect with the help of before and after Pseudo element."
},
{
"code": null,
"e": 4052,
"s": 4029,
"text": "Stacked-diagonal-left:"
},
{
"code": null,
"e": 4464,
"s": 4052,
"text": "In diagonal-left, Initially multi-layer stack card is positioned in opposite direction to the directional-left ( translate(-16px, -16px) ) using transform:translate property and thenWhen the user hovers over the card, stacked multi-layer card will translate to diagonal-left direction using same value i.e ( translate(16px, 16px) ) but opposite sign so that stacked multi-layer cards can cover equal direction."
},
{
"code": null,
"e": 4647,
"s": 4464,
"text": "In diagonal-left, Initially multi-layer stack card is positioned in opposite direction to the directional-left ( translate(-16px, -16px) ) using transform:translate property and then"
},
{
"code": null,
"e": 4877,
"s": 4647,
"text": "When the user hovers over the card, stacked multi-layer card will translate to diagonal-left direction using same value i.e ( translate(16px, 16px) ) but opposite sign so that stacked multi-layer cards can cover equal direction."
},
{
"code": null,
"e": 4882,
"s": 4877,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> body { color: #FDFAF6; background: #50CB93; } :root { --offset-before: 8px; --offset-after: 16px; } .card { position: relative; width: 400px; margin: 60px auto; } .card::before, .card::after { content: \"\"; position: absolute; top: 0; left: 0; width: 100%; height: 100%; } .card::before, .card::after, .card .card-inner { background-color: #423F3E; border: 1px solid #01937C; transition: transform 0.5s; } .card::before, .card-inner { z-index: 1; } .card-inner { position: relative; padding: 4rem; } /*Diagonal => Left*/ .cards-diagonal::before { transform: translate(calc(-1 * 8px), calc(-1 * 8px)); } .cards-diagonal::after { transform: translate(calc(-1 * 16px), calc(-1 * 16px)); } .cards-diagonal:hover::before { transform: translate(8px, 8px); } .cards-diagonal:hover::after { transform: translate(16px, 16px); } /*Rotate => Left */ .cards-rotate::before, .cards-rotate::after { transform-origin: 50% 100%; } .cards-rotate:hover { transform: translate(2.5px, 0) rotate(2.5deg); } .cards-rotate:hover::before { transform: translate(2.5px, 0) rotate(2.5deg); } .cards-rotate:hover::after { transform: translate(5px, 0) rotate(5deg); } } </style></head> <body> <center> <h1>Welcome to GeeksforGeeks</h1> <div class=\"card-container\"> <div class=\"card cards-diagonal\"> <div class=\"card-inner\"> <h1>Diagonal-Left</h1> <h3 class=\"card-title\">GeeksforGeeks</h3> <div class=\"card-body\"> A Complete Portal for Geeks. </div> </div> </div> </div> <div class=\"card-container\"> <div class=\"card cards-rotate\"> <div class=\"card-inner\"> <h1>Rotate-Left</h1> <h3 class=\"card-title\">GeeksforGeeks</h3> <div class=\"card-body\"> A Complete Portal for Geeks. </div> </div> </div> </div> </center></body> </html>",
"e": 7595,
"s": 4882,
"text": null
},
{
"code": null,
"e": 7603,
"s": 7595,
"text": "Output:"
},
{
"code": null,
"e": 7724,
"s": 7603,
"text": "Example 3: In this example, we will see stacked-Up and stacked-Right effects using the same approach as explained above."
},
{
"code": null,
"e": 7736,
"s": 7724,
"text": "Stacked-Up:"
},
{
"code": null,
"e": 8041,
"s": 7736,
"text": "Top Card will translate only in negative Y-axis , here (translate(0, -5px)) Up direction, thenbelow stacked card will translate positive Y-axis i.e opposite to Up direction and it will also scale along Y-axis which will create multiple stacked-Up effects with the help of before and after Pseudo element."
},
{
"code": null,
"e": 8136,
"s": 8041,
"text": "Top Card will translate only in negative Y-axis , here (translate(0, -5px)) Up direction, then"
},
{
"code": null,
"e": 8347,
"s": 8136,
"text": "below stacked card will translate positive Y-axis i.e opposite to Up direction and it will also scale along Y-axis which will create multiple stacked-Up effects with the help of before and after Pseudo element."
},
{
"code": null,
"e": 8362,
"s": 8347,
"text": "Stacked-Right:"
},
{
"code": null,
"e": 8710,
"s": 8362,
"text": "Top Card will translate only in positive X-axis , here ( translate(5px, 0) ) Right direction, thenbelow stacked card will translate negative X-axis ( translate(-10px, 0) ) i.e opposite to right direction and it will also scale along negative X-axis which will create multiple stacked-Up effects with the help of before and after Pseudo element."
},
{
"code": null,
"e": 8809,
"s": 8710,
"text": "Top Card will translate only in positive X-axis , here ( translate(5px, 0) ) Right direction, then"
},
{
"code": null,
"e": 9059,
"s": 8809,
"text": "below stacked card will translate negative X-axis ( translate(-10px, 0) ) i.e opposite to right direction and it will also scale along negative X-axis which will create multiple stacked-Up effects with the help of before and after Pseudo element."
},
{
"code": null,
"e": 9064,
"s": 9059,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> body { color: #FDFAF6; background: #50CB93; } :root { --offset-before: 8px; --offset-after: 16px; } .card { position: relative; width: 400px; margin: 60px auto; } .card::before, .card::after { content: \"\"; position: absolute; top: 0; left: 0; width: 100%; height: 100%; } .card::before, .card::after, .card .card-inner { background-color: #423F3E; border: 1px solid #01937C; transition: transform 0.5s; } .card::before, .card-inner { z-index: 1; } .card-inner { position: relative; padding: 4rem; } /*Stacked => Up*/ .cards-up::before, .cards-up::after { transform-origin: center bottom; } .cards-up:hover { transform: translate(0, -5px); } .cards-up:hover::before { transform: translate(0, 5px) scale(0.95); } .cards-up:hover::after { transform: translate(0, 10px) scale(0.90); } /*Stacked => Right */ .cards-right::before, .cards-right::after { transform-origin: left center; } .cards-right:hover { transform: translate(5px, 0); } .cards-right:hover::before { transform: translate(-10px, 0) scale(0.95); } } .cards-right:hover::after { transform: translate(-10px, 0) scale(0.90); } } </style></head> <body> <center> <h1>Welcome to GeeksforGeeks</h1> <div class=\"card-container\"> <div class=\"card cards-up\"> <div class=\"card-inner\"> <h1>Stacked-Up</h1> <h3 class=\"card-title\">GeeksforGeeks</h3> <div class=\"card-body\"> A Complete Portal for Geeks. </div> </div> </div> </div> <div class=\"card-container\"> <div class=\"card cards-right\"> <div class=\"card-inner\"> <h1>Stacked-Right</h1> <h3 class=\"card-title\">GeeksforGeeks</h3> <div class=\"card-body\"> A Complete Portal for Geeks. </div> </div> </div> </div> </center></body> </html>",
"e": 11691,
"s": 9064,
"text": null
},
{
"code": null,
"e": 11699,
"s": 11691,
"text": "Output:"
},
{
"code": null,
"e": 11714,
"s": 11699,
"text": "CSS-Properties"
},
{
"code": null,
"e": 11728,
"s": 11714,
"text": "CSS-Questions"
},
{
"code": null,
"e": 11744,
"s": 11728,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 11759,
"s": 11744,
"text": "HTML-Questions"
},
{
"code": null,
"e": 11769,
"s": 11759,
"text": "HTML-Tags"
},
{
"code": null,
"e": 11773,
"s": 11769,
"text": "CSS"
},
{
"code": null,
"e": 11778,
"s": 11773,
"text": "HTML"
},
{
"code": null,
"e": 11795,
"s": 11778,
"text": "Web Technologies"
},
{
"code": null,
"e": 11800,
"s": 11795,
"text": "HTML"
},
{
"code": null,
"e": 11898,
"s": 11800,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11937,
"s": 11898,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 11976,
"s": 11937,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 12015,
"s": 11976,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 12044,
"s": 12015,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 12081,
"s": 12044,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 12105,
"s": 12081,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 12158,
"s": 12105,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 12218,
"s": 12158,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 12279,
"s": 12218,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
Python – Extract Unique values dictionary values
|
22 Apr, 2020
Sometimes, while working with data, we can have problem in which we need to perform the extraction of only unique values from dictionary values list. This can have application in many domains such as web development. Lets discuss certain ways in which this task can be performed.
Method #1 : Using sorted() + set comprehension + values()The combination of above functionalities can be used to perform this task. In this, we extract all the values using values() and set comprehension is used to get unique values compiled in list.
# Python3 code to demonstrate working of # Extract Unique values dictionary values# Using set comprehension + values() + sorted() # initializing dictionarytest_dict = {'gfg' : [5, 6, 7, 8], 'is' : [10, 11, 7, 5], 'best' : [6, 12, 10, 8], 'for' : [1, 2, 5]} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Extract Unique values dictionary values# Using set comprehension + values() + sorted()res = list(sorted({ele for val in test_dict.values() for ele in val})) # printing result print("The unique values list is : " + str(res))
The original dictionary is : {‘gfg’: [5, 6, 7, 8], ‘best’: [6, 12, 10, 8], ‘is’: [10, 11, 7, 5], ‘for’: [1, 2, 5]}The unique values list is : [1, 2, 5, 6, 7, 8, 10, 11, 12]
Method #2 : Using chain() + sorted() + values()This performs the task in similar way. The difference is that the task of set comprehension is performed using chain().
# Python3 code to demonstrate working of # Extract Unique values dictionary values# Using chain() + sorted() + values()from itertools import chain # initializing dictionarytest_dict = {'gfg' : [5, 6, 7, 8], 'is' : [10, 11, 7, 5], 'best' : [6, 12, 10, 8], 'for' : [1, 2, 5]} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Extract Unique values dictionary values# Using chain() + sorted() + values()res = list(sorted(set(chain(*test_dict.values())))) # printing result print("The unique values list is : " + str(res))
The original dictionary is : {‘gfg’: [5, 6, 7, 8], ‘best’: [6, 12, 10, 8], ‘is’: [10, 11, 7, 5], ‘for’: [1, 2, 5]}The unique values list is : [1, 2, 5, 6, 7, 8, 10, 11, 12]
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n22 Apr, 2020"
},
{
"code": null,
"e": 333,
"s": 53,
"text": "Sometimes, while working with data, we can have problem in which we need to perform the extraction of only unique values from dictionary values list. This can have application in many domains such as web development. Lets discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 584,
"s": 333,
"text": "Method #1 : Using sorted() + set comprehension + values()The combination of above functionalities can be used to perform this task. In this, we extract all the values using values() and set comprehension is used to get unique values compiled in list."
},
{
"code": "# Python3 code to demonstrate working of # Extract Unique values dictionary values# Using set comprehension + values() + sorted() # initializing dictionarytest_dict = {'gfg' : [5, 6, 7, 8], 'is' : [10, 11, 7, 5], 'best' : [6, 12, 10, 8], 'for' : [1, 2, 5]} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # Extract Unique values dictionary values# Using set comprehension + values() + sorted()res = list(sorted({ele for val in test_dict.values() for ele in val})) # printing result print(\"The unique values list is : \" + str(res)) ",
"e": 1194,
"s": 584,
"text": null
},
{
"code": null,
"e": 1367,
"s": 1194,
"text": "The original dictionary is : {‘gfg’: [5, 6, 7, 8], ‘best’: [6, 12, 10, 8], ‘is’: [10, 11, 7, 5], ‘for’: [1, 2, 5]}The unique values list is : [1, 2, 5, 6, 7, 8, 10, 11, 12]"
},
{
"code": null,
"e": 1536,
"s": 1369,
"text": "Method #2 : Using chain() + sorted() + values()This performs the task in similar way. The difference is that the task of set comprehension is performed using chain()."
},
{
"code": "# Python3 code to demonstrate working of # Extract Unique values dictionary values# Using chain() + sorted() + values()from itertools import chain # initializing dictionarytest_dict = {'gfg' : [5, 6, 7, 8], 'is' : [10, 11, 7, 5], 'best' : [6, 12, 10, 8], 'for' : [1, 2, 5]} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # Extract Unique values dictionary values# Using chain() + sorted() + values()res = list(sorted(set(chain(*test_dict.values())))) # printing result print(\"The unique values list is : \" + str(res)) ",
"e": 2134,
"s": 1536,
"text": null
},
{
"code": null,
"e": 2307,
"s": 2134,
"text": "The original dictionary is : {‘gfg’: [5, 6, 7, 8], ‘best’: [6, 12, 10, 8], ‘is’: [10, 11, 7, 5], ‘for’: [1, 2, 5]}The unique values list is : [1, 2, 5, 6, 7, 8, 10, 11, 12]"
},
{
"code": null,
"e": 2334,
"s": 2307,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 2341,
"s": 2334,
"text": "Python"
},
{
"code": null,
"e": 2357,
"s": 2341,
"text": "Python Programs"
}
] |
JavaScript and Cookies
|
Web Browsers and Servers use HTTP protocol to communicate and HTTP is a stateless protocol. But for a commercial website, it is required to maintain session information among different pages. For example, one user registration ends after completing many pages. But how to maintain users' session information across all the web pages.
In many situations, using cookies is the most efficient method of remembering and tracking preferences, purchases, commissions, and other information required for better visitor experience or site statistics.
Your server sends some data to the visitor's browser in the form of a cookie. The browser may accept the cookie. If it does, it is stored as a plain text record on the visitor's hard drive. Now, when the visitor arrives at another page on your site, the browser sends the same cookie to the server for retrieval. Once retrieved, your server knows/remembers what was stored earlier.
Cookies are a plain text data record of 5 variable-length fields −
Expires − The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser.
Expires − The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser.
Domain − The domain name of your site.
Domain − The domain name of your site.
Path − The path to the directory or web page that set the cookie. This may be blank if you want to retrieve the cookie from any directory or page.
Path − The path to the directory or web page that set the cookie. This may be blank if you want to retrieve the cookie from any directory or page.
Secure − If this field contains the word "secure", then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists.
Secure − If this field contains the word "secure", then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists.
Name=Value − Cookies are set and retrieved in the form of key-value pairs
Name=Value − Cookies are set and retrieved in the form of key-value pairs
Cookies were originally designed for CGI programming. The data contained in a cookie is automatically transmitted between the web browser and the web server, so CGI scripts on the server can read and write cookie values that are stored on the client.
JavaScript can also manipulate cookies using the cookie property of the Document object. JavaScript can read, create, modify, and delete the cookies that apply to the current web page.
The simplest way to create a cookie is to assign a string value to the document.cookie object, which looks like this.
document.cookie = "key1 = value1;key2 = value2;expires = date";
Here the expires attribute is optional. If you provide this attribute with a valid date or time, then the cookie will expire on a given date or time and thereafter, the cookies' value will not be accessible.
Note − Cookie values may not include semicolons, commas, or whitespace. For this reason, you may want to use the JavaScript escape() function to encode the value before storing it in the cookie. If you do this, you will also have to use the corresponding unescape() function when you read the cookie value.
Try the following. It sets a customer name in an input cookie.
<html>
<head>
<script type = "text/javascript">
<!--
function WriteCookie() {
if( document.myform.customer.value == "" ) {
alert("Enter some value!");
return;
}
cookievalue = escape(document.myform.customer.value) + ";";
document.cookie = "name=" + cookievalue;
document.write ("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name = "myform" action = "">
Enter name: <input type = "text" name = "customer"/>
<input type = "button" value = "Set Cookie" onclick = "WriteCookie();"/>
</form>
</body>
</html>
Now your machine has a cookie called name. You can set multiple cookies using multiple key = value pairs separated by comma.
Reading a cookie is just as simple as writing one, because the value of the document.cookie object is the cookie. So you can use this string whenever you want to access the cookie. The document.cookie string will keep a list of name=value pairs separated by semicolons, where name is the name of a cookie and value is its string value.
You can use strings' split() function to break a string into key and values as follows −
Try the following example to get all the cookies.
<html>
<head>
<script type = "text/javascript">
<!--
function ReadCookie() {
var allcookies = document.cookie;
document.write ("All Cookies : " + allcookies );
// Get all the cookies pairs in an array
cookiearray = allcookies.split(';');
// Now take key value pair out of this array
for(var i=0; i<cookiearray.length; i++) {
name = cookiearray[i].split('=')[0];
value = cookiearray[i].split('=')[1];
document.write ("Key is : " + name + " and Value is : " + value);
}
}
//-->
</script>
</head>
<body>
<form name = "myform" action = "">
<p> click the following button and see the result:</p>
<input type = "button" value = "Get Cookie" onclick = "ReadCookie()"/>
</form>
</body>
</html>
Note − Here length is a method of Array class which returns the length of an array. We will discuss Arrays in a separate chapter. By that time, please try to digest it.
click the following button and see the result:
Note − There may be some other cookies already set on your machine. The above code will display all the cookies set on your machine.
You can extend the life of a cookie beyond the current browser session by setting an expiration date and saving the expiry date within the cookie. This can be done by setting the ‘expires’ attribute to a date and time.
Try the following example. It illustrates how to extend the expiry date of a cookie by 1 Month.
<html>
<head>
<script type = "text/javascript">
<!--
function WriteCookie() {
var now = new Date();
now.setMonth( now.getMonth() + 1 );
cookievalue = escape(document.myform.customer.value) + ";"
document.cookie = "name=" + cookievalue;
document.cookie = "expires=" + now.toUTCString() + ";"
document.write ("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name = "myform" action = "">
Enter name: <input type = "text" name = "customer"/>
<input type = "button" value = "Set Cookie" onclick = "WriteCookie()"/>
</form>
</body>
</html>
Sometimes you will want to delete a cookie so that subsequent attempts to read the cookie return nothing. To do this, you just need to set the expiry date to a time in the past.
Try the following example. It illustrates how to delete a cookie by setting its expiry date to one month behind the current date.
<html>
<head>
<script type = "text/javascript">
<!--
function WriteCookie() {
var now = new Date();
now.setMonth( now.getMonth() - 1 );
cookievalue = escape(document.myform.customer.value) + ";"
document.cookie = "name=" + cookievalue;
document.cookie = "expires=" + now.toUTCString() + ";"
document.write("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name = "myform" action = "">
Enter name: <input type = "text" name = "customer"/>
<input type = "button" value = "Set Cookie" onclick = "WriteCookie()"/>
|
[
{
"code": null,
"e": 2934,
"s": 2600,
"text": "Web Browsers and Servers use HTTP protocol to communicate and HTTP is a stateless protocol. But for a commercial website, it is required to maintain session information among different pages. For example, one user registration ends after completing many pages. But how to maintain users' session information across all the web pages."
},
{
"code": null,
"e": 3143,
"s": 2934,
"text": "In many situations, using cookies is the most efficient method of remembering and tracking preferences, purchases, commissions, and other information required for better visitor experience or site statistics."
},
{
"code": null,
"e": 3525,
"s": 3143,
"text": "Your server sends some data to the visitor's browser in the form of a cookie. The browser may accept the cookie. If it does, it is stored as a plain text record on the visitor's hard drive. Now, when the visitor arrives at another page on your site, the browser sends the same cookie to the server for retrieval. Once retrieved, your server knows/remembers what was stored earlier."
},
{
"code": null,
"e": 3592,
"s": 3525,
"text": "Cookies are a plain text data record of 5 variable-length fields −"
},
{
"code": null,
"e": 3712,
"s": 3592,
"text": "Expires − The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser."
},
{
"code": null,
"e": 3832,
"s": 3712,
"text": "Expires − The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser."
},
{
"code": null,
"e": 3871,
"s": 3832,
"text": "Domain − The domain name of your site."
},
{
"code": null,
"e": 3910,
"s": 3871,
"text": "Domain − The domain name of your site."
},
{
"code": null,
"e": 4057,
"s": 3910,
"text": "Path − The path to the directory or web page that set the cookie. This may be blank if you want to retrieve the cookie from any directory or page."
},
{
"code": null,
"e": 4204,
"s": 4057,
"text": "Path − The path to the directory or web page that set the cookie. This may be blank if you want to retrieve the cookie from any directory or page."
},
{
"code": null,
"e": 4367,
"s": 4204,
"text": "Secure − If this field contains the word \"secure\", then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists."
},
{
"code": null,
"e": 4530,
"s": 4367,
"text": "Secure − If this field contains the word \"secure\", then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists."
},
{
"code": null,
"e": 4604,
"s": 4530,
"text": "Name=Value − Cookies are set and retrieved in the form of key-value pairs"
},
{
"code": null,
"e": 4678,
"s": 4604,
"text": "Name=Value − Cookies are set and retrieved in the form of key-value pairs"
},
{
"code": null,
"e": 4929,
"s": 4678,
"text": "Cookies were originally designed for CGI programming. The data contained in a cookie is automatically transmitted between the web browser and the web server, so CGI scripts on the server can read and write cookie values that are stored on the client."
},
{
"code": null,
"e": 5114,
"s": 4929,
"text": "JavaScript can also manipulate cookies using the cookie property of the Document object. JavaScript can read, create, modify, and delete the cookies that apply to the current web page."
},
{
"code": null,
"e": 5232,
"s": 5114,
"text": "The simplest way to create a cookie is to assign a string value to the document.cookie object, which looks like this."
},
{
"code": null,
"e": 5297,
"s": 5232,
"text": "document.cookie = \"key1 = value1;key2 = value2;expires = date\";\n"
},
{
"code": null,
"e": 5505,
"s": 5297,
"text": "Here the expires attribute is optional. If you provide this attribute with a valid date or time, then the cookie will expire on a given date or time and thereafter, the cookies' value will not be accessible."
},
{
"code": null,
"e": 5812,
"s": 5505,
"text": "Note − Cookie values may not include semicolons, commas, or whitespace. For this reason, you may want to use the JavaScript escape() function to encode the value before storing it in the cookie. If you do this, you will also have to use the corresponding unescape() function when you read the cookie value."
},
{
"code": null,
"e": 5875,
"s": 5812,
"text": "Try the following. It sets a customer name in an input cookie."
},
{
"code": null,
"e": 6648,
"s": 5875,
"text": "<html>\n <head> \n <script type = \"text/javascript\">\n <!--\n function WriteCookie() {\n if( document.myform.customer.value == \"\" ) {\n alert(\"Enter some value!\");\n return;\n }\n cookievalue = escape(document.myform.customer.value) + \";\";\n document.cookie = \"name=\" + cookievalue;\n document.write (\"Setting Cookies : \" + \"name=\" + cookievalue );\n }\n //-->\n </script> \n </head>\n \n <body> \n <form name = \"myform\" action = \"\">\n Enter name: <input type = \"text\" name = \"customer\"/>\n <input type = \"button\" value = \"Set Cookie\" onclick = \"WriteCookie();\"/>\n </form> \n </body>\n</html>"
},
{
"code": null,
"e": 6773,
"s": 6648,
"text": "Now your machine has a cookie called name. You can set multiple cookies using multiple key = value pairs separated by comma."
},
{
"code": null,
"e": 7109,
"s": 6773,
"text": "Reading a cookie is just as simple as writing one, because the value of the document.cookie object is the cookie. So you can use this string whenever you want to access the cookie. The document.cookie string will keep a list of name=value pairs separated by semicolons, where name is the name of a cookie and value is its string value."
},
{
"code": null,
"e": 7198,
"s": 7109,
"text": "You can use strings' split() function to break a string into key and values as follows −"
},
{
"code": null,
"e": 7248,
"s": 7198,
"text": "Try the following example to get all the cookies."
},
{
"code": null,
"e": 8245,
"s": 7248,
"text": "<html>\n <head> \n <script type = \"text/javascript\">\n <!--\n function ReadCookie() {\n var allcookies = document.cookie;\n document.write (\"All Cookies : \" + allcookies );\n \n // Get all the cookies pairs in an array\n cookiearray = allcookies.split(';');\n \n // Now take key value pair out of this array\n for(var i=0; i<cookiearray.length; i++) {\n name = cookiearray[i].split('=')[0];\n value = cookiearray[i].split('=')[1];\n document.write (\"Key is : \" + name + \" and Value is : \" + value);\n }\n }\n //-->\n </script> \n </head>\n \n <body> \n <form name = \"myform\" action = \"\">\n <p> click the following button and see the result:</p>\n <input type = \"button\" value = \"Get Cookie\" onclick = \"ReadCookie()\"/>\n </form> \n </body>\n</html>"
},
{
"code": null,
"e": 8414,
"s": 8245,
"text": "Note − Here length is a method of Array class which returns the length of an array. We will discuss Arrays in a separate chapter. By that time, please try to digest it."
},
{
"code": null,
"e": 8462,
"s": 8414,
"text": " click the following button and see the result:"
},
{
"code": null,
"e": 8595,
"s": 8462,
"text": "Note − There may be some other cookies already set on your machine. The above code will display all the cookies set on your machine."
},
{
"code": null,
"e": 8814,
"s": 8595,
"text": "You can extend the life of a cookie beyond the current browser session by setting an expiration date and saving the expiry date within the cookie. This can be done by setting the ‘expires’ attribute to a date and time."
},
{
"code": null,
"e": 8910,
"s": 8814,
"text": "Try the following example. It illustrates how to extend the expiry date of a cookie by 1 Month."
},
{
"code": null,
"e": 9703,
"s": 8910,
"text": "<html>\n <head> \n <script type = \"text/javascript\">\n <!--\n function WriteCookie() {\n var now = new Date();\n now.setMonth( now.getMonth() + 1 );\n cookievalue = escape(document.myform.customer.value) + \";\"\n \n document.cookie = \"name=\" + cookievalue;\n document.cookie = \"expires=\" + now.toUTCString() + \";\"\n document.write (\"Setting Cookies : \" + \"name=\" + cookievalue );\n }\n //-->\n </script> \n </head>\n \n <body>\n <form name = \"myform\" action = \"\">\n Enter name: <input type = \"text\" name = \"customer\"/>\n <input type = \"button\" value = \"Set Cookie\" onclick = \"WriteCookie()\"/>\n </form> \n </body>\n</html>"
},
{
"code": null,
"e": 9881,
"s": 9703,
"text": "Sometimes you will want to delete a cookie so that subsequent attempts to read the cookie return nothing. To do this, you just need to set the expiry date to a time in the past."
},
{
"code": null,
"e": 10011,
"s": 9881,
"text": "Try the following example. It illustrates how to delete a cookie by setting its expiry date to one month behind the current date."
}
] |
Find two prime numbers with given sum
|
02 May, 2022
Given an even number (greater than 2 ), print two prime numbers whose sum will be equal to given number. There may be several combinations possible. Print only first such pair. An interesting point is, a solution always exist according to Goldbach’s conjecture.Examples :
Input: n = 74
Output: 3 71
Input : n = 1024
Output: 3 1021
Input: n = 66
Output: 5 61
Input: n = 9990
Output: 17 9973
The idea is to find all the primes less than or equal to the given number N using Sieve of Eratosthenes. Once we have an array that tells all primes, we can traverse through this array to find pair with given sum.
C++
C
Java
Python 3
C#
PHP
Javascript
// C++ program to find a prime number pair whose sum is// equal to given number// C++ program to print super primes less than or equal to n.#include <bits/stdc++.h>using namespace std; // Generate all prime numbers less than n.bool SieveOfEratosthenes(int n, bool isPrime[]){ // Initialize all entries of boolean array as true. A // value in isPrime[i] will finally be false if i is Not // a prime, else true bool isPrime[n+1]; isPrime[0] = isPrime[1] = false; for (int i = 2; i <= n; i++) isPrime[i] = true; for (int p = 2; p * p <= n; p++) { // If isPrime[p] is not changed, then it is a prime if (isPrime[p] == true) { // Update all multiples of p for (int i = p * p; i <= n; i += p) isPrime[i] = false; } }} // Prints a prime pair with given sumvoid findPrimePair(int n){ // Generating primes using Sieve bool isPrime[n + 1]; SieveOfEratosthenes(n, isPrime); // Traversing all numbers to find first pair for (int i = 0; i < n; i++) { if (isPrime[i] && isPrime[n - i]) { cout << i << " " << (n - i); return; } }} // Driven programint main(){ int n = 74; findPrimePair(n); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// C program to find a prime number pair whose sum is// equal to given number// C program to print super primes less than or equal to n.#include <stdio.h>#include <stdbool.h> // Generate all prime numbers less than n.bool SieveOfEratosthenes(int n, bool isPrime[]){ // Initialize all entries of boolean array as true. A // value in isPrime[i] will finally be false if i is Not // a prime, else true bool isPrime[n+1]; isPrime[0] = isPrime[1] = false; for (int i = 2; i <= n; i++) isPrime[i] = true; for (int p = 2; p * p <= n; p++) { // If isPrime[p] is not changed, then it is a prime if (isPrime[p] == true) { // Update all multiples of p for (int i = p * p; i <= n; i += p) isPrime[i] = false; } }} // Prints a prime pair with given sumvoid findPrimePair(int n){ // Generating primes using Sieve bool isPrime[n + 1]; SieveOfEratosthenes(n, isPrime); // Traversing all numbers to find first // pair for (int i = 0; i < n; i++) { if (isPrime[i] && isPrime[n - i]) { printf("%d %d",i,n-i); return; } }} // Driven programint main(){ int n = 74; findPrimePair(n); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// Java program to find a prime number pair whose sum is// equal to given number// Java program to print super primes less than or equal to n. class GFG { // Generate all prime numbers less than n. static boolean SieveOfEratosthenes(int n, boolean isPrime[]) { // Initialize all entries of boolean array as true. // A value in isPrime[i] will finally be false if i // is Not a prime, else true bool isPrime[n+1]; isPrime[0] = isPrime[1] = false; for (int i = 2; i <= n; i++) isPrime[i] = true; for (int p = 2; p * p <= n; p++) { // If isPrime[p] is not changed, then it is a // prime if (isPrime[p] == true) { // Update all multiples of p for (int i = p * p; i <= n; i += p) isPrime[i] = false; } } return false; } // Prints a prime pair with given sum static void findPrimePair(int n) { // Generating primes using Sieve boolean isPrime[] = new boolean[n + 1]; SieveOfEratosthenes(n, isPrime); // Traversing all numbers to find first pair for (int i = 0; i < n; i++) { if (isPrime[i] && isPrime[n - i]) { System.out.print(i + " " + (n - i)); return; } } } // Driver code public static void main(String[] args) { int n = 74; findPrimePair(n); }} // This code is contributed by Aditya Kumar (adityakumar129)
# Python 3 program to find a prime number# pair whose sum is equal to given number# Python 3 program to print super primes# less than or equal to n. # Generate all prime numbers less than n.def SieveOfEratosthenes(n, isPrime): # Initialize all entries of boolean # array as True. A value in isPrime[i] # will finally be False if i is Not a # prime, else True bool isPrime[n+1] isPrime[0] = isPrime[1] = False for i in range(2, n+1): isPrime[i] = True p = 2 while(p*p <= n): # If isPrime[p] is not changed, # then it is a prime if (isPrime[p] == True): # Update all multiples of p i = p*p while(i <= n): isPrime[i] = False i += p p += 1 # Prints a prime pair with given sumdef findPrimePair(n): # Generating primes using Sieve isPrime = [0] * (n+1) SieveOfEratosthenes(n, isPrime) # Traversing all numbers to find # first pair for i in range(0, n): if (isPrime[i] and isPrime[n - i]): print(i,(n - i)) return # Driven programn = 74findPrimePair(n) # This code is contributed by# Smitha Dinesh Semwal
// C# program to find a prime number pair whose// sum is equal to given number// C# program to print super primes less than// or equal to n.using System; class GFG{ // Generate all prime numbers less than n. static bool SieveOfEratosthenes(int n, bool []isPrime) { // Initialize all entries of boolean // array as true. A value in isPrime[i] // will finally be false if i is Not a // prime, else true bool isPrime[n+1]; isPrime[0] = isPrime[1] = false; for (int i = 2; i <= n; i++) isPrime[i] = true; for (int p = 2; p * p <= n; p++) { // If isPrime[p] is not changed, // then it is a prime if (isPrime[p] == true) { // Update all multiples of p for (int i = p * p; i <= n; i += p) isPrime[i] = false; } } return false; } // Prints a prime pair with given sum static void findPrimePair(int n) { // Generating primes using Sieve bool []isPrime=new bool[n + 1]; SieveOfEratosthenes(n, isPrime); // Traversing all numbers to find first // pair for (int i = 0; i < n; i++) { if (isPrime[i] && isPrime[n - i]) { Console.Write(i + " " + (n - i)); return; } } } // Driver code public static void Main () { int n = 74; findPrimePair(n); }} // This code is contributed by vt_m.
<?php// PHP program to find a prime// number pair whose sum is equal// to given number // Generate all prime numbers// less than n.function SieveOfEratosthenes($n, &$isPrime){ // Initialize all entries of // boolean array as true. A value // in isPrime[i] will finally // be false if i is Not a prime, // else true bool isPrime[n+1]; $isPrime[0] = $isPrime[1] = false; for ($i = 2; $i <= $n; $i++) $isPrime[$i] = true; for ($p = 2; $p * $p <= $n; $p++) { // If isPrime[p] is not changed, // then it is a prime if ($isPrime[$p] == true) { // Update all multiples of p for ($i = $p * $p; $i <= $n; $i += $p) $isPrime[$i] = false; } }} // Prints a prime pair with given sumfunction findPrimePair($n){ // Generating primes using Sieve $isPrime = array_fill(0, $n + 1, NULL); SieveOfEratosthenes($n, $isPrime); // Traversing all numbers // to find first pair for ($i = 0; $i < $n; $i++) { if ($isPrime[$i] && $isPrime[$n - $i]) { echo $i . " " . ($n - $i); return; } }} // Driver Code$n = 74;findPrimePair($n); // This code is contributed// by ChitraNayal?>
<script> // Javascript program to find a prime number pair whose// sum is equal to given number// Java program to print super primes less than// or equal to n. // Generate all prime numbers less than n. function SieveOfEratosthenes(n,isPrime) { // Initialize all entries of boolean // array as true. A value in isPrime[i] // will finally be false if i is Not a // prime, else true bool isPrime[n+1]; isPrime[0] = isPrime[1] = false; for (let i = 2; i <= n; i++) isPrime[i] = true; for (let p = 2; p * p <= n; p++) { // If isPrime[p] is not changed, // then it is a prime if (isPrime[p] == true) { // Update all multiples of p for (let i = p * p; i <= n; i += p) isPrime[i] = false; } } return false; } // Prints a prime pair with given sum function findPrimePair(n) { // Generating primes using Sieve let isPrime = new Array(n+1); for(let i=0;i<n+1;i++) { isPrime[i]=false; } SieveOfEratosthenes(n, isPrime); // Traversing all numbers to find first // pair for (let i = 0; i < n; i++) { if (isPrime[i] && isPrime[n - i]) { document.write(i + " " + (n - i)); return; } } } // Driver code let n = 74; findPrimePair(n); // This code is contributed by rag2127 </script>
Output:
3 71
This article is contributed by Rakesh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
vt_m
Smitha Dinesh Semwal
ukasp
aks9388
rag2127
adityakumar129
Amazon
Prime Number
sieve
Yahoo
Zoho
Mathematical
Zoho
Amazon
Yahoo
Mathematical
Prime Number
sieve
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n02 May, 2022"
},
{
"code": null,
"e": 328,
"s": 54,
"text": "Given an even number (greater than 2 ), print two prime numbers whose sum will be equal to given number. There may be several combinations possible. Print only first such pair. An interesting point is, a solution always exist according to Goldbach’s conjecture.Examples : "
},
{
"code": null,
"e": 449,
"s": 328,
"text": "Input: n = 74\nOutput: 3 71\n\nInput : n = 1024\nOutput: 3 1021\n\nInput: n = 66\nOutput: 5 61\n\nInput: n = 9990\nOutput: 17 9973"
},
{
"code": null,
"e": 667,
"s": 451,
"text": "The idea is to find all the primes less than or equal to the given number N using Sieve of Eratosthenes. Once we have an array that tells all primes, we can traverse through this array to find pair with given sum. "
},
{
"code": null,
"e": 671,
"s": 667,
"text": "C++"
},
{
"code": null,
"e": 673,
"s": 671,
"text": "C"
},
{
"code": null,
"e": 678,
"s": 673,
"text": "Java"
},
{
"code": null,
"e": 687,
"s": 678,
"text": "Python 3"
},
{
"code": null,
"e": 690,
"s": 687,
"text": "C#"
},
{
"code": null,
"e": 694,
"s": 690,
"text": "PHP"
},
{
"code": null,
"e": 705,
"s": 694,
"text": "Javascript"
},
{
"code": "// C++ program to find a prime number pair whose sum is// equal to given number// C++ program to print super primes less than or equal to n.#include <bits/stdc++.h>using namespace std; // Generate all prime numbers less than n.bool SieveOfEratosthenes(int n, bool isPrime[]){ // Initialize all entries of boolean array as true. A // value in isPrime[i] will finally be false if i is Not // a prime, else true bool isPrime[n+1]; isPrime[0] = isPrime[1] = false; for (int i = 2; i <= n; i++) isPrime[i] = true; for (int p = 2; p * p <= n; p++) { // If isPrime[p] is not changed, then it is a prime if (isPrime[p] == true) { // Update all multiples of p for (int i = p * p; i <= n; i += p) isPrime[i] = false; } }} // Prints a prime pair with given sumvoid findPrimePair(int n){ // Generating primes using Sieve bool isPrime[n + 1]; SieveOfEratosthenes(n, isPrime); // Traversing all numbers to find first pair for (int i = 0; i < n; i++) { if (isPrime[i] && isPrime[n - i]) { cout << i << \" \" << (n - i); return; } }} // Driven programint main(){ int n = 74; findPrimePair(n); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 2003,
"s": 705,
"text": null
},
{
"code": "// C program to find a prime number pair whose sum is// equal to given number// C program to print super primes less than or equal to n.#include <stdio.h>#include <stdbool.h> // Generate all prime numbers less than n.bool SieveOfEratosthenes(int n, bool isPrime[]){ // Initialize all entries of boolean array as true. A // value in isPrime[i] will finally be false if i is Not // a prime, else true bool isPrime[n+1]; isPrime[0] = isPrime[1] = false; for (int i = 2; i <= n; i++) isPrime[i] = true; for (int p = 2; p * p <= n; p++) { // If isPrime[p] is not changed, then it is a prime if (isPrime[p] == true) { // Update all multiples of p for (int i = p * p; i <= n; i += p) isPrime[i] = false; } }} // Prints a prime pair with given sumvoid findPrimePair(int n){ // Generating primes using Sieve bool isPrime[n + 1]; SieveOfEratosthenes(n, isPrime); // Traversing all numbers to find first // pair for (int i = 0; i < n; i++) { if (isPrime[i] && isPrime[n - i]) { printf(\"%d %d\",i,n-i); return; } }} // Driven programint main(){ int n = 74; findPrimePair(n); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 3292,
"s": 2003,
"text": null
},
{
"code": "// Java program to find a prime number pair whose sum is// equal to given number// Java program to print super primes less than or equal to n. class GFG { // Generate all prime numbers less than n. static boolean SieveOfEratosthenes(int n, boolean isPrime[]) { // Initialize all entries of boolean array as true. // A value in isPrime[i] will finally be false if i // is Not a prime, else true bool isPrime[n+1]; isPrime[0] = isPrime[1] = false; for (int i = 2; i <= n; i++) isPrime[i] = true; for (int p = 2; p * p <= n; p++) { // If isPrime[p] is not changed, then it is a // prime if (isPrime[p] == true) { // Update all multiples of p for (int i = p * p; i <= n; i += p) isPrime[i] = false; } } return false; } // Prints a prime pair with given sum static void findPrimePair(int n) { // Generating primes using Sieve boolean isPrime[] = new boolean[n + 1]; SieveOfEratosthenes(n, isPrime); // Traversing all numbers to find first pair for (int i = 0; i < n; i++) { if (isPrime[i] && isPrime[n - i]) { System.out.print(i + \" \" + (n - i)); return; } } } // Driver code public static void main(String[] args) { int n = 74; findPrimePair(n); }} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 4806,
"s": 3292,
"text": null
},
{
"code": "# Python 3 program to find a prime number# pair whose sum is equal to given number# Python 3 program to print super primes# less than or equal to n. # Generate all prime numbers less than n.def SieveOfEratosthenes(n, isPrime): # Initialize all entries of boolean # array as True. A value in isPrime[i] # will finally be False if i is Not a # prime, else True bool isPrime[n+1] isPrime[0] = isPrime[1] = False for i in range(2, n+1): isPrime[i] = True p = 2 while(p*p <= n): # If isPrime[p] is not changed, # then it is a prime if (isPrime[p] == True): # Update all multiples of p i = p*p while(i <= n): isPrime[i] = False i += p p += 1 # Prints a prime pair with given sumdef findPrimePair(n): # Generating primes using Sieve isPrime = [0] * (n+1) SieveOfEratosthenes(n, isPrime) # Traversing all numbers to find # first pair for i in range(0, n): if (isPrime[i] and isPrime[n - i]): print(i,(n - i)) return # Driven programn = 74findPrimePair(n) # This code is contributed by# Smitha Dinesh Semwal",
"e": 6026,
"s": 4806,
"text": null
},
{
"code": "// C# program to find a prime number pair whose// sum is equal to given number// C# program to print super primes less than// or equal to n.using System; class GFG{ // Generate all prime numbers less than n. static bool SieveOfEratosthenes(int n, bool []isPrime) { // Initialize all entries of boolean // array as true. A value in isPrime[i] // will finally be false if i is Not a // prime, else true bool isPrime[n+1]; isPrime[0] = isPrime[1] = false; for (int i = 2; i <= n; i++) isPrime[i] = true; for (int p = 2; p * p <= n; p++) { // If isPrime[p] is not changed, // then it is a prime if (isPrime[p] == true) { // Update all multiples of p for (int i = p * p; i <= n; i += p) isPrime[i] = false; } } return false; } // Prints a prime pair with given sum static void findPrimePair(int n) { // Generating primes using Sieve bool []isPrime=new bool[n + 1]; SieveOfEratosthenes(n, isPrime); // Traversing all numbers to find first // pair for (int i = 0; i < n; i++) { if (isPrime[i] && isPrime[n - i]) { Console.Write(i + \" \" + (n - i)); return; } } } // Driver code public static void Main () { int n = 74; findPrimePair(n); }} // This code is contributed by vt_m.",
"e": 7569,
"s": 6026,
"text": null
},
{
"code": "<?php// PHP program to find a prime// number pair whose sum is equal// to given number // Generate all prime numbers// less than n.function SieveOfEratosthenes($n, &$isPrime){ // Initialize all entries of // boolean array as true. A value // in isPrime[i] will finally // be false if i is Not a prime, // else true bool isPrime[n+1]; $isPrime[0] = $isPrime[1] = false; for ($i = 2; $i <= $n; $i++) $isPrime[$i] = true; for ($p = 2; $p * $p <= $n; $p++) { // If isPrime[p] is not changed, // then it is a prime if ($isPrime[$p] == true) { // Update all multiples of p for ($i = $p * $p; $i <= $n; $i += $p) $isPrime[$i] = false; } }} // Prints a prime pair with given sumfunction findPrimePair($n){ // Generating primes using Sieve $isPrime = array_fill(0, $n + 1, NULL); SieveOfEratosthenes($n, $isPrime); // Traversing all numbers // to find first pair for ($i = 0; $i < $n; $i++) { if ($isPrime[$i] && $isPrime[$n - $i]) { echo $i . \" \" . ($n - $i); return; } }} // Driver Code$n = 74;findPrimePair($n); // This code is contributed// by ChitraNayal?>",
"e": 8827,
"s": 7569,
"text": null
},
{
"code": "<script> // Javascript program to find a prime number pair whose// sum is equal to given number// Java program to print super primes less than// or equal to n. // Generate all prime numbers less than n. function SieveOfEratosthenes(n,isPrime) { // Initialize all entries of boolean // array as true. A value in isPrime[i] // will finally be false if i is Not a // prime, else true bool isPrime[n+1]; isPrime[0] = isPrime[1] = false; for (let i = 2; i <= n; i++) isPrime[i] = true; for (let p = 2; p * p <= n; p++) { // If isPrime[p] is not changed, // then it is a prime if (isPrime[p] == true) { // Update all multiples of p for (let i = p * p; i <= n; i += p) isPrime[i] = false; } } return false; } // Prints a prime pair with given sum function findPrimePair(n) { // Generating primes using Sieve let isPrime = new Array(n+1); for(let i=0;i<n+1;i++) { isPrime[i]=false; } SieveOfEratosthenes(n, isPrime); // Traversing all numbers to find first // pair for (let i = 0; i < n; i++) { if (isPrime[i] && isPrime[n - i]) { document.write(i + \" \" + (n - i)); return; } } } // Driver code let n = 74; findPrimePair(n); // This code is contributed by rag2127 </script>",
"e": 10400,
"s": 8827,
"text": null
},
{
"code": null,
"e": 10410,
"s": 10400,
"text": "Output: "
},
{
"code": null,
"e": 10415,
"s": 10410,
"text": "3 71"
},
{
"code": null,
"e": 10836,
"s": 10415,
"text": "This article is contributed by Rakesh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 10841,
"s": 10836,
"text": "vt_m"
},
{
"code": null,
"e": 10862,
"s": 10841,
"text": "Smitha Dinesh Semwal"
},
{
"code": null,
"e": 10868,
"s": 10862,
"text": "ukasp"
},
{
"code": null,
"e": 10876,
"s": 10868,
"text": "aks9388"
},
{
"code": null,
"e": 10884,
"s": 10876,
"text": "rag2127"
},
{
"code": null,
"e": 10899,
"s": 10884,
"text": "adityakumar129"
},
{
"code": null,
"e": 10906,
"s": 10899,
"text": "Amazon"
},
{
"code": null,
"e": 10919,
"s": 10906,
"text": "Prime Number"
},
{
"code": null,
"e": 10925,
"s": 10919,
"text": "sieve"
},
{
"code": null,
"e": 10931,
"s": 10925,
"text": "Yahoo"
},
{
"code": null,
"e": 10936,
"s": 10931,
"text": "Zoho"
},
{
"code": null,
"e": 10949,
"s": 10936,
"text": "Mathematical"
},
{
"code": null,
"e": 10954,
"s": 10949,
"text": "Zoho"
},
{
"code": null,
"e": 10961,
"s": 10954,
"text": "Amazon"
},
{
"code": null,
"e": 10967,
"s": 10961,
"text": "Yahoo"
},
{
"code": null,
"e": 10980,
"s": 10967,
"text": "Mathematical"
},
{
"code": null,
"e": 10993,
"s": 10980,
"text": "Prime Number"
},
{
"code": null,
"e": 10999,
"s": 10993,
"text": "sieve"
}
] |
GATE | GATE CS 2021 | Set 2 | Question 10
|
23 May, 2021
Six students P, Q, R, S, T and U, with distinct heights, compare their heights and make the following observations.
Observation I: S is taller than R.
Observation II: Q is the shortest of all.
Observation III: U is taller than only one student.
Observation IV: T is taller than S but is not the tallest.
The number of students that are taller than R is the same as the number of students shorter than ____________.(A) T(B) R(C) S(D) PAnswer: (C)Explanation: From observations II and III, we can say that Q is the shortest. U is the second shortest.
__ __ __ __ U Q
From observations I and IV, we can say that T is the second tallest. S is the third tallest. R is the fourthtallest. Thus, P is the tallest. Therefore, the final arrangement is as follows,
P T S R U Q
Three students are taller than R, hence three students are shorter than S.Quiz of this Question
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2014-(Set-1) | Question 51
GATE | GATE CS 1996 | Question 63
GATE | GATE-CS-2015 (Set 2) | Question 55
GATE | GATE-CS-2001 | Question 50
GATE | GATE-CS-2004 | Question 31
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 May, 2021"
},
{
"code": null,
"e": 144,
"s": 28,
"text": "Six students P, Q, R, S, T and U, with distinct heights, compare their heights and make the following observations."
},
{
"code": null,
"e": 179,
"s": 144,
"text": "Observation I: S is taller than R."
},
{
"code": null,
"e": 221,
"s": 179,
"text": "Observation II: Q is the shortest of all."
},
{
"code": null,
"e": 273,
"s": 221,
"text": "Observation III: U is taller than only one student."
},
{
"code": null,
"e": 332,
"s": 273,
"text": "Observation IV: T is taller than S but is not the tallest."
},
{
"code": null,
"e": 577,
"s": 332,
"text": "The number of students that are taller than R is the same as the number of students shorter than ____________.(A) T(B) R(C) S(D) PAnswer: (C)Explanation: From observations II and III, we can say that Q is the shortest. U is the second shortest."
},
{
"code": null,
"e": 595,
"s": 577,
"text": " __ __ __ __ U Q "
},
{
"code": null,
"e": 784,
"s": 595,
"text": "From observations I and IV, we can say that T is the second tallest. S is the third tallest. R is the fourthtallest. Thus, P is the tallest. Therefore, the final arrangement is as follows,"
},
{
"code": null,
"e": 797,
"s": 784,
"text": "P T S R U Q "
},
{
"code": null,
"e": 893,
"s": 797,
"text": "Three students are taller than R, hence three students are shorter than S.Quiz of this Question"
},
{
"code": null,
"e": 898,
"s": 893,
"text": "GATE"
},
{
"code": null,
"e": 996,
"s": 898,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1038,
"s": 996,
"text": "GATE | GATE-CS-2014-(Set-2) | Question 65"
},
{
"code": null,
"e": 1100,
"s": 1038,
"text": "GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33"
},
{
"code": null,
"e": 1134,
"s": 1100,
"text": "GATE | GATE CS 2008 | Question 46"
},
{
"code": null,
"e": 1176,
"s": 1134,
"text": "GATE | GATE-CS-2015 (Set 3) | Question 65"
},
{
"code": null,
"e": 1218,
"s": 1176,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 65"
},
{
"code": null,
"e": 1260,
"s": 1218,
"text": "GATE | GATE-CS-2014-(Set-1) | Question 51"
},
{
"code": null,
"e": 1294,
"s": 1260,
"text": "GATE | GATE CS 1996 | Question 63"
},
{
"code": null,
"e": 1336,
"s": 1294,
"text": "GATE | GATE-CS-2015 (Set 2) | Question 55"
},
{
"code": null,
"e": 1370,
"s": 1336,
"text": "GATE | GATE-CS-2001 | Question 50"
}
] |
Scales of Measurement
|
02 Jul, 2018
Data can be classified as being on one of four scales: nominal, ordinal, interval or ratio. Each level of measurement has some important properties that are useful to know.
Properties of Measurement Scales:
Identity – Each value on the measurement scale has a unique meaning.
Magnitude – Values on the measurement scale have an ordered relationship to one another. That is, some values are larger and some are smaller.
Equal intervals – Scale units along the scale are equal to one another. For Example the difference between 1 and 2 would be equal to the difference between 11 and 12.
A minimum value of zero – The scale has a true zero point, below which no values exist.
1. Nominal Scale –Nominal variables can be placed into categories. These don’t have a numeric value and so cannot be added, subtracted, divided or multiplied. These also have no order, and nominal scale of measurement only satisfies the identity property of measurement.
For example, gender is an example of a variable that is measured on a nominal scale. Individuals may be classified as “male” or “female”, but neither value represents more or less “gender” than the other.
2. Ordinal Scale –The ordinal scale contains things that you can place in order. It measures a variable in terms of magnitude, or rank. Ordinal scales tell us relative order, but give us no information regarding differences between the categories. The ordinal scale has the property of both identity and magnitude.
For example, in a race If Ram takes first and Vidur takes second place, we do not know competition was close by how many seconds.
3. Interval Scale –An interval scale has ordered numbers with meaningful divisions, the magnitude between the consecutive intervals are equal. Interval scales do not have a true zero i.e In Celsius 0 degrees does not mean the absence of heat.
Interval scales have the properties of:
Identity
Magnitude
Equal distance
For example, temperature on Fahrenheit/Celsius thermometer i.e. 90° are hotter than 45° and the difference between 10° and 30° are the same as the difference between 60° degrees and 80°.
4. Ratio Scale –The ratio scale of measurement is similar to the interval scale in that it also represents quantity and has equality of units with one major difference: zero is meaningful (no numbers exist below the zero). The true zero allows us to know how many times greater one case is than another. Ratio scales have all of the characteristics of the nominal, ordinal and interval scales. The simplest example of a ratio scale is the measurement of length. Having zero length or zero money means that there is no length and no money but zero temperature is not an absolute zero.
Properties of Ratio Scale:
Identity
Magnitude
Equal distance
Absolute/true zero
For example, in distance 10 miles is twice as long as 5 mile.
Engineering Mathematics
Misc
Misc
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Relationship between number of nodes and height of binary tree
Inequalities in LaTeX
Mathematics | The Pigeonhole Principle
Number of Possible Super Keys in DBMS
Various Implicants in K-Map
Overview of Data Structures | Set 1 (Linear Data Structures)
Top 10 algorithms in Interview Questions
vector::push_back() and vector::pop_back() in C++ STL
Program for nth Catalan Number
How to write Regular Expressions?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Jul, 2018"
},
{
"code": null,
"e": 201,
"s": 28,
"text": "Data can be classified as being on one of four scales: nominal, ordinal, interval or ratio. Each level of measurement has some important properties that are useful to know."
},
{
"code": null,
"e": 235,
"s": 201,
"text": "Properties of Measurement Scales:"
},
{
"code": null,
"e": 304,
"s": 235,
"text": "Identity – Each value on the measurement scale has a unique meaning."
},
{
"code": null,
"e": 447,
"s": 304,
"text": "Magnitude – Values on the measurement scale have an ordered relationship to one another. That is, some values are larger and some are smaller."
},
{
"code": null,
"e": 614,
"s": 447,
"text": "Equal intervals – Scale units along the scale are equal to one another. For Example the difference between 1 and 2 would be equal to the difference between 11 and 12."
},
{
"code": null,
"e": 702,
"s": 614,
"text": "A minimum value of zero – The scale has a true zero point, below which no values exist."
},
{
"code": null,
"e": 973,
"s": 702,
"text": "1. Nominal Scale –Nominal variables can be placed into categories. These don’t have a numeric value and so cannot be added, subtracted, divided or multiplied. These also have no order, and nominal scale of measurement only satisfies the identity property of measurement."
},
{
"code": null,
"e": 1178,
"s": 973,
"text": "For example, gender is an example of a variable that is measured on a nominal scale. Individuals may be classified as “male” or “female”, but neither value represents more or less “gender” than the other."
},
{
"code": null,
"e": 1493,
"s": 1178,
"text": "2. Ordinal Scale –The ordinal scale contains things that you can place in order. It measures a variable in terms of magnitude, or rank. Ordinal scales tell us relative order, but give us no information regarding differences between the categories. The ordinal scale has the property of both identity and magnitude."
},
{
"code": null,
"e": 1623,
"s": 1493,
"text": "For example, in a race If Ram takes first and Vidur takes second place, we do not know competition was close by how many seconds."
},
{
"code": null,
"e": 1866,
"s": 1623,
"text": "3. Interval Scale –An interval scale has ordered numbers with meaningful divisions, the magnitude between the consecutive intervals are equal. Interval scales do not have a true zero i.e In Celsius 0 degrees does not mean the absence of heat."
},
{
"code": null,
"e": 1906,
"s": 1866,
"text": "Interval scales have the properties of:"
},
{
"code": null,
"e": 1915,
"s": 1906,
"text": "Identity"
},
{
"code": null,
"e": 1925,
"s": 1915,
"text": "Magnitude"
},
{
"code": null,
"e": 1940,
"s": 1925,
"text": "Equal distance"
},
{
"code": null,
"e": 2127,
"s": 1940,
"text": "For example, temperature on Fahrenheit/Celsius thermometer i.e. 90° are hotter than 45° and the difference between 10° and 30° are the same as the difference between 60° degrees and 80°."
},
{
"code": null,
"e": 2711,
"s": 2127,
"text": "4. Ratio Scale –The ratio scale of measurement is similar to the interval scale in that it also represents quantity and has equality of units with one major difference: zero is meaningful (no numbers exist below the zero). The true zero allows us to know how many times greater one case is than another. Ratio scales have all of the characteristics of the nominal, ordinal and interval scales. The simplest example of a ratio scale is the measurement of length. Having zero length or zero money means that there is no length and no money but zero temperature is not an absolute zero."
},
{
"code": null,
"e": 2738,
"s": 2711,
"text": "Properties of Ratio Scale:"
},
{
"code": null,
"e": 2747,
"s": 2738,
"text": "Identity"
},
{
"code": null,
"e": 2757,
"s": 2747,
"text": "Magnitude"
},
{
"code": null,
"e": 2772,
"s": 2757,
"text": "Equal distance"
},
{
"code": null,
"e": 2791,
"s": 2772,
"text": "Absolute/true zero"
},
{
"code": null,
"e": 2853,
"s": 2791,
"text": "For example, in distance 10 miles is twice as long as 5 mile."
},
{
"code": null,
"e": 2877,
"s": 2853,
"text": "Engineering Mathematics"
},
{
"code": null,
"e": 2882,
"s": 2877,
"text": "Misc"
},
{
"code": null,
"e": 2887,
"s": 2882,
"text": "Misc"
},
{
"code": null,
"e": 2892,
"s": 2887,
"text": "Misc"
},
{
"code": null,
"e": 2990,
"s": 2892,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3053,
"s": 2990,
"text": "Relationship between number of nodes and height of binary tree"
},
{
"code": null,
"e": 3075,
"s": 3053,
"text": "Inequalities in LaTeX"
},
{
"code": null,
"e": 3114,
"s": 3075,
"text": "Mathematics | The Pigeonhole Principle"
},
{
"code": null,
"e": 3152,
"s": 3114,
"text": "Number of Possible Super Keys in DBMS"
},
{
"code": null,
"e": 3180,
"s": 3152,
"text": "Various Implicants in K-Map"
},
{
"code": null,
"e": 3241,
"s": 3180,
"text": "Overview of Data Structures | Set 1 (Linear Data Structures)"
},
{
"code": null,
"e": 3282,
"s": 3241,
"text": "Top 10 algorithms in Interview Questions"
},
{
"code": null,
"e": 3336,
"s": 3282,
"text": "vector::push_back() and vector::pop_back() in C++ STL"
},
{
"code": null,
"e": 3367,
"s": 3336,
"text": "Program for nth Catalan Number"
}
] |
Queries for bitwise AND in the index range [L, R] of the given array
|
26 Nov, 2021
Given an array arr[] of N and Q queries consisting of a range [L, R]. the task is to find the bit-wise AND of all the elements of in that index range.Examples:
Input: arr[] = {1, 3, 1, 2, 3, 4}, q[] = {{0, 1}, {3, 5}} Output: 1 0 1 AND 3 = 1 2 AND 3 AND 4 = 0Input: arr[] = {1, 2, 3, 4, 5}, q[] = {{0, 4}, {1, 3}} Output: 0 0
Naive approach: Iterate through the range and find bit-wise AND of all the numbers in that range. This will take O(n) time for each query.Efficient approach: If we look at the integers as binary number, we can easily see that condition for ith bit of our answer to be set is that ith bit of all the integers in the range [L, R] should be set. So, we will calculate prefix-count for each bit. We will use this to find the number of integers in the range with ith bit set. If it is equal to the size of the range then the ith bit of our answer will also be set.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>#define MAX 100000#define bitscount 32using namespace std; // Array to store bit-wise// prefix countint prefix_count[bitscount][MAX]; // Function to find the prefix sumvoid findPrefixCount(int arr[], int n){ // Loop for each bit for (int i = 0; i < bitscount; i++) { // Loop to find prefix count prefix_count[i][0] = ((arr[0] >> i) & 1); for (int j = 1; j < n; j++) { prefix_count[i][j] = ((arr[j] >> i) & 1); prefix_count[i][j] += prefix_count[i][j - 1]; } }} // Function to answer queryint rangeAnd(int l, int r){ // To store the answer int ans = 0; // Loop for each bit for (int i = 0; i < bitscount; i++) { // To store the number of variables // with ith bit set int x; if (l == 0) x = prefix_count[i][r]; else x = prefix_count[i][r] - prefix_count[i][l - 1]; // Condition for ith bit // of answer to be set if (x == r - l + 1) ans = (ans | (1 << i)); } return ans;} // Driver codeint main(){ int arr[] = { 7, 5, 3, 5, 2, 3 }; int n = sizeof(arr) / sizeof(int); findPrefixCount(arr, n); int queries[][2] = { { 1, 3 }, { 4, 5 } }; int q = sizeof(queries) / sizeof(queries[0]); for (int i = 0; i < q; i++) cout << rangeAnd(queries[i][0], queries[i][1]) << endl; return 0;}
// Java implementation of the approachimport java.io.*; class GFG{ static int MAX = 100000;static int bitscount =32; // Array to store bit-wise// prefix countstatic int [][]prefix_count = new int [bitscount][MAX]; // Function to find the prefix sumstatic void findPrefixCount(int arr[], int n){ // Loop for each bit for (int i = 0; i < bitscount; i++) { // Loop to find prefix count prefix_count[i][0] = ((arr[0] >> i) & 1); for (int j = 1; j < n; j++) { prefix_count[i][j] = ((arr[j] >> i) & 1); prefix_count[i][j] += prefix_count[i][j - 1]; } }} // Function to answer querystatic int rangeAnd(int l, int r){ // To store the answer int ans = 0; // Loop for each bit for (int i = 0; i < bitscount; i++) { // To store the number of variables // with ith bit set int x; if (l == 0) x = prefix_count[i][r]; else x = prefix_count[i][r] - prefix_count[i][l - 1]; // Condition for ith bit // of answer to be set if (x == r - l + 1) ans = (ans | (1 << i)); } return ans;} // Driver codepublic static void main (String[] args){ int arr[] = { 7, 5, 3, 5, 2, 3 }; int n = arr.length; findPrefixCount(arr, n); int queries[][] = { { 1, 3 }, { 4, 5 } }; int q = queries.length; for (int i = 0; i < q; i++) System.out.println (rangeAnd(queries[i][0],queries[i][1])); }} // This code is contributed by ajit.
# Python3 implementation of the approach import numpy as np MAX = 100000bitscount = 32 # Array to store bit-wise# prefix countprefix_count = np.zeros((bitscount,MAX)); # Function to find the prefix sumdef findPrefixCount(arr, n) : # Loop for each bit for i in range(0, bitscount) : # Loop to find prefix count prefix_count[i][0] = ((arr[0] >> i) & 1); for j in range(1, n) : prefix_count[i][j] = ((arr[j] >> i) & 1); prefix_count[i][j] += prefix_count[i][j - 1]; # Function to answer querydef rangeOr(l, r) : # To store the answer ans = 0; # Loop for each bit for i in range(bitscount) : # To store the number of variables # with ith bit set x = 0; if (l == 0) : x = prefix_count[i][r]; else : x = prefix_count[i][r] - prefix_count[i][l - 1]; # Condition for ith bit # of answer to be set if (x == r - l + 1) : ans = (ans | (1 << i)); return ans; # Driver codeif __name__ == "__main__" : arr = [ 7, 5, 3, 5, 2, 3 ]; n = len(arr); findPrefixCount(arr, n); queries = [ [ 1, 3 ], [ 4, 5 ] ]; q = len(queries); for i in range(q) : print(rangeOr(queries[i][0], queries[i][1])); # This code is contributed by AnkitRai01
// C# implementation of the approachusing System; class GFG{ static int MAX = 100000;static int bitscount =32; // Array to store bit-wise// prefix countstatic int [,]prefix_count = new int [bitscount,MAX]; // Function to find the prefix sumstatic void findPrefixCount(int []arr, int n){ // Loop for each bit for (int i = 0; i < bitscount; i++) { // Loop to find prefix count prefix_count[i,0] = ((arr[0] >> i) & 1); for (int j = 1; j < n; j++) { prefix_count[i,j] = ((arr[j] >> i) & 1); prefix_count[i,j] += prefix_count[i,j - 1]; } }} // Function to answer querystatic int rangeAnd(int l, int r){ // To store the answer int ans = 0; // Loop for each bit for (int i = 0; i < bitscount; i++) { // To store the number of variables // with ith bit set int x; if (l == 0) x = prefix_count[i,r]; else x = prefix_count[i,r] - prefix_count[i,l - 1]; // Condition for ith bit // of answer to be set if (x == r - l + 1) ans = (ans | (1 << i)); } return ans;} // Driver codepublic static void Main (String[] args){ int []arr = { 7, 5, 3, 5, 2, 3 }; int n = arr.Length; findPrefixCount(arr, n); int [,]queries = { { 1, 3 }, { 4, 5 } }; int q = queries.GetLength(0); for (int i = 0; i < q; i++) Console.WriteLine(rangeAnd(queries[i,0],queries[i,1])); }} // This code contributed by Rajput-Ji
<script> // Javascript implementation of the approach let MAX = 100000; let bitscount =32; // Array to store bit-wise // prefix count let prefix_count = new Array(bitscount); for (let i = 0; i < bitscount; i++) { prefix_count[i] = new Array(MAX); for (let j = 0; j < MAX; j++) { prefix_count[i][j] = 0; } } // Function to find the prefix sum function findPrefixCount(arr, n) { // Loop for each bit for (let i = 0; i < bitscount; i++) { // Loop to find prefix count prefix_count[i][0] = ((arr[0] >> i) & 1); for (let j = 1; j < n; j++) { prefix_count[i][j] = ((arr[j] >> i) & 1); prefix_count[i][j] += prefix_count[i][j - 1]; } } } // Function to answer query function rangeAnd(l, r) { // To store the answer let ans = 0; // Loop for each bit for (let i = 0; i < bitscount; i++) { // To store the number of variables // with ith bit set let x; if (l == 0) x = prefix_count[i][r]; else x = prefix_count[i][r] - prefix_count[i][l - 1]; // Condition for ith bit // of answer to be set if (x == r - l + 1) ans = (ans | (1 << i)); } return ans; } let arr = [ 7, 5, 3, 5, 2, 3 ]; let n = arr.length; findPrefixCount(arr, n); let queries = [ [ 1, 3 ], [ 4, 5 ] ]; let q = queries.length; for (let i = 0; i < q; i++) document.write(rangeAnd(queries[i][0],queries[i][1]) + "</br>");</script>
1
2
Time complexity for pre-computation is O(n) and each query can be answered in O(1)
Auxiliary Space: O(bitcount * MAX)
ankthon
jit_t
Rajput-Ji
rameshtravel07
subhammahato348
array-range-queries
Bitwise-AND
Arrays
Bit Magic
Dynamic Programming
Arrays
Dynamic Programming
Bit Magic
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
Left Shift and Right Shift Operators in C/C++
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
How to swap two numbers without using a temporary variable?
Program to find whether a given number is power of 2
Little and Big Endian Mystery
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n26 Nov, 2021"
},
{
"code": null,
"e": 216,
"s": 54,
"text": "Given an array arr[] of N and Q queries consisting of a range [L, R]. the task is to find the bit-wise AND of all the elements of in that index range.Examples: "
},
{
"code": null,
"e": 384,
"s": 216,
"text": "Input: arr[] = {1, 3, 1, 2, 3, 4}, q[] = {{0, 1}, {3, 5}} Output: 1 0 1 AND 3 = 1 2 AND 3 AND 4 = 0Input: arr[] = {1, 2, 3, 4, 5}, q[] = {{0, 4}, {1, 3}} Output: 0 0 "
},
{
"code": null,
"e": 998,
"s": 386,
"text": "Naive approach: Iterate through the range and find bit-wise AND of all the numbers in that range. This will take O(n) time for each query.Efficient approach: If we look at the integers as binary number, we can easily see that condition for ith bit of our answer to be set is that ith bit of all the integers in the range [L, R] should be set. So, we will calculate prefix-count for each bit. We will use this to find the number of integers in the range with ith bit set. If it is equal to the size of the range then the ith bit of our answer will also be set.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1002,
"s": 998,
"text": "C++"
},
{
"code": null,
"e": 1007,
"s": 1002,
"text": "Java"
},
{
"code": null,
"e": 1015,
"s": 1007,
"text": "Python3"
},
{
"code": null,
"e": 1018,
"s": 1015,
"text": "C#"
},
{
"code": null,
"e": 1029,
"s": 1018,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>#define MAX 100000#define bitscount 32using namespace std; // Array to store bit-wise// prefix countint prefix_count[bitscount][MAX]; // Function to find the prefix sumvoid findPrefixCount(int arr[], int n){ // Loop for each bit for (int i = 0; i < bitscount; i++) { // Loop to find prefix count prefix_count[i][0] = ((arr[0] >> i) & 1); for (int j = 1; j < n; j++) { prefix_count[i][j] = ((arr[j] >> i) & 1); prefix_count[i][j] += prefix_count[i][j - 1]; } }} // Function to answer queryint rangeAnd(int l, int r){ // To store the answer int ans = 0; // Loop for each bit for (int i = 0; i < bitscount; i++) { // To store the number of variables // with ith bit set int x; if (l == 0) x = prefix_count[i][r]; else x = prefix_count[i][r] - prefix_count[i][l - 1]; // Condition for ith bit // of answer to be set if (x == r - l + 1) ans = (ans | (1 << i)); } return ans;} // Driver codeint main(){ int arr[] = { 7, 5, 3, 5, 2, 3 }; int n = sizeof(arr) / sizeof(int); findPrefixCount(arr, n); int queries[][2] = { { 1, 3 }, { 4, 5 } }; int q = sizeof(queries) / sizeof(queries[0]); for (int i = 0; i < q; i++) cout << rangeAnd(queries[i][0], queries[i][1]) << endl; return 0;}",
"e": 2520,
"s": 1029,
"text": null
},
{
"code": "// Java implementation of the approachimport java.io.*; class GFG{ static int MAX = 100000;static int bitscount =32; // Array to store bit-wise// prefix countstatic int [][]prefix_count = new int [bitscount][MAX]; // Function to find the prefix sumstatic void findPrefixCount(int arr[], int n){ // Loop for each bit for (int i = 0; i < bitscount; i++) { // Loop to find prefix count prefix_count[i][0] = ((arr[0] >> i) & 1); for (int j = 1; j < n; j++) { prefix_count[i][j] = ((arr[j] >> i) & 1); prefix_count[i][j] += prefix_count[i][j - 1]; } }} // Function to answer querystatic int rangeAnd(int l, int r){ // To store the answer int ans = 0; // Loop for each bit for (int i = 0; i < bitscount; i++) { // To store the number of variables // with ith bit set int x; if (l == 0) x = prefix_count[i][r]; else x = prefix_count[i][r] - prefix_count[i][l - 1]; // Condition for ith bit // of answer to be set if (x == r - l + 1) ans = (ans | (1 << i)); } return ans;} // Driver codepublic static void main (String[] args){ int arr[] = { 7, 5, 3, 5, 2, 3 }; int n = arr.length; findPrefixCount(arr, n); int queries[][] = { { 1, 3 }, { 4, 5 } }; int q = queries.length; for (int i = 0; i < q; i++) System.out.println (rangeAnd(queries[i][0],queries[i][1])); }} // This code is contributed by ajit.",
"e": 4075,
"s": 2520,
"text": null
},
{
"code": "# Python3 implementation of the approach import numpy as np MAX = 100000bitscount = 32 # Array to store bit-wise# prefix countprefix_count = np.zeros((bitscount,MAX)); # Function to find the prefix sumdef findPrefixCount(arr, n) : # Loop for each bit for i in range(0, bitscount) : # Loop to find prefix count prefix_count[i][0] = ((arr[0] >> i) & 1); for j in range(1, n) : prefix_count[i][j] = ((arr[j] >> i) & 1); prefix_count[i][j] += prefix_count[i][j - 1]; # Function to answer querydef rangeOr(l, r) : # To store the answer ans = 0; # Loop for each bit for i in range(bitscount) : # To store the number of variables # with ith bit set x = 0; if (l == 0) : x = prefix_count[i][r]; else : x = prefix_count[i][r] - prefix_count[i][l - 1]; # Condition for ith bit # of answer to be set if (x == r - l + 1) : ans = (ans | (1 << i)); return ans; # Driver codeif __name__ == \"__main__\" : arr = [ 7, 5, 3, 5, 2, 3 ]; n = len(arr); findPrefixCount(arr, n); queries = [ [ 1, 3 ], [ 4, 5 ] ]; q = len(queries); for i in range(q) : print(rangeOr(queries[i][0], queries[i][1])); # This code is contributed by AnkitRai01",
"e": 5443,
"s": 4075,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ static int MAX = 100000;static int bitscount =32; // Array to store bit-wise// prefix countstatic int [,]prefix_count = new int [bitscount,MAX]; // Function to find the prefix sumstatic void findPrefixCount(int []arr, int n){ // Loop for each bit for (int i = 0; i < bitscount; i++) { // Loop to find prefix count prefix_count[i,0] = ((arr[0] >> i) & 1); for (int j = 1; j < n; j++) { prefix_count[i,j] = ((arr[j] >> i) & 1); prefix_count[i,j] += prefix_count[i,j - 1]; } }} // Function to answer querystatic int rangeAnd(int l, int r){ // To store the answer int ans = 0; // Loop for each bit for (int i = 0; i < bitscount; i++) { // To store the number of variables // with ith bit set int x; if (l == 0) x = prefix_count[i,r]; else x = prefix_count[i,r] - prefix_count[i,l - 1]; // Condition for ith bit // of answer to be set if (x == r - l + 1) ans = (ans | (1 << i)); } return ans;} // Driver codepublic static void Main (String[] args){ int []arr = { 7, 5, 3, 5, 2, 3 }; int n = arr.Length; findPrefixCount(arr, n); int [,]queries = { { 1, 3 }, { 4, 5 } }; int q = queries.GetLength(0); for (int i = 0; i < q; i++) Console.WriteLine(rangeAnd(queries[i,0],queries[i,1])); }} // This code contributed by Rajput-Ji",
"e": 6980,
"s": 5443,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach let MAX = 100000; let bitscount =32; // Array to store bit-wise // prefix count let prefix_count = new Array(bitscount); for (let i = 0; i < bitscount; i++) { prefix_count[i] = new Array(MAX); for (let j = 0; j < MAX; j++) { prefix_count[i][j] = 0; } } // Function to find the prefix sum function findPrefixCount(arr, n) { // Loop for each bit for (let i = 0; i < bitscount; i++) { // Loop to find prefix count prefix_count[i][0] = ((arr[0] >> i) & 1); for (let j = 1; j < n; j++) { prefix_count[i][j] = ((arr[j] >> i) & 1); prefix_count[i][j] += prefix_count[i][j - 1]; } } } // Function to answer query function rangeAnd(l, r) { // To store the answer let ans = 0; // Loop for each bit for (let i = 0; i < bitscount; i++) { // To store the number of variables // with ith bit set let x; if (l == 0) x = prefix_count[i][r]; else x = prefix_count[i][r] - prefix_count[i][l - 1]; // Condition for ith bit // of answer to be set if (x == r - l + 1) ans = (ans | (1 << i)); } return ans; } let arr = [ 7, 5, 3, 5, 2, 3 ]; let n = arr.length; findPrefixCount(arr, n); let queries = [ [ 1, 3 ], [ 4, 5 ] ]; let q = queries.length; for (let i = 0; i < q; i++) document.write(rangeAnd(queries[i][0],queries[i][1]) + \"</br>\");</script>",
"e": 8736,
"s": 6980,
"text": null
},
{
"code": null,
"e": 8740,
"s": 8736,
"text": "1\n2"
},
{
"code": null,
"e": 8825,
"s": 8742,
"text": "Time complexity for pre-computation is O(n) and each query can be answered in O(1)"
},
{
"code": null,
"e": 8861,
"s": 8825,
"text": "Auxiliary Space: O(bitcount * MAX) "
},
{
"code": null,
"e": 8869,
"s": 8861,
"text": "ankthon"
},
{
"code": null,
"e": 8875,
"s": 8869,
"text": "jit_t"
},
{
"code": null,
"e": 8885,
"s": 8875,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 8900,
"s": 8885,
"text": "rameshtravel07"
},
{
"code": null,
"e": 8916,
"s": 8900,
"text": "subhammahato348"
},
{
"code": null,
"e": 8936,
"s": 8916,
"text": "array-range-queries"
},
{
"code": null,
"e": 8948,
"s": 8936,
"text": "Bitwise-AND"
},
{
"code": null,
"e": 8955,
"s": 8948,
"text": "Arrays"
},
{
"code": null,
"e": 8965,
"s": 8955,
"text": "Bit Magic"
},
{
"code": null,
"e": 8985,
"s": 8965,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 8992,
"s": 8985,
"text": "Arrays"
},
{
"code": null,
"e": 9012,
"s": 8992,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 9022,
"s": 9012,
"text": "Bit Magic"
},
{
"code": null,
"e": 9120,
"s": 9022,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9188,
"s": 9120,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 9232,
"s": 9188,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 9264,
"s": 9232,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 9312,
"s": 9264,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 9326,
"s": 9312,
"text": "Linear Search"
},
{
"code": null,
"e": 9372,
"s": 9326,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 9440,
"s": 9372,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 9500,
"s": 9440,
"text": "How to swap two numbers without using a temporary variable?"
},
{
"code": null,
"e": 9553,
"s": 9500,
"text": "Program to find whether a given number is power of 2"
}
] |
Linear Convolution using C and MATLAB
|
13 Jul, 2021
A key concept often introduced to those pursuing electronics engineering is Linear Convolution. This is a crucial component of Digital Signal Processing and Signals and Systems. Keeping general interest and academic implications in mind, this article introduces the concept and its applications and implements it using C and MATLAB.
Convolution: When speaking purely mathematically, convolution is the process by which one may compute the overlap of two graphs. In fact, convolution is also interpreted as the area shared by the two graphs over time. Metaphorically, it is a blend between the two functions as one passes over the other. So, given two functions F(n) and G(n), the convolution of the two is expressed and given by the following mathematical expression:
or
So, clearly intuitive as it looks, we must account for TIME. Convolution involves functions that blend over time. This is introduced in the expression using the time shift i.e., g(t-u) is g(t) shifted to the right ‘u’ times). Additionally, how we characterize this time is also important. Before proceeding further, let us compile the prerequisites involved:
Functions: Mathematically, we look at functions or graphs. However, it is important to note that the practical equivalent here is a Signal. We deal with the convolution of 2 signals.
LTI Systems: Linear Time-Invariant Systems are systems or processes which produce a Linear and a Time-Invariant output i.e., the output satisfies Linearity (superposition rule) and does not change with time. Convolution is the relation between the input and output of an LTI system.
Impulse Response: An impulse response is what you usually get if the system in consideration is subjected to a short-duration time-domain signal. Different LTI systems have different impulse responses.
Time System: We may use Continuous-Time signals or Discrete-Time signals. It is assumed the difference is known and understood to readers. Convolution may be defined for CT and DT signals.
Linear Convolution: Linear Convolution is a means by which one may relate the output and input of an LTI system given the system’s impulse response. Clearly, it is required to convolve the input signal with the impulse response of the system. Using the expression earlier, the following equation can be formed-
The reason why the expression is summed an infinite number of times is just to ensure that the probability of the two functions overlapping is 1. The impulse response is time-shifted endlessly so that during some duration of time, the two functions will certainly overlap. It may seem it would be careless on behalf of the programmer to run an infinite loop – the code may continue to execute for as long as the two functions do not overlap.
The solution lies in the fact LTI systems are being used. Since the functions do not change their values/shape over time (time-invariant), they can simply be slid closer to each other. Remember only the output is required, and it is not important ‘when’ the output is received. All manual calculations also depend on the same idea.
Explanation: Here’s one technique that may be used while calculating the output:
Take the input signal and impulse response as two separate single-row matrices.
The first element of the impulse response is multiplied with every element of the input signal. This result is stored.
The second element of the impulse response is multiplied with every element of the input signal. The result is shifted by one step to the right and stored.
The above two steps are done for the remaining elements in the impulse response.
Once all elements have been multiplied, align all the results under one another. Refer to the figure below.
Vertically, add all the elements in each column.
The resulting single row matrix is the convolved output.
Approach:
Obtain the input signal and the impulse response as two distinct arrays.
Obtain a time index sequence. The Time Index Sequence is a way by which MATLAB is informed about when our functions start. It starts at 0 by default i.e., [0 1 2 3 ........]. The 2nd sequence or the impulse response, however, needn’t begin at the same time. One can choose to delay it or start it earlier. If it is introduced earlier by a second, then its Time Index Sequence should be input as [ -1 0 1 2 .......].
Use user-defined functions. The function findconv() defines how the length of the output is calculated. Define ‘ny‘ as the length of our x-axis in output. It is earlier defined as an array starting from ‘nybegin‘ and extending till ‘nyend‘. The function calconv() is referenced in findconv() and calculates the actual output sequentially by taking different values of k and n, using 2 distinct for loops.
For each value of n, the sum of outputs is calculated by taking a different X(k) value in each iteration.
This result is stored in an array – y(n).
Plot the result. The function stem() is used while plotting due to the fact that the input is DISCRETE in nature. If a continuous-time output were to be plotted, it wouldn’t make any sense to use stem() as it would make it appear that the output is sampled. It is recommended to use plot(x_axis, y_axis) when plotting continuous values.
Note: DO NOT vary the lengths of the time index sequence and the 1st and 2nd sequences. The stem() returns an error indicating that it is not able to establish the length of the x-axis in the output.
Below is the Matlab program to implement the above approach:
Matlab
% Matlab program to implement% the above approachclc;x = input('Enter the 1st sequence: ');nx = input('Enter the Time Index sequence: ');h = input('Enter the second sequence: ');nh = input('Enter the Time Index sequence: '); % Sending parameters to a separate function[y, ny] = findconv(x, nx, h, nh); figure;stem(ny, y);xlabel('Time');ylabel('Amplitude');title('Linear Convolution');disp(y);disp(ny); % Function to find the length of our outputfunction [y, ny] = findconv(x, nx, h, nh) nybegin = nx(1) + nh(1); nyend = nx(length(nx)) + nh(length(nh)); ny = nybegin : nyend; % Calling a function within a function y = calconv(x, h);end % Here is where the summation is calculatedfunction [y] = calconv(x, h) l1 = length(x); l2 = length(h); N = l1 + l2 - 1; for n = 1 : 1 : N y(n) = 0; for k = 1 : 1 : l1 if(n - k + 1 >= 1 & n - k + 1 <= l2) y(n) = y(n) + x(k) * h(n - k + 1); end end endend
Input (any arbitrary set of numbers):
>> Enter the 1st Sequence: [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17]
>> Enter the Time Index sequence: [0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16]
>> Enter the second sequence: [1 2 2 1 4 5 2 2 1 1 4 5 2 2 1 2 2]
>> Enter the Time Index sequence: [0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16]
Output:
>> Columns 1 through 17
1 4 9 15 25 40 57 76 96 117 142 172 204 238 273 310 349
>> Columns 18 through 33
370 372 372 388 349 288 276 262 264 265 211 135 108 79 66 34
These are the input sequences. Note that they are Discrete-Time sequences.
The Output. This is also Discrete in time.
Note: Readers are encouraged to attempt the same using continuous-time signals. In those cases, the input is taken as a pre-defined continuous signal such as y = sin x. Also, use plot(x_axis, y_axis) and not stem(x_axis, y_axis).
Below is the C program to implement the above approach:
C
// C program for the above approach#include <math.h>#include <stdio.h> void calc_conv(int*, int*); // Chose any length. They must// all be equal though.int x[10], h[10], y[10]; int l1, l2 = 0; // Driver codevoid main(){ printf("Enter the length of " "the first sequence: "); scanf("%d", &l1); printf("Enter the length of the" " second sequence: "); scanf("%d", &l2); // Delegating calculation to a // separate function. calc_conv(l1, l2);} void calc_conv(int* len1, int* len2){ int l = (*len1) + (*len2) - 1; int i, j, n, k = 0; // Getting values of 1st sequence for (i = 0; i < *len1; i++) { scanf("%d", &x[i]); } // Getting values of 2nd sequence for (j = 0; j < *len2; j++) { scanf("%d", &h[i]); } for (n = 0; n < l; n++) { y[n] = 0; for (k = 0; k < len1; k++) { // To right shift the impulse if ((n - k) >= 0 && (n - k) < *len2) { // Main calculation y[n] = y[n] + x[k] * h[n - k]; } printf("%d\t", y[n]); } }}
Input:
Enter the length of the first sequence: 4
Enter the length of the second sequence: 4
Enter x[0]: 1
Enter x[1]: 2
Enter x[2]: 3
Enter x[3]: 4
Enter h[0]: 1
Enter h[1]: 2
Enter h[2]: 2
Enter h[3]: 1
Output:
1 4 9 15 16 11 4
C Language
C Programs
MATLAB
Project
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n13 Jul, 2021"
},
{
"code": null,
"e": 386,
"s": 53,
"text": "A key concept often introduced to those pursuing electronics engineering is Linear Convolution. This is a crucial component of Digital Signal Processing and Signals and Systems. Keeping general interest and academic implications in mind, this article introduces the concept and its applications and implements it using C and MATLAB."
},
{
"code": null,
"e": 821,
"s": 386,
"text": "Convolution: When speaking purely mathematically, convolution is the process by which one may compute the overlap of two graphs. In fact, convolution is also interpreted as the area shared by the two graphs over time. Metaphorically, it is a blend between the two functions as one passes over the other. So, given two functions F(n) and G(n), the convolution of the two is expressed and given by the following mathematical expression:"
},
{
"code": null,
"e": 824,
"s": 821,
"text": "or"
},
{
"code": null,
"e": 1183,
"s": 824,
"text": "So, clearly intuitive as it looks, we must account for TIME. Convolution involves functions that blend over time. This is introduced in the expression using the time shift i.e., g(t-u) is g(t) shifted to the right ‘u’ times). Additionally, how we characterize this time is also important. Before proceeding further, let us compile the prerequisites involved:"
},
{
"code": null,
"e": 1366,
"s": 1183,
"text": "Functions: Mathematically, we look at functions or graphs. However, it is important to note that the practical equivalent here is a Signal. We deal with the convolution of 2 signals."
},
{
"code": null,
"e": 1649,
"s": 1366,
"text": "LTI Systems: Linear Time-Invariant Systems are systems or processes which produce a Linear and a Time-Invariant output i.e., the output satisfies Linearity (superposition rule) and does not change with time. Convolution is the relation between the input and output of an LTI system."
},
{
"code": null,
"e": 1851,
"s": 1649,
"text": "Impulse Response: An impulse response is what you usually get if the system in consideration is subjected to a short-duration time-domain signal. Different LTI systems have different impulse responses."
},
{
"code": null,
"e": 2040,
"s": 1851,
"text": "Time System: We may use Continuous-Time signals or Discrete-Time signals. It is assumed the difference is known and understood to readers. Convolution may be defined for CT and DT signals."
},
{
"code": null,
"e": 2351,
"s": 2040,
"text": "Linear Convolution: Linear Convolution is a means by which one may relate the output and input of an LTI system given the system’s impulse response. Clearly, it is required to convolve the input signal with the impulse response of the system. Using the expression earlier, the following equation can be formed-"
},
{
"code": null,
"e": 2793,
"s": 2351,
"text": "The reason why the expression is summed an infinite number of times is just to ensure that the probability of the two functions overlapping is 1. The impulse response is time-shifted endlessly so that during some duration of time, the two functions will certainly overlap. It may seem it would be careless on behalf of the programmer to run an infinite loop – the code may continue to execute for as long as the two functions do not overlap."
},
{
"code": null,
"e": 3125,
"s": 2793,
"text": "The solution lies in the fact LTI systems are being used. Since the functions do not change their values/shape over time (time-invariant), they can simply be slid closer to each other. Remember only the output is required, and it is not important ‘when’ the output is received. All manual calculations also depend on the same idea."
},
{
"code": null,
"e": 3206,
"s": 3125,
"text": "Explanation: Here’s one technique that may be used while calculating the output:"
},
{
"code": null,
"e": 3286,
"s": 3206,
"text": "Take the input signal and impulse response as two separate single-row matrices."
},
{
"code": null,
"e": 3405,
"s": 3286,
"text": "The first element of the impulse response is multiplied with every element of the input signal. This result is stored."
},
{
"code": null,
"e": 3561,
"s": 3405,
"text": "The second element of the impulse response is multiplied with every element of the input signal. The result is shifted by one step to the right and stored."
},
{
"code": null,
"e": 3642,
"s": 3561,
"text": "The above two steps are done for the remaining elements in the impulse response."
},
{
"code": null,
"e": 3750,
"s": 3642,
"text": "Once all elements have been multiplied, align all the results under one another. Refer to the figure below."
},
{
"code": null,
"e": 3799,
"s": 3750,
"text": "Vertically, add all the elements in each column."
},
{
"code": null,
"e": 3856,
"s": 3799,
"text": "The resulting single row matrix is the convolved output."
},
{
"code": null,
"e": 3866,
"s": 3856,
"text": "Approach:"
},
{
"code": null,
"e": 3939,
"s": 3866,
"text": "Obtain the input signal and the impulse response as two distinct arrays."
},
{
"code": null,
"e": 4355,
"s": 3939,
"text": "Obtain a time index sequence. The Time Index Sequence is a way by which MATLAB is informed about when our functions start. It starts at 0 by default i.e., [0 1 2 3 ........]. The 2nd sequence or the impulse response, however, needn’t begin at the same time. One can choose to delay it or start it earlier. If it is introduced earlier by a second, then its Time Index Sequence should be input as [ -1 0 1 2 .......]."
},
{
"code": null,
"e": 4760,
"s": 4355,
"text": "Use user-defined functions. The function findconv() defines how the length of the output is calculated. Define ‘ny‘ as the length of our x-axis in output. It is earlier defined as an array starting from ‘nybegin‘ and extending till ‘nyend‘. The function calconv() is referenced in findconv() and calculates the actual output sequentially by taking different values of k and n, using 2 distinct for loops."
},
{
"code": null,
"e": 4866,
"s": 4760,
"text": "For each value of n, the sum of outputs is calculated by taking a different X(k) value in each iteration."
},
{
"code": null,
"e": 4908,
"s": 4866,
"text": "This result is stored in an array – y(n)."
},
{
"code": null,
"e": 5245,
"s": 4908,
"text": "Plot the result. The function stem() is used while plotting due to the fact that the input is DISCRETE in nature. If a continuous-time output were to be plotted, it wouldn’t make any sense to use stem() as it would make it appear that the output is sampled. It is recommended to use plot(x_axis, y_axis) when plotting continuous values."
},
{
"code": null,
"e": 5445,
"s": 5245,
"text": "Note: DO NOT vary the lengths of the time index sequence and the 1st and 2nd sequences. The stem() returns an error indicating that it is not able to establish the length of the x-axis in the output."
},
{
"code": null,
"e": 5506,
"s": 5445,
"text": "Below is the Matlab program to implement the above approach:"
},
{
"code": null,
"e": 5513,
"s": 5506,
"text": "Matlab"
},
{
"code": "% Matlab program to implement% the above approachclc;x = input('Enter the 1st sequence: ');nx = input('Enter the Time Index sequence: ');h = input('Enter the second sequence: ');nh = input('Enter the Time Index sequence: '); % Sending parameters to a separate function[y, ny] = findconv(x, nx, h, nh); figure;stem(ny, y);xlabel('Time');ylabel('Amplitude');title('Linear Convolution');disp(y);disp(ny); % Function to find the length of our outputfunction [y, ny] = findconv(x, nx, h, nh) nybegin = nx(1) + nh(1); nyend = nx(length(nx)) + nh(length(nh)); ny = nybegin : nyend; % Calling a function within a function y = calconv(x, h);end % Here is where the summation is calculatedfunction [y] = calconv(x, h) l1 = length(x); l2 = length(h); N = l1 + l2 - 1; for n = 1 : 1 : N y(n) = 0; for k = 1 : 1 : l1 if(n - k + 1 >= 1 & n - k + 1 <= l2) y(n) = y(n) + x(k) * h(n - k + 1); end end endend",
"e": 6502,
"s": 5513,
"text": null
},
{
"code": null,
"e": 6540,
"s": 6502,
"text": "Input (any arbitrary set of numbers):"
},
{
"code": null,
"e": 6831,
"s": 6540,
"text": ">> Enter the 1st Sequence: [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17]\n>> Enter the Time Index sequence: [0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16]\n>> Enter the second sequence: [1 2 2 1 4 5 2 2 1 1 4 5 2 2 1 2 2]\n>> Enter the Time Index sequence: [0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16]"
},
{
"code": null,
"e": 6839,
"s": 6831,
"text": "Output:"
},
{
"code": null,
"e": 7089,
"s": 6839,
"text": ">> Columns 1 through 17\n 1 4 9 15 25 40 57 76 96 117 142 172 204 238 273 310 349\n\n>> Columns 18 through 33\n\n 370 372 372 388 349 288 276 262 264 265 211 135 108 79 66 34"
},
{
"code": null,
"e": 7164,
"s": 7089,
"text": "These are the input sequences. Note that they are Discrete-Time sequences."
},
{
"code": null,
"e": 7207,
"s": 7164,
"text": "The Output. This is also Discrete in time."
},
{
"code": null,
"e": 7437,
"s": 7207,
"text": "Note: Readers are encouraged to attempt the same using continuous-time signals. In those cases, the input is taken as a pre-defined continuous signal such as y = sin x. Also, use plot(x_axis, y_axis) and not stem(x_axis, y_axis)."
},
{
"code": null,
"e": 7493,
"s": 7437,
"text": "Below is the C program to implement the above approach:"
},
{
"code": null,
"e": 7495,
"s": 7493,
"text": "C"
},
{
"code": "// C program for the above approach#include <math.h>#include <stdio.h> void calc_conv(int*, int*); // Chose any length. They must// all be equal though.int x[10], h[10], y[10]; int l1, l2 = 0; // Driver codevoid main(){ printf(\"Enter the length of \" \"the first sequence: \"); scanf(\"%d\", &l1); printf(\"Enter the length of the\" \" second sequence: \"); scanf(\"%d\", &l2); // Delegating calculation to a // separate function. calc_conv(l1, l2);} void calc_conv(int* len1, int* len2){ int l = (*len1) + (*len2) - 1; int i, j, n, k = 0; // Getting values of 1st sequence for (i = 0; i < *len1; i++) { scanf(\"%d\", &x[i]); } // Getting values of 2nd sequence for (j = 0; j < *len2; j++) { scanf(\"%d\", &h[i]); } for (n = 0; n < l; n++) { y[n] = 0; for (k = 0; k < len1; k++) { // To right shift the impulse if ((n - k) >= 0 && (n - k) < *len2) { // Main calculation y[n] = y[n] + x[k] * h[n - k]; } printf(\"%d\\t\", y[n]); } }}",
"e": 8622,
"s": 7495,
"text": null
},
{
"code": null,
"e": 8629,
"s": 8622,
"text": "Input:"
},
{
"code": null,
"e": 8826,
"s": 8629,
"text": "Enter the length of the first sequence: 4\nEnter the length of the second sequence: 4\nEnter x[0]: 1\nEnter x[1]: 2\nEnter x[2]: 3\nEnter x[3]: 4\nEnter h[0]: 1\nEnter h[1]: 2\nEnter h[2]: 2\nEnter h[3]: 1"
},
{
"code": null,
"e": 8834,
"s": 8826,
"text": "Output:"
},
{
"code": null,
"e": 8869,
"s": 8834,
"text": "1 4 9 15 16 11 4"
},
{
"code": null,
"e": 8880,
"s": 8869,
"text": "C Language"
},
{
"code": null,
"e": 8891,
"s": 8880,
"text": "C Programs"
},
{
"code": null,
"e": 8898,
"s": 8891,
"text": "MATLAB"
},
{
"code": null,
"e": 8906,
"s": 8898,
"text": "Project"
}
] |
How to make a timezone aware datetime object in Python
|
26 Sep, 2021
In this example, we are going to see how to make a timezone-aware DateTime object in Python.
Timezone-aware objects are Python DateTime or time objects that include timezone information. An aware object represents a specific moment in time that is not open to interpretation.
We can easily check if a datetime object is timezone-aware or not. For this, we will store the current date and time in a new variable using the datetime.now() function of datetime module.
Syntax: datetime.now(tz)
Parameters: tz : Specified time zone of which current time and date is required. (Uses Greenwich Meridian time by default.)
Then we will check the timezone information of the object stored in the tzinfo base class. tzinfo is an abstract base class for time zone information objects.
Python3
# Importing the datetime moduleimport datetime # Storing the current date and time in# a new variable using the datetime.now()# function of datetime modulecurrent_date = datetime.datetime.now() # Checking the timezone information of the# object stored in tzinfo base classif current_date.tzinfo == None or current_date.tzinfo.\ utcoffset(current_date) == None: # If passes the above condition then # the object is unaware print("Unaware")else: # Else printing "Aware" print("Aware")
Output:
Unaware
For this, we will store the current time in a new variable using the datetime.now().time() function of datetime module. Then we will replace the value of the timezone in the tzinfo class of the object using the replace() function. After that convert the date value into ISO 8601 format using the isoformat() method.
Syntax: isoformat(sep=’T’, timespec=’auto’)
Parameters:
sep: It is a one character separator placed between date and time.
timespec: Number of additional component of time to include
Code:
Python3
# Importing the datetime moduleimport datetime # Storing the current date and time in# a new variable using the datetime.now()# function of datetime modulecurrent_date = datetime.datetime.now() # Replacing the value of the timezone in tzinfo class of# the object using the replace() functioncurrent_date = current_date.\ replace(tzinfo=datetime.timezone.utc) # Converting the date value into ISO 8601# format using isoformat() methodcurrent_date = current_date.isoformat() # Printing the value of current_dateprint(current_date)
Output:
2021-08-30T09:45:43.291212+00:00
Now let’s check if the object is timezone aware or not using the method we used in the 1st section of the article.
Python3
# Importing the datetime moduleimport datetime # Storing the current date and time in# a new variable using the datetime.now()# function of datetime modulecurrent_date = datetime.datetime.now() # Replacing the value of the timezone in tzinfo class of# the object using the replace() functioncurrent_date = current_date.replace(tzinfo=datetime.timezone.utc) # Checking the timezone information of the# object stored in tzinfo base classif current_date.tzinfo == None or \current_date.tzinfo.utcoffset(current_date) == None: # If passes the above condition then # the object is unaware print("Unaware")else: # Else printing "Aware" print("Aware") # Converting the date value into ISO 8601# format using isoformat() methodcurrent_date = current_date.isoformat() # Printing the value of current_dateprint(current_date)
Output:
Aware
2021-08-30T09:55:15.111556+00:00
You can also use the pytz module to create timezone-aware objects.
For this, we will store the current date and time in a new variable using the datetime.now() function of datetime module and then we will add the timezone using timezone function of pytz module.
Python3
# Importing the datetime moduleimport datetimeimport pytz # Storing the current date and time in# a new variable using the datetime.now()# function of datetime module and adding the timezone# using timezone function of pytz module.current_date = datetime.datetime.now(pytz.timezone('Africa/Abidjan')) # Printing the value of current_dateprint(current_date)
Output:
2021-08-30 04:35:37.036990+00:00
Now let’s check if the object is timezone aware or not using the method we used in the 1st section of the article.
Python3
# Importing the datetime moduleimport datetimeimport pytz # Storing the current date and time in# a new variable using the datetime.now()# function of datetime module and adding the timezone# using timezone function of pytz module.current_date = datetime.datetime.now(pytz.timezone('Africa/Abidjan')) # Checking the timezone information of the# object stored in tzinfo base classif current_date.tzinfo == None or current_date.\tzinfo.utcoffset(current_date)== None: # If passes the above condition then # the object is unaware print("Unaware")else: # Else printing "Aware" print("Aware") # Printing the value of current_dateprint(current_date)
Output:
Aware
2021-08-30 04:46:40.670455+00:00
arorakashish0911
sweetyty
Picked
Python-datetime
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n26 Sep, 2021"
},
{
"code": null,
"e": 145,
"s": 52,
"text": "In this example, we are going to see how to make a timezone-aware DateTime object in Python."
},
{
"code": null,
"e": 328,
"s": 145,
"text": "Timezone-aware objects are Python DateTime or time objects that include timezone information. An aware object represents a specific moment in time that is not open to interpretation."
},
{
"code": null,
"e": 518,
"s": 328,
"text": "We can easily check if a datetime object is timezone-aware or not. For this, we will store the current date and time in a new variable using the datetime.now() function of datetime module."
},
{
"code": null,
"e": 543,
"s": 518,
"text": "Syntax: datetime.now(tz)"
},
{
"code": null,
"e": 667,
"s": 543,
"text": "Parameters: tz : Specified time zone of which current time and date is required. (Uses Greenwich Meridian time by default.)"
},
{
"code": null,
"e": 826,
"s": 667,
"text": "Then we will check the timezone information of the object stored in the tzinfo base class. tzinfo is an abstract base class for time zone information objects."
},
{
"code": null,
"e": 834,
"s": 826,
"text": "Python3"
},
{
"code": "# Importing the datetime moduleimport datetime # Storing the current date and time in# a new variable using the datetime.now()# function of datetime modulecurrent_date = datetime.datetime.now() # Checking the timezone information of the# object stored in tzinfo base classif current_date.tzinfo == None or current_date.tzinfo.\\ utcoffset(current_date) == None: # If passes the above condition then # the object is unaware print(\"Unaware\")else: # Else printing \"Aware\" print(\"Aware\")",
"e": 1345,
"s": 834,
"text": null
},
{
"code": null,
"e": 1353,
"s": 1345,
"text": "Output:"
},
{
"code": null,
"e": 1361,
"s": 1353,
"text": "Unaware"
},
{
"code": null,
"e": 1677,
"s": 1361,
"text": "For this, we will store the current time in a new variable using the datetime.now().time() function of datetime module. Then we will replace the value of the timezone in the tzinfo class of the object using the replace() function. After that convert the date value into ISO 8601 format using the isoformat() method."
},
{
"code": null,
"e": 1721,
"s": 1677,
"text": "Syntax: isoformat(sep=’T’, timespec=’auto’)"
},
{
"code": null,
"e": 1733,
"s": 1721,
"text": "Parameters:"
},
{
"code": null,
"e": 1800,
"s": 1733,
"text": "sep: It is a one character separator placed between date and time."
},
{
"code": null,
"e": 1860,
"s": 1800,
"text": "timespec: Number of additional component of time to include"
},
{
"code": null,
"e": 1866,
"s": 1860,
"text": "Code:"
},
{
"code": null,
"e": 1874,
"s": 1866,
"text": "Python3"
},
{
"code": "# Importing the datetime moduleimport datetime # Storing the current date and time in# a new variable using the datetime.now()# function of datetime modulecurrent_date = datetime.datetime.now() # Replacing the value of the timezone in tzinfo class of# the object using the replace() functioncurrent_date = current_date.\\ replace(tzinfo=datetime.timezone.utc) # Converting the date value into ISO 8601# format using isoformat() methodcurrent_date = current_date.isoformat() # Printing the value of current_dateprint(current_date)",
"e": 2406,
"s": 1874,
"text": null
},
{
"code": null,
"e": 2414,
"s": 2406,
"text": "Output:"
},
{
"code": null,
"e": 2447,
"s": 2414,
"text": "2021-08-30T09:45:43.291212+00:00"
},
{
"code": null,
"e": 2562,
"s": 2447,
"text": "Now let’s check if the object is timezone aware or not using the method we used in the 1st section of the article."
},
{
"code": null,
"e": 2570,
"s": 2562,
"text": "Python3"
},
{
"code": "# Importing the datetime moduleimport datetime # Storing the current date and time in# a new variable using the datetime.now()# function of datetime modulecurrent_date = datetime.datetime.now() # Replacing the value of the timezone in tzinfo class of# the object using the replace() functioncurrent_date = current_date.replace(tzinfo=datetime.timezone.utc) # Checking the timezone information of the# object stored in tzinfo base classif current_date.tzinfo == None or \\current_date.tzinfo.utcoffset(current_date) == None: # If passes the above condition then # the object is unaware print(\"Unaware\")else: # Else printing \"Aware\" print(\"Aware\") # Converting the date value into ISO 8601# format using isoformat() methodcurrent_date = current_date.isoformat() # Printing the value of current_dateprint(current_date)",
"e": 3406,
"s": 2570,
"text": null
},
{
"code": null,
"e": 3414,
"s": 3406,
"text": "Output:"
},
{
"code": null,
"e": 3453,
"s": 3414,
"text": "Aware\n2021-08-30T09:55:15.111556+00:00"
},
{
"code": null,
"e": 3520,
"s": 3453,
"text": "You can also use the pytz module to create timezone-aware objects."
},
{
"code": null,
"e": 3715,
"s": 3520,
"text": "For this, we will store the current date and time in a new variable using the datetime.now() function of datetime module and then we will add the timezone using timezone function of pytz module."
},
{
"code": null,
"e": 3723,
"s": 3715,
"text": "Python3"
},
{
"code": "# Importing the datetime moduleimport datetimeimport pytz # Storing the current date and time in# a new variable using the datetime.now()# function of datetime module and adding the timezone# using timezone function of pytz module.current_date = datetime.datetime.now(pytz.timezone('Africa/Abidjan')) # Printing the value of current_dateprint(current_date)",
"e": 4080,
"s": 3723,
"text": null
},
{
"code": null,
"e": 4088,
"s": 4080,
"text": "Output:"
},
{
"code": null,
"e": 4121,
"s": 4088,
"text": "2021-08-30 04:35:37.036990+00:00"
},
{
"code": null,
"e": 4236,
"s": 4121,
"text": "Now let’s check if the object is timezone aware or not using the method we used in the 1st section of the article."
},
{
"code": null,
"e": 4244,
"s": 4236,
"text": "Python3"
},
{
"code": "# Importing the datetime moduleimport datetimeimport pytz # Storing the current date and time in# a new variable using the datetime.now()# function of datetime module and adding the timezone# using timezone function of pytz module.current_date = datetime.datetime.now(pytz.timezone('Africa/Abidjan')) # Checking the timezone information of the# object stored in tzinfo base classif current_date.tzinfo == None or current_date.\\tzinfo.utcoffset(current_date)== None: # If passes the above condition then # the object is unaware print(\"Unaware\")else: # Else printing \"Aware\" print(\"Aware\") # Printing the value of current_dateprint(current_date)",
"e": 4910,
"s": 4244,
"text": null
},
{
"code": null,
"e": 4918,
"s": 4910,
"text": "Output:"
},
{
"code": null,
"e": 4957,
"s": 4918,
"text": "Aware\n2021-08-30 04:46:40.670455+00:00"
},
{
"code": null,
"e": 4974,
"s": 4957,
"text": "arorakashish0911"
},
{
"code": null,
"e": 4983,
"s": 4974,
"text": "sweetyty"
},
{
"code": null,
"e": 4990,
"s": 4983,
"text": "Picked"
},
{
"code": null,
"e": 5006,
"s": 4990,
"text": "Python-datetime"
},
{
"code": null,
"e": 5013,
"s": 5006,
"text": "Python"
}
] |
How to use NULL in MySQL SELECT statement?
|
In MySQL, the length of NULL is 0. Here, we will see how NULL can be used with SELECT
statement. Let us create a table with the help of CREATE command −
Creating a table −
mysql> CREATE table NullWIthSelect
-> (
-> Name varchar(100)
-> );
Query OK, 0 rows affected (0.62 sec)
Above, I have created a table successfully. Now I will insert some records with the help of
INSERT command −
Inserting records −
mysql> INSERT into NullWIthSelect values('John');
Query OK, 1 row affected (0.16 sec)
mysql> INSERT into NullWIthSelect values('Bob');
Query OK, 1 row affected (0.12 sec)
mysql> INSERT into NullWIthSelect values();
Query OK, 1 row affected (0.18 sec)
mysql> INSERT into NullWIthSelect values('Carol');
Query OK, 1 row affected (0.15 sec)
mysql> INSERT into NullWIthSelect values('');
Query OK, 1 row affected (0.16 sec)
mysql> INSERT into NullWIthSelect values('David');
Query OK, 1 row affected (0.19 sec)
mysql> INSERT into NullWIthSelect values();
Query OK, 1 row affected (0.08 sec)
Above, I have inserted 7 records in which one record has empty value and two have null values.
Rest of them has some values.
To display all the records, we can use the SELECT command −
mysql> SELECT * from NullWIthSelect;
The following is the output
+-------+
| Name |
+-------+
| John |
| Bob |
| NULL |
| Carol |
| |
| David |
| NULL |
+-------+
7 rows in set (0.00 sec)
Now, we can use NULL with SELECT statement as shown below.
Firstly, let us see the syntax −
SELECT * from yourTableNamet where column_name is NULL;
Applying the above query to know which column value is null. The query is as follows −
mysql> SELECT * from NullWIthSelect where Name is NULL;
The following is the output −
+------+
| Name |
+------+
| NULL |
| NULL |
+------+
2 rows in set (0.00 sec)
Now, we can get the length of NULL value that is 0. The query is as follows −
mysql> SELECT count(Name) from NullWIthSelect where Name is NULL;
The following is the output −
+-------------+
| count(Name) |
+-------------+
| 0 |
+-------------+
1 row in set (0.04 sec)
|
[
{
"code": null,
"e": 1340,
"s": 1187,
"text": "In MySQL, the length of NULL is 0. Here, we will see how NULL can be used with SELECT\nstatement. Let us create a table with the help of CREATE command −"
},
{
"code": null,
"e": 1359,
"s": 1340,
"text": "Creating a table −"
},
{
"code": null,
"e": 1463,
"s": 1359,
"text": "mysql> CREATE table NullWIthSelect\n-> (\n-> Name varchar(100)\n-> );\nQuery OK, 0 rows affected (0.62 sec)"
},
{
"code": null,
"e": 1572,
"s": 1463,
"text": "Above, I have created a table successfully. Now I will insert some records with the help of\nINSERT command −"
},
{
"code": null,
"e": 1592,
"s": 1572,
"text": "Inserting records −"
},
{
"code": null,
"e": 2185,
"s": 1592,
"text": "mysql> INSERT into NullWIthSelect values('John');\nQuery OK, 1 row affected (0.16 sec)\n\nmysql> INSERT into NullWIthSelect values('Bob');\nQuery OK, 1 row affected (0.12 sec)\n\nmysql> INSERT into NullWIthSelect values();\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> INSERT into NullWIthSelect values('Carol');\nQuery OK, 1 row affected (0.15 sec)\n\nmysql> INSERT into NullWIthSelect values('');\nQuery OK, 1 row affected (0.16 sec)\n\nmysql> INSERT into NullWIthSelect values('David');\nQuery OK, 1 row affected (0.19 sec)\n\nmysql> INSERT into NullWIthSelect values();\nQuery OK, 1 row affected (0.08 sec)"
},
{
"code": null,
"e": 2310,
"s": 2185,
"text": "Above, I have inserted 7 records in which one record has empty value and two have null values.\nRest of them has some values."
},
{
"code": null,
"e": 2370,
"s": 2310,
"text": "To display all the records, we can use the SELECT command −"
},
{
"code": null,
"e": 2408,
"s": 2370,
"text": "mysql> SELECT * from NullWIthSelect;\n"
},
{
"code": null,
"e": 2436,
"s": 2408,
"text": "The following is the output"
},
{
"code": null,
"e": 2571,
"s": 2436,
"text": "+-------+\n| Name |\n+-------+\n| John |\n| Bob |\n| NULL |\n| Carol |\n| |\n| David |\n| NULL |\n+-------+\n7 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2630,
"s": 2571,
"text": "Now, we can use NULL with SELECT statement as shown below."
},
{
"code": null,
"e": 2663,
"s": 2630,
"text": "Firstly, let us see the syntax −"
},
{
"code": null,
"e": 2720,
"s": 2663,
"text": "SELECT * from yourTableNamet where column_name is NULL;\n"
},
{
"code": null,
"e": 2807,
"s": 2720,
"text": "Applying the above query to know which column value is null. The query is as follows −"
},
{
"code": null,
"e": 2863,
"s": 2807,
"text": "mysql> SELECT * from NullWIthSelect where Name is NULL;"
},
{
"code": null,
"e": 2893,
"s": 2863,
"text": "The following is the output −"
},
{
"code": null,
"e": 2972,
"s": 2893,
"text": "+------+\n| Name |\n+------+\n| NULL |\n| NULL |\n+------+\n2 rows in set (0.00 sec)"
},
{
"code": null,
"e": 3050,
"s": 2972,
"text": "Now, we can get the length of NULL value that is 0. The query is as follows −"
},
{
"code": null,
"e": 3117,
"s": 3050,
"text": "mysql> SELECT count(Name) from NullWIthSelect where Name is NULL;\n"
},
{
"code": null,
"e": 3147,
"s": 3117,
"text": "The following is the output −"
},
{
"code": null,
"e": 3251,
"s": 3147,
"text": "+-------------+\n| count(Name) |\n+-------------+\n| 0 |\n+-------------+\n1 row in set (0.04 sec)"
}
] |
Java.util.Timer Class in Java
|
14 Nov, 2021
Timer class provides a method call that is used by a thread to schedule a task, such as running a block of code after some regular instant of time. Each task may be scheduled to run once or for a repeated number of executions. Each timer object is associated with a background thread that is responsible for the execution of all the tasks of a timer object. Note:
Timer class is thread-safe.
Timer class uses binary heap data structure in order to store its task.
Constructors:
Timer(): Creates a new timer
Timer(boolean isDaemon): Creates a new timer whose associated thread may be specified to run as a daemon
Timer(String name): Creates a new timer whose associated thread has the specified name
Timer(String name, boolean isDaemon): Creates a new timer whose associated thread has the specified name, and may be specified to run as a daemon
Declaration:
public class Timer
extends Object
Methods inherited from class java.lang.Object
clone
equals
finalize
getClass
hashCode
notify
notifyAll
toString
wait
Methods:
cancel(): java.util.Timer.cancel() Terminates this timer, discarding any currently scheduled tasks. Does not interfere with a currently executing task (if it exists). Once a timer has been terminated, its execution thread terminates gracefully, and no more tasks may be scheduled on it Syntax:
public void cancel()
purge(): java.util.Timer.purge() Removes all cancelled tasks from this timer’s task queue Syntax:
public int purge()
Returns:
the number of tasks removed from the queue
schedule(TimerTask task, Date time): java.util.Timer.schedule(TimerTask task, Date time) Schedules the specified task for execution at the specified time Syntax:
public void schedule(TimerTask task, Date time)
Parameters:
task - task to be scheduled.
time - time at which task is to be executed.
Throws:
IllegalArgumentException - if time.getTime() is negative.
IllegalStateException - if the task was already scheduled or cancelled,
the timer was cancelled, or timer thread terminated.
NullPointerException - if task or time is null
schedule(TimerTask task, Date firstTime, long period): java.util.Timer.schedule(TimerTask task, Date firstTime, long period) Schedules the specified task for repeated fixed-delay execution, beginning at the specified time Syntax:
public void schedule(TimerTask task, Date firstTime, long period)
Parameters:
task - task to be scheduled.
firstTime - First time at which task is to be executed.
period - time in milliseconds between successive task executions.
Throws:
IllegalArgumentException - if firstTime.getTime() < 0,
or period <= 0
IllegalStateException - if task was already scheduled
or cancelled, timer was cancelled,
or timer thread terminated.
NullPointerException - if task or firstTime is null
Java
// Java program to demonstrate//schedule method calls of Timer class import java.util.Timer;import java.util.TimerTask; class Helper extends TimerTask{ public static int i = 0; public void run() { System.out.println("Timer ran " + ++i); }} public class Test{ public static void main(String[] args) { Timer timer = new Timer(); TimerTask task = new Helper(); timer.schedule(task, 2000, 5000); }}
Output:
Timer ran 1
Timer ran 2
Timer ran 3
Timer ran 4
Timer ran 5
.
.
.
schedule(TimerTask task, long delay): java.util.Timer.schedule(TimerTask task, long delay) Schedules the specified task for execution after the specified delay Syntax:
public void schedule(TimerTask task, long delay)
Parameters:
task - task to be scheduled.
delay - delay in milliseconds before task is to be executed.
Throws:
IllegalArgumentException - if delay is negative,
or delay + System.currentTimeMillis() is negative.
IllegalStateException - if a task was already scheduled
or cancelled, the timer was cancelled,
or timer thread terminated.
NullPointerException - if task is null
schedule(TimerTask task, long delay, long period): java.util.Timer.schedule(TimerTask task, long delay, long period) Schedules the specified task for repeated fixed-delay execution, beginning after the specified delaySyntax:
public void schedule(TimerTask task, long delay, long period)
Parameters:
task - task to be scheduled.
delay - delay in milliseconds before task is to be executed.
period - time in milliseconds between successive task executions.
Throws:
IllegalArgumentException - if delay < 0,
or delay + System.currentTimeMillis() < 0, or
period <= 0
IllegalStateException - if task was already scheduled
or cancelled, timer was cancelled,
or timer thread terminated.
NullPointerException - if task is null
scheduleAtFixedRate(TimerTask task, Date firstTime, long period): java.util.Timer.scheduleAtFixedRate(TimerTask task, Date firstTime, long period) Schedules the specified task for repeated fixed-rate execution, beginning at the specified timeSyntax:
public void scheduleAtFixedRate(TimerTask task, Date firstTime, long period)
Parameters:
task - task to be scheduled.
firstTime - First time at which task is to be executed.
period - time in milliseconds between successive task executions.
Throws:
IllegalArgumentException - if firstTime.getTime() <
0 or period <= 0
IllegalStateException - if task was already scheduled
or cancelled, timer was cancelled,
or timer thread terminated.
NullPointerException - if task or firstTime is null
scheduleAtFixedRate(TimerTask task, long delay, long period): java.util.Timer.scheduleAtFixedRate(TimerTask task, long delay, long period) Schedules the specified task for repeated fixed-rate execution, beginning after the specified delaySyntax:
public void scheduleAtFixedRate(TimerTask task, long delay, long period)
Parameters:
task - task to be scheduled.
delay - delay in milliseconds before task is to be executed.
period - time in milliseconds between successive task executions.
Throws:
IllegalArgumentException - if delay < 0,
or delay + System.currentTimeMillis() < 0, or
period <= 0
IllegalStateException - if task was already
scheduled or cancelled, timer was cancelled,
or timer thread terminated.
NullPointerException - if task is null
Java
// Java program to demonstrate// scheduleAtFixedRate method of Timer class import java.util.Timer;import java.util.TimerTask;import java.util.*; class Helper extends TimerTask{ public static int i = 0; public void run() { System.out.println("Timer ran " + ++i); if(i == 4) { synchronized(Test.obj) { Test.obj.notify(); } } } } public class Test{ protected static Test obj; public static void main(String[] args) throws InterruptedException { obj = new Test(); //creating a new instance of timer class Timer timer = new Timer(); TimerTask task = new Helper(); //instance of date object for fixed-rate execution Date date = new Date(); timer.scheduleAtFixedRate(task, date, 5000); System.out.println("Timer running"); synchronized(obj) { //make the main thread wait obj.wait(); //once timer has scheduled the task 4 times, //main thread resumes //and terminates the timer timer.cancel(); //purge is used to remove all cancelled //tasks from the timer'stack queue System.out.println(timer.purge()); } }}
Output:
Timer running
Timer ran 1
Timer ran 2
Timer ran 3
Timer ran 4
0
Reference:
Oracle
This article is contributed by Mayank Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Akanksha_Rai
surinderdawra388
Java - util package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n14 Nov, 2021"
},
{
"code": null,
"e": 418,
"s": 53,
"text": "Timer class provides a method call that is used by a thread to schedule a task, such as running a block of code after some regular instant of time. Each task may be scheduled to run once or for a repeated number of executions. Each timer object is associated with a background thread that is responsible for the execution of all the tasks of a timer object. Note: "
},
{
"code": null,
"e": 446,
"s": 418,
"text": "Timer class is thread-safe."
},
{
"code": null,
"e": 518,
"s": 446,
"text": "Timer class uses binary heap data structure in order to store its task."
},
{
"code": null,
"e": 533,
"s": 518,
"text": "Constructors: "
},
{
"code": null,
"e": 562,
"s": 533,
"text": "Timer(): Creates a new timer"
},
{
"code": null,
"e": 667,
"s": 562,
"text": "Timer(boolean isDaemon): Creates a new timer whose associated thread may be specified to run as a daemon"
},
{
"code": null,
"e": 754,
"s": 667,
"text": "Timer(String name): Creates a new timer whose associated thread has the specified name"
},
{
"code": null,
"e": 900,
"s": 754,
"text": "Timer(String name, boolean isDaemon): Creates a new timer whose associated thread has the specified name, and may be specified to run as a daemon"
},
{
"code": null,
"e": 915,
"s": 900,
"text": "Declaration: "
},
{
"code": null,
"e": 957,
"s": 915,
"text": "public class Timer\n extends Object"
},
{
"code": null,
"e": 1003,
"s": 957,
"text": "Methods inherited from class java.lang.Object"
},
{
"code": null,
"e": 1009,
"s": 1003,
"text": "clone"
},
{
"code": null,
"e": 1016,
"s": 1009,
"text": "equals"
},
{
"code": null,
"e": 1025,
"s": 1016,
"text": "finalize"
},
{
"code": null,
"e": 1034,
"s": 1025,
"text": "getClass"
},
{
"code": null,
"e": 1043,
"s": 1034,
"text": "hashCode"
},
{
"code": null,
"e": 1050,
"s": 1043,
"text": "notify"
},
{
"code": null,
"e": 1060,
"s": 1050,
"text": "notifyAll"
},
{
"code": null,
"e": 1069,
"s": 1060,
"text": "toString"
},
{
"code": null,
"e": 1074,
"s": 1069,
"text": "wait"
},
{
"code": null,
"e": 1084,
"s": 1074,
"text": "Methods: "
},
{
"code": null,
"e": 1379,
"s": 1084,
"text": "cancel(): java.util.Timer.cancel() Terminates this timer, discarding any currently scheduled tasks. Does not interfere with a currently executing task (if it exists). Once a timer has been terminated, its execution thread terminates gracefully, and no more tasks may be scheduled on it Syntax: "
},
{
"code": null,
"e": 1400,
"s": 1379,
"text": "public void cancel()"
},
{
"code": null,
"e": 1499,
"s": 1400,
"text": "purge(): java.util.Timer.purge() Removes all cancelled tasks from this timer’s task queue Syntax: "
},
{
"code": null,
"e": 1570,
"s": 1499,
"text": "public int purge()\nReturns:\nthe number of tasks removed from the queue"
},
{
"code": null,
"e": 1733,
"s": 1570,
"text": "schedule(TimerTask task, Date time): java.util.Timer.schedule(TimerTask task, Date time) Schedules the specified task for execution at the specified time Syntax: "
},
{
"code": null,
"e": 2106,
"s": 1733,
"text": "public void schedule(TimerTask task, Date time)\nParameters:\ntask - task to be scheduled.\ntime - time at which task is to be executed.\nThrows:\nIllegalArgumentException - if time.getTime() is negative.\nIllegalStateException - if the task was already scheduled or cancelled, \nthe timer was cancelled, or timer thread terminated.\nNullPointerException - if task or time is null"
},
{
"code": null,
"e": 2337,
"s": 2106,
"text": "schedule(TimerTask task, Date firstTime, long period): java.util.Timer.schedule(TimerTask task, Date firstTime, long period) Schedules the specified task for repeated fixed-delay execution, beginning at the specified time Syntax: "
},
{
"code": null,
"e": 2816,
"s": 2337,
"text": "public void schedule(TimerTask task, Date firstTime, long period)\nParameters:\ntask - task to be scheduled.\nfirstTime - First time at which task is to be executed.\nperiod - time in milliseconds between successive task executions.\nThrows:\nIllegalArgumentException - if firstTime.getTime() < 0,\n or period <= 0\nIllegalStateException - if task was already scheduled \nor cancelled, timer was cancelled, \nor timer thread terminated.\nNullPointerException - if task or firstTime is null"
},
{
"code": null,
"e": 2821,
"s": 2816,
"text": "Java"
},
{
"code": "// Java program to demonstrate//schedule method calls of Timer class import java.util.Timer;import java.util.TimerTask; class Helper extends TimerTask{ public static int i = 0; public void run() { System.out.println(\"Timer ran \" + ++i); }} public class Test{ public static void main(String[] args) { Timer timer = new Timer(); TimerTask task = new Helper(); timer.schedule(task, 2000, 5000); }}",
"e": 3292,
"s": 2821,
"text": null
},
{
"code": null,
"e": 3301,
"s": 3292,
"text": "Output: "
},
{
"code": null,
"e": 3367,
"s": 3301,
"text": "Timer ran 1\nTimer ran 2\nTimer ran 3\nTimer ran 4\nTimer ran 5\n.\n.\n."
},
{
"code": null,
"e": 3536,
"s": 3367,
"text": "schedule(TimerTask task, long delay): java.util.Timer.schedule(TimerTask task, long delay) Schedules the specified task for execution after the specified delay Syntax: "
},
{
"code": null,
"e": 3959,
"s": 3536,
"text": "public void schedule(TimerTask task, long delay)\nParameters:\ntask - task to be scheduled.\ndelay - delay in milliseconds before task is to be executed.\nThrows:\nIllegalArgumentException - if delay is negative,\nor delay + System.currentTimeMillis() is negative.\nIllegalStateException - if a task was already scheduled \nor cancelled, the timer was cancelled, \nor timer thread terminated.\nNullPointerException - if task is null"
},
{
"code": null,
"e": 4186,
"s": 3959,
"text": "schedule(TimerTask task, long delay, long period): java.util.Timer.schedule(TimerTask task, long delay, long period) Schedules the specified task for repeated fixed-delay execution, beginning after the specified delaySyntax: "
},
{
"code": null,
"e": 4683,
"s": 4186,
"text": "public void schedule(TimerTask task, long delay, long period)\nParameters:\ntask - task to be scheduled.\ndelay - delay in milliseconds before task is to be executed.\nperiod - time in milliseconds between successive task executions.\nThrows:\nIllegalArgumentException - if delay < 0, \nor delay + System.currentTimeMillis() < 0, or \nperiod <= 0\nIllegalStateException - if task was already scheduled \nor cancelled, timer was cancelled, \nor timer thread terminated.\nNullPointerException - if task is null"
},
{
"code": null,
"e": 4935,
"s": 4683,
"text": "scheduleAtFixedRate(TimerTask task, Date firstTime, long period): java.util.Timer.scheduleAtFixedRate(TimerTask task, Date firstTime, long period) Schedules the specified task for repeated fixed-rate execution, beginning at the specified timeSyntax: "
},
{
"code": null,
"e": 5423,
"s": 4935,
"text": "public void scheduleAtFixedRate(TimerTask task, Date firstTime, long period)\nParameters:\ntask - task to be scheduled.\nfirstTime - First time at which task is to be executed.\nperiod - time in milliseconds between successive task executions.\nThrows:\nIllegalArgumentException - if firstTime.getTime() <\n0 or period <= 0\nIllegalStateException - if task was already scheduled\n or cancelled, timer was cancelled, \nor timer thread terminated.\nNullPointerException - if task or firstTime is null"
},
{
"code": null,
"e": 5671,
"s": 5423,
"text": "scheduleAtFixedRate(TimerTask task, long delay, long period): java.util.Timer.scheduleAtFixedRate(TimerTask task, long delay, long period) Schedules the specified task for repeated fixed-rate execution, beginning after the specified delaySyntax: "
},
{
"code": null,
"e": 6179,
"s": 5671,
"text": "public void scheduleAtFixedRate(TimerTask task, long delay, long period)\nParameters:\ntask - task to be scheduled.\ndelay - delay in milliseconds before task is to be executed.\nperiod - time in milliseconds between successive task executions.\nThrows:\nIllegalArgumentException - if delay < 0, \nor delay + System.currentTimeMillis() < 0, or \nperiod <= 0\nIllegalStateException - if task was already \nscheduled or cancelled, timer was cancelled, \nor timer thread terminated.\nNullPointerException - if task is null"
},
{
"code": null,
"e": 6184,
"s": 6179,
"text": "Java"
},
{
"code": "// Java program to demonstrate// scheduleAtFixedRate method of Timer class import java.util.Timer;import java.util.TimerTask;import java.util.*; class Helper extends TimerTask{ public static int i = 0; public void run() { System.out.println(\"Timer ran \" + ++i); if(i == 4) { synchronized(Test.obj) { Test.obj.notify(); } } } } public class Test{ protected static Test obj; public static void main(String[] args) throws InterruptedException { obj = new Test(); //creating a new instance of timer class Timer timer = new Timer(); TimerTask task = new Helper(); //instance of date object for fixed-rate execution Date date = new Date(); timer.scheduleAtFixedRate(task, date, 5000); System.out.println(\"Timer running\"); synchronized(obj) { //make the main thread wait obj.wait(); //once timer has scheduled the task 4 times, //main thread resumes //and terminates the timer timer.cancel(); //purge is used to remove all cancelled //tasks from the timer'stack queue System.out.println(timer.purge()); } }}",
"e": 7513,
"s": 6184,
"text": null
},
{
"code": null,
"e": 7522,
"s": 7513,
"text": "Output: "
},
{
"code": null,
"e": 7586,
"s": 7522,
"text": "Timer running\nTimer ran 1\nTimer ran 2\nTimer ran 3\nTimer ran 4\n0"
},
{
"code": null,
"e": 7599,
"s": 7586,
"text": "Reference: "
},
{
"code": null,
"e": 7606,
"s": 7599,
"text": "Oracle"
},
{
"code": null,
"e": 8026,
"s": 7606,
"text": "This article is contributed by Mayank Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 8039,
"s": 8026,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 8056,
"s": 8039,
"text": "surinderdawra388"
},
{
"code": null,
"e": 8076,
"s": 8056,
"text": "Java - util package"
},
{
"code": null,
"e": 8081,
"s": 8076,
"text": "Java"
},
{
"code": null,
"e": 8086,
"s": 8081,
"text": "Java"
}
] |
How to Convert Excel to XML Format in Python?
|
17 Feb, 2021
Python proves to be a powerful language when the requirement is to convert a file from one format to the other. It supports tools that can be employed to easily achieve the functionality. In this article, we’ll find out how we will convert from an Excel file to Extensible terminology (XML) files with Python.
OpenPyXL helps in interacting with Excel files. It can read and write to .xlsx and .xlsm files and can be installed as:
pip install openpyxl
Yattag is a Python library for generating HTML or XML documents with Python in a very readable way. This Yattag Library is pretty simple and easy to use library. If you are searching for any library in order to more easily generate HTML or XML documents.
pip install yattag
To load the contents of the Excel file load_workbook() method of OpenPyXl is used.
To iterate through loaded file and read data Iter_rows() with appropriate attributes is used
Syntax: Iter_rows(min_col, min_row, max_col, max_row, values_only)
Parameters:
min_col (int) – smallest column value (1-based index)
min_row (int) – smallest row value (1-based index)
max_col (int) – largest column value (1-based index)
Max_row (int) – largest row value (1-based index)
values_only (bool) – whether only cell values should be returned
The tagtext() method is a helper method that returns a triplet composed of:The Doc instance itselfThe tag method of the Doc instanceThe text method of the Doc instance
The Doc instance itself
The tag method of the Doc instance
The text method of the Doc instance
The asis method appends a string to the document without any form of escaping.
The tag method will accept any string as a tag name.
The indent function takes a string representing an XML or HTML document and returns a well-indented version of this document.
Database in use: Click here
To convert Excel data to XML first, it needs to be read, the given program explains the mechanism for reading data.
Approach
Import module
Load Excel file
Create sheet object
Iterate through rows
Example
Python3
# Install the openpyxl libraryfrom openpyxl import load_workbook # Loading our Excel filewb = load_workbook("demo_database.xlsx") # creating the sheet 1 objectws = wb.worksheets[0] # Iterating rows for getting the values of each rowfor row in ws.iter_rows(min_row=1, max_row=2, min_col=1, max_col=6): print([cell.value for cell in row])
Now, Once we are done with Reading data. Let’s Code how to convert Excel to XML format,
Approach:
Import module
Read data
Create XML format page
Append to file
Save file
Example:
Python3
from openpyxl import load_workbookfrom yattag import Doc, indent # Load our Excel Filewb = load_workbook("demo_database.xlsx")# Getting an object of active sheet 1ws = wb.worksheets[0] # Returning returns a tripletdoc, tag, text = Doc().tagtext() xml_header = '<?xml version="1.0" encoding="UTF-8"?>'xml_schema = '<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"></xs:schema>' # Appends the String to documentdoc.asis(xml_header)doc.asis(xml_schema) with tag('People'): for row in ws.iter_rows(min_row=2, max_row=10, min_col=1, max_col=6): row = [cell.value for cell in row] with tag("Person"): with tag("First_Name"): text(row[0]) with tag("Last_Name"): text(row[1]) with tag("Gender"): text(row[2]) with tag("Country"): text(row[3]) with tag("Age"): text(row[4]) with tag("Date"): text(row[5]) result = indent( doc.getvalue(), indentation=' ', indent_text=True) with open("output.xml", "w") as f: f.write(result)
Output: output.xml
Picked
Python-XML
Technical Scripter 2020
Python
Technical Scripter
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
Check if element exists in list in Python
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Defaultdict in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Feb, 2021"
},
{
"code": null,
"e": 339,
"s": 28,
"text": "Python proves to be a powerful language when the requirement is to convert a file from one format to the other. It supports tools that can be employed to easily achieve the functionality. In this article, we’ll find out how we will convert from an Excel file to Extensible terminology (XML) files with Python. "
},
{
"code": null,
"e": 459,
"s": 339,
"text": "OpenPyXL helps in interacting with Excel files. It can read and write to .xlsx and .xlsm files and can be installed as:"
},
{
"code": null,
"e": 480,
"s": 459,
"text": "pip install openpyxl"
},
{
"code": null,
"e": 735,
"s": 480,
"text": "Yattag is a Python library for generating HTML or XML documents with Python in a very readable way. This Yattag Library is pretty simple and easy to use library. If you are searching for any library in order to more easily generate HTML or XML documents."
},
{
"code": null,
"e": 754,
"s": 735,
"text": "pip install yattag"
},
{
"code": null,
"e": 837,
"s": 754,
"text": "To load the contents of the Excel file load_workbook() method of OpenPyXl is used."
},
{
"code": null,
"e": 930,
"s": 837,
"text": "To iterate through loaded file and read data Iter_rows() with appropriate attributes is used"
},
{
"code": null,
"e": 997,
"s": 930,
"text": "Syntax: Iter_rows(min_col, min_row, max_col, max_row, values_only)"
},
{
"code": null,
"e": 1009,
"s": 997,
"text": "Parameters:"
},
{
"code": null,
"e": 1063,
"s": 1009,
"text": "min_col (int) – smallest column value (1-based index)"
},
{
"code": null,
"e": 1114,
"s": 1063,
"text": "min_row (int) – smallest row value (1-based index)"
},
{
"code": null,
"e": 1167,
"s": 1114,
"text": "max_col (int) – largest column value (1-based index)"
},
{
"code": null,
"e": 1217,
"s": 1167,
"text": "Max_row (int) – largest row value (1-based index)"
},
{
"code": null,
"e": 1282,
"s": 1217,
"text": "values_only (bool) – whether only cell values should be returned"
},
{
"code": null,
"e": 1450,
"s": 1282,
"text": "The tagtext() method is a helper method that returns a triplet composed of:The Doc instance itselfThe tag method of the Doc instanceThe text method of the Doc instance"
},
{
"code": null,
"e": 1474,
"s": 1450,
"text": "The Doc instance itself"
},
{
"code": null,
"e": 1509,
"s": 1474,
"text": "The tag method of the Doc instance"
},
{
"code": null,
"e": 1545,
"s": 1509,
"text": "The text method of the Doc instance"
},
{
"code": null,
"e": 1624,
"s": 1545,
"text": "The asis method appends a string to the document without any form of escaping."
},
{
"code": null,
"e": 1677,
"s": 1624,
"text": "The tag method will accept any string as a tag name."
},
{
"code": null,
"e": 1803,
"s": 1677,
"text": "The indent function takes a string representing an XML or HTML document and returns a well-indented version of this document."
},
{
"code": null,
"e": 1832,
"s": 1803,
"text": "Database in use: Click here "
},
{
"code": null,
"e": 1948,
"s": 1832,
"text": "To convert Excel data to XML first, it needs to be read, the given program explains the mechanism for reading data."
},
{
"code": null,
"e": 1957,
"s": 1948,
"text": "Approach"
},
{
"code": null,
"e": 1971,
"s": 1957,
"text": "Import module"
},
{
"code": null,
"e": 1987,
"s": 1971,
"text": "Load Excel file"
},
{
"code": null,
"e": 2007,
"s": 1987,
"text": "Create sheet object"
},
{
"code": null,
"e": 2028,
"s": 2007,
"text": "Iterate through rows"
},
{
"code": null,
"e": 2036,
"s": 2028,
"text": "Example"
},
{
"code": null,
"e": 2044,
"s": 2036,
"text": "Python3"
},
{
"code": "# Install the openpyxl libraryfrom openpyxl import load_workbook # Loading our Excel filewb = load_workbook(\"demo_database.xlsx\") # creating the sheet 1 objectws = wb.worksheets[0] # Iterating rows for getting the values of each rowfor row in ws.iter_rows(min_row=1, max_row=2, min_col=1, max_col=6): print([cell.value for cell in row])",
"e": 2387,
"s": 2044,
"text": null
},
{
"code": null,
"e": 2476,
"s": 2387,
"text": "Now, Once we are done with Reading data. Let’s Code how to convert Excel to XML format, "
},
{
"code": null,
"e": 2486,
"s": 2476,
"text": "Approach:"
},
{
"code": null,
"e": 2500,
"s": 2486,
"text": "Import module"
},
{
"code": null,
"e": 2510,
"s": 2500,
"text": "Read data"
},
{
"code": null,
"e": 2533,
"s": 2510,
"text": "Create XML format page"
},
{
"code": null,
"e": 2548,
"s": 2533,
"text": "Append to file"
},
{
"code": null,
"e": 2558,
"s": 2548,
"text": "Save file"
},
{
"code": null,
"e": 2567,
"s": 2558,
"text": "Example:"
},
{
"code": null,
"e": 2575,
"s": 2567,
"text": "Python3"
},
{
"code": "from openpyxl import load_workbookfrom yattag import Doc, indent # Load our Excel Filewb = load_workbook(\"demo_database.xlsx\")# Getting an object of active sheet 1ws = wb.worksheets[0] # Returning returns a tripletdoc, tag, text = Doc().tagtext() xml_header = '<?xml version=\"1.0\" encoding=\"UTF-8\"?>'xml_schema = '<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"></xs:schema>' # Appends the String to documentdoc.asis(xml_header)doc.asis(xml_schema) with tag('People'): for row in ws.iter_rows(min_row=2, max_row=10, min_col=1, max_col=6): row = [cell.value for cell in row] with tag(\"Person\"): with tag(\"First_Name\"): text(row[0]) with tag(\"Last_Name\"): text(row[1]) with tag(\"Gender\"): text(row[2]) with tag(\"Country\"): text(row[3]) with tag(\"Age\"): text(row[4]) with tag(\"Date\"): text(row[5]) result = indent( doc.getvalue(), indentation=' ', indent_text=True) with open(\"output.xml\", \"w\") as f: f.write(result)",
"e": 3690,
"s": 2575,
"text": null
},
{
"code": null,
"e": 3709,
"s": 3690,
"text": "Output: output.xml"
},
{
"code": null,
"e": 3716,
"s": 3709,
"text": "Picked"
},
{
"code": null,
"e": 3727,
"s": 3716,
"text": "Python-XML"
},
{
"code": null,
"e": 3751,
"s": 3727,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 3758,
"s": 3751,
"text": "Python"
},
{
"code": null,
"e": 3777,
"s": 3758,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3875,
"s": 3777,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3907,
"s": 3875,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3934,
"s": 3907,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3955,
"s": 3934,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3978,
"s": 3955,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 4034,
"s": 3978,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 4076,
"s": 4034,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 4107,
"s": 4076,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 4149,
"s": 4107,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 4188,
"s": 4149,
"text": "Python | Get unique values from a list"
}
] |
PyQtGraph – Adding Qt Widgets with the Bar Graph
|
30 Nov, 2021
In this article we will see how we can add Qt widgets with the bar graph in the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) and second is to provide tools to aid in rapid application development (for example, property trees such as used in Qt Designer).A bar chart or bar graph is a chart or graph that presents categorical data with rectangular bars with heights or lengths proportional to the values that they represent. The bars can be plotted vertically or horizontally. A vertical bar chart is sometimes called a column chart. Qt have lots of multipurpose widgets which can be added with the bar graph so that it can become more interactive.We can create a plot window and bar graph with the help of commands given below
# creating a pyqtgraph plot window
window = pg.plot()
# creating a bar graph of green color
bargraph = pg.BarGraphItem(x=x, height=y1, width=0.6, brush='g')
In order to do this we have to do the following 1. Import the QWidgets from the PyQt5 2. Import the pyqtgraph module 3. Create the main window class 4. Add various feature to the main window class 5. Create different types of QtWidgets 6. Create a plot window in which bar graph is added 7. Create a grid layout and add different widgets and plot window to it 8. Set the layout widget as the central widget of the window
Below is the implementation
Python3
# importing Qt widgetsfrom PyQt5.QtWidgets import * import sys # importing pyqtgraph as pgimport pyqtgraph as pg class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("PyQtGraph") # setting geometry self.setGeometry(100, 100, 600, 500) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a widget object widget = QWidget() # creating a push button object btn = QPushButton('Push Button') # creating a line edit widget text = QLineEdit("Line Edit") # creating a check box widget check = QCheckBox("Check Box") # creating a plot window plot = pg.plot() # create list for y-axis y1 = [5, 5, 7, 10, 3, 8, 9, 1, 6, 2] # create horizontal list i.e x-axis x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # create pyqt5graph bar graph item # with width = 0.6 # with bar colors = green bargraph = pg.BarGraphItem(x = x, height = y1, width = 0.6, brush ='g') # add item to plot window # adding bargraph item to the plot window plot.addItem(bargraph) # Creating a grid layout layout = QGridLayout() # setting this layout to the widget widget.setLayout(layout) # adding widgets in the layout in their proper positions # button goes in upper-left layout.addWidget(btn, 0, 0) # text edit goes in middle-left layout.addWidget(text, 1, 0) # check box widget goes in bottom-left layout.addWidget(check, 3, 0) # plot window goes on right side, spanning 3 rows layout.addWidget(plot, 0, 1, 3, 1) # setting this widget as central widget of the main window self.setCentralWidget(widget) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
anikakapoor
Python-gui
Python-PyQt
Python-PyQtGraph
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Iterate over a list in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Nov, 2021"
},
{
"code": null,
"e": 977,
"s": 28,
"text": "In this article we will see how we can add Qt widgets with the bar graph in the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) and second is to provide tools to aid in rapid application development (for example, property trees such as used in Qt Designer).A bar chart or bar graph is a chart or graph that presents categorical data with rectangular bars with heights or lengths proportional to the values that they represent. The bars can be plotted vertically or horizontally. A vertical bar chart is sometimes called a column chart. Qt have lots of multipurpose widgets which can be added with the bar graph so that it can become more interactive.We can create a plot window and bar graph with the help of commands given below "
},
{
"code": null,
"e": 1135,
"s": 977,
"text": "# creating a pyqtgraph plot window\nwindow = pg.plot()\n\n# creating a bar graph of green color\nbargraph = pg.BarGraphItem(x=x, height=y1, width=0.6, brush='g')"
},
{
"code": null,
"e": 1558,
"s": 1135,
"text": "In order to do this we have to do the following 1. Import the QWidgets from the PyQt5 2. Import the pyqtgraph module 3. Create the main window class 4. Add various feature to the main window class 5. Create different types of QtWidgets 6. Create a plot window in which bar graph is added 7. Create a grid layout and add different widgets and plot window to it 8. Set the layout widget as the central widget of the window "
},
{
"code": null,
"e": 1587,
"s": 1558,
"text": "Below is the implementation "
},
{
"code": null,
"e": 1595,
"s": 1587,
"text": "Python3"
},
{
"code": "# importing Qt widgetsfrom PyQt5.QtWidgets import * import sys # importing pyqtgraph as pgimport pyqtgraph as pg class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"PyQtGraph\") # setting geometry self.setGeometry(100, 100, 600, 500) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a widget object widget = QWidget() # creating a push button object btn = QPushButton('Push Button') # creating a line edit widget text = QLineEdit(\"Line Edit\") # creating a check box widget check = QCheckBox(\"Check Box\") # creating a plot window plot = pg.plot() # create list for y-axis y1 = [5, 5, 7, 10, 3, 8, 9, 1, 6, 2] # create horizontal list i.e x-axis x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # create pyqt5graph bar graph item # with width = 0.6 # with bar colors = green bargraph = pg.BarGraphItem(x = x, height = y1, width = 0.6, brush ='g') # add item to plot window # adding bargraph item to the plot window plot.addItem(bargraph) # Creating a grid layout layout = QGridLayout() # setting this layout to the widget widget.setLayout(layout) # adding widgets in the layout in their proper positions # button goes in upper-left layout.addWidget(btn, 0, 0) # text edit goes in middle-left layout.addWidget(text, 1, 0) # check box widget goes in bottom-left layout.addWidget(check, 3, 0) # plot window goes on right side, spanning 3 rows layout.addWidget(plot, 0, 1, 3, 1) # setting this widget as central widget of the main window self.setCentralWidget(widget) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 3664,
"s": 1595,
"text": null
},
{
"code": null,
"e": 3674,
"s": 3664,
"text": "Output : "
},
{
"code": null,
"e": 3686,
"s": 3674,
"text": "anikakapoor"
},
{
"code": null,
"e": 3697,
"s": 3686,
"text": "Python-gui"
},
{
"code": null,
"e": 3709,
"s": 3697,
"text": "Python-PyQt"
},
{
"code": null,
"e": 3726,
"s": 3709,
"text": "Python-PyQtGraph"
},
{
"code": null,
"e": 3733,
"s": 3726,
"text": "Python"
},
{
"code": null,
"e": 3831,
"s": 3733,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3849,
"s": 3831,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3891,
"s": 3849,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3913,
"s": 3891,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3948,
"s": 3913,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 3974,
"s": 3948,
"text": "Python String | replace()"
},
{
"code": null,
"e": 4006,
"s": 3974,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4035,
"s": 4006,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 4062,
"s": 4035,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4083,
"s": 4062,
"text": "Python OOPs Concepts"
}
] |
Treap (A Randomized Binary Search Tree)
|
22 Mar, 2017
Like Red-Black and AVL Trees, Treap is a Balanced Binary Search Tree, but not guaranteed to have height as O(Log n). The idea is to use Randomization and Binary Heap property to maintain balance with high probability. The expected time complexity of search, insert and delete is O(Log n).
Every node of Treap maintains two values.1) Key Follows standard BST ordering (left is smaller and right is greater)2) Priority Randomly assigned value that follows Max-Heap property.
Basic Operation on Treap:Like other self-balancing Binary Search Trees, Treap uses rotations to maintain Max-Heap property during insertion and deletion.
T1, T2 and T3 are subtrees of the tree rooted with y (on left side)
or x (on right side)
y x
/ \ Right Rotation / \
x T3 – – – – – – – > T1 y
/ \ < - - - - - - - / \
T1 T2 Left Rotation T2 T3
Keys in both of the above trees follow the following order
keys(T1) < key(x) < keys(T2) < key(y) < keys(T3)
So BST property is not violated anywhere.
search(x)Perform standard BST Search to find x.
Insert(x):1) Create new node with key equals to x and value equals to a random value.2) Perform standard BST insert.3) Use rotations to make sure that inserted node's priority follows max heap property.
Delete(x):1) If node to be deleted is a leaf, delete it.2) Else replace node's priority with minus infinite ( -INF ), and do appropriate rotations to bring the node down to a leaf.
Refer Implementation of Treap Search, Insert and Delete for more details.
References:https://en.wikipedia.org/wiki/Treaphttps://courses.cs.washington.edu/courses/cse326/00wi/handouts/lecture19/sld017.htm
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Self-Balancing-BST
Advanced Data Structure
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
AVL Tree | Set 1 (Insertion)
Trie | (Insert and Search)
Agents in Artificial Intelligence
LRU Cache Implementation
Introduction of B-Tree
Red-Black Tree | Set 1 (Introduction)
Difference between B tree and B+ tree
Decision Tree Introduction with example
AVL Tree | Set 2 (Deletion)
Binary Indexed Tree or Fenwick Tree
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n22 Mar, 2017"
},
{
"code": null,
"e": 343,
"s": 54,
"text": "Like Red-Black and AVL Trees, Treap is a Balanced Binary Search Tree, but not guaranteed to have height as O(Log n). The idea is to use Randomization and Binary Heap property to maintain balance with high probability. The expected time complexity of search, insert and delete is O(Log n)."
},
{
"code": null,
"e": 527,
"s": 343,
"text": "Every node of Treap maintains two values.1) Key Follows standard BST ordering (left is smaller and right is greater)2) Priority Randomly assigned value that follows Max-Heap property."
},
{
"code": null,
"e": 681,
"s": 527,
"text": "Basic Operation on Treap:Like other self-balancing Binary Search Trees, Treap uses rotations to maintain Max-Heap property during insertion and deletion."
},
{
"code": null,
"e": 1205,
"s": 681,
"text": "T1, T2 and T3 are subtrees of the tree rooted with y (on left side) \nor x (on right side) \n y x\n / \\ Right Rotation / \\\n x T3 – – – – – – – > T1 y \n / \\ < - - - - - - - / \\\n T1 T2 Left Rotation T2 T3\nKeys in both of the above trees follow the following order \n keys(T1) < key(x) < keys(T2) < key(y) < keys(T3)\nSo BST property is not violated anywhere. "
},
{
"code": null,
"e": 1253,
"s": 1205,
"text": "search(x)Perform standard BST Search to find x."
},
{
"code": null,
"e": 1456,
"s": 1253,
"text": "Insert(x):1) Create new node with key equals to x and value equals to a random value.2) Perform standard BST insert.3) Use rotations to make sure that inserted node's priority follows max heap property."
},
{
"code": null,
"e": 1637,
"s": 1456,
"text": "Delete(x):1) If node to be deleted is a leaf, delete it.2) Else replace node's priority with minus infinite ( -INF ), and do appropriate rotations to bring the node down to a leaf."
},
{
"code": null,
"e": 1711,
"s": 1637,
"text": "Refer Implementation of Treap Search, Insert and Delete for more details."
},
{
"code": null,
"e": 1841,
"s": 1711,
"text": "References:https://en.wikipedia.org/wiki/Treaphttps://courses.cs.washington.edu/courses/cse326/00wi/handouts/lecture19/sld017.htm"
},
{
"code": null,
"e": 1966,
"s": 1841,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 1985,
"s": 1966,
"text": "Self-Balancing-BST"
},
{
"code": null,
"e": 2009,
"s": 1985,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 2107,
"s": 2009,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2136,
"s": 2107,
"text": "AVL Tree | Set 1 (Insertion)"
},
{
"code": null,
"e": 2163,
"s": 2136,
"text": "Trie | (Insert and Search)"
},
{
"code": null,
"e": 2197,
"s": 2163,
"text": "Agents in Artificial Intelligence"
},
{
"code": null,
"e": 2222,
"s": 2197,
"text": "LRU Cache Implementation"
},
{
"code": null,
"e": 2245,
"s": 2222,
"text": "Introduction of B-Tree"
},
{
"code": null,
"e": 2283,
"s": 2245,
"text": "Red-Black Tree | Set 1 (Introduction)"
},
{
"code": null,
"e": 2321,
"s": 2283,
"text": "Difference between B tree and B+ tree"
},
{
"code": null,
"e": 2361,
"s": 2321,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 2389,
"s": 2361,
"text": "AVL Tree | Set 2 (Deletion)"
}
] |
Scala List init() method with example
|
29 Jul, 2019
The init() method is utilized to find all the elements of the list except the last one.
Method Definition: def init: List[A]
Return Type: It returns all the elements of the list except the last one.
Example #1:
// Scala program of init()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a list val m1 = List(3, 6, 2, 9, 21) // Applying init method val result = m1.init // Displays output println(result) }}
List(3, 6, 2, 9)
Example #2:
// Scala program of init()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a list val m1 = List(3) // Applying init method val result = m1.init // Displays output println(result) }}
List()
Scala
Scala-list
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Class and Object in Scala
Scala Lists
Operators in Scala
Scala Constructors
Scala | Arrays
How to Install Scala with VSCode?
Enumeration in Scala
Lambda Expression in Scala
Scala String replace() method with example
How to get the first element of List in Scala
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Jul, 2019"
},
{
"code": null,
"e": 116,
"s": 28,
"text": "The init() method is utilized to find all the elements of the list except the last one."
},
{
"code": null,
"e": 153,
"s": 116,
"text": "Method Definition: def init: List[A]"
},
{
"code": null,
"e": 227,
"s": 153,
"text": "Return Type: It returns all the elements of the list except the last one."
},
{
"code": null,
"e": 239,
"s": 227,
"text": "Example #1:"
},
{
"code": "// Scala program of init()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a list val m1 = List(3, 6, 2, 9, 21) // Applying init method val result = m1.init // Displays output println(result) }} ",
"e": 568,
"s": 239,
"text": null
},
{
"code": null,
"e": 586,
"s": 568,
"text": "List(3, 6, 2, 9)\n"
},
{
"code": null,
"e": 598,
"s": 586,
"text": "Example #2:"
},
{
"code": "// Scala program of init()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a list val m1 = List(3) // Applying init method val result = m1.init // Displays output println(result) }} ",
"e": 914,
"s": 598,
"text": null
},
{
"code": null,
"e": 922,
"s": 914,
"text": "List()\n"
},
{
"code": null,
"e": 928,
"s": 922,
"text": "Scala"
},
{
"code": null,
"e": 939,
"s": 928,
"text": "Scala-list"
},
{
"code": null,
"e": 952,
"s": 939,
"text": "Scala-Method"
},
{
"code": null,
"e": 958,
"s": 952,
"text": "Scala"
},
{
"code": null,
"e": 1056,
"s": 958,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1082,
"s": 1056,
"text": "Class and Object in Scala"
},
{
"code": null,
"e": 1094,
"s": 1082,
"text": "Scala Lists"
},
{
"code": null,
"e": 1113,
"s": 1094,
"text": "Operators in Scala"
},
{
"code": null,
"e": 1132,
"s": 1113,
"text": "Scala Constructors"
},
{
"code": null,
"e": 1147,
"s": 1132,
"text": "Scala | Arrays"
},
{
"code": null,
"e": 1181,
"s": 1147,
"text": "How to Install Scala with VSCode?"
},
{
"code": null,
"e": 1202,
"s": 1181,
"text": "Enumeration in Scala"
},
{
"code": null,
"e": 1229,
"s": 1202,
"text": "Lambda Expression in Scala"
},
{
"code": null,
"e": 1272,
"s": 1229,
"text": "Scala String replace() method with example"
}
] |
Python Program to print digit pattern
|
16 Jun, 2022
The program must accept an integer N as the input. The program must print the desired pattern as shown in the example input/ output. Examples:
Input : 41325 Output : |**** |* |*** |** |***** Explanation: for a given integer print the number of *’s that are equivalent to each digit in the integer. Here the first digit is 4 so print four *sin the first line. The second digit is 1 so print one *. So on and the last i.e., the fifth digit is 5 hence print five *s in the fifth line. Input : 60710 Output : |****** | |******* |* |
Approach Read the input For each digit in the integer print the corresponding number of *s If the digit is 0 then print no *s and skip to the next line
Python3
# function to print the patterndef pattern(n): # traverse through the elements # in n assuming it as a string for i in n: # print | for every line print("|", end = "") # print i number of * s in # each line print("*" * int(i)) # get the input as string n = "41325"pattern(n)
|****
|*
|***
|**
|*****
Time complexity: O(n)Auxiliary Space: O(1)
Alternate solution that takes integer as input :
Python3
n = 41325x = []while n>0: x.append(n%10) n //= 10for i in range(len(x)-1,-1,-1): print('|'+x[i]*'*') # code contributed by Baivab Dash
|****
|*
|***
|**
|*****
Time complexity: O(n)Auxiliary Space: O(n)
dbaivab
hasani
pattern-printing
Python Pattern-printing
Python
Python Programs
School Programming
Technical Scripter
pattern-printing
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()
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": 53,
"s": 25,
"text": "\n16 Jun, 2022"
},
{
"code": null,
"e": 196,
"s": 53,
"text": "The program must accept an integer N as the input. The program must print the desired pattern as shown in the example input/ output. Examples:"
},
{
"code": null,
"e": 582,
"s": 196,
"text": "Input : 41325 Output : |**** |* |*** |** |***** Explanation: for a given integer print the number of *’s that are equivalent to each digit in the integer. Here the first digit is 4 so print four *sin the first line. The second digit is 1 so print one *. So on and the last i.e., the fifth digit is 5 hence print five *s in the fifth line. Input : 60710 Output : |****** | |******* |* |"
},
{
"code": null,
"e": 735,
"s": 582,
"text": "Approach Read the input For each digit in the integer print the corresponding number of *s If the digit is 0 then print no *s and skip to the next line "
},
{
"code": null,
"e": 743,
"s": 735,
"text": "Python3"
},
{
"code": "# function to print the patterndef pattern(n): # traverse through the elements # in n assuming it as a string for i in n: # print | for every line print(\"|\", end = \"\") # print i number of * s in # each line print(\"*\" * int(i)) # get the input as string n = \"41325\"pattern(n)",
"e": 1072,
"s": 743,
"text": null
},
{
"code": null,
"e": 1097,
"s": 1072,
"text": "|****\n|*\n|***\n|**\n|*****"
},
{
"code": null,
"e": 1140,
"s": 1097,
"text": "Time complexity: O(n)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1190,
"s": 1140,
"text": "Alternate solution that takes integer as input : "
},
{
"code": null,
"e": 1198,
"s": 1190,
"text": "Python3"
},
{
"code": "n = 41325x = []while n>0: x.append(n%10) n //= 10for i in range(len(x)-1,-1,-1): print('|'+x[i]*'*') # code contributed by Baivab Dash",
"e": 1342,
"s": 1198,
"text": null
},
{
"code": null,
"e": 1367,
"s": 1342,
"text": "|****\n|*\n|***\n|**\n|*****"
},
{
"code": null,
"e": 1410,
"s": 1367,
"text": "Time complexity: O(n)Auxiliary Space: O(n)"
},
{
"code": null,
"e": 1418,
"s": 1410,
"text": "dbaivab"
},
{
"code": null,
"e": 1425,
"s": 1418,
"text": "hasani"
},
{
"code": null,
"e": 1442,
"s": 1425,
"text": "pattern-printing"
},
{
"code": null,
"e": 1466,
"s": 1442,
"text": "Python Pattern-printing"
},
{
"code": null,
"e": 1473,
"s": 1466,
"text": "Python"
},
{
"code": null,
"e": 1489,
"s": 1473,
"text": "Python Programs"
},
{
"code": null,
"e": 1508,
"s": 1489,
"text": "School Programming"
},
{
"code": null,
"e": 1527,
"s": 1508,
"text": "Technical Scripter"
},
{
"code": null,
"e": 1544,
"s": 1527,
"text": "pattern-printing"
},
{
"code": null,
"e": 1642,
"s": 1544,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1660,
"s": 1642,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1702,
"s": 1660,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1724,
"s": 1702,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1759,
"s": 1724,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1785,
"s": 1759,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1828,
"s": 1785,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 1850,
"s": 1828,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 1889,
"s": 1850,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 1927,
"s": 1889,
"text": "Python | Convert a list to dictionary"
}
] |
Building an End-to-End Defect Classifier Application for Printed Circuit Boards | by Sean McClure | Towards Data Science
|
The Printed Circuit Board (PCB) is in most electronic products, mechanically supporting and connecting components along conductive tracks. Their prevalence underlies the modern electronics industry, with a world market exceeding $60 billion1.
PCBs are prone to a variety of defects that impede proper manufacturing, costing companies money. Defects such as shorts, spurs, mousebites, and pinholes cause issues like current leakage and open circuits, quickly degrading performance or rendering PCBs useless. PCB manufacturers must strive to ship defect-free units to remain competitive and ensure customer satisfaction.
Failure analysts are employed to ensure defects are kept to a minimum. But inspecting and diagnosing defects manually is challenging. There are multiple defects to detect, an extremely low tolerance for errors, and significant expertise required to reliably recognize and handle flawed units. Considering the time to train new analysts, and the cognitive load required to ensure reliability, an automated solution to detecting and classifying defects in PCBs is in demand.
In this article we will build a full PCB Defect Classifier that automates the task of detecting and classifying defects in printed circuit boards. I always encourage AI practitioners to build full products rather than throwing models over the fence to developers and other engineers. Your machine learning must exist in concert with a full application; thus only through its survival inside a holistic product can you be certain you’re building for users, not engineers.
Play the following video to see the application we will be building in this article:
In this article I will go over the application’s back-end and front-end code. I will walk through all of the code related to defect detection, extraction, and prediction. Thus the machine learning aspects will be covered in full. However I will only review the high-level aspects of the actual application pipeline code and front-end code, in order to keep this article to a reasonable size. Note that the entire application and its code are available on GitHub, thus readers have access to everything. I encourage others to clone and play with the project as they see fit.
This is always the best way to learn. I welcome questions in the comments section for those needing support (you can also @ me on Twitter so the support benefits others more publicly).
Let’s get started.
Google Colab
Flask
Deep Learning: fastai
Image Processing: tetryonai
User Interface: Azle
Notebook: PCB_Defect_Extraction_and_Classification.ipynb
Defect Turker: (for creating labelled image data)
PCB Defect Classifier: (automated visual inspection system and classifier)
There are a number of challenges we face when attempting to automate defect detection and classification2. A few of these were already mentioned in the introduction. The fuller list includes:
low tolerance for defects in units;
multiple defect types to account for;
low inference times required for automated solutions;
training data for ML models limited (usually narrow, domain-specific, and small);
traditional systems rely on hand-crafted features and significant expertise;
methods used by others often private.
We will need an approach that addresses these challenges while supporting a real-world application that effectively detects, extracts and predicts defect types in PCBs.
Given the challenges we face it makes sense to use a hybrid approach to build our classifier application, which combines the reference method and non-reference method.
Reference Method: the inspected PCB board (test board) is compared to a reference template image (template board) that has no defects, in order to allow analysts to identify differences.
Non-Reference Method: the inspected PCB board is checked for compliance against design principles, without relying on template images.
The reference method is relatively straightforward to implement but has large storage requirements (holding all the images). The non-reference method doesn’t suffer from storage issues, but can be limited in the number of defects found.
Building a product that automates both reference and non-reference methods may not cut down on storage and computational requirements, but if the manual detection and classification errors are reduced we gain massively from the increased and reliable throughput .
While we could attempt to train our deep learning model to classify the defects present on an entire board, this would be challenging. Take a look at the following example test and template PCB boards:
The board on the left is what our model needs to classify. We can see the individual defects by comparing to the template. But how likely is it that our model will be able to reliably classify a combination of defects? What would the class be called? How many unique defect combinations exist?
To lower the burden placed on our model we will first extract the individual defects from the test image. This can be accomplished by creating a differenced image and extracting the parts of the image that are different.
The following is the kind of differenced image we can produce using image processing in Python:
Notice the defects are highlighted in red. The above image doesn’t show all the defects since in this article we are only concerned with extracting 3 types. Capturing the other defect types of fairly trivial, and I will discuss this later.
Since we have a differenced image that highlights the defects in the test image we can also use image processing to extract the colored parts of the image:
This dramatically lowers the burden placed on our deep learning classifier. By extracting individual defects we convert the problem from a complex recognition problem into something akin to digit recognition (a problem that already works well with deep learning). This also means we are more likely to be successful using transfer learning, since there are numerous successful models in the OCR space. I will discuss transfer learning in more detail later on.
With this approach we can outline 5 major efforts:
DEFECT EXTRACTIONDEFECT LABELLINGDEFECT CLASSIFICATIONBUILDING A PCB DEFECT CLASSIFIER APPLICATIONRUNNING/TESTING THE APPLICATION
DEFECT EXTRACTION
DEFECT LABELLING
DEFECT CLASSIFICATION
BUILDING A PCB DEFECT CLASSIFIER APPLICATION
RUNNING/TESTING THE APPLICATION
Head on over to Google Colab and start a new Python 3 notebook. This will be our modeling environment. This is a Jupyter notebook environment that runs entirely in the cloud.
Google Colab allows access to an environment capable of running GPUs at no cost. Colab also makes installing and importing libraries a breeze. This is back-end as a service (BaaS), which helps (immensely) with rapid prototyping.
You have 2 options for getting the notebook into your own Google Colab environment.
You can simply upload the notebook contained in the GitHub project:
You can simply upload the notebook contained in the GitHub project:
2. Or you can mount a drive in Google Colab, clone the defect_classifier repo, and open the notebook from your Google drive.
2.1 Open New Python3 Notebook
2.2 Mount a Drive on Google Colab
Run the following in the first cell (play button, or shift-return on Mac):
You will be presented with a URL. Click it, get the auth code, return to your notebook and enter it. You now have access to your Google Drive inside Colab:
2.3 Clone Repo
...then copy the cloned notebook into your mounted drive:
2.4 Open Notebook from Drive
Now find the notebook inside your Google drive, as you would any other file, right-click, and choose open with Google Colab.
We will require Graphical Processing Units (GPU) to train our Deep Learning model in reasonable time. We can set the hardware acceleration in Colab by clicking on Runtime at the top, choosing Change runtime type, selecting GPU under hardware accelerator, and clicking SAVE.
First we need to build the defect extraction pipeline. To use less code I’ve created a small library that will abstract much of the image processing. I plan on continuing to add to this library going forward to stay tuned. For an intuitive yet detailed tutorial on creating libraries in R and Python see here.
Let’s import the library now:
The library is freely available on GitHub. We can install libraries from GitHub using pip as follows:
!pip install git+https://github.com/sean-mcclure/tetryon_ai.git
Note the ! before the usual pip command. This is the “bang” symbol commonly used when doing interactive computing. It allows our Google Colab environment to access the underlying shell.
We can now import the library:
from tetryonai.main import *
You can also click on the Files icon to the left so we can see the files we work with (click on Refresh as needed):
Let’s create folders to hold our differenced images, extracted defects, and the hold out images needed to test our model. We’ll use tetryonai’s directory function:
directory(**{ "choice" : "make", "directory_path" : "difference_img"})directory(**{ "choice" : "make", "directory_path" : "extracted_defects"})directory(**{ "choice" : "make", "directory_path" : "hold_out"})
We will need access to a large number of test and template PCB board images. These are available on GitHub3 via the DeepPCB project. This provides us with a large number of images obtained from a linear scan CCD. Review this project for more details.
Clone the DeepPCB project into your Colab environment by running the following in the next cell:
!git clone https://github.com/tangsanli5201/DeepPCB.git
Hit Refresh in the Files pane to see the new DeepPCB folder. You can expand through the folder to see just how many images are available.
For this project we will use only the group00041 set of temp and test images as shown above. These are the images previously described in Figures 1-3.
Let’s write some Python for storing the group00041 temp and test image paths from our DeepPCB folder inside a dict. We’ll then use this in the next step to difference our images:
Now we will use image processing to difference each pair of temp and test images using the paths specified inside the dict we just created. We also need to hold out a set of these images to test in our application. I will combine these operations into one codeblock for convenience:
We are using tetryonai’s copy_files function to copy the necessary files into the target_directory called hold_out that we created earlier. I am using a split_percentage of 20% for the hold out set. In the code above, once 20% of the images have been held out the remaining are subtracted using tetryonai’s subtract_images function.
If we Refresh our Files pane and inspect our difference_img and hold_out folders we will see the images placed as inspected. You can also open a few of the images inside difference_img to confirm the subtraction process worked (as was shown in Figure 2):
We are now ready to extract the highlighted defects that appear in the differenced images. We will use tetryonai’s extract_contours_from_image function to read in each differenced image, extract defects per image, and save the defects to the extracted_defects folder we created towards the beginning:
Images that are corrupt/non-readable will be skipped by the extract_contours_from_image function. This still leaves us with plenty of images to train our model.
The extract_contours_from_image function uses contours to extract the highlighted parts of our differenced images. Think of contours as a curve joining all the continuous points (along the boundary) that have the same color or intensity. Contours are a useful tool for shape analysis and object detection/recognition. You can read more about contours on OpenCV.
Refresh the Files pane and inspect the extracted_defects folder. You will notice individual folders have been created for each set of contours extracted from each differenced image.
We will now combine all the extracted defects into a single directory called all_extracts. Let’s make that directory now:
directory(**{ "choice" : "make", "directory_path" : "all_extracts"})
We write some Python to walk through the extracted_defects directory and move any PNG files using tetryonai’s move_files function:
Refreshing the Files pane and inspecting the all_extracts folder will reveal all extracted defects.
In PART 2 we will be applying labels to our extracted defects (“turking”). We thus need to download all extracted defect images to use with the labelling application we create next. So let’s zip all extracted defects for easy downloading:
!zip -r /content/extracted_defects.zip /content/all_extracts/
If you Refresh your Files pane you will see a new extracted_defects.zip file created.
Our labelling application will also require a JSON file with the filenames of the images in our zip folder. Let’s write some Python to grab all filenames in the all_extracts directory:
Save the JSON file we just created:
with open('extracted_defects.json', 'w') as outfile: json.dump(file_names_and_sizes, outfile)
Refresh the File pane and download both the extracted_defects.zip and extracted_defects.json files:
Save these files to your Desktop for now.
In PART I we differenced a large set of test and template PCB images, extracted defects in the differenced images using contours, and created the 2 files we need to use the labelling application we create next. Let’s do that now.
With our set of extracted defect images in hand we have a good-sized dataset to use for training a Deep Learning model for image classification. But like any supervised machine learning approach our training data requires labels. Since we extracted our images we obviously don’t have these labels available.
Image classification requires large amounts of labelled data, making hand-crafted labeling an arduous task. But the colossal data prerequisite to image classification often isn’t a show stopper. This is because there are a wealth of publicly-available models that have already been trained on large benchmark sets of images. As long as the domain isn’t too different we can use much less data to train a pre-trained model. Can we get away with successfully classifying our extracted defects using much less labelled data, paired with an existing image classifier?
My bet is yes, but there is only one way to find out. This is a good opportunity to build a new, general-purpose product. This product will allow us to create labels for a set of images.
TI won’t go through the steps for creating the Defect Turker since this article is already long enough. It’s a simple application that allows us to apply labels to any images that are inside its img folder.
Too often people rush to find existing solutions, with products that don’t address their true requirements. A lot of time (and money) ends up being wasted trying to force existing products to their specific set of challenges. Bespoke software development is immensely powerful, but only when it’s not inhibited by over-staffed projects and over-engineered solutions. Rapid prototyping is a massively beneficial skill.
We won’t do our labelling on Colab since it currently has no obvious way to host web applications inside its environment. We will thus run the Defect Turker locally.
The Defect Turker is available on GitHub. Clone the application onto your local machine by running the following in a terminal session:
git clone https://github.com/sean-mcclure/defect_turker.git
I also start a simple web service using the following line:
python3 -m http.server
Before opening our browser to the application let’s add the extracted defect images (extracted_defects.zip) and JSON file (extracted_defects.json) we created earlier to the application. These files are on my Desktop, so I’ll double-click the ZIP file to decompress it contents:
..and run the following line in a new tab in terminal, from inside the defect_turker directory:
mv ../content/all_extracts/* ../defect_turker/img/
Confirm our extracted defect images are inside the application’s img folder:
We also need the JSON file containing all image names. Move these now:
mv ../extracted_defects.json ../defect_turker/img/
We’re now ready to label our images. Let’s start the application. Since our web server is already up-and-running we simply point our browser to http://localhost:8000/.
If you need to change the port # on the web server you simply add the port to the end of the full command (e.g. python3 -m http.server 5555)
You should see the following:
Your first image will likely be something other than the one shown here. We can see there are 1333 total images. That’s a lot of labelling. I decided to break this up throughout the day and do a few hundred at a time. Ideally we would split this task among a few people on the team.
Product Idea: Create a version of this application that allows labelling to be done by multiple people, then recombines the results into a single CSV file.
The first icon is a legend showing the labels for each defect type. Refer to this to learn which defect has what label.
It turns out our image differencing only extracted 3 types of defects:
spur
spurious copper
short
The reason only 3 types were extracted has to do with how our image differencing was set up. We can easily detect the other types of defects as well, but I will keep our application to these 3 defect types for this article. See NOTES at the end for details.
Now we can start labelling:
Simply click on the button that corresponds to the label for the presented image. Once we have labelled all the images (or as many as you wish) we click on the upper right icon to download a CSV file that can be used to train our Deep Learning model.
The CSV file has each image name and the label we applied. Save the file as image_labels.csv and keep it on your Desktop for Part 3.
We’re now ready to train our Deep Learning PCB Classifier.
We move back to the Colab notebook to train our Deep Learning model using the CSV file we created with the Defect Turker. We will use fastai to train our Deep Learning model.
fast.ai, the research institute, is dedicated to making deep learning more accessible, via their courses, software, research and community. Their library fastai is a powerful open source API sitting on top of PyTorch. Recent research breakthroughs in Deep Learning are embedded into the fastai library meaning we get access to cutting-edge Deep Learning models that are more accurate and faster than many other DL libraries; all while writing much less code.
!pip install http://download.pytorch.org/whl/cpu/torch-1.0.0-cp36-cp36m-linux_x86_64.whl!pip install fastai
and import:
from fastai.vision import *
We will upload the image_labels.csv file created with the Defect Turker in Part 2. Run the following line in Colab to upload the file:
from google.colab import filesfiles.upload()
You may have to run this twice as the first run often fails.
We’ll now convert image_labels.csv to a data frame using tetryonai’s csv_to_dataframe function:
image_labels_frame = csv_to_dataframe(**{ "path_to_csv" : "image_labels.csv"})
Let’s check the class balance between our labels. First, we’ll get the number of examples of each label using tetryonai’s get_feature_counts function:
labelled_counts = get_feature_counts(**{ "data_frame" : image_labels_frame, "feature" : "label"})
...then use Matplotlib to create our plot:
...which gives:
Note: If “label” appears in the chart, run del labelled_counts[‘label’] in the cell prior to creating the visual.
We have a “majority class” of NOT, while the 3 defect types are fairly balanced. We could downsample the majority class but it may not be needed. We’ll go ahead and use our labelled data as is, and readjust the balance in our training data only if needed.
The fastai training approach we will use requires individual labelled CSV files for each class we want to predict. Let’s create a folder called training_csvs to hold these individual files:
directory(**{ "choice" : "make", "directory_path" : "training_csvs"})
...now let’s create individual CSV files for each class using the image_labels_frame dataframe we created from our uploaded image_labels.csv file.
First we create individual lists for each class:
...then we convert those lists into data frames for each class:
Now let’s create individual folders for the CSV files:
Now we can move the individual CSV files to their appropriate folders:
We obviously need images to train our image classifier. These will be the defect images we extracted in PART 1, zipped into the file called extracted_defects.zip, and added to our Defect Turker for labelling.
We could just use the extracted_defects.zip file that is currently in our Colab environment, but we may have restarted and rerun our pipeline from PART 1 if we are doing this project over a few days. This will obviously recreate our zipped image file making the filenames in our previously labelled CSV file (image_labels.csv) mismatch our zipped images filenames.
Given the above, let’s remove the extracted_defects.zip file currently in Colab and upload the extracted_defects.zip file we know we used with the Defect Turker.
Remove zipped images from Colab:
!rm extracted_defects.zip
Upload used for labelling:
files.upload()
Move extracted_defects.zip into training_csvs folder:
move_files(**{ "file_paths" : ["extracted_defects.zip"], "target_directory" : "training_csvs"})
Extract all images from extracted_defects.zip into the training_csvs folder:
import zipfilewith zipfile.ZipFile("training_csvs/extracted_defects.zip", 'r') as zip_ref: zip_ref.extractall("training_csvs/")
Now we can move all extracted defect images into their proper training folder, using the image_labels.csv file:
To clean up, let’s remove any remaining PNG files (defect images) that were not labelled:
directory(**{ "choice" : "remove", "directory_path" : "training_csvs/content", "force" : True})
We should inspect the image data to confirm they were read-in properly:
data.show_batch(rows=4, figsize=(7, 8))
We can see the labels match the images (the spur, spurious, short, and not_defect images all match the labels shown).
We are now ready to train our classifier. We need a fairly deep architecture if we are to get good enough results to create a product people use. Deep networks (large number of stacked layers) allow for deeper representations than their shallow counterparts and have been shown to perform very well on image recognition tasks.
We will download a pre-trained PyTorch model from torchvision. We want to use a pre-trained model to cut down on training time and CPU requirements. Pre-trained models have been trained on large benchmark datasets to solve problems similar to ours. This is called transfer learning.
The following figure shows the ResNet34 architecture we will use. This architecture is based off research discussed in this paper.
To download the pre-trained ResNet34 model from fastai we run the following:
from fastai.metrics import error_rate # 1 - accuracylearn = create_cnn(data, models.resnet34, metrics=error_rate)
Let’s train our model on our defect data.
By using a pre-trained model it means all the weights are already trained prior to our implementation. We refer to this kind of setup as a frozen model, which be default has “all” layers frozen (except the very last layers). Freezing prevents well-trained weights from being modified, which is what we want since are looking to implement transfer learning.
We are using the default values across a large number of hyper-parameters. It makes sense to see how good our model can perform with the least amount of work possible.
We need to make sure our notebook is utilizing GPU hardware acceleration. We did this at the beginning when we set the hardware accelerator to GPU. If you restarted your notebook since the beginning of this article ensure this is still set.
We access GPU hardware via Nvidia’s CUDA API. This enables us to tap into the parallel computing needed to train our model is reasonable time.
fastai’s fit_one_cycle method uses Leslie Smith’s 1cycle policy, which gives us a faster way to train complex models. You can learn more about this policy Sylvain Gugger’s post here.
We will train our model for 10 epochs. An “epoch” is the number of times our learning algorithm will work through the entire training dataset (each example in the training data had an opportunity to update the model parameters).
Epoch is different than the batch size, which is the number of samples processed before the model is updated.
We begin by training only the last layers of our model, by calling fastai’s fit_one_cycle method, specifying 10 epochs:
defaults.device = torch.device('cuda')learn.fit_one_cycle(10)
Below shows the first 3 epochs during training:
Total training will take around 40 mins. Keep in mind this training would be performed offline, thus training time isn’t that important for our product (whereas inference time is).
Your final result should look similar to this:
We have fairly low error rates, which is good. Not bad for a frozen model using default hyper-parameters. But let’s see if we can improve the results.
Now we will unfreeze the network, which means all the weights in our model can now be updated. We can call fastai’s unfreeze() method in our learn object:
learn.unfreeze()
Since we have “thawed” our model it no longer makes sense to use the same learning rate across all layers. Different layers in deep models benefit from so-called “differential” learning rates, where various rates are used depending on where in the network they are applied. To use differential learning rates we first need to find a suitable range.
To find a suitable range of learning rates we will plot our model’s loss against increasing rates. We can do this by first running:
learn.lr_find()
We are attempting to observe and understand clues that sometimes appear earl-on in training. By doing so, we can potentially tune our architecture via its hyper-parameters in such a way that less epochs are required. This enables us to avoid running complete grid and random searches in our efforts to find good hyper-parameters.
We can plot the learning rates against loss by running the following:
learn.recorder.plot()
The typical approach is to take the values right below the lowest point, prior the error becoming worse. We will use the range between 3 x 10^–5 and 3 x 10^e-4.
We will now run fit_one_cycle again, this using the max_lr argument to specify the range of learning rates. Let’s train our thawed model across 4 epochs using differential learning rates:
learn.fit_one_cycle(4, max_lr=slice(3e-5, 3e-4))
Note we achieved much lower error. Of course this is near-meaningless without first examining the quality of predictions.
As usual we examine the confusion matrix (CM) to see if there are any red flags with respect to misclassification. There might be certain defect types that our model struggles with.
We see most values sitting across the characteristic diagonal of the CM. Looks like our model is quite effective at predicting defects. We will use this model for our product.
Now that we have a trained model with reasonable accuracy we want to download it as an object that can be used for inference (predictions on real data):
learn.save('defect_classifier')learn.load('defect_classifier')learn.export('defect_classifier.pkl')
The .pkl file should appear in the training_csvs folder. Download this:
It’s about 84MB in size.
Recall in PART 1 we created the extracted_defects.json file and uploaded this to the Defect Turker for labelling. We will now create a JSON file with filenames for the actual application we build Part 4:
...and save this file test_temps.json:
with open('test_temps.json', 'w') as outfile: json.dump(test_temps, outfile)
and download the file:
Finally, let’s zip and download the hold out images to use with PCB Defect Classifier:
.., and download from Colab as usual:
We will use these files in PART 4.
We’re now ready to build our PCB Defect Classifier application.
We’ve arrived at the ultimate goal of this project (and of any real-world project), which is to create a real application for end users. As I stated in the introduction, creating products around our machine learning is the only true test our work has utility beyond a group of engineers.
I also stated that I will not cover all pipeline and front-end coding in order to keep this article a reasonable size.
TThis is the main application we want to create in this article. We looked at the reasons why a product like this would prove useful to end users in the printed circuit board domain. Let’s go over the major parts needed to craft this product, building out both the back-end and front-end components.
User fetches next set of PCB images (test and template);
User inspects PCB images;
User runs differencing/extraction/prediction pipeline;
User inspects predictions;
User reviews tallied costs.
The user can also set the defect costs based on their organization’s manufacturing.
We will use Flask to create a lightweight web service. Between Flask and Azle it will be easy to call our Python functions in the back-end. There are many tutorials on how to create a Flask web service so I won’t detail those steps here. Again, all code is available on GitHub.
We will use the major pipeline functions used in our Colab environment to create the back-end of our product pipeline.
From the figures above we know we need:
image differencing
image extraction
defect prediction
We will use Azle to call the functions (via app.py) contained in classifier.py, image_differencing.py and utility.py.
Here are the major functions needed:
Image Differencing:
subtract_images(**{ "image_path_1": image_path_1, "image_path_2": image_path_2, "write_path": "diff_img/diff_" + id + ".png"})
Defect Extraction:
extract_contours_from_image(**{ "image_path": path_to_diff, "write_path": "contours/" + id + "/", "hsv_lower": [0, 150, 50], "hsv_upper": [10, 255, 255]})
Defect Prediction:
def classifier(image_path): learn = load_learner('model') img = open_image(image_path) prediction = learn.predict(img) return(str(prediction))def predict(image_path): prediction = classifier(image_path) return(prediction)
The first 2 are the same tetryonai functions we used in our Colab environment for processing the test and template images.
I will create a directory called api that holds the main Flask file (app.py) and the files pertaining to our pipeline:
api└── app.py└── classifier.py└── image_differencing.py└── utility.py
The utility functions inside utility.py just help with some basic operations needed for the operation of the application.
Creating the application in Azle enables rapid prototyping. Here the major pieces:
Add buttons:
az.add_button("target_class", target_instance, { "this_class": "my_button", "text": "FETCH BOARDS"})
Show images:
az.add_image("target_class", target_instance, { "this_class": "my_image", "image_path": "https://bit.ly/1L574po"})
Call APIs
Sliders
Clone the application from GitHub by running the following in terminal:
git clone https://github.com/sean-mcclure/defect_classifier.git
We need to add the following files:
new PCB board images not used during model training;
JSON file containing all new board names;
Trained PCB defect classifier model.
Recall in PART 3 we created and downloaded the files test_temps.json and hold_out.zip. Place these files on your Desktop if they’re not already and unzip the hold_out.zip folder.
Now we can add all the hold out images to our application by moving them into the test_temps folder. From inside the cloned application (assuming application was cloned to Desktop):
mv ../Desktop/hold_out/* test_temps/
...and the test_temps.json file:
mv ../Desktop/test_temps.json test_temps/
Now we have:
test_temps └── 000410009_temp.jpg └── 000410009_test.jpg └── 00041012_temp.jpg └── 00041012_test.jpg ... └── test_temps.json
Our application now has access to the kind of images we would expect in our PCB board manufacturing scenario.
In PART 3 we saved the .pkl file. This is our trained defect classifier model. Let’s add this to the model folder of the application:
mv ../Desktop/defect_classifier.pkl model/
We need to rename our model object since fastai’s load_learner method expects the object to be called “export.pkl”:
mv model/defect_classifier.pkl model/export.pkl
Let’s go ahead and see how our PCB Defect Classifier works!
We built the web service in Flask. We call this as usual:
python api/app.py
You should see the following in your terminal:
* Serving Flask app "app" (lazy loading)* Environment: production WARNING: This is a development server. * Debug mode: on * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) * Restarting with stat * Debugger is active! * Debugger PIN: 622-284-701
We can see that we are running in debugger mode. This is ideal since any change we make to the Python will cause the service to automatically restart. This is very beneficial for prototyping.
Now we need to start a web service to show the front-end of the application. In your terminal run the following:
python3 -m http.server
Then open your browser to:
http://localhost:8000/app/
Our first screen looks like this:
The first step for the user is to run FETCH BOARDS, which will bring in our PCB images stored in test_temps (our hold out images).
This fetches both the TEST and TEMPLATE images. These are the PCB boards that manufactures need to test to see if any defects exist.
Now the user runs the pipeline, which will:
subtract the images to create a differenced image;
extract the defects contained in the differenced image;
predict the defect class for each extracted defect;
add the predicted cost to the cost summary.
Here’s the fuller video again we saw at the beginning, showing how we can make multiple runs against our pipeline, getting accurate predictions each time:
Beautiful. We can see that differencing and defect extraction is almost instantaneous. The prediction is set to 1000ms for each extracted defects, which seems reasonable for our demonstration. Is this fast enough for a PCB manufacturer?
FFeature Idea: Users could be presented a slider to set the prediction time. Based on manufacturing throughput, setting a lower prediction time might make sense. Of course this has to be balanced with how fast the prediction can be made with our pre-trained model (inference time). Setting up a chart showing best inference times would be a good experiment to run and show clients.
There are a number of things we could do to improve our product. While model accuracy is already quite good we didn’t try the other defect types. Will model performance be as good on these defects? What if this product needs to predict at a much higher rate? Would it be worth using shallower networks that run faster inference, while sacrificing some of our hard-won accuracy?
Here are some things we could try:
Data Augmentation
Other hyper-parameter settings
More data
Different architectures
There are also various user experiences we might build for, by way of different/additional product features. Would it make sense for users to have an option to mark bad predictions as incorrect (feed this info back to model). What about tallying additional information about the predicted defects, other than cost? Perhaps creating interesting summarizing visualizations. By embracing rapid prototyping we don’t have to know the answers to these questions upfront; we can build, showcase, and change as needed, with real products.
In this article we created an end-to-end PCB Defect Classifier application. We used image processing to difference sets of test and template PCB images, extract defects using contours, and classify the extracted defects using Deep Learning. We then created a front-end application that allows users to run our machine learning pipeline and review model predictions.
Applications like this help automate tasks that are manual, time-consuming, and prone to human error. The purpose is not to replace human experts, but rather augment their efforts so they may focus on more strategic and creative aspects of their jobs.
If you have any questions / need support please use the comments section. I can help others modify these applications for their specific purpose. Azle questions can be asked on Stack Overflow.
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
You’ll notice that we only get 3 of the defect types. This is because of the way the differencing works. It only picks up the black-differenced defects. The other defects, like mousebites, etc. need to be white-differenced. This can be achieved by simply changing the order of the image paths in the differencing function. Thus, if you want to detect, extract and predict all defects run both versions.If you want to remove the folders in contours run rm -r contours/* in terminal. If you want to remove all images in diff_img run rm diff_img/*.
You’ll notice that we only get 3 of the defect types. This is because of the way the differencing works. It only picks up the black-differenced defects. The other defects, like mousebites, etc. need to be white-differenced. This can be achieved by simply changing the order of the image paths in the differencing function. Thus, if you want to detect, extract and predict all defects run both versions.
If you want to remove the folders in contours run rm -r contours/* in terminal. If you want to remove all images in diff_img run rm diff_img/*.
World PCB Production in 2014 Estimated at $60.2BA PCB Dataset for Defects Detection and Classificationtangsanli5201/DeepPCB on GitHub
World PCB Production in 2014 Estimated at $60.2B
A PCB Dataset for Defects Detection and Classification
tangsanli5201/DeepPCB on GitHub
|
[
{
"code": null,
"e": 414,
"s": 171,
"text": "The Printed Circuit Board (PCB) is in most electronic products, mechanically supporting and connecting components along conductive tracks. Their prevalence underlies the modern electronics industry, with a world market exceeding $60 billion1."
},
{
"code": null,
"e": 790,
"s": 414,
"text": "PCBs are prone to a variety of defects that impede proper manufacturing, costing companies money. Defects such as shorts, spurs, mousebites, and pinholes cause issues like current leakage and open circuits, quickly degrading performance or rendering PCBs useless. PCB manufacturers must strive to ship defect-free units to remain competitive and ensure customer satisfaction."
},
{
"code": null,
"e": 1263,
"s": 790,
"text": "Failure analysts are employed to ensure defects are kept to a minimum. But inspecting and diagnosing defects manually is challenging. There are multiple defects to detect, an extremely low tolerance for errors, and significant expertise required to reliably recognize and handle flawed units. Considering the time to train new analysts, and the cognitive load required to ensure reliability, an automated solution to detecting and classifying defects in PCBs is in demand."
},
{
"code": null,
"e": 1734,
"s": 1263,
"text": "In this article we will build a full PCB Defect Classifier that automates the task of detecting and classifying defects in printed circuit boards. I always encourage AI practitioners to build full products rather than throwing models over the fence to developers and other engineers. Your machine learning must exist in concert with a full application; thus only through its survival inside a holistic product can you be certain you’re building for users, not engineers."
},
{
"code": null,
"e": 1819,
"s": 1734,
"text": "Play the following video to see the application we will be building in this article:"
},
{
"code": null,
"e": 2393,
"s": 1819,
"text": "In this article I will go over the application’s back-end and front-end code. I will walk through all of the code related to defect detection, extraction, and prediction. Thus the machine learning aspects will be covered in full. However I will only review the high-level aspects of the actual application pipeline code and front-end code, in order to keep this article to a reasonable size. Note that the entire application and its code are available on GitHub, thus readers have access to everything. I encourage others to clone and play with the project as they see fit."
},
{
"code": null,
"e": 2578,
"s": 2393,
"text": "This is always the best way to learn. I welcome questions in the comments section for those needing support (you can also @ me on Twitter so the support benefits others more publicly)."
},
{
"code": null,
"e": 2597,
"s": 2578,
"text": "Let’s get started."
},
{
"code": null,
"e": 2610,
"s": 2597,
"text": "Google Colab"
},
{
"code": null,
"e": 2616,
"s": 2610,
"text": "Flask"
},
{
"code": null,
"e": 2638,
"s": 2616,
"text": "Deep Learning: fastai"
},
{
"code": null,
"e": 2666,
"s": 2638,
"text": "Image Processing: tetryonai"
},
{
"code": null,
"e": 2687,
"s": 2666,
"text": "User Interface: Azle"
},
{
"code": null,
"e": 2744,
"s": 2687,
"text": "Notebook: PCB_Defect_Extraction_and_Classification.ipynb"
},
{
"code": null,
"e": 2794,
"s": 2744,
"text": "Defect Turker: (for creating labelled image data)"
},
{
"code": null,
"e": 2869,
"s": 2794,
"text": "PCB Defect Classifier: (automated visual inspection system and classifier)"
},
{
"code": null,
"e": 3061,
"s": 2869,
"text": "There are a number of challenges we face when attempting to automate defect detection and classification2. A few of these were already mentioned in the introduction. The fuller list includes:"
},
{
"code": null,
"e": 3097,
"s": 3061,
"text": "low tolerance for defects in units;"
},
{
"code": null,
"e": 3135,
"s": 3097,
"text": "multiple defect types to account for;"
},
{
"code": null,
"e": 3189,
"s": 3135,
"text": "low inference times required for automated solutions;"
},
{
"code": null,
"e": 3271,
"s": 3189,
"text": "training data for ML models limited (usually narrow, domain-specific, and small);"
},
{
"code": null,
"e": 3348,
"s": 3271,
"text": "traditional systems rely on hand-crafted features and significant expertise;"
},
{
"code": null,
"e": 3386,
"s": 3348,
"text": "methods used by others often private."
},
{
"code": null,
"e": 3555,
"s": 3386,
"text": "We will need an approach that addresses these challenges while supporting a real-world application that effectively detects, extracts and predicts defect types in PCBs."
},
{
"code": null,
"e": 3723,
"s": 3555,
"text": "Given the challenges we face it makes sense to use a hybrid approach to build our classifier application, which combines the reference method and non-reference method."
},
{
"code": null,
"e": 3910,
"s": 3723,
"text": "Reference Method: the inspected PCB board (test board) is compared to a reference template image (template board) that has no defects, in order to allow analysts to identify differences."
},
{
"code": null,
"e": 4045,
"s": 3910,
"text": "Non-Reference Method: the inspected PCB board is checked for compliance against design principles, without relying on template images."
},
{
"code": null,
"e": 4282,
"s": 4045,
"text": "The reference method is relatively straightforward to implement but has large storage requirements (holding all the images). The non-reference method doesn’t suffer from storage issues, but can be limited in the number of defects found."
},
{
"code": null,
"e": 4546,
"s": 4282,
"text": "Building a product that automates both reference and non-reference methods may not cut down on storage and computational requirements, but if the manual detection and classification errors are reduced we gain massively from the increased and reliable throughput ."
},
{
"code": null,
"e": 4748,
"s": 4546,
"text": "While we could attempt to train our deep learning model to classify the defects present on an entire board, this would be challenging. Take a look at the following example test and template PCB boards:"
},
{
"code": null,
"e": 5042,
"s": 4748,
"text": "The board on the left is what our model needs to classify. We can see the individual defects by comparing to the template. But how likely is it that our model will be able to reliably classify a combination of defects? What would the class be called? How many unique defect combinations exist?"
},
{
"code": null,
"e": 5263,
"s": 5042,
"text": "To lower the burden placed on our model we will first extract the individual defects from the test image. This can be accomplished by creating a differenced image and extracting the parts of the image that are different."
},
{
"code": null,
"e": 5359,
"s": 5263,
"text": "The following is the kind of differenced image we can produce using image processing in Python:"
},
{
"code": null,
"e": 5599,
"s": 5359,
"text": "Notice the defects are highlighted in red. The above image doesn’t show all the defects since in this article we are only concerned with extracting 3 types. Capturing the other defect types of fairly trivial, and I will discuss this later."
},
{
"code": null,
"e": 5755,
"s": 5599,
"text": "Since we have a differenced image that highlights the defects in the test image we can also use image processing to extract the colored parts of the image:"
},
{
"code": null,
"e": 6215,
"s": 5755,
"text": "This dramatically lowers the burden placed on our deep learning classifier. By extracting individual defects we convert the problem from a complex recognition problem into something akin to digit recognition (a problem that already works well with deep learning). This also means we are more likely to be successful using transfer learning, since there are numerous successful models in the OCR space. I will discuss transfer learning in more detail later on."
},
{
"code": null,
"e": 6266,
"s": 6215,
"text": "With this approach we can outline 5 major efforts:"
},
{
"code": null,
"e": 6396,
"s": 6266,
"text": "DEFECT EXTRACTIONDEFECT LABELLINGDEFECT CLASSIFICATIONBUILDING A PCB DEFECT CLASSIFIER APPLICATIONRUNNING/TESTING THE APPLICATION"
},
{
"code": null,
"e": 6414,
"s": 6396,
"text": "DEFECT EXTRACTION"
},
{
"code": null,
"e": 6431,
"s": 6414,
"text": "DEFECT LABELLING"
},
{
"code": null,
"e": 6453,
"s": 6431,
"text": "DEFECT CLASSIFICATION"
},
{
"code": null,
"e": 6498,
"s": 6453,
"text": "BUILDING A PCB DEFECT CLASSIFIER APPLICATION"
},
{
"code": null,
"e": 6530,
"s": 6498,
"text": "RUNNING/TESTING THE APPLICATION"
},
{
"code": null,
"e": 6705,
"s": 6530,
"text": "Head on over to Google Colab and start a new Python 3 notebook. This will be our modeling environment. This is a Jupyter notebook environment that runs entirely in the cloud."
},
{
"code": null,
"e": 6934,
"s": 6705,
"text": "Google Colab allows access to an environment capable of running GPUs at no cost. Colab also makes installing and importing libraries a breeze. This is back-end as a service (BaaS), which helps (immensely) with rapid prototyping."
},
{
"code": null,
"e": 7018,
"s": 6934,
"text": "You have 2 options for getting the notebook into your own Google Colab environment."
},
{
"code": null,
"e": 7086,
"s": 7018,
"text": "You can simply upload the notebook contained in the GitHub project:"
},
{
"code": null,
"e": 7154,
"s": 7086,
"text": "You can simply upload the notebook contained in the GitHub project:"
},
{
"code": null,
"e": 7279,
"s": 7154,
"text": "2. Or you can mount a drive in Google Colab, clone the defect_classifier repo, and open the notebook from your Google drive."
},
{
"code": null,
"e": 7309,
"s": 7279,
"text": "2.1 Open New Python3 Notebook"
},
{
"code": null,
"e": 7343,
"s": 7309,
"text": "2.2 Mount a Drive on Google Colab"
},
{
"code": null,
"e": 7418,
"s": 7343,
"text": "Run the following in the first cell (play button, or shift-return on Mac):"
},
{
"code": null,
"e": 7574,
"s": 7418,
"text": "You will be presented with a URL. Click it, get the auth code, return to your notebook and enter it. You now have access to your Google Drive inside Colab:"
},
{
"code": null,
"e": 7589,
"s": 7574,
"text": "2.3 Clone Repo"
},
{
"code": null,
"e": 7647,
"s": 7589,
"text": "...then copy the cloned notebook into your mounted drive:"
},
{
"code": null,
"e": 7676,
"s": 7647,
"text": "2.4 Open Notebook from Drive"
},
{
"code": null,
"e": 7801,
"s": 7676,
"text": "Now find the notebook inside your Google drive, as you would any other file, right-click, and choose open with Google Colab."
},
{
"code": null,
"e": 8075,
"s": 7801,
"text": "We will require Graphical Processing Units (GPU) to train our Deep Learning model in reasonable time. We can set the hardware acceleration in Colab by clicking on Runtime at the top, choosing Change runtime type, selecting GPU under hardware accelerator, and clicking SAVE."
},
{
"code": null,
"e": 8385,
"s": 8075,
"text": "First we need to build the defect extraction pipeline. To use less code I’ve created a small library that will abstract much of the image processing. I plan on continuing to add to this library going forward to stay tuned. For an intuitive yet detailed tutorial on creating libraries in R and Python see here."
},
{
"code": null,
"e": 8415,
"s": 8385,
"text": "Let’s import the library now:"
},
{
"code": null,
"e": 8517,
"s": 8415,
"text": "The library is freely available on GitHub. We can install libraries from GitHub using pip as follows:"
},
{
"code": null,
"e": 8581,
"s": 8517,
"text": "!pip install git+https://github.com/sean-mcclure/tetryon_ai.git"
},
{
"code": null,
"e": 8767,
"s": 8581,
"text": "Note the ! before the usual pip command. This is the “bang” symbol commonly used when doing interactive computing. It allows our Google Colab environment to access the underlying shell."
},
{
"code": null,
"e": 8798,
"s": 8767,
"text": "We can now import the library:"
},
{
"code": null,
"e": 8827,
"s": 8798,
"text": "from tetryonai.main import *"
},
{
"code": null,
"e": 8943,
"s": 8827,
"text": "You can also click on the Files icon to the left so we can see the files we work with (click on Refresh as needed):"
},
{
"code": null,
"e": 9107,
"s": 8943,
"text": "Let’s create folders to hold our differenced images, extracted defects, and the hold out images needed to test our model. We’ll use tetryonai’s directory function:"
},
{
"code": null,
"e": 9333,
"s": 9107,
"text": "directory(**{ \"choice\" : \"make\", \"directory_path\" : \"difference_img\"})directory(**{ \"choice\" : \"make\", \"directory_path\" : \"extracted_defects\"})directory(**{ \"choice\" : \"make\", \"directory_path\" : \"hold_out\"})"
},
{
"code": null,
"e": 9584,
"s": 9333,
"text": "We will need access to a large number of test and template PCB board images. These are available on GitHub3 via the DeepPCB project. This provides us with a large number of images obtained from a linear scan CCD. Review this project for more details."
},
{
"code": null,
"e": 9681,
"s": 9584,
"text": "Clone the DeepPCB project into your Colab environment by running the following in the next cell:"
},
{
"code": null,
"e": 9737,
"s": 9681,
"text": "!git clone https://github.com/tangsanli5201/DeepPCB.git"
},
{
"code": null,
"e": 9875,
"s": 9737,
"text": "Hit Refresh in the Files pane to see the new DeepPCB folder. You can expand through the folder to see just how many images are available."
},
{
"code": null,
"e": 10026,
"s": 9875,
"text": "For this project we will use only the group00041 set of temp and test images as shown above. These are the images previously described in Figures 1-3."
},
{
"code": null,
"e": 10205,
"s": 10026,
"text": "Let’s write some Python for storing the group00041 temp and test image paths from our DeepPCB folder inside a dict. We’ll then use this in the next step to difference our images:"
},
{
"code": null,
"e": 10488,
"s": 10205,
"text": "Now we will use image processing to difference each pair of temp and test images using the paths specified inside the dict we just created. We also need to hold out a set of these images to test in our application. I will combine these operations into one codeblock for convenience:"
},
{
"code": null,
"e": 10821,
"s": 10488,
"text": "We are using tetryonai’s copy_files function to copy the necessary files into the target_directory called hold_out that we created earlier. I am using a split_percentage of 20% for the hold out set. In the code above, once 20% of the images have been held out the remaining are subtracted using tetryonai’s subtract_images function."
},
{
"code": null,
"e": 11076,
"s": 10821,
"text": "If we Refresh our Files pane and inspect our difference_img and hold_out folders we will see the images placed as inspected. You can also open a few of the images inside difference_img to confirm the subtraction process worked (as was shown in Figure 2):"
},
{
"code": null,
"e": 11377,
"s": 11076,
"text": "We are now ready to extract the highlighted defects that appear in the differenced images. We will use tetryonai’s extract_contours_from_image function to read in each differenced image, extract defects per image, and save the defects to the extracted_defects folder we created towards the beginning:"
},
{
"code": null,
"e": 11538,
"s": 11377,
"text": "Images that are corrupt/non-readable will be skipped by the extract_contours_from_image function. This still leaves us with plenty of images to train our model."
},
{
"code": null,
"e": 11900,
"s": 11538,
"text": "The extract_contours_from_image function uses contours to extract the highlighted parts of our differenced images. Think of contours as a curve joining all the continuous points (along the boundary) that have the same color or intensity. Contours are a useful tool for shape analysis and object detection/recognition. You can read more about contours on OpenCV."
},
{
"code": null,
"e": 12082,
"s": 11900,
"text": "Refresh the Files pane and inspect the extracted_defects folder. You will notice individual folders have been created for each set of contours extracted from each differenced image."
},
{
"code": null,
"e": 12204,
"s": 12082,
"text": "We will now combine all the extracted defects into a single directory called all_extracts. Let’s make that directory now:"
},
{
"code": null,
"e": 12279,
"s": 12204,
"text": "directory(**{ \"choice\" : \"make\", \"directory_path\" : \"all_extracts\"})"
},
{
"code": null,
"e": 12410,
"s": 12279,
"text": "We write some Python to walk through the extracted_defects directory and move any PNG files using tetryonai’s move_files function:"
},
{
"code": null,
"e": 12510,
"s": 12410,
"text": "Refreshing the Files pane and inspecting the all_extracts folder will reveal all extracted defects."
},
{
"code": null,
"e": 12749,
"s": 12510,
"text": "In PART 2 we will be applying labels to our extracted defects (“turking”). We thus need to download all extracted defect images to use with the labelling application we create next. So let’s zip all extracted defects for easy downloading:"
},
{
"code": null,
"e": 12811,
"s": 12749,
"text": "!zip -r /content/extracted_defects.zip /content/all_extracts/"
},
{
"code": null,
"e": 12897,
"s": 12811,
"text": "If you Refresh your Files pane you will see a new extracted_defects.zip file created."
},
{
"code": null,
"e": 13082,
"s": 12897,
"text": "Our labelling application will also require a JSON file with the filenames of the images in our zip folder. Let’s write some Python to grab all filenames in the all_extracts directory:"
},
{
"code": null,
"e": 13118,
"s": 13082,
"text": "Save the JSON file we just created:"
},
{
"code": null,
"e": 13215,
"s": 13118,
"text": "with open('extracted_defects.json', 'w') as outfile: json.dump(file_names_and_sizes, outfile)"
},
{
"code": null,
"e": 13315,
"s": 13215,
"text": "Refresh the File pane and download both the extracted_defects.zip and extracted_defects.json files:"
},
{
"code": null,
"e": 13357,
"s": 13315,
"text": "Save these files to your Desktop for now."
},
{
"code": null,
"e": 13587,
"s": 13357,
"text": "In PART I we differenced a large set of test and template PCB images, extracted defects in the differenced images using contours, and created the 2 files we need to use the labelling application we create next. Let’s do that now."
},
{
"code": null,
"e": 13895,
"s": 13587,
"text": "With our set of extracted defect images in hand we have a good-sized dataset to use for training a Deep Learning model for image classification. But like any supervised machine learning approach our training data requires labels. Since we extracted our images we obviously don’t have these labels available."
},
{
"code": null,
"e": 14459,
"s": 13895,
"text": "Image classification requires large amounts of labelled data, making hand-crafted labeling an arduous task. But the colossal data prerequisite to image classification often isn’t a show stopper. This is because there are a wealth of publicly-available models that have already been trained on large benchmark sets of images. As long as the domain isn’t too different we can use much less data to train a pre-trained model. Can we get away with successfully classifying our extracted defects using much less labelled data, paired with an existing image classifier?"
},
{
"code": null,
"e": 14646,
"s": 14459,
"text": "My bet is yes, but there is only one way to find out. This is a good opportunity to build a new, general-purpose product. This product will allow us to create labels for a set of images."
},
{
"code": null,
"e": 14853,
"s": 14646,
"text": "TI won’t go through the steps for creating the Defect Turker since this article is already long enough. It’s a simple application that allows us to apply labels to any images that are inside its img folder."
},
{
"code": null,
"e": 15271,
"s": 14853,
"text": "Too often people rush to find existing solutions, with products that don’t address their true requirements. A lot of time (and money) ends up being wasted trying to force existing products to their specific set of challenges. Bespoke software development is immensely powerful, but only when it’s not inhibited by over-staffed projects and over-engineered solutions. Rapid prototyping is a massively beneficial skill."
},
{
"code": null,
"e": 15437,
"s": 15271,
"text": "We won’t do our labelling on Colab since it currently has no obvious way to host web applications inside its environment. We will thus run the Defect Turker locally."
},
{
"code": null,
"e": 15573,
"s": 15437,
"text": "The Defect Turker is available on GitHub. Clone the application onto your local machine by running the following in a terminal session:"
},
{
"code": null,
"e": 15633,
"s": 15573,
"text": "git clone https://github.com/sean-mcclure/defect_turker.git"
},
{
"code": null,
"e": 15693,
"s": 15633,
"text": "I also start a simple web service using the following line:"
},
{
"code": null,
"e": 15716,
"s": 15693,
"text": "python3 -m http.server"
},
{
"code": null,
"e": 15994,
"s": 15716,
"text": "Before opening our browser to the application let’s add the extracted defect images (extracted_defects.zip) and JSON file (extracted_defects.json) we created earlier to the application. These files are on my Desktop, so I’ll double-click the ZIP file to decompress it contents:"
},
{
"code": null,
"e": 16090,
"s": 15994,
"text": "..and run the following line in a new tab in terminal, from inside the defect_turker directory:"
},
{
"code": null,
"e": 16141,
"s": 16090,
"text": "mv ../content/all_extracts/* ../defect_turker/img/"
},
{
"code": null,
"e": 16218,
"s": 16141,
"text": "Confirm our extracted defect images are inside the application’s img folder:"
},
{
"code": null,
"e": 16289,
"s": 16218,
"text": "We also need the JSON file containing all image names. Move these now:"
},
{
"code": null,
"e": 16340,
"s": 16289,
"text": "mv ../extracted_defects.json ../defect_turker/img/"
},
{
"code": null,
"e": 16508,
"s": 16340,
"text": "We’re now ready to label our images. Let’s start the application. Since our web server is already up-and-running we simply point our browser to http://localhost:8000/."
},
{
"code": null,
"e": 16649,
"s": 16508,
"text": "If you need to change the port # on the web server you simply add the port to the end of the full command (e.g. python3 -m http.server 5555)"
},
{
"code": null,
"e": 16679,
"s": 16649,
"text": "You should see the following:"
},
{
"code": null,
"e": 16962,
"s": 16679,
"text": "Your first image will likely be something other than the one shown here. We can see there are 1333 total images. That’s a lot of labelling. I decided to break this up throughout the day and do a few hundred at a time. Ideally we would split this task among a few people on the team."
},
{
"code": null,
"e": 17118,
"s": 16962,
"text": "Product Idea: Create a version of this application that allows labelling to be done by multiple people, then recombines the results into a single CSV file."
},
{
"code": null,
"e": 17238,
"s": 17118,
"text": "The first icon is a legend showing the labels for each defect type. Refer to this to learn which defect has what label."
},
{
"code": null,
"e": 17309,
"s": 17238,
"text": "It turns out our image differencing only extracted 3 types of defects:"
},
{
"code": null,
"e": 17314,
"s": 17309,
"text": "spur"
},
{
"code": null,
"e": 17330,
"s": 17314,
"text": "spurious copper"
},
{
"code": null,
"e": 17336,
"s": 17330,
"text": "short"
},
{
"code": null,
"e": 17594,
"s": 17336,
"text": "The reason only 3 types were extracted has to do with how our image differencing was set up. We can easily detect the other types of defects as well, but I will keep our application to these 3 defect types for this article. See NOTES at the end for details."
},
{
"code": null,
"e": 17622,
"s": 17594,
"text": "Now we can start labelling:"
},
{
"code": null,
"e": 17873,
"s": 17622,
"text": "Simply click on the button that corresponds to the label for the presented image. Once we have labelled all the images (or as many as you wish) we click on the upper right icon to download a CSV file that can be used to train our Deep Learning model."
},
{
"code": null,
"e": 18006,
"s": 17873,
"text": "The CSV file has each image name and the label we applied. Save the file as image_labels.csv and keep it on your Desktop for Part 3."
},
{
"code": null,
"e": 18065,
"s": 18006,
"text": "We’re now ready to train our Deep Learning PCB Classifier."
},
{
"code": null,
"e": 18240,
"s": 18065,
"text": "We move back to the Colab notebook to train our Deep Learning model using the CSV file we created with the Defect Turker. We will use fastai to train our Deep Learning model."
},
{
"code": null,
"e": 18699,
"s": 18240,
"text": "fast.ai, the research institute, is dedicated to making deep learning more accessible, via their courses, software, research and community. Their library fastai is a powerful open source API sitting on top of PyTorch. Recent research breakthroughs in Deep Learning are embedded into the fastai library meaning we get access to cutting-edge Deep Learning models that are more accurate and faster than many other DL libraries; all while writing much less code."
},
{
"code": null,
"e": 18807,
"s": 18699,
"text": "!pip install http://download.pytorch.org/whl/cpu/torch-1.0.0-cp36-cp36m-linux_x86_64.whl!pip install fastai"
},
{
"code": null,
"e": 18819,
"s": 18807,
"text": "and import:"
},
{
"code": null,
"e": 18847,
"s": 18819,
"text": "from fastai.vision import *"
},
{
"code": null,
"e": 18982,
"s": 18847,
"text": "We will upload the image_labels.csv file created with the Defect Turker in Part 2. Run the following line in Colab to upload the file:"
},
{
"code": null,
"e": 19027,
"s": 18982,
"text": "from google.colab import filesfiles.upload()"
},
{
"code": null,
"e": 19088,
"s": 19027,
"text": "You may have to run this twice as the first run often fails."
},
{
"code": null,
"e": 19184,
"s": 19088,
"text": "We’ll now convert image_labels.csv to a data frame using tetryonai’s csv_to_dataframe function:"
},
{
"code": null,
"e": 19266,
"s": 19184,
"text": "image_labels_frame = csv_to_dataframe(**{ \"path_to_csv\" : \"image_labels.csv\"})"
},
{
"code": null,
"e": 19417,
"s": 19266,
"text": "Let’s check the class balance between our labels. First, we’ll get the number of examples of each label using tetryonai’s get_feature_counts function:"
},
{
"code": null,
"e": 19521,
"s": 19417,
"text": "labelled_counts = get_feature_counts(**{ \"data_frame\" : image_labels_frame, \"feature\" : \"label\"})"
},
{
"code": null,
"e": 19564,
"s": 19521,
"text": "...then use Matplotlib to create our plot:"
},
{
"code": null,
"e": 19580,
"s": 19564,
"text": "...which gives:"
},
{
"code": null,
"e": 19694,
"s": 19580,
"text": "Note: If “label” appears in the chart, run del labelled_counts[‘label’] in the cell prior to creating the visual."
},
{
"code": null,
"e": 19950,
"s": 19694,
"text": "We have a “majority class” of NOT, while the 3 defect types are fairly balanced. We could downsample the majority class but it may not be needed. We’ll go ahead and use our labelled data as is, and readjust the balance in our training data only if needed."
},
{
"code": null,
"e": 20140,
"s": 19950,
"text": "The fastai training approach we will use requires individual labelled CSV files for each class we want to predict. Let’s create a folder called training_csvs to hold these individual files:"
},
{
"code": null,
"e": 20216,
"s": 20140,
"text": "directory(**{ \"choice\" : \"make\", \"directory_path\" : \"training_csvs\"})"
},
{
"code": null,
"e": 20363,
"s": 20216,
"text": "...now let’s create individual CSV files for each class using the image_labels_frame dataframe we created from our uploaded image_labels.csv file."
},
{
"code": null,
"e": 20412,
"s": 20363,
"text": "First we create individual lists for each class:"
},
{
"code": null,
"e": 20476,
"s": 20412,
"text": "...then we convert those lists into data frames for each class:"
},
{
"code": null,
"e": 20531,
"s": 20476,
"text": "Now let’s create individual folders for the CSV files:"
},
{
"code": null,
"e": 20602,
"s": 20531,
"text": "Now we can move the individual CSV files to their appropriate folders:"
},
{
"code": null,
"e": 20811,
"s": 20602,
"text": "We obviously need images to train our image classifier. These will be the defect images we extracted in PART 1, zipped into the file called extracted_defects.zip, and added to our Defect Turker for labelling."
},
{
"code": null,
"e": 21176,
"s": 20811,
"text": "We could just use the extracted_defects.zip file that is currently in our Colab environment, but we may have restarted and rerun our pipeline from PART 1 if we are doing this project over a few days. This will obviously recreate our zipped image file making the filenames in our previously labelled CSV file (image_labels.csv) mismatch our zipped images filenames."
},
{
"code": null,
"e": 21338,
"s": 21176,
"text": "Given the above, let’s remove the extracted_defects.zip file currently in Colab and upload the extracted_defects.zip file we know we used with the Defect Turker."
},
{
"code": null,
"e": 21371,
"s": 21338,
"text": "Remove zipped images from Colab:"
},
{
"code": null,
"e": 21397,
"s": 21371,
"text": "!rm extracted_defects.zip"
},
{
"code": null,
"e": 21424,
"s": 21397,
"text": "Upload used for labelling:"
},
{
"code": null,
"e": 21439,
"s": 21424,
"text": "files.upload()"
},
{
"code": null,
"e": 21493,
"s": 21439,
"text": "Move extracted_defects.zip into training_csvs folder:"
},
{
"code": null,
"e": 21595,
"s": 21493,
"text": "move_files(**{ \"file_paths\" : [\"extracted_defects.zip\"], \"target_directory\" : \"training_csvs\"})"
},
{
"code": null,
"e": 21672,
"s": 21595,
"text": "Extract all images from extracted_defects.zip into the training_csvs folder:"
},
{
"code": null,
"e": 21803,
"s": 21672,
"text": "import zipfilewith zipfile.ZipFile(\"training_csvs/extracted_defects.zip\", 'r') as zip_ref: zip_ref.extractall(\"training_csvs/\")"
},
{
"code": null,
"e": 21915,
"s": 21803,
"text": "Now we can move all extracted defect images into their proper training folder, using the image_labels.csv file:"
},
{
"code": null,
"e": 22005,
"s": 21915,
"text": "To clean up, let’s remove any remaining PNG files (defect images) that were not labelled:"
},
{
"code": null,
"e": 22110,
"s": 22005,
"text": "directory(**{ \"choice\" : \"remove\", \"directory_path\" : \"training_csvs/content\", \"force\" : True})"
},
{
"code": null,
"e": 22182,
"s": 22110,
"text": "We should inspect the image data to confirm they were read-in properly:"
},
{
"code": null,
"e": 22222,
"s": 22182,
"text": "data.show_batch(rows=4, figsize=(7, 8))"
},
{
"code": null,
"e": 22340,
"s": 22222,
"text": "We can see the labels match the images (the spur, spurious, short, and not_defect images all match the labels shown)."
},
{
"code": null,
"e": 22667,
"s": 22340,
"text": "We are now ready to train our classifier. We need a fairly deep architecture if we are to get good enough results to create a product people use. Deep networks (large number of stacked layers) allow for deeper representations than their shallow counterparts and have been shown to perform very well on image recognition tasks."
},
{
"code": null,
"e": 22950,
"s": 22667,
"text": "We will download a pre-trained PyTorch model from torchvision. We want to use a pre-trained model to cut down on training time and CPU requirements. Pre-trained models have been trained on large benchmark datasets to solve problems similar to ours. This is called transfer learning."
},
{
"code": null,
"e": 23081,
"s": 22950,
"text": "The following figure shows the ResNet34 architecture we will use. This architecture is based off research discussed in this paper."
},
{
"code": null,
"e": 23158,
"s": 23081,
"text": "To download the pre-trained ResNet34 model from fastai we run the following:"
},
{
"code": null,
"e": 23272,
"s": 23158,
"text": "from fastai.metrics import error_rate # 1 - accuracylearn = create_cnn(data, models.resnet34, metrics=error_rate)"
},
{
"code": null,
"e": 23314,
"s": 23272,
"text": "Let’s train our model on our defect data."
},
{
"code": null,
"e": 23671,
"s": 23314,
"text": "By using a pre-trained model it means all the weights are already trained prior to our implementation. We refer to this kind of setup as a frozen model, which be default has “all” layers frozen (except the very last layers). Freezing prevents well-trained weights from being modified, which is what we want since are looking to implement transfer learning."
},
{
"code": null,
"e": 23839,
"s": 23671,
"text": "We are using the default values across a large number of hyper-parameters. It makes sense to see how good our model can perform with the least amount of work possible."
},
{
"code": null,
"e": 24080,
"s": 23839,
"text": "We need to make sure our notebook is utilizing GPU hardware acceleration. We did this at the beginning when we set the hardware accelerator to GPU. If you restarted your notebook since the beginning of this article ensure this is still set."
},
{
"code": null,
"e": 24223,
"s": 24080,
"text": "We access GPU hardware via Nvidia’s CUDA API. This enables us to tap into the parallel computing needed to train our model is reasonable time."
},
{
"code": null,
"e": 24406,
"s": 24223,
"text": "fastai’s fit_one_cycle method uses Leslie Smith’s 1cycle policy, which gives us a faster way to train complex models. You can learn more about this policy Sylvain Gugger’s post here."
},
{
"code": null,
"e": 24635,
"s": 24406,
"text": "We will train our model for 10 epochs. An “epoch” is the number of times our learning algorithm will work through the entire training dataset (each example in the training data had an opportunity to update the model parameters)."
},
{
"code": null,
"e": 24745,
"s": 24635,
"text": "Epoch is different than the batch size, which is the number of samples processed before the model is updated."
},
{
"code": null,
"e": 24865,
"s": 24745,
"text": "We begin by training only the last layers of our model, by calling fastai’s fit_one_cycle method, specifying 10 epochs:"
},
{
"code": null,
"e": 24927,
"s": 24865,
"text": "defaults.device = torch.device('cuda')learn.fit_one_cycle(10)"
},
{
"code": null,
"e": 24975,
"s": 24927,
"text": "Below shows the first 3 epochs during training:"
},
{
"code": null,
"e": 25156,
"s": 24975,
"text": "Total training will take around 40 mins. Keep in mind this training would be performed offline, thus training time isn’t that important for our product (whereas inference time is)."
},
{
"code": null,
"e": 25203,
"s": 25156,
"text": "Your final result should look similar to this:"
},
{
"code": null,
"e": 25354,
"s": 25203,
"text": "We have fairly low error rates, which is good. Not bad for a frozen model using default hyper-parameters. But let’s see if we can improve the results."
},
{
"code": null,
"e": 25509,
"s": 25354,
"text": "Now we will unfreeze the network, which means all the weights in our model can now be updated. We can call fastai’s unfreeze() method in our learn object:"
},
{
"code": null,
"e": 25526,
"s": 25509,
"text": "learn.unfreeze()"
},
{
"code": null,
"e": 25875,
"s": 25526,
"text": "Since we have “thawed” our model it no longer makes sense to use the same learning rate across all layers. Different layers in deep models benefit from so-called “differential” learning rates, where various rates are used depending on where in the network they are applied. To use differential learning rates we first need to find a suitable range."
},
{
"code": null,
"e": 26007,
"s": 25875,
"text": "To find a suitable range of learning rates we will plot our model’s loss against increasing rates. We can do this by first running:"
},
{
"code": null,
"e": 26023,
"s": 26007,
"text": "learn.lr_find()"
},
{
"code": null,
"e": 26353,
"s": 26023,
"text": "We are attempting to observe and understand clues that sometimes appear earl-on in training. By doing so, we can potentially tune our architecture via its hyper-parameters in such a way that less epochs are required. This enables us to avoid running complete grid and random searches in our efforts to find good hyper-parameters."
},
{
"code": null,
"e": 26423,
"s": 26353,
"text": "We can plot the learning rates against loss by running the following:"
},
{
"code": null,
"e": 26445,
"s": 26423,
"text": "learn.recorder.plot()"
},
{
"code": null,
"e": 26606,
"s": 26445,
"text": "The typical approach is to take the values right below the lowest point, prior the error becoming worse. We will use the range between 3 x 10^–5 and 3 x 10^e-4."
},
{
"code": null,
"e": 26794,
"s": 26606,
"text": "We will now run fit_one_cycle again, this using the max_lr argument to specify the range of learning rates. Let’s train our thawed model across 4 epochs using differential learning rates:"
},
{
"code": null,
"e": 26843,
"s": 26794,
"text": "learn.fit_one_cycle(4, max_lr=slice(3e-5, 3e-4))"
},
{
"code": null,
"e": 26965,
"s": 26843,
"text": "Note we achieved much lower error. Of course this is near-meaningless without first examining the quality of predictions."
},
{
"code": null,
"e": 27147,
"s": 26965,
"text": "As usual we examine the confusion matrix (CM) to see if there are any red flags with respect to misclassification. There might be certain defect types that our model struggles with."
},
{
"code": null,
"e": 27323,
"s": 27147,
"text": "We see most values sitting across the characteristic diagonal of the CM. Looks like our model is quite effective at predicting defects. We will use this model for our product."
},
{
"code": null,
"e": 27476,
"s": 27323,
"text": "Now that we have a trained model with reasonable accuracy we want to download it as an object that can be used for inference (predictions on real data):"
},
{
"code": null,
"e": 27576,
"s": 27476,
"text": "learn.save('defect_classifier')learn.load('defect_classifier')learn.export('defect_classifier.pkl')"
},
{
"code": null,
"e": 27648,
"s": 27576,
"text": "The .pkl file should appear in the training_csvs folder. Download this:"
},
{
"code": null,
"e": 27673,
"s": 27648,
"text": "It’s about 84MB in size."
},
{
"code": null,
"e": 27877,
"s": 27673,
"text": "Recall in PART 1 we created the extracted_defects.json file and uploaded this to the Defect Turker for labelling. We will now create a JSON file with filenames for the actual application we build Part 4:"
},
{
"code": null,
"e": 27916,
"s": 27877,
"text": "...and save this file test_temps.json:"
},
{
"code": null,
"e": 27996,
"s": 27916,
"text": "with open('test_temps.json', 'w') as outfile: json.dump(test_temps, outfile)"
},
{
"code": null,
"e": 28019,
"s": 27996,
"text": "and download the file:"
},
{
"code": null,
"e": 28106,
"s": 28019,
"text": "Finally, let’s zip and download the hold out images to use with PCB Defect Classifier:"
},
{
"code": null,
"e": 28144,
"s": 28106,
"text": ".., and download from Colab as usual:"
},
{
"code": null,
"e": 28179,
"s": 28144,
"text": "We will use these files in PART 4."
},
{
"code": null,
"e": 28243,
"s": 28179,
"text": "We’re now ready to build our PCB Defect Classifier application."
},
{
"code": null,
"e": 28531,
"s": 28243,
"text": "We’ve arrived at the ultimate goal of this project (and of any real-world project), which is to create a real application for end users. As I stated in the introduction, creating products around our machine learning is the only true test our work has utility beyond a group of engineers."
},
{
"code": null,
"e": 28650,
"s": 28531,
"text": "I also stated that I will not cover all pipeline and front-end coding in order to keep this article a reasonable size."
},
{
"code": null,
"e": 28950,
"s": 28650,
"text": "TThis is the main application we want to create in this article. We looked at the reasons why a product like this would prove useful to end users in the printed circuit board domain. Let’s go over the major parts needed to craft this product, building out both the back-end and front-end components."
},
{
"code": null,
"e": 29007,
"s": 28950,
"text": "User fetches next set of PCB images (test and template);"
},
{
"code": null,
"e": 29033,
"s": 29007,
"text": "User inspects PCB images;"
},
{
"code": null,
"e": 29088,
"s": 29033,
"text": "User runs differencing/extraction/prediction pipeline;"
},
{
"code": null,
"e": 29115,
"s": 29088,
"text": "User inspects predictions;"
},
{
"code": null,
"e": 29143,
"s": 29115,
"text": "User reviews tallied costs."
},
{
"code": null,
"e": 29227,
"s": 29143,
"text": "The user can also set the defect costs based on their organization’s manufacturing."
},
{
"code": null,
"e": 29505,
"s": 29227,
"text": "We will use Flask to create a lightweight web service. Between Flask and Azle it will be easy to call our Python functions in the back-end. There are many tutorials on how to create a Flask web service so I won’t detail those steps here. Again, all code is available on GitHub."
},
{
"code": null,
"e": 29624,
"s": 29505,
"text": "We will use the major pipeline functions used in our Colab environment to create the back-end of our product pipeline."
},
{
"code": null,
"e": 29664,
"s": 29624,
"text": "From the figures above we know we need:"
},
{
"code": null,
"e": 29683,
"s": 29664,
"text": "image differencing"
},
{
"code": null,
"e": 29700,
"s": 29683,
"text": "image extraction"
},
{
"code": null,
"e": 29718,
"s": 29700,
"text": "defect prediction"
},
{
"code": null,
"e": 29836,
"s": 29718,
"text": "We will use Azle to call the functions (via app.py) contained in classifier.py, image_differencing.py and utility.py."
},
{
"code": null,
"e": 29873,
"s": 29836,
"text": "Here are the major functions needed:"
},
{
"code": null,
"e": 29893,
"s": 29873,
"text": "Image Differencing:"
},
{
"code": null,
"e": 30029,
"s": 29893,
"text": "subtract_images(**{ \"image_path_1\": image_path_1, \"image_path_2\": image_path_2, \"write_path\": \"diff_img/diff_\" + id + \".png\"})"
},
{
"code": null,
"e": 30048,
"s": 30029,
"text": "Defect Extraction:"
},
{
"code": null,
"e": 30215,
"s": 30048,
"text": "extract_contours_from_image(**{ \"image_path\": path_to_diff, \"write_path\": \"contours/\" + id + \"/\", \"hsv_lower\": [0, 150, 50], \"hsv_upper\": [10, 255, 255]})"
},
{
"code": null,
"e": 30234,
"s": 30215,
"text": "Defect Prediction:"
},
{
"code": null,
"e": 30474,
"s": 30234,
"text": "def classifier(image_path): learn = load_learner('model') img = open_image(image_path) prediction = learn.predict(img) return(str(prediction))def predict(image_path): prediction = classifier(image_path) return(prediction)"
},
{
"code": null,
"e": 30597,
"s": 30474,
"text": "The first 2 are the same tetryonai functions we used in our Colab environment for processing the test and template images."
},
{
"code": null,
"e": 30716,
"s": 30597,
"text": "I will create a directory called api that holds the main Flask file (app.py) and the files pertaining to our pipeline:"
},
{
"code": null,
"e": 30786,
"s": 30716,
"text": "api└── app.py└── classifier.py└── image_differencing.py└── utility.py"
},
{
"code": null,
"e": 30908,
"s": 30786,
"text": "The utility functions inside utility.py just help with some basic operations needed for the operation of the application."
},
{
"code": null,
"e": 30991,
"s": 30908,
"text": "Creating the application in Azle enables rapid prototyping. Here the major pieces:"
},
{
"code": null,
"e": 31004,
"s": 30991,
"text": "Add buttons:"
},
{
"code": null,
"e": 31111,
"s": 31004,
"text": "az.add_button(\"target_class\", target_instance, { \"this_class\": \"my_button\", \"text\": \"FETCH BOARDS\"})"
},
{
"code": null,
"e": 31124,
"s": 31111,
"text": "Show images:"
},
{
"code": null,
"e": 31245,
"s": 31124,
"text": "az.add_image(\"target_class\", target_instance, { \"this_class\": \"my_image\", \"image_path\": \"https://bit.ly/1L574po\"})"
},
{
"code": null,
"e": 31255,
"s": 31245,
"text": "Call APIs"
},
{
"code": null,
"e": 31263,
"s": 31255,
"text": "Sliders"
},
{
"code": null,
"e": 31335,
"s": 31263,
"text": "Clone the application from GitHub by running the following in terminal:"
},
{
"code": null,
"e": 31399,
"s": 31335,
"text": "git clone https://github.com/sean-mcclure/defect_classifier.git"
},
{
"code": null,
"e": 31435,
"s": 31399,
"text": "We need to add the following files:"
},
{
"code": null,
"e": 31488,
"s": 31435,
"text": "new PCB board images not used during model training;"
},
{
"code": null,
"e": 31530,
"s": 31488,
"text": "JSON file containing all new board names;"
},
{
"code": null,
"e": 31567,
"s": 31530,
"text": "Trained PCB defect classifier model."
},
{
"code": null,
"e": 31746,
"s": 31567,
"text": "Recall in PART 3 we created and downloaded the files test_temps.json and hold_out.zip. Place these files on your Desktop if they’re not already and unzip the hold_out.zip folder."
},
{
"code": null,
"e": 31928,
"s": 31746,
"text": "Now we can add all the hold out images to our application by moving them into the test_temps folder. From inside the cloned application (assuming application was cloned to Desktop):"
},
{
"code": null,
"e": 31965,
"s": 31928,
"text": "mv ../Desktop/hold_out/* test_temps/"
},
{
"code": null,
"e": 31998,
"s": 31965,
"text": "...and the test_temps.json file:"
},
{
"code": null,
"e": 32040,
"s": 31998,
"text": "mv ../Desktop/test_temps.json test_temps/"
},
{
"code": null,
"e": 32053,
"s": 32040,
"text": "Now we have:"
},
{
"code": null,
"e": 32196,
"s": 32053,
"text": "test_temps └── 000410009_temp.jpg └── 000410009_test.jpg └── 00041012_temp.jpg └── 00041012_test.jpg ... └── test_temps.json"
},
{
"code": null,
"e": 32306,
"s": 32196,
"text": "Our application now has access to the kind of images we would expect in our PCB board manufacturing scenario."
},
{
"code": null,
"e": 32440,
"s": 32306,
"text": "In PART 3 we saved the .pkl file. This is our trained defect classifier model. Let’s add this to the model folder of the application:"
},
{
"code": null,
"e": 32483,
"s": 32440,
"text": "mv ../Desktop/defect_classifier.pkl model/"
},
{
"code": null,
"e": 32599,
"s": 32483,
"text": "We need to rename our model object since fastai’s load_learner method expects the object to be called “export.pkl”:"
},
{
"code": null,
"e": 32647,
"s": 32599,
"text": "mv model/defect_classifier.pkl model/export.pkl"
},
{
"code": null,
"e": 32707,
"s": 32647,
"text": "Let’s go ahead and see how our PCB Defect Classifier works!"
},
{
"code": null,
"e": 32765,
"s": 32707,
"text": "We built the web service in Flask. We call this as usual:"
},
{
"code": null,
"e": 32783,
"s": 32765,
"text": "python api/app.py"
},
{
"code": null,
"e": 32830,
"s": 32783,
"text": "You should see the following in your terminal:"
},
{
"code": null,
"e": 33086,
"s": 32830,
"text": "* Serving Flask app \"app\" (lazy loading)* Environment: production WARNING: This is a development server. * Debug mode: on * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) * Restarting with stat * Debugger is active! * Debugger PIN: 622-284-701"
},
{
"code": null,
"e": 33278,
"s": 33086,
"text": "We can see that we are running in debugger mode. This is ideal since any change we make to the Python will cause the service to automatically restart. This is very beneficial for prototyping."
},
{
"code": null,
"e": 33391,
"s": 33278,
"text": "Now we need to start a web service to show the front-end of the application. In your terminal run the following:"
},
{
"code": null,
"e": 33414,
"s": 33391,
"text": "python3 -m http.server"
},
{
"code": null,
"e": 33441,
"s": 33414,
"text": "Then open your browser to:"
},
{
"code": null,
"e": 33468,
"s": 33441,
"text": "http://localhost:8000/app/"
},
{
"code": null,
"e": 33502,
"s": 33468,
"text": "Our first screen looks like this:"
},
{
"code": null,
"e": 33633,
"s": 33502,
"text": "The first step for the user is to run FETCH BOARDS, which will bring in our PCB images stored in test_temps (our hold out images)."
},
{
"code": null,
"e": 33766,
"s": 33633,
"text": "This fetches both the TEST and TEMPLATE images. These are the PCB boards that manufactures need to test to see if any defects exist."
},
{
"code": null,
"e": 33810,
"s": 33766,
"text": "Now the user runs the pipeline, which will:"
},
{
"code": null,
"e": 33861,
"s": 33810,
"text": "subtract the images to create a differenced image;"
},
{
"code": null,
"e": 33917,
"s": 33861,
"text": "extract the defects contained in the differenced image;"
},
{
"code": null,
"e": 33969,
"s": 33917,
"text": "predict the defect class for each extracted defect;"
},
{
"code": null,
"e": 34013,
"s": 33969,
"text": "add the predicted cost to the cost summary."
},
{
"code": null,
"e": 34168,
"s": 34013,
"text": "Here’s the fuller video again we saw at the beginning, showing how we can make multiple runs against our pipeline, getting accurate predictions each time:"
},
{
"code": null,
"e": 34405,
"s": 34168,
"text": "Beautiful. We can see that differencing and defect extraction is almost instantaneous. The prediction is set to 1000ms for each extracted defects, which seems reasonable for our demonstration. Is this fast enough for a PCB manufacturer?"
},
{
"code": null,
"e": 34787,
"s": 34405,
"text": "FFeature Idea: Users could be presented a slider to set the prediction time. Based on manufacturing throughput, setting a lower prediction time might make sense. Of course this has to be balanced with how fast the prediction can be made with our pre-trained model (inference time). Setting up a chart showing best inference times would be a good experiment to run and show clients."
},
{
"code": null,
"e": 35165,
"s": 34787,
"text": "There are a number of things we could do to improve our product. While model accuracy is already quite good we didn’t try the other defect types. Will model performance be as good on these defects? What if this product needs to predict at a much higher rate? Would it be worth using shallower networks that run faster inference, while sacrificing some of our hard-won accuracy?"
},
{
"code": null,
"e": 35200,
"s": 35165,
"text": "Here are some things we could try:"
},
{
"code": null,
"e": 35218,
"s": 35200,
"text": "Data Augmentation"
},
{
"code": null,
"e": 35249,
"s": 35218,
"text": "Other hyper-parameter settings"
},
{
"code": null,
"e": 35259,
"s": 35249,
"text": "More data"
},
{
"code": null,
"e": 35283,
"s": 35259,
"text": "Different architectures"
},
{
"code": null,
"e": 35814,
"s": 35283,
"text": "There are also various user experiences we might build for, by way of different/additional product features. Would it make sense for users to have an option to mark bad predictions as incorrect (feed this info back to model). What about tallying additional information about the predicted defects, other than cost? Perhaps creating interesting summarizing visualizations. By embracing rapid prototyping we don’t have to know the answers to these questions upfront; we can build, showcase, and change as needed, with real products."
},
{
"code": null,
"e": 36180,
"s": 35814,
"text": "In this article we created an end-to-end PCB Defect Classifier application. We used image processing to difference sets of test and template PCB images, extract defects using contours, and classify the extracted defects using Deep Learning. We then created a front-end application that allows users to run our machine learning pipeline and review model predictions."
},
{
"code": null,
"e": 36432,
"s": 36180,
"text": "Applications like this help automate tasks that are manual, time-consuming, and prone to human error. The purpose is not to replace human experts, but rather augment their efforts so they may focus on more strategic and creative aspects of their jobs."
},
{
"code": null,
"e": 36625,
"s": 36432,
"text": "If you have any questions / need support please use the comments section. I can help others modify these applications for their specific purpose. Azle questions can be asked on Stack Overflow."
},
{
"code": null,
"e": 36648,
"s": 36625,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 36671,
"s": 36648,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 36694,
"s": 36671,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 36717,
"s": 36694,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 36740,
"s": 36717,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 37286,
"s": 36740,
"text": "You’ll notice that we only get 3 of the defect types. This is because of the way the differencing works. It only picks up the black-differenced defects. The other defects, like mousebites, etc. need to be white-differenced. This can be achieved by simply changing the order of the image paths in the differencing function. Thus, if you want to detect, extract and predict all defects run both versions.If you want to remove the folders in contours run rm -r contours/* in terminal. If you want to remove all images in diff_img run rm diff_img/*."
},
{
"code": null,
"e": 37689,
"s": 37286,
"text": "You’ll notice that we only get 3 of the defect types. This is because of the way the differencing works. It only picks up the black-differenced defects. The other defects, like mousebites, etc. need to be white-differenced. This can be achieved by simply changing the order of the image paths in the differencing function. Thus, if you want to detect, extract and predict all defects run both versions."
},
{
"code": null,
"e": 37833,
"s": 37689,
"text": "If you want to remove the folders in contours run rm -r contours/* in terminal. If you want to remove all images in diff_img run rm diff_img/*."
},
{
"code": null,
"e": 37967,
"s": 37833,
"text": "World PCB Production in 2014 Estimated at $60.2BA PCB Dataset for Defects Detection and Classificationtangsanli5201/DeepPCB on GitHub"
},
{
"code": null,
"e": 38016,
"s": 37967,
"text": "World PCB Production in 2014 Estimated at $60.2B"
},
{
"code": null,
"e": 38071,
"s": 38016,
"text": "A PCB Dataset for Defects Detection and Classification"
}
] |
Angular Google Charts - Tree Map
|
TreeMap is a visual representation of a data tree, where each node may have zero or more children, and one parent (except for the root). Each node is displayed as a rectangle, can be sized and colored according to values that we assign. Sizes and colors are valued relative to all other nodes in the graph. Following is an example of a treemap chart.
We have already seen the configurations used to draw a chart in Google Charts Configuration Syntax chapter. Now, let us see an example of a TreeMap Chart.
We've used TreeMap class to show a TreeMap chart.
type = 'TreeMap';
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = '';
type='TreeMap';
data = [
["Global",null,0,0],
["America","Global",0,0],
["Europe","Global",0,0],
["Asia","Global",0,0],
["Australia","Global",0,0],
["Africa","Global",0,0],
["USA","America",52,31],
["Mexico","America",24,12],
["Canada","America",16,-23],
["France","Europe",42,-11],
["Germany","Europe",31,-2],
["Sweden","Europe",22,-13],
["China","Asia",36,4],
["Japan","Asia",20,-12],
["India","Asia",40,63],
["Egypt","Africa",21,0],
["Congo","Africa",10,12],
["Zaire","Africa",8,10],
];
columnNames = ["Location", "Parent","Market trade volume (size)","Market increase/decrease (color)"];
options = {
minColor:"#ff7777",
midColor:'#ffff77',
maxColor:'#77ff77',
headerHeight:15,
showScale:true
};
width = 550;
height = 400;
}
Verify the result.
16 Lectures
1.5 hours
Anadi Sharma
28 Lectures
2.5 hours
Anadi Sharma
11 Lectures
7.5 hours
SHIVPRASAD KOIRALA
16 Lectures
2.5 hours
Frahaan Hussain
69 Lectures
5 hours
Senol Atac
53 Lectures
3.5 hours
Senol Atac
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2147,
"s": 1796,
"text": "TreeMap is a visual representation of a data tree, where each node may have zero or more children, and one parent (except for the root). Each node is displayed as a rectangle, can be sized and colored according to values that we assign. Sizes and colors are valued relative to all other nodes in the graph. Following is an example of a treemap chart."
},
{
"code": null,
"e": 2302,
"s": 2147,
"text": "We have already seen the configurations used to draw a chart in Google Charts Configuration Syntax chapter. Now, let us see an example of a TreeMap Chart."
},
{
"code": null,
"e": 2352,
"s": 2302,
"text": "We've used TreeMap class to show a TreeMap chart."
},
{
"code": null,
"e": 2371,
"s": 2352,
"text": "type = 'TreeMap';\n"
},
{
"code": null,
"e": 2388,
"s": 2371,
"text": "app.component.ts"
},
{
"code": null,
"e": 3499,
"s": 2388,
"text": "import { Component } from '@angular/core';\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\nexport class AppComponent {\n title = '';\n type='TreeMap';\n data = [\n [\"Global\",null,0,0],\n [\"America\",\"Global\",0,0],\n [\"Europe\",\"Global\",0,0],\n [\"Asia\",\"Global\",0,0],\n [\"Australia\",\"Global\",0,0],\n [\"Africa\",\"Global\",0,0],\n\n [\"USA\",\"America\",52,31],\n [\"Mexico\",\"America\",24,12],\n [\"Canada\",\"America\",16,-23],\n\n [\"France\",\"Europe\",42,-11],\n [\"Germany\",\"Europe\",31,-2],\n [\"Sweden\",\"Europe\",22,-13],\n\n [\"China\",\"Asia\",36,4],\n [\"Japan\",\"Asia\",20,-12],\n [\"India\",\"Asia\",40,63],\n\n [\"Egypt\",\"Africa\",21,0],\n [\"Congo\",\"Africa\",10,12],\n [\"Zaire\",\"Africa\",8,10],\n \n ];\n columnNames = [\"Location\", \"Parent\",\"Market trade volume (size)\",\"Market increase/decrease (color)\"];\n options = { \n minColor:\"#ff7777\",\n midColor:'#ffff77',\n maxColor:'#77ff77',\n headerHeight:15,\n showScale:true\n };\n width = 550;\n height = 400;\n}"
},
{
"code": null,
"e": 3518,
"s": 3499,
"text": "Verify the result."
},
{
"code": null,
"e": 3553,
"s": 3518,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3567,
"s": 3553,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3602,
"s": 3567,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3616,
"s": 3602,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3651,
"s": 3616,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 3671,
"s": 3651,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 3706,
"s": 3671,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3723,
"s": 3706,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3756,
"s": 3723,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 3768,
"s": 3756,
"text": " Senol Atac"
},
{
"code": null,
"e": 3803,
"s": 3768,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3815,
"s": 3803,
"text": " Senol Atac"
},
{
"code": null,
"e": 3822,
"s": 3815,
"text": " Print"
},
{
"code": null,
"e": 3833,
"s": 3822,
"text": " Add Notes"
}
] |
Angular ng Bootstrap Rating Component - GeeksforGeeks
|
06 Jul, 2021
Angular ng bootstrap is a bootstrap framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites.
In this article, we will see how to use Rating in angular ng bootstrap. Rating component is used to make a component that will be shown by using stars.
Installation syntax:
ng add @ng-bootstrap/ng-bootstrap
Approach:
First, install the angular ng bootstrap using the above-mentioned command.
Add the following script in index.html<link href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css” rel=”stylesheet”>
<link href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css” rel=”stylesheet”>
Import ng bootstrap module in module.tsimport { NgbModule } from '@ng-bootstrap/ng-bootstrap';
imports: [
NgbModule
]
In app.component.html, make a rating component.Serve the app using ng serve.
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
imports: [
NgbModule
]
In app.component.html, make a rating component.Serve the app using ng serve.
In app.component.html, make a rating component.
Serve the app using ng serve.
Example 1: In this example, we are making a basic example of rating.
app.component.html
<ngb-rating [(rate)]="gfg"></ngb-rating> <pre>GeeksforGeeks: <b>{{gfg}}</b></pre>
app.module.ts
import { NgModule } from '@angular/core'; // Importing forms moduleimport { FormsModule, ReactiveFormsModule }from '@angular/forms';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { NgbModule }from '@ng-bootstrap/ng-bootstrap'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent ], imports: [ FormsModule, BrowserModule, BrowserAnimationsModule, ReactiveFormsModule, NgbModule ]})export class AppModule { }
app.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { gfg = 5; }
Output:
Example 2: In this example, we have set the rating to readonly.
app.component.html
<ngb-rating [(rate)]="gfg" [readonly]='true'></ngb-rating><pre>GeeksforGeeks: <b>{{gfg}}</b></pre>
app.module.ts
import { NgModule } from '@angular/core'; // Importing forms moduleimport { FormsModule, ReactiveFormsModule } from '@angular/forms';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { NgbModule }from '@ng-bootstrap/ng-bootstrap'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent ], imports: [ FormsModule, BrowserModule, BrowserAnimationsModule, ReactiveFormsModule, NgbModule ]})export class AppModule { }
app.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { gfg = 5; }
Output:
Reference: https://ng-bootstrap.github.io/#/components/rating/examples
Angular-ng-bootstrap
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Angular Libraries For Web Developers
Angular 10 (blur) Event
Angular PrimeNG Dropdown Component
How to make a Bootstrap Modal Popup in Angular 9/8 ?
How to create module with Routing in Angular 9 ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
|
[
{
"code": null,
"e": 25109,
"s": 25081,
"text": "\n06 Jul, 2021"
},
{
"code": null,
"e": 25293,
"s": 25109,
"text": "Angular ng bootstrap is a bootstrap framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites."
},
{
"code": null,
"e": 25445,
"s": 25293,
"text": "In this article, we will see how to use Rating in angular ng bootstrap. Rating component is used to make a component that will be shown by using stars."
},
{
"code": null,
"e": 25466,
"s": 25445,
"text": "Installation syntax:"
},
{
"code": null,
"e": 25500,
"s": 25466,
"text": "ng add @ng-bootstrap/ng-bootstrap"
},
{
"code": null,
"e": 25510,
"s": 25500,
"text": "Approach:"
},
{
"code": null,
"e": 25586,
"s": 25510,
"text": "First, install the angular ng bootstrap using the above-mentioned command. "
},
{
"code": null,
"e": 25727,
"s": 25588,
"text": "Add the following script in index.html<link href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css” rel=”stylesheet”>"
},
{
"code": null,
"e": 25828,
"s": 25727,
"text": "<link href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css” rel=”stylesheet”>"
},
{
"code": null,
"e": 26027,
"s": 25828,
"text": "Import ng bootstrap module in module.tsimport { NgbModule } from '@ng-bootstrap/ng-bootstrap';\n\nimports: [\n NgbModule\n]\n\nIn app.component.html, make a rating component.Serve the app using ng serve."
},
{
"code": null,
"e": 26187,
"s": 26027,
"text": "import { NgbModule } from '@ng-bootstrap/ng-bootstrap';\n\nimports: [\n NgbModule\n]\n\nIn app.component.html, make a rating component.Serve the app using ng serve."
},
{
"code": null,
"e": 26235,
"s": 26187,
"text": "In app.component.html, make a rating component."
},
{
"code": null,
"e": 26265,
"s": 26235,
"text": "Serve the app using ng serve."
},
{
"code": null,
"e": 26336,
"s": 26265,
"text": "Example 1: In this example, we are making a basic example of rating.\n\n"
},
{
"code": null,
"e": 26355,
"s": 26336,
"text": "app.component.html"
},
{
"code": "<ngb-rating [(rate)]=\"gfg\"></ngb-rating> <pre>GeeksforGeeks: <b>{{gfg}}</b></pre>\n",
"e": 26438,
"s": 26355,
"text": null
},
{
"code": null,
"e": 26452,
"s": 26438,
"text": "app.module.ts"
},
{
"code": "import { NgModule } from '@angular/core'; // Importing forms moduleimport { FormsModule, ReactiveFormsModule }from '@angular/forms';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { NgbModule }from '@ng-bootstrap/ng-bootstrap'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent ], imports: [ FormsModule, BrowserModule, BrowserAnimationsModule, ReactiveFormsModule, NgbModule ]})export class AppModule { }",
"e": 27062,
"s": 26452,
"text": null
},
{
"code": null,
"e": 27079,
"s": 27062,
"text": "app.component.ts"
},
{
"code": "import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { gfg = 5; }",
"e": 27283,
"s": 27079,
"text": null
},
{
"code": null,
"e": 27291,
"s": 27283,
"text": "Output:"
},
{
"code": null,
"e": 27355,
"s": 27291,
"text": "Example 2: In this example, we have set the rating to readonly."
},
{
"code": null,
"e": 27374,
"s": 27355,
"text": "app.component.html"
},
{
"code": "<ngb-rating [(rate)]=\"gfg\" [readonly]='true'></ngb-rating><pre>GeeksforGeeks: <b>{{gfg}}</b></pre>",
"e": 27473,
"s": 27374,
"text": null
},
{
"code": null,
"e": 27487,
"s": 27473,
"text": "app.module.ts"
},
{
"code": "import { NgModule } from '@angular/core'; // Importing forms moduleimport { FormsModule, ReactiveFormsModule } from '@angular/forms';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { NgbModule }from '@ng-bootstrap/ng-bootstrap'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent ], imports: [ FormsModule, BrowserModule, BrowserAnimationsModule, ReactiveFormsModule, NgbModule ]})export class AppModule { }",
"e": 28098,
"s": 27487,
"text": null
},
{
"code": null,
"e": 28115,
"s": 28098,
"text": "app.component.ts"
},
{
"code": "import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { gfg = 5; }",
"e": 28319,
"s": 28115,
"text": null
},
{
"code": null,
"e": 28327,
"s": 28319,
"text": "Output:"
},
{
"code": null,
"e": 28398,
"s": 28327,
"text": "Reference: https://ng-bootstrap.github.io/#/components/rating/examples"
},
{
"code": null,
"e": 28419,
"s": 28398,
"text": "Angular-ng-bootstrap"
},
{
"code": null,
"e": 28429,
"s": 28419,
"text": "AngularJS"
},
{
"code": null,
"e": 28446,
"s": 28429,
"text": "Web Technologies"
},
{
"code": null,
"e": 28544,
"s": 28446,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28588,
"s": 28544,
"text": "Top 10 Angular Libraries For Web Developers"
},
{
"code": null,
"e": 28612,
"s": 28588,
"text": "Angular 10 (blur) Event"
},
{
"code": null,
"e": 28647,
"s": 28612,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 28700,
"s": 28647,
"text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?"
},
{
"code": null,
"e": 28749,
"s": 28700,
"text": "How to create module with Routing in Angular 9 ?"
},
{
"code": null,
"e": 28791,
"s": 28749,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 28824,
"s": 28791,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28886,
"s": 28824,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28929,
"s": 28886,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How do I unload (reload) a Python module?
|
The function reload(moduleName) reloads a previously loaded module (assuming you loaded it with the syntax "importmoduleName" without exiting the script. It is intended for conversational use, where you have edited the source file for a module and want to test it without leaving Python and starting it again. For example,
>>> import mymodule
>>> # Edited mymoduleand want to reload it in this script
>>> reload(mymodule)
Note that the moduleName is the actual name of the module, not a string containing its name. The python docs state following about reload function:
Python modules’ code is recompiled and the module-level code re-executed, defining a new set of objects which are bound to names in the module’s dictionary. The init function of extension modules is not called a second time. The names in the module namespace are updated to point to any new or changed objects. Other references to the old objects (such as names external to the module) are not rebound to refer to the new objects and must be updated in each namespace where they occur if that is desired.
|
[
{
"code": null,
"e": 1385,
"s": 1062,
"text": "The function reload(moduleName) reloads a previously loaded module (assuming you loaded it with the syntax \"importmoduleName\" without exiting the script. It is intended for conversational use, where you have edited the source file for a module and want to test it without leaving Python and starting it again. For example,"
},
{
"code": null,
"e": 1484,
"s": 1385,
"text": ">>> import mymodule\n>>> # Edited mymoduleand want to reload it in this script\n>>> reload(mymodule)"
},
{
"code": null,
"e": 1632,
"s": 1484,
"text": "Note that the moduleName is the actual name of the module, not a string containing its name. The python docs state following about reload function:"
},
{
"code": null,
"e": 2138,
"s": 1632,
"text": " Python modules’ code is recompiled and the module-level code re-executed, defining a new set of objects which are bound to names in the module’s dictionary. The init function of extension modules is not called a second time. The names in the module namespace are updated to point to any new or changed objects. Other references to the old objects (such as names external to the module) are not rebound to refer to the new objects and must be updated in each namespace where they occur if that is desired."
}
] |
Declare an empty List in Python - GeeksforGeeks
|
12 Dec, 2019
Lists are just like the arrays, declared in other languages. Lists need not be homogeneous always which makes it the most powerful tool in Python. A single list may contain DataTypes like Integers, Strings, as well as Objects. Lists are mutable, and hence, they can be altered even after their creation.
However, Have you ever wondered about how to declare an empty list in Python? This can be achieved by two ways i.e. either by using square brackets[] or using the list() constructor.
Using square brackets []Lists in Python can be created by just placing the sequence inside the square brackets[]. To declare an empty list just assign a variable with square brackets.
Example:
# Python program to declare# empty list # list is declareda = [] print("Values of a:", a)print("Type of a:", type(a))print("Size of a:", len(a))
Output:
Values of a: []
Type of a: <class 'list'>
Size of a: 0
Using list() constructorThe list() constructor is used to create list in Python.
Syntax: list([iterable])
Parameters:iterable: This is an optional argument that can be a sequence(string, tuple) or collection(dictionary, set) or an iterator object.
Return Type:
Returns an empty list if no parameters are passed.
If a parameter is passed then it returns a list of elements in the iterable.
Example:
# Python program to create# empty list # list is declareda = list() print("Values of a:", a)print("Type of a:", type(a))print("Size of a:", len(a))
Output:
Values of a: []
Type of a: <class 'list'>
Size of a: 0
python-list
Python
Technical Scripter
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
*args and **kwargs in Python
How to drop one or multiple columns in Pandas Dataframe
|
[
{
"code": null,
"e": 24402,
"s": 24374,
"text": "\n12 Dec, 2019"
},
{
"code": null,
"e": 24706,
"s": 24402,
"text": "Lists are just like the arrays, declared in other languages. Lists need not be homogeneous always which makes it the most powerful tool in Python. A single list may contain DataTypes like Integers, Strings, as well as Objects. Lists are mutable, and hence, they can be altered even after their creation."
},
{
"code": null,
"e": 24889,
"s": 24706,
"text": "However, Have you ever wondered about how to declare an empty list in Python? This can be achieved by two ways i.e. either by using square brackets[] or using the list() constructor."
},
{
"code": null,
"e": 25073,
"s": 24889,
"text": "Using square brackets []Lists in Python can be created by just placing the sequence inside the square brackets[]. To declare an empty list just assign a variable with square brackets."
},
{
"code": null,
"e": 25082,
"s": 25073,
"text": "Example:"
},
{
"code": "# Python program to declare# empty list # list is declareda = [] print(\"Values of a:\", a)print(\"Type of a:\", type(a))print(\"Size of a:\", len(a)) ",
"e": 25243,
"s": 25082,
"text": null
},
{
"code": null,
"e": 25251,
"s": 25243,
"text": "Output:"
},
{
"code": null,
"e": 25307,
"s": 25251,
"text": "Values of a: []\nType of a: <class 'list'>\nSize of a: 0\n"
},
{
"code": null,
"e": 25388,
"s": 25307,
"text": "Using list() constructorThe list() constructor is used to create list in Python."
},
{
"code": null,
"e": 25413,
"s": 25388,
"text": "Syntax: list([iterable])"
},
{
"code": null,
"e": 25555,
"s": 25413,
"text": "Parameters:iterable: This is an optional argument that can be a sequence(string, tuple) or collection(dictionary, set) or an iterator object."
},
{
"code": null,
"e": 25568,
"s": 25555,
"text": "Return Type:"
},
{
"code": null,
"e": 25619,
"s": 25568,
"text": "Returns an empty list if no parameters are passed."
},
{
"code": null,
"e": 25696,
"s": 25619,
"text": "If a parameter is passed then it returns a list of elements in the iterable."
},
{
"code": null,
"e": 25705,
"s": 25696,
"text": "Example:"
},
{
"code": "# Python program to create# empty list # list is declareda = list() print(\"Values of a:\", a)print(\"Type of a:\", type(a))print(\"Size of a:\", len(a)) ",
"e": 25864,
"s": 25705,
"text": null
},
{
"code": null,
"e": 25872,
"s": 25864,
"text": "Output:"
},
{
"code": null,
"e": 25928,
"s": 25872,
"text": "Values of a: []\nType of a: <class 'list'>\nSize of a: 0\n"
},
{
"code": null,
"e": 25940,
"s": 25928,
"text": "python-list"
},
{
"code": null,
"e": 25947,
"s": 25940,
"text": "Python"
},
{
"code": null,
"e": 25966,
"s": 25947,
"text": "Technical Scripter"
},
{
"code": null,
"e": 25978,
"s": 25966,
"text": "python-list"
},
{
"code": null,
"e": 26076,
"s": 25978,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26085,
"s": 26076,
"text": "Comments"
},
{
"code": null,
"e": 26098,
"s": 26085,
"text": "Old Comments"
},
{
"code": null,
"e": 26116,
"s": 26098,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26151,
"s": 26116,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26183,
"s": 26151,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26225,
"s": 26183,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26251,
"s": 26225,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26294,
"s": 26251,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 26331,
"s": 26294,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 26375,
"s": 26331,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 26404,
"s": 26375,
"text": "*args and **kwargs in Python"
}
] |
Dynamic filtering in Power BI. Check this simple technique to avoid... | by Nikola Ilic | Towards Data Science
|
Recently, I’ve come across a request to deliver a report which will enable end-users to choose if they want to see data filtered by specific year/month or as Year-To-Date calculation. I wrote about 5 useful tips and tricks which can boost your Power BI development, but I thought that this one deserves a separate post.
The first thing that came to my mind was to play around with buttons, actions, and bookmarks, but I’ve decided to apply different approaches in tackling this.
So, let’s switch to Power BI and I will show you how to achieve this dynamic filtering. I’m using the Contoso database for this example.
The first step is creating a measure for Sales Amount, and it’s pretty straightforward:
Sales Amt = SUM('Online Sales'[SalesAmount])
Since I also need a measure which will calculate Year-To-Date Sales Amount (YTD), let’s create it as:
Sales Amt YTD = CALCULATE('Online Sales'[Sales Amt],DATESYTD(Dates[Date]))
Here, we are simply using built-in DAX function DATESYTD, which will automatically evaluate an expression and return desired values. So, when I drag a table to Power BI Desktop canvas and select for the example year 2009, I’m getting the following numbers for our newly created measures:
As you can see, Sales Amt shows figures for every selected month, while Sales Amt YTD simply adds those figures to display YTD values.
Ok, that was simple. Now, I need to find a way to enable users to see one of the specific values, based on their selection. As I mentioned in the beginning, this can be achieved using buttons and bookmarks, with hiding and showing visuals based on the user’s selection, but let’s try with a slightly different approach.
Let’s first create a new table, which will hold data for our dynamic filter:
Under Enter Data, I’ve just created a plain simple table called Calculation TimeFrame, with 2 columns: ID and TimeFrame. Of course, you can define as many options as you want, depending on your needs. After I loaded this table to a model, I need to find a way to somehow connect this table with my existing model.
First of all, I need to know what user selected to display, therefore the following measure needs to be created:
Selected TimeFrame = MIN('Calculation TimeFrame'[ID])
This measure will return the minimum ID value of user selection. In case that no value is selected, the option with ID = 1 (Monthly) will be displayed.
The next step is the most interesting since it puts user’s selection in context of existing data model. Within the Online Sales table, I create the following measure:
Sales Amt Selected = SWITCH([Selected TimeFrame], 1,'Online Sales'[Sales Amt], 2,'Online Sales'[Sales Amt YTD])
Let me shortly explain what this measure does: It takes ID value from user selection, and based on that value, display respective calculation. It is easily done with the SWITCH function. To translate what this function does: if the user chooses ID 1 (Monthly), return me Sales Amt value. If he chooses 2 (YTD), return YTD value. Simple as that.
The final touch is to create a filter for this. Simply drag Slicer visual and put the Time Frame field. Make that Horizontal, so it looks a bit nicer:
As you can see, by default Monthly time frame will be displayed:
However, if you click on the YTD slicer button, visuals will perform differently:
Now, visuals show YTD values:)
This is a neat trick on how to avoid using buttons and bookmarks for some usual users’ requests and still keep everything tidy. Key thing is to define proper measures and to link your custom tables with the data model, after that it’s up to you to define limits for usage of this technique.
Become a member and read every story on Medium!
Subscribe here to get more insightful data articles!
|
[
{
"code": null,
"e": 491,
"s": 171,
"text": "Recently, I’ve come across a request to deliver a report which will enable end-users to choose if they want to see data filtered by specific year/month or as Year-To-Date calculation. I wrote about 5 useful tips and tricks which can boost your Power BI development, but I thought that this one deserves a separate post."
},
{
"code": null,
"e": 650,
"s": 491,
"text": "The first thing that came to my mind was to play around with buttons, actions, and bookmarks, but I’ve decided to apply different approaches in tackling this."
},
{
"code": null,
"e": 787,
"s": 650,
"text": "So, let’s switch to Power BI and I will show you how to achieve this dynamic filtering. I’m using the Contoso database for this example."
},
{
"code": null,
"e": 875,
"s": 787,
"text": "The first step is creating a measure for Sales Amount, and it’s pretty straightforward:"
},
{
"code": null,
"e": 920,
"s": 875,
"text": "Sales Amt = SUM('Online Sales'[SalesAmount])"
},
{
"code": null,
"e": 1022,
"s": 920,
"text": "Since I also need a measure which will calculate Year-To-Date Sales Amount (YTD), let’s create it as:"
},
{
"code": null,
"e": 1097,
"s": 1022,
"text": "Sales Amt YTD = CALCULATE('Online Sales'[Sales Amt],DATESYTD(Dates[Date]))"
},
{
"code": null,
"e": 1385,
"s": 1097,
"text": "Here, we are simply using built-in DAX function DATESYTD, which will automatically evaluate an expression and return desired values. So, when I drag a table to Power BI Desktop canvas and select for the example year 2009, I’m getting the following numbers for our newly created measures:"
},
{
"code": null,
"e": 1520,
"s": 1385,
"text": "As you can see, Sales Amt shows figures for every selected month, while Sales Amt YTD simply adds those figures to display YTD values."
},
{
"code": null,
"e": 1840,
"s": 1520,
"text": "Ok, that was simple. Now, I need to find a way to enable users to see one of the specific values, based on their selection. As I mentioned in the beginning, this can be achieved using buttons and bookmarks, with hiding and showing visuals based on the user’s selection, but let’s try with a slightly different approach."
},
{
"code": null,
"e": 1917,
"s": 1840,
"text": "Let’s first create a new table, which will hold data for our dynamic filter:"
},
{
"code": null,
"e": 2231,
"s": 1917,
"text": "Under Enter Data, I’ve just created a plain simple table called Calculation TimeFrame, with 2 columns: ID and TimeFrame. Of course, you can define as many options as you want, depending on your needs. After I loaded this table to a model, I need to find a way to somehow connect this table with my existing model."
},
{
"code": null,
"e": 2344,
"s": 2231,
"text": "First of all, I need to know what user selected to display, therefore the following measure needs to be created:"
},
{
"code": null,
"e": 2398,
"s": 2344,
"text": "Selected TimeFrame = MIN('Calculation TimeFrame'[ID])"
},
{
"code": null,
"e": 2550,
"s": 2398,
"text": "This measure will return the minimum ID value of user selection. In case that no value is selected, the option with ID = 1 (Monthly) will be displayed."
},
{
"code": null,
"e": 2717,
"s": 2550,
"text": "The next step is the most interesting since it puts user’s selection in context of existing data model. Within the Online Sales table, I create the following measure:"
},
{
"code": null,
"e": 2875,
"s": 2717,
"text": "Sales Amt Selected = SWITCH([Selected TimeFrame], 1,'Online Sales'[Sales Amt], 2,'Online Sales'[Sales Amt YTD])"
},
{
"code": null,
"e": 3220,
"s": 2875,
"text": "Let me shortly explain what this measure does: It takes ID value from user selection, and based on that value, display respective calculation. It is easily done with the SWITCH function. To translate what this function does: if the user chooses ID 1 (Monthly), return me Sales Amt value. If he chooses 2 (YTD), return YTD value. Simple as that."
},
{
"code": null,
"e": 3371,
"s": 3220,
"text": "The final touch is to create a filter for this. Simply drag Slicer visual and put the Time Frame field. Make that Horizontal, so it looks a bit nicer:"
},
{
"code": null,
"e": 3436,
"s": 3371,
"text": "As you can see, by default Monthly time frame will be displayed:"
},
{
"code": null,
"e": 3518,
"s": 3436,
"text": "However, if you click on the YTD slicer button, visuals will perform differently:"
},
{
"code": null,
"e": 3549,
"s": 3518,
"text": "Now, visuals show YTD values:)"
},
{
"code": null,
"e": 3840,
"s": 3549,
"text": "This is a neat trick on how to avoid using buttons and bookmarks for some usual users’ requests and still keep everything tidy. Key thing is to define proper measures and to link your custom tables with the data model, after that it’s up to you to define limits for usage of this technique."
},
{
"code": null,
"e": 3888,
"s": 3840,
"text": "Become a member and read every story on Medium!"
}
] |
Create a large button group with Bootstrap
|
To create a large button group in Bootstrap, use the .btn-group-lg class.
You can try to run the following code to form a large button group −
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Example</title>
<link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
</head>
<body>
<p>The following are the car brands:</p>
<div class = "btn-group-justified">
<button type = "button" class = "btn btn-default">BMW</button>
<button type = "button" class = "btn btn-default">Audi</button>
<button type = "button" class = "btn btn-default">Jeep</button>
<button type = "button" class = "btn btn-default">Datsun</button>
<button type = "button" class = "btn btn-default">Toyota</button>
</div>
<p>The following are FMCG:</p>
<div class = "btn-group-justified btn-group-lg">
<button type = "button" class = "btn btn-default">ITC Limited</button>
<button type = "button" class = "btn btn-default">Colgate-Palmolive</button>
<button type = "button" class = "btn btn-default">Nestle</button>
<button type="button" class = "btn btn-default">Britannia Industries Limited</button>
</div>
</body>
</html>
|
[
{
"code": null,
"e": 1136,
"s": 1062,
"text": "To create a large button group in Bootstrap, use the .btn-group-lg class."
},
{
"code": null,
"e": 1205,
"s": 1136,
"text": "You can try to run the following code to form a large button group −"
},
{
"code": null,
"e": 1215,
"s": 1205,
"text": "Live Demo"
},
{
"code": null,
"e": 2546,
"s": 1215,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link rel = \"stylesheet\" href = \"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css\">\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src = \"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <p>The following are the car brands:</p>\n <div class = \"btn-group-justified\">\n <button type = \"button\" class = \"btn btn-default\">BMW</button>\n <button type = \"button\" class = \"btn btn-default\">Audi</button>\n <button type = \"button\" class = \"btn btn-default\">Jeep</button>\n <button type = \"button\" class = \"btn btn-default\">Datsun</button>\n <button type = \"button\" class = \"btn btn-default\">Toyota</button>\n </div>\n <p>The following are FMCG:</p>\n <div class = \"btn-group-justified btn-group-lg\">\n <button type = \"button\" class = \"btn btn-default\">ITC Limited</button>\n <button type = \"button\" class = \"btn btn-default\">Colgate-Palmolive</button>\n <button type = \"button\" class = \"btn btn-default\">Nestle</button>\n <button type=\"button\" class = \"btn btn-default\">Britannia Industries Limited</button>\n </div>\n </body>\n</html>"
}
] |
3 Methods for Parallelization in Spark | by Ben Weber | Towards Data Science
|
Spark is great for scaling up data science tasks and workloads! As long as you’re using Spark data frames and libraries that operate on these data structures, you can scale to massive data sets that distribute across a cluster. However, there are some scenarios where libraries may not be available for working with Spark data frames, and other approaches are needed to achieve parallelization with Spark. This post discusses three different ways of achieving parallelization in PySpark:
Native Spark: if you’re using Spark data frames and libraries (e.g. MLlib), then your code we’ll be parallelized and distributed natively by Spark.Thread Pools: The multiprocessing library can be used to run concurrent Python threads, and even perform operations with Spark data frames.Pandas UDFs: A new feature in Spark that enables parallelized processing on Pandas data frames within a Spark environment.
Native Spark: if you’re using Spark data frames and libraries (e.g. MLlib), then your code we’ll be parallelized and distributed natively by Spark.
Thread Pools: The multiprocessing library can be used to run concurrent Python threads, and even perform operations with Spark data frames.
Pandas UDFs: A new feature in Spark that enables parallelized processing on Pandas data frames within a Spark environment.
I’ll provide examples of each of these different approaches to achieving parallelism in PySpark, using the Boston housing data set as a sample data set.
Before getting started, it;s important to make a distinction between parallelism and distribution in Spark. When a task is parallelized in Spark, it means that concurrent tasks may be running on the driver node or worker nodes. How the task is split across these different nodes in the cluster depends on the types of data structures and libraries that you’re using. It’s possible to have parallelism without distribution in Spark, which means that the driver node may be performing all of the work. This is a situation that happens with the scikit-learn example with thread pools that I discuss below, and should be avoided if possible. When a task is distributed in Spark, it means that the data being operated on is split across different nodes in the cluster, and that the tasks are being performed concurrently. Ideally, you want to author tasks that are both parallelized and distributed.
The full notebook for the examples presented in this tutorial are available on GitHub and a rendering of the notebook is available here. I used the Databricks community edition to author this notebook and previously wrote about using this environment in my PySpark introduction post.
Before showing off parallel processing in Spark, let’s start with a single node example in base Python. I used the Boston housing data set to build a regression model for predicting house prices using 13 different features. The code below shows how to load the data set, and convert the data set into a Pandas data frame.
Next, we split the data set into training and testing groups and separate the features from the labels for each group. We then use the LinearRegression class to fit the training data set and create predictions for the test data set. The last portion of the snippet below shows how to calculate the correlation coefficient between the actual and predicted house prices.
We now have a task that we’d like to parallelize. For this tutorial, the goal of parallelizing the task is to try out different hyperparameters concurrently, but this is just one example of the types of tasks you can parallelize with Spark.
If you use Spark data frames and libraries, then Spark will natively parallelize and distribute your task. First, we’ll need to convert the Pandas data frame to a Spark data frame, and then transform the features into the sparse vector representation required for MLlib. The snippet below shows how to perform this task for the housing data set.
In general, it’s best to avoid loading data into a Pandas representation before converting it to Spark. Instead, use interfaces such as spark.read to directly load data sources into Spark data frames.
Now that we have the data prepared in the Spark format, we can use MLlib to perform parallelized fitting and model prediction. The snippet below shows how to instantiate and train a linear regression model and calculate the correlation coefficient for the estimated house prices.
When operating on Spark data frames in the Databricks environment, you’ll notice a list of tasks shown below the cell. This output indicates that the task is being distributed to different worker nodes in the cluster. In the single threaded example, all code executed on the driver node.
We now have a model fitting and prediction task that is parallelized. However, what if we also want to concurrently try out different hyperparameter configurations? You can do this manually, as shown in the next two sections, or use the CrossValidator class that performs this operation natively in Spark. The code below shows how to try out different elastic net parameters using cross validation to select the best performing model.
If MLlib has the libraries you need for building predictive models, then it’s usually straightforward to parallelize a task. However, you may want to use algorithms that are not included in MLlib, or use other Python libraries that don’t work directly with Spark data frames. This is where thread pools and Pandas UDFs become useful.
One of the ways that you can achieve parallelism in Spark without using Spark data frames is by using the multiprocessing library. The library provides a thread abstraction that you can use to create concurrent threads of execution. However, by default all of your code will run on the driver node. The snippet below shows how to create a set of threads that will run in parallel, are return results for different hyperparameters for a random forest.
This approach works by using the map function on a pool of threads. The map function takes a lambda expression and array of values as input, and invokes the lambda expression for each of the values in the array. Once all of the threads complete, the output displays the hyperparameter value (n_estimators) and the R-squared result for each thread.
[[10, 0.92121913976894299], [20, 0.92413752558900675], [50, 0.92705124846648523]]
Using thread pools this way is dangerous, because all of the threads will execute on the driver node. If possible it’s best to use Spark data frames when working with thread pools, because then the operations will be distributed across the worker nodes in the cluster. The MLib version of using thread pools is shown in the example below, which distributes the tasks to worker nodes.
One of the newer features in Spark that enables parallel processing is Pandas UDFs. With this feature, you can partition a Spark data frame into smaller data sets that are distributed and converted to Pandas objects, where your function is applied, and then the results are combined back into one large Spark data frame. Essentially, Pandas UDFs enable data scientists to work with base Python libraries while getting the benefits of parallelization and distribution. I provided an example of this functionality in my PySpark introduction post, and I’ll be presenting how Zynga uses functionality at Spark Summit 2019.
The code below shows how to perform parallelized (and distributed) hyperparameter tuning when using scikit-learn. The first part of this script takes the Boston data set and performs a cross join that create multiple copies of the input data set, and also appends a tree value (n_estimators) to each group. Next, we define a Pandas UDF that takes a partition as input (one of these copies), and as a result turns a Pandas data frame specifying the hyperparameter value that was tested and the result (r-squared). The final step is the groupby and apply call that performs the parallelized calculation.
With this approach, the result is similar to the method with thread pools, but the main difference is that the task is distributed across worker nodes rather than performed only on the driver. Example output is below:
[Row(trees=20, r_squared=0.8633562691646341), Row(trees=50, r_squared=0.866335129308371), Row(trees=11, r_squared=0.8257884742588874)]
There’s multiple ways of achieving parallelism when using PySpark for data science. It’s best to use native libraries if possible, but based on your use cases there may not be Spark libraries available. In this situation, it’s possible to use thread pools or Pandas UDFs to parallelize your Python code in a Spark environment. Just be careful about how you parallelize your tasks, and try to also distribute workloads if possible.
Ben Weber is a principal data scientist at Zynga. We are hiring!
|
[
{
"code": null,
"e": 660,
"s": 172,
"text": "Spark is great for scaling up data science tasks and workloads! As long as you’re using Spark data frames and libraries that operate on these data structures, you can scale to massive data sets that distribute across a cluster. However, there are some scenarios where libraries may not be available for working with Spark data frames, and other approaches are needed to achieve parallelization with Spark. This post discusses three different ways of achieving parallelization in PySpark:"
},
{
"code": null,
"e": 1069,
"s": 660,
"text": "Native Spark: if you’re using Spark data frames and libraries (e.g. MLlib), then your code we’ll be parallelized and distributed natively by Spark.Thread Pools: The multiprocessing library can be used to run concurrent Python threads, and even perform operations with Spark data frames.Pandas UDFs: A new feature in Spark that enables parallelized processing on Pandas data frames within a Spark environment."
},
{
"code": null,
"e": 1217,
"s": 1069,
"text": "Native Spark: if you’re using Spark data frames and libraries (e.g. MLlib), then your code we’ll be parallelized and distributed natively by Spark."
},
{
"code": null,
"e": 1357,
"s": 1217,
"text": "Thread Pools: The multiprocessing library can be used to run concurrent Python threads, and even perform operations with Spark data frames."
},
{
"code": null,
"e": 1480,
"s": 1357,
"text": "Pandas UDFs: A new feature in Spark that enables parallelized processing on Pandas data frames within a Spark environment."
},
{
"code": null,
"e": 1633,
"s": 1480,
"text": "I’ll provide examples of each of these different approaches to achieving parallelism in PySpark, using the Boston housing data set as a sample data set."
},
{
"code": null,
"e": 2528,
"s": 1633,
"text": "Before getting started, it;s important to make a distinction between parallelism and distribution in Spark. When a task is parallelized in Spark, it means that concurrent tasks may be running on the driver node or worker nodes. How the task is split across these different nodes in the cluster depends on the types of data structures and libraries that you’re using. It’s possible to have parallelism without distribution in Spark, which means that the driver node may be performing all of the work. This is a situation that happens with the scikit-learn example with thread pools that I discuss below, and should be avoided if possible. When a task is distributed in Spark, it means that the data being operated on is split across different nodes in the cluster, and that the tasks are being performed concurrently. Ideally, you want to author tasks that are both parallelized and distributed."
},
{
"code": null,
"e": 2812,
"s": 2528,
"text": "The full notebook for the examples presented in this tutorial are available on GitHub and a rendering of the notebook is available here. I used the Databricks community edition to author this notebook and previously wrote about using this environment in my PySpark introduction post."
},
{
"code": null,
"e": 3134,
"s": 2812,
"text": "Before showing off parallel processing in Spark, let’s start with a single node example in base Python. I used the Boston housing data set to build a regression model for predicting house prices using 13 different features. The code below shows how to load the data set, and convert the data set into a Pandas data frame."
},
{
"code": null,
"e": 3503,
"s": 3134,
"text": "Next, we split the data set into training and testing groups and separate the features from the labels for each group. We then use the LinearRegression class to fit the training data set and create predictions for the test data set. The last portion of the snippet below shows how to calculate the correlation coefficient between the actual and predicted house prices."
},
{
"code": null,
"e": 3744,
"s": 3503,
"text": "We now have a task that we’d like to parallelize. For this tutorial, the goal of parallelizing the task is to try out different hyperparameters concurrently, but this is just one example of the types of tasks you can parallelize with Spark."
},
{
"code": null,
"e": 4090,
"s": 3744,
"text": "If you use Spark data frames and libraries, then Spark will natively parallelize and distribute your task. First, we’ll need to convert the Pandas data frame to a Spark data frame, and then transform the features into the sparse vector representation required for MLlib. The snippet below shows how to perform this task for the housing data set."
},
{
"code": null,
"e": 4291,
"s": 4090,
"text": "In general, it’s best to avoid loading data into a Pandas representation before converting it to Spark. Instead, use interfaces such as spark.read to directly load data sources into Spark data frames."
},
{
"code": null,
"e": 4571,
"s": 4291,
"text": "Now that we have the data prepared in the Spark format, we can use MLlib to perform parallelized fitting and model prediction. The snippet below shows how to instantiate and train a linear regression model and calculate the correlation coefficient for the estimated house prices."
},
{
"code": null,
"e": 4859,
"s": 4571,
"text": "When operating on Spark data frames in the Databricks environment, you’ll notice a list of tasks shown below the cell. This output indicates that the task is being distributed to different worker nodes in the cluster. In the single threaded example, all code executed on the driver node."
},
{
"code": null,
"e": 5294,
"s": 4859,
"text": "We now have a model fitting and prediction task that is parallelized. However, what if we also want to concurrently try out different hyperparameter configurations? You can do this manually, as shown in the next two sections, or use the CrossValidator class that performs this operation natively in Spark. The code below shows how to try out different elastic net parameters using cross validation to select the best performing model."
},
{
"code": null,
"e": 5628,
"s": 5294,
"text": "If MLlib has the libraries you need for building predictive models, then it’s usually straightforward to parallelize a task. However, you may want to use algorithms that are not included in MLlib, or use other Python libraries that don’t work directly with Spark data frames. This is where thread pools and Pandas UDFs become useful."
},
{
"code": null,
"e": 6079,
"s": 5628,
"text": "One of the ways that you can achieve parallelism in Spark without using Spark data frames is by using the multiprocessing library. The library provides a thread abstraction that you can use to create concurrent threads of execution. However, by default all of your code will run on the driver node. The snippet below shows how to create a set of threads that will run in parallel, are return results for different hyperparameters for a random forest."
},
{
"code": null,
"e": 6427,
"s": 6079,
"text": "This approach works by using the map function on a pool of threads. The map function takes a lambda expression and array of values as input, and invokes the lambda expression for each of the values in the array. Once all of the threads complete, the output displays the hyperparameter value (n_estimators) and the R-squared result for each thread."
},
{
"code": null,
"e": 6513,
"s": 6427,
"text": "[[10, 0.92121913976894299], [20, 0.92413752558900675], [50, 0.92705124846648523]]"
},
{
"code": null,
"e": 6897,
"s": 6513,
"text": "Using thread pools this way is dangerous, because all of the threads will execute on the driver node. If possible it’s best to use Spark data frames when working with thread pools, because then the operations will be distributed across the worker nodes in the cluster. The MLib version of using thread pools is shown in the example below, which distributes the tasks to worker nodes."
},
{
"code": null,
"e": 7516,
"s": 6897,
"text": "One of the newer features in Spark that enables parallel processing is Pandas UDFs. With this feature, you can partition a Spark data frame into smaller data sets that are distributed and converted to Pandas objects, where your function is applied, and then the results are combined back into one large Spark data frame. Essentially, Pandas UDFs enable data scientists to work with base Python libraries while getting the benefits of parallelization and distribution. I provided an example of this functionality in my PySpark introduction post, and I’ll be presenting how Zynga uses functionality at Spark Summit 2019."
},
{
"code": null,
"e": 8118,
"s": 7516,
"text": "The code below shows how to perform parallelized (and distributed) hyperparameter tuning when using scikit-learn. The first part of this script takes the Boston data set and performs a cross join that create multiple copies of the input data set, and also appends a tree value (n_estimators) to each group. Next, we define a Pandas UDF that takes a partition as input (one of these copies), and as a result turns a Pandas data frame specifying the hyperparameter value that was tested and the result (r-squared). The final step is the groupby and apply call that performs the parallelized calculation."
},
{
"code": null,
"e": 8336,
"s": 8118,
"text": "With this approach, the result is similar to the method with thread pools, but the main difference is that the task is distributed across worker nodes rather than performed only on the driver. Example output is below:"
},
{
"code": null,
"e": 8473,
"s": 8336,
"text": "[Row(trees=20, r_squared=0.8633562691646341), Row(trees=50, r_squared=0.866335129308371), Row(trees=11, r_squared=0.8257884742588874)]"
},
{
"code": null,
"e": 8904,
"s": 8473,
"text": "There’s multiple ways of achieving parallelism when using PySpark for data science. It’s best to use native libraries if possible, but based on your use cases there may not be Spark libraries available. In this situation, it’s possible to use thread pools or Pandas UDFs to parallelize your Python code in a Spark environment. Just be careful about how you parallelize your tasks, and try to also distribute workloads if possible."
}
] |
Java Program to display Time in 12-hour format
|
Use the SimpleDateFormat class to display time in 12-hour format.
Set the format
Date dt = new Date();
SimpleDateFormat dateFormat;
dateFormat = new SimpleDateFormat("hh:mm:ss a");
Now, the following will display time in 12-hour format
dateFormat.format(dt)
The following is an example
Live Demo
import java.text.SimpleDateFormat;
import java.util.Date;
public class Demo {
public static void main(String[] argv) throws Exception {
Date dt = new Date();
SimpleDateFormat dateFormat;
dateFormat = new SimpleDateFormat("hh:mm:ss a");
System.out.println("Time in 12 hr format = "+dateFormat.format(dt));
}
}
Time in 12 hr format = 11:33:53 AM
|
[
{
"code": null,
"e": 1128,
"s": 1062,
"text": "Use the SimpleDateFormat class to display time in 12-hour format."
},
{
"code": null,
"e": 1143,
"s": 1128,
"text": "Set the format"
},
{
"code": null,
"e": 1243,
"s": 1143,
"text": "Date dt = new Date();\nSimpleDateFormat dateFormat;\ndateFormat = new SimpleDateFormat(\"hh:mm:ss a\");"
},
{
"code": null,
"e": 1298,
"s": 1243,
"text": "Now, the following will display time in 12-hour format"
},
{
"code": null,
"e": 1320,
"s": 1298,
"text": "dateFormat.format(dt)"
},
{
"code": null,
"e": 1348,
"s": 1320,
"text": "The following is an example"
},
{
"code": null,
"e": 1359,
"s": 1348,
"text": " Live Demo"
},
{
"code": null,
"e": 1698,
"s": 1359,
"text": "import java.text.SimpleDateFormat;\nimport java.util.Date;\npublic class Demo {\n public static void main(String[] argv) throws Exception {\n Date dt = new Date();\n SimpleDateFormat dateFormat;\n dateFormat = new SimpleDateFormat(\"hh:mm:ss a\");\n System.out.println(\"Time in 12 hr format = \"+dateFormat.format(dt));\n }\n}"
},
{
"code": null,
"e": 1733,
"s": 1698,
"text": "Time in 12 hr format = 11:33:53 AM"
}
] |
Integer toString() in Java
|
The toString() method of the java.lang.Integer returns a string object. The Integer class has three toString() methods. Let us see them one by one −
The java.lang.Integer.toString() method returns a String object representing this Integer's value. Let us now see an example −
Live Demo
import java.lang.*;
public class Demo {
public static void main(String[] args) {
Integer i = new Integer(20);
// returns a string representation of the integer value in base 10
String retval = i.toString();
System.out.println("Value = " + retval);
}
}
Value = 20
The java.lang.Integer.toString(int i) method returns a String object representing the specified integer. Here, i is the integer to be converted.
Let us now see an example −
Live Demo
import java.lang.*;
public class Demo {
public static void main(String[] args) {
Integer i = new Integer(10);
// returns a string representation of the specified integer in base 10
String retval = i.toString(30);
System.out.println("Value = " + retval);
}
}
Value = 30
The java.lang.Integer.toString(int i, int radix) method returns a string representation of the first argument i in the radix specified by the second argument radix.If the radix is smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX, then the radix 10 is used instead.
Here, i is the integer to be converted, whereas radix is the radix to be used in the string representation.
Let us now see an example −
Live Demo
import java.lang.*;
public class Demo {
public static void main(String[] args) {
Integer i = new Integer(10);
// returns a string representation of the specified integer with radix 10
String retval = i.toString(30, 10);
System.out.println("Value = " + retval);
// returns a string representation of the specified integer with radix 16
retval = i.toString(30, 16);
System.out.println("Value = " + retval);
// returns a string representation of the specified integer with radix 8
retval = i.toString(30, 8);
System.out.println("Value = " + retval);
}
}
Value = 30
Value = 1e
Value = 36
|
[
{
"code": null,
"e": 1211,
"s": 1062,
"text": "The toString() method of the java.lang.Integer returns a string object. The Integer class has three toString() methods. Let us see them one by one −"
},
{
"code": null,
"e": 1338,
"s": 1211,
"text": "The java.lang.Integer.toString() method returns a String object representing this Integer's value. Let us now see an example −"
},
{
"code": null,
"e": 1349,
"s": 1338,
"text": " Live Demo"
},
{
"code": null,
"e": 1631,
"s": 1349,
"text": "import java.lang.*;\npublic class Demo {\n public static void main(String[] args) {\n Integer i = new Integer(20);\n // returns a string representation of the integer value in base 10\n String retval = i.toString();\n System.out.println(\"Value = \" + retval);\n }\n}"
},
{
"code": null,
"e": 1642,
"s": 1631,
"text": "Value = 20"
},
{
"code": null,
"e": 1787,
"s": 1642,
"text": "The java.lang.Integer.toString(int i) method returns a String object representing the specified integer. Here, i is the integer to be converted."
},
{
"code": null,
"e": 1815,
"s": 1787,
"text": "Let us now see an example −"
},
{
"code": null,
"e": 1826,
"s": 1815,
"text": " Live Demo"
},
{
"code": null,
"e": 2114,
"s": 1826,
"text": "import java.lang.*;\npublic class Demo {\n public static void main(String[] args) {\n Integer i = new Integer(10);\n // returns a string representation of the specified integer in base 10\n String retval = i.toString(30);\n System.out.println(\"Value = \" + retval);\n }\n}"
},
{
"code": null,
"e": 2125,
"s": 2114,
"text": "Value = 30"
},
{
"code": null,
"e": 2409,
"s": 2125,
"text": "The java.lang.Integer.toString(int i, int radix) method returns a string representation of the first argument i in the radix specified by the second argument radix.If the radix is smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX, then the radix 10 is used instead."
},
{
"code": null,
"e": 2517,
"s": 2409,
"text": "Here, i is the integer to be converted, whereas radix is the radix to be used in the string representation."
},
{
"code": null,
"e": 2545,
"s": 2517,
"text": "Let us now see an example −"
},
{
"code": null,
"e": 2556,
"s": 2545,
"text": " Live Demo"
},
{
"code": null,
"e": 3173,
"s": 2556,
"text": "import java.lang.*;\npublic class Demo {\n public static void main(String[] args) {\n Integer i = new Integer(10);\n // returns a string representation of the specified integer with radix 10\n String retval = i.toString(30, 10);\n System.out.println(\"Value = \" + retval);\n // returns a string representation of the specified integer with radix 16\n retval = i.toString(30, 16);\n System.out.println(\"Value = \" + retval);\n // returns a string representation of the specified integer with radix 8\n retval = i.toString(30, 8);\n System.out.println(\"Value = \" + retval);\n }\n}"
},
{
"code": null,
"e": 3206,
"s": 3173,
"text": "Value = 30\nValue = 1e\nValue = 36"
}
] |
How to delete the specific node from the XML file using PowerShell?
|
To delete the specific XML node from the PowerShell, we can use the RemoveChild() method of the XML.
For example, We have a sample XML file from Microsoft.
https://docs.microsoft.com/en-us/previous-versions/windows/desktop/ms762271(v=vs.85)
We have saved the above file into C:\Temp\SampleXml.XML and we need to delete the book node with attribute ‘bk102’ and for that, we will use the XPath method of the XML.
Below commands will first search the XML book node with the book attribute ‘bk102’ and then we will delete it.
$xml = [xml](Get-Content C:\Temp\SampleXML.xml)
$node = $xml.SelectSingleNode("//book[@id='bk102']")
$node.ParentNode.RemoveChild($node) | Out-Null
$xml.Save('C:\Temp\SampleXML.xml')
If you want to delete all the nodes which have the name “Book”, we can use the below commands.
$xml = [xml](Get-Content C:\Temp\SampleXML.xml)
$xml.SelectNodes("//book")
$nodes = $xml.SelectNodes("//book")
foreach($node in $nodes){$node.ParentNode.RemoveChild($node)}
In the above example, SelectNodes(‘//book’) method will select all nodes having the name Book and then deletes them.
|
[
{
"code": null,
"e": 1163,
"s": 1062,
"text": "To delete the specific XML node from the PowerShell, we can use the RemoveChild() method of the XML."
},
{
"code": null,
"e": 1218,
"s": 1163,
"text": "For example, We have a sample XML file from Microsoft."
},
{
"code": null,
"e": 1303,
"s": 1218,
"text": "https://docs.microsoft.com/en-us/previous-versions/windows/desktop/ms762271(v=vs.85)"
},
{
"code": null,
"e": 1473,
"s": 1303,
"text": "We have saved the above file into C:\\Temp\\SampleXml.XML and we need to delete the book node with attribute ‘bk102’ and for that, we will use the XPath method of the XML."
},
{
"code": null,
"e": 1584,
"s": 1473,
"text": "Below commands will first search the XML book node with the book attribute ‘bk102’ and then we will delete it."
},
{
"code": null,
"e": 1767,
"s": 1584,
"text": "$xml = [xml](Get-Content C:\\Temp\\SampleXML.xml)\n$node = $xml.SelectSingleNode(\"//book[@id='bk102']\")\n$node.ParentNode.RemoveChild($node) | Out-Null\n$xml.Save('C:\\Temp\\SampleXML.xml')"
},
{
"code": null,
"e": 1862,
"s": 1767,
"text": "If you want to delete all the nodes which have the name “Book”, we can use the below commands."
},
{
"code": null,
"e": 2035,
"s": 1862,
"text": "$xml = [xml](Get-Content C:\\Temp\\SampleXML.xml)\n$xml.SelectNodes(\"//book\")\n$nodes = $xml.SelectNodes(\"//book\")\nforeach($node in $nodes){$node.ParentNode.RemoveChild($node)}"
},
{
"code": null,
"e": 2152,
"s": 2035,
"text": "In the above example, SelectNodes(‘//book’) method will select all nodes having the name Book and then deletes them."
}
] |
Lodash _.mapValues() Method - GeeksforGeeks
|
22 Mar, 2021
Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc.
The _.mapValues() method is used to create a new mapped object with the same keys of the given object and the values are generated using the given iteratee function.
Syntax:
_.mapValues( object, iteratee )
Parameters: This method accepts two parameters as mentioned above and described below:
object: This parameter holds the object to iterate over.
iteratee: This parameter holds the function that is invoked per iteration on the object. It is an optional value.
Return Value: This method returns the new mapped object.
Example 1:
Javascript
// Requiring the lodash library const _ = require("lodash"); var users = {'Geeksforgeeks': { 'username': 'gfg_id', 'password': 'gfg@123' }, 'W3school': { 'username': 'w3school_id', 'password': 'w@123' }}; // Using the _.mapValues() methodconsole.log( _.mapValues(users, function(o) { return o.password; }));
Output:
{Geeksforgeeks: "gfg@123", W3school: "w@123"}
Example 2:
Javascript
// Requiring the lodash library const _ = require("lodash"); var users = { 'Geeksforgeeks': { 'username': 'gfg_id', 'password': 'gfg@123' }, 'W3school': { 'username': 'w3school_id', 'password': 'w@123' }}; // Using the _.mapValues() methodconsole.log(_.mapValues(users, 'password'));
Output:
{Geeksforgeeks: "gfg@123", W3school: "w@123"}
arorakashish0911
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to Open URL in New Tab using JavaScript ?
Set the value of an input field in JavaScript
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 24678,
"s": 24650,
"text": "\n22 Mar, 2021"
},
{
"code": null,
"e": 24818,
"s": 24678,
"text": "Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc."
},
{
"code": null,
"e": 24984,
"s": 24818,
"text": "The _.mapValues() method is used to create a new mapped object with the same keys of the given object and the values are generated using the given iteratee function."
},
{
"code": null,
"e": 24992,
"s": 24984,
"text": "Syntax:"
},
{
"code": null,
"e": 25024,
"s": 24992,
"text": "_.mapValues( object, iteratee )"
},
{
"code": null,
"e": 25111,
"s": 25024,
"text": "Parameters: This method accepts two parameters as mentioned above and described below:"
},
{
"code": null,
"e": 25168,
"s": 25111,
"text": "object: This parameter holds the object to iterate over."
},
{
"code": null,
"e": 25282,
"s": 25168,
"text": "iteratee: This parameter holds the function that is invoked per iteration on the object. It is an optional value."
},
{
"code": null,
"e": 25339,
"s": 25282,
"text": "Return Value: This method returns the new mapped object."
},
{
"code": null,
"e": 25350,
"s": 25339,
"text": "Example 1:"
},
{
"code": null,
"e": 25361,
"s": 25350,
"text": "Javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); var users = {'Geeksforgeeks': { 'username': 'gfg_id', 'password': 'gfg@123' }, 'W3school': { 'username': 'w3school_id', 'password': 'w@123' }}; // Using the _.mapValues() methodconsole.log( _.mapValues(users, function(o) { return o.password; }));",
"e": 25690,
"s": 25361,
"text": null
},
{
"code": null,
"e": 25702,
"s": 25694,
"text": "Output:"
},
{
"code": null,
"e": 25750,
"s": 25704,
"text": "{Geeksforgeeks: \"gfg@123\", W3school: \"w@123\"}"
},
{
"code": null,
"e": 25765,
"s": 25752,
"text": "Example 2: "
},
{
"code": null,
"e": 25778,
"s": 25767,
"text": "Javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); var users = { 'Geeksforgeeks': { 'username': 'gfg_id', 'password': 'gfg@123' }, 'W3school': { 'username': 'w3school_id', 'password': 'w@123' }}; // Using the _.mapValues() methodconsole.log(_.mapValues(users, 'password'));",
"e": 26079,
"s": 25778,
"text": null
},
{
"code": null,
"e": 26087,
"s": 26079,
"text": "Output:"
},
{
"code": null,
"e": 26133,
"s": 26087,
"text": "{Geeksforgeeks: \"gfg@123\", W3school: \"w@123\"}"
},
{
"code": null,
"e": 26150,
"s": 26133,
"text": "arorakashish0911"
},
{
"code": null,
"e": 26168,
"s": 26150,
"text": "JavaScript-Lodash"
},
{
"code": null,
"e": 26179,
"s": 26168,
"text": "JavaScript"
},
{
"code": null,
"e": 26196,
"s": 26179,
"text": "Web Technologies"
},
{
"code": null,
"e": 26294,
"s": 26196,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26303,
"s": 26294,
"text": "Comments"
},
{
"code": null,
"e": 26316,
"s": 26303,
"text": "Old Comments"
},
{
"code": null,
"e": 26361,
"s": 26316,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 26422,
"s": 26361,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 26494,
"s": 26422,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 26540,
"s": 26494,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 26586,
"s": 26540,
"text": "Set the value of an input field in JavaScript"
},
{
"code": null,
"e": 26628,
"s": 26586,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 26661,
"s": 26628,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26723,
"s": 26661,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 26766,
"s": 26723,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
PHP | DOMNode removeChild() Function - GeeksforGeeks
|
02 Mar, 2020
The DOMNode::removeChild() function is an inbuilt function in PHP which is used remove child from list of children.
Syntax:
DOMNode DOMNode::removeChild( DOMNode $oldnode )
Parameters: This function accepts a single parameter $oldnode which holds the child to remove.
Return Value: This function returns the removed child on success.
Exceptions: This function throws DOM_NO_MODIFICATION_ALLOWED_ERR, if the node is readonly and DOM_NOT_FOUND, if $oldnode is not a child of this node.
Below examples illustrate the DOMNode::removeChild() function in PHP:
Example 1:
<?php // Create a new DOMDocument instance$document = new DOMDocument(); // Create a div element$element = $document-> appendChild(new DOMElement('div')); // Create a text Node$text1 = $document-> createTextNode('GeeksforGeeks'); // Append the nodes$element->appendChild($text1); // Remove the child$element->removeChild($text1); // Render the XMLecho $document->saveXML();?>
Output: Press Ctrl+U to see the XML
Example 2:
<?php // Create a new DOMDocument instance$document = new DOMDocument(); // Create a h1 element$element = $document-> appendChild(new DOMElement('h1')); // Create the text Node$text1 = $document-> createTextNode('GeeksforGeeks');$text2 = $document-> createTextNode('Text to be removed'); // Append the nodes$element->appendChild($text1);$element->appendChild($text2); // Remove the child$element->removeChild($text2); // Render the outputecho $document->saveXML();?>
Output:
Reference: https://www.php.net/manual/en/domnode.removechild.php
PHP-DOM
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to 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?
How to receive JSON POST with PHP ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 24495,
"s": 24467,
"text": "\n02 Mar, 2020"
},
{
"code": null,
"e": 24611,
"s": 24495,
"text": "The DOMNode::removeChild() function is an inbuilt function in PHP which is used remove child from list of children."
},
{
"code": null,
"e": 24619,
"s": 24611,
"text": "Syntax:"
},
{
"code": null,
"e": 24668,
"s": 24619,
"text": "DOMNode DOMNode::removeChild( DOMNode $oldnode )"
},
{
"code": null,
"e": 24763,
"s": 24668,
"text": "Parameters: This function accepts a single parameter $oldnode which holds the child to remove."
},
{
"code": null,
"e": 24829,
"s": 24763,
"text": "Return Value: This function returns the removed child on success."
},
{
"code": null,
"e": 24979,
"s": 24829,
"text": "Exceptions: This function throws DOM_NO_MODIFICATION_ALLOWED_ERR, if the node is readonly and DOM_NOT_FOUND, if $oldnode is not a child of this node."
},
{
"code": null,
"e": 25049,
"s": 24979,
"text": "Below examples illustrate the DOMNode::removeChild() function in PHP:"
},
{
"code": null,
"e": 25060,
"s": 25049,
"text": "Example 1:"
},
{
"code": "<?php // Create a new DOMDocument instance$document = new DOMDocument(); // Create a div element$element = $document-> appendChild(new DOMElement('div')); // Create a text Node$text1 = $document-> createTextNode('GeeksforGeeks'); // Append the nodes$element->appendChild($text1); // Remove the child$element->removeChild($text1); // Render the XMLecho $document->saveXML();?>",
"e": 25459,
"s": 25060,
"text": null
},
{
"code": null,
"e": 25495,
"s": 25459,
"text": "Output: Press Ctrl+U to see the XML"
},
{
"code": null,
"e": 25506,
"s": 25495,
"text": "Example 2:"
},
{
"code": "<?php // Create a new DOMDocument instance$document = new DOMDocument(); // Create a h1 element$element = $document-> appendChild(new DOMElement('h1')); // Create the text Node$text1 = $document-> createTextNode('GeeksforGeeks');$text2 = $document-> createTextNode('Text to be removed'); // Append the nodes$element->appendChild($text1);$element->appendChild($text2); // Remove the child$element->removeChild($text2); // Render the outputecho $document->saveXML();?>",
"e": 26014,
"s": 25506,
"text": null
},
{
"code": null,
"e": 26022,
"s": 26014,
"text": "Output:"
},
{
"code": null,
"e": 26087,
"s": 26022,
"text": "Reference: https://www.php.net/manual/en/domnode.removechild.php"
},
{
"code": null,
"e": 26095,
"s": 26087,
"text": "PHP-DOM"
},
{
"code": null,
"e": 26108,
"s": 26095,
"text": "PHP-function"
},
{
"code": null,
"e": 26112,
"s": 26108,
"text": "PHP"
},
{
"code": null,
"e": 26129,
"s": 26112,
"text": "Web Technologies"
},
{
"code": null,
"e": 26133,
"s": 26129,
"text": "PHP"
},
{
"code": null,
"e": 26231,
"s": 26133,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26240,
"s": 26231,
"text": "Comments"
},
{
"code": null,
"e": 26253,
"s": 26240,
"text": "Old Comments"
},
{
"code": null,
"e": 26303,
"s": 26253,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 26343,
"s": 26303,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 26404,
"s": 26343,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 26454,
"s": 26404,
"text": "How to check whether an array is empty using PHP?"
},
{
"code": null,
"e": 26490,
"s": 26454,
"text": "How to receive JSON POST with PHP ?"
},
{
"code": null,
"e": 26546,
"s": 26490,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 26579,
"s": 26546,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26641,
"s": 26579,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 26684,
"s": 26641,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Sending data from a Flask app to PostgreSQL database | by Brendan Ferris | Towards Data Science
|
Managing the flow of data through a website or app is a crucial skill to master if you plan on making any sort of modern web service. With flask, Object Relational Mappers (ORM’s) are employed to allow your app to interact with a relational database. An Object Relational Mapper is a framework that, in our case, will allow us to interact with a SQL database using python instead of explicit SQL queries. The name of the ORM we are using is SQLAlchemy and can be downloaded as follows:
pip install flask_sqlalchemypip install psycopg2-binary #for using postgres
This article assumes that you have some basic knowledge of SQL, and have Flask, PostgreSQL, and pgAdmin installed on your machine.
Directory structure.
In order for our app to function properly, the directory needs to be laid out as follows. Make sure not to change the name or spelling of any files/folders you see below.
# from the terminal in the project folder$ mkdir templates static$ touch app.py$ cd templates$ touch index.html$ tree (optional: only works if tree is installed on OSX)├── app.py├── static└── templates └── index.html2 directories, 2 files
In the next sections, we are going to make a basic form that will send a persons name, and their favorite color to a local PostgreSQL database.
We will create a database in pgAdmin:
Now, we need to set up app.py to connect our database to our application. We start by creating our app and configuring the database URI, and secret_key.
The SQLALCHEMY_DATABASE_URI is a string describing our database connection. For the puposes of this article that connection is local, and can be described as follows:
engine:[//[user[:password]@][host]/[dbname]]engine -> postgresqluser -> postgres (see `owner` field in previous screenshot)password -> password (my db password is the string, `password`)host -> localhost (because we are running locally on out machine)dbname -> flasksql (this is the name I gave to the db in the previous step)
After configuring our connection to our local database, we need to create our people table. This will consist of a primary key of integer type, a name column that must be unique, and a color column. Both the color and name columns must be entered by the user.
Now where the landing page would normally be, we will add a button that takes us to the input form. When we hit submit on the form, we add the name of the person and their favorite color to the People class/table, then using db.session we add that entry to the database, and commit the change.
We need to use db.create() to create the database before the app is run:
To get the information from the user and into the database, we use an HTML form, with inputs that have name attributes corresponding to the column names in the database. We grab this information from the form in the personadd() function with request.form["pname"] and request.form["color"] .
Now that we have the names and colors in the database, we can go to pgAdmin and query the database directly. Every time we add a new entry using the form, we can go to pgAdmin and refresh the database to reflect the results.
Every time you add a new entry, press F5 and the query will update with the new data!
This article is not meant to illustrate best practices or a production ready solution, it is intended for those who have no idea where to start. We went over some of the basic concepts such as ORM’s and database URI’s, this foundational knowledge should serve you well as you learn more about databases, application infrastructure.
Happy Coding!
The GitHub repo can be found here.
💻 Feel free to check out my website.
|
[
{
"code": null,
"e": 657,
"s": 171,
"text": "Managing the flow of data through a website or app is a crucial skill to master if you plan on making any sort of modern web service. With flask, Object Relational Mappers (ORM’s) are employed to allow your app to interact with a relational database. An Object Relational Mapper is a framework that, in our case, will allow us to interact with a SQL database using python instead of explicit SQL queries. The name of the ORM we are using is SQLAlchemy and can be downloaded as follows:"
},
{
"code": null,
"e": 733,
"s": 657,
"text": "pip install flask_sqlalchemypip install psycopg2-binary #for using postgres"
},
{
"code": null,
"e": 864,
"s": 733,
"text": "This article assumes that you have some basic knowledge of SQL, and have Flask, PostgreSQL, and pgAdmin installed on your machine."
},
{
"code": null,
"e": 885,
"s": 864,
"text": "Directory structure."
},
{
"code": null,
"e": 1056,
"s": 885,
"text": "In order for our app to function properly, the directory needs to be laid out as follows. Make sure not to change the name or spelling of any files/folders you see below."
},
{
"code": null,
"e": 1298,
"s": 1056,
"text": "# from the terminal in the project folder$ mkdir templates static$ touch app.py$ cd templates$ touch index.html$ tree (optional: only works if tree is installed on OSX)├── app.py├── static└── templates └── index.html2 directories, 2 files"
},
{
"code": null,
"e": 1442,
"s": 1298,
"text": "In the next sections, we are going to make a basic form that will send a persons name, and their favorite color to a local PostgreSQL database."
},
{
"code": null,
"e": 1480,
"s": 1442,
"text": "We will create a database in pgAdmin:"
},
{
"code": null,
"e": 1633,
"s": 1480,
"text": "Now, we need to set up app.py to connect our database to our application. We start by creating our app and configuring the database URI, and secret_key."
},
{
"code": null,
"e": 1800,
"s": 1633,
"text": "The SQLALCHEMY_DATABASE_URI is a string describing our database connection. For the puposes of this article that connection is local, and can be described as follows:"
},
{
"code": null,
"e": 2127,
"s": 1800,
"text": "engine:[//[user[:password]@][host]/[dbname]]engine -> postgresqluser -> postgres (see `owner` field in previous screenshot)password -> password (my db password is the string, `password`)host -> localhost (because we are running locally on out machine)dbname -> flasksql (this is the name I gave to the db in the previous step)"
},
{
"code": null,
"e": 2387,
"s": 2127,
"text": "After configuring our connection to our local database, we need to create our people table. This will consist of a primary key of integer type, a name column that must be unique, and a color column. Both the color and name columns must be entered by the user."
},
{
"code": null,
"e": 2681,
"s": 2387,
"text": "Now where the landing page would normally be, we will add a button that takes us to the input form. When we hit submit on the form, we add the name of the person and their favorite color to the People class/table, then using db.session we add that entry to the database, and commit the change."
},
{
"code": null,
"e": 2754,
"s": 2681,
"text": "We need to use db.create() to create the database before the app is run:"
},
{
"code": null,
"e": 3046,
"s": 2754,
"text": "To get the information from the user and into the database, we use an HTML form, with inputs that have name attributes corresponding to the column names in the database. We grab this information from the form in the personadd() function with request.form[\"pname\"] and request.form[\"color\"] ."
},
{
"code": null,
"e": 3271,
"s": 3046,
"text": "Now that we have the names and colors in the database, we can go to pgAdmin and query the database directly. Every time we add a new entry using the form, we can go to pgAdmin and refresh the database to reflect the results."
},
{
"code": null,
"e": 3357,
"s": 3271,
"text": "Every time you add a new entry, press F5 and the query will update with the new data!"
},
{
"code": null,
"e": 3689,
"s": 3357,
"text": "This article is not meant to illustrate best practices or a production ready solution, it is intended for those who have no idea where to start. We went over some of the basic concepts such as ORM’s and database URI’s, this foundational knowledge should serve you well as you learn more about databases, application infrastructure."
},
{
"code": null,
"e": 3703,
"s": 3689,
"text": "Happy Coding!"
},
{
"code": null,
"e": 3738,
"s": 3703,
"text": "The GitHub repo can be found here."
}
] |
Java Examples - Use of label in a method
|
How to use method overloading for printing different types of array ?
This example shows how to jump to a particular label when break or continue statements occour in a loop.
public class NewClass {
public static void main(String[] args) {
String strSearch = "This is the string in which you have to search for a substring.";
String substring = "substring";
boolean found = false;
int max = strSearch.length() - substring.length();
testlbl: for (int i = 0; i <= max; i++) {
int length = substring.length();
int j = i;
int k = 0;
while (length-- != 0) {
if(strSearch.charAt(j++) != substring.charAt(k++)){
continue testlbl;
}
}
found = true;
break testlbl;
}
if (found) {
System.out.println("Found the substring .");
} else {
System.out.println("did not find the substing in the string.");
}
}
}
The above code sample will produce the following result.
Found the substring .
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2139,
"s": 2068,
"text": "How to use method overloading for printing different types of array ?"
},
{
"code": null,
"e": 2244,
"s": 2139,
"text": "This example shows how to jump to a particular label when break or continue statements occour in a loop."
},
{
"code": null,
"e": 3044,
"s": 2244,
"text": "public class NewClass {\n public static void main(String[] args) {\n String strSearch = \"This is the string in which you have to search for a substring.\";\n String substring = \"substring\";\n boolean found = false;\n int max = strSearch.length() - substring.length();\n testlbl: for (int i = 0; i <= max; i++) {\n int length = substring.length();\n int j = i;\n int k = 0;\n while (length-- != 0) {\n if(strSearch.charAt(j++) != substring.charAt(k++)){\n continue testlbl;\n }\n }\n found = true;\n break testlbl;\n }\n if (found) {\n System.out.println(\"Found the substring .\");\n } else {\n System.out.println(\"did not find the substing in the string.\");\n }\n }\n}"
},
{
"code": null,
"e": 3101,
"s": 3044,
"text": "The above code sample will produce the following result."
},
{
"code": null,
"e": 3124,
"s": 3101,
"text": "Found the substring .\n"
},
{
"code": null,
"e": 3131,
"s": 3124,
"text": " Print"
},
{
"code": null,
"e": 3142,
"s": 3131,
"text": " Add Notes"
}
] |
Kali Linux - Information Gathering Tools - GeeksforGeeks
|
07 Sep, 2021
Information Gathering means gathering different kinds of information about the target. It is basically, the first step or the beginning stage of Ethical Hacking, where the penetration testers or hackers (both black hat or white hat) tries to gather all the information about the target, in order to use it for Hacking. To obtain more relevant results, we have to gather more information about the target to increase the probability of a successful attack. 0
Information gathering is an art that every penetration-tester (pen-tester) and hacker should master for a better experience in penetration testing. It is a method used by analysts to determine the needs of customers and users. Techniques that provide safety, utility, usability, learnability, etc. for collaborators result in their collaboration, commitment, and honesty. Various tools and techniques are available, including public sources such as Whois, nslookup which can help hackers to gather user information. This step is very important because while performing attacks on any target information (such as his pet name, best friend’s name, age, or phone number to perform password guessing attacks(brute force) or other kinds of attacks) are required.
Information gathering can be classified into the following categories:
Footprinting
Scanning
Enumeration
Reconnaissance
Nmap is an open-source network scanner that is used to recon/scan networks. It is used to discover hosts, ports, and services along with their versions over a network. It sends packets to the host and then analyzes the responses in order to produce the desired results. It could even be used for host discovery, operating system detection, or scanning for open ports. It is one of the most popular reconnaissance tools.
To use nmap:
Ping the host with the ping command to get the IP address
ping hostname
Open the terminal and enter the following command there.
nmap -sV ipaddress
Replace the IP address with the IP address of the host you want to scan.
It will display all the captured details of the host.
Read more about nmap.
It is another useful tool for the scanning phase of Ethical Hacking in Kali Linux. It uses the Graphical User Interface. It is a great tool for network discovery and security auditing. It does the same functions as that of the Nmap tool or in other words, it is the graphical Interface version of the Nmap tool. It uses command line Interface. It is a free utility tool for network discovery and security auditing. Tasks such as network inventory, managing service upgrade schedules, and monitoring host or service uptime are considered really useful by systems and network administrators.
To use Zenmap, enter the target URL in the target field to scan the target.
whois is a database record of all the registered domains over the internet. It is used for many purposes, a few of them are listed below.
It is used by Network Administrators in order to identify and fix DNS or domain-related issues.
It is used to check the availability of domain names.
It is used to identify trademark infringement.
It could even be used to track down the registrants of the Fraud domain.
To use whois lookup, enter the following command in the terminal
whois geeksforgeeks.org
Replace geeksforgeeks.org with the name of the website you want to lookup.
SPARTA is a python based Graphical User Interface tool which is used in the scanning and enumeration phase of information gathering. It is a toolkit having a collection of some useful tools for information gathering. It is used for many purposes, a few of them are listed below.
It is used to export Nmap output to an XML file.
It is used to automate the process of Nikto tool to every HTTP service or any other service.
It is used to save the scan of the hosts you have scanned earlier in order to save time.
It is used to reuse the password which is already found and is not present in the wordlist.
To use SPARTA, enter the IP address of the host you want to scan in the host section to start scanning.
nslookup stands for nameserver lookup, which is a command used to get the information from the DNS server. It queries DNS to obtain a domain name, IP address mapping, or any other DNS record. It even helps in troubleshooting DNS-related problems. It is used for many purposes, a few of them are listed below.
To get the IP address of a domain.
For reverse DNS lookup
For lookup for any record
Lookup for an SOA record
Lookup for an ns record
Lookup for an MX record
Lookup for a txt record
Osintgram is an OSINT tool to run on reconnaissance Instagram to collect and analyze. It offers an interactive shell to perform analysis on account of any users by its nickname. One can get:
– addrs : It gets all registered addressed by target photos.
– captions : It gets the user’s photos captions.
– comments : It gets total comments of the target’s posts.
– followers : It gets target followers.
– followings : It gets users followed by the target.
– fwersemail : It gets emails of target followers.
– fwingsemail : It gets an email of users followed by the target.
– fwersnumber : It gets the phone number of target followers.
– fwingsnumber : It gets the phone number of users followed by the target.
– hashtags : It gets hashtags used by the target.
mtalhahussain
Kali-Linux
linux
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
ZIP command in Linux with examples
tar command in Linux with examples
SORT command in Linux/Unix with examples
UDP Server-Client implementation in C
curl command in Linux with Examples
'crontab' in Linux with Examples
Conditional Statements | Shell Script
diff command in Linux with examples
Cat command in Linux with examples
|
[
{
"code": null,
"e": 24624,
"s": 24596,
"text": "\n07 Sep, 2021"
},
{
"code": null,
"e": 25082,
"s": 24624,
"text": "Information Gathering means gathering different kinds of information about the target. It is basically, the first step or the beginning stage of Ethical Hacking, where the penetration testers or hackers (both black hat or white hat) tries to gather all the information about the target, in order to use it for Hacking. To obtain more relevant results, we have to gather more information about the target to increase the probability of a successful attack. 0"
},
{
"code": null,
"e": 25841,
"s": 25082,
"text": "Information gathering is an art that every penetration-tester (pen-tester) and hacker should master for a better experience in penetration testing. It is a method used by analysts to determine the needs of customers and users. Techniques that provide safety, utility, usability, learnability, etc. for collaborators result in their collaboration, commitment, and honesty. Various tools and techniques are available, including public sources such as Whois, nslookup which can help hackers to gather user information. This step is very important because while performing attacks on any target information (such as his pet name, best friend’s name, age, or phone number to perform password guessing attacks(brute force) or other kinds of attacks) are required. "
},
{
"code": null,
"e": 25913,
"s": 25841,
"text": "Information gathering can be classified into the following categories: "
},
{
"code": null,
"e": 25926,
"s": 25913,
"text": "Footprinting"
},
{
"code": null,
"e": 25935,
"s": 25926,
"text": "Scanning"
},
{
"code": null,
"e": 25947,
"s": 25935,
"text": "Enumeration"
},
{
"code": null,
"e": 25962,
"s": 25947,
"text": "Reconnaissance"
},
{
"code": null,
"e": 26383,
"s": 25962,
"text": "Nmap is an open-source network scanner that is used to recon/scan networks. It is used to discover hosts, ports, and services along with their versions over a network. It sends packets to the host and then analyzes the responses in order to produce the desired results. It could even be used for host discovery, operating system detection, or scanning for open ports. It is one of the most popular reconnaissance tools. "
},
{
"code": null,
"e": 26397,
"s": 26383,
"text": "To use nmap: "
},
{
"code": null,
"e": 26455,
"s": 26397,
"text": "Ping the host with the ping command to get the IP address"
},
{
"code": null,
"e": 26469,
"s": 26455,
"text": "ping hostname"
},
{
"code": null,
"e": 26526,
"s": 26469,
"text": "Open the terminal and enter the following command there."
},
{
"code": null,
"e": 26545,
"s": 26526,
"text": "nmap -sV ipaddress"
},
{
"code": null,
"e": 26618,
"s": 26545,
"text": "Replace the IP address with the IP address of the host you want to scan."
},
{
"code": null,
"e": 26672,
"s": 26618,
"text": "It will display all the captured details of the host."
},
{
"code": null,
"e": 26695,
"s": 26672,
"text": "Read more about nmap. "
},
{
"code": null,
"e": 27286,
"s": 26695,
"text": "It is another useful tool for the scanning phase of Ethical Hacking in Kali Linux. It uses the Graphical User Interface. It is a great tool for network discovery and security auditing. It does the same functions as that of the Nmap tool or in other words, it is the graphical Interface version of the Nmap tool. It uses command line Interface. It is a free utility tool for network discovery and security auditing. Tasks such as network inventory, managing service upgrade schedules, and monitoring host or service uptime are considered really useful by systems and network administrators. "
},
{
"code": null,
"e": 27363,
"s": 27286,
"text": "To use Zenmap, enter the target URL in the target field to scan the target. "
},
{
"code": null,
"e": 27502,
"s": 27363,
"text": "whois is a database record of all the registered domains over the internet. It is used for many purposes, a few of them are listed below. "
},
{
"code": null,
"e": 27598,
"s": 27502,
"text": "It is used by Network Administrators in order to identify and fix DNS or domain-related issues."
},
{
"code": null,
"e": 27652,
"s": 27598,
"text": "It is used to check the availability of domain names."
},
{
"code": null,
"e": 27699,
"s": 27652,
"text": "It is used to identify trademark infringement."
},
{
"code": null,
"e": 27772,
"s": 27699,
"text": "It could even be used to track down the registrants of the Fraud domain."
},
{
"code": null,
"e": 27838,
"s": 27772,
"text": "To use whois lookup, enter the following command in the terminal "
},
{
"code": null,
"e": 27862,
"s": 27838,
"text": "whois geeksforgeeks.org"
},
{
"code": null,
"e": 27938,
"s": 27862,
"text": "Replace geeksforgeeks.org with the name of the website you want to lookup. "
},
{
"code": null,
"e": 28218,
"s": 27938,
"text": "SPARTA is a python based Graphical User Interface tool which is used in the scanning and enumeration phase of information gathering. It is a toolkit having a collection of some useful tools for information gathering. It is used for many purposes, a few of them are listed below. "
},
{
"code": null,
"e": 28267,
"s": 28218,
"text": "It is used to export Nmap output to an XML file."
},
{
"code": null,
"e": 28360,
"s": 28267,
"text": "It is used to automate the process of Nikto tool to every HTTP service or any other service."
},
{
"code": null,
"e": 28449,
"s": 28360,
"text": "It is used to save the scan of the hosts you have scanned earlier in order to save time."
},
{
"code": null,
"e": 28541,
"s": 28449,
"text": "It is used to reuse the password which is already found and is not present in the wordlist."
},
{
"code": null,
"e": 28646,
"s": 28541,
"text": "To use SPARTA, enter the IP address of the host you want to scan in the host section to start scanning. "
},
{
"code": null,
"e": 28956,
"s": 28646,
"text": "nslookup stands for nameserver lookup, which is a command used to get the information from the DNS server. It queries DNS to obtain a domain name, IP address mapping, or any other DNS record. It even helps in troubleshooting DNS-related problems. It is used for many purposes, a few of them are listed below. "
},
{
"code": null,
"e": 28991,
"s": 28956,
"text": "To get the IP address of a domain."
},
{
"code": null,
"e": 29014,
"s": 28991,
"text": "For reverse DNS lookup"
},
{
"code": null,
"e": 29040,
"s": 29014,
"text": "For lookup for any record"
},
{
"code": null,
"e": 29065,
"s": 29040,
"text": "Lookup for an SOA record"
},
{
"code": null,
"e": 29089,
"s": 29065,
"text": "Lookup for an ns record"
},
{
"code": null,
"e": 29113,
"s": 29089,
"text": "Lookup for an MX record"
},
{
"code": null,
"e": 29137,
"s": 29113,
"text": "Lookup for a txt record"
},
{
"code": null,
"e": 29328,
"s": 29137,
"text": "Osintgram is an OSINT tool to run on reconnaissance Instagram to collect and analyze. It offers an interactive shell to perform analysis on account of any users by its nickname. One can get:"
},
{
"code": null,
"e": 29389,
"s": 29328,
"text": "– addrs : It gets all registered addressed by target photos."
},
{
"code": null,
"e": 29438,
"s": 29389,
"text": "– captions : It gets the user’s photos captions."
},
{
"code": null,
"e": 29497,
"s": 29438,
"text": "– comments : It gets total comments of the target’s posts."
},
{
"code": null,
"e": 29537,
"s": 29497,
"text": "– followers : It gets target followers."
},
{
"code": null,
"e": 29590,
"s": 29537,
"text": "– followings : It gets users followed by the target."
},
{
"code": null,
"e": 29641,
"s": 29590,
"text": "– fwersemail : It gets emails of target followers."
},
{
"code": null,
"e": 29707,
"s": 29641,
"text": "– fwingsemail : It gets an email of users followed by the target."
},
{
"code": null,
"e": 29769,
"s": 29707,
"text": "– fwersnumber : It gets the phone number of target followers."
},
{
"code": null,
"e": 29844,
"s": 29769,
"text": "– fwingsnumber : It gets the phone number of users followed by the target."
},
{
"code": null,
"e": 29894,
"s": 29844,
"text": "– hashtags : It gets hashtags used by the target."
},
{
"code": null,
"e": 29908,
"s": 29894,
"text": "mtalhahussain"
},
{
"code": null,
"e": 29919,
"s": 29908,
"text": "Kali-Linux"
},
{
"code": null,
"e": 29925,
"s": 29919,
"text": "linux"
},
{
"code": null,
"e": 29936,
"s": 29925,
"text": "Linux-Unix"
},
{
"code": null,
"e": 30034,
"s": 29936,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30043,
"s": 30034,
"text": "Comments"
},
{
"code": null,
"e": 30056,
"s": 30043,
"text": "Old Comments"
},
{
"code": null,
"e": 30094,
"s": 30056,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 30129,
"s": 30094,
"text": "ZIP command in Linux with examples"
},
{
"code": null,
"e": 30164,
"s": 30129,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 30205,
"s": 30164,
"text": "SORT command in Linux/Unix with examples"
},
{
"code": null,
"e": 30243,
"s": 30205,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 30279,
"s": 30243,
"text": "curl command in Linux with Examples"
},
{
"code": null,
"e": 30312,
"s": 30279,
"text": "'crontab' in Linux with Examples"
},
{
"code": null,
"e": 30350,
"s": 30312,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 30386,
"s": 30350,
"text": "diff command in Linux with examples"
}
] |
Python Tkinter - Label - GeeksforGeeks
|
04 Sep, 2020
Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications. Creating a GUI using Tkinter is an easy task using widgets. Widgets are standard graphical user interfaces (GUI) elements, like buttons and menus.
Note: For more information, refer to Python GUI – tkinter
Tkinter Label is a widget that is used to implement display boxes where you can place text or images. The text displayed by this widget can be changed by the developer at any time you want. It is also used to perform tasks such as to underline the part of the text and span the text across multiple lines. It is important to note that a label can use only one font at a time to display text. To use a label, you just have to specify what to display in it (this can be text, a bitmap, or an image).
Syntax:
w = Label ( master, option, ... )
Parameters:
master: This represents the parent window
options: Below is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas:
Various Options are:
anchor: This options is used to control the positioning of the text if the widget has more space than required for the text. The default is anchor=CENTER, which centers the text in the available space.
bg:This option is used to set the normal background clior displayed behind the label and indicator.
height:This option is used to set the vertical dimension of the new frame.
width:Width of the label in characters (not pixels!). If this option is not set, the label will be sized to fit its contents.
bd:This option is used to set the size of the border around the indicator. Default bd value is set on 2 pixels.
font:If you are displaying text in the label (with the text or textvariable option), the font option is used to specify in what font that text in the label will be displayed.
cursor:It is used to specify what cursor to show when the mouse is moved over the label. The default is to use the standard cursor.
textvariable: As the name suggests it is associated with a Tkinter variable (usually a StringVar) with the label. If the variable is changed, the label text is updated.
bitmap:It is used to set the bitmap to the graphical object specified so that, the label can represent the graphics instead of text.
fg:The label clior, used for text and bitmap labels. The default is system specific. If you are displaying a bitmap, this is the clior that will appear at the position of the 1-bits in the bitmap.
image: This option is used to display a static image in the label widget.
padx:This option is used to add extra spaces between left and right of the text within the label.The default value for this option is 1.
pady:This option is used to add extra spaces between top and bottom of the text within the label.The default value for this option is 1.
justify:This option is used to define how to align multiple lines of text. Use LEFT, RIGHT, or CENTER as its values. Note that to position the text inside the widget, use the anchor option. Default value for justify is CENTER.
relief: This option is used to specify appearance of a decorative border around the label. The default value for this option is FLAT.
underline:This
wraplength:Instead of having only one line as the label text it can be broken itno to the number of lines where each line has the number of characters specified to this option.
Example:
from tkinter import * top = Tk() top.geometry("450x300") # the label for user_name user_name = Label(top, text = "Username").place(x = 40, y = 60) # the label for user_password user_password = Label(top, text = "Password").place(x = 40, y = 100) submit_button = Button(top, text = "Submit").place(x = 40, y = 130) user_name_input_area = Entry(top, width = 30).place(x = 110, y = 60) user_password_entry_area = Entry(top, width = 30).place(x = 110, y = 100) top.mainloop()
Output :
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
|
[
{
"code": null,
"e": 41554,
"s": 41526,
"text": "\n04 Sep, 2020"
},
{
"code": null,
"e": 42007,
"s": 41554,
"text": "Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications. Creating a GUI using Tkinter is an easy task using widgets. Widgets are standard graphical user interfaces (GUI) elements, like buttons and menus."
},
{
"code": null,
"e": 42065,
"s": 42007,
"text": "Note: For more information, refer to Python GUI – tkinter"
},
{
"code": null,
"e": 42563,
"s": 42065,
"text": "Tkinter Label is a widget that is used to implement display boxes where you can place text or images. The text displayed by this widget can be changed by the developer at any time you want. It is also used to perform tasks such as to underline the part of the text and span the text across multiple lines. It is important to note that a label can use only one font at a time to display text. To use a label, you just have to specify what to display in it (this can be text, a bitmap, or an image)."
},
{
"code": null,
"e": 42571,
"s": 42563,
"text": "Syntax:"
},
{
"code": null,
"e": 42605,
"s": 42571,
"text": "w = Label ( master, option, ... )"
},
{
"code": null,
"e": 42617,
"s": 42605,
"text": "Parameters:"
},
{
"code": null,
"e": 42659,
"s": 42617,
"text": "master: This represents the parent window"
},
{
"code": null,
"e": 42799,
"s": 42659,
"text": "options: Below is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas:"
},
{
"code": null,
"e": 42820,
"s": 42799,
"text": "Various Options are:"
},
{
"code": null,
"e": 43022,
"s": 42820,
"text": "anchor: This options is used to control the positioning of the text if the widget has more space than required for the text. The default is anchor=CENTER, which centers the text in the available space."
},
{
"code": null,
"e": 43122,
"s": 43022,
"text": "bg:This option is used to set the normal background clior displayed behind the label and indicator."
},
{
"code": null,
"e": 43197,
"s": 43122,
"text": "height:This option is used to set the vertical dimension of the new frame."
},
{
"code": null,
"e": 43323,
"s": 43197,
"text": "width:Width of the label in characters (not pixels!). If this option is not set, the label will be sized to fit its contents."
},
{
"code": null,
"e": 43435,
"s": 43323,
"text": "bd:This option is used to set the size of the border around the indicator. Default bd value is set on 2 pixels."
},
{
"code": null,
"e": 43610,
"s": 43435,
"text": "font:If you are displaying text in the label (with the text or textvariable option), the font option is used to specify in what font that text in the label will be displayed."
},
{
"code": null,
"e": 43742,
"s": 43610,
"text": "cursor:It is used to specify what cursor to show when the mouse is moved over the label. The default is to use the standard cursor."
},
{
"code": null,
"e": 43911,
"s": 43742,
"text": "textvariable: As the name suggests it is associated with a Tkinter variable (usually a StringVar) with the label. If the variable is changed, the label text is updated."
},
{
"code": null,
"e": 44044,
"s": 43911,
"text": "bitmap:It is used to set the bitmap to the graphical object specified so that, the label can represent the graphics instead of text."
},
{
"code": null,
"e": 44241,
"s": 44044,
"text": "fg:The label clior, used for text and bitmap labels. The default is system specific. If you are displaying a bitmap, this is the clior that will appear at the position of the 1-bits in the bitmap."
},
{
"code": null,
"e": 44315,
"s": 44241,
"text": "image: This option is used to display a static image in the label widget."
},
{
"code": null,
"e": 44452,
"s": 44315,
"text": "padx:This option is used to add extra spaces between left and right of the text within the label.The default value for this option is 1."
},
{
"code": null,
"e": 44589,
"s": 44452,
"text": "pady:This option is used to add extra spaces between top and bottom of the text within the label.The default value for this option is 1."
},
{
"code": null,
"e": 44816,
"s": 44589,
"text": "justify:This option is used to define how to align multiple lines of text. Use LEFT, RIGHT, or CENTER as its values. Note that to position the text inside the widget, use the anchor option. Default value for justify is CENTER."
},
{
"code": null,
"e": 44950,
"s": 44816,
"text": "relief: This option is used to specify appearance of a decorative border around the label. The default value for this option is FLAT."
},
{
"code": null,
"e": 44965,
"s": 44950,
"text": "underline:This"
},
{
"code": null,
"e": 45142,
"s": 44965,
"text": "wraplength:Instead of having only one line as the label text it can be broken itno to the number of lines where each line has the number of characters specified to this option."
},
{
"code": null,
"e": 45151,
"s": 45142,
"text": "Example:"
},
{
"code": "from tkinter import * top = Tk() top.geometry(\"450x300\") # the label for user_name user_name = Label(top, text = \"Username\").place(x = 40, y = 60) # the label for user_password user_password = Label(top, text = \"Password\").place(x = 40, y = 100) submit_button = Button(top, text = \"Submit\").place(x = 40, y = 130) user_name_input_area = Entry(top, width = 30).place(x = 110, y = 60) user_password_entry_area = Entry(top, width = 30).place(x = 110, y = 100) top.mainloop() ",
"e": 46013,
"s": 45151,
"text": null
},
{
"code": null,
"e": 46022,
"s": 46013,
"text": "Output :"
},
{
"code": null,
"e": 46037,
"s": 46022,
"text": "Python-tkinter"
},
{
"code": null,
"e": 46044,
"s": 46037,
"text": "Python"
},
{
"code": null,
"e": 46142,
"s": 46044,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 46170,
"s": 46142,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 46220,
"s": 46170,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 46242,
"s": 46220,
"text": "Python map() function"
},
{
"code": null,
"e": 46286,
"s": 46242,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 46321,
"s": 46286,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 46343,
"s": 46321,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 46375,
"s": 46343,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 46405,
"s": 46375,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 46447,
"s": 46405,
"text": "Different ways to create Pandas Dataframe"
}
] |
Deploying a TensorFlow Model to Production made Easy. | by Renu Khandelwal | Towards Data Science
|
Learn step by step deployment of a TensorFlow model to Production using TensorFlow Serving.
You created a deep learning model using Tensorflow, fine-tuned the model for better accuracy and precision, and now want to deploy your model to production for users to use it to make predictions.
What’s the best way to deploy your model to production?
Fast, flexible ways to deploy a TensorFlow deep learning model is to use high performing and highly scalable serving system-Tensorflow Serving
TensorFlow Serving allows you to
Easily manage multiple versions of your model, like an experimental or stable version.
Keep your server architecture and APIs the same
Dynamically discovers a new version of the TensorFlow flow model and serves it using gRPC(remote procedure protocol) using a consistent API structure.
Consistent experience for all clients making inferences by centralizing the location of the model
What are the components of TensorFlow Serving that makes deployment to production easy?
The key components of TF Serving are
Servables: A Servable is an underlying object used by clients to perform computation or inference. TensorFlow serving represents the deep learning models as one or more Servables.
Loaders: Manage the lifecycle of the Servables as Servables cannot manage their own lifecycle. Loaders standardize the APIs for loading and unloading the Servables, independent of the specific learning algorithm.
Source: Finds and provides Servables and then supplies one Loader instance for each version of the servable.
Managers: Manage the full lifecycle of the servable: Loading the servable, Serving the servable, and Unloading the servable.
TensorFlow Core: Manages lifecycle and metrics of the Servable by making the Loader and servable as opaque objects
Let’s say you have two different versions of a model, version 1 and version 2.
The clients make an API call by either specifying a version of the model explicitly or just requesting the model's latest version.
Managers listen to the Sources and keep track of all the versions of the Servable; it then applies the configured version policy to determine which version of the model should be loaded or unloaded and then let’s Loader load the appropriate version.
The loader contains all the meta-data to load the Servable.
The Source plug-in will create an instance of Loader for each version of the Servable.
The Source makes a callback to the Manager to notify the Aspired Version of the Loader to be loaded and serve it to the client.
Whenever the Source detects a new version of the Servable, it creates a Loader pointing to the Servable on the disk.
How to deploy a deep learning model using Tensorflow serving on Windows 10?
For Windows 10, we will use a TensorFlow serving image.
docker pull tensorflow/serving
Once you have the TensorFlow Serving image
Port 8500 is exposed for gRPC
Port 8501 is exposed for the REST API
Optional environment variable MODEL_NAME (defaults to model)
Optional environment variable MODEL_BASE_PATH (defaults to /models)
Here I have taken the MNIST dataset from TensorFlow datasets
#Importing required librariesimport osimport jsonimport tempfileimport requestsimport numpy as npimport tensorflow as tfimport tensorflow_datasets as tfds#Loading MNIST train and test dataset#as_supervised=True, will return tuple instead of a dictionary for image and label(ds_train, ds_test), ds_info = tfds.load("mnist", split=['train','test'], with_info=True, as_supervised=True)#to select the 'image' and 'label' using indexing coverting train and test dataset to a numpy arrayarray = np.vstack(tfds.as_numpy(ds_train))X_train = np.array(list(map(lambda x: x[0], array)))y_train = np.array(list(map(lambda x: x[1], array)))X_test = np.array(list(map(lambda x: x[0], array)))y_test = np.array(list(map(lambda x: x[1], array)))#setting batch_size and epochsepoch=10batch_size=128#Creating input data pipeline for train and test dataset# Function to normalize the imagesdef normalize_image(image, label): #Normalizes images from uint8` to float32 return tf.cast(image, tf.float32) / 255., label# Input data pipeline for test dataset#Normalize the image using map function then cache and shuffle the #train dataset # Create a batch of the training dataset and then prefecth for #overlapiing image preprocessing(producer) and model execution work #(consumer)ds_train = ds_train.map( normalize_img, num_parallel_calls=tf.data.experimental.AUTOTUNE)ds_train = ds_train.cache()ds_train = ds_train.shuffle(ds_info.splits['train'].num_examples)ds_train = ds_train.batch(batch_size)ds_train = ds_train.prefetch(tf.data.experimental.AUTOTUNE)# Input data pipeline for test dataset (No need to shuffle the test #dataset)ds_test = ds_test.map( normalize_image, num_parallel_calls=tf.data.experimental.AUTOTUNE)ds_test = ds_test.batch(batch_size)ds_test = ds_test.cache()ds_test = ds_test.prefetch(tf.data.experimental.AUTOTUNE)# Build the modelmodel = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28, 1)), tf.keras.layers.Dense(128,activation='relu'), tf.keras.layers.Dense(196, activation='softmax')])#Compile the modelmodel.compile( loss='sparse_categorical_crossentropy', optimizer=tf.keras.optimizers.Adam(0.001), metrics=['accuracy'],)#Fit the modelmodel.fit( ds_train, epochs=epoch, validation_data=ds_test, verbose=2)
Saving the model into a protocol buffer file by specifying the save_format as “tf”.
MODEL_DIR='tf_model'version = "1"export_path = os.path.join(MODEL_DIR, str(version))#Save the model model.save(export_path, save_format="tf")print('\nexport_path = {}'.format(export_path))!dir {export_path}
When we save a version of the model, we can see the following directories containing files:
Saved_model.pb: Contains the serialized graph definition of one or more model along with the metadata of the model as a MetaGraphDef protocol buffer. Weights and variables are stored in the separate checkpoint files.
Variables: files that hold the standard training checkpoint
You can examine the model using the saved_model_cli command.
!saved_model_cli show --dir {export_path} --all
Open Windows Powershell and execute the following command to start the TensorFlow Serving container for serving the TensorFlow model using the REST API port.
docker run -p 8501:8501 --mount type=bind,source=C:\TF_serving\tf_model,target=/models/mnist/ -e MODEL_NAME=mnist -t tensorflow/serving
To successfully serve the TensorFlow model with Docker.
Open the port 8501 to serve the model using -p
Mount will bind the model base path, which should be an absolute path to the container's location where the model will be saved.
The name of the model client will use to call by specifying the MODEL_NAME
assign a pseudo-terminal “tensorflow/serving” using -t option
We will create a JSON object to pass the data for prediction.
#Create JSON Objectdata = json.dumps({“signature_name”: “serving_default”, “instances”: X_test[:20].tolist()})
Request the model’s predict method as a POST to the server’s REST endpoint.
headers = {"content-type": "application/json"}json_response = requests.post('http://localhost:8501/v1/models/mnist:predict', data=data, headers=headers)predictions = json.loads(json_response.text)['predictions']
Checking the accuracy of the prediction
pred=[ np.argmax(predictions[p]) for p in range(len(predictions)) ]print("Predictions: ",pred)print("Actual: ",y_test[:20].tolist())
In the next article, we will explore the different model server configurations.
TensorFlow Serving is a fast, flexible, highly scalable, and easy-to-use way to serve your production model using consistent gRPC or REST APIs.
|
[
{
"code": null,
"e": 264,
"s": 172,
"text": "Learn step by step deployment of a TensorFlow model to Production using TensorFlow Serving."
},
{
"code": null,
"e": 461,
"s": 264,
"text": "You created a deep learning model using Tensorflow, fine-tuned the model for better accuracy and precision, and now want to deploy your model to production for users to use it to make predictions."
},
{
"code": null,
"e": 517,
"s": 461,
"text": "What’s the best way to deploy your model to production?"
},
{
"code": null,
"e": 660,
"s": 517,
"text": "Fast, flexible ways to deploy a TensorFlow deep learning model is to use high performing and highly scalable serving system-Tensorflow Serving"
},
{
"code": null,
"e": 693,
"s": 660,
"text": "TensorFlow Serving allows you to"
},
{
"code": null,
"e": 780,
"s": 693,
"text": "Easily manage multiple versions of your model, like an experimental or stable version."
},
{
"code": null,
"e": 828,
"s": 780,
"text": "Keep your server architecture and APIs the same"
},
{
"code": null,
"e": 979,
"s": 828,
"text": "Dynamically discovers a new version of the TensorFlow flow model and serves it using gRPC(remote procedure protocol) using a consistent API structure."
},
{
"code": null,
"e": 1077,
"s": 979,
"text": "Consistent experience for all clients making inferences by centralizing the location of the model"
},
{
"code": null,
"e": 1165,
"s": 1077,
"text": "What are the components of TensorFlow Serving that makes deployment to production easy?"
},
{
"code": null,
"e": 1202,
"s": 1165,
"text": "The key components of TF Serving are"
},
{
"code": null,
"e": 1382,
"s": 1202,
"text": "Servables: A Servable is an underlying object used by clients to perform computation or inference. TensorFlow serving represents the deep learning models as one or more Servables."
},
{
"code": null,
"e": 1595,
"s": 1382,
"text": "Loaders: Manage the lifecycle of the Servables as Servables cannot manage their own lifecycle. Loaders standardize the APIs for loading and unloading the Servables, independent of the specific learning algorithm."
},
{
"code": null,
"e": 1704,
"s": 1595,
"text": "Source: Finds and provides Servables and then supplies one Loader instance for each version of the servable."
},
{
"code": null,
"e": 1829,
"s": 1704,
"text": "Managers: Manage the full lifecycle of the servable: Loading the servable, Serving the servable, and Unloading the servable."
},
{
"code": null,
"e": 1944,
"s": 1829,
"text": "TensorFlow Core: Manages lifecycle and metrics of the Servable by making the Loader and servable as opaque objects"
},
{
"code": null,
"e": 2023,
"s": 1944,
"text": "Let’s say you have two different versions of a model, version 1 and version 2."
},
{
"code": null,
"e": 2154,
"s": 2023,
"text": "The clients make an API call by either specifying a version of the model explicitly or just requesting the model's latest version."
},
{
"code": null,
"e": 2404,
"s": 2154,
"text": "Managers listen to the Sources and keep track of all the versions of the Servable; it then applies the configured version policy to determine which version of the model should be loaded or unloaded and then let’s Loader load the appropriate version."
},
{
"code": null,
"e": 2464,
"s": 2404,
"text": "The loader contains all the meta-data to load the Servable."
},
{
"code": null,
"e": 2551,
"s": 2464,
"text": "The Source plug-in will create an instance of Loader for each version of the Servable."
},
{
"code": null,
"e": 2679,
"s": 2551,
"text": "The Source makes a callback to the Manager to notify the Aspired Version of the Loader to be loaded and serve it to the client."
},
{
"code": null,
"e": 2796,
"s": 2679,
"text": "Whenever the Source detects a new version of the Servable, it creates a Loader pointing to the Servable on the disk."
},
{
"code": null,
"e": 2872,
"s": 2796,
"text": "How to deploy a deep learning model using Tensorflow serving on Windows 10?"
},
{
"code": null,
"e": 2928,
"s": 2872,
"text": "For Windows 10, we will use a TensorFlow serving image."
},
{
"code": null,
"e": 2959,
"s": 2928,
"text": "docker pull tensorflow/serving"
},
{
"code": null,
"e": 3002,
"s": 2959,
"text": "Once you have the TensorFlow Serving image"
},
{
"code": null,
"e": 3032,
"s": 3002,
"text": "Port 8500 is exposed for gRPC"
},
{
"code": null,
"e": 3070,
"s": 3032,
"text": "Port 8501 is exposed for the REST API"
},
{
"code": null,
"e": 3131,
"s": 3070,
"text": "Optional environment variable MODEL_NAME (defaults to model)"
},
{
"code": null,
"e": 3199,
"s": 3131,
"text": "Optional environment variable MODEL_BASE_PATH (defaults to /models)"
},
{
"code": null,
"e": 3260,
"s": 3199,
"text": "Here I have taken the MNIST dataset from TensorFlow datasets"
},
{
"code": null,
"e": 5532,
"s": 3260,
"text": "#Importing required librariesimport osimport jsonimport tempfileimport requestsimport numpy as npimport tensorflow as tfimport tensorflow_datasets as tfds#Loading MNIST train and test dataset#as_supervised=True, will return tuple instead of a dictionary for image and label(ds_train, ds_test), ds_info = tfds.load(\"mnist\", split=['train','test'], with_info=True, as_supervised=True)#to select the 'image' and 'label' using indexing coverting train and test dataset to a numpy arrayarray = np.vstack(tfds.as_numpy(ds_train))X_train = np.array(list(map(lambda x: x[0], array)))y_train = np.array(list(map(lambda x: x[1], array)))X_test = np.array(list(map(lambda x: x[0], array)))y_test = np.array(list(map(lambda x: x[1], array)))#setting batch_size and epochsepoch=10batch_size=128#Creating input data pipeline for train and test dataset# Function to normalize the imagesdef normalize_image(image, label): #Normalizes images from uint8` to float32 return tf.cast(image, tf.float32) / 255., label# Input data pipeline for test dataset#Normalize the image using map function then cache and shuffle the #train dataset # Create a batch of the training dataset and then prefecth for #overlapiing image preprocessing(producer) and model execution work #(consumer)ds_train = ds_train.map( normalize_img, num_parallel_calls=tf.data.experimental.AUTOTUNE)ds_train = ds_train.cache()ds_train = ds_train.shuffle(ds_info.splits['train'].num_examples)ds_train = ds_train.batch(batch_size)ds_train = ds_train.prefetch(tf.data.experimental.AUTOTUNE)# Input data pipeline for test dataset (No need to shuffle the test #dataset)ds_test = ds_test.map( normalize_image, num_parallel_calls=tf.data.experimental.AUTOTUNE)ds_test = ds_test.batch(batch_size)ds_test = ds_test.cache()ds_test = ds_test.prefetch(tf.data.experimental.AUTOTUNE)# Build the modelmodel = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28, 1)), tf.keras.layers.Dense(128,activation='relu'), tf.keras.layers.Dense(196, activation='softmax')])#Compile the modelmodel.compile( loss='sparse_categorical_crossentropy', optimizer=tf.keras.optimizers.Adam(0.001), metrics=['accuracy'],)#Fit the modelmodel.fit( ds_train, epochs=epoch, validation_data=ds_test, verbose=2)"
},
{
"code": null,
"e": 5616,
"s": 5532,
"text": "Saving the model into a protocol buffer file by specifying the save_format as “tf”."
},
{
"code": null,
"e": 5823,
"s": 5616,
"text": "MODEL_DIR='tf_model'version = \"1\"export_path = os.path.join(MODEL_DIR, str(version))#Save the model model.save(export_path, save_format=\"tf\")print('\\nexport_path = {}'.format(export_path))!dir {export_path}"
},
{
"code": null,
"e": 5915,
"s": 5823,
"text": "When we save a version of the model, we can see the following directories containing files:"
},
{
"code": null,
"e": 6132,
"s": 5915,
"text": "Saved_model.pb: Contains the serialized graph definition of one or more model along with the metadata of the model as a MetaGraphDef protocol buffer. Weights and variables are stored in the separate checkpoint files."
},
{
"code": null,
"e": 6192,
"s": 6132,
"text": "Variables: files that hold the standard training checkpoint"
},
{
"code": null,
"e": 6253,
"s": 6192,
"text": "You can examine the model using the saved_model_cli command."
},
{
"code": null,
"e": 6301,
"s": 6253,
"text": "!saved_model_cli show --dir {export_path} --all"
},
{
"code": null,
"e": 6459,
"s": 6301,
"text": "Open Windows Powershell and execute the following command to start the TensorFlow Serving container for serving the TensorFlow model using the REST API port."
},
{
"code": null,
"e": 6596,
"s": 6459,
"text": "docker run -p 8501:8501 --mount type=bind,source=C:\\TF_serving\\tf_model,target=/models/mnist/ -e MODEL_NAME=mnist -t tensorflow/serving "
},
{
"code": null,
"e": 6652,
"s": 6596,
"text": "To successfully serve the TensorFlow model with Docker."
},
{
"code": null,
"e": 6699,
"s": 6652,
"text": "Open the port 8501 to serve the model using -p"
},
{
"code": null,
"e": 6828,
"s": 6699,
"text": "Mount will bind the model base path, which should be an absolute path to the container's location where the model will be saved."
},
{
"code": null,
"e": 6903,
"s": 6828,
"text": "The name of the model client will use to call by specifying the MODEL_NAME"
},
{
"code": null,
"e": 6965,
"s": 6903,
"text": "assign a pseudo-terminal “tensorflow/serving” using -t option"
},
{
"code": null,
"e": 7027,
"s": 6965,
"text": "We will create a JSON object to pass the data for prediction."
},
{
"code": null,
"e": 7138,
"s": 7027,
"text": "#Create JSON Objectdata = json.dumps({“signature_name”: “serving_default”, “instances”: X_test[:20].tolist()})"
},
{
"code": null,
"e": 7214,
"s": 7138,
"text": "Request the model’s predict method as a POST to the server’s REST endpoint."
},
{
"code": null,
"e": 7426,
"s": 7214,
"text": "headers = {\"content-type\": \"application/json\"}json_response = requests.post('http://localhost:8501/v1/models/mnist:predict', data=data, headers=headers)predictions = json.loads(json_response.text)['predictions']"
},
{
"code": null,
"e": 7466,
"s": 7426,
"text": "Checking the accuracy of the prediction"
},
{
"code": null,
"e": 7604,
"s": 7466,
"text": "pred=[ np.argmax(predictions[p]) for p in range(len(predictions)) ]print(\"Predictions: \",pred)print(\"Actual: \",y_test[:20].tolist())"
},
{
"code": null,
"e": 7684,
"s": 7604,
"text": "In the next article, we will explore the different model server configurations."
}
] |
JavaScript group a JSON object by two properties and count
|
Suppose, we have an array of objects like this −
const arr = [
{"location":"Kirrawee","identity_long":"student"},
{"location":"Kirrawee","identity_long":"visitor"},
{"location":"Kirrawee","identity_long":"visitor"},
{"location":"Kirrawee","identity_long":"worker"},
{"location":"Sutherland","identity_long":"student"},
{"location":"Sutherland","identity_long":"resident"},
{"location":"Sutherland","identity_long":"worker"},
{"location":"Sutherland","identity_long":"resident"},
{"location":"Miranda","identity_long":"resident"},
{"location":"Miranda","identity_long":"worker"},
{"location":"Miranda","identity_long":"student"},
{"location":"Miranda","identity_long":""},
{"location":"Miranda","identity_long":"worker"},
{"location":"Miranda","identity_long":"resident"}
];
We are required to write a JavaScript function that takes in one such array of objects. The function should prepare a new array of objects in which all (identical) the objects are grouped together based on the location property.
And the objects should be assigned a count property that contains the number of times it appeared in the original array of objects.
Therefore, for the above array, the output should look like −
const output = [
{"location":"Kirrawee","identity":"student","count":1},
{"location":"Kirrawee","identity":"visitor","count":2},
{"location":"Kirrawee","identity":"worker","count":1},
{"location":"Sutherland","identity":"student","count":1},
{"location":"Sutherland","identity":"resident","count":2},
{"location":"Sutherland","identity":"worker","count":1},
{"location":"Miranda","identity":"resident","count":2},
{"location":"Miranda","identity":"worker","count":2},
{"location":"Miranda","identity":"student","count":1}
];
The code for this will be −
const arr = [
{"location":"Kirrawee","identity_long":"student"},
{"location":"Kirrawee","identity_long":"visitor"},
{"location":"Kirrawee","identity_long":"visitor"},
{"location":"Kirrawee","identity_long":"worker"},
{"location":"Sutherland","identity_long":"student"},
{"location":"Sutherland","identity_long":"resident"},
{"location":"Sutherland","identity_long":"worker"},
{"location":"Sutherland","identity_long":"resident"},
{"location":"Miranda","identity_long":"resident"},
{"location":"Miranda","identity_long":"worker"},
{"location":"Miranda","identity_long":"student"},
{"location":"Miranda","identity_long":""},
{"location":"Miranda","identity_long":"worker"},
{"location":"Miranda","identity_long":"resident"}
];
const groupArray = (arr = []) => {
// create map
let map = new Map()
for (let i = 0; i < arr.length; i++) {
const s = JSON.stringify(arr[i]);
if (!map.has(s)) {
map.set(s, {
location: arr[i].location,
identity: arr[i].identity_long,
count: 1,
});
} else {
map.get(s).count++;
}
}
const res = Array.from(map.values())
return res;
};
console.log(groupArray(arr));
And the output in the console will be −
[
{ location: 'Kirrawee', identity: 'student', count: 1 },
{ location: 'Kirrawee', identity: 'visitor', count: 2 },
{ location: 'Kirrawee', identity: 'worker', count: 1 },
{ location: 'Sutherland', identity: 'student', count: 1 },
{ location: 'Sutherland', identity: 'resident', count: 2 },
{ location: 'Sutherland', identity: 'worker', count: 1 },
{ location: 'Miranda', identity: 'resident', count: 2 },
{ location: 'Miranda', identity: 'worker', count: 2 },
{ location: 'Miranda', identity: 'student', count: 1 },
{ location: 'Miranda', identity: '', count: 1 }
]
|
[
{
"code": null,
"e": 1111,
"s": 1062,
"text": "Suppose, we have an array of objects like this −"
},
{
"code": null,
"e": 1878,
"s": 1111,
"text": "const arr = [\n {\"location\":\"Kirrawee\",\"identity_long\":\"student\"},\n {\"location\":\"Kirrawee\",\"identity_long\":\"visitor\"},\n {\"location\":\"Kirrawee\",\"identity_long\":\"visitor\"},\n {\"location\":\"Kirrawee\",\"identity_long\":\"worker\"},\n {\"location\":\"Sutherland\",\"identity_long\":\"student\"},\n {\"location\":\"Sutherland\",\"identity_long\":\"resident\"},\n {\"location\":\"Sutherland\",\"identity_long\":\"worker\"},\n {\"location\":\"Sutherland\",\"identity_long\":\"resident\"},\n {\"location\":\"Miranda\",\"identity_long\":\"resident\"},\n {\"location\":\"Miranda\",\"identity_long\":\"worker\"},\n {\"location\":\"Miranda\",\"identity_long\":\"student\"},\n {\"location\":\"Miranda\",\"identity_long\":\"\"},\n {\"location\":\"Miranda\",\"identity_long\":\"worker\"},\n {\"location\":\"Miranda\",\"identity_long\":\"resident\"}\n];"
},
{
"code": null,
"e": 2107,
"s": 1878,
"text": "We are required to write a JavaScript function that takes in one such array of objects. The function should prepare a new array of objects in which all (identical) the objects are grouped together based on the location property."
},
{
"code": null,
"e": 2239,
"s": 2107,
"text": "And the objects should be assigned a count property that contains the number of times it appeared in the original array of objects."
},
{
"code": null,
"e": 2301,
"s": 2239,
"text": "Therefore, for the above array, the output should look like −"
},
{
"code": null,
"e": 2853,
"s": 2301,
"text": "const output = [\n {\"location\":\"Kirrawee\",\"identity\":\"student\",\"count\":1},\n {\"location\":\"Kirrawee\",\"identity\":\"visitor\",\"count\":2},\n {\"location\":\"Kirrawee\",\"identity\":\"worker\",\"count\":1},\n {\"location\":\"Sutherland\",\"identity\":\"student\",\"count\":1},\n {\"location\":\"Sutherland\",\"identity\":\"resident\",\"count\":2},\n {\"location\":\"Sutherland\",\"identity\":\"worker\",\"count\":1},\n {\"location\":\"Miranda\",\"identity\":\"resident\",\"count\":2},\n {\"location\":\"Miranda\",\"identity\":\"worker\",\"count\":2},\n {\"location\":\"Miranda\",\"identity\":\"student\",\"count\":1}\n];"
},
{
"code": null,
"e": 2881,
"s": 2853,
"text": "The code for this will be −"
},
{
"code": null,
"e": 4115,
"s": 2881,
"text": "const arr = [\n {\"location\":\"Kirrawee\",\"identity_long\":\"student\"},\n {\"location\":\"Kirrawee\",\"identity_long\":\"visitor\"},\n {\"location\":\"Kirrawee\",\"identity_long\":\"visitor\"},\n {\"location\":\"Kirrawee\",\"identity_long\":\"worker\"},\n {\"location\":\"Sutherland\",\"identity_long\":\"student\"},\n {\"location\":\"Sutherland\",\"identity_long\":\"resident\"},\n {\"location\":\"Sutherland\",\"identity_long\":\"worker\"},\n {\"location\":\"Sutherland\",\"identity_long\":\"resident\"},\n {\"location\":\"Miranda\",\"identity_long\":\"resident\"},\n {\"location\":\"Miranda\",\"identity_long\":\"worker\"},\n {\"location\":\"Miranda\",\"identity_long\":\"student\"},\n {\"location\":\"Miranda\",\"identity_long\":\"\"},\n {\"location\":\"Miranda\",\"identity_long\":\"worker\"},\n {\"location\":\"Miranda\",\"identity_long\":\"resident\"}\n];\nconst groupArray = (arr = []) => {\n // create map\n let map = new Map()\n for (let i = 0; i < arr.length; i++) {\n const s = JSON.stringify(arr[i]);\n if (!map.has(s)) {\n map.set(s, {\n location: arr[i].location,\n identity: arr[i].identity_long,\n count: 1,\n });\n } else {\n map.get(s).count++;\n }\n }\n const res = Array.from(map.values())\n return res;\n};\nconsole.log(groupArray(arr));"
},
{
"code": null,
"e": 4155,
"s": 4115,
"text": "And the output in the console will be −"
},
{
"code": null,
"e": 4752,
"s": 4155,
"text": "[\n { location: 'Kirrawee', identity: 'student', count: 1 },\n { location: 'Kirrawee', identity: 'visitor', count: 2 },\n { location: 'Kirrawee', identity: 'worker', count: 1 },\n { location: 'Sutherland', identity: 'student', count: 1 },\n { location: 'Sutherland', identity: 'resident', count: 2 },\n { location: 'Sutherland', identity: 'worker', count: 1 },\n { location: 'Miranda', identity: 'resident', count: 2 },\n { location: 'Miranda', identity: 'worker', count: 2 },\n { location: 'Miranda', identity: 'student', count: 1 },\n { location: 'Miranda', identity: '', count: 1 }\n]"
}
] |
Python | Create a Pandas Dataframe from a dict of equal length lists - GeeksforGeeks
|
23 Nov, 2018
Given a dictionary of equal length lists, task is to create a Pandas DataFrame from it.
There are various ways of creating a DataFrame in Pandas. One way is to convert a dictionary containing lists of equal lengths as values. Let’s discuss how to create a Pandas Dataframe from a dict of equal length lists with help of examples.
Example #1: Given a dictionary which contains format of cricket as keys and list of top five teams as values.
# Import pandas package import pandas as pd # Define a dictionary containing ICC rankingsrankings = {'test': ['India', 'South Africa', 'England', 'New Zealand', 'Australia'], 'odi': ['England', 'India', 'New Zealand', 'South Africa', 'Pakistan'], 't20': ['Pakistan', 'India', 'Australia', 'England', 'New Zealand']} # Convert the dictionary into DataFramerankings_pd = pd.DataFrame(rankings) # Increment the index so that index # starts at 1 (starts at 0 by default) rankings_pd.index += 1 rankings_pd
Output:
Example #2: Given three lists test_batsmen, odi_batsmen, t20_batsmen. So we first need to convert this data into a dictionary and then convert the dictionary into DataFrame.
# Import pandas package import pandas as pd # Lists of top 5 batsmen for each formattest_batsmen = ['Virat Kohli', 'Steve Smith', 'Kane Williamson', 'Joe Root', 'David Warner']odi_batsmen = ['Virat Kohli', 'Rohit Sharma', 'Joe Root', 'David Warner', 'Babar Azam']t20_batsmen = ['Babar Azam', 'Aaron Finch', 'Colin Munro', 'Lokesh Rahul', 'Fakhar Zaman'] # Define a dictionary containing ICC rankings for batsmenrankings_batsmen = {'test': test_batsmen, 'odi': odi_batsmen, 't20': t20_batsmen} # Convert the dictionary into DataFramerankings_batsmen_pd = pd.DataFrame(rankings_batsmen) # Increment the index so that index# starts at 1 (starts at 0 by default) rankings_batsmen_pd.index += 1 rankings_batsmen_pd
Output:
pandas-dataframe-program
Picked
Python pandas-dataFrame
Python-pandas
Technical Scripter 2018
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Selecting rows in pandas DataFrame based on conditions
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Split string into list of characters
|
[
{
"code": null,
"e": 24318,
"s": 24290,
"text": "\n23 Nov, 2018"
},
{
"code": null,
"e": 24406,
"s": 24318,
"text": "Given a dictionary of equal length lists, task is to create a Pandas DataFrame from it."
},
{
"code": null,
"e": 24648,
"s": 24406,
"text": "There are various ways of creating a DataFrame in Pandas. One way is to convert a dictionary containing lists of equal lengths as values. Let’s discuss how to create a Pandas Dataframe from a dict of equal length lists with help of examples."
},
{
"code": null,
"e": 24758,
"s": 24648,
"text": "Example #1: Given a dictionary which contains format of cricket as keys and list of top five teams as values."
},
{
"code": "# Import pandas package import pandas as pd # Define a dictionary containing ICC rankingsrankings = {'test': ['India', 'South Africa', 'England', 'New Zealand', 'Australia'], 'odi': ['England', 'India', 'New Zealand', 'South Africa', 'Pakistan'], 't20': ['Pakistan', 'India', 'Australia', 'England', 'New Zealand']} # Convert the dictionary into DataFramerankings_pd = pd.DataFrame(rankings) # Increment the index so that index # starts at 1 (starts at 0 by default) rankings_pd.index += 1 rankings_pd",
"e": 25375,
"s": 24758,
"text": null
},
{
"code": null,
"e": 25383,
"s": 25375,
"text": "Output:"
},
{
"code": null,
"e": 25558,
"s": 25383,
"text": " Example #2: Given three lists test_batsmen, odi_batsmen, t20_batsmen. So we first need to convert this data into a dictionary and then convert the dictionary into DataFrame."
},
{
"code": "# Import pandas package import pandas as pd # Lists of top 5 batsmen for each formattest_batsmen = ['Virat Kohli', 'Steve Smith', 'Kane Williamson', 'Joe Root', 'David Warner']odi_batsmen = ['Virat Kohli', 'Rohit Sharma', 'Joe Root', 'David Warner', 'Babar Azam']t20_batsmen = ['Babar Azam', 'Aaron Finch', 'Colin Munro', 'Lokesh Rahul', 'Fakhar Zaman'] # Define a dictionary containing ICC rankings for batsmenrankings_batsmen = {'test': test_batsmen, 'odi': odi_batsmen, 't20': t20_batsmen} # Convert the dictionary into DataFramerankings_batsmen_pd = pd.DataFrame(rankings_batsmen) # Increment the index so that index# starts at 1 (starts at 0 by default) rankings_batsmen_pd.index += 1 rankings_batsmen_pd",
"e": 26404,
"s": 25558,
"text": null
},
{
"code": null,
"e": 26412,
"s": 26404,
"text": "Output:"
},
{
"code": null,
"e": 26437,
"s": 26412,
"text": "pandas-dataframe-program"
},
{
"code": null,
"e": 26444,
"s": 26437,
"text": "Picked"
},
{
"code": null,
"e": 26468,
"s": 26444,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 26482,
"s": 26468,
"text": "Python-pandas"
},
{
"code": null,
"e": 26506,
"s": 26482,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 26513,
"s": 26506,
"text": "Python"
},
{
"code": null,
"e": 26532,
"s": 26513,
"text": "Technical Scripter"
},
{
"code": null,
"e": 26630,
"s": 26532,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26662,
"s": 26630,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26718,
"s": 26662,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26760,
"s": 26718,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26802,
"s": 26760,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26857,
"s": 26802,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 26879,
"s": 26857,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26918,
"s": 26879,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26949,
"s": 26918,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26978,
"s": 26949,
"text": "Create a directory in Python"
}
] |
How to use snackbar in Android?
|
This example demonstrates how do I use snackBar 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"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Click button below to bring up snackBar" />
<Button
android:id="@+id/callbackButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_below="@id/textView"
android:layout_marginTop="16sp"
android:text="Tap To Display SnackBar"
android:textStyle="bold"
android:textSize="16sp"/>
</RelativeLayout>
Step 3 – Open build.gradle(Module app) add the following dependancy -
implementation 'com.android.support:design:28.0.0'
Step 4 − Add the following code to src/MainActivity.java
import android.graphics.Color;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.callbackButton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Snackbar snackBar = Snackbar .make(v, "An Error Occurred!", Snackbar.LENGTH_LONG) .setAction("RETRY", new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
snackBar.setActionTextColor(Color.BLUE);
View snackBarView = snackBar.getView();
TextView textView = snackBarView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.RED);
snackBar.show();
}
});
}
}
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": 1122,
"s": 1062,
"text": "This example demonstrates how do I use snackBar in android."
},
{
"code": null,
"e": 1251,
"s": 1122,
"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": 1316,
"s": 1251,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2215,
"s": 1316,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:text=\"Click button below to bring up snackBar\" />\n <Button\n android:id=\"@+id/callbackButton\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:layout_below=\"@id/textView\"\n android:layout_marginTop=\"16sp\"\n android:text=\"Tap To Display SnackBar\"\n android:textStyle=\"bold\"\n android:textSize=\"16sp\"/>\n</RelativeLayout>"
},
{
"code": null,
"e": 2285,
"s": 2215,
"text": "Step 3 – Open build.gradle(Module app) add the following dependancy -"
},
{
"code": null,
"e": 2336,
"s": 2285,
"text": "implementation 'com.android.support:design:28.0.0'"
},
{
"code": null,
"e": 2393,
"s": 2336,
"text": "Step 4 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3561,
"s": 2393,
"text": "import android.graphics.Color;\nimport android.support.design.widget.Snackbar;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\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 Button button = findViewById(R.id.callbackButton);\n button.setOnClickListener(new View.OnClickListener() {\n public void onClick(View v) {\n Snackbar snackBar = Snackbar .make(v, \"An Error Occurred!\", Snackbar.LENGTH_LONG) .setAction(\"RETRY\", new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n }\n });\n snackBar.setActionTextColor(Color.BLUE);\n View snackBarView = snackBar.getView();\n TextView textView = snackBarView.findViewById(android.support.design.R.id.snackbar_text);\n textView.setTextColor(Color.RED);\n snackBar.show();\n }\n });\n }\n}"
},
{
"code": null,
"e": 3616,
"s": 3561,
"text": "Step 4 - Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 4286,
"s": 3616,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 4633,
"s": 4286,
"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": 4674,
"s": 4633,
"text": "Click here to download the project code."
}
] |
Inheritance in Dart Programming
|
Inheritance in dart is defined as the process in which one class derive the properties and characteristics of another class. It is helpful as it provides an ability with which we can create a new class from an existing class.
Inheritance is a major component of a programming paradigm known as OOPS (Object-Oriented Programming).
With the help of Inheritance, one class can make use of all the properties and characteristics of another class.
In general, two classes are required for inheritance and these mainly are −
Parent class - A class that is inherited by the other class is known as the parent class. Sometimes, we also refer it to as the base class.
Parent class - A class that is inherited by the other class is known as the parent class. Sometimes, we also refer it to as the base class.
Child class - A class that inherits the properties and characteristics of the parent class is known as child class.
Child class - A class that inherits the properties and characteristics of the parent class is known as child class.
The syntax for a class to inherit the properties and characteristics of another class looks something like this −
class Childclass extends ParentClass {
...
}
Whenever a child class wants to inherit the properties and characteristics of a parent class, we make use of the extends keyword.
There are different types of inheritance that are possible in Dart. Mainly these are −
Single level inheritance
Single level inheritance
Multi-level inheritance
Multi-level inheritance
Hierarchal inheritance
Hierarchal inheritance
In this article, we will learn only about single level inheritance to keep things simple.
Single level inheritance is that case of inheritance where a single class inherits from the parent class.
Consider the example shown below −
Live Demo
class Human{
void walk(){
print("Humans walk!");
}
}
// inherting the parent class i.e Human
class Person extends Human{
void speak(){
print("That person can speak");
}
}
void main(){
Person p = new Person();
p.speak();
p.walk(); // invoking the parent class method
}
In the above example, we have two classes, named Human and Person respectively, the class named Human is the superclass and the class named Person is the child class, which is inheriting the method named walk() from the class named Human.
That person can speak
Humans walk!
|
[
{
"code": null,
"e": 1288,
"s": 1062,
"text": "Inheritance in dart is defined as the process in which one class derive the properties and characteristics of another class. It is helpful as it provides an ability with which we can create a new class from an existing class."
},
{
"code": null,
"e": 1392,
"s": 1288,
"text": "Inheritance is a major component of a programming paradigm known as OOPS (Object-Oriented Programming)."
},
{
"code": null,
"e": 1505,
"s": 1392,
"text": "With the help of Inheritance, one class can make use of all the properties and characteristics of another class."
},
{
"code": null,
"e": 1581,
"s": 1505,
"text": "In general, two classes are required for inheritance and these mainly are −"
},
{
"code": null,
"e": 1721,
"s": 1581,
"text": "Parent class - A class that is inherited by the other class is known as the parent class. Sometimes, we also refer it to as the base class."
},
{
"code": null,
"e": 1861,
"s": 1721,
"text": "Parent class - A class that is inherited by the other class is known as the parent class. Sometimes, we also refer it to as the base class."
},
{
"code": null,
"e": 1977,
"s": 1861,
"text": "Child class - A class that inherits the properties and characteristics of the parent class is known as child class."
},
{
"code": null,
"e": 2093,
"s": 1977,
"text": "Child class - A class that inherits the properties and characteristics of the parent class is known as child class."
},
{
"code": null,
"e": 2207,
"s": 2093,
"text": "The syntax for a class to inherit the properties and characteristics of another class looks something like this −"
},
{
"code": null,
"e": 2252,
"s": 2207,
"text": "class Childclass extends ParentClass {\n...\n}"
},
{
"code": null,
"e": 2382,
"s": 2252,
"text": "Whenever a child class wants to inherit the properties and characteristics of a parent class, we make use of the extends keyword."
},
{
"code": null,
"e": 2469,
"s": 2382,
"text": "There are different types of inheritance that are possible in Dart. Mainly these are −"
},
{
"code": null,
"e": 2494,
"s": 2469,
"text": "Single level inheritance"
},
{
"code": null,
"e": 2519,
"s": 2494,
"text": "Single level inheritance"
},
{
"code": null,
"e": 2543,
"s": 2519,
"text": "Multi-level inheritance"
},
{
"code": null,
"e": 2567,
"s": 2543,
"text": "Multi-level inheritance"
},
{
"code": null,
"e": 2590,
"s": 2567,
"text": "Hierarchal inheritance"
},
{
"code": null,
"e": 2613,
"s": 2590,
"text": "Hierarchal inheritance"
},
{
"code": null,
"e": 2703,
"s": 2613,
"text": "In this article, we will learn only about single level inheritance to keep things simple."
},
{
"code": null,
"e": 2809,
"s": 2703,
"text": "Single level inheritance is that case of inheritance where a single class inherits from the parent class."
},
{
"code": null,
"e": 2844,
"s": 2809,
"text": "Consider the example shown below −"
},
{
"code": null,
"e": 2855,
"s": 2844,
"text": " Live Demo"
},
{
"code": null,
"e": 3158,
"s": 2855,
"text": "class Human{\n void walk(){\n print(\"Humans walk!\");\n }\n}\n\n// inherting the parent class i.e Human\nclass Person extends Human{\n void speak(){\n print(\"That person can speak\");\n }\n}\n\nvoid main(){\n Person p = new Person();\n p.speak();\n p.walk(); // invoking the parent class method\n}"
},
{
"code": null,
"e": 3397,
"s": 3158,
"text": "In the above example, we have two classes, named Human and Person respectively, the class named Human is the superclass and the class named Person is the child class, which is inheriting the method named walk() from the class named Human."
},
{
"code": null,
"e": 3432,
"s": 3397,
"text": "That person can speak\nHumans walk!"
}
] |
GATE | Gate IT 2007 | Question 30
|
28 Jun, 2021
Suppose you are given an implementation of a queue of integers. The operations that can be performed on the queue are:i. isEmpty (Q) — returns true if the queue is empty, false otherwise.ii. delete (Q) — deletes the element at the front of the queue and returns its value.iii. insert (Q, i) — inserts the integer i at the rear of the queue.Consider the following function:
void f (queue Q) {int i ;if (!isEmpty(Q)) { i = delete(Q); f(Q); insert(Q, i); }}
What operation is performed by the above function f ?(A) Leaves the queue Q unchanged(B) Reverses the order of the elements in the queue Q(C) Deletes the element at the front of the queue Q and inserts it at the rear keeping the other elements in the same order(D) Empties the queue Q
Answer: (B)Explanation: As it is recursive call, and removing from front while inserting from end, that means last element will be deleted at last and will be inserted 1st in the new queue. And like that it will continue till first call executes insert(Q,i) function.So, the queue will be in reverse.Quiz of this Question
Gate IT 2007
GATE-Gate IT 2007
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 401,
"s": 28,
"text": "Suppose you are given an implementation of a queue of integers. The operations that can be performed on the queue are:i. isEmpty (Q) — returns true if the queue is empty, false otherwise.ii. delete (Q) — deletes the element at the front of the queue and returns its value.iii. insert (Q, i) — inserts the integer i at the rear of the queue.Consider the following function:"
},
{
"code": "void f (queue Q) {int i ;if (!isEmpty(Q)) { i = delete(Q); f(Q); insert(Q, i); }}",
"e": 490,
"s": 401,
"text": null
},
{
"code": null,
"e": 775,
"s": 490,
"text": "What operation is performed by the above function f ?(A) Leaves the queue Q unchanged(B) Reverses the order of the elements in the queue Q(C) Deletes the element at the front of the queue Q and inserts it at the rear keeping the other elements in the same order(D) Empties the queue Q"
},
{
"code": null,
"e": 1097,
"s": 775,
"text": "Answer: (B)Explanation: As it is recursive call, and removing from front while inserting from end, that means last element will be deleted at last and will be inserted 1st in the new queue. And like that it will continue till first call executes insert(Q,i) function.So, the queue will be in reverse.Quiz of this Question"
},
{
"code": null,
"e": 1110,
"s": 1097,
"text": "Gate IT 2007"
},
{
"code": null,
"e": 1128,
"s": 1110,
"text": "GATE-Gate IT 2007"
},
{
"code": null,
"e": 1133,
"s": 1128,
"text": "GATE"
}
] |
Primary key constraint in SQL
|
11 Nov, 2020
A primary key constraint depicts a key comprising one or more columns that will help uniquely identify every tuple/record in a table.
Properties :
No duplicate values are allowed, i.e. Column assigned as primary key should have UNIQUE values only.NO NULL values are present in column with Primary key. Hence there is Mandatory value in column having Primary key.Only one primary key per table exist although Primary key may have multiple columns.No new row can be inserted with the already existing primary key.Classified as : a) Simple primary key that has a Single column 2) Composite primary key has Multiple column.Defined in Create table / Alter table statement.
No duplicate values are allowed, i.e. Column assigned as primary key should have UNIQUE values only.
NO NULL values are present in column with Primary key. Hence there is Mandatory value in column having Primary key.
Only one primary key per table exist although Primary key may have multiple columns.
No new row can be inserted with the already existing primary key.
Classified as : a) Simple primary key that has a Single column 2) Composite primary key has Multiple column.
Defined in Create table / Alter table statement.
The primary key can be created in a table using PRIMARY KEY constraint. It can be created at two levels.
ColumnTable.
Column
Table.
SQL PRIMARY KEY at Column Level :If Primary key contains just one column, it should be defined at column level. The following code creates the Primary key “ID” on the person table.
Syntax :
Create Table Person
(
Id int NOT NULL PRIMARY KEY,
Name varchar2(20),
Address varchar2(50)
);
Here NOT NULL is added to make sure ID should have unique values. SQL will automatically set null values to the primary key if it is not specified.
Example-1 :To verify the working of Primary key :
Insert into Person values(1, 'Ajay', 'Mumbai');
Output :
1 row created
Example-2 :Let’s see if you will insert the same values again.
Insert into Person values(1, 'Ajay', 'Mumbai');
Output :
Error at line 1: unique constraint violated
Since we are inserting duplicate values, an error will be thrown since the Primary key “Id” can contain only unique values.
Example-3 :
Insert into Person values('', 'Ajay', 'Mumbai');
Output :
Error at line 1: cannot insert Null into<"user"."Person"."ID">
Primary Key cannot contain Null Values so That too will throw an error.
SQL PRIMARY KEY at Table Level :Whenever the primary key contains multiple columns it has to be specified at Table level.
Syntax:
Create Table Person
(Id int NOT NULL,
Name varchar2(20),
Address varchar2(50),
PRIMARY KEY(Id, Name)
);
Here, you have only one Primary Key in a table but it consists of Multiple Columns(Id, Name). However, the Following are permissible.
Insert into Person values(1, 'Ajay', 'Mumbai');
Insert into Person values(2, 'Ajay', 'Mumbai');
Since multiple columns make up Primary Key so both the rows are considered different. SQL permits either of the two values can be duplicated but the combination must be unique.
SQL PRIMARY KEY with ALTER TABLE :Most of the time, Primary Key is defined during the creation of the table but sometimes the Primary key may not be created in the already existing table. We can however add Primary Key using Alter Statement.
Syntax :
Alter Table Person add Primary Key(Id);
To add Primary key in multiple columns using the following query.
Alter Table Person add Primary Key(Id, Name);
It is necessary that the column added as primary key MUST contain unique values or else it will be violated. An id cannot be made Primary key if it contains duplicate values. It violates the basic rule of Primary Key. Altering the table to add Id as a primary key that may contain duplicate values generates an error.
Output :
Error at line 1: cannot validate- primary key violated
Also, A column added as primary key using alter statement should not have null values. Altering table to add Id as primary key that may contain null values generates an error.
Output :
Error at line 1: column contains NULL values; cannot alter to NOT NULL
DELETE PRIMARY KEY CONSTRAINT :To remove Primary Key constraint on table use given SQL as follows.
ALTER table Person DROP PRIMARY KEY;
DBMS-SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n11 Nov, 2020"
},
{
"code": null,
"e": 187,
"s": 53,
"text": "A primary key constraint depicts a key comprising one or more columns that will help uniquely identify every tuple/record in a table."
},
{
"code": null,
"e": 200,
"s": 187,
"text": "Properties :"
},
{
"code": null,
"e": 721,
"s": 200,
"text": "No duplicate values are allowed, i.e. Column assigned as primary key should have UNIQUE values only.NO NULL values are present in column with Primary key. Hence there is Mandatory value in column having Primary key.Only one primary key per table exist although Primary key may have multiple columns.No new row can be inserted with the already existing primary key.Classified as : a) Simple primary key that has a Single column 2) Composite primary key has Multiple column.Defined in Create table / Alter table statement."
},
{
"code": null,
"e": 822,
"s": 721,
"text": "No duplicate values are allowed, i.e. Column assigned as primary key should have UNIQUE values only."
},
{
"code": null,
"e": 938,
"s": 822,
"text": "NO NULL values are present in column with Primary key. Hence there is Mandatory value in column having Primary key."
},
{
"code": null,
"e": 1023,
"s": 938,
"text": "Only one primary key per table exist although Primary key may have multiple columns."
},
{
"code": null,
"e": 1089,
"s": 1023,
"text": "No new row can be inserted with the already existing primary key."
},
{
"code": null,
"e": 1198,
"s": 1089,
"text": "Classified as : a) Simple primary key that has a Single column 2) Composite primary key has Multiple column."
},
{
"code": null,
"e": 1247,
"s": 1198,
"text": "Defined in Create table / Alter table statement."
},
{
"code": null,
"e": 1352,
"s": 1247,
"text": "The primary key can be created in a table using PRIMARY KEY constraint. It can be created at two levels."
},
{
"code": null,
"e": 1365,
"s": 1352,
"text": "ColumnTable."
},
{
"code": null,
"e": 1372,
"s": 1365,
"text": "Column"
},
{
"code": null,
"e": 1379,
"s": 1372,
"text": "Table."
},
{
"code": null,
"e": 1560,
"s": 1379,
"text": "SQL PRIMARY KEY at Column Level :If Primary key contains just one column, it should be defined at column level. The following code creates the Primary key “ID” on the person table."
},
{
"code": null,
"e": 1569,
"s": 1560,
"text": "Syntax :"
},
{
"code": null,
"e": 1666,
"s": 1569,
"text": "Create Table Person\n(\nId int NOT NULL PRIMARY KEY, \nName varchar2(20), \nAddress varchar2(50)\n);\n"
},
{
"code": null,
"e": 1814,
"s": 1666,
"text": "Here NOT NULL is added to make sure ID should have unique values. SQL will automatically set null values to the primary key if it is not specified."
},
{
"code": null,
"e": 1864,
"s": 1814,
"text": "Example-1 :To verify the working of Primary key :"
},
{
"code": null,
"e": 1913,
"s": 1864,
"text": "Insert into Person values(1, 'Ajay', 'Mumbai');\n"
},
{
"code": null,
"e": 1922,
"s": 1913,
"text": "Output :"
},
{
"code": null,
"e": 1937,
"s": 1922,
"text": "1 row created\n"
},
{
"code": null,
"e": 2000,
"s": 1937,
"text": "Example-2 :Let’s see if you will insert the same values again."
},
{
"code": null,
"e": 2048,
"s": 2000,
"text": "Insert into Person values(1, 'Ajay', 'Mumbai');"
},
{
"code": null,
"e": 2057,
"s": 2048,
"text": "Output :"
},
{
"code": null,
"e": 2102,
"s": 2057,
"text": "Error at line 1: unique constraint violated\n"
},
{
"code": null,
"e": 2226,
"s": 2102,
"text": "Since we are inserting duplicate values, an error will be thrown since the Primary key “Id” can contain only unique values."
},
{
"code": null,
"e": 2238,
"s": 2226,
"text": "Example-3 :"
},
{
"code": null,
"e": 2288,
"s": 2238,
"text": "Insert into Person values('', 'Ajay', 'Mumbai');\n"
},
{
"code": null,
"e": 2297,
"s": 2288,
"text": "Output :"
},
{
"code": null,
"e": 2361,
"s": 2297,
"text": "Error at line 1: cannot insert Null into<\"user\".\"Person\".\"ID\">\n"
},
{
"code": null,
"e": 2433,
"s": 2361,
"text": "Primary Key cannot contain Null Values so That too will throw an error."
},
{
"code": null,
"e": 2555,
"s": 2433,
"text": "SQL PRIMARY KEY at Table Level :Whenever the primary key contains multiple columns it has to be specified at Table level."
},
{
"code": null,
"e": 2563,
"s": 2555,
"text": "Syntax:"
},
{
"code": null,
"e": 2687,
"s": 2563,
"text": "Create Table Person\n(Id int NOT NULL, \nName varchar2(20), \nAddress varchar2(50), \nPRIMARY KEY(Id, Name)\n); \n"
},
{
"code": null,
"e": 2821,
"s": 2687,
"text": "Here, you have only one Primary Key in a table but it consists of Multiple Columns(Id, Name). However, the Following are permissible."
},
{
"code": null,
"e": 2918,
"s": 2821,
"text": "Insert into Person values(1, 'Ajay', 'Mumbai');\nInsert into Person values(2, 'Ajay', 'Mumbai');\n"
},
{
"code": null,
"e": 3095,
"s": 2918,
"text": "Since multiple columns make up Primary Key so both the rows are considered different. SQL permits either of the two values can be duplicated but the combination must be unique."
},
{
"code": null,
"e": 3337,
"s": 3095,
"text": "SQL PRIMARY KEY with ALTER TABLE :Most of the time, Primary Key is defined during the creation of the table but sometimes the Primary key may not be created in the already existing table. We can however add Primary Key using Alter Statement."
},
{
"code": null,
"e": 3346,
"s": 3337,
"text": "Syntax :"
},
{
"code": null,
"e": 3387,
"s": 3346,
"text": "Alter Table Person add Primary Key(Id);\n"
},
{
"code": null,
"e": 3453,
"s": 3387,
"text": "To add Primary key in multiple columns using the following query."
},
{
"code": null,
"e": 3500,
"s": 3453,
"text": "Alter Table Person add Primary Key(Id, Name);\n"
},
{
"code": null,
"e": 3818,
"s": 3500,
"text": "It is necessary that the column added as primary key MUST contain unique values or else it will be violated. An id cannot be made Primary key if it contains duplicate values. It violates the basic rule of Primary Key. Altering the table to add Id as a primary key that may contain duplicate values generates an error."
},
{
"code": null,
"e": 3827,
"s": 3818,
"text": "Output :"
},
{
"code": null,
"e": 3883,
"s": 3827,
"text": "Error at line 1: cannot validate- primary key violated\n"
},
{
"code": null,
"e": 4059,
"s": 3883,
"text": "Also, A column added as primary key using alter statement should not have null values. Altering table to add Id as primary key that may contain null values generates an error."
},
{
"code": null,
"e": 4068,
"s": 4059,
"text": "Output :"
},
{
"code": null,
"e": 4140,
"s": 4068,
"text": "Error at line 1: column contains NULL values; cannot alter to NOT NULL\n"
},
{
"code": null,
"e": 4239,
"s": 4140,
"text": "DELETE PRIMARY KEY CONSTRAINT :To remove Primary Key constraint on table use given SQL as follows."
},
{
"code": null,
"e": 4277,
"s": 4239,
"text": "ALTER table Person DROP PRIMARY KEY;\n"
},
{
"code": null,
"e": 4286,
"s": 4277,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 4290,
"s": 4286,
"text": "SQL"
},
{
"code": null,
"e": 4294,
"s": 4290,
"text": "SQL"
}
] |
Sum of Fibonacci Numbers in a range
|
09 Jun, 2022
Given a range [l, r], the task is to find the sum fib(l) + fib(l + 1) + fib(l + 2) + ..... + fib(r) where fib(n) is the nth Fibonacci number.
Examples:
Input: l = 2, r = 5 Output: 11 fib(2) + fib(3) + fib(4) + fib(5) = 1 + 2 + 3 + 5 = 11
Input: l = 4, r = 8 Output: 50
Naive approach: Simply calculate fib(l) + fib(l + 1) + fib(l + 2) + ..... + fib(r) in O(r – l) time complexity. In order to find fib(n) in O(1) we will take the help of the Golden Ratio.
Fibonacci’s calculation using Binet’s Formula
fib(n) = phin – psin) / ?5 Where, phi = (1 + sqrt(5)) / 2 which is roughly equal to 1.61803398875 psi = 1 – phi = (1 – sqrt(5)) / 2 which is roughly equal to 0.61803398875
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define ll long long int // Function to return the nth Fibonacci numberint fib(int n){ double phi = (1 + sqrt(5)) / 2; return round(pow(phi, n) / sqrt(5));} // Function to return the required sumll calculateSum(int l, int r){ // To store the sum ll sum = 0; // Calculate the sum for (int i = l; i <= r; i++) sum += fib(i); return sum;} // Driver codeint main(){ int l = 4, r = 8; cout << calculateSum(l, r); return 0;}
// Java implementation of the approachimport java.lang.Math;class GFG{ // Function to return the nth Fibonacci numberstatic int fib(int n){ double phi = (1 + Math.sqrt(5)) / 2; return (int)Math.round(Math.pow(phi, n) / Math.sqrt(5));} // Function to return the required sumstatic int calculateSum(int l, int r){ // To store the sum int sum = 0; // Calculate the sum for (int i = l; i <= r; i++) sum += fib(i); return sum;} // Driver codepublic static void main(String[] args){ int l = 4, r = 8; System.out.println(calculateSum(l, r)); }} //This code is contributed by Code_Mech.
# Python3 implementation of the approach # Function to return the nth# Fibonacci numberdef fib(n): phi = ((1 + (5 ** (1 / 2))) / 2); return round((phi ** n) / (5 ** (1 / 2))); # Function to return the required sumdef calculateSum(l, r): # To store the sum sum = 0; # Calculate the sum for i in range(l, r + 1): sum += fib(i); return sum; # Driver Codeif __name__ == '__main__': l, r = 4, 8; print(calculateSum(l, r)); # This code contributed by Rajput-Ji
// C# implementation of above approach using System; class GFG{ // Function to return the nth Fibonacci numberstatic int fib(int n){ double phi = (1 + Math.Sqrt(5)) / 2; return (int)Math.Round(Math.Pow(phi, n) / Math.Sqrt(5));} // Function to return the required sumstatic int calculateSum(int l, int r){ // To store the sum int sum = 0; // Calculate the sum for (int i = l; i <= r; i++) sum += fib(i); return sum;} // Driver codepublic static void Main(){ int l = 4, r = 8; Console.WriteLine(calculateSum(l, r));}} /* This code contributed by PrinciRaj1992 */
<?php// PHP implementation of the approach // Function to return the nth // Fibonacci numberfunction fib($n){ $phi = (1 + sqrt(5)) / 2; return (int)round(pow($phi, $n) / sqrt(5));} // Function to return the required sumfunction calculateSum($l, $r){ // To store the sum $sum = 0; // Calculate the sum for ($i = $l; $i <= $r; $i++) $sum += fib($i); return $sum;} // Driver code$l = 4;$r = 8;echo calculateSum($l, $r); // This code is contributed by mits?>
<script> // Javascript implementation of the approach // Function to return the nth Fibonacci number function fib(n) { var phi = (1 + Math.sqrt(5)) / 2; return parseInt( Math.round (Math.pow(phi, n)/ Math.sqrt(5)) ); } // Function to return the required sum function calculateSum(l , r) { // To store the sum var sum = 0; // Calculate the sum for (i = l; i <= r; i++) sum += fib(i); return sum; } // Driver code var l = 4, r = 8; document.write(calculateSum(l, r)); // This code contributed by gauravrajput1 </script>
50
Efficient approach: The idea is to find the relationship between the sum of Fibonacci numbers and nth Fibonacci number and use Binet’s Formula to calculate its value.
Relationship Deduction
F(i) refers to the ith Fibonacci number.S(i) refers to the sum of Fibonacci numbers till F(i).
F(i) refers to the ith Fibonacci number.
S(i) refers to the sum of Fibonacci numbers till F(i).
We can rewrite the relation F(n + 1) = F(n) + F(n – 1) as below: F(n – 1) = F(n + 1) – F(n) Similarly, F(n – 2) = F(n) – F(n – 1) ... ... ... F(0) = F(2) – F(1)Adding all the equations, on left side, we have F(0) + F(1) + ... + F(n – 1) which is S(n – 1)
Therefore, S(n – 1) = F(n + 1) – F(1) S(n – 1) = F(n + 1) – 1 S(n) = F(n + 2) – 1
In order to find S(n), simply calculate the (n + 2)th Fibonacci number and subtract 1 from the result. Therefore, S(l, r) = S(r) – S(l – 1) S(l, r) = F(r + 2) – 1 – (F(l + 1) – 1) S(l, r) = F(r + 2) – F(l + 1)
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the nth Fibonacci numberint fib(int n){ double phi = (1 + sqrt(5)) / 2; return round(pow(phi, n) / sqrt(5));} // Function to return the required sumint calculateSum(int l, int r){ // Using our deduced result int sum = fib(r + 2) - fib(l + 1); return sum;} // Driver codeint main(){ int l = 4, r = 8; cout << calculateSum(l, r); return 0;}
// Java implementation of the approachclass GFG { // Function to return the nth Fibonacci numberstatic int fib(int n){ double phi = (1 + Math.sqrt(5)) / 2; return (int) Math.round(Math.pow(phi, n) / Math.sqrt(5));} // Function to return the required sumstatic int calculateSum(int l, int r){ // Using our deduced result int sum = fib(r + 2) - fib(l + 1); return sum;} // Driver codepublic static void main(String[] args) { int l = 4, r = 8; System.out.println(calculateSum(l, r)); }} // This code is contributed by 29AjayKumar
# Python3 implementation of the approachimport math # Function to return the nth # Fibonacci numberdef fib(n): phi = (1 + math.sqrt(5)) / 2; return int(round(pow(phi, n) / math.sqrt(5))); # Function to return the required sumdef calculateSum(l, r): # Using our deduced result sum = fib(r + 2) - fib(l + 1); return sum; # Driver codel = 4; r = 8;print(calculateSum(l, r)); # This code is contributed by mits
// C# implementation of the approachusing System; class GFG { // Function to return the nth Fibonacci numberstatic int fib(int n){ double phi = (1 + Math.Sqrt(5)) / 2; return (int) Math.Round(Math.Pow(phi, n) / Math.Sqrt(5));} // Function to return the required sumstatic int calculateSum(int l, int r){ // Using our deduced result int sum = fib(r + 2) - fib(l + 1); return sum;} // Driver codepublic static void Main() { int l = 4, r = 8; Console.WriteLine(calculateSum(l, r));}} // This code is contributed// by Akanksha Rai
<?php// PHP implementation of the approach // Function to return the nth Fibonacci numberfunction fib($n){ $phi = (1 + sqrt(5)) / 2; return (int) round(pow($phi, $n) / sqrt(5));} // Function to return the required sumfunction calculateSum($l, $r){ // Using our deduced result $sum = fib($r + 2) - fib($l + 1); return $sum;} // Driver code$l = 4; $r = 8;echo(calculateSum($l, $r)); // This code is contributed by Code_Mech?>
<script>// javascript implementation of the approach // Function to return the nth Fibonacci number function fib(n) { var phi = (1 + Math.sqrt(5)) / 2; return parseInt( Math.round(Math.pow(phi, n) / Math.sqrt(5))); } // Function to return the required sum function calculateSum(l , r) { // Using our deduced result var sum = fib(r + 2) - fib(l + 1); return sum; } // Driver code var l = 4, r = 8; document.write(calculateSum(l, r)); // This code contributed by aashish1995</script>
50
Time Complexity: O(log r)Auxiliary Space: O(1)
Mithun Kumar
Code_Mech
princiraj1992
29AjayKumar
Akanksha_Rai
Rajput-Ji
GauravRajput1
aashish1995
pankajsharmagfg
saurabh1990aror
Fibonacci
Algorithms
Competitive Programming
Mathematical
Mathematical
Fibonacci
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n09 Jun, 2022"
},
{
"code": null,
"e": 196,
"s": 54,
"text": "Given a range [l, r], the task is to find the sum fib(l) + fib(l + 1) + fib(l + 2) + ..... + fib(r) where fib(n) is the nth Fibonacci number."
},
{
"code": null,
"e": 207,
"s": 196,
"text": "Examples: "
},
{
"code": null,
"e": 293,
"s": 207,
"text": "Input: l = 2, r = 5 Output: 11 fib(2) + fib(3) + fib(4) + fib(5) = 1 + 2 + 3 + 5 = 11"
},
{
"code": null,
"e": 326,
"s": 293,
"text": "Input: l = 4, r = 8 Output: 50 "
},
{
"code": null,
"e": 514,
"s": 326,
"text": "Naive approach: Simply calculate fib(l) + fib(l + 1) + fib(l + 2) + ..... + fib(r) in O(r – l) time complexity. In order to find fib(n) in O(1) we will take the help of the Golden Ratio. "
},
{
"code": null,
"e": 562,
"s": 514,
"text": "Fibonacci’s calculation using Binet’s Formula "
},
{
"code": null,
"e": 736,
"s": 562,
"text": "fib(n) = phin – psin) / ?5 Where, phi = (1 + sqrt(5)) / 2 which is roughly equal to 1.61803398875 psi = 1 – phi = (1 – sqrt(5)) / 2 which is roughly equal to 0.61803398875 "
},
{
"code": null,
"e": 789,
"s": 736,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 793,
"s": 789,
"text": "C++"
},
{
"code": null,
"e": 798,
"s": 793,
"text": "Java"
},
{
"code": null,
"e": 806,
"s": 798,
"text": "Python3"
},
{
"code": null,
"e": 809,
"s": 806,
"text": "C#"
},
{
"code": null,
"e": 813,
"s": 809,
"text": "PHP"
},
{
"code": null,
"e": 824,
"s": 813,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define ll long long int // Function to return the nth Fibonacci numberint fib(int n){ double phi = (1 + sqrt(5)) / 2; return round(pow(phi, n) / sqrt(5));} // Function to return the required sumll calculateSum(int l, int r){ // To store the sum ll sum = 0; // Calculate the sum for (int i = l; i <= r; i++) sum += fib(i); return sum;} // Driver codeint main(){ int l = 4, r = 8; cout << calculateSum(l, r); return 0;}",
"e": 1372,
"s": 824,
"text": null
},
{
"code": "// Java implementation of the approachimport java.lang.Math;class GFG{ // Function to return the nth Fibonacci numberstatic int fib(int n){ double phi = (1 + Math.sqrt(5)) / 2; return (int)Math.round(Math.pow(phi, n) / Math.sqrt(5));} // Function to return the required sumstatic int calculateSum(int l, int r){ // To store the sum int sum = 0; // Calculate the sum for (int i = l; i <= r; i++) sum += fib(i); return sum;} // Driver codepublic static void main(String[] args){ int l = 4, r = 8; System.out.println(calculateSum(l, r)); }} //This code is contributed by Code_Mech.",
"e": 2000,
"s": 1372,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to return the nth# Fibonacci numberdef fib(n): phi = ((1 + (5 ** (1 / 2))) / 2); return round((phi ** n) / (5 ** (1 / 2))); # Function to return the required sumdef calculateSum(l, r): # To store the sum sum = 0; # Calculate the sum for i in range(l, r + 1): sum += fib(i); return sum; # Driver Codeif __name__ == '__main__': l, r = 4, 8; print(calculateSum(l, r)); # This code contributed by Rajput-Ji",
"e": 2503,
"s": 2000,
"text": null
},
{
"code": "// C# implementation of above approach using System; class GFG{ // Function to return the nth Fibonacci numberstatic int fib(int n){ double phi = (1 + Math.Sqrt(5)) / 2; return (int)Math.Round(Math.Pow(phi, n) / Math.Sqrt(5));} // Function to return the required sumstatic int calculateSum(int l, int r){ // To store the sum int sum = 0; // Calculate the sum for (int i = l; i <= r; i++) sum += fib(i); return sum;} // Driver codepublic static void Main(){ int l = 4, r = 8; Console.WriteLine(calculateSum(l, r));}} /* This code contributed by PrinciRaj1992 */",
"e": 3113,
"s": 2503,
"text": null
},
{
"code": "<?php// PHP implementation of the approach // Function to return the nth // Fibonacci numberfunction fib($n){ $phi = (1 + sqrt(5)) / 2; return (int)round(pow($phi, $n) / sqrt(5));} // Function to return the required sumfunction calculateSum($l, $r){ // To store the sum $sum = 0; // Calculate the sum for ($i = $l; $i <= $r; $i++) $sum += fib($i); return $sum;} // Driver code$l = 4;$r = 8;echo calculateSum($l, $r); // This code is contributed by mits?>",
"e": 3606,
"s": 3113,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function to return the nth Fibonacci number function fib(n) { var phi = (1 + Math.sqrt(5)) / 2; return parseInt( Math.round (Math.pow(phi, n)/ Math.sqrt(5)) ); } // Function to return the required sum function calculateSum(l , r) { // To store the sum var sum = 0; // Calculate the sum for (i = l; i <= r; i++) sum += fib(i); return sum; } // Driver code var l = 4, r = 8; document.write(calculateSum(l, r)); // This code contributed by gauravrajput1 </script>",
"e": 4256,
"s": 3606,
"text": null
},
{
"code": null,
"e": 4259,
"s": 4256,
"text": "50"
},
{
"code": null,
"e": 4428,
"s": 4261,
"text": "Efficient approach: The idea is to find the relationship between the sum of Fibonacci numbers and nth Fibonacci number and use Binet’s Formula to calculate its value."
},
{
"code": null,
"e": 4452,
"s": 4428,
"text": "Relationship Deduction "
},
{
"code": null,
"e": 4548,
"s": 4452,
"text": "F(i) refers to the ith Fibonacci number.S(i) refers to the sum of Fibonacci numbers till F(i). "
},
{
"code": null,
"e": 4589,
"s": 4548,
"text": "F(i) refers to the ith Fibonacci number."
},
{
"code": null,
"e": 4645,
"s": 4589,
"text": "S(i) refers to the sum of Fibonacci numbers till F(i). "
},
{
"code": null,
"e": 4902,
"s": 4645,
"text": "We can rewrite the relation F(n + 1) = F(n) + F(n – 1) as below: F(n – 1) = F(n + 1) – F(n) Similarly, F(n – 2) = F(n) – F(n – 1) ... ... ... F(0) = F(2) – F(1)Adding all the equations, on left side, we have F(0) + F(1) + ... + F(n – 1) which is S(n – 1) "
},
{
"code": null,
"e": 4985,
"s": 4902,
"text": "Therefore, S(n – 1) = F(n + 1) – F(1) S(n – 1) = F(n + 1) – 1 S(n) = F(n + 2) – 1 "
},
{
"code": null,
"e": 5196,
"s": 4985,
"text": "In order to find S(n), simply calculate the (n + 2)th Fibonacci number and subtract 1 from the result. Therefore, S(l, r) = S(r) – S(l – 1) S(l, r) = F(r + 2) – 1 – (F(l + 1) – 1) S(l, r) = F(r + 2) – F(l + 1) "
},
{
"code": null,
"e": 5200,
"s": 5196,
"text": "C++"
},
{
"code": null,
"e": 5205,
"s": 5200,
"text": "Java"
},
{
"code": null,
"e": 5213,
"s": 5205,
"text": "Python3"
},
{
"code": null,
"e": 5216,
"s": 5213,
"text": "C#"
},
{
"code": null,
"e": 5220,
"s": 5216,
"text": "PHP"
},
{
"code": null,
"e": 5231,
"s": 5220,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the nth Fibonacci numberint fib(int n){ double phi = (1 + sqrt(5)) / 2; return round(pow(phi, n) / sqrt(5));} // Function to return the required sumint calculateSum(int l, int r){ // Using our deduced result int sum = fib(r + 2) - fib(l + 1); return sum;} // Driver codeint main(){ int l = 4, r = 8; cout << calculateSum(l, r); return 0;}",
"e": 5705,
"s": 5231,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG { // Function to return the nth Fibonacci numberstatic int fib(int n){ double phi = (1 + Math.sqrt(5)) / 2; return (int) Math.round(Math.pow(phi, n) / Math.sqrt(5));} // Function to return the required sumstatic int calculateSum(int l, int r){ // Using our deduced result int sum = fib(r + 2) - fib(l + 1); return sum;} // Driver codepublic static void main(String[] args) { int l = 4, r = 8; System.out.println(calculateSum(l, r)); }} // This code is contributed by 29AjayKumar",
"e": 6260,
"s": 5705,
"text": null
},
{
"code": "# Python3 implementation of the approachimport math # Function to return the nth # Fibonacci numberdef fib(n): phi = (1 + math.sqrt(5)) / 2; return int(round(pow(phi, n) / math.sqrt(5))); # Function to return the required sumdef calculateSum(l, r): # Using our deduced result sum = fib(r + 2) - fib(l + 1); return sum; # Driver codel = 4; r = 8;print(calculateSum(l, r)); # This code is contributed by mits",
"e": 6715,
"s": 6260,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG { // Function to return the nth Fibonacci numberstatic int fib(int n){ double phi = (1 + Math.Sqrt(5)) / 2; return (int) Math.Round(Math.Pow(phi, n) / Math.Sqrt(5));} // Function to return the required sumstatic int calculateSum(int l, int r){ // Using our deduced result int sum = fib(r + 2) - fib(l + 1); return sum;} // Driver codepublic static void Main() { int l = 4, r = 8; Console.WriteLine(calculateSum(l, r));}} // This code is contributed// by Akanksha Rai",
"e": 7298,
"s": 6715,
"text": null
},
{
"code": "<?php// PHP implementation of the approach // Function to return the nth Fibonacci numberfunction fib($n){ $phi = (1 + sqrt(5)) / 2; return (int) round(pow($phi, $n) / sqrt(5));} // Function to return the required sumfunction calculateSum($l, $r){ // Using our deduced result $sum = fib($r + 2) - fib($l + 1); return $sum;} // Driver code$l = 4; $r = 8;echo(calculateSum($l, $r)); // This code is contributed by Code_Mech?>",
"e": 7743,
"s": 7298,
"text": null
},
{
"code": "<script>// javascript implementation of the approach // Function to return the nth Fibonacci number function fib(n) { var phi = (1 + Math.sqrt(5)) / 2; return parseInt( Math.round(Math.pow(phi, n) / Math.sqrt(5))); } // Function to return the required sum function calculateSum(l , r) { // Using our deduced result var sum = fib(r + 2) - fib(l + 1); return sum; } // Driver code var l = 4, r = 8; document.write(calculateSum(l, r)); // This code contributed by aashish1995</script>",
"e": 8310,
"s": 7743,
"text": null
},
{
"code": null,
"e": 8313,
"s": 8310,
"text": "50"
},
{
"code": null,
"e": 8362,
"s": 8315,
"text": "Time Complexity: O(log r)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 8375,
"s": 8362,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 8385,
"s": 8375,
"text": "Code_Mech"
},
{
"code": null,
"e": 8399,
"s": 8385,
"text": "princiraj1992"
},
{
"code": null,
"e": 8411,
"s": 8399,
"text": "29AjayKumar"
},
{
"code": null,
"e": 8424,
"s": 8411,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 8434,
"s": 8424,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 8448,
"s": 8434,
"text": "GauravRajput1"
},
{
"code": null,
"e": 8460,
"s": 8448,
"text": "aashish1995"
},
{
"code": null,
"e": 8476,
"s": 8460,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 8492,
"s": 8476,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 8502,
"s": 8492,
"text": "Fibonacci"
},
{
"code": null,
"e": 8513,
"s": 8502,
"text": "Algorithms"
},
{
"code": null,
"e": 8537,
"s": 8513,
"text": "Competitive Programming"
},
{
"code": null,
"e": 8550,
"s": 8537,
"text": "Mathematical"
},
{
"code": null,
"e": 8563,
"s": 8550,
"text": "Mathematical"
},
{
"code": null,
"e": 8573,
"s": 8563,
"text": "Fibonacci"
},
{
"code": null,
"e": 8584,
"s": 8573,
"text": "Algorithms"
}
] |
Thread Safety and how to achieve it in Java
|
24 Jun, 2021
As we know Java has a feature, Multithreading, which is a process of running multiple threads simultaneously. When multiple threads are working on the same data, and the value of our data is changing, that scenario is not thread-safe and we will get inconsistent results. When a thread is already working on an object and preventing another thread on working on the same object, this process is called Thread-Safety.
There are four ways to achieve Thread Safety in Java. These are:
Using Synchronization.Using Volatile Keyword.Using Atomic Variable.Using Final Keyword.
Using Synchronization.
Using Volatile Keyword.
Using Atomic Variable.
Using Final Keyword.
Synchronization is the process of allowing only one thread at a time to complete the particular task. It means when multiple threads executing simultaneously, and want to access the same resource at the same time, then the problem of inconsistency will occur. so synchronization is used to resolve inconsistency problem by allowing only one thread at a time. Synchronization uses a synchronized keyword. Synchronized is the modifier that creates a block of code known as a critical section.
Java
class A { synchronized void sum(int n) { // Creating a thread instance Thread t = Thread.currentThread(); for (int i = 1; i <= 5; i++) { System.out.println( t.getName() + " : " + (n + i)); } }} // Class B extending thread classclass B extends Thread { // Creating an object of class A A a = new A(); public void run() { // Calling sum() method a.sum(10); }}class Test { public static void main(String[] args) { // Creating an object of class B B b = new B(); // Initializing instance t1 of Thread // class with object of class B Thread t1 = new Thread(b); // Initializing instance t2 of Thread // class with object of class B Thread t2 = new Thread(b); // Initializing thread t1 with name //'Thread A' t1.setName("Thread A"); // Initializing thread t2 with name //'Thread B' t2.setName("Thread B"); // Starting thread instance t1 and t2 t1.start(); t2.start(); }}
Thread A : 11
Thread A : 12
Thread A : 13
Thread A : 14
Thread A : 15
Thread B : 11
Thread B : 12
Thread B : 13
Thread B : 14
Thread B : 15
A volatile keyword is a field modifier that ensures that the object can be used by multiple threads at the same time without having any problem. volatile is one good way of ensuring that the Java program is thread-safe. a volatile keyword can be used as an alternative way of achieving Thread Safety in Java.
Java
public class VolatileExample { // Initializing volatile variables // a, b static volatile int a = 0, b = 0; // Defining a static void method static void method_one() { a++; b++; } // Defining static void method static void method_two() { System.out.println( "a=" + a + " b=" + b); } public static void main(String[] args) { // Creating an instance t1 of // Thread class Thread t1 = new Thread() { public void run() { for (int i = 0; i < 5; i++) method_one(); } }; // Creating an instance t2 of // Thread class Thread t2 = new Thread() { public void run() { for (int i = 0; i < 5; i++) method_two(); } }; // Starting instance t1 and t2 t1.start(); t2.start(); }}
a=5 b=5
a=5 b=5
a=5 b=5
a=5 b=5
a=5 b=5
Using an atomic variable is another way to achieve thread-safety in java. When variables are shared by multiple threads, the atomic variable ensures that threads don’t crash into each other.
Java
import java.util.concurrent.atomic.AtomicInteger; class Counter { // Creating a variable of // class type AtomicInteger AtomicInteger count = new AtomicInteger(); // Defining increment() method // to change value of // AtomicInteger variable public void increment() { count.incrementAndGet(); }} public class TestCounter { public static void main( String[] args) throws Exception { // Creating an instance of // Counter class Counter c = new Counter(); // Creating an instance t1 of // Thread class Thread t1 = new Thread( new Runnable() { public void run() { for (int i = 1; i <= 2000; i++) { c.increment(); } } }); // Creating an instance t2 // of Thread class Thread t2 = new Thread( new Runnable() { public void run() { for (int i = 1; i <= 2000; i++) { c.increment(); } } }); // Calling start() method with t1 and t2 t1.start(); t2.start(); // Calling join method with t1 and t2 t1.join(); t2.join(); System.out.println(c.count); }}
4000
Final Variables are also thread-safe in java because once assigned some reference of an object It cannot point to reference of another object.
Java
public class FinalTest { // Initializing a string // variable of final type final String str = new String("hello"); // Defining a method to // change the value of the final // variable which is not possible, // hence the error will be shown void method() { str = "world"; }}
Output:
Compilation Error in java code :-
prog.java:14: error: cannot assign a value to final variable str
str = "world";
^
1 error
simranarora5sos
Java-Multithreading
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Split() String method in Java with examples
Arrays.sort() in Java with examples
Reverse a string in Java
How to iterate any Map in Java
Stream In Java
Singleton Class in Java
Initialize an ArrayList in Java
Initializing a List in Java
Generics in Java
Java Programming Examples
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n24 Jun, 2021"
},
{
"code": null,
"e": 472,
"s": 54,
"text": "As we know Java has a feature, Multithreading, which is a process of running multiple threads simultaneously. When multiple threads are working on the same data, and the value of our data is changing, that scenario is not thread-safe and we will get inconsistent results. When a thread is already working on an object and preventing another thread on working on the same object, this process is called Thread-Safety. "
},
{
"code": null,
"e": 537,
"s": 472,
"text": "There are four ways to achieve Thread Safety in Java. These are:"
},
{
"code": null,
"e": 625,
"s": 537,
"text": "Using Synchronization.Using Volatile Keyword.Using Atomic Variable.Using Final Keyword."
},
{
"code": null,
"e": 648,
"s": 625,
"text": "Using Synchronization."
},
{
"code": null,
"e": 672,
"s": 648,
"text": "Using Volatile Keyword."
},
{
"code": null,
"e": 695,
"s": 672,
"text": "Using Atomic Variable."
},
{
"code": null,
"e": 716,
"s": 695,
"text": "Using Final Keyword."
},
{
"code": null,
"e": 1209,
"s": 716,
"text": "Synchronization is the process of allowing only one thread at a time to complete the particular task. It means when multiple threads executing simultaneously, and want to access the same resource at the same time, then the problem of inconsistency will occur. so synchronization is used to resolve inconsistency problem by allowing only one thread at a time. Synchronization uses a synchronized keyword. Synchronized is the modifier that creates a block of code known as a critical section. "
},
{
"code": null,
"e": 1214,
"s": 1209,
"text": "Java"
},
{
"code": "class A { synchronized void sum(int n) { // Creating a thread instance Thread t = Thread.currentThread(); for (int i = 1; i <= 5; i++) { System.out.println( t.getName() + \" : \" + (n + i)); } }} // Class B extending thread classclass B extends Thread { // Creating an object of class A A a = new A(); public void run() { // Calling sum() method a.sum(10); }}class Test { public static void main(String[] args) { // Creating an object of class B B b = new B(); // Initializing instance t1 of Thread // class with object of class B Thread t1 = new Thread(b); // Initializing instance t2 of Thread // class with object of class B Thread t2 = new Thread(b); // Initializing thread t1 with name //'Thread A' t1.setName(\"Thread A\"); // Initializing thread t2 with name //'Thread B' t2.setName(\"Thread B\"); // Starting thread instance t1 and t2 t1.start(); t2.start(); }}",
"e": 2307,
"s": 1214,
"text": null
},
{
"code": null,
"e": 2450,
"s": 2310,
"text": "Thread A : 11\nThread A : 12\nThread A : 13\nThread A : 14\nThread A : 15\nThread B : 11\nThread B : 12\nThread B : 13\nThread B : 14\nThread B : 15"
},
{
"code": null,
"e": 2766,
"s": 2456,
"text": "A volatile keyword is a field modifier that ensures that the object can be used by multiple threads at the same time without having any problem. volatile is one good way of ensuring that the Java program is thread-safe. a volatile keyword can be used as an alternative way of achieving Thread Safety in Java. "
},
{
"code": null,
"e": 2773,
"s": 2768,
"text": "Java"
},
{
"code": "public class VolatileExample { // Initializing volatile variables // a, b static volatile int a = 0, b = 0; // Defining a static void method static void method_one() { a++; b++; } // Defining static void method static void method_two() { System.out.println( \"a=\" + a + \" b=\" + b); } public static void main(String[] args) { // Creating an instance t1 of // Thread class Thread t1 = new Thread() { public void run() { for (int i = 0; i < 5; i++) method_one(); } }; // Creating an instance t2 of // Thread class Thread t2 = new Thread() { public void run() { for (int i = 0; i < 5; i++) method_two(); } }; // Starting instance t1 and t2 t1.start(); t2.start(); }}",
"e": 3727,
"s": 2773,
"text": null
},
{
"code": null,
"e": 3770,
"s": 3730,
"text": "a=5 b=5\na=5 b=5\na=5 b=5\na=5 b=5\na=5 b=5"
},
{
"code": null,
"e": 3969,
"s": 3776,
"text": "Using an atomic variable is another way to achieve thread-safety in java. When variables are shared by multiple threads, the atomic variable ensures that threads don’t crash into each other. "
},
{
"code": null,
"e": 3976,
"s": 3971,
"text": "Java"
},
{
"code": "import java.util.concurrent.atomic.AtomicInteger; class Counter { // Creating a variable of // class type AtomicInteger AtomicInteger count = new AtomicInteger(); // Defining increment() method // to change value of // AtomicInteger variable public void increment() { count.incrementAndGet(); }} public class TestCounter { public static void main( String[] args) throws Exception { // Creating an instance of // Counter class Counter c = new Counter(); // Creating an instance t1 of // Thread class Thread t1 = new Thread( new Runnable() { public void run() { for (int i = 1; i <= 2000; i++) { c.increment(); } } }); // Creating an instance t2 // of Thread class Thread t2 = new Thread( new Runnable() { public void run() { for (int i = 1; i <= 2000; i++) { c.increment(); } } }); // Calling start() method with t1 and t2 t1.start(); t2.start(); // Calling join method with t1 and t2 t1.join(); t2.join(); System.out.println(c.count); }}",
"e": 5347,
"s": 3976,
"text": null
},
{
"code": null,
"e": 5355,
"s": 5350,
"text": "4000"
},
{
"code": null,
"e": 5506,
"s": 5361,
"text": "Final Variables are also thread-safe in java because once assigned some reference of an object It cannot point to reference of another object. "
},
{
"code": null,
"e": 5513,
"s": 5508,
"text": "Java"
},
{
"code": "public class FinalTest { // Initializing a string // variable of final type final String str = new String(\"hello\"); // Defining a method to // change the value of the final // variable which is not possible, // hence the error will be shown void method() { str = \"world\"; }}",
"e": 5834,
"s": 5513,
"text": null
},
{
"code": null,
"e": 5842,
"s": 5834,
"text": "Output:"
},
{
"code": null,
"e": 5983,
"s": 5842,
"text": "Compilation Error in java code :- \nprog.java:14: error: cannot assign a value to final variable str\n str = \"world\";\n ^\n1 error"
},
{
"code": null,
"e": 5999,
"s": 5983,
"text": "simranarora5sos"
},
{
"code": null,
"e": 6019,
"s": 5999,
"text": "Java-Multithreading"
},
{
"code": null,
"e": 6024,
"s": 6019,
"text": "Java"
},
{
"code": null,
"e": 6029,
"s": 6024,
"text": "Java"
},
{
"code": null,
"e": 6127,
"s": 6029,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6171,
"s": 6127,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 6207,
"s": 6171,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 6232,
"s": 6207,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 6263,
"s": 6232,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 6278,
"s": 6263,
"text": "Stream In Java"
},
{
"code": null,
"e": 6302,
"s": 6278,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 6334,
"s": 6302,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 6362,
"s": 6334,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 6379,
"s": 6362,
"text": "Generics in Java"
}
] |
How to swap columns of a given NumPy array?
|
22 Jun, 2021
In this article, let’s discuss how to swap columns of a given NumPy array.
Approach :
Import NumPy module
Create a NumPy array
Swap the column with Index
Print the Final array
Example 1: Swapping the column of an array.
Python3
# importing Moduleimport numpy as np # creating array with shape(4,3)my_array = np.arange(12).reshape(4, 3)print("Original array:")print(my_array) # swapping the column with index of# original arraymy_array[:, [2, 0]] = my_array[:, [0, 2]]print("After swapping arrays the last column and first column:")print(my_array)
Output :
Original array:
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
After swapping arrays the last column and first column:
[[ 2 1 0]
[ 5 4 3]
[ 8 7 6]
[11 10 9]]
Example 2: Swapping the column of an array with the user chooses.
Python3
# Importing Moduleimport numpy as np # Creating arraymy_array = np.arange(12).reshape(4, 3)print("Original Array : ")print(my_array)# creating function for swap def Swap(arr, start_index, last_index): arr[:, [start_index, last_index]] = arr[:, [last_index, start_index]] # passing parameter into the functionSwap(my_array, 0, 1)print(" After Swapping :")print(my_array)
Output :
Original Array :
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
After Swapping :
[[ 1 0 2]
[ 4 3 5]
[ 7 6 8]
[10 9 11]]
simranarora5sos
Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Enumerate() in Python
Different ways to create Pandas Dataframe
Read a file line by line in Python
How to Install PIP on Windows ?
Python String | replace()
Python OOPs Concepts
Python Classes and Objects
*args and **kwargs in Python
Introduction To PYTHON
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Jun, 2021"
},
{
"code": null,
"e": 103,
"s": 28,
"text": "In this article, let’s discuss how to swap columns of a given NumPy array."
},
{
"code": null,
"e": 114,
"s": 103,
"text": "Approach :"
},
{
"code": null,
"e": 134,
"s": 114,
"text": "Import NumPy module"
},
{
"code": null,
"e": 155,
"s": 134,
"text": "Create a NumPy array"
},
{
"code": null,
"e": 182,
"s": 155,
"text": "Swap the column with Index"
},
{
"code": null,
"e": 204,
"s": 182,
"text": "Print the Final array"
},
{
"code": null,
"e": 249,
"s": 204,
"text": "Example 1: Swapping the column of an array. "
},
{
"code": null,
"e": 257,
"s": 249,
"text": "Python3"
},
{
"code": "# importing Moduleimport numpy as np # creating array with shape(4,3)my_array = np.arange(12).reshape(4, 3)print(\"Original array:\")print(my_array) # swapping the column with index of# original arraymy_array[:, [2, 0]] = my_array[:, [0, 2]]print(\"After swapping arrays the last column and first column:\")print(my_array)",
"e": 577,
"s": 257,
"text": null
},
{
"code": null,
"e": 590,
"s": 581,
"text": "Output :"
},
{
"code": null,
"e": 762,
"s": 592,
"text": "Original array:\n[[ 0 1 2]\n [ 3 4 5]\n [ 6 7 8]\n [ 9 10 11]]\nAfter swapping arrays the last column and first column:\n[[ 2 1 0]\n [ 5 4 3]\n [ 8 7 6]\n [11 10 9]]"
},
{
"code": null,
"e": 830,
"s": 764,
"text": "Example 2: Swapping the column of an array with the user chooses."
},
{
"code": null,
"e": 840,
"s": 832,
"text": "Python3"
},
{
"code": "# Importing Moduleimport numpy as np # Creating arraymy_array = np.arange(12).reshape(4, 3)print(\"Original Array : \")print(my_array)# creating function for swap def Swap(arr, start_index, last_index): arr[:, [start_index, last_index]] = arr[:, [last_index, start_index]] # passing parameter into the functionSwap(my_array, 0, 1)print(\" After Swapping :\")print(my_array)",
"e": 1214,
"s": 840,
"text": null
},
{
"code": null,
"e": 1223,
"s": 1214,
"text": "Output :"
},
{
"code": null,
"e": 1357,
"s": 1223,
"text": "Original Array : \n[[ 0 1 2]\n [ 3 4 5]\n [ 6 7 8]\n [ 9 10 11]]\n After Swapping :\n[[ 1 0 2]\n [ 4 3 5]\n [ 7 6 8]\n [10 9 11]]"
},
{
"code": null,
"e": 1373,
"s": 1357,
"text": "simranarora5sos"
},
{
"code": null,
"e": 1404,
"s": 1373,
"text": "Python numpy-arrayManipulation"
},
{
"code": null,
"e": 1417,
"s": 1404,
"text": "Python-numpy"
},
{
"code": null,
"e": 1424,
"s": 1417,
"text": "Python"
},
{
"code": null,
"e": 1522,
"s": 1424,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1540,
"s": 1522,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1562,
"s": 1540,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1604,
"s": 1562,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1639,
"s": 1604,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1671,
"s": 1639,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1697,
"s": 1671,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1718,
"s": 1697,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1745,
"s": 1718,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1774,
"s": 1745,
"text": "*args and **kwargs in Python"
}
] |
HTML | <Iframe> frameborder Attribute
|
19 Sep, 2019
The HTML Iframe frameborder Attribute is used to specify whether or not to display the border around the content of an <Iframe> Element.
Syntax:
<iframe frameborder="1 | 0">
Attribute Values:
0: It has a Default value. It sets the border on one state.
1: It sets the border on-off state.
Note: This attribute does not support in HTML5 as a replacement you can use CSS.
Below program will illustrate HTML Iframe frameborder Attribute:Example:
<!DOCTYPE html><html> <head> <title> HTML <Iframe> frameborder Attribute </title></head> <body> <center> <h1 style="color:green;"> GeeksforGeeks </h1> <h2> HTML Iframe frameborder Attribute </h2> <p>Content goes here</p> <iframe src="https://ide.geeksforgeeks.org/tryit.php" height="300" width="400" marginheight="40" frameborder="0"> </iframe> </center> </body> </html>
Output:
Supported Browsers: The browsers supported by HTML <Iframe> frameborder Attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
nidhi_biet
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Sep, 2019"
},
{
"code": null,
"e": 165,
"s": 28,
"text": "The HTML Iframe frameborder Attribute is used to specify whether or not to display the border around the content of an <Iframe> Element."
},
{
"code": null,
"e": 173,
"s": 165,
"text": "Syntax:"
},
{
"code": null,
"e": 202,
"s": 173,
"text": "<iframe frameborder=\"1 | 0\">"
},
{
"code": null,
"e": 220,
"s": 202,
"text": "Attribute Values:"
},
{
"code": null,
"e": 280,
"s": 220,
"text": "0: It has a Default value. It sets the border on one state."
},
{
"code": null,
"e": 316,
"s": 280,
"text": "1: It sets the border on-off state."
},
{
"code": null,
"e": 397,
"s": 316,
"text": "Note: This attribute does not support in HTML5 as a replacement you can use CSS."
},
{
"code": null,
"e": 470,
"s": 397,
"text": "Below program will illustrate HTML Iframe frameborder Attribute:Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> HTML <Iframe> frameborder Attribute </title></head> <body> <center> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h2> HTML Iframe frameborder Attribute </h2> <p>Content goes here</p> <iframe src=\"https://ide.geeksforgeeks.org/tryit.php\" height=\"300\" width=\"400\" marginheight=\"40\" frameborder=\"0\"> </iframe> </center> </body> </html>",
"e": 946,
"s": 470,
"text": null
},
{
"code": null,
"e": 954,
"s": 946,
"text": "Output:"
},
{
"code": null,
"e": 1054,
"s": 954,
"text": "Supported Browsers: The browsers supported by HTML <Iframe> frameborder Attribute are listed below:"
},
{
"code": null,
"e": 1068,
"s": 1054,
"text": "Google Chrome"
},
{
"code": null,
"e": 1086,
"s": 1068,
"text": "Internet Explorer"
},
{
"code": null,
"e": 1094,
"s": 1086,
"text": "Firefox"
},
{
"code": null,
"e": 1100,
"s": 1094,
"text": "Opera"
},
{
"code": null,
"e": 1107,
"s": 1100,
"text": "Safari"
},
{
"code": null,
"e": 1118,
"s": 1107,
"text": "nidhi_biet"
},
{
"code": null,
"e": 1134,
"s": 1118,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 1139,
"s": 1134,
"text": "HTML"
},
{
"code": null,
"e": 1156,
"s": 1139,
"text": "Web Technologies"
},
{
"code": null,
"e": 1161,
"s": 1156,
"text": "HTML"
}
] |
A Programmer’s approach of looking at Array vs. Linked List
|
22 Jun, 2022
In general, the array is considered a data structure for which size is fixed at the compile time, and array memory is allocated either from the Data section (e.g. global array) or Stack section (e.g. local array). Similarly, a linked list is considered a data structure for which size is not fixed and memory is allocated from the Heap section (e.g. using malloc(), etc.) as and when needed. In this sense, the array is taken as a static data structure (residing in Data or Stack section) while the linked list is taken as a dynamic data structure (residing in the Heap section). Memory representation of the array and the linked list can be visualized as follows:
An array of 4 elements (integer type) have been initialized with 1, 2, 3, and 4. Suppose, these elements are allocated at memory addresses 0x100, 0x104, 0x108 and 0x10C respectively.
[(1)] [(2)] [(3)] [(4)]
0x100 0x104 0x108 0x10C
A linked list with 4 nodes where each node has an integer as data and these data are initialized with 1, 2, 3, and 4. Suppose, these nodes are allocated via malloc() and memory allocated for them is 0x200, 0x308, 0x404 and 0x20B respectively.
[(1), 0x308] [(2),0x404] [(3),0x20B] [(4),NULL]
0x200 0x308 0x404 0x20B
Anyone with even little understanding of array and linked-list might not be interested in the above explanation. I mean, it is well known that the array elements are allocated memory in sequence i.e. contiguous memory while nodes of a linked list are non-contiguous in memory. Though it sounds trivial yet this is the most important difference between an array and a linked list. It should be noted that due to this contiguous versus non-contiguous memory, array and linked list are different. This difference is what makes array vs. linked list! In the following sections, we will try to explore this very idea further.
Since elements of an array are contiguous in memory, we can access any element randomly using an index e.g. intArr[3] will directly access the fourth element of the array. (For newbies, array indexing starts from 0 and that’s why the fourth element is indexed with 3). Also, due to contiguous memory for successive elements in the array, no extra information is needed to be stored in individual elements i.e. no overhead of metadata in arrays. Contrary to this, linked list nodes are non-contiguous in memory. It means that we need some mechanism to traverse or access linked list nodes. To achieve this, each node stores the location of the next node and this forms the basis of the link from one node to the next node. Therefore, it’s called a Linked list. Though storing the location of the next node is overhead in the linked list but it’s required. Typically, we see the linked list node declaration as follows:
C
struct llNode{ int dataInt; /* nextNode is the pointer to next node in linked list*/ struct llNode * nextNode; };
So array elements are contiguous in memory and therefore do not require any metadata. And linked list nodes are non-contiguous in memory thereby requiring metadata in the form of the location of the next node. Apart from this difference, we can see that the array could have several unused elements because memory has already been allocated. But the linked list will have only the required no. of data items. All the above information about the array and the linked list has been mentioned in several textbooks though in different ways.
What if we need to allocate array memory from the Heap section (i.e. at run time) and linked list memory from Data/Stack section. First of all, is it possible? Before that, one might ask why would someone need to do this? Now, I hope that the remaining article would make you rethink the idea of array vs. linked-list
Now consider the case when we need to store certain data in an array (because the array has the property of random access due to contiguous memory) but we don’t know the total size apriori. One possibility is to allocate memory of this array from Heap at run time. For example, as follows:
/*At run-time, suppose we know the required size for an integer array (e.g. input size from the user). Say, the array size is stored in the variable arrSize. Allocate this array from Heap as follows*/
C
int * dynArr = (int *)malloc(sizeof(int)*arrSize);
Though the memory of this array is allocated from Heap, the elements can still be accessed via the index mechanism e.g. dynArr[i]. Based on the programming problem, we have combined one benefit of the array (i.e. random access of elements) and one benefit of the linked list (i.e. delaying the memory allocation till run time and allocating memory from Heap). Another advantage of having this type of dynamic array is that this method of allocating array from Heap at run time could reduce code size (of course, it depends on certain other factors e.g. program format, etc.)
Now consider the case when we need to store data in a linked list (because no. of nodes in a linked list would be equal to actual data items stored i.e. no extra space like an array) but we aren’t allowed to get this memory from Heap again and again for each node. This might look hypothetical situation to some folks but it’s not a very uncommon requirement in embedded systems. Basically, in several embedded programs, allocating memory via malloc(), etc. isn’t allowed due to multiple reasons. One obvious reason is performance i.e. allocating memory via malloc() is costly in terms of time complexity because your embedded program is required to be deterministic most of the time. Another reason could be module-specific memory management i.e. each module in the embedded system may manage its memory. In short, if we need to perform our memory management, instead of relying on the system-provided APIs of malloc() and free(), we might choose the linked list which is simulated using an array. I hope that you got some idea of why we might need to simulate the linked list using an array. Now, let us first see how this can be done. Suppose, the type of a node in the linked list (i.e. the underlying array) is declared as follows:
C
struct sllNode{ int dataInt; /*Here, note that nextIndex stores the location of next node in linked list*/ int nextIndex;}; struct sllNode arrayLL[5];
If we initialize this linked list (which is actually an array), it would look as follows in memory:
[(0),-1] [(0),-1] [(0),-1] [(0),-1] [(0),-1]
0x500 0x508 0x510 0x518 0x520
The important thing to notice is that all the nodes of the linked list are contiguous in memory (each one occupying 8 bytes) and the next index of each node is set to -1. This (i.e. -1) is done to denote that each node of the linked list is empty as of now. This linked list is denoted by head index 0.
Now, if this linked list is updated with four elements of data parts 4, 3, 2, and 1 successively, it would look as follows in memory. This linked list can be viewed as 0x500 -> 0x508 -> 0x510 -> 0x518.
[(1),1] [(2),2] [(3),3] [(4),-2] [(0),-1]
0x500 0x508 0x510 0x518 0x520
The important thing to notice is next index of the last node (i.e. fourth node) is set to -2. This (i.e. -2) is done to denote the end of the linked list. Also, the head node of the linked list is index 0. This concept of simulating linked lists using an array would look more interesting if we delete say the second node from the above-linked list. In that case, the linked list will look as follows in memory:
[(1),2] [(0),-1] [(3),3] [(4),-2] [(0),-1]
0x500 0x508 0x510 0x518 0x520
The resultant linked list is 0x500 -> 0x510 -> 0x518. Here, it should be noted that even though we have deleted the second node from our linked list, the memory for this node is still there because the underlying array is still there. But the next index of the first node now points to the third node (for which index is 2).
Hopefully, the above examples would have given some idea that for the simulated linked list, we need to write our API similar to malloc() and free() which would be used to insert and delete a node. Now, this is what’s called own memory management. Let us see how this can be done algorithmically.
There are multiple ways to do so. If we take the simplistic approach of creating a linked list using an array, we can use the following logic. For inserting a node, traverse the underlying array and find a node whose next index is -1. It means that this node is empty. Use this node as a new node. Update the data part in this new node and set the next index of this node to the current head node (i.e. head index) of the linked list. Finally, make the index of this new node as the head index of the linked list. To visualize it, let us take an example. Suppose the linked list is as follows where head Index is 0 i.e. linked list is 0x500 -> 0x508 -> 0x518 -> 0x520
[(1),1] [(2),3] [(0),-1] [(4),4] [(5),-2]
0x500 0x508 0x510 0x518 0x520
After inserting a new node with data 8, the linked list would look as follows with head index as 2.
[(1),1] [(2),3] [(8),0] [(4),4] [(5),-2]
0x500 0x508 0x510 0x518 0x520
So the linked list nodes would be at addresses 0x510 -> 0x500 -> 0x508 -> 0x518 -> 0x520
For deleting a node, we need to set the next index of the node as -1 so that the node is marked as the empty node. But, before doing so, we need to make sure that the next index of the previous node is updated correctly to the index of the next node of this node to be deleted. We can see that we have done our memory management for creating a linked list out of the array memory. But, this is one way of inserting and deleting nodes in this linked list. It can be easily noticed that finding an empty node is not so efficient in terms of time complexity. We’re searching the complete array linearly to find an empty node.
Let us see if we can optimize it further. We can maintain a linked list of empty nodes as well in the same array. In that case, the linked list would be denoted by two indexes – one index would be for the linked list which has the actual data values i.e. nodes that have been inserted so far, and the other indexes for a linked list of empty nodes. By doing so, whenever, we need to insert a new node in the existing linked list, we can quickly find an empty node. Let us take an example:
[(4),2] [(0),3] [(5),5] [(0),-1] [(0),1] [(9),-1]
0x500 0x508 0x510 0x518 0x520 0x528
The above-linked list which is represented using two indexes (0 and 5) has two linked lists: one for actual values and another for empty nodes. The linked list with actual values has nodes at address 0x500 -> 0x510 -> 0x528 while the linked list with empty nodes has nodes at addresses 0x520 -> 0x508 -> 0x518. It can be seen that finding an empty node (i.e. writing our API similar to malloc()) should be relatively faster now because we can quickly find a free node. In real-world embedded programs, a fixed chunk of memory (normally called memory pool) is allocated using malloc() only once by a module. And then the management of this memory pool (which is an array) is done by that module itself using the techniques mentioned earlier. Sometimes, there are multiple memory pools each one having different sizes of a node. Of course, there are several other aspects of our memory management but we’ll leave them here. But it’s worth mentioning that there are several methods by which the insertion (which requires our memory allocation) and deletion (which requires our memory freeing) can be improved further.
If we look carefully, it can be noticed that the Heap section of memory is a big array of bytes that is being managed by the underlying operating system (OS). And OS is providing this memory management service to programmers via malloc(), free(), etc. Aha !!
The important takeaways from this article can be summed as follows:
A) Array means contiguous memory. It can exist in any memory section be it Data or Stack or Heap. B) Linked List means non-contiguous linked memory. It can exist in any memory section be it Heap or Data or Stack. C) As a programmer, looking at a data structure from a memory perspective could provide us with better insight into choosing a particular data structure or even designing a new data structure. For example, we might create an array of linked lists, etc.
Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above
sahil_tah
niharikatanwar61
shreyasnaphad
Linked List
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n22 Jun, 2022"
},
{
"code": null,
"e": 719,
"s": 54,
"text": "In general, the array is considered a data structure for which size is fixed at the compile time, and array memory is allocated either from the Data section (e.g. global array) or Stack section (e.g. local array). Similarly, a linked list is considered a data structure for which size is not fixed and memory is allocated from the Heap section (e.g. using malloc(), etc.) as and when needed. In this sense, the array is taken as a static data structure (residing in Data or Stack section) while the linked list is taken as a dynamic data structure (residing in the Heap section). Memory representation of the array and the linked list can be visualized as follows:"
},
{
"code": null,
"e": 903,
"s": 719,
"text": "An array of 4 elements (integer type) have been initialized with 1, 2, 3, and 4. Suppose, these elements are allocated at memory addresses 0x100, 0x104, 0x108 and 0x10C respectively. "
},
{
"code": null,
"e": 983,
"s": 903,
"text": "[(1)] [(2)] [(3)] [(4)]\n0x100 0x104 0x108 0x10C"
},
{
"code": null,
"e": 1227,
"s": 983,
"text": "A linked list with 4 nodes where each node has an integer as data and these data are initialized with 1, 2, 3, and 4. Suppose, these nodes are allocated via malloc() and memory allocated for them is 0x200, 0x308, 0x404 and 0x20B respectively. "
},
{
"code": null,
"e": 1355,
"s": 1227,
"text": "[(1), 0x308] [(2),0x404] [(3),0x20B] [(4),NULL] \n 0x200 0x308 0x404 0x20B "
},
{
"code": null,
"e": 1976,
"s": 1355,
"text": "Anyone with even little understanding of array and linked-list might not be interested in the above explanation. I mean, it is well known that the array elements are allocated memory in sequence i.e. contiguous memory while nodes of a linked list are non-contiguous in memory. Though it sounds trivial yet this is the most important difference between an array and a linked list. It should be noted that due to this contiguous versus non-contiguous memory, array and linked list are different. This difference is what makes array vs. linked list! In the following sections, we will try to explore this very idea further."
},
{
"code": null,
"e": 2894,
"s": 1976,
"text": "Since elements of an array are contiguous in memory, we can access any element randomly using an index e.g. intArr[3] will directly access the fourth element of the array. (For newbies, array indexing starts from 0 and that’s why the fourth element is indexed with 3). Also, due to contiguous memory for successive elements in the array, no extra information is needed to be stored in individual elements i.e. no overhead of metadata in arrays. Contrary to this, linked list nodes are non-contiguous in memory. It means that we need some mechanism to traverse or access linked list nodes. To achieve this, each node stores the location of the next node and this forms the basis of the link from one node to the next node. Therefore, it’s called a Linked list. Though storing the location of the next node is overhead in the linked list but it’s required. Typically, we see the linked list node declaration as follows:"
},
{
"code": null,
"e": 2896,
"s": 2894,
"text": "C"
},
{
"code": "struct llNode{ int dataInt; /* nextNode is the pointer to next node in linked list*/ struct llNode * nextNode; };",
"e": 3016,
"s": 2896,
"text": null
},
{
"code": null,
"e": 3553,
"s": 3016,
"text": "So array elements are contiguous in memory and therefore do not require any metadata. And linked list nodes are non-contiguous in memory thereby requiring metadata in the form of the location of the next node. Apart from this difference, we can see that the array could have several unused elements because memory has already been allocated. But the linked list will have only the required no. of data items. All the above information about the array and the linked list has been mentioned in several textbooks though in different ways."
},
{
"code": null,
"e": 3872,
"s": 3553,
"text": "What if we need to allocate array memory from the Heap section (i.e. at run time) and linked list memory from Data/Stack section. First of all, is it possible? Before that, one might ask why would someone need to do this? Now, I hope that the remaining article would make you rethink the idea of array vs. linked-list "
},
{
"code": null,
"e": 4162,
"s": 3872,
"text": "Now consider the case when we need to store certain data in an array (because the array has the property of random access due to contiguous memory) but we don’t know the total size apriori. One possibility is to allocate memory of this array from Heap at run time. For example, as follows:"
},
{
"code": null,
"e": 4365,
"s": 4162,
"text": "/*At run-time, suppose we know the required size for an integer array (e.g. input size from the user). Say, the array size is stored in the variable arrSize. Allocate this array from Heap as follows*/ "
},
{
"code": null,
"e": 4367,
"s": 4365,
"text": "C"
},
{
"code": "int * dynArr = (int *)malloc(sizeof(int)*arrSize);",
"e": 4418,
"s": 4367,
"text": null
},
{
"code": null,
"e": 4993,
"s": 4418,
"text": "Though the memory of this array is allocated from Heap, the elements can still be accessed via the index mechanism e.g. dynArr[i]. Based on the programming problem, we have combined one benefit of the array (i.e. random access of elements) and one benefit of the linked list (i.e. delaying the memory allocation till run time and allocating memory from Heap). Another advantage of having this type of dynamic array is that this method of allocating array from Heap at run time could reduce code size (of course, it depends on certain other factors e.g. program format, etc.)"
},
{
"code": null,
"e": 6230,
"s": 4993,
"text": "Now consider the case when we need to store data in a linked list (because no. of nodes in a linked list would be equal to actual data items stored i.e. no extra space like an array) but we aren’t allowed to get this memory from Heap again and again for each node. This might look hypothetical situation to some folks but it’s not a very uncommon requirement in embedded systems. Basically, in several embedded programs, allocating memory via malloc(), etc. isn’t allowed due to multiple reasons. One obvious reason is performance i.e. allocating memory via malloc() is costly in terms of time complexity because your embedded program is required to be deterministic most of the time. Another reason could be module-specific memory management i.e. each module in the embedded system may manage its memory. In short, if we need to perform our memory management, instead of relying on the system-provided APIs of malloc() and free(), we might choose the linked list which is simulated using an array. I hope that you got some idea of why we might need to simulate the linked list using an array. Now, let us first see how this can be done. Suppose, the type of a node in the linked list (i.e. the underlying array) is declared as follows:"
},
{
"code": null,
"e": 6232,
"s": 6230,
"text": "C"
},
{
"code": "struct sllNode{ int dataInt; /*Here, note that nextIndex stores the location of next node in linked list*/ int nextIndex;}; struct sllNode arrayLL[5];",
"e": 6387,
"s": 6232,
"text": null
},
{
"code": null,
"e": 6487,
"s": 6387,
"text": "If we initialize this linked list (which is actually an array), it would look as follows in memory:"
},
{
"code": null,
"e": 6595,
"s": 6487,
"text": "[(0),-1] [(0),-1] [(0),-1] [(0),-1] [(0),-1]\n0x500 0x508 0x510 0x518 0x520"
},
{
"code": null,
"e": 6898,
"s": 6595,
"text": "The important thing to notice is that all the nodes of the linked list are contiguous in memory (each one occupying 8 bytes) and the next index of each node is set to -1. This (i.e. -1) is done to denote that each node of the linked list is empty as of now. This linked list is denoted by head index 0."
},
{
"code": null,
"e": 7101,
"s": 6898,
"text": "Now, if this linked list is updated with four elements of data parts 4, 3, 2, and 1 successively, it would look as follows in memory. This linked list can be viewed as 0x500 -> 0x508 -> 0x510 -> 0x518. "
},
{
"code": null,
"e": 7221,
"s": 7101,
"text": "[(1),1] [(2),2] [(3),3] [(4),-2] [(0),-1]\n 0x500 0x508 0x510 0x518 0x520"
},
{
"code": null,
"e": 7634,
"s": 7221,
"text": "The important thing to notice is next index of the last node (i.e. fourth node) is set to -2. This (i.e. -2) is done to denote the end of the linked list. Also, the head node of the linked list is index 0. This concept of simulating linked lists using an array would look more interesting if we delete say the second node from the above-linked list. In that case, the linked list will look as follows in memory: "
},
{
"code": null,
"e": 7756,
"s": 7634,
"text": "[(1),2] [(0),-1] [(3),3] [(4),-2] [(0),-1]\n 0x500 0x508 0x510 0x518 0x520"
},
{
"code": null,
"e": 8081,
"s": 7756,
"text": "The resultant linked list is 0x500 -> 0x510 -> 0x518. Here, it should be noted that even though we have deleted the second node from our linked list, the memory for this node is still there because the underlying array is still there. But the next index of the first node now points to the third node (for which index is 2)."
},
{
"code": null,
"e": 8378,
"s": 8081,
"text": "Hopefully, the above examples would have given some idea that for the simulated linked list, we need to write our API similar to malloc() and free() which would be used to insert and delete a node. Now, this is what’s called own memory management. Let us see how this can be done algorithmically."
},
{
"code": null,
"e": 9047,
"s": 8378,
"text": "There are multiple ways to do so. If we take the simplistic approach of creating a linked list using an array, we can use the following logic. For inserting a node, traverse the underlying array and find a node whose next index is -1. It means that this node is empty. Use this node as a new node. Update the data part in this new node and set the next index of this node to the current head node (i.e. head index) of the linked list. Finally, make the index of this new node as the head index of the linked list. To visualize it, let us take an example. Suppose the linked list is as follows where head Index is 0 i.e. linked list is 0x500 -> 0x508 -> 0x518 -> 0x520 "
},
{
"code": null,
"e": 9167,
"s": 9047,
"text": "[(1),1] [(2),3] [(0),-1] [(4),4] [(5),-2]\n 0x500 0x508 0x510 0x518 0x520"
},
{
"code": null,
"e": 9267,
"s": 9167,
"text": "After inserting a new node with data 8, the linked list would look as follows with head index as 2."
},
{
"code": null,
"e": 9385,
"s": 9267,
"text": "[(1),1] [(2),3] [(8),0] [(4),4] [(5),-2]\n 0x500 0x508 0x510 0x518 0x520"
},
{
"code": null,
"e": 9474,
"s": 9385,
"text": "So the linked list nodes would be at addresses 0x510 -> 0x500 -> 0x508 -> 0x518 -> 0x520"
},
{
"code": null,
"e": 10097,
"s": 9474,
"text": "For deleting a node, we need to set the next index of the node as -1 so that the node is marked as the empty node. But, before doing so, we need to make sure that the next index of the previous node is updated correctly to the index of the next node of this node to be deleted. We can see that we have done our memory management for creating a linked list out of the array memory. But, this is one way of inserting and deleting nodes in this linked list. It can be easily noticed that finding an empty node is not so efficient in terms of time complexity. We’re searching the complete array linearly to find an empty node."
},
{
"code": null,
"e": 10586,
"s": 10097,
"text": "Let us see if we can optimize it further. We can maintain a linked list of empty nodes as well in the same array. In that case, the linked list would be denoted by two indexes – one index would be for the linked list which has the actual data values i.e. nodes that have been inserted so far, and the other indexes for a linked list of empty nodes. By doing so, whenever, we need to insert a new node in the existing linked list, we can quickly find an empty node. Let us take an example:"
},
{
"code": null,
"e": 10711,
"s": 10586,
"text": "[(4),2] [(0),3] [(5),5] [(0),-1] [(0),1] [(9),-1]\n 0x500 0x508 0x510 0x518 0x520 0x528"
},
{
"code": null,
"e": 11827,
"s": 10711,
"text": "The above-linked list which is represented using two indexes (0 and 5) has two linked lists: one for actual values and another for empty nodes. The linked list with actual values has nodes at address 0x500 -> 0x510 -> 0x528 while the linked list with empty nodes has nodes at addresses 0x520 -> 0x508 -> 0x518. It can be seen that finding an empty node (i.e. writing our API similar to malloc()) should be relatively faster now because we can quickly find a free node. In real-world embedded programs, a fixed chunk of memory (normally called memory pool) is allocated using malloc() only once by a module. And then the management of this memory pool (which is an array) is done by that module itself using the techniques mentioned earlier. Sometimes, there are multiple memory pools each one having different sizes of a node. Of course, there are several other aspects of our memory management but we’ll leave them here. But it’s worth mentioning that there are several methods by which the insertion (which requires our memory allocation) and deletion (which requires our memory freeing) can be improved further. "
},
{
"code": null,
"e": 12086,
"s": 11827,
"text": "If we look carefully, it can be noticed that the Heap section of memory is a big array of bytes that is being managed by the underlying operating system (OS). And OS is providing this memory management service to programmers via malloc(), free(), etc. Aha !!"
},
{
"code": null,
"e": 12154,
"s": 12086,
"text": "The important takeaways from this article can be summed as follows:"
},
{
"code": null,
"e": 12620,
"s": 12154,
"text": "A) Array means contiguous memory. It can exist in any memory section be it Data or Stack or Heap. B) Linked List means non-contiguous linked memory. It can exist in any memory section be it Heap or Data or Stack. C) As a programmer, looking at a data structure from a memory perspective could provide us with better insight into choosing a particular data structure or even designing a new data structure. For example, we might create an array of linked lists, etc."
},
{
"code": null,
"e": 12748,
"s": 12620,
"text": "Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 12758,
"s": 12748,
"text": "sahil_tah"
},
{
"code": null,
"e": 12775,
"s": 12758,
"text": "niharikatanwar61"
},
{
"code": null,
"e": 12789,
"s": 12775,
"text": "shreyasnaphad"
},
{
"code": null,
"e": 12801,
"s": 12789,
"text": "Linked List"
},
{
"code": null,
"e": 12813,
"s": 12801,
"text": "Linked List"
}
] |
MongoDB - Aggregation
|
Aggregations operations process data records and return computed results. Aggregation operations group values from multiple documents together, and can perform a variety of operations on the grouped data to return a single result. In SQL count(*) and with group by is an equivalent of MongoDB aggregation.
For the aggregation in MongoDB, you should use aggregate() method.
Basic syntax of aggregate() method is as follows −
>db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)
In the collection you have the following data −
{
_id: ObjectId(7df78ad8902c)
title: 'MongoDB Overview',
description: 'MongoDB is no sql database',
by_user: 'tutorials point',
url: 'http://www.tutorialspoint.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 100
},
{
_id: ObjectId(7df78ad8902d)
title: 'NoSQL Overview',
description: 'No sql database is very fast',
by_user: 'tutorials point',
url: 'http://www.tutorialspoint.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 10
},
{
_id: ObjectId(7df78ad8902e)
title: 'Neo4j Overview',
description: 'Neo4j is no sql database',
by_user: 'Neo4j',
url: 'http://www.neo4j.com',
tags: ['neo4j', 'database', 'NoSQL'],
likes: 750
},
Now from the above collection, if you want to display a list stating how many tutorials are written by each user, then you will use the following aggregate() method −
> db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$sum : 1}}}])
{ "_id" : "tutorials point", "num_tutorial" : 2 }
{ "_id" : "Neo4j", "num_tutorial" : 1 }
>
Sql equivalent query for the above use case will be select by_user, count(*) from mycol group by by_user.
In the above example, we have grouped documents by field by_user and on each occurrence of by user previous value of sum is incremented. Following is a list of available aggregation expressions.
In UNIX command, shell pipeline means the possibility to execute an operation on some input and use the output as the input for the next command and so on. MongoDB also supports same concept in aggregation framework. There is a set of possible stages and each of those is taken as a set of documents as an input and produces a resulting set of documents (or the final resulting JSON document at the end of the pipeline). This can then in turn be used for the next stage and so on.
Following are the possible stages in aggregation framework −
$project − Used to select some specific fields from a collection.
$project − Used to select some specific fields from a collection.
$match − This is a filtering operation and thus this can reduce the amount of documents that are given as input to the next stage.
$match − This is a filtering operation and thus this can reduce the amount of documents that are given as input to the next stage.
$group − This does the actual aggregation as discussed above.
$group − This does the actual aggregation as discussed above.
$sort − Sorts the documents.
$sort − Sorts the documents.
$skip − With this, it is possible to skip forward in the list of documents for a given amount of documents.
$skip − With this, it is possible to skip forward in the list of documents for a given amount of documents.
$limit − This limits the amount of documents to look at, by the given number starting from the current positions.
$limit − This limits the amount of documents to look at, by the given number starting from the current positions.
$unwind − This is used to unwind document that are using arrays. When using an array, the data is kind of pre-joined and this operation will be undone with this to have individual documents again. Thus with this stage we will increase the amount of documents for the next stage.
$unwind − This is used to unwind document that are using arrays. When using an array, the data is kind of pre-joined and this operation will be undone with this to have individual documents again. Thus with this stage we will increase the amount of documents for the next stage.
|
[
{
"code": null,
"e": 2993,
"s": 2687,
"text": "Aggregations operations process data records and return computed results. Aggregation operations group values from multiple documents together, and can perform a variety of operations on the grouped data to return a single result. In SQL count(*) and with group by is an equivalent of MongoDB aggregation."
},
{
"code": null,
"e": 3060,
"s": 2993,
"text": "For the aggregation in MongoDB, you should use aggregate() method."
},
{
"code": null,
"e": 3111,
"s": 3060,
"text": "Basic syntax of aggregate() method is as follows −"
},
{
"code": null,
"e": 3163,
"s": 3111,
"text": ">db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)\n"
},
{
"code": null,
"e": 3211,
"s": 3163,
"text": "In the collection you have the following data −"
},
{
"code": null,
"e": 3911,
"s": 3211,
"text": "{\n _id: ObjectId(7df78ad8902c)\n title: 'MongoDB Overview', \n description: 'MongoDB is no sql database',\n by_user: 'tutorials point',\n url: 'http://www.tutorialspoint.com',\n tags: ['mongodb', 'database', 'NoSQL'],\n likes: 100\n},\n{\n _id: ObjectId(7df78ad8902d)\n title: 'NoSQL Overview', \n description: 'No sql database is very fast',\n by_user: 'tutorials point',\n url: 'http://www.tutorialspoint.com',\n tags: ['mongodb', 'database', 'NoSQL'],\n likes: 10\n},\n{\n _id: ObjectId(7df78ad8902e)\n title: 'Neo4j Overview', \n description: 'Neo4j is no sql database',\n by_user: 'Neo4j',\n url: 'http://www.neo4j.com',\n tags: ['neo4j', 'database', 'NoSQL'],\n likes: 750\n},"
},
{
"code": null,
"e": 4078,
"s": 3911,
"text": "Now from the above collection, if you want to display a list stating how many tutorials are written by each user, then you will use the following aggregate() method −"
},
{
"code": null,
"e": 4251,
"s": 4078,
"text": "> db.mycol.aggregate([{$group : {_id : \"$by_user\", num_tutorial : {$sum : 1}}}])\n{ \"_id\" : \"tutorials point\", \"num_tutorial\" : 2 }\n{ \"_id\" : \"Neo4j\", \"num_tutorial\" : 1 }\n>"
},
{
"code": null,
"e": 4357,
"s": 4251,
"text": "Sql equivalent query for the above use case will be select by_user, count(*) from mycol group by by_user."
},
{
"code": null,
"e": 4552,
"s": 4357,
"text": "In the above example, we have grouped documents by field by_user and on each occurrence of by user previous value of sum is incremented. Following is a list of available aggregation expressions."
},
{
"code": null,
"e": 5033,
"s": 4552,
"text": "In UNIX command, shell pipeline means the possibility to execute an operation on some input and use the output as the input for the next command and so on. MongoDB also supports same concept in aggregation framework. There is a set of possible stages and each of those is taken as a set of documents as an input and produces a resulting set of documents (or the final resulting JSON document at the end of the pipeline). This can then in turn be used for the next stage and so on."
},
{
"code": null,
"e": 5094,
"s": 5033,
"text": "Following are the possible stages in aggregation framework −"
},
{
"code": null,
"e": 5160,
"s": 5094,
"text": "$project − Used to select some specific fields from a collection."
},
{
"code": null,
"e": 5226,
"s": 5160,
"text": "$project − Used to select some specific fields from a collection."
},
{
"code": null,
"e": 5357,
"s": 5226,
"text": "$match − This is a filtering operation and thus this can reduce the amount of documents that are given as input to the next stage."
},
{
"code": null,
"e": 5488,
"s": 5357,
"text": "$match − This is a filtering operation and thus this can reduce the amount of documents that are given as input to the next stage."
},
{
"code": null,
"e": 5550,
"s": 5488,
"text": "$group − This does the actual aggregation as discussed above."
},
{
"code": null,
"e": 5612,
"s": 5550,
"text": "$group − This does the actual aggregation as discussed above."
},
{
"code": null,
"e": 5641,
"s": 5612,
"text": "$sort − Sorts the documents."
},
{
"code": null,
"e": 5670,
"s": 5641,
"text": "$sort − Sorts the documents."
},
{
"code": null,
"e": 5778,
"s": 5670,
"text": "$skip − With this, it is possible to skip forward in the list of documents for a given amount of documents."
},
{
"code": null,
"e": 5886,
"s": 5778,
"text": "$skip − With this, it is possible to skip forward in the list of documents for a given amount of documents."
},
{
"code": null,
"e": 6000,
"s": 5886,
"text": "$limit − This limits the amount of documents to look at, by the given number starting from the current positions."
},
{
"code": null,
"e": 6114,
"s": 6000,
"text": "$limit − This limits the amount of documents to look at, by the given number starting from the current positions."
},
{
"code": null,
"e": 6393,
"s": 6114,
"text": "$unwind − This is used to unwind document that are using arrays. When using an array, the data is kind of pre-joined and this operation will be undone with this to have individual documents again. Thus with this stage we will increase the amount of documents for the next stage."
}
] |
Python | Intersection of two lists
|
01 Sep, 2021
Intersection of two list means we need to take all those elements which are common to both of the initial lists and store them into another list. Now there are various ways in Python, through which we can perform the Intersection of the lists. Examples:
Input :
lst1 = [15, 9, 10, 56, 23, 78, 5, 4, 9]
lst2 = [9, 4, 5, 36, 47, 26, 10, 45, 87]
Output :
[9, 10, 4, 5]
Input :
lst1 = [4, 9, 1, 17, 11, 26, 28, 54, 69]
lst2 = [9, 9, 74, 21, 45, 11, 63, 28, 26]
Output :
[9, 11, 26, 28]
Method 1: This is the simplest method where we haven’t used any built-in functions.
Python3
# Python program to illustrate the intersection# of two lists in most simple waydef intersection(lst1, lst2): lst3 = [value for value in lst1 if value in lst2] return lst3 # Driver Codelst1 = [4, 9, 1, 17, 11, 26, 28, 54, 69]lst2 = [9, 9, 74, 21, 45, 11, 63, 28, 26]print(intersection(lst1, lst2))
Output:
[9, 11, 26, 28]
Method 2: This method includes the use of set() method.
Python3
# Python program to illustrate the intersection# of two lists using set() methoddef intersection(lst1, lst2): return list(set(lst1) & set(lst2)) # Driver Codelst1 = [15, 9, 10, 56, 23, 78, 5, 4, 9]lst2 = [9, 4, 5, 36, 47, 26, 10, 45, 87]print(intersection(lst1, lst2))
Output:
[9, 10, 4, 5]
Method 3: In this method we set() the larger list and then use the built-in function called intersection() to compute the intersected list. intersection() is a first-class part of set.
Python3
# Python program to illustrate the intersection# of two lists using set() and intersection()def Intersection(lst1, lst2): return set(lst1).intersection(lst2) # Driver Codelst1 = [ 4, 9, 1, 17, 11, 26, 28, 28, 26, 66, 91]lst2 = [9, 9, 74, 21, 45, 11, 63]print(Intersection(lst1, lst2))
Output:
{9, 11}
Method 4: By the use of this hybrid method the complexity of the program falls to O(n). This is an efficient way of doing the following program.
Python3
# Python program to illustrate the intersection# of two listsdef intersection(lst1, lst2): # Use of hybrid method temp = set(lst2) lst3 = [value for value in lst1 if value in temp] return lst3 # Driver Codelst1 = [9, 9, 74, 21, 45, 11, 63]lst2 = [4, 9, 1, 17, 11, 26, 28, 28, 26, 66, 91]print(intersection(lst1, lst2))
Output:
[9, 9, 11]
Method 5: This is the where the intersection is performed over sub-lists inside other lists. Here we have used the concept of filter().
Python3
# Python program to illustrate the intersection# of two lists, sublists and use of filter()def intersection(lst1, lst2): lst3 = [list(filter(lambda x: x in lst1, sublist)) for sublist in lst2] return lst3 # Driver Codelst1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]lst2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]print(intersection(lst1, lst2))
Working: The filter part takes each sublist’s item and checks to see if it is in the source list. The list comprehension is executed for each sublist in list2. Output:
[[13, 32], [7, 13, 28], [1, 6]]
sagar0719kumar
Python list-programs
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Iterate over a list in Python
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n01 Sep, 2021"
},
{
"code": null,
"e": 309,
"s": 53,
"text": "Intersection of two list means we need to take all those elements which are common to both of the initial lists and store them into another list. Now there are various ways in Python, through which we can perform the Intersection of the lists. Examples: "
},
{
"code": null,
"e": 539,
"s": 309,
"text": "Input : \nlst1 = [15, 9, 10, 56, 23, 78, 5, 4, 9]\nlst2 = [9, 4, 5, 36, 47, 26, 10, 45, 87]\nOutput :\n[9, 10, 4, 5]\n\nInput :\nlst1 = [4, 9, 1, 17, 11, 26, 28, 54, 69]\nlst2 = [9, 9, 74, 21, 45, 11, 63, 28, 26]\nOutput :\n[9, 11, 26, 28]"
},
{
"code": null,
"e": 627,
"s": 541,
"text": "Method 1: This is the simplest method where we haven’t used any built-in functions. "
},
{
"code": null,
"e": 635,
"s": 627,
"text": "Python3"
},
{
"code": "# Python program to illustrate the intersection# of two lists in most simple waydef intersection(lst1, lst2): lst3 = [value for value in lst1 if value in lst2] return lst3 # Driver Codelst1 = [4, 9, 1, 17, 11, 26, 28, 54, 69]lst2 = [9, 9, 74, 21, 45, 11, 63, 28, 26]print(intersection(lst1, lst2))",
"e": 939,
"s": 635,
"text": null
},
{
"code": null,
"e": 949,
"s": 939,
"text": "Output: "
},
{
"code": null,
"e": 965,
"s": 949,
"text": "[9, 11, 26, 28]"
},
{
"code": null,
"e": 1023,
"s": 965,
"text": "Method 2: This method includes the use of set() method. "
},
{
"code": null,
"e": 1031,
"s": 1023,
"text": "Python3"
},
{
"code": "# Python program to illustrate the intersection# of two lists using set() methoddef intersection(lst1, lst2): return list(set(lst1) & set(lst2)) # Driver Codelst1 = [15, 9, 10, 56, 23, 78, 5, 4, 9]lst2 = [9, 4, 5, 36, 47, 26, 10, 45, 87]print(intersection(lst1, lst2))",
"e": 1303,
"s": 1031,
"text": null
},
{
"code": null,
"e": 1313,
"s": 1303,
"text": "Output: "
},
{
"code": null,
"e": 1327,
"s": 1313,
"text": "[9, 10, 4, 5]"
},
{
"code": null,
"e": 1514,
"s": 1327,
"text": "Method 3: In this method we set() the larger list and then use the built-in function called intersection() to compute the intersected list. intersection() is a first-class part of set. "
},
{
"code": null,
"e": 1522,
"s": 1514,
"text": "Python3"
},
{
"code": "# Python program to illustrate the intersection# of two lists using set() and intersection()def Intersection(lst1, lst2): return set(lst1).intersection(lst2) # Driver Codelst1 = [ 4, 9, 1, 17, 11, 26, 28, 28, 26, 66, 91]lst2 = [9, 9, 74, 21, 45, 11, 63]print(Intersection(lst1, lst2))",
"e": 1814,
"s": 1522,
"text": null
},
{
"code": null,
"e": 1824,
"s": 1814,
"text": "Output: "
},
{
"code": null,
"e": 1832,
"s": 1824,
"text": "{9, 11}"
},
{
"code": null,
"e": 1979,
"s": 1832,
"text": "Method 4: By the use of this hybrid method the complexity of the program falls to O(n). This is an efficient way of doing the following program. "
},
{
"code": null,
"e": 1987,
"s": 1979,
"text": "Python3"
},
{
"code": "# Python program to illustrate the intersection# of two listsdef intersection(lst1, lst2): # Use of hybrid method temp = set(lst2) lst3 = [value for value in lst1 if value in temp] return lst3 # Driver Codelst1 = [9, 9, 74, 21, 45, 11, 63]lst2 = [4, 9, 1, 17, 11, 26, 28, 28, 26, 66, 91]print(intersection(lst1, lst2))",
"e": 2319,
"s": 1987,
"text": null
},
{
"code": null,
"e": 2329,
"s": 2319,
"text": "Output: "
},
{
"code": null,
"e": 2340,
"s": 2329,
"text": "[9, 9, 11]"
},
{
"code": null,
"e": 2478,
"s": 2340,
"text": "Method 5: This is the where the intersection is performed over sub-lists inside other lists. Here we have used the concept of filter(). "
},
{
"code": null,
"e": 2486,
"s": 2478,
"text": "Python3"
},
{
"code": "# Python program to illustrate the intersection# of two lists, sublists and use of filter()def intersection(lst1, lst2): lst3 = [list(filter(lambda x: x in lst1, sublist)) for sublist in lst2] return lst3 # Driver Codelst1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]lst2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]print(intersection(lst1, lst2))",
"e": 2858,
"s": 2486,
"text": null
},
{
"code": null,
"e": 3028,
"s": 2858,
"text": "Working: The filter part takes each sublist’s item and checks to see if it is in the source list. The list comprehension is executed for each sublist in list2. Output: "
},
{
"code": null,
"e": 3060,
"s": 3028,
"text": "[[13, 32], [7, 13, 28], [1, 6]]"
},
{
"code": null,
"e": 3077,
"s": 3062,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 3098,
"s": 3077,
"text": "Python list-programs"
},
{
"code": null,
"e": 3110,
"s": 3098,
"text": "python-list"
},
{
"code": null,
"e": 3117,
"s": 3110,
"text": "Python"
},
{
"code": null,
"e": 3129,
"s": 3117,
"text": "python-list"
},
{
"code": null,
"e": 3227,
"s": 3129,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3245,
"s": 3227,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3287,
"s": 3245,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3309,
"s": 3287,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3344,
"s": 3309,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 3370,
"s": 3344,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3402,
"s": 3370,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3431,
"s": 3402,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3458,
"s": 3431,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3479,
"s": 3458,
"text": "Python OOPs Concepts"
}
] |
Elements that occurred only once in the array
|
20 May, 2021
Given an array arr that has numbers appearing twice or once. The task is to identify numbers that occur only once in the array.
Note: Duplicates appear side by side every time. There might be a few numbers that can occur at one time and just assume this is a right rotating array (just say an array can rotate k times towards right). The order of the elements in the output doesn’t matter.
Examples:
Input: arr[] = { 7, 7, 8, 8, 9, 1, 1, 4, 2, 2 }
Output: 9 4
Input: arr[] = {-9, -8, 4, 4, 5, 5, -1}
Output: -9 -8 -1
Method-1: Using Sorting.
Sort the array.
Check for each element at index i (except the first and last element), if
arr[i] != arr[i-1] && arr [i] != arr[i+1]
For the first element, check if arr[0] != arr[1].
For the last element, check if arr[n-1] != arr[n-2].
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to find the elements that// appeared only once in the arrayvoid occurredOnce(int arr[], int n){ // Sort the array sort(arr, arr + n); // Check for first element if (arr[0] != arr[1]) cout << arr[0] << " "; // Check for all the elements if it is different // its adjacent elements for (int i = 1; i < n - 1; i++) if (arr[i] != arr[i + 1] && arr[i] != arr[i - 1]) cout << arr[i] << " "; // Check for the last element if (arr[n - 2] != arr[n - 1]) cout << arr[n - 1] << " ";} // Driver codeint main(){ int arr[] = { 7, 7, 8, 8, 9, 1, 1, 4, 2, 2 }; int n = sizeof(arr) / sizeof(arr[0]); occurredOnce(arr, n); return 0;}
// Java implementation// of above approachimport java.util.*; class GFG{ // Function to find the elements that// appeared only once in the arraystatic void occurredOnce(int arr[], int n){ // Sort the array Arrays.sort(arr); // Check for first element if (arr[0] != arr[1]) System.out.println(arr[0] + " "); // Check for all the elements // if it is different // its adjacent elements for (int i = 1; i < n - 1; i++) if (arr[i] != arr[i + 1] && arr[i] != arr[i - 1]) System.out.print(arr[i] + " "); // Check for the last element if (arr[n - 2] != arr[n - 1]) System.out.print(arr[n - 1] + " ");} // Driver codepublic static void main(String args[]){ int arr[] = {7, 7, 8, 8, 9, 1, 1, 4, 2, 2}; int n = arr.length; occurredOnce(arr, n);}} // This code is contributed// by Arnab Kundu
# Python 3 implementation# of above approach # Function to find the elements# that appeared only once in# the arraydef occurredOnce(arr, n): # Sort the array arr.sort() # Check for first element if arr[0] != arr[1]: print(arr[0], end = " ") # Check for all the elements # if it is different its # adjacent elements for i in range(1, n - 1): if (arr[i] != arr[i + 1] and arr[i] != arr[i - 1]): print( arr[i], end = " ") # Check for the last element if arr[n - 2] != arr[n - 1]: print(arr[n - 1], end = " ") # Driver codeif __name__ == "__main__": arr = [ 7, 7, 8, 8, 9, 1, 1, 4, 2, 2 ] n = len(arr) occurredOnce(arr, n) # This code is contributed# by ChitraNayal
// C# implementation// of above approachusing System; class GFG{ // Function to find the elements that// appeared only once in the arraystatic void occurredOnce(int[] arr, int n){ // Sort the array Array.Sort(arr); // Check for first element if (arr[0] != arr[1]) Console.Write(arr[0] + " "); // Check for all the elements // if it is different // its adjacent elements for (int i = 1; i < n - 1; i++) if (arr[i] != arr[i + 1] && arr[i] != arr[i - 1]) Console.Write(arr[i] + " "); // Check for the last element if (arr[n - 2] != arr[n - 1]) Console.Write(arr[n - 1] + " ");} // Driver codepublic static void Main(){ int[] arr = {7, 7, 8, 8, 9, 1, 1, 4, 2, 2}; int n = arr.Length; occurredOnce(arr, n);}} // This code is contributed// by ChitraNayal
<?php// PHP implementation// of above approach // Function to find the elements// that appeared only once in// the arrayfunction occurredOnce(&$arr, $n){ // Sort the array sort($arr); // Check for first element if ($arr[0] != $arr[1]) echo $arr[0]." "; // Check for all the elements // if it is different its // adjacent elements for ($i = 1; $i < $n - 1; $i++) if ($arr[$i] != $arr[$i + 1] && $arr[$i] != $arr[$i - 1]) echo $arr[$i]." "; // Check for the last element if ($arr[$n - 2] != $arr[$n - 1]) echo $arr[$n - 1]." ";} // Driver code$arr = array(7, 7, 8, 8, 9, 1, 1, 4, 2, 2);$n = sizeof($arr);occurredOnce($arr, $n); // This code is contributed// by ChitraNayal?>
<script> // Javascript implementation// of above approach // Function to find the elements that// appeared only once in the arrayfunction occurredOnce(arr,n){ // Sort the array arr.sort(function(a,b){return a-b;}); // Check for first element if (arr[0] != arr[1]) document.write(arr[0] + " "); // Check for all the elements // if it is different // its adjacent elements for (let i = 1; i < n - 1; i++) if (arr[i] != arr[i + 1] && arr[i] != arr[i - 1]) document.write(arr[i] + " "); // Check for the last element if (arr[n - 2] != arr[n - 1]) document.write(arr[n - 1] + " ");} // Driver codelet arr=[7, 7, 8, 8, 9, 1, 1, 4, 2, 2];let n = arr.length;occurredOnce(arr, n); // This code is contributed by rag2127 </script>
4 9
Time Complexity: O(Nlogn) Space Complexity: O(1)
Method-2: (Using Hashing): In C++, unordered_map can be used for hashing.
Traverse the array.
Store each element with its occurrence in the unordered_map.
Traverse the unordered_map and print all the elements with occurrence 1.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to find elements// that appeared only once#include <bits/stdc++.h>using namespace std; // Function to find the elements that// appeared only once in the arrayvoid occurredOnce(int arr[], int n){ unordered_map<int, int> mp; // Store all the elements in the map with // their occurrence for (int i = 0; i < n; i++) mp[arr[i]]++; // Traverse the map and print all the // elements with occurrence 1 for (auto it = mp.begin(); it != mp.end(); it++) if (it->second == 1) cout << it->first << " ";} // Driver codeint main(){ int arr[] = { 7, 7, 8, 8, 9, 1, 1, 4, 2, 2 }; int n = sizeof(arr) / sizeof(arr[0]); occurredOnce(arr, n); return 0;}
// Java implementation to find elements// that appeared only onceimport java.util.*;import java.io.*; class GFG{ // Function to find the elements that // appeared only once in the array static void occurredOnce(int[] arr, int n) { HashMap<Integer, Integer> mp = new HashMap<>(); // Store all the elements in the map with // their occurrence for (int i = 0; i < n; i++) { if (mp.containsKey(arr[i])) mp.put(arr[i], 1 + mp.get(arr[i])); else mp.put(arr[i], 1); } // Traverse the map and print all the // elements with occurrence 1 for (Map.Entry entry : mp.entrySet()) { if (Integer.parseInt(String.valueOf(entry.getValue())) == 1) System.out.print(entry.getKey() + " "); } } // Driver code public static void main(String args[]) { int[] arr = { 7, 7, 8, 8, 9, 1, 1, 4, 2, 2 }; int n = arr.length; occurredOnce(arr, n); }} // This code is contributed by rachana soma
# Python3 implementation to find elements# that appeared only onceimport math as mt # Function to find the elements that# appeared only once in the arraydef occurredOnce(arr, n): mp = dict() # Store all the elements in the # map with their occurrence for i in range(n): if arr[i] in mp.keys(): mp[arr[i]] += 1 else: mp[arr[i]] = 1 # Traverse the map and print all # the elements with occurrence 1 for it in mp: if mp[it] == 1: print(it, end = " ") # Driver codearr = [7, 7, 8, 8, 9, 1, 1, 4, 2, 2]n = len(arr) occurredOnce(arr, n) # This code is contributed by# Mohit Kumar 29
// C# implementation to find elements// that appeared only onceusing System;using System.Collections.Generic;class GFG{ // Function to find the elements that // appeared only once in the array static void occurredOnce(int[] arr, int n) { Dictionary<int, int> mp = new Dictionary<int, int>(); // Store all the elements in the map with // their occurrence for (int i = 0; i < n; i++) { if (mp.ContainsKey(arr[i])) mp[arr[i]] = 1 + mp[arr[i]]; else mp.Add(arr[i], 1); } // Traverse the map and print all the // elements with occurrence 1 foreach(KeyValuePair<int, int> entry in mp) { if (Int32.Parse(String.Join("", entry.Value)) == 1) Console.Write(entry.Key + " "); } } // Driver code public static void Main(String []args) { int[] arr = { 7, 7, 8, 8, 9, 1, 1, 4, 2, 2 }; int n = arr.Length; occurredOnce(arr, n); }} // This code is contributed by shikhasingrajput
<script> // Javascript implementation to find elements// that appeared only once // Function to find the elements that// appeared only once in the arrayfunction occurredOnce(arr, n){ let mp = new Map(); // Store all the elements in the map // with their occurrence for(let i = 0; i < n; i++) { if (mp.has(arr[i])) mp.set(arr[i], 1 + mp.get(arr[i])); else mp.set(arr[i], 1); } // Traverse the map and print all the // elements with occurrence 1 for(let [key, value] of mp.entries()) { if (value == 1) document.write(key + " "); }} // Driver codelet arr = [ 7, 7, 8, 8, 9, 1, 1, 4, 2, 2 ];let n = arr.length; occurredOnce(arr, n); // This code is contributed by avanitrachhadiya2155 </script>
4 9
Time Complexity: O(N) Space Complexity: O(N)
Method-3: Using given assumptions. It is given that an array can be rotated any time and duplicates will appear side by side every time. So, after rotating, the first and last elements will appear side by side.
Check if the first and last elements are equal. If yes, then start traversing the elements between them.
Check if the current element is equal to the element in the immediate previous index. If yes, check the same for the next element.
If not, print the current element.
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation to find elements// that appeared only once#include <bits/stdc++.h>using namespace std; // Function to find the elements that// appeared only once in the arrayvoid occurredOnce(int arr[], int n){ int i = 1, len = n; // Check if the first and last element is equal // If yes, remove those elements if (arr[0] == arr[len - 1]) { i = 2; len--; } // Start traversing the remaining elements for (; i < n; i++) // Check if current element is equal to // the element at immediate previous index // If yes, check the same for next element if (arr[i] == arr[i - 1]) i++; // Else print the current element else cout << arr[i - 1] << " "; // Check for the last element if (arr[n - 1] != arr[0] && arr[n - 1] != arr[n - 2]) cout << arr[n - 1];} // Driver codeint main(){ int arr[] = { 7, 7, 8, 8, 9, 1, 1, 4, 2, 2 }; int n = sizeof(arr) / sizeof(arr[0]); occurredOnce(arr, n); return 0;}
// Java implementation to find// elements that appeared only onceclass GFG{// Function to find the elements that// appeared only once in the arraystatic void occurredOnce(int arr[], int n){ int i = 1, len = n; // Check if the first and last // element is equal. If yes, // remove those elements if (arr[0] == arr[len - 1]) { i = 2; len--; } // Start traversing the // remaining elements for (; i < n; i++) // Check if current element is // equal to the element at // immediate previous index // If yes, check the same // for next element if (arr[i] == arr[i - 1]) i++; // Else print the current element else System.out.print(arr[i - 1] + " "); // Check for the last element if (arr[n - 1] != arr[0] && arr[n - 1] != arr[n - 2]) System.out.print(arr[n - 1]);} // Driver codepublic static void main(String args[]){ int arr[] = {7, 7, 8, 8, 9, 1, 1, 4, 2, 2}; int n = arr.length; occurredOnce(arr, n);}} // This code is contributed// by Arnab Kundu
# Python 3 implementation to find# elements that appeared only once # Function to find the elements that# appeared only once in the arraydef occurredOnce(arr, n): i = 1 len = n # Check if the first and # last element is equal # If yes, remove those elements if arr[0] == arr[len - 1]: i = 2 len -= 1 # Start traversing the # remaining elements while i < n: # Check if current element is # equal to the element at # immediate previous index # If yes, check the same for # next element if arr[i] == arr[i - 1]: i += 1 # Else print the current element else: print(arr[i - 1], end = " ") i += 1 # Check for the last element if (arr[n - 1] != arr[0] and arr[n - 1] != arr[n - 2]): print(arr[n - 1]) # Driver codeif __name__ == "__main__": arr = [ 7, 7, 8, 8, 9, 1, 1, 4, 2, 2 ] n = len(arr) occurredOnce(arr, n) # This code is contributed# by ChitraNayal
// C# implementation to find// elements that appeared only onceusing System; class GFG{// Function to find the elements that// appeared only once in the arraystatic void occurredOnce(int[] arr, int n){ int i = 1, len = n; // Check if the first and last // element is equal. If yes, // remove those elements if (arr[0] == arr[len - 1]) { i = 2; len--; } // Start traversing the // remaining elements for (; i < n; i++) // Check if current element is // equal to the element at // immediate previous index // If yes, check the same // for next element if (arr[i] == arr[i - 1]) i++; // Else print the current element else Console.Write(arr[i - 1] + " "); // Check for the last element if (arr[n - 1] != arr[0] && arr[n - 1] != arr[n - 2]) Console.Write(arr[n - 1]);} // Driver codepublic static void Main(){ int[] arr = {7, 7, 8, 8, 9, 1, 1, 4, 2, 2}; int n = arr.Length; occurredOnce(arr, n);}} // This code is contributed// by ChitraNayal
<?php// PHP implementation to find// elements that appeared only once // Function to find the elements that// appeared only once in the arrayfunction occurredOnce(&$arr, $n){ $i = 1; $len = $n; // Check if the first and last // element is equal. If yes, // remove those elements if ($arr[0] == $arr[$len - 1]) { $i = 2; $len--; } // Start traversing the // remaining elements for (; $i < $n; $i++) // Check if current element is // equal to the element at // immediate previous index // If yes, check the same for // next element if ($arr[$i] == $arr[$i - 1]) $i++; // Else print the current element else echo $arr[$i - 1] . " "; // Check for the last element if ($arr[$n - 1] != $arr[0] && $arr[$n - 1] != $arr[$n - 2]) echo $arr[$n - 1];} // Driver code$arr = array(7, 7, 8, 8, 9, 1, 1, 4, 2, 2);$n = sizeof($arr); occurredOnce($arr, $n); // This code is contributed// by ChitraNayal?>
<script> // Javascript implementation to find// elements that appeared only once // Function to find the elements that// appeared only once in the arrayfunction occurredOnce(arr, n){ var i = 1, len = n; // Check if the first and last // element is equal. If yes, // remove those elements if (arr[0] == arr[len - 1]) { i = 2; len--; } // Start traversing the // remaining elements for(; i < n; i++) // Check if current element is // equal to the element at // immediate previous index // If yes, check the same // for next element if (arr[i] == arr[i - 1]) i++; // Else print the current element else document.write(arr[i - 1] + " "); // Check for the last element if (arr[n - 1] != arr[0] && arr[n - 1] != arr[n - 2]) document.write(arr[n - 1]);} // Driver codevar arr = [ 7, 7, 8, 8, 9, 1, 1, 4, 2, 2 ];var n = arr.length; occurredOnce(arr, n); // This code is contributed by Ankita saini </script>
9 4
Time Complexity: O(N) Space Complexity: O(1)
Count the frequencies of every element using the Counter function
Traverse the frequency array and print all the elements with occurrence 1.
Below is the implementation
Python3
# Python3 implementation to find elements# that appeared only oncefrom collections import Counter # Function to find the elements that# appeared only once in the arraydef occurredOnce(arr, n): #counting frequency of every element using Counter mp=Counter(arr) # Traverse the map and print all # the elements with occurrence 1 for it in mp: if mp[it] == 1: print(it, end = " ") # Driver codearr = [7, 7, 8, 8, 9, 1, 1, 4, 2, 2]n = len(arr) occurredOnce(arr, n) # This code is contributed by vikkycirus
9 4
Time Complexity: O(n)
andrew1234
ukasp
SivaPrakashReddyKomma
mohit kumar 29
rachana soma
shikhasingrajput
vikkycirus
rag2127
avanitrachhadiya2155
ankita_saini
Amazon
cpp-unordered_map
Picked
rotation
Arrays
Hash
Sorting
Amazon
Arrays
Hash
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Window Sliding Technique
Search, insert and delete in an unsorted array
What is Data Structure: Types, Classifications and Applications
Next Greater Element
What is Hashing | A Complete Tutorial
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Count pairs with given sum
Longest Consecutive Subsequence
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n20 May, 2021"
},
{
"code": null,
"e": 181,
"s": 52,
"text": "Given an array arr that has numbers appearing twice or once. The task is to identify numbers that occur only once in the array. "
},
{
"code": null,
"e": 443,
"s": 181,
"text": "Note: Duplicates appear side by side every time. There might be a few numbers that can occur at one time and just assume this is a right rotating array (just say an array can rotate k times towards right). The order of the elements in the output doesn’t matter."
},
{
"code": null,
"e": 454,
"s": 443,
"text": "Examples: "
},
{
"code": null,
"e": 572,
"s": 454,
"text": "Input: arr[] = { 7, 7, 8, 8, 9, 1, 1, 4, 2, 2 }\nOutput: 9 4\n\nInput: arr[] = {-9, -8, 4, 4, 5, 5, -1}\nOutput: -9 -8 -1"
},
{
"code": null,
"e": 598,
"s": 572,
"text": "Method-1: Using Sorting. "
},
{
"code": null,
"e": 614,
"s": 598,
"text": "Sort the array."
},
{
"code": null,
"e": 688,
"s": 614,
"text": "Check for each element at index i (except the first and last element), if"
},
{
"code": null,
"e": 730,
"s": 688,
"text": "arr[i] != arr[i-1] && arr [i] != arr[i+1]"
},
{
"code": null,
"e": 780,
"s": 730,
"text": "For the first element, check if arr[0] != arr[1]."
},
{
"code": null,
"e": 833,
"s": 780,
"text": "For the last element, check if arr[n-1] != arr[n-2]."
},
{
"code": null,
"e": 884,
"s": 833,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 888,
"s": 884,
"text": "C++"
},
{
"code": null,
"e": 893,
"s": 888,
"text": "Java"
},
{
"code": null,
"e": 901,
"s": 893,
"text": "Python3"
},
{
"code": null,
"e": 904,
"s": 901,
"text": "C#"
},
{
"code": null,
"e": 908,
"s": 904,
"text": "PHP"
},
{
"code": null,
"e": 919,
"s": 908,
"text": "Javascript"
},
{
"code": "// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to find the elements that// appeared only once in the arrayvoid occurredOnce(int arr[], int n){ // Sort the array sort(arr, arr + n); // Check for first element if (arr[0] != arr[1]) cout << arr[0] << \" \"; // Check for all the elements if it is different // its adjacent elements for (int i = 1; i < n - 1; i++) if (arr[i] != arr[i + 1] && arr[i] != arr[i - 1]) cout << arr[i] << \" \"; // Check for the last element if (arr[n - 2] != arr[n - 1]) cout << arr[n - 1] << \" \";} // Driver codeint main(){ int arr[] = { 7, 7, 8, 8, 9, 1, 1, 4, 2, 2 }; int n = sizeof(arr) / sizeof(arr[0]); occurredOnce(arr, n); return 0;}",
"e": 1708,
"s": 919,
"text": null
},
{
"code": "// Java implementation// of above approachimport java.util.*; class GFG{ // Function to find the elements that// appeared only once in the arraystatic void occurredOnce(int arr[], int n){ // Sort the array Arrays.sort(arr); // Check for first element if (arr[0] != arr[1]) System.out.println(arr[0] + \" \"); // Check for all the elements // if it is different // its adjacent elements for (int i = 1; i < n - 1; i++) if (arr[i] != arr[i + 1] && arr[i] != arr[i - 1]) System.out.print(arr[i] + \" \"); // Check for the last element if (arr[n - 2] != arr[n - 1]) System.out.print(arr[n - 1] + \" \");} // Driver codepublic static void main(String args[]){ int arr[] = {7, 7, 8, 8, 9, 1, 1, 4, 2, 2}; int n = arr.length; occurredOnce(arr, n);}} // This code is contributed// by Arnab Kundu",
"e": 2592,
"s": 1708,
"text": null
},
{
"code": "# Python 3 implementation# of above approach # Function to find the elements# that appeared only once in# the arraydef occurredOnce(arr, n): # Sort the array arr.sort() # Check for first element if arr[0] != arr[1]: print(arr[0], end = \" \") # Check for all the elements # if it is different its # adjacent elements for i in range(1, n - 1): if (arr[i] != arr[i + 1] and arr[i] != arr[i - 1]): print( arr[i], end = \" \") # Check for the last element if arr[n - 2] != arr[n - 1]: print(arr[n - 1], end = \" \") # Driver codeif __name__ == \"__main__\": arr = [ 7, 7, 8, 8, 9, 1, 1, 4, 2, 2 ] n = len(arr) occurredOnce(arr, n) # This code is contributed# by ChitraNayal",
"e": 3356,
"s": 2592,
"text": null
},
{
"code": "// C# implementation// of above approachusing System; class GFG{ // Function to find the elements that// appeared only once in the arraystatic void occurredOnce(int[] arr, int n){ // Sort the array Array.Sort(arr); // Check for first element if (arr[0] != arr[1]) Console.Write(arr[0] + \" \"); // Check for all the elements // if it is different // its adjacent elements for (int i = 1; i < n - 1; i++) if (arr[i] != arr[i + 1] && arr[i] != arr[i - 1]) Console.Write(arr[i] + \" \"); // Check for the last element if (arr[n - 2] != arr[n - 1]) Console.Write(arr[n - 1] + \" \");} // Driver codepublic static void Main(){ int[] arr = {7, 7, 8, 8, 9, 1, 1, 4, 2, 2}; int n = arr.Length; occurredOnce(arr, n);}} // This code is contributed// by ChitraNayal",
"e": 4206,
"s": 3356,
"text": null
},
{
"code": "<?php// PHP implementation// of above approach // Function to find the elements// that appeared only once in// the arrayfunction occurredOnce(&$arr, $n){ // Sort the array sort($arr); // Check for first element if ($arr[0] != $arr[1]) echo $arr[0].\" \"; // Check for all the elements // if it is different its // adjacent elements for ($i = 1; $i < $n - 1; $i++) if ($arr[$i] != $arr[$i + 1] && $arr[$i] != $arr[$i - 1]) echo $arr[$i].\" \"; // Check for the last element if ($arr[$n - 2] != $arr[$n - 1]) echo $arr[$n - 1].\" \";} // Driver code$arr = array(7, 7, 8, 8, 9, 1, 1, 4, 2, 2);$n = sizeof($arr);occurredOnce($arr, $n); // This code is contributed// by ChitraNayal?>",
"e": 4967,
"s": 4206,
"text": null
},
{
"code": "<script> // Javascript implementation// of above approach // Function to find the elements that// appeared only once in the arrayfunction occurredOnce(arr,n){ // Sort the array arr.sort(function(a,b){return a-b;}); // Check for first element if (arr[0] != arr[1]) document.write(arr[0] + \" \"); // Check for all the elements // if it is different // its adjacent elements for (let i = 1; i < n - 1; i++) if (arr[i] != arr[i + 1] && arr[i] != arr[i - 1]) document.write(arr[i] + \" \"); // Check for the last element if (arr[n - 2] != arr[n - 1]) document.write(arr[n - 1] + \" \");} // Driver codelet arr=[7, 7, 8, 8, 9, 1, 1, 4, 2, 2];let n = arr.length;occurredOnce(arr, n); // This code is contributed by rag2127 </script>",
"e": 5784,
"s": 4967,
"text": null
},
{
"code": null,
"e": 5789,
"s": 5784,
"text": "4 9 "
},
{
"code": null,
"e": 5838,
"s": 5789,
"text": "Time Complexity: O(Nlogn) Space Complexity: O(1)"
},
{
"code": null,
"e": 5913,
"s": 5838,
"text": "Method-2: (Using Hashing): In C++, unordered_map can be used for hashing. "
},
{
"code": null,
"e": 5933,
"s": 5913,
"text": "Traverse the array."
},
{
"code": null,
"e": 5994,
"s": 5933,
"text": "Store each element with its occurrence in the unordered_map."
},
{
"code": null,
"e": 6067,
"s": 5994,
"text": "Traverse the unordered_map and print all the elements with occurrence 1."
},
{
"code": null,
"e": 6119,
"s": 6067,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 6123,
"s": 6119,
"text": "C++"
},
{
"code": null,
"e": 6128,
"s": 6123,
"text": "Java"
},
{
"code": null,
"e": 6136,
"s": 6128,
"text": "Python3"
},
{
"code": null,
"e": 6139,
"s": 6136,
"text": "C#"
},
{
"code": null,
"e": 6150,
"s": 6139,
"text": "Javascript"
},
{
"code": "// C++ implementation to find elements// that appeared only once#include <bits/stdc++.h>using namespace std; // Function to find the elements that// appeared only once in the arrayvoid occurredOnce(int arr[], int n){ unordered_map<int, int> mp; // Store all the elements in the map with // their occurrence for (int i = 0; i < n; i++) mp[arr[i]]++; // Traverse the map and print all the // elements with occurrence 1 for (auto it = mp.begin(); it != mp.end(); it++) if (it->second == 1) cout << it->first << \" \";} // Driver codeint main(){ int arr[] = { 7, 7, 8, 8, 9, 1, 1, 4, 2, 2 }; int n = sizeof(arr) / sizeof(arr[0]); occurredOnce(arr, n); return 0;}",
"e": 6870,
"s": 6150,
"text": null
},
{
"code": "// Java implementation to find elements// that appeared only onceimport java.util.*;import java.io.*; class GFG{ // Function to find the elements that // appeared only once in the array static void occurredOnce(int[] arr, int n) { HashMap<Integer, Integer> mp = new HashMap<>(); // Store all the elements in the map with // their occurrence for (int i = 0; i < n; i++) { if (mp.containsKey(arr[i])) mp.put(arr[i], 1 + mp.get(arr[i])); else mp.put(arr[i], 1); } // Traverse the map and print all the // elements with occurrence 1 for (Map.Entry entry : mp.entrySet()) { if (Integer.parseInt(String.valueOf(entry.getValue())) == 1) System.out.print(entry.getKey() + \" \"); } } // Driver code public static void main(String args[]) { int[] arr = { 7, 7, 8, 8, 9, 1, 1, 4, 2, 2 }; int n = arr.length; occurredOnce(arr, n); }} // This code is contributed by rachana soma",
"e": 8034,
"s": 6870,
"text": null
},
{
"code": "# Python3 implementation to find elements# that appeared only onceimport math as mt # Function to find the elements that# appeared only once in the arraydef occurredOnce(arr, n): mp = dict() # Store all the elements in the # map with their occurrence for i in range(n): if arr[i] in mp.keys(): mp[arr[i]] += 1 else: mp[arr[i]] = 1 # Traverse the map and print all # the elements with occurrence 1 for it in mp: if mp[it] == 1: print(it, end = \" \") # Driver codearr = [7, 7, 8, 8, 9, 1, 1, 4, 2, 2]n = len(arr) occurredOnce(arr, n) # This code is contributed by# Mohit Kumar 29",
"e": 8689,
"s": 8034,
"text": null
},
{
"code": "// C# implementation to find elements// that appeared only onceusing System;using System.Collections.Generic;class GFG{ // Function to find the elements that // appeared only once in the array static void occurredOnce(int[] arr, int n) { Dictionary<int, int> mp = new Dictionary<int, int>(); // Store all the elements in the map with // their occurrence for (int i = 0; i < n; i++) { if (mp.ContainsKey(arr[i])) mp[arr[i]] = 1 + mp[arr[i]]; else mp.Add(arr[i], 1); } // Traverse the map and print all the // elements with occurrence 1 foreach(KeyValuePair<int, int> entry in mp) { if (Int32.Parse(String.Join(\"\", entry.Value)) == 1) Console.Write(entry.Key + \" \"); } } // Driver code public static void Main(String []args) { int[] arr = { 7, 7, 8, 8, 9, 1, 1, 4, 2, 2 }; int n = arr.Length; occurredOnce(arr, n); }} // This code is contributed by shikhasingrajput",
"e": 9701,
"s": 8689,
"text": null
},
{
"code": "<script> // Javascript implementation to find elements// that appeared only once // Function to find the elements that// appeared only once in the arrayfunction occurredOnce(arr, n){ let mp = new Map(); // Store all the elements in the map // with their occurrence for(let i = 0; i < n; i++) { if (mp.has(arr[i])) mp.set(arr[i], 1 + mp.get(arr[i])); else mp.set(arr[i], 1); } // Traverse the map and print all the // elements with occurrence 1 for(let [key, value] of mp.entries()) { if (value == 1) document.write(key + \" \"); }} // Driver codelet arr = [ 7, 7, 8, 8, 9, 1, 1, 4, 2, 2 ];let n = arr.length; occurredOnce(arr, n); // This code is contributed by avanitrachhadiya2155 </script>",
"e": 10500,
"s": 9701,
"text": null
},
{
"code": null,
"e": 10505,
"s": 10500,
"text": "4 9 "
},
{
"code": null,
"e": 10550,
"s": 10505,
"text": "Time Complexity: O(N) Space Complexity: O(N)"
},
{
"code": null,
"e": 10762,
"s": 10550,
"text": "Method-3: Using given assumptions. It is given that an array can be rotated any time and duplicates will appear side by side every time. So, after rotating, the first and last elements will appear side by side. "
},
{
"code": null,
"e": 10867,
"s": 10762,
"text": "Check if the first and last elements are equal. If yes, then start traversing the elements between them."
},
{
"code": null,
"e": 10998,
"s": 10867,
"text": "Check if the current element is equal to the element in the immediate previous index. If yes, check the same for the next element."
},
{
"code": null,
"e": 11033,
"s": 10998,
"text": "If not, print the current element."
},
{
"code": null,
"e": 11037,
"s": 11033,
"text": "C++"
},
{
"code": null,
"e": 11042,
"s": 11037,
"text": "Java"
},
{
"code": null,
"e": 11050,
"s": 11042,
"text": "Python3"
},
{
"code": null,
"e": 11053,
"s": 11050,
"text": "C#"
},
{
"code": null,
"e": 11057,
"s": 11053,
"text": "PHP"
},
{
"code": null,
"e": 11068,
"s": 11057,
"text": "Javascript"
},
{
"code": "// C++ implementation to find elements// that appeared only once#include <bits/stdc++.h>using namespace std; // Function to find the elements that// appeared only once in the arrayvoid occurredOnce(int arr[], int n){ int i = 1, len = n; // Check if the first and last element is equal // If yes, remove those elements if (arr[0] == arr[len - 1]) { i = 2; len--; } // Start traversing the remaining elements for (; i < n; i++) // Check if current element is equal to // the element at immediate previous index // If yes, check the same for next element if (arr[i] == arr[i - 1]) i++; // Else print the current element else cout << arr[i - 1] << \" \"; // Check for the last element if (arr[n - 1] != arr[0] && arr[n - 1] != arr[n - 2]) cout << arr[n - 1];} // Driver codeint main(){ int arr[] = { 7, 7, 8, 8, 9, 1, 1, 4, 2, 2 }; int n = sizeof(arr) / sizeof(arr[0]); occurredOnce(arr, n); return 0;}",
"e": 12097,
"s": 11068,
"text": null
},
{
"code": "// Java implementation to find// elements that appeared only onceclass GFG{// Function to find the elements that// appeared only once in the arraystatic void occurredOnce(int arr[], int n){ int i = 1, len = n; // Check if the first and last // element is equal. If yes, // remove those elements if (arr[0] == arr[len - 1]) { i = 2; len--; } // Start traversing the // remaining elements for (; i < n; i++) // Check if current element is // equal to the element at // immediate previous index // If yes, check the same // for next element if (arr[i] == arr[i - 1]) i++; // Else print the current element else System.out.print(arr[i - 1] + \" \"); // Check for the last element if (arr[n - 1] != arr[0] && arr[n - 1] != arr[n - 2]) System.out.print(arr[n - 1]);} // Driver codepublic static void main(String args[]){ int arr[] = {7, 7, 8, 8, 9, 1, 1, 4, 2, 2}; int n = arr.length; occurredOnce(arr, n);}} // This code is contributed// by Arnab Kundu",
"e": 13216,
"s": 12097,
"text": null
},
{
"code": "# Python 3 implementation to find# elements that appeared only once # Function to find the elements that# appeared only once in the arraydef occurredOnce(arr, n): i = 1 len = n # Check if the first and # last element is equal # If yes, remove those elements if arr[0] == arr[len - 1]: i = 2 len -= 1 # Start traversing the # remaining elements while i < n: # Check if current element is # equal to the element at # immediate previous index # If yes, check the same for # next element if arr[i] == arr[i - 1]: i += 1 # Else print the current element else: print(arr[i - 1], end = \" \") i += 1 # Check for the last element if (arr[n - 1] != arr[0] and arr[n - 1] != arr[n - 2]): print(arr[n - 1]) # Driver codeif __name__ == \"__main__\": arr = [ 7, 7, 8, 8, 9, 1, 1, 4, 2, 2 ] n = len(arr) occurredOnce(arr, n) # This code is contributed# by ChitraNayal",
"e": 14240,
"s": 13216,
"text": null
},
{
"code": "// C# implementation to find// elements that appeared only onceusing System; class GFG{// Function to find the elements that// appeared only once in the arraystatic void occurredOnce(int[] arr, int n){ int i = 1, len = n; // Check if the first and last // element is equal. If yes, // remove those elements if (arr[0] == arr[len - 1]) { i = 2; len--; } // Start traversing the // remaining elements for (; i < n; i++) // Check if current element is // equal to the element at // immediate previous index // If yes, check the same // for next element if (arr[i] == arr[i - 1]) i++; // Else print the current element else Console.Write(arr[i - 1] + \" \"); // Check for the last element if (arr[n - 1] != arr[0] && arr[n - 1] != arr[n - 2]) Console.Write(arr[n - 1]);} // Driver codepublic static void Main(){ int[] arr = {7, 7, 8, 8, 9, 1, 1, 4, 2, 2}; int n = arr.Length; occurredOnce(arr, n);}} // This code is contributed// by ChitraNayal",
"e": 15351,
"s": 14240,
"text": null
},
{
"code": "<?php// PHP implementation to find// elements that appeared only once // Function to find the elements that// appeared only once in the arrayfunction occurredOnce(&$arr, $n){ $i = 1; $len = $n; // Check if the first and last // element is equal. If yes, // remove those elements if ($arr[0] == $arr[$len - 1]) { $i = 2; $len--; } // Start traversing the // remaining elements for (; $i < $n; $i++) // Check if current element is // equal to the element at // immediate previous index // If yes, check the same for // next element if ($arr[$i] == $arr[$i - 1]) $i++; // Else print the current element else echo $arr[$i - 1] . \" \"; // Check for the last element if ($arr[$n - 1] != $arr[0] && $arr[$n - 1] != $arr[$n - 2]) echo $arr[$n - 1];} // Driver code$arr = array(7, 7, 8, 8, 9, 1, 1, 4, 2, 2);$n = sizeof($arr); occurredOnce($arr, $n); // This code is contributed// by ChitraNayal?>",
"e": 16401,
"s": 15351,
"text": null
},
{
"code": "<script> // Javascript implementation to find// elements that appeared only once // Function to find the elements that// appeared only once in the arrayfunction occurredOnce(arr, n){ var i = 1, len = n; // Check if the first and last // element is equal. If yes, // remove those elements if (arr[0] == arr[len - 1]) { i = 2; len--; } // Start traversing the // remaining elements for(; i < n; i++) // Check if current element is // equal to the element at // immediate previous index // If yes, check the same // for next element if (arr[i] == arr[i - 1]) i++; // Else print the current element else document.write(arr[i - 1] + \" \"); // Check for the last element if (arr[n - 1] != arr[0] && arr[n - 1] != arr[n - 2]) document.write(arr[n - 1]);} // Driver codevar arr = [ 7, 7, 8, 8, 9, 1, 1, 4, 2, 2 ];var n = arr.length; occurredOnce(arr, n); // This code is contributed by Ankita saini </script>",
"e": 17459,
"s": 16401,
"text": null
},
{
"code": null,
"e": 17464,
"s": 17459,
"text": "9 4 "
},
{
"code": null,
"e": 17509,
"s": 17464,
"text": "Time Complexity: O(N) Space Complexity: O(1)"
},
{
"code": null,
"e": 17575,
"s": 17509,
"text": "Count the frequencies of every element using the Counter function"
},
{
"code": null,
"e": 17650,
"s": 17575,
"text": "Traverse the frequency array and print all the elements with occurrence 1."
},
{
"code": null,
"e": 17678,
"s": 17650,
"text": "Below is the implementation"
},
{
"code": null,
"e": 17686,
"s": 17678,
"text": "Python3"
},
{
"code": "# Python3 implementation to find elements# that appeared only oncefrom collections import Counter # Function to find the elements that# appeared only once in the arraydef occurredOnce(arr, n): #counting frequency of every element using Counter mp=Counter(arr) # Traverse the map and print all # the elements with occurrence 1 for it in mp: if mp[it] == 1: print(it, end = \" \") # Driver codearr = [7, 7, 8, 8, 9, 1, 1, 4, 2, 2]n = len(arr) occurredOnce(arr, n) # This code is contributed by vikkycirus",
"e": 18221,
"s": 17686,
"text": null
},
{
"code": null,
"e": 18226,
"s": 18221,
"text": "9 4 "
},
{
"code": null,
"e": 18248,
"s": 18226,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 18259,
"s": 18248,
"text": "andrew1234"
},
{
"code": null,
"e": 18265,
"s": 18259,
"text": "ukasp"
},
{
"code": null,
"e": 18287,
"s": 18265,
"text": "SivaPrakashReddyKomma"
},
{
"code": null,
"e": 18302,
"s": 18287,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 18315,
"s": 18302,
"text": "rachana soma"
},
{
"code": null,
"e": 18332,
"s": 18315,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 18343,
"s": 18332,
"text": "vikkycirus"
},
{
"code": null,
"e": 18351,
"s": 18343,
"text": "rag2127"
},
{
"code": null,
"e": 18372,
"s": 18351,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 18385,
"s": 18372,
"text": "ankita_saini"
},
{
"code": null,
"e": 18392,
"s": 18385,
"text": "Amazon"
},
{
"code": null,
"e": 18410,
"s": 18392,
"text": "cpp-unordered_map"
},
{
"code": null,
"e": 18417,
"s": 18410,
"text": "Picked"
},
{
"code": null,
"e": 18426,
"s": 18417,
"text": "rotation"
},
{
"code": null,
"e": 18433,
"s": 18426,
"text": "Arrays"
},
{
"code": null,
"e": 18438,
"s": 18433,
"text": "Hash"
},
{
"code": null,
"e": 18446,
"s": 18438,
"text": "Sorting"
},
{
"code": null,
"e": 18453,
"s": 18446,
"text": "Amazon"
},
{
"code": null,
"e": 18460,
"s": 18453,
"text": "Arrays"
},
{
"code": null,
"e": 18465,
"s": 18460,
"text": "Hash"
},
{
"code": null,
"e": 18473,
"s": 18465,
"text": "Sorting"
},
{
"code": null,
"e": 18571,
"s": 18473,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 18603,
"s": 18571,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 18628,
"s": 18603,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 18675,
"s": 18628,
"text": "Search, insert and delete in an unsorted array"
},
{
"code": null,
"e": 18739,
"s": 18675,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 18760,
"s": 18739,
"text": "Next Greater Element"
},
{
"code": null,
"e": 18798,
"s": 18760,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 18834,
"s": 18798,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 18865,
"s": 18834,
"text": "Hashing | Set 1 (Introduction)"
},
{
"code": null,
"e": 18892,
"s": 18865,
"text": "Count pairs with given sum"
}
] |
Timeline Component in React.js
|
31 Mar, 2021
Timelines are often used in user interfaces to illustrate a step-by-step procedure. It can describe to the user which stage of the process they currently are and what the further tasks are. Material UI labs module provide a Timeline component along with some other utility components to make this very easy to include in our React app.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:npx create-react-app gfg
Step 1: Create a React application using the following command:
npx create-react-app gfg
Step 2: After creating your project folder i.e. gfg, move to it using the following command:cd gfg
Step 2: After creating your project folder i.e. gfg, move to it using the following command:
cd gfg
Step 3: After creating the ReactJS application, Install the material-ui modules using the following command:npm install @material-ui/core
npm install @material-ui/lab
Step 3: After creating the ReactJS application, Install the material-ui modules using the following command:
npm install @material-ui/core
npm install @material-ui/lab
As an example, we’ll create a Stages component that illustrates the different stages an Article at GeeksforGeeks goes through in form of a Timeline. Create a file stages.js in the src folder where we’ll define this component.
Project Structure: It will look like the following.
The Timeline component in Material UI labs displays items in chronological order and gives the developers freedom to alter how it’s displayed up to some extent. It has some useful props:
align: The textual content can be posted at the left, right, or alternating to the timeline.
color: Used to denote the color of the timeline dot at that stage. It’s the prop of the TimelineDot component which we use inside the Timeline component.
stages.js
import React from 'react';import Timeline from '@material-ui/lab/Timeline';import TimelineItem from '@material-ui/lab/TimelineItem';import TimelineSeparator from '@material-ui/lab/TimelineSeparator';import TimelineConnector from '@material-ui/lab/TimelineConnector';import TimelineContent from '@material-ui/lab/TimelineContent';import TimelineDot from '@material-ui/lab/TimelineDot';import { Paper } from '@material-ui/core'; const paperstyle={ padding: '8px 1px', textAlign:'center',} export default function Stages() { return ( <Timeline align="alternate"> <TimelineItem> <TimelineSeparator> <TimelineDot color="primary" /> <TimelineConnector /> </TimelineSeparator> <TimelineContent> <Paper elevation={3} style={paperstyle}>Step 1 : Write </Paper> </TimelineContent> </TimelineItem> <TimelineItem> <TimelineSeparator> <TimelineDot color="primary" /> <TimelineConnector /> </TimelineSeparator> <TimelineContent> <Paper elevation={3} style={paperstyle}>Step 2 : Draft </Paper> </TimelineContent> </TimelineItem> <TimelineItem> <TimelineSeparator> <TimelineDot color="primary" /> <TimelineConnector /> </TimelineSeparator> <TimelineContent> <Paper elevation={3} style={paperstyle}>Step 3 : Pending </Paper> </TimelineContent> </TimelineItem> <TimelineItem> <TimelineSeparator> <TimelineDot /> </TimelineSeparator> <TimelineContent> <Paper elevation={3} style={paperstyle}>Step 4 : Publish </Paper> </TimelineContent> </TimelineItem> </Timeline> );}
Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React, { Component } from 'react';import CssBaseline from '@material-ui/core/CssBaseline';import Container from '@material-ui/core/Container';import Typography from '@material-ui/core/Typography';import Stages from './stages'; class GFG extends Component { render() { return ( <React.Fragment> <CssBaseline /> <br></br> <Container maxWidth="sm"> <Typography component="h1" variant="h1" align="center" gutterBottom> Geeks for Geeks </Typography> <br /> <Typography component="h3" variant="h3" align="center" gutterBottom> Timeline of an Article </Typography> </Container> <Container maxWidth="sm"> <Stages></Stages> </Container> </React.Fragment> ); }} export default GFG;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Material-UI
JavaScript
ReactJS
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": "\n31 Mar, 2021"
},
{
"code": null,
"e": 364,
"s": 28,
"text": "Timelines are often used in user interfaces to illustrate a step-by-step procedure. It can describe to the user which stage of the process they currently are and what the further tasks are. Material UI labs module provide a Timeline component along with some other utility components to make this very easy to include in our React app."
},
{
"code": null,
"e": 414,
"s": 364,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 502,
"s": 414,
"text": "Step 1: Create a React application using the following command:npx create-react-app gfg"
},
{
"code": null,
"e": 566,
"s": 502,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 591,
"s": 566,
"text": "npx create-react-app gfg"
},
{
"code": null,
"e": 690,
"s": 591,
"text": "Step 2: After creating your project folder i.e. gfg, move to it using the following command:cd gfg"
},
{
"code": null,
"e": 783,
"s": 690,
"text": "Step 2: After creating your project folder i.e. gfg, move to it using the following command:"
},
{
"code": null,
"e": 790,
"s": 783,
"text": "cd gfg"
},
{
"code": null,
"e": 957,
"s": 790,
"text": "Step 3: After creating the ReactJS application, Install the material-ui modules using the following command:npm install @material-ui/core\nnpm install @material-ui/lab"
},
{
"code": null,
"e": 1066,
"s": 957,
"text": "Step 3: After creating the ReactJS application, Install the material-ui modules using the following command:"
},
{
"code": null,
"e": 1125,
"s": 1066,
"text": "npm install @material-ui/core\nnpm install @material-ui/lab"
},
{
"code": null,
"e": 1351,
"s": 1125,
"text": "As an example, we’ll create a Stages component that illustrates the different stages an Article at GeeksforGeeks goes through in form of a Timeline. Create a file stages.js in the src folder where we’ll define this component."
},
{
"code": null,
"e": 1403,
"s": 1351,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 1590,
"s": 1403,
"text": "The Timeline component in Material UI labs displays items in chronological order and gives the developers freedom to alter how it’s displayed up to some extent. It has some useful props:"
},
{
"code": null,
"e": 1683,
"s": 1590,
"text": "align: The textual content can be posted at the left, right, or alternating to the timeline."
},
{
"code": null,
"e": 1837,
"s": 1683,
"text": "color: Used to denote the color of the timeline dot at that stage. It’s the prop of the TimelineDot component which we use inside the Timeline component."
},
{
"code": null,
"e": 1847,
"s": 1837,
"text": "stages.js"
},
{
"code": "import React from 'react';import Timeline from '@material-ui/lab/Timeline';import TimelineItem from '@material-ui/lab/TimelineItem';import TimelineSeparator from '@material-ui/lab/TimelineSeparator';import TimelineConnector from '@material-ui/lab/TimelineConnector';import TimelineContent from '@material-ui/lab/TimelineContent';import TimelineDot from '@material-ui/lab/TimelineDot';import { Paper } from '@material-ui/core'; const paperstyle={ padding: '8px 1px', textAlign:'center',} export default function Stages() { return ( <Timeline align=\"alternate\"> <TimelineItem> <TimelineSeparator> <TimelineDot color=\"primary\" /> <TimelineConnector /> </TimelineSeparator> <TimelineContent> <Paper elevation={3} style={paperstyle}>Step 1 : Write </Paper> </TimelineContent> </TimelineItem> <TimelineItem> <TimelineSeparator> <TimelineDot color=\"primary\" /> <TimelineConnector /> </TimelineSeparator> <TimelineContent> <Paper elevation={3} style={paperstyle}>Step 2 : Draft </Paper> </TimelineContent> </TimelineItem> <TimelineItem> <TimelineSeparator> <TimelineDot color=\"primary\" /> <TimelineConnector /> </TimelineSeparator> <TimelineContent> <Paper elevation={3} style={paperstyle}>Step 3 : Pending </Paper> </TimelineContent> </TimelineItem> <TimelineItem> <TimelineSeparator> <TimelineDot /> </TimelineSeparator> <TimelineContent> <Paper elevation={3} style={paperstyle}>Step 4 : Publish </Paper> </TimelineContent> </TimelineItem> </Timeline> );}",
"e": 3952,
"s": 1847,
"text": null
},
{
"code": null,
"e": 4073,
"s": 3952,
"text": "Now write down the following code in the App.js file. Here, App is our default component where we have written our code."
},
{
"code": null,
"e": 4080,
"s": 4073,
"text": "App.js"
},
{
"code": "import React, { Component } from 'react';import CssBaseline from '@material-ui/core/CssBaseline';import Container from '@material-ui/core/Container';import Typography from '@material-ui/core/Typography';import Stages from './stages'; class GFG extends Component { render() { return ( <React.Fragment> <CssBaseline /> <br></br> <Container maxWidth=\"sm\"> <Typography component=\"h1\" variant=\"h1\" align=\"center\" gutterBottom> Geeks for Geeks </Typography> <br /> <Typography component=\"h3\" variant=\"h3\" align=\"center\" gutterBottom> Timeline of an Article </Typography> </Container> <Container maxWidth=\"sm\"> <Stages></Stages> </Container> </React.Fragment> ); }} export default GFG;",
"e": 5157,
"s": 4080,
"text": null
},
{
"code": null,
"e": 5270,
"s": 5157,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 5280,
"s": 5270,
"text": "npm start"
},
{
"code": null,
"e": 5379,
"s": 5280,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 5391,
"s": 5379,
"text": "Material-UI"
},
{
"code": null,
"e": 5402,
"s": 5391,
"text": "JavaScript"
},
{
"code": null,
"e": 5410,
"s": 5402,
"text": "ReactJS"
},
{
"code": null,
"e": 5427,
"s": 5410,
"text": "Web Technologies"
}
] |
HTML | DOM Input Radio disabled Property
|
17 Oct, 2019
The DOM Input Radio disabled Property is used to set or return whether the Radio Button must be disabled or not. A disabled Radio Button is un-clickable and unusable. It is a boolean attribute and used to reflect the HTML Disabled attribute. It is usually rendered in grey color by default in all the Browsers.
Syntax:
It returns the disabled property.radioObject.disabled
radioObject.disabled
It is used to set the disabled property.radioObject.disabled = true|false
radioObject.disabled = true|false
Property Values:
true: It defines that the Input Radio Button is disabled.
False: It has a default value. It defines that the Radio Button is not disabled.
Return Value: It returns a boolean value which represents that the Radio Button is disabled or not.
Example-1: This Example illustrates how to return the Property.
<!DOCTYPE html><html> <head> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1> GeeksforGeeks </h1> <h2> HTML DOM Input Radio Disabled Property </h2> <form id="myGeeks"> Radio Button: <input type="radio" checked=true id="radioID" value="Geeks_radio" name="Geek_radio" disabled> <br> <br> </form> <button onclick="GFG()"> Click! </button> <p id="GFG" style="font-size:25px; color:green;"> </p> <script> function GFG() { // Accessing input element // type="radio" var x = document.getElementById( "radioID").disabled; document.getElementById( "GFG").innerHTML = x; } </script> </body> </html>
Output:Before Clicking On Button:
After Clicking On Button :
Example-2: This Example illustrates how to set the Disabled Property.
<!DOCTYPE html><html> <head> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1> GeeksforGeeks </h1> <h2> HTML DOM Input Radio Disabled Property </h2> <form id="myGeeks"> Radio Button: <input type="radio" checked=true id="radioID" value="Geeks_radio" name="Geek_radio" disabled> <br> <br> </form> <button onclick="GFG()"> Click! </button> <p id="GFG" style="font-size:25px; color:green;"> </p> <script> function GFG() { // Accessing input element // type="radio" var x = document.getElementById( "radioID").disabled = "false"; document.getElementById( "GFG").innerHTML = x; } </script> </body> </html>
Output:Before Clicking On Button :
After Clicking On Button :
Supported Browsers: The browser supported by DOM input Radio disabled property are listed below:
Google Chrome
Internet Explorer 10.0 +
Firefox
Opera
Safari
shubham_singh
HTML-DOM
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
HTTP headers | Content-Type
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": 53,
"s": 25,
"text": "\n17 Oct, 2019"
},
{
"code": null,
"e": 364,
"s": 53,
"text": "The DOM Input Radio disabled Property is used to set or return whether the Radio Button must be disabled or not. A disabled Radio Button is un-clickable and unusable. It is a boolean attribute and used to reflect the HTML Disabled attribute. It is usually rendered in grey color by default in all the Browsers."
},
{
"code": null,
"e": 372,
"s": 364,
"text": "Syntax:"
},
{
"code": null,
"e": 426,
"s": 372,
"text": "It returns the disabled property.radioObject.disabled"
},
{
"code": null,
"e": 447,
"s": 426,
"text": "radioObject.disabled"
},
{
"code": null,
"e": 521,
"s": 447,
"text": "It is used to set the disabled property.radioObject.disabled = true|false"
},
{
"code": null,
"e": 555,
"s": 521,
"text": "radioObject.disabled = true|false"
},
{
"code": null,
"e": 572,
"s": 555,
"text": "Property Values:"
},
{
"code": null,
"e": 630,
"s": 572,
"text": "true: It defines that the Input Radio Button is disabled."
},
{
"code": null,
"e": 711,
"s": 630,
"text": "False: It has a default value. It defines that the Radio Button is not disabled."
},
{
"code": null,
"e": 811,
"s": 711,
"text": "Return Value: It returns a boolean value which represents that the Radio Button is disabled or not."
},
{
"code": null,
"e": 875,
"s": 811,
"text": "Example-1: This Example illustrates how to return the Property."
},
{
"code": "<!DOCTYPE html><html> <head> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1> GeeksforGeeks </h1> <h2> HTML DOM Input Radio Disabled Property </h2> <form id=\"myGeeks\"> Radio Button: <input type=\"radio\" checked=true id=\"radioID\" value=\"Geeks_radio\" name=\"Geek_radio\" disabled> <br> <br> </form> <button onclick=\"GFG()\"> Click! </button> <p id=\"GFG\" style=\"font-size:25px; color:green;\"> </p> <script> function GFG() { // Accessing input element // type=\"radio\" var x = document.getElementById( \"radioID\").disabled; document.getElementById( \"GFG\").innerHTML = x; } </script> </body> </html>",
"e": 1862,
"s": 875,
"text": null
},
{
"code": null,
"e": 1896,
"s": 1862,
"text": "Output:Before Clicking On Button:"
},
{
"code": null,
"e": 1923,
"s": 1896,
"text": "After Clicking On Button :"
},
{
"code": null,
"e": 1993,
"s": 1923,
"text": "Example-2: This Example illustrates how to set the Disabled Property."
},
{
"code": "<!DOCTYPE html><html> <head> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1> GeeksforGeeks </h1> <h2> HTML DOM Input Radio Disabled Property </h2> <form id=\"myGeeks\"> Radio Button: <input type=\"radio\" checked=true id=\"radioID\" value=\"Geeks_radio\" name=\"Geek_radio\" disabled> <br> <br> </form> <button onclick=\"GFG()\"> Click! </button> <p id=\"GFG\" style=\"font-size:25px; color:green;\"> </p> <script> function GFG() { // Accessing input element // type=\"radio\" var x = document.getElementById( \"radioID\").disabled = \"false\"; document.getElementById( \"GFG\").innerHTML = x; } </script> </body> </html>",
"e": 2990,
"s": 1993,
"text": null
},
{
"code": null,
"e": 3025,
"s": 2990,
"text": "Output:Before Clicking On Button :"
},
{
"code": null,
"e": 3052,
"s": 3025,
"text": "After Clicking On Button :"
},
{
"code": null,
"e": 3149,
"s": 3052,
"text": "Supported Browsers: The browser supported by DOM input Radio disabled property are listed below:"
},
{
"code": null,
"e": 3163,
"s": 3149,
"text": "Google Chrome"
},
{
"code": null,
"e": 3188,
"s": 3163,
"text": "Internet Explorer 10.0 +"
},
{
"code": null,
"e": 3196,
"s": 3188,
"text": "Firefox"
},
{
"code": null,
"e": 3202,
"s": 3196,
"text": "Opera"
},
{
"code": null,
"e": 3209,
"s": 3202,
"text": "Safari"
},
{
"code": null,
"e": 3223,
"s": 3209,
"text": "shubham_singh"
},
{
"code": null,
"e": 3232,
"s": 3223,
"text": "HTML-DOM"
},
{
"code": null,
"e": 3237,
"s": 3232,
"text": "HTML"
},
{
"code": null,
"e": 3254,
"s": 3237,
"text": "Web Technologies"
},
{
"code": null,
"e": 3259,
"s": 3254,
"text": "HTML"
},
{
"code": null,
"e": 3357,
"s": 3259,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3405,
"s": 3357,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 3429,
"s": 3405,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 3479,
"s": 3429,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 3516,
"s": 3479,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 3544,
"s": 3516,
"text": "HTTP headers | Content-Type"
},
{
"code": null,
"e": 3577,
"s": 3544,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3638,
"s": 3577,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3681,
"s": 3638,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 3753,
"s": 3681,
"text": "Differences between Functional Components and Class Components in React"
}
] |
How to Fix: module ‘pandas’ has no attribute ‘dataframe’
|
19 Dec, 2021
In this article, we are going to see how to fix errors while creating dataframe ” module ‘pandas’ has no attribute ‘dataframe’”.
To create dataframe we need to use DataFrame(). If we use dataframe it will throw an error because there is no dataframe attribute in pandas. The method is DataFrame(). We need to pass any dictionary as an argument. Since the dictionary has a key, value pairs we can pass it as an argument. Dataframe considers keys as attributes and pairs as tuples. Let us see why we get errors while creating a dataframe.
Python3
import pandas as pd data = {"id": [1, 2, 3], "name": ["karthik", "nikhil", "bhagi"]} df = pd.dataframe(data)print(df)
Output:
To fix the above error we need to use DataFrame instead of dataframe.
Python3
import pandas as pd data = {"id": [1, 2, 3], "name": ["karthik", "nikhil", "bhagi"]} df = pd.DataFrame(data)df
Output:
id name
0 1 karthik
1 2 nikhil
2 3 bhagi
In this way, we can fix the module ‘pandas’ has no attribute ‘dataframe’ error .
Picked
Python How-to-fix
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Dec, 2021"
},
{
"code": null,
"e": 157,
"s": 28,
"text": "In this article, we are going to see how to fix errors while creating dataframe ” module ‘pandas’ has no attribute ‘dataframe’”."
},
{
"code": null,
"e": 565,
"s": 157,
"text": "To create dataframe we need to use DataFrame(). If we use dataframe it will throw an error because there is no dataframe attribute in pandas. The method is DataFrame(). We need to pass any dictionary as an argument. Since the dictionary has a key, value pairs we can pass it as an argument. Dataframe considers keys as attributes and pairs as tuples. Let us see why we get errors while creating a dataframe."
},
{
"code": null,
"e": 573,
"s": 565,
"text": "Python3"
},
{
"code": "import pandas as pd data = {\"id\": [1, 2, 3], \"name\": [\"karthik\", \"nikhil\", \"bhagi\"]} df = pd.dataframe(data)print(df)",
"e": 700,
"s": 573,
"text": null
},
{
"code": null,
"e": 708,
"s": 700,
"text": "Output:"
},
{
"code": null,
"e": 778,
"s": 708,
"text": "To fix the above error we need to use DataFrame instead of dataframe."
},
{
"code": null,
"e": 786,
"s": 778,
"text": "Python3"
},
{
"code": "import pandas as pd data = {\"id\": [1, 2, 3], \"name\": [\"karthik\", \"nikhil\", \"bhagi\"]} df = pd.DataFrame(data)df",
"e": 906,
"s": 786,
"text": null
},
{
"code": null,
"e": 914,
"s": 906,
"text": "Output:"
},
{
"code": null,
"e": 992,
"s": 914,
"text": "id name\n0 1 karthik\n1 2 nikhil\n2 3 bhagi"
},
{
"code": null,
"e": 1074,
"s": 992,
"text": "In this way, we can fix the module ‘pandas’ has no attribute ‘dataframe’ error ."
},
{
"code": null,
"e": 1081,
"s": 1074,
"text": "Picked"
},
{
"code": null,
"e": 1099,
"s": 1081,
"text": "Python How-to-fix"
},
{
"code": null,
"e": 1113,
"s": 1099,
"text": "Python-pandas"
},
{
"code": null,
"e": 1120,
"s": 1113,
"text": "Python"
}
] |
set vs unordered_set in C++ STL
|
13 Jun, 2022
Pre-requisite : set in C++, unordered_set in C++ Differences :
| set | unordered_set
---------------------------------------------------------
Ordering | increasing order | no ordering
| (by default) |
Implementation | Self balancing BST | Hash Table
| like Red-Black Tree |
search time | log(n) | O(1) -> Average
| | O(n) -> Worst Case
Insertion time | log(n) + Rebalance | Same as search
Deletion time | log(n) + Rebalance | Same as search
Use set when
We need ordered data.
We would have to print/access the data (in sorted order).
We need predecessor/successor of elements.
Since set is ordered, we can use functions like binary_search(), lower_bound() and upper_bound() on set elements. These functions cannot be used on unordered_set().
See advantages of BST over Hash Table for more cases.
Use unordered_set when
We need to keep a set of distinct elements and no ordering is required.
We need single element access i.e. no traversal.
Examples:
set:
Input : 1, 8, 2, 5, 3, 9
Output : 1, 2, 3, 5, 8, 9
Unordered_set:
Input : 1, 8, 2, 5, 3, 9
Output : 9 3 1 8 2 5
If you want to look at implementation details of set and unordered_set in c++ STL, see Set Vs Map. Set allows to traverse elements in sorted order whereas Unordered_set doesn’t allow to traverse elements in sorted order.
CPP
// Program to print elements of set#include <bits/stdc++.h>using namespace std; int main(){ set<int> s; s.insert(5); s.insert(1); s.insert(6); s.insert(3); s.insert(7); s.insert(2); cout << "Elements of set in sorted order: \n"; for (auto it : s) cout << it << " "; return 0;}
Elements of set in sorted order:
1 2 3 5 6 7
CPP
// Program to print elements of set#include <bits/stdc++.h>using namespace std; int main(){ unordered_set<int> s; s.insert(5); s.insert(1); s.insert(6); s.insert(3); s.insert(7); s.insert(2); cout << "Elements of unordered_set: \n"; for (auto it : s) cout << it << " "; return 0;}
Elements of unordered_set:
2 7 5 1 6 3
Predecessor/Successor in Set: Set can be modified to find predecessor or successor whereas Unordered_set doesn’t allow to find predecessor/Successor.
CPP
// Program to print inorder predecessor and inorder successor#include <bits/stdc++.h>using namespace std; set<int> s; void inorderPredecessor(int key){ if (s.find(key) == s.end()) { cout << "Key doesn't exist\n"; return; } set<int>::iterator it; it = s.find(key); // get iterator of key // If iterator is at first position // Then, it doesn't have predecessor if (it == s.begin()) { cout << "No predecessor\n"; return; } --it; // get previous element cout << "predecessor of " << key << " is="; cout << *(it) << "\n";} void inorderSuccessor(int key){ if (s.find(key) == s.end()) { cout << "Key doesn't exist\n"; return; } set<int>::iterator it; it = s.find(key); // get iterator of key ++it; // get next element // Iterator points to NULL (Element does // not exist) if (it == s.end()) { cout << "No successor\n"; return; } cout << "successor of " << key << " is="; cout << *(it) << "\n";} int main(){ s.insert(1); s.insert(5); s.insert(2); s.insert(9); s.insert(8); inorderPredecessor(5); inorderPredecessor(1); inorderPredecessor(8); inorderSuccessor(5); inorderSuccessor(2); inorderSuccessor(9); return 0;}
predecessor of 5 is=2
No predecessor
predecessor of 8 is=5
successor of 5 is=8
successor of 2 is=5
No successor
Let us see the differences in a tabular form -:
mayank007rawa
cpp-set
cpp-unordered_set
STL
Binary Search Tree
C++
Difference Between
Hash
Hash
Binary Search Tree
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n13 Jun, 2022"
},
{
"code": null,
"e": 118,
"s": 54,
"text": "Pre-requisite : set in C++, unordered_set in C++ Differences : "
},
{
"code": null,
"e": 667,
"s": 118,
"text": " | set | unordered_set\n---------------------------------------------------------\nOrdering | increasing order | no ordering\n | (by default) |\n\nImplementation | Self balancing BST | Hash Table\n | like Red-Black Tree | \n\nsearch time | log(n) | O(1) -> Average \n | | O(n) -> Worst Case\n\nInsertion time | log(n) + Rebalance | Same as search\n \nDeletion time | log(n) + Rebalance | Same as search"
},
{
"code": null,
"e": 680,
"s": 667,
"text": "Use set when"
},
{
"code": null,
"e": 702,
"s": 680,
"text": "We need ordered data."
},
{
"code": null,
"e": 760,
"s": 702,
"text": "We would have to print/access the data (in sorted order)."
},
{
"code": null,
"e": 803,
"s": 760,
"text": "We need predecessor/successor of elements."
},
{
"code": null,
"e": 968,
"s": 803,
"text": "Since set is ordered, we can use functions like binary_search(), lower_bound() and upper_bound() on set elements. These functions cannot be used on unordered_set()."
},
{
"code": null,
"e": 1022,
"s": 968,
"text": "See advantages of BST over Hash Table for more cases."
},
{
"code": null,
"e": 1045,
"s": 1022,
"text": "Use unordered_set when"
},
{
"code": null,
"e": 1117,
"s": 1045,
"text": "We need to keep a set of distinct elements and no ordering is required."
},
{
"code": null,
"e": 1166,
"s": 1117,
"text": "We need single element access i.e. no traversal."
},
{
"code": null,
"e": 1176,
"s": 1166,
"text": "Examples:"
},
{
"code": null,
"e": 1299,
"s": 1176,
"text": "set:\nInput : 1, 8, 2, 5, 3, 9\nOutput : 1, 2, 3, 5, 8, 9\n\nUnordered_set:\nInput : 1, 8, 2, 5, 3, 9\nOutput : 9 3 1 8 2 5 "
},
{
"code": null,
"e": 1521,
"s": 1299,
"text": "If you want to look at implementation details of set and unordered_set in c++ STL, see Set Vs Map. Set allows to traverse elements in sorted order whereas Unordered_set doesn’t allow to traverse elements in sorted order. "
},
{
"code": null,
"e": 1525,
"s": 1521,
"text": "CPP"
},
{
"code": "// Program to print elements of set#include <bits/stdc++.h>using namespace std; int main(){ set<int> s; s.insert(5); s.insert(1); s.insert(6); s.insert(3); s.insert(7); s.insert(2); cout << \"Elements of set in sorted order: \\n\"; for (auto it : s) cout << it << \" \"; return 0;}",
"e": 1841,
"s": 1525,
"text": null
},
{
"code": null,
"e": 1887,
"s": 1841,
"text": "Elements of set in sorted order: \n1 2 3 5 6 7"
},
{
"code": null,
"e": 1891,
"s": 1887,
"text": "CPP"
},
{
"code": "// Program to print elements of set#include <bits/stdc++.h>using namespace std; int main(){ unordered_set<int> s; s.insert(5); s.insert(1); s.insert(6); s.insert(3); s.insert(7); s.insert(2); cout << \"Elements of unordered_set: \\n\"; for (auto it : s) cout << it << \" \"; return 0;}",
"e": 2211,
"s": 1891,
"text": null
},
{
"code": null,
"e": 2251,
"s": 2211,
"text": "Elements of unordered_set: \n2 7 5 1 6 3"
},
{
"code": null,
"e": 2402,
"s": 2251,
"text": "Predecessor/Successor in Set: Set can be modified to find predecessor or successor whereas Unordered_set doesn’t allow to find predecessor/Successor. "
},
{
"code": null,
"e": 2406,
"s": 2402,
"text": "CPP"
},
{
"code": "// Program to print inorder predecessor and inorder successor#include <bits/stdc++.h>using namespace std; set<int> s; void inorderPredecessor(int key){ if (s.find(key) == s.end()) { cout << \"Key doesn't exist\\n\"; return; } set<int>::iterator it; it = s.find(key); // get iterator of key // If iterator is at first position // Then, it doesn't have predecessor if (it == s.begin()) { cout << \"No predecessor\\n\"; return; } --it; // get previous element cout << \"predecessor of \" << key << \" is=\"; cout << *(it) << \"\\n\";} void inorderSuccessor(int key){ if (s.find(key) == s.end()) { cout << \"Key doesn't exist\\n\"; return; } set<int>::iterator it; it = s.find(key); // get iterator of key ++it; // get next element // Iterator points to NULL (Element does // not exist) if (it == s.end()) { cout << \"No successor\\n\"; return; } cout << \"successor of \" << key << \" is=\"; cout << *(it) << \"\\n\";} int main(){ s.insert(1); s.insert(5); s.insert(2); s.insert(9); s.insert(8); inorderPredecessor(5); inorderPredecessor(1); inorderPredecessor(8); inorderSuccessor(5); inorderSuccessor(2); inorderSuccessor(9); return 0;}",
"e": 3684,
"s": 2406,
"text": null
},
{
"code": null,
"e": 3796,
"s": 3684,
"text": "predecessor of 5 is=2\nNo predecessor\npredecessor of 8 is=5\nsuccessor of 5 is=8\nsuccessor of 2 is=5\nNo successor"
},
{
"code": null,
"e": 3844,
"s": 3796,
"text": "Let us see the differences in a tabular form -:"
},
{
"code": null,
"e": 3858,
"s": 3844,
"text": "mayank007rawa"
},
{
"code": null,
"e": 3866,
"s": 3858,
"text": "cpp-set"
},
{
"code": null,
"e": 3884,
"s": 3866,
"text": "cpp-unordered_set"
},
{
"code": null,
"e": 3888,
"s": 3884,
"text": "STL"
},
{
"code": null,
"e": 3907,
"s": 3888,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 3911,
"s": 3907,
"text": "C++"
},
{
"code": null,
"e": 3930,
"s": 3911,
"text": "Difference Between"
},
{
"code": null,
"e": 3935,
"s": 3930,
"text": "Hash"
},
{
"code": null,
"e": 3940,
"s": 3935,
"text": "Hash"
},
{
"code": null,
"e": 3959,
"s": 3940,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 3963,
"s": 3959,
"text": "STL"
},
{
"code": null,
"e": 3967,
"s": 3963,
"text": "CPP"
}
] |
Instruction Level Parallelism
|
02 Feb, 2022
Prerequisite – Introduction to Parallel Computing
Instruction Level Parallelism (ILP) is used to refer to the architecture in which multiple operations can be performed parallelly in a particular process, with its own set of resources – address space, registers, identifiers, state, program counters. It refers to the compiler design techniques and processors designed to execute operations, like memory load and store, integer addition, float multiplication, in parallel to improve the performance of the processors. Examples of architectures that exploit ILP are VLIWs, Superscalar Architecture.
ILP processors have the same execution hardware as RISC processors. The machines without ILP have complex hardware which is hard to implement. A typical ILP allows multiple-cycle operations to be pipelined.
Example :Suppose, 4 operations can be carried out in single clock cycle. So there will be 4 functional units, each attached to one of the operations, branch unit, and common register file in the ILP execution hardware. The sub-operations that can be performed by the functional units are Integer ALU, Integer Multiplication, Floating Point Operations, Load, Store. Let the respective latencies be 1, 2, 3, 2, 1.
Let the sequence of instructions be –
y1 = x1*1010y2 = x2*1100z1 = y1+0010z2 = y2+0101t1 = t1+1p = q*1000clr = clr+0010r = r+0001
y1 = x1*1010
y2 = x2*1100
z1 = y1+0010
z2 = y2+0101
t1 = t1+1
p = q*1000
clr = clr+0010
r = r+0001
Sequential record of execution vs. Instruction-level Parallel record of execution –
Fig. a shows sequential execution of operations.Fig. b shows use of ILP in improving performance of the processor.
The ‘nop’s or the ‘no operations’ in the above diagram are used to show idle time of processor. Since latency of floating-point operations is 3, hence multiplications take 3 cycles and processor has to remain idle for that time period. However, in Fig. b processor can utilize those nop’s to execute other operations while previous ones are still being executed.
While in sequential execution, each cycle has only one operation being executed, in processor with ILP, cycle 1 has 4 operations, cycle 2 has 2 operations. In cycle 3 there is ‘nop’ as the next two operations are dependent on first two multiplication operations. The sequential processor takes 12 cycles to execute 8 operations whereas processor with ILP takes only 4 cycles.Architecture :Instruction Level Parallelism is achieved when multiple operations are performed in single cycle, that is done by either executing them simultaneously or by utilizing gaps between two successive operations that is created due to the latencies.
Now, the decision of when to execute an operation depends largely on the compiler rather than hardware. However, extent of compiler’s control depends on type of ILP architecture where information regarding parallelism given by compiler to hardware via program varies. The classification of ILP architectures can be done in the following ways –
Sequential Architecture :Here, program is not expected to explicitly convey any information regarding parallelism to hardware, like superscalar architecture.Dependence Architectures :Here, program explicitly mentions information regarding dependencies between operations like dataflow architecture.Independence Architecture :Here, program gives information regarding which operations are independent of each other so that they can be executed instead of the ‘nop’s.
Sequential Architecture :Here, program is not expected to explicitly convey any information regarding parallelism to hardware, like superscalar architecture.
Dependence Architectures :Here, program explicitly mentions information regarding dependencies between operations like dataflow architecture.
Independence Architecture :Here, program gives information regarding which operations are independent of each other so that they can be executed instead of the ‘nop’s.
In order to apply ILP, compiler and hardware must determine data dependencies, independent operations, and scheduling of these independent operations, assignment of functional unit, and register to store data.
vaibhavsinghtanwar
Computer Organization & Architecture
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n02 Feb, 2022"
},
{
"code": null,
"e": 103,
"s": 53,
"text": "Prerequisite – Introduction to Parallel Computing"
},
{
"code": null,
"e": 651,
"s": 103,
"text": "Instruction Level Parallelism (ILP) is used to refer to the architecture in which multiple operations can be performed parallelly in a particular process, with its own set of resources – address space, registers, identifiers, state, program counters. It refers to the compiler design techniques and processors designed to execute operations, like memory load and store, integer addition, float multiplication, in parallel to improve the performance of the processors. Examples of architectures that exploit ILP are VLIWs, Superscalar Architecture."
},
{
"code": null,
"e": 858,
"s": 651,
"text": "ILP processors have the same execution hardware as RISC processors. The machines without ILP have complex hardware which is hard to implement. A typical ILP allows multiple-cycle operations to be pipelined."
},
{
"code": null,
"e": 1270,
"s": 858,
"text": "Example :Suppose, 4 operations can be carried out in single clock cycle. So there will be 4 functional units, each attached to one of the operations, branch unit, and common register file in the ILP execution hardware. The sub-operations that can be performed by the functional units are Integer ALU, Integer Multiplication, Floating Point Operations, Load, Store. Let the respective latencies be 1, 2, 3, 2, 1."
},
{
"code": null,
"e": 1308,
"s": 1270,
"text": "Let the sequence of instructions be –"
},
{
"code": null,
"e": 1400,
"s": 1308,
"text": "y1 = x1*1010y2 = x2*1100z1 = y1+0010z2 = y2+0101t1 = t1+1p = q*1000clr = clr+0010r = r+0001"
},
{
"code": null,
"e": 1413,
"s": 1400,
"text": "y1 = x1*1010"
},
{
"code": null,
"e": 1426,
"s": 1413,
"text": "y2 = x2*1100"
},
{
"code": null,
"e": 1439,
"s": 1426,
"text": "z1 = y1+0010"
},
{
"code": null,
"e": 1452,
"s": 1439,
"text": "z2 = y2+0101"
},
{
"code": null,
"e": 1462,
"s": 1452,
"text": "t1 = t1+1"
},
{
"code": null,
"e": 1473,
"s": 1462,
"text": "p = q*1000"
},
{
"code": null,
"e": 1488,
"s": 1473,
"text": "clr = clr+0010"
},
{
"code": null,
"e": 1499,
"s": 1488,
"text": "r = r+0001"
},
{
"code": null,
"e": 1583,
"s": 1499,
"text": "Sequential record of execution vs. Instruction-level Parallel record of execution –"
},
{
"code": null,
"e": 1698,
"s": 1583,
"text": "Fig. a shows sequential execution of operations.Fig. b shows use of ILP in improving performance of the processor."
},
{
"code": null,
"e": 2061,
"s": 1698,
"text": "The ‘nop’s or the ‘no operations’ in the above diagram are used to show idle time of processor. Since latency of floating-point operations is 3, hence multiplications take 3 cycles and processor has to remain idle for that time period. However, in Fig. b processor can utilize those nop’s to execute other operations while previous ones are still being executed."
},
{
"code": null,
"e": 2694,
"s": 2061,
"text": "While in sequential execution, each cycle has only one operation being executed, in processor with ILP, cycle 1 has 4 operations, cycle 2 has 2 operations. In cycle 3 there is ‘nop’ as the next two operations are dependent on first two multiplication operations. The sequential processor takes 12 cycles to execute 8 operations whereas processor with ILP takes only 4 cycles.Architecture :Instruction Level Parallelism is achieved when multiple operations are performed in single cycle, that is done by either executing them simultaneously or by utilizing gaps between two successive operations that is created due to the latencies."
},
{
"code": null,
"e": 3038,
"s": 2694,
"text": "Now, the decision of when to execute an operation depends largely on the compiler rather than hardware. However, extent of compiler’s control depends on type of ILP architecture where information regarding parallelism given by compiler to hardware via program varies. The classification of ILP architectures can be done in the following ways –"
},
{
"code": null,
"e": 3504,
"s": 3038,
"text": "Sequential Architecture :Here, program is not expected to explicitly convey any information regarding parallelism to hardware, like superscalar architecture.Dependence Architectures :Here, program explicitly mentions information regarding dependencies between operations like dataflow architecture.Independence Architecture :Here, program gives information regarding which operations are independent of each other so that they can be executed instead of the ‘nop’s."
},
{
"code": null,
"e": 3662,
"s": 3504,
"text": "Sequential Architecture :Here, program is not expected to explicitly convey any information regarding parallelism to hardware, like superscalar architecture."
},
{
"code": null,
"e": 3804,
"s": 3662,
"text": "Dependence Architectures :Here, program explicitly mentions information regarding dependencies between operations like dataflow architecture."
},
{
"code": null,
"e": 3972,
"s": 3804,
"text": "Independence Architecture :Here, program gives information regarding which operations are independent of each other so that they can be executed instead of the ‘nop’s."
},
{
"code": null,
"e": 4182,
"s": 3972,
"text": "In order to apply ILP, compiler and hardware must determine data dependencies, independent operations, and scheduling of these independent operations, assignment of functional unit, and register to store data."
},
{
"code": null,
"e": 4201,
"s": 4182,
"text": "vaibhavsinghtanwar"
},
{
"code": null,
"e": 4238,
"s": 4201,
"text": "Computer Organization & Architecture"
}
] |
How to Enable Authentication on MongoDB ?
|
21 Jul, 2021
Authentication is enforced when access control is enabled on a MongoDB deployment, requiring users to identify themselves. Users can only conduct activities that are defined by their roles when visiting a MongoDB deployment with access control enabled.
The following tutorial utilizes the default authentication approach to provide access control on a solo mongo instance. See Authentication Techniques for a list of all supported authentication mechanisms.
If access control is enabled, make sure the admin database has a user with the userAdmin or userAdminAnyDatabase roles. This user has the ability to manage users and roles, including the ability to create new users, give or revoke roles to existing users, and create or change custom roles.
Note: The instance of MongoDB uses port 27017 as well as the location of data /var/lib/mongodb. The example presumes the existence of the data directory, i.e., /var/lib/mongodb. And specify a different data directory as appropriate.
To access or alter the database, MongoDB does not require a login or password by default. Mandatory authentication should be enabled and configured.
Follow the commands mentioned below to enable Authentication:
Step 1: Open a Mongo Shell
mongo
Step 2: The database binstar must be able to read and write to the repository. To establish an administrator user and a service user, run the following commands in the MongoDB shell:
use admin
Step 3: To manage database users, create an administrative user:
db.createUser({user:'siteUserAdmin', pwd: '<secure password #1>',
roles:['userAdminAnyDatabase']})
Step 4: To validate the password, log in as that user:
db.auth('siteUserAdmin', '<secure password #1>')
Step 5: Create a Repository service user:
db.createUser({user:'spandan', pwd: '<secure password #2>',
roles:[{db:'binstar', role:'readWrite'}]})
Step 6: In MongoDB, enable required authentication:
Add the auth key to /etc/mongod.conf if you’re using the classic MongoDB configuration format:
auth=true
Add the security.authorization key to /etc/mongod.conf if you’re using the current MongoDB configuration format:
security:
authorization: enabled
Step 7: To reload the settings, restart MongoDB:
sudo service mongod restart
Step 8: Set the MONGO URL option in the Repository configuration file to mongodb:/username:password@hostname>.
Step 9: Restart Repository after modifying the configuration file to see the changes take effect.
It is possible to create users before or after access control is activated. MongoDB supports a localhost exception if you activate access control before establishing any user. This allows you to establish a user administrator in the admin database. Once a user has been created, you must log in as the user administrator to add other users as needed.
Picked
MongoDB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to connect MongoDB with ReactJS ?
MongoDB - limit() Method
MongoDB - sort() Method
MongoDB - FindOne() Method
MongoDB updateOne() Method - db.Collection.updateOne()
MongoDB - Compound Indexes
MongoDB - Regex
MongoDB updateMany() Method - db.Collection.updateMany()
MongoDB Cursor
Spring Boot - CRUD Operations using MongoDB
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Jul, 2021"
},
{
"code": null,
"e": 281,
"s": 28,
"text": "Authentication is enforced when access control is enabled on a MongoDB deployment, requiring users to identify themselves. Users can only conduct activities that are defined by their roles when visiting a MongoDB deployment with access control enabled."
},
{
"code": null,
"e": 486,
"s": 281,
"text": "The following tutorial utilizes the default authentication approach to provide access control on a solo mongo instance. See Authentication Techniques for a list of all supported authentication mechanisms."
},
{
"code": null,
"e": 777,
"s": 486,
"text": "If access control is enabled, make sure the admin database has a user with the userAdmin or userAdminAnyDatabase roles. This user has the ability to manage users and roles, including the ability to create new users, give or revoke roles to existing users, and create or change custom roles."
},
{
"code": null,
"e": 1010,
"s": 777,
"text": "Note: The instance of MongoDB uses port 27017 as well as the location of data /var/lib/mongodb. The example presumes the existence of the data directory, i.e., /var/lib/mongodb. And specify a different data directory as appropriate."
},
{
"code": null,
"e": 1159,
"s": 1010,
"text": "To access or alter the database, MongoDB does not require a login or password by default. Mandatory authentication should be enabled and configured."
},
{
"code": null,
"e": 1221,
"s": 1159,
"text": "Follow the commands mentioned below to enable Authentication:"
},
{
"code": null,
"e": 1249,
"s": 1221,
"text": "Step 1: Open a Mongo Shell "
},
{
"code": null,
"e": 1255,
"s": 1249,
"text": "mongo"
},
{
"code": null,
"e": 1438,
"s": 1255,
"text": "Step 2: The database binstar must be able to read and write to the repository. To establish an administrator user and a service user, run the following commands in the MongoDB shell:"
},
{
"code": null,
"e": 1448,
"s": 1438,
"text": "use admin"
},
{
"code": null,
"e": 1514,
"s": 1448,
"text": "Step 3: To manage database users, create an administrative user: "
},
{
"code": null,
"e": 1629,
"s": 1514,
"text": "db.createUser({user:'siteUserAdmin', pwd: '<secure password #1>', \n roles:['userAdminAnyDatabase']})"
},
{
"code": null,
"e": 1684,
"s": 1629,
"text": "Step 4: To validate the password, log in as that user:"
},
{
"code": null,
"e": 1733,
"s": 1684,
"text": "db.auth('siteUserAdmin', '<secure password #1>')"
},
{
"code": null,
"e": 1775,
"s": 1733,
"text": "Step 5: Create a Repository service user:"
},
{
"code": null,
"e": 1894,
"s": 1775,
"text": "db.createUser({user:'spandan', pwd: '<secure password #2>', \n roles:[{db:'binstar', role:'readWrite'}]})"
},
{
"code": null,
"e": 1947,
"s": 1894,
"text": "Step 6: In MongoDB, enable required authentication: "
},
{
"code": null,
"e": 2042,
"s": 1947,
"text": "Add the auth key to /etc/mongod.conf if you’re using the classic MongoDB configuration format:"
},
{
"code": null,
"e": 2052,
"s": 2042,
"text": "auth=true"
},
{
"code": null,
"e": 2165,
"s": 2052,
"text": "Add the security.authorization key to /etc/mongod.conf if you’re using the current MongoDB configuration format:"
},
{
"code": null,
"e": 2202,
"s": 2165,
"text": "security:\n authorization: enabled"
},
{
"code": null,
"e": 2252,
"s": 2202,
"text": "Step 7: To reload the settings, restart MongoDB: "
},
{
"code": null,
"e": 2280,
"s": 2252,
"text": "sudo service mongod restart"
},
{
"code": null,
"e": 2392,
"s": 2280,
"text": "Step 8: Set the MONGO URL option in the Repository configuration file to mongodb:/username:password@hostname>. "
},
{
"code": null,
"e": 2490,
"s": 2392,
"text": "Step 9: Restart Repository after modifying the configuration file to see the changes take effect."
},
{
"code": null,
"e": 2841,
"s": 2490,
"text": "It is possible to create users before or after access control is activated. MongoDB supports a localhost exception if you activate access control before establishing any user. This allows you to establish a user administrator in the admin database. Once a user has been created, you must log in as the user administrator to add other users as needed."
},
{
"code": null,
"e": 2848,
"s": 2841,
"text": "Picked"
},
{
"code": null,
"e": 2856,
"s": 2848,
"text": "MongoDB"
},
{
"code": null,
"e": 2954,
"s": 2856,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2992,
"s": 2954,
"text": "How to connect MongoDB with ReactJS ?"
},
{
"code": null,
"e": 3017,
"s": 2992,
"text": "MongoDB - limit() Method"
},
{
"code": null,
"e": 3041,
"s": 3017,
"text": "MongoDB - sort() Method"
},
{
"code": null,
"e": 3068,
"s": 3041,
"text": "MongoDB - FindOne() Method"
},
{
"code": null,
"e": 3123,
"s": 3068,
"text": "MongoDB updateOne() Method - db.Collection.updateOne()"
},
{
"code": null,
"e": 3150,
"s": 3123,
"text": "MongoDB - Compound Indexes"
},
{
"code": null,
"e": 3166,
"s": 3150,
"text": "MongoDB - Regex"
},
{
"code": null,
"e": 3223,
"s": 3166,
"text": "MongoDB updateMany() Method - db.Collection.updateMany()"
},
{
"code": null,
"e": 3238,
"s": 3223,
"text": "MongoDB Cursor"
}
] |
Find three closest elements from given three sorted arrays
|
24 Sep, 2021
Given three sorted arrays A[], B[] and C[], find 3 elements i, j and k from A, B and C respectively such that max(abs(A[i] – B[j]), abs(B[j] – C[k]), abs(C[k] – A[i])) is minimized. Here abs() indicates absolute value.
Example :
Input: A[] = {1, 4, 10}
B[] = {2, 15, 20}
C[] = {10, 12}
Output: 10 15 10
10 from A, 15 from B and 10 from C
Input: A[] = {20, 24, 100}
B[] = {2, 19, 22, 79, 800}
C[] = {10, 12, 23, 24, 119}
Output: 24 22 23
24 from A, 22 from B and 23 from C
We strongly recommend you to minimize your browser and try this yourself first.
A Simple Solution is to run three nested loops to consider all triplets from A, B and C. Compute the value of max(abs(A[i] – B[j]), abs(B[j] – C[k]), abs(C[k] – A[i])) for every triplet and return minimum of all values. Time complexity of this solution is O(n3)
A Better Solution is to use Binary Search. 1) Iterate over all elements of A[], a) Binary search for element just smaller than or equal to in B[] and C[], and note the difference. 2) Repeat step 1 for B[] and C[]. 3) Return overall minimum.Time complexity of this solution is O(nLogn)
Efficient Solution Let ‘p’ be size of A[], ‘q’ be size of B[] and ‘r’ be size of C[]
1) Start with i=0, j=0 and k=0 (Three index variables for A,
B and C respectively)
// p, q and r are sizes of A[], B[] and C[] respectively.
2) Do following while i < p and j < q and k < r
a) Find min and maximum of A[i], B[j] and C[k]
b) Compute diff = max(X, Y, Z) - min(A[i], B[j], C[k]).
c) If new result is less than current result, change
it to the new result.
d) Increment the pointer of the array which contains
the minimum.
Note that we increment the pointer of the array which has the minimum because our goal is to decrease the difference. Increasing the maximum pointer increases the difference. Increase the second maximum pointer can potentially increase the difference.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find 3 elements such that max(abs(A[i]-B[j]), abs(B[j]-// C[k]), abs(C[k]-A[i])) is minimized. #include<bits/stdc++.h>using namespace std; void findClosest(int A[], int B[], int C[], int p, int q, int r){ int diff = INT_MAX; // Initialize min diff // Initialize result int res_i =0, res_j = 0, res_k = 0; // Traverse arrays int i=0,j=0,k=0; while (i < p && j < q && k < r) { // Find minimum and maximum of current three elements int minimum = min(A[i], min(B[j], C[k])); int maximum = max(A[i], max(B[j], C[k])); // Update result if current diff is less than the min // diff so far if (maximum-minimum < diff) { res_i = i, res_j = j, res_k = k; diff = maximum - minimum; } // We can't get less than 0 as values are absolute if (diff == 0) break; // Increment index of array with smallest value if (A[i] == minimum) i++; else if (B[j] == minimum) j++; else k++; } // Print result cout << A[res_i] << " " << B[res_j] << " " << C[res_k];} // Driver programint main(){ int A[] = {1, 4, 10}; int B[] = {2, 15, 20}; int C[] = {10, 12}; int p = sizeof A / sizeof A[0]; int q = sizeof B / sizeof B[0]; int r = sizeof C / sizeof C[0]; findClosest(A, B, C, p, q, r); return 0;}
// Java program to find 3 elements such// that max(abs(A[i]-B[j]), abs(B[j]-C[k]),// abs(C[k]-A[i])) is minimized.import java.io.*; class GFG { static void findClosest(int A[], int B[], int C[], int p, int q, int r) { int diff = Integer.MAX_VALUE; // Initialize min diff // Initialize result int res_i =0, res_j = 0, res_k = 0; // Traverse arrays int i = 0, j = 0, k = 0; while (i < p && j < q && k < r) { // Find minimum and maximum of current three elements int minimum = Math.min(A[i], Math.min(B[j], C[k])); int maximum = Math.max(A[i], Math.max(B[j], C[k])); // Update result if current diff is // less than the min diff so far if (maximum-minimum < diff) { res_i = i; res_j = j; res_k = k; diff = maximum - minimum; } // We can't get less than 0 // as values are absolute if (diff == 0) break; // Increment index of array // with smallest value if (A[i] == minimum) i++; else if (B[j] == minimum) j++; else k++; } // Print result System.out.println(A[res_i] + " " + B[res_j] + " " + C[res_k]); } // Driver code public static void main (String[] args) { int A[] = {1, 4, 10}; int B[] = {2, 15, 20}; int C[] = {10, 12}; int p = A.length; int q = B.length; int r = C.length; // Function calling findClosest(A, B, C, p, q, r); }} // This code is contributed by Ajit.
# Python program to find 3 elements such# that max(abs(A[i]-B[j]), abs(B[j]- C[k]),# abs(C[k]-A[i])) is minimized.import sys def findCloset(A, B, C, p, q, r): # Initialize min diff diff = sys.maxsize res_i = 0 res_j = 0 res_k = 0 # Traverse Array i = 0 j = 0 k = 0 while(i < p and j < q and k < r): # Find minimum and maximum of # current three elements minimum = min(A[i], min(B[j], C[k])) maximum = max(A[i], max(B[j], C[k])); # Update result if current diff is # less than the min diff so far if maximum-minimum < diff: res_i = i res_j = j res_k = k diff = maximum - minimum; # We can 't get less than 0 as # values are absolute if diff == 0: break # Increment index of array with # smallest value if A[i] == minimum: i = i+1 elif B[j] == minimum: j = j+1 else: k = k+1 # Print result print(A[res_i], " ", B[res_j], " ", C[res_k]) # Driver ProgramA = [1, 4, 10]B = [2, 15, 20]C = [10, 12] p = len(A)q = len(B)r = len(C) findCloset(A,B,C,p,q,r) # This code is contributed by Shrikant13.
// C# program to find 3 elements// such that max(abs(A[i]-B[j]),// abs(B[j]-C[k]), abs(C[k]-A[i]))// is minimized.using System; class GFG{ static void findClosest(int []A, int []B, int []C, int p, int q, int r) { // Initialize min diff int diff = int.MaxValue; // Initialize result int res_i = 0, res_j = 0, res_k = 0; // Traverse arrays int i = 0, j = 0, k = 0; while (i < p && j < q && k < r) { // Find minimum and maximum // of current three elements int minimum = Math.Min(A[i], Math.Min(B[j], C[k])); int maximum = Math.Max(A[i], Math.Max(B[j], C[k])); // Update result if current // diff is less than the min // diff so far if (maximum - minimum < diff) { res_i = i; res_j = j; res_k = k; diff = maximum - minimum; } // We can't get less than 0 // as values are absolute if (diff == 0) break; // Increment index of array // with smallest value if (A[i] == minimum) i++; else if (B[j] == minimum) j++; else k++; } // Print result Console.WriteLine(A[res_i] + " " + B[res_j] + " " + C[res_k]); } // Driver code public static void Main () { int []A = {1, 4, 10}; int []B = {2, 15, 20}; int []C = {10, 12}; int p = A.Length; int q = B.Length; int r = C.Length; // Function calling findClosest(A, B, C, p, q, r); }} // This code is contributed// by anuj_67.
<?php// PHP program to find 3 elements such// that max(abs(A[i]-B[j]), abs(B[j]-// C[k]), abs(C[k]-A[i])) is minimized. function findClosest($A, $B, $C, $p, $q, $r){ $diff = PHP_INT_MAX; // Initialize min diff // Initialize result $res_i = 0; $res_j = 0; $res_k = 0; // Traverse arrays $i = 0; $j = 0; $k = 0; while ($i < $p && $j < $q && $k < $r) { // Find minimum and maximum of // current three elements $minimum = min($A[$i], min($B[$j], $C[$k])); $maximum = max($A[$i], max($B[$j], $C[$k])); // Update result if current diff is // less than the min diff so far if ($maximum-$minimum < $diff) { $res_i = $i; $res_j = $j; $res_k = $k; $diff = $maximum - $minimum; } // We can't get less than 0 as // values are absolute if ($diff == 0) break; // Increment index of array with // smallest value if ($A[$i] == $minimum) $i++; else if ($B[$j] == $minimum) $j++; else $k++; } // Print result echo $A[$res_i] , " ", $B[$res_j], " ", $C[$res_k];} // Driver Code$A = array(1, 4, 10);$B = array(2, 15, 20);$C = array(10, 12); $p = sizeof($A);$q = sizeof($B);$r = sizeof($C); findClosest($A, $B, $C, $p, $q, $r); // This code is contributed by Sach_Code?>
<script> // JavaScript program to find 3 elements // such that max(abs(A[i]-B[j]), abs(B[j]- // C[k]), abs(C[k]-A[i])) is minimized. function findClosest(A, B, C, p, q, r) { var diff = Math.pow(10, 9); // Initialize min diff // Initialize result var res_i = 0, res_j = 0, res_k = 0; // Traverse arrays var i = 0, j = 0, k = 0; while (i < p && j < q && k < r) { // Find minimum and maximum of current three elements var minimum = Math.min(A[i], Math.min(B[j], C[k])); var maximum = Math.max(A[i], Math.max(B[j], C[k])); // Update result if current diff is less than the min // diff so far if (maximum - minimum < diff) { (res_i = i), (res_j = j), (res_k = k); diff = maximum - minimum; } // We can't get less than 0 as values are absolute if (diff == 0) break; // Increment index of array with smallest value if (A[i] == minimum) i++; else if (B[j] == minimum) j++; else k++; } // Print result document.write(A[res_i] + " " + B[res_j] + " " + C[res_k]); } // Driver program var A = [1, 4, 10]; var B = [2, 15, 20]; var C = [10, 12]; var p = A.length; var q = B.length; var r = C.length; findClosest(A, B, C, p, q, r); // This code is contributed by rdtank. </script>
Output:
10 15 10
Time complexity of this solution is O(p + q + r) where p, q and r are sizes of A[], B[] and C[] respectively.Thanks to Gaurav Ahirwar for suggesting the above solutions.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
shrikanth13
jit_t
vt_m
Sach_Code
paperba1l
rdtank
anantsingh2
sweetyty
Searching
Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Search, insert and delete in an unsorted array
Median of two sorted arrays of different sizes
Program to find largest element in an array
k largest(or smallest) elements in an array
Two Pointers Technique
Given an array of size n and a number k, find all elements that appear more than n/k times
Find the missing and repeating number
Search, insert and delete in a sorted array
Find the index of an array element in Java
Count number of occurrences (or frequency) in a sorted array
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n24 Sep, 2021"
},
{
"code": null,
"e": 273,
"s": 54,
"text": "Given three sorted arrays A[], B[] and C[], find 3 elements i, j and k from A, B and C respectively such that max(abs(A[i] – B[j]), abs(B[j] – C[k]), abs(C[k] – A[i])) is minimized. Here abs() indicates absolute value."
},
{
"code": null,
"e": 284,
"s": 273,
"text": "Example : "
},
{
"code": null,
"e": 556,
"s": 284,
"text": "Input: A[] = {1, 4, 10}\n B[] = {2, 15, 20}\n C[] = {10, 12}\nOutput: 10 15 10\n10 from A, 15 from B and 10 from C\n\nInput: A[] = {20, 24, 100}\n B[] = {2, 19, 22, 79, 800}\n C[] = {10, 12, 23, 24, 119}\nOutput: 24 22 23\n24 from A, 22 from B and 23 from C"
},
{
"code": null,
"e": 636,
"s": 556,
"text": "We strongly recommend you to minimize your browser and try this yourself first."
},
{
"code": null,
"e": 898,
"s": 636,
"text": "A Simple Solution is to run three nested loops to consider all triplets from A, B and C. Compute the value of max(abs(A[i] – B[j]), abs(B[j] – C[k]), abs(C[k] – A[i])) for every triplet and return minimum of all values. Time complexity of this solution is O(n3)"
},
{
"code": null,
"e": 1189,
"s": 898,
"text": "A Better Solution is to use Binary Search. 1) Iterate over all elements of A[], a) Binary search for element just smaller than or equal to in B[] and C[], and note the difference. 2) Repeat step 1 for B[] and C[]. 3) Return overall minimum.Time complexity of this solution is O(nLogn)"
},
{
"code": null,
"e": 1276,
"s": 1189,
"text": "Efficient Solution Let ‘p’ be size of A[], ‘q’ be size of B[] and ‘r’ be size of C[] "
},
{
"code": null,
"e": 1781,
"s": 1276,
"text": "1) Start with i=0, j=0 and k=0 (Three index variables for A,\n B and C respectively)\n\n// p, q and r are sizes of A[], B[] and C[] respectively.\n2) Do following while i < p and j < q and k < r\n a) Find min and maximum of A[i], B[j] and C[k]\n b) Compute diff = max(X, Y, Z) - min(A[i], B[j], C[k]).\n c) If new result is less than current result, change \n it to the new result.\n d) Increment the pointer of the array which contains \n the minimum."
},
{
"code": null,
"e": 2034,
"s": 1781,
"text": "Note that we increment the pointer of the array which has the minimum because our goal is to decrease the difference. Increasing the maximum pointer increases the difference. Increase the second maximum pointer can potentially increase the difference. "
},
{
"code": null,
"e": 2038,
"s": 2034,
"text": "C++"
},
{
"code": null,
"e": 2043,
"s": 2038,
"text": "Java"
},
{
"code": null,
"e": 2051,
"s": 2043,
"text": "Python3"
},
{
"code": null,
"e": 2054,
"s": 2051,
"text": "C#"
},
{
"code": null,
"e": 2058,
"s": 2054,
"text": "PHP"
},
{
"code": null,
"e": 2069,
"s": 2058,
"text": "Javascript"
},
{
"code": "// C++ program to find 3 elements such that max(abs(A[i]-B[j]), abs(B[j]-// C[k]), abs(C[k]-A[i])) is minimized. #include<bits/stdc++.h>using namespace std; void findClosest(int A[], int B[], int C[], int p, int q, int r){ int diff = INT_MAX; // Initialize min diff // Initialize result int res_i =0, res_j = 0, res_k = 0; // Traverse arrays int i=0,j=0,k=0; while (i < p && j < q && k < r) { // Find minimum and maximum of current three elements int minimum = min(A[i], min(B[j], C[k])); int maximum = max(A[i], max(B[j], C[k])); // Update result if current diff is less than the min // diff so far if (maximum-minimum < diff) { res_i = i, res_j = j, res_k = k; diff = maximum - minimum; } // We can't get less than 0 as values are absolute if (diff == 0) break; // Increment index of array with smallest value if (A[i] == minimum) i++; else if (B[j] == minimum) j++; else k++; } // Print result cout << A[res_i] << \" \" << B[res_j] << \" \" << C[res_k];} // Driver programint main(){ int A[] = {1, 4, 10}; int B[] = {2, 15, 20}; int C[] = {10, 12}; int p = sizeof A / sizeof A[0]; int q = sizeof B / sizeof B[0]; int r = sizeof C / sizeof C[0]; findClosest(A, B, C, p, q, r); return 0;}",
"e": 3441,
"s": 2069,
"text": null
},
{
"code": "// Java program to find 3 elements such// that max(abs(A[i]-B[j]), abs(B[j]-C[k]),// abs(C[k]-A[i])) is minimized.import java.io.*; class GFG { static void findClosest(int A[], int B[], int C[], int p, int q, int r) { int diff = Integer.MAX_VALUE; // Initialize min diff // Initialize result int res_i =0, res_j = 0, res_k = 0; // Traverse arrays int i = 0, j = 0, k = 0; while (i < p && j < q && k < r) { // Find minimum and maximum of current three elements int minimum = Math.min(A[i], Math.min(B[j], C[k])); int maximum = Math.max(A[i], Math.max(B[j], C[k])); // Update result if current diff is // less than the min diff so far if (maximum-minimum < diff) { res_i = i; res_j = j; res_k = k; diff = maximum - minimum; } // We can't get less than 0 // as values are absolute if (diff == 0) break; // Increment index of array // with smallest value if (A[i] == minimum) i++; else if (B[j] == minimum) j++; else k++; } // Print result System.out.println(A[res_i] + \" \" + B[res_j] + \" \" + C[res_k]); } // Driver code public static void main (String[] args) { int A[] = {1, 4, 10}; int B[] = {2, 15, 20}; int C[] = {10, 12}; int p = A.length; int q = B.length; int r = C.length; // Function calling findClosest(A, B, C, p, q, r); }} // This code is contributed by Ajit.",
"e": 5248,
"s": 3441,
"text": null
},
{
"code": "# Python program to find 3 elements such# that max(abs(A[i]-B[j]), abs(B[j]- C[k]),# abs(C[k]-A[i])) is minimized.import sys def findCloset(A, B, C, p, q, r): # Initialize min diff diff = sys.maxsize res_i = 0 res_j = 0 res_k = 0 # Traverse Array i = 0 j = 0 k = 0 while(i < p and j < q and k < r): # Find minimum and maximum of # current three elements minimum = min(A[i], min(B[j], C[k])) maximum = max(A[i], max(B[j], C[k])); # Update result if current diff is # less than the min diff so far if maximum-minimum < diff: res_i = i res_j = j res_k = k diff = maximum - minimum; # We can 't get less than 0 as # values are absolute if diff == 0: break # Increment index of array with # smallest value if A[i] == minimum: i = i+1 elif B[j] == minimum: j = j+1 else: k = k+1 # Print result print(A[res_i], \" \", B[res_j], \" \", C[res_k]) # Driver ProgramA = [1, 4, 10]B = [2, 15, 20]C = [10, 12] p = len(A)q = len(B)r = len(C) findCloset(A,B,C,p,q,r) # This code is contributed by Shrikant13.",
"e": 6475,
"s": 5248,
"text": null
},
{
"code": "// C# program to find 3 elements// such that max(abs(A[i]-B[j]),// abs(B[j]-C[k]), abs(C[k]-A[i]))// is minimized.using System; class GFG{ static void findClosest(int []A, int []B, int []C, int p, int q, int r) { // Initialize min diff int diff = int.MaxValue; // Initialize result int res_i = 0, res_j = 0, res_k = 0; // Traverse arrays int i = 0, j = 0, k = 0; while (i < p && j < q && k < r) { // Find minimum and maximum // of current three elements int minimum = Math.Min(A[i], Math.Min(B[j], C[k])); int maximum = Math.Max(A[i], Math.Max(B[j], C[k])); // Update result if current // diff is less than the min // diff so far if (maximum - minimum < diff) { res_i = i; res_j = j; res_k = k; diff = maximum - minimum; } // We can't get less than 0 // as values are absolute if (diff == 0) break; // Increment index of array // with smallest value if (A[i] == minimum) i++; else if (B[j] == minimum) j++; else k++; } // Print result Console.WriteLine(A[res_i] + \" \" + B[res_j] + \" \" + C[res_k]); } // Driver code public static void Main () { int []A = {1, 4, 10}; int []B = {2, 15, 20}; int []C = {10, 12}; int p = A.Length; int q = B.Length; int r = C.Length; // Function calling findClosest(A, B, C, p, q, r); }} // This code is contributed// by anuj_67.",
"e": 8363,
"s": 6475,
"text": null
},
{
"code": "<?php// PHP program to find 3 elements such// that max(abs(A[i]-B[j]), abs(B[j]-// C[k]), abs(C[k]-A[i])) is minimized. function findClosest($A, $B, $C, $p, $q, $r){ $diff = PHP_INT_MAX; // Initialize min diff // Initialize result $res_i = 0; $res_j = 0; $res_k = 0; // Traverse arrays $i = 0; $j = 0; $k = 0; while ($i < $p && $j < $q && $k < $r) { // Find minimum and maximum of // current three elements $minimum = min($A[$i], min($B[$j], $C[$k])); $maximum = max($A[$i], max($B[$j], $C[$k])); // Update result if current diff is // less than the min diff so far if ($maximum-$minimum < $diff) { $res_i = $i; $res_j = $j; $res_k = $k; $diff = $maximum - $minimum; } // We can't get less than 0 as // values are absolute if ($diff == 0) break; // Increment index of array with // smallest value if ($A[$i] == $minimum) $i++; else if ($B[$j] == $minimum) $j++; else $k++; } // Print result echo $A[$res_i] , \" \", $B[$res_j], \" \", $C[$res_k];} // Driver Code$A = array(1, 4, 10);$B = array(2, 15, 20);$C = array(10, 12); $p = sizeof($A);$q = sizeof($B);$r = sizeof($C); findClosest($A, $B, $C, $p, $q, $r); // This code is contributed by Sach_Code?>",
"e": 9724,
"s": 8363,
"text": null
},
{
"code": "<script> // JavaScript program to find 3 elements // such that max(abs(A[i]-B[j]), abs(B[j]- // C[k]), abs(C[k]-A[i])) is minimized. function findClosest(A, B, C, p, q, r) { var diff = Math.pow(10, 9); // Initialize min diff // Initialize result var res_i = 0, res_j = 0, res_k = 0; // Traverse arrays var i = 0, j = 0, k = 0; while (i < p && j < q && k < r) { // Find minimum and maximum of current three elements var minimum = Math.min(A[i], Math.min(B[j], C[k])); var maximum = Math.max(A[i], Math.max(B[j], C[k])); // Update result if current diff is less than the min // diff so far if (maximum - minimum < diff) { (res_i = i), (res_j = j), (res_k = k); diff = maximum - minimum; } // We can't get less than 0 as values are absolute if (diff == 0) break; // Increment index of array with smallest value if (A[i] == minimum) i++; else if (B[j] == minimum) j++; else k++; } // Print result document.write(A[res_i] + \" \" + B[res_j] + \" \" + C[res_k]); } // Driver program var A = [1, 4, 10]; var B = [2, 15, 20]; var C = [10, 12]; var p = A.length; var q = B.length; var r = C.length; findClosest(A, B, C, p, q, r); // This code is contributed by rdtank. </script>",
"e": 11236,
"s": 9724,
"text": null
},
{
"code": null,
"e": 11245,
"s": 11236,
"text": "Output: "
},
{
"code": null,
"e": 11254,
"s": 11245,
"text": "10 15 10"
},
{
"code": null,
"e": 11424,
"s": 11254,
"text": "Time complexity of this solution is O(p + q + r) where p, q and r are sizes of A[], B[] and C[] respectively.Thanks to Gaurav Ahirwar for suggesting the above solutions."
},
{
"code": null,
"e": 11550,
"s": 11424,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 11562,
"s": 11550,
"text": "shrikanth13"
},
{
"code": null,
"e": 11568,
"s": 11562,
"text": "jit_t"
},
{
"code": null,
"e": 11573,
"s": 11568,
"text": "vt_m"
},
{
"code": null,
"e": 11583,
"s": 11573,
"text": "Sach_Code"
},
{
"code": null,
"e": 11593,
"s": 11583,
"text": "paperba1l"
},
{
"code": null,
"e": 11600,
"s": 11593,
"text": "rdtank"
},
{
"code": null,
"e": 11612,
"s": 11600,
"text": "anantsingh2"
},
{
"code": null,
"e": 11621,
"s": 11612,
"text": "sweetyty"
},
{
"code": null,
"e": 11631,
"s": 11621,
"text": "Searching"
},
{
"code": null,
"e": 11641,
"s": 11631,
"text": "Searching"
},
{
"code": null,
"e": 11739,
"s": 11641,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11786,
"s": 11739,
"text": "Search, insert and delete in an unsorted array"
},
{
"code": null,
"e": 11833,
"s": 11786,
"text": "Median of two sorted arrays of different sizes"
},
{
"code": null,
"e": 11877,
"s": 11833,
"text": "Program to find largest element in an array"
},
{
"code": null,
"e": 11921,
"s": 11877,
"text": "k largest(or smallest) elements in an array"
},
{
"code": null,
"e": 11944,
"s": 11921,
"text": "Two Pointers Technique"
},
{
"code": null,
"e": 12035,
"s": 11944,
"text": "Given an array of size n and a number k, find all elements that appear more than n/k times"
},
{
"code": null,
"e": 12073,
"s": 12035,
"text": "Find the missing and repeating number"
},
{
"code": null,
"e": 12117,
"s": 12073,
"text": "Search, insert and delete in a sorted array"
},
{
"code": null,
"e": 12160,
"s": 12117,
"text": "Find the index of an array element in Java"
}
] |
StringBuilder toString() method in Java with Examples
|
30 Aug, 2021
The toString() method of the StringBuilder class is the inbuilt method used to return a string representing the data contained by StringBuilder Object. A new String object is created and initialized to get the character sequence from this StringBuilder object and then String is returned by toString(). Subsequent changes to this sequence contained by Object do not affect the contents of the String.
Syntax:
public abstract String toString() ;
Return Value: This method always returns a string representing the data contained by StringBuilder Object.
As this is a very basic method been incorporated in java so we will be discussing it within our clean java programs to get to know its working. INternally in the class, it is defined as follows which will give you a better understanding of how it actually works.
return getClass().getName()+ "@" + Integer.toHexString(hashCode);
Example 1:
Java
// Java program to demonstrate toString() Method // Importing I/O classesimport java.io.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder("GeeksForGeeks"); // Print and display the string // using standard toString() method System.out.println("String contains = " + str.toString()); }}
String contains = GeeksForGeeks
Example 2:
Java
// Java program to demonstrate toString() Method. // Importing input output classesimport java.io.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating a StringBuilder object with // a String pass as parameter StringBuilder str = new StringBuilder( "Geeks for Geeks contribute"); // Print and display the string // using to.String() method System.out.println("String contains = " + str.toString()); }}
String contains = Geeks for Geeks contribute
Now we are done with discussing basic examples let us operate the same over an array of strings by converting it to a single string using to.String() method. Here we will create a StringBuilder class object then we will store the array of string as its object. Later on, we will create another string and will throw all elements in this. Lastly, we will print this string.
Example 3:
Java
// Java Program to Convert Array of Strings to A String// Using toString() method // Importing required classesimport java.io.*;import java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Random array of string as input String gfg[] = { "Are", "You", "A", "Programmer" }; // Creating object of StringBuilder class StringBuilder obj = new StringBuilder(); // Adding above arrays of strings to // Stringbuilder object obj.append(gfg[0]); obj.append(" " + gfg[1]); obj.append(" " + gfg[2]); obj.append(" " + gfg[3]); // Note if elements are more then // we will be using loops to append(add) // Creating a single string String str = obj.toString(); // Print and display the above string // containing all strings as a single string // using toString() method System.out.println( "Single string generated using toString() method is --> " + str); }}
Single string generated using toString() method is --> Are You A Programmer
Akanksha_Rai
solankimayank
arorakashish0911
surinderdawra388
java-basics
Java-Functions
Java-StringBuilder
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": "\n30 Aug, 2021"
},
{
"code": null,
"e": 429,
"s": 28,
"text": "The toString() method of the StringBuilder class is the inbuilt method used to return a string representing the data contained by StringBuilder Object. A new String object is created and initialized to get the character sequence from this StringBuilder object and then String is returned by toString(). Subsequent changes to this sequence contained by Object do not affect the contents of the String."
},
{
"code": null,
"e": 438,
"s": 429,
"text": "Syntax: "
},
{
"code": null,
"e": 474,
"s": 438,
"text": "public abstract String toString() ;"
},
{
"code": null,
"e": 581,
"s": 474,
"text": "Return Value: This method always returns a string representing the data contained by StringBuilder Object."
},
{
"code": null,
"e": 845,
"s": 581,
"text": "As this is a very basic method been incorporated in java so we will be discussing it within our clean java programs to get to know its working. INternally in the class, it is defined as follows which will give you a better understanding of how it actually works. "
},
{
"code": null,
"e": 911,
"s": 845,
"text": "return getClass().getName()+ \"@\" + Integer.toHexString(hashCode);"
},
{
"code": null,
"e": 922,
"s": 911,
"text": "Example 1:"
},
{
"code": null,
"e": 927,
"s": 922,
"text": "Java"
},
{
"code": "// Java program to demonstrate toString() Method // Importing I/O classesimport java.io.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder(\"GeeksForGeeks\"); // Print and display the string // using standard toString() method System.out.println(\"String contains = \" + str.toString()); }}",
"e": 1455,
"s": 927,
"text": null
},
{
"code": null,
"e": 1487,
"s": 1455,
"text": "String contains = GeeksForGeeks"
},
{
"code": null,
"e": 1498,
"s": 1487,
"text": "Example 2:"
},
{
"code": null,
"e": 1503,
"s": 1498,
"text": "Java"
},
{
"code": "// Java program to demonstrate toString() Method. // Importing input output classesimport java.io.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating a StringBuilder object with // a String pass as parameter StringBuilder str = new StringBuilder( \"Geeks for Geeks contribute\"); // Print and display the string // using to.String() method System.out.println(\"String contains = \" + str.toString()); }}",
"e": 2047,
"s": 1503,
"text": null
},
{
"code": null,
"e": 2092,
"s": 2047,
"text": "String contains = Geeks for Geeks contribute"
},
{
"code": null,
"e": 2465,
"s": 2092,
"text": "Now we are done with discussing basic examples let us operate the same over an array of strings by converting it to a single string using to.String() method. Here we will create a StringBuilder class object then we will store the array of string as its object. Later on, we will create another string and will throw all elements in this. Lastly, we will print this string."
},
{
"code": null,
"e": 2476,
"s": 2465,
"text": "Example 3:"
},
{
"code": null,
"e": 2481,
"s": 2476,
"text": "Java"
},
{
"code": "// Java Program to Convert Array of Strings to A String// Using toString() method // Importing required classesimport java.io.*;import java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Random array of string as input String gfg[] = { \"Are\", \"You\", \"A\", \"Programmer\" }; // Creating object of StringBuilder class StringBuilder obj = new StringBuilder(); // Adding above arrays of strings to // Stringbuilder object obj.append(gfg[0]); obj.append(\" \" + gfg[1]); obj.append(\" \" + gfg[2]); obj.append(\" \" + gfg[3]); // Note if elements are more then // we will be using loops to append(add) // Creating a single string String str = obj.toString(); // Print and display the above string // containing all strings as a single string // using toString() method System.out.println( \"Single string generated using toString() method is --> \" + str); }}",
"e": 3544,
"s": 2481,
"text": null
},
{
"code": null,
"e": 3620,
"s": 3544,
"text": "Single string generated using toString() method is --> Are You A Programmer"
},
{
"code": null,
"e": 3633,
"s": 3620,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 3647,
"s": 3633,
"text": "solankimayank"
},
{
"code": null,
"e": 3664,
"s": 3647,
"text": "arorakashish0911"
},
{
"code": null,
"e": 3681,
"s": 3664,
"text": "surinderdawra388"
},
{
"code": null,
"e": 3693,
"s": 3681,
"text": "java-basics"
},
{
"code": null,
"e": 3708,
"s": 3693,
"text": "Java-Functions"
},
{
"code": null,
"e": 3727,
"s": 3708,
"text": "Java-StringBuilder"
},
{
"code": null,
"e": 3732,
"s": 3727,
"text": "Java"
},
{
"code": null,
"e": 3737,
"s": 3732,
"text": "Java"
},
{
"code": null,
"e": 3835,
"s": 3737,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3850,
"s": 3835,
"text": "Stream In Java"
},
{
"code": null,
"e": 3871,
"s": 3850,
"text": "Introduction to Java"
},
{
"code": null,
"e": 3892,
"s": 3871,
"text": "Constructors in Java"
},
{
"code": null,
"e": 3911,
"s": 3892,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 3928,
"s": 3911,
"text": "Generics in Java"
},
{
"code": null,
"e": 3958,
"s": 3928,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 3984,
"s": 3958,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 4000,
"s": 3984,
"text": "Strings in Java"
},
{
"code": null,
"e": 4037,
"s": 4000,
"text": "Differences between JDK, JRE and JVM"
}
] |
Machine Learning in C++
|
30 Jun, 2019
Most of us have C++ as our First Language but when it comes to something like Data Analysis and Machine Learning, Python becomes our go-to Language because of its simplicity and plenty of libraries of pre-written Modules.But can C++ be used for Machine Learning too? and If yes, then how?
Pre-requisites:
C++ Boost Library:- It is a powerful C++ library used for various purposes like big Maths Operations, etc.You can refer here for installation of this LibraryML pack C++ Library:- This is a small and Scalable C++ Machine Learning Library.You can refer here for the installation of this Library.Note: set USE_OPENMP=OFF when installing mlpack, don’t sweat, given link has guide on how to do thatSample CSV Data File:- As MLpack library does not have any inbuilt Sample Dataset so we have to use our own Sample Dataset.
C++ Boost Library:- It is a powerful C++ library used for various purposes like big Maths Operations, etc.You can refer here for installation of this Library
ML pack C++ Library:- This is a small and Scalable C++ Machine Learning Library.You can refer here for the installation of this Library.Note: set USE_OPENMP=OFF when installing mlpack, don’t sweat, given link has guide on how to do that
Sample CSV Data File:- As MLpack library does not have any inbuilt Sample Dataset so we have to use our own Sample Dataset.
The Code we are writing takes a simple dataset of vectors and finds the nearest neighbour for each data point.
The Training Part has been highlighted
Input : Our Input is a file named data.csv containing a dataset of vectors
The File Contains the Following Data:
3, 3, 3, 3, 0
3, 4, 4, 3, 0
3, 4, 4, 3, 0
3, 3, 4, 3, 0
3, 6, 4, 3, 0
2, 4, 4, 3, 0
2, 4, 4, 1, 0
3, 3, 3, 2, 0
3, 4, 4, 2, 0
3, 4, 4, 2, 0
3, 3, 4, 2, 0
3, 6, 4, 2, 0
2, 4, 4, 2, 0
Code:
#include <mlpack/core.hpp>#include <mlpack/methods/neighbor_search/neighbor_search.hpp> using namespace std;using namespace mlpack;// NeighborSearch and NearestNeighborSortusing namespace mlpack::neighbor;// ManhattanDistanceusing namespace mlpack::metric; void mlModel(){ // Armadillo is a C++ linear algebra library; // mlpack uses its matrix data type. arma::mat data; /* data::Load is used to import data to the mlpack, It takes 3 parameters, 1. Filename = Name of the File to be used 2. Matrix = Matrix to hold the Data in the File 3. fatal = true if you want it to throw an exception if there is an issue */ data::Load("data.csv", data, true); /* Create a NeighborSearch model. The parameters of the model are specified with templates: 1. Sorting method: "NearestNeighborSort" - This class sorts by increasing distance. 2. Distance metric: "ManhattanDistance" - The L1 distance, the sum of absolute distances. 3. Pass the reference dataset (the vectors to be searched through) to the constructor. */ NeighborSearch<NearestNeighborSort, ManhattanDistance> nn(data); // in the above line we trained our model or // fitted the data to the model // now we will predict arma::Mat<size_t> neighbors; // Matrices to hold arma::mat distances; // the results /* Find the nearest neighbors. Arguments are:- 1. k = 1, Specify the number of neighbors to find 2. Matrices to hold the result, in this case, neighbors and distances */ nn.Search(1, neighbors, distances); // in the above line we find the nearest neighbor // Print out each neighbor and its distance. for (size_t i = 0; i < neighbors.n_elem; ++i) { std::cout << "Nearest neighbor of point " << i << " is point " << neighbors[i] << " and the distance is " << distances[i] << ".\n"; }} int main(){ mlModel(); return 0;}
Run the above code in Terminal/CMD using
g++ knn_example.cpp -o knn_example -std=c++11 -larmadillo -lmlpack -lboost_serialization
followed by
./knn_example
Output:
Nearest neighbor of point 0 is point 7 and the distance is 1.
Nearest neighbor of point 1 is point 2 and the distance is 0.
Nearest neighbor of point 2 is point 1 and the distance is 0.
Nearest neighbor of point 3 is point 10 and the distance is 1.
Nearest neighbor of point 4 is point 11 and the distance is 1.
Nearest neighbor of point 5 is point 12 and the distance is 1.
Nearest neighbor of point 6 is point 12 and the distance is 1.
Nearest neighbor of point 7 is point 10 and the distance is 1.
Nearest neighbor of point 8 is point 9 and the distance is 0.
Nearest neighbor of point 9 is point 8 and the distance is 0.
Nearest neighbor of point 10 is point 9 and the distance is 1.
Nearest neighbor of point 11 is point 4 and the distance is 1.
Nearest neighbor of point 12 is point 9 and the distance is 1.
C++
Machine Learning
Machine Learning
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Set in C++ Standard Template Library (STL)
Priority Queue in C++ Standard Template Library (STL)
vector erase() and clear() in C++
Substring in C++
unordered_map in C++ STL
Naive Bayes Classifiers
ML | Linear Regression
Linear Regression (Python Implementation)
Reinforcement learning
Removing stop words with NLTK in Python
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n30 Jun, 2019"
},
{
"code": null,
"e": 341,
"s": 52,
"text": "Most of us have C++ as our First Language but when it comes to something like Data Analysis and Machine Learning, Python becomes our go-to Language because of its simplicity and plenty of libraries of pre-written Modules.But can C++ be used for Machine Learning too? and If yes, then how?"
},
{
"code": null,
"e": 357,
"s": 341,
"text": "Pre-requisites:"
},
{
"code": null,
"e": 874,
"s": 357,
"text": "C++ Boost Library:- It is a powerful C++ library used for various purposes like big Maths Operations, etc.You can refer here for installation of this LibraryML pack C++ Library:- This is a small and Scalable C++ Machine Learning Library.You can refer here for the installation of this Library.Note: set USE_OPENMP=OFF when installing mlpack, don’t sweat, given link has guide on how to do thatSample CSV Data File:- As MLpack library does not have any inbuilt Sample Dataset so we have to use our own Sample Dataset."
},
{
"code": null,
"e": 1032,
"s": 874,
"text": "C++ Boost Library:- It is a powerful C++ library used for various purposes like big Maths Operations, etc.You can refer here for installation of this Library"
},
{
"code": null,
"e": 1269,
"s": 1032,
"text": "ML pack C++ Library:- This is a small and Scalable C++ Machine Learning Library.You can refer here for the installation of this Library.Note: set USE_OPENMP=OFF when installing mlpack, don’t sweat, given link has guide on how to do that"
},
{
"code": null,
"e": 1393,
"s": 1269,
"text": "Sample CSV Data File:- As MLpack library does not have any inbuilt Sample Dataset so we have to use our own Sample Dataset."
},
{
"code": null,
"e": 1504,
"s": 1393,
"text": "The Code we are writing takes a simple dataset of vectors and finds the nearest neighbour for each data point."
},
{
"code": null,
"e": 1543,
"s": 1504,
"text": "The Training Part has been highlighted"
},
{
"code": null,
"e": 1839,
"s": 1543,
"text": "Input : Our Input is a file named data.csv containing a dataset of vectors\nThe File Contains the Following Data:\n3, 3, 3, 3, 0\n3, 4, 4, 3, 0\n3, 4, 4, 3, 0\n3, 3, 4, 3, 0\n3, 6, 4, 3, 0\n2, 4, 4, 3, 0\n2, 4, 4, 1, 0\n3, 3, 3, 2, 0\n3, 4, 4, 2, 0\n3, 4, 4, 2, 0\n3, 3, 4, 2, 0\n3, 6, 4, 2, 0\n2, 4, 4, 2, 0\n"
},
{
"code": null,
"e": 1845,
"s": 1839,
"text": "Code:"
},
{
"code": "#include <mlpack/core.hpp>#include <mlpack/methods/neighbor_search/neighbor_search.hpp> using namespace std;using namespace mlpack;// NeighborSearch and NearestNeighborSortusing namespace mlpack::neighbor;// ManhattanDistanceusing namespace mlpack::metric; void mlModel(){ // Armadillo is a C++ linear algebra library; // mlpack uses its matrix data type. arma::mat data; /* data::Load is used to import data to the mlpack, It takes 3 parameters, 1. Filename = Name of the File to be used 2. Matrix = Matrix to hold the Data in the File 3. fatal = true if you want it to throw an exception if there is an issue */ data::Load(\"data.csv\", data, true); /* Create a NeighborSearch model. The parameters of the model are specified with templates: 1. Sorting method: \"NearestNeighborSort\" - This class sorts by increasing distance. 2. Distance metric: \"ManhattanDistance\" - The L1 distance, the sum of absolute distances. 3. Pass the reference dataset (the vectors to be searched through) to the constructor. */ NeighborSearch<NearestNeighborSort, ManhattanDistance> nn(data); // in the above line we trained our model or // fitted the data to the model // now we will predict arma::Mat<size_t> neighbors; // Matrices to hold arma::mat distances; // the results /* Find the nearest neighbors. Arguments are:- 1. k = 1, Specify the number of neighbors to find 2. Matrices to hold the result, in this case, neighbors and distances */ nn.Search(1, neighbors, distances); // in the above line we find the nearest neighbor // Print out each neighbor and its distance. for (size_t i = 0; i < neighbors.n_elem; ++i) { std::cout << \"Nearest neighbor of point \" << i << \" is point \" << neighbors[i] << \" and the distance is \" << distances[i] << \".\\n\"; }} int main(){ mlModel(); return 0;}",
"e": 3862,
"s": 1845,
"text": null
},
{
"code": null,
"e": 3903,
"s": 3862,
"text": "Run the above code in Terminal/CMD using"
},
{
"code": null,
"e": 3993,
"s": 3903,
"text": "g++ knn_example.cpp -o knn_example -std=c++11 -larmadillo -lmlpack -lboost_serialization\n"
},
{
"code": null,
"e": 4005,
"s": 3993,
"text": "followed by"
},
{
"code": null,
"e": 4020,
"s": 4005,
"text": "./knn_example\n"
},
{
"code": null,
"e": 4843,
"s": 4020,
"text": "Output:\nNearest neighbor of point 0 is point 7 and the distance is 1.\nNearest neighbor of point 1 is point 2 and the distance is 0.\nNearest neighbor of point 2 is point 1 and the distance is 0.\nNearest neighbor of point 3 is point 10 and the distance is 1.\nNearest neighbor of point 4 is point 11 and the distance is 1.\nNearest neighbor of point 5 is point 12 and the distance is 1.\nNearest neighbor of point 6 is point 12 and the distance is 1.\nNearest neighbor of point 7 is point 10 and the distance is 1.\nNearest neighbor of point 8 is point 9 and the distance is 0.\nNearest neighbor of point 9 is point 8 and the distance is 0.\nNearest neighbor of point 10 is point 9 and the distance is 1.\nNearest neighbor of point 11 is point 4 and the distance is 1.\nNearest neighbor of point 12 is point 9 and the distance is 1.\n"
},
{
"code": null,
"e": 4847,
"s": 4843,
"text": "C++"
},
{
"code": null,
"e": 4864,
"s": 4847,
"text": "Machine Learning"
},
{
"code": null,
"e": 4881,
"s": 4864,
"text": "Machine Learning"
},
{
"code": null,
"e": 4885,
"s": 4881,
"text": "CPP"
},
{
"code": null,
"e": 4983,
"s": 4885,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5026,
"s": 4983,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 5080,
"s": 5026,
"text": "Priority Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 5114,
"s": 5080,
"text": "vector erase() and clear() in C++"
},
{
"code": null,
"e": 5131,
"s": 5114,
"text": "Substring in C++"
},
{
"code": null,
"e": 5156,
"s": 5131,
"text": "unordered_map in C++ STL"
},
{
"code": null,
"e": 5180,
"s": 5156,
"text": "Naive Bayes Classifiers"
},
{
"code": null,
"e": 5203,
"s": 5180,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 5245,
"s": 5203,
"text": "Linear Regression (Python Implementation)"
},
{
"code": null,
"e": 5268,
"s": 5245,
"text": "Reinforcement learning"
}
] |
Top Information Security Attack Vectors
|
06 Jan, 2021
Information Security alludes to the cycles and procedures which are planned and executed to ensure print, electronic, or some other type of secret, private and touchy data or information from unapproved access, use, abuse, revelation, obliteration, change, or disturbance.
An attack vector is a way or means by which a programmer (or saltine) can access a PC or organization’s mainframe to convey a payload or malevolent result. Attack vectors empower programmers to misuse framework weaknesses, including the human component. Attack vectors incorporate worms, email connections, Web pages, spring up windows, texts, visit rooms, and duplicity. These strategies include programming (or, in a couple of cases, equipment), aside from trickiness, in which a human administrator is tricked into eliminating or debilitating framework guards.
Somewhat, firewalls and against infection programming can obstruct assault vectors. However, no security technique is thoroughly assaulted verification. A safeguard technique that is viable today may not remain so for long, in light of the fact that programmers are continually refreshing attack vectors, and looking for new ones, in their journey to pick up unapproved admittance to PCs and mainframes. The most well-known malignant payloads are viruses (which can work as their own attack vectors), Trojan ponies, worms, and spyware. In the event that an assault vector is considered as a guided rocket, its payload can be contrasted with the warhead in the tip of the rocket.
Information Security Threat Categories
Network Threats
Host Threats
Application Threats
The following is a rundown of information security hack vectors through which a hacker can access a PC or organization mainframe to convey a payload or malevolent result:
Cloud Computing Threats: Cloud computing is an on-request conveyance of IT abilities in which IT foundation and applications are given to endorsers as a metered administration over an organization. Customers can store delicate information on the cloud. A defect in one customer’s application cloud might permit programmers to get to another customer’s information.
Mobile Threats: Hackers are progressively zeroing in on smartphones, because of the expanded selection of phones for business and individual use and their comparatively fewer security controls. Clients may download malware applications (APKs) onto their cell phones, which can harm different applications and information and pass on touchy information to programmers. Programmers can distantly get to a cell phone’s camera and recording application to see client exercises and track voice interchanges, which can help them in an assault.
Botnet: A botnet is a malicious network of hacked frameworks utilized by aggressors to perform disavowal of-administration assaults. Bots, in a botnet, perform errands, for example, transferring infections, sending sends with botnets appended to them, taking information, etc. Antivirus projects may neglect to discover or even output for spyware or botnets. Consequently, it is basic to send programs explicitly intended to discover and dispose of such threats.
Insider Attack: An insider attack is a type of hack which is executed by somebody from inside an association who has approved admittance to its network and knows about the organization’s design.
Ransomware: It is a kind of malware, which confines admittance to the PC framework’s documents and OS and requests an online payoff to the malware creator(s) to eliminate the limitations. It is generally spread by means of noxious connections to email messages, contaminated programming applications, tainted plates, or traded off-sites.
Viruses and Worms: These are the most pervasive systems administration threats, equipped for contaminating an organization in no time. A virus is a self-repeating program that delivers a duplicate of itself by joining to another program, PC boot area, or record. A worm is a malignant program that recreates, executed, and spreads across network associations.
APT (Advanced Persistent Threats): It is an assault that centers around taking information from the casualty machine without its client monitoring it. These assaults are commonly focused everywhere in organizations and government organizations. Adept assaults are delayed in nature, so the impact on PC execution and Internet associations is immaterial. APTs abuse weaknesses in the applications running on a PC, working framework, and implanted frameworks.
Phishing: It is an act of sending an ill-conceived email dishonestly asserting to be from an authentic site in an attempt to procure a client’s close to home or record information. Aggressors perform phishing assaults by appropriating pernicious connections by means of some correspondence channel or sends to get private information like record numbers, Visa numbers, portable numbers, and so on from the objective.
Web Application Threats: Web Application assaults like SQL injection, cross-website scripting has made web applications a positive objective for the assailants to take certifications, set up phishing webpage, or procure private information. The dominant part of such assaults is the consequence of imperfect coding and inappropriate sanitization of info and yield information from the web application. These can compromise the exhibition of the site and hamper its security.
IoT Threats: The IoT gadgets associated with the web have practically no security that made them helpless against different kinds of assaults. These gadgets incorporate numerous product applications that are utilized to get to the gadget distantly. Because of the equipment limitations, for example, memory, battery, and so forth these IoT applications do exclude complex security systems to shield the gadgets from assaults.
Cyber-security
GBlog
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You!
Geek Streak - 24 Days POTD Challenge
What is Hashing | A Complete Tutorial
GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?
GeeksforGeeks Job-A-Thon Exclusive - Hiring Challenge For Amazon Alexa
How to Learn Data Science in 10 weeks?
Roadmap to Learn JavaScript For Beginners
What is Data Structure: Types, Classifications and Applications
How To Switch From A Service-Based To A Product-Based Company?
Axios in React: A Guide for Beginners
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n06 Jan, 2021"
},
{
"code": null,
"e": 327,
"s": 54,
"text": "Information Security alludes to the cycles and procedures which are planned and executed to ensure print, electronic, or some other type of secret, private and touchy data or information from unapproved access, use, abuse, revelation, obliteration, change, or disturbance."
},
{
"code": null,
"e": 891,
"s": 327,
"text": "An attack vector is a way or means by which a programmer (or saltine) can access a PC or organization’s mainframe to convey a payload or malevolent result. Attack vectors empower programmers to misuse framework weaknesses, including the human component. Attack vectors incorporate worms, email connections, Web pages, spring up windows, texts, visit rooms, and duplicity. These strategies include programming (or, in a couple of cases, equipment), aside from trickiness, in which a human administrator is tricked into eliminating or debilitating framework guards."
},
{
"code": null,
"e": 1570,
"s": 891,
"text": "Somewhat, firewalls and against infection programming can obstruct assault vectors. However, no security technique is thoroughly assaulted verification. A safeguard technique that is viable today may not remain so for long, in light of the fact that programmers are continually refreshing attack vectors, and looking for new ones, in their journey to pick up unapproved admittance to PCs and mainframes. The most well-known malignant payloads are viruses (which can work as their own attack vectors), Trojan ponies, worms, and spyware. In the event that an assault vector is considered as a guided rocket, its payload can be contrasted with the warhead in the tip of the rocket."
},
{
"code": null,
"e": 1609,
"s": 1570,
"text": "Information Security Threat Categories"
},
{
"code": null,
"e": 1625,
"s": 1609,
"text": "Network Threats"
},
{
"code": null,
"e": 1638,
"s": 1625,
"text": "Host Threats"
},
{
"code": null,
"e": 1658,
"s": 1638,
"text": "Application Threats"
},
{
"code": null,
"e": 1829,
"s": 1658,
"text": "The following is a rundown of information security hack vectors through which a hacker can access a PC or organization mainframe to convey a payload or malevolent result:"
},
{
"code": null,
"e": 2194,
"s": 1829,
"text": "Cloud Computing Threats: Cloud computing is an on-request conveyance of IT abilities in which IT foundation and applications are given to endorsers as a metered administration over an organization. Customers can store delicate information on the cloud. A defect in one customer’s application cloud might permit programmers to get to another customer’s information."
},
{
"code": null,
"e": 2732,
"s": 2194,
"text": "Mobile Threats: Hackers are progressively zeroing in on smartphones, because of the expanded selection of phones for business and individual use and their comparatively fewer security controls. Clients may download malware applications (APKs) onto their cell phones, which can harm different applications and information and pass on touchy information to programmers. Programmers can distantly get to a cell phone’s camera and recording application to see client exercises and track voice interchanges, which can help them in an assault."
},
{
"code": null,
"e": 3195,
"s": 2732,
"text": "Botnet: A botnet is a malicious network of hacked frameworks utilized by aggressors to perform disavowal of-administration assaults. Bots, in a botnet, perform errands, for example, transferring infections, sending sends with botnets appended to them, taking information, etc. Antivirus projects may neglect to discover or even output for spyware or botnets. Consequently, it is basic to send programs explicitly intended to discover and dispose of such threats."
},
{
"code": null,
"e": 3390,
"s": 3195,
"text": "Insider Attack: An insider attack is a type of hack which is executed by somebody from inside an association who has approved admittance to its network and knows about the organization’s design."
},
{
"code": null,
"e": 3728,
"s": 3390,
"text": "Ransomware: It is a kind of malware, which confines admittance to the PC framework’s documents and OS and requests an online payoff to the malware creator(s) to eliminate the limitations. It is generally spread by means of noxious connections to email messages, contaminated programming applications, tainted plates, or traded off-sites."
},
{
"code": null,
"e": 4088,
"s": 3728,
"text": "Viruses and Worms: These are the most pervasive systems administration threats, equipped for contaminating an organization in no time. A virus is a self-repeating program that delivers a duplicate of itself by joining to another program, PC boot area, or record. A worm is a malignant program that recreates, executed, and spreads across network associations."
},
{
"code": null,
"e": 4546,
"s": 4088,
"text": "APT (Advanced Persistent Threats): It is an assault that centers around taking information from the casualty machine without its client monitoring it. These assaults are commonly focused everywhere in organizations and government organizations. Adept assaults are delayed in nature, so the impact on PC execution and Internet associations is immaterial. APTs abuse weaknesses in the applications running on a PC, working framework, and implanted frameworks."
},
{
"code": null,
"e": 4963,
"s": 4546,
"text": "Phishing: It is an act of sending an ill-conceived email dishonestly asserting to be from an authentic site in an attempt to procure a client’s close to home or record information. Aggressors perform phishing assaults by appropriating pernicious connections by means of some correspondence channel or sends to get private information like record numbers, Visa numbers, portable numbers, and so on from the objective."
},
{
"code": null,
"e": 5438,
"s": 4963,
"text": "Web Application Threats: Web Application assaults like SQL injection, cross-website scripting has made web applications a positive objective for the assailants to take certifications, set up phishing webpage, or procure private information. The dominant part of such assaults is the consequence of imperfect coding and inappropriate sanitization of info and yield information from the web application. These can compromise the exhibition of the site and hamper its security."
},
{
"code": null,
"e": 5864,
"s": 5438,
"text": "IoT Threats: The IoT gadgets associated with the web have practically no security that made them helpless against different kinds of assaults. These gadgets incorporate numerous product applications that are utilized to get to the gadget distantly. Because of the equipment limitations, for example, memory, battery, and so forth these IoT applications do exclude complex security systems to shield the gadgets from assaults."
},
{
"code": null,
"e": 5879,
"s": 5864,
"text": "Cyber-security"
},
{
"code": null,
"e": 5885,
"s": 5879,
"text": "GBlog"
},
{
"code": null,
"e": 5983,
"s": 5885,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6038,
"s": 5983,
"text": "GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You!"
},
{
"code": null,
"e": 6075,
"s": 6038,
"text": "Geek Streak - 24 Days POTD Challenge"
},
{
"code": null,
"e": 6113,
"s": 6075,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 6179,
"s": 6113,
"text": "GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?"
},
{
"code": null,
"e": 6250,
"s": 6179,
"text": "GeeksforGeeks Job-A-Thon Exclusive - Hiring Challenge For Amazon Alexa"
},
{
"code": null,
"e": 6289,
"s": 6250,
"text": "How to Learn Data Science in 10 weeks?"
},
{
"code": null,
"e": 6331,
"s": 6289,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 6395,
"s": 6331,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 6458,
"s": 6395,
"text": "How To Switch From A Service-Based To A Product-Based Company?"
}
] |
What is Event Capturing in JavaScript?
|
Event capturing is the event starts from top element to the target element. It is the opposite of Event bubbling, which starts from target element to the top element.
In the following code, in body section three div elements are taken and a style got applied so as to make them nested.
Add a event handler to each of the div tags using addEventListener().
Make sure that here the event is "click" event.
The addEventListener() method accepts 3 parameters.
a) The event it is going to access, here it is click event.
b) An event handler function so as to display alert messages.
c) The third parameter is called phase. In this parameter if we keep true then the event capturing will be enabled.If we keep false then event bubbling will be enabled.
The event handler function, which is used to display alert boxes, will use getAttribute() to get the id value of the div element which got clicked.
When we click on the inner most nested tag div3, since event capturing got enabled here, the alert messages starts from top div1 tag to the target tag div3.
When we click on the div2 tag, then alert boxes will display from top div1 tag to target tag div2.
Example
Live Demo
<html>
<head>
<style>
.divstyle{
display:table-cell;
border: 2px solid black;
padding: 20px;
text-align: center;
}
</style>
</head>
<body>
<div id = "div1" class="divstyle">
div1
<div id = "div2" class="divstyle">
div2
<div id = "div3" class="divstyle">
div3
<script>
var divs = document.getElementsByTagName("div");
for(var i = 0; i<divs.length; i++){
divs[i].addEventListener("click",clickhandler,true );
}
function clickhandler() {
alert(this.getAttribute("id") + "event got handled");
}
</script>
</body>
</html>
On executing the above program we get the following image on the screen
On clicking the above div3(target element) we get the following as output
On clicking ok of the above div1 alert box we get the following div2 alert box opened
On clicking ok of the above div2 alert box we get the following div3 alert box opened.
|
[
{
"code": null,
"e": 1354,
"s": 1187,
"text": "Event capturing is the event starts from top element to the target element. It is the opposite of Event bubbling, which starts from target element to the top element."
},
{
"code": null,
"e": 1473,
"s": 1354,
"text": "In the following code, in body section three div elements are taken and a style got applied so as to make them nested."
},
{
"code": null,
"e": 1543,
"s": 1473,
"text": "Add a event handler to each of the div tags using addEventListener()."
},
{
"code": null,
"e": 1591,
"s": 1543,
"text": "Make sure that here the event is \"click\" event."
},
{
"code": null,
"e": 1643,
"s": 1591,
"text": "The addEventListener() method accepts 3 parameters."
},
{
"code": null,
"e": 1718,
"s": 1643,
"text": " a) The event it is going to access, here it is click event. "
},
{
"code": null,
"e": 1793,
"s": 1718,
"text": " b) An event handler function so as to display alert messages."
},
{
"code": null,
"e": 2003,
"s": 1793,
"text": " c) The third parameter is called phase. In this parameter if we keep true then the event capturing will be enabled.If we keep false then event bubbling will be enabled. "
},
{
"code": null,
"e": 2151,
"s": 2003,
"text": "The event handler function, which is used to display alert boxes, will use getAttribute() to get the id value of the div element which got clicked."
},
{
"code": null,
"e": 2308,
"s": 2151,
"text": "When we click on the inner most nested tag div3, since event capturing got enabled here, the alert messages starts from top div1 tag to the target tag div3."
},
{
"code": null,
"e": 2407,
"s": 2308,
"text": "When we click on the div2 tag, then alert boxes will display from top div1 tag to target tag div2."
},
{
"code": null,
"e": 2415,
"s": 2407,
"text": "Example"
},
{
"code": null,
"e": 2425,
"s": 2415,
"text": "Live Demo"
},
{
"code": null,
"e": 3017,
"s": 2425,
"text": "<html>\n<head>\n<style>\n .divstyle{\n display:table-cell;\n border: 2px solid black;\n padding: 20px;\n text-align: center;\n }\n</style>\n</head>\n<body>\n <div id = \"div1\" class=\"divstyle\">\n div1\n <div id = \"div2\" class=\"divstyle\">\n div2\n <div id = \"div3\" class=\"divstyle\">\n div3\n<script>\n var divs = document.getElementsByTagName(\"div\");\n for(var i = 0; i<divs.length; i++){\n divs[i].addEventListener(\"click\",clickhandler,true );\n }\n function clickhandler() {\n alert(this.getAttribute(\"id\") + \"event got handled\");\n }\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 3089,
"s": 3017,
"text": "On executing the above program we get the following image on the screen"
},
{
"code": null,
"e": 3163,
"s": 3089,
"text": "On clicking the above div3(target element) we get the following as output"
},
{
"code": null,
"e": 3341,
"s": 3163,
"text": "\nOn clicking ok of the above div1 alert box we get the following div2 alert box opened\n\n\nOn clicking ok of the above div2 alert box we get the following div3 alert box opened.\n\n"
}
] |
Python | Ways to find all permutation of a string
|
23 Jul, 2021
Given a string, write a Python program to find out all possible permutations of a string. Let’s discuss a few methods to solve the problem.Method #1: Using Naive Method
Python3
# Python code to demonstrate# to find all permutation of# a given string # Initialising stringini_str = "abc" # Printing initial stringprint("Initial string", ini_str) # Finding all permutationresult = [] def permute(data, i, length): if i == length: result.append(''.join(data) ) else: for j in range(i, length): # swap data[i], data[j] = data[j], data[i] permute(data, i + 1, length) data[i], data[j] = data[j], data[i] permute(list(ini_str), 0, len(ini_str)) # Printing resultprint("Resultant permutations", str(result))
Initial string abc
Resultant permutations ['abc', 'acb', 'bac', 'bca', 'cba', 'cab']
Method #2: Using itertools
Python3
# Python code to demonstrate# to find all permutation of# a given string from itertools import permutations # Initialising stringini_str = "abc" # Printing initial stringprint("Initial string", ini_str) # Finding all permutationpermutation = [''.join(p) for p in permutations(ini_str)]# Printing resultprint("Resultant List", str(permutation))
Initial string abc
Resultant List ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
anikaseth98
akshaysingh98088
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 | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 Jul, 2021"
},
{
"code": null,
"e": 223,
"s": 52,
"text": "Given a string, write a Python program to find out all possible permutations of a string. Let’s discuss a few methods to solve the problem.Method #1: Using Naive Method "
},
{
"code": null,
"e": 231,
"s": 223,
"text": "Python3"
},
{
"code": "# Python code to demonstrate# to find all permutation of# a given string # Initialising stringini_str = \"abc\" # Printing initial stringprint(\"Initial string\", ini_str) # Finding all permutationresult = [] def permute(data, i, length): if i == length: result.append(''.join(data) ) else: for j in range(i, length): # swap data[i], data[j] = data[j], data[i] permute(data, i + 1, length) data[i], data[j] = data[j], data[i] permute(list(ini_str), 0, len(ini_str)) # Printing resultprint(\"Resultant permutations\", str(result))",
"e": 819,
"s": 231,
"text": null
},
{
"code": null,
"e": 904,
"s": 819,
"text": "Initial string abc\nResultant permutations ['abc', 'acb', 'bac', 'bca', 'cba', 'cab']"
},
{
"code": null,
"e": 937,
"s": 906,
"text": " Method #2: Using itertools "
},
{
"code": null,
"e": 945,
"s": 937,
"text": "Python3"
},
{
"code": "# Python code to demonstrate# to find all permutation of# a given string from itertools import permutations # Initialising stringini_str = \"abc\" # Printing initial stringprint(\"Initial string\", ini_str) # Finding all permutationpermutation = [''.join(p) for p in permutations(ini_str)]# Printing resultprint(\"Resultant List\", str(permutation))",
"e": 1289,
"s": 945,
"text": null
},
{
"code": null,
"e": 1366,
"s": 1289,
"text": "Initial string abc\nResultant List ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']"
},
{
"code": null,
"e": 1380,
"s": 1368,
"text": "anikaseth98"
},
{
"code": null,
"e": 1397,
"s": 1380,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 1420,
"s": 1397,
"text": "Python string-programs"
},
{
"code": null,
"e": 1427,
"s": 1420,
"text": "Python"
},
{
"code": null,
"e": 1443,
"s": 1427,
"text": "Python Programs"
},
{
"code": null,
"e": 1541,
"s": 1443,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1559,
"s": 1541,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1601,
"s": 1559,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1623,
"s": 1601,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1649,
"s": 1623,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1681,
"s": 1649,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1703,
"s": 1681,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 1742,
"s": 1703,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 1780,
"s": 1742,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 1829,
"s": 1780,
"text": "Python | Convert string dictionary to dictionary"
}
] |
ReactJS | Using Babel
|
30 Mar, 2021
Now we know that what Babel is, we will focus on how to install it on your machine using node. Babel can be installed easily after following these simple steps. Requirements :
A code editor like atom, sublime text or Visual studio code.
Node should be installed on the machine with npm too.
We will install Babel using Node. Open your text editor, then create your directories structure like the one below:
|--node_modules
|--src
--app.js
|--.babelrc
|--package.json
|--package.lock.json
If you know how node works then you know about node_modules, package.json, and package.lock.json. These are automatically formed once we run some commands. Now, open the command line and set the path to the directory of the folder then write these lines in the cmd:
npm install --save-dev @babel/core @babel/cli @babel/preset-env @babel/node
npm install nodemon --save-dev
The first npm commands will install babel dependencies and the second will is used to install nodemon which allows us to update the browser content without refreshing it. After entering the command we will get:
As we can see in the above image, the command that we used to install babel dependencies are now visible in our ‘package.json’ file. It is also important to add the below line inside the .babelrc file which we have in our project directory.
// .babelrc
{
"presets": ["@babel/preset-env"]
}
Now we finally need to add scripts into our ‘package.json’ file.
"start": "nodemon --exec babel-node src/app.js" // inside your scripts tag
The final ‘package.json’ will look like this:
Now we are all set we just need to write normal ES6, 7, 8 code in our app.js file and run it with ‘npx babel filename’ command where ‘filename’ is replaced by app.js here, and we will get the ES5 output in the console. Example:
javascript
// next generation javascript codelet alice = () => {}; let bob = (b) => b; const usingMap = [1, 2, 3].map((number) => number * 2);console.log(usingMap); // [2, 4, 6] var immukul = { _name: "Mukul", _friends: ["Mukul", "Mayank"], printFriends(){ this._friends.forEach( f =>console.log(this._name + " knows " + f)); } }; console.log(immukul.printFriends());
Output:
suryap
kananivinitrocking
react-js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
Node.js fs.readFileSync() Method
How to set input type date in dd-mm-yyyy format using HTML ?
File uploading in React.js
REST API (Introduction)
How to set the default value for an HTML <select> element ?
How to calculate the number of days between two dates in javascript?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Mar, 2021"
},
{
"code": null,
"e": 206,
"s": 28,
"text": "Now we know that what Babel is, we will focus on how to install it on your machine using node. Babel can be installed easily after following these simple steps. Requirements : "
},
{
"code": null,
"e": 267,
"s": 206,
"text": "A code editor like atom, sublime text or Visual studio code."
},
{
"code": null,
"e": 321,
"s": 267,
"text": "Node should be installed on the machine with npm too."
},
{
"code": null,
"e": 439,
"s": 321,
"text": "We will install Babel using Node. Open your text editor, then create your directories structure like the one below: "
},
{
"code": null,
"e": 534,
"s": 439,
"text": " |--node_modules\n |--src\n --app.js\n |--.babelrc\n |--package.json\n |--package.lock.json"
},
{
"code": null,
"e": 802,
"s": 534,
"text": "If you know how node works then you know about node_modules, package.json, and package.lock.json. These are automatically formed once we run some commands. Now, open the command line and set the path to the directory of the folder then write these lines in the cmd: "
},
{
"code": null,
"e": 909,
"s": 802,
"text": "npm install --save-dev @babel/core @babel/cli @babel/preset-env @babel/node\nnpm install nodemon --save-dev"
},
{
"code": null,
"e": 1122,
"s": 909,
"text": "The first npm commands will install babel dependencies and the second will is used to install nodemon which allows us to update the browser content without refreshing it. After entering the command we will get: "
},
{
"code": null,
"e": 1365,
"s": 1122,
"text": "As we can see in the above image, the command that we used to install babel dependencies are now visible in our ‘package.json’ file. It is also important to add the below line inside the .babelrc file which we have in our project directory. "
},
{
"code": null,
"e": 1416,
"s": 1365,
"text": "// .babelrc\n{\n \"presets\": [\"@babel/preset-env\"]\n}"
},
{
"code": null,
"e": 1483,
"s": 1416,
"text": "Now we finally need to add scripts into our ‘package.json’ file. "
},
{
"code": null,
"e": 1558,
"s": 1483,
"text": "\"start\": \"nodemon --exec babel-node src/app.js\" // inside your scripts tag"
},
{
"code": null,
"e": 1606,
"s": 1558,
"text": "The final ‘package.json’ will look like this: "
},
{
"code": null,
"e": 1836,
"s": 1606,
"text": "Now we are all set we just need to write normal ES6, 7, 8 code in our app.js file and run it with ‘npx babel filename’ command where ‘filename’ is replaced by app.js here, and we will get the ES5 output in the console. Example: "
},
{
"code": null,
"e": 1847,
"s": 1836,
"text": "javascript"
},
{
"code": "// next generation javascript codelet alice = () => {}; let bob = (b) => b; const usingMap = [1, 2, 3].map((number) => number * 2);console.log(usingMap); // [2, 4, 6] var immukul = { _name: \"Mukul\", _friends: [\"Mukul\", \"Mayank\"], printFriends(){ this._friends.forEach( f =>console.log(this._name + \" knows \" + f)); } }; console.log(immukul.printFriends());",
"e": 2255,
"s": 1847,
"text": null
},
{
"code": null,
"e": 2265,
"s": 2255,
"text": "Output: "
},
{
"code": null,
"e": 2274,
"s": 2267,
"text": "suryap"
},
{
"code": null,
"e": 2293,
"s": 2274,
"text": "kananivinitrocking"
},
{
"code": null,
"e": 2302,
"s": 2293,
"text": "react-js"
},
{
"code": null,
"e": 2319,
"s": 2302,
"text": "Web Technologies"
},
{
"code": null,
"e": 2417,
"s": 2319,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2450,
"s": 2417,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2512,
"s": 2450,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2562,
"s": 2512,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 2623,
"s": 2562,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2656,
"s": 2623,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 2717,
"s": 2656,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 2744,
"s": 2717,
"text": "File uploading in React.js"
},
{
"code": null,
"e": 2768,
"s": 2744,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 2828,
"s": 2768,
"text": "How to set the default value for an HTML <select> element ?"
}
] |
Python | Ways to count number of substring in string
|
30 Jun, 2019
Given a string and a substring, write a Python program to find how many numbers of substring are there in the string (including overlapping cases). Let’s discuss a few methods below.
Method #1: Using re.findall()
# Python code to demonstrate # to count total number# of substring in string import re# Initialising stringini_str = "ababababa"sub_str = 'aba' # Count count of substrings using re.findallres = len(re.findall('(?= aba)', ini_str)) # Printing resultprint("Number of substrings", res)
Number of substrings 0
Method #2: Using re.finditer()
# Python code to demonstrate # to count total number# of substring in string import re# Initialising stringini_str = "ababababa"sub_str = 'aba' # Count count of substrings using re.finditerres = sum(1 for _ in re.finditer('(?= aba)', ini_str)) # Printing resultprint("Number of substrings", res)
Number of substrings 0
Method #3: Using startswith()
# Python code to demonstrate # to count total number# of substring in string # Initialising stringini_str = "ababababa"sub_str = 'aba' # Count count of substrings using startswithres = sum(1 for i in range(len(ini_str)) if ini_str.startswith("aba", i)) # Printing resultprint("Number of substrings", res)
Number of substrings 4
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n30 Jun, 2019"
},
{
"code": null,
"e": 236,
"s": 53,
"text": "Given a string and a substring, write a Python program to find how many numbers of substring are there in the string (including overlapping cases). Let’s discuss a few methods below."
},
{
"code": null,
"e": 266,
"s": 236,
"text": "Method #1: Using re.findall()"
},
{
"code": "# Python code to demonstrate # to count total number# of substring in string import re# Initialising stringini_str = \"ababababa\"sub_str = 'aba' # Count count of substrings using re.findallres = len(re.findall('(?= aba)', ini_str)) # Printing resultprint(\"Number of substrings\", res)",
"e": 552,
"s": 266,
"text": null
},
{
"code": null,
"e": 576,
"s": 552,
"text": "Number of substrings 0\n"
},
{
"code": null,
"e": 607,
"s": 576,
"text": "Method #2: Using re.finditer()"
},
{
"code": "# Python code to demonstrate # to count total number# of substring in string import re# Initialising stringini_str = \"ababababa\"sub_str = 'aba' # Count count of substrings using re.finditerres = sum(1 for _ in re.finditer('(?= aba)', ini_str)) # Printing resultprint(\"Number of substrings\", res)",
"e": 906,
"s": 607,
"text": null
},
{
"code": null,
"e": 930,
"s": 906,
"text": "Number of substrings 0\n"
},
{
"code": null,
"e": 961,
"s": 930,
"text": " Method #3: Using startswith()"
},
{
"code": "# Python code to demonstrate # to count total number# of substring in string # Initialising stringini_str = \"ababababa\"sub_str = 'aba' # Count count of substrings using startswithres = sum(1 for i in range(len(ini_str)) if ini_str.startswith(\"aba\", i)) # Printing resultprint(\"Number of substrings\", res)",
"e": 1278,
"s": 961,
"text": null
},
{
"code": null,
"e": 1302,
"s": 1278,
"text": "Number of substrings 4\n"
},
{
"code": null,
"e": 1325,
"s": 1302,
"text": "Python string-programs"
},
{
"code": null,
"e": 1332,
"s": 1325,
"text": "Python"
},
{
"code": null,
"e": 1348,
"s": 1332,
"text": "Python Programs"
}
] |
Perl | eq operator
|
07 May, 2019
‘eq‘ operator in Perl is one of the string comparison operators used to check for the equality of the two strings. It is used to check if the string to its left is stringwise equal to the string to its right.
Syntax: String1 eq String2
Returns: 1 if left argument is equal to the right argument
Example 1:
#!/usr/local/bin/perl # Initializing Strings$a = "Welcome";$b = "Geeks"; # Comparing the strings using eq operator$c = $a eq $b; if($c == 1){ print"String1 is equal to String2";}else{ print"String1 is not equal to String2";}
String1 is not equal to String2
Example 2:
#!/usr/local/bin/perl # Initializing Strings$a = "Geeks";$b = "Geeks"; # Comparing the strings using eq operator$c = $a eq $b; if($c == 1){ print"String1 is equal to String2";}else{ print"String1 is not equal to String2";}
String1 is equal to String2
perl-operators
Perl-String-Operators
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Perl | Arrays (push, pop, shift, unshift)
Perl | Arrays
Perl Tutorial - Learn Perl With Examples
Perl | Polymorphism in OOPs
Perl | Boolean Values
Perl | length() Function
Perl | Subroutines or Functions
Hello World Program in Perl
Use of print() and say() in Perl
Perl | Basic Syntax of a Perl Program
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 May, 2019"
},
{
"code": null,
"e": 237,
"s": 28,
"text": "‘eq‘ operator in Perl is one of the string comparison operators used to check for the equality of the two strings. It is used to check if the string to its left is stringwise equal to the string to its right."
},
{
"code": null,
"e": 264,
"s": 237,
"text": "Syntax: String1 eq String2"
},
{
"code": null,
"e": 323,
"s": 264,
"text": "Returns: 1 if left argument is equal to the right argument"
},
{
"code": null,
"e": 334,
"s": 323,
"text": "Example 1:"
},
{
"code": "#!/usr/local/bin/perl # Initializing Strings$a = \"Welcome\";$b = \"Geeks\"; # Comparing the strings using eq operator$c = $a eq $b; if($c == 1){ print\"String1 is equal to String2\";}else{ print\"String1 is not equal to String2\";}",
"e": 568,
"s": 334,
"text": null
},
{
"code": null,
"e": 601,
"s": 568,
"text": "String1 is not equal to String2\n"
},
{
"code": null,
"e": 612,
"s": 601,
"text": "Example 2:"
},
{
"code": "#!/usr/local/bin/perl # Initializing Strings$a = \"Geeks\";$b = \"Geeks\"; # Comparing the strings using eq operator$c = $a eq $b; if($c == 1){ print\"String1 is equal to String2\";}else{ print\"String1 is not equal to String2\";}",
"e": 844,
"s": 612,
"text": null
},
{
"code": null,
"e": 873,
"s": 844,
"text": "String1 is equal to String2\n"
},
{
"code": null,
"e": 888,
"s": 873,
"text": "perl-operators"
},
{
"code": null,
"e": 910,
"s": 888,
"text": "Perl-String-Operators"
},
{
"code": null,
"e": 915,
"s": 910,
"text": "Perl"
},
{
"code": null,
"e": 920,
"s": 915,
"text": "Perl"
},
{
"code": null,
"e": 1018,
"s": 920,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1060,
"s": 1018,
"text": "Perl | Arrays (push, pop, shift, unshift)"
},
{
"code": null,
"e": 1074,
"s": 1060,
"text": "Perl | Arrays"
},
{
"code": null,
"e": 1115,
"s": 1074,
"text": "Perl Tutorial - Learn Perl With Examples"
},
{
"code": null,
"e": 1143,
"s": 1115,
"text": "Perl | Polymorphism in OOPs"
},
{
"code": null,
"e": 1165,
"s": 1143,
"text": "Perl | Boolean Values"
},
{
"code": null,
"e": 1190,
"s": 1165,
"text": "Perl | length() Function"
},
{
"code": null,
"e": 1222,
"s": 1190,
"text": "Perl | Subroutines or Functions"
},
{
"code": null,
"e": 1250,
"s": 1222,
"text": "Hello World Program in Perl"
},
{
"code": null,
"e": 1283,
"s": 1250,
"text": "Use of print() and say() in Perl"
}
] |
HTTP headers | If-Match
|
21 May, 2020
The HTTP headers If-Match is request-type header. It is used to make the request conditional. If it matches one of the listed conditional ETags then the server will send back the requested resource for PUT and other non-safe methods, it will only upload the resource in this case.
This ETag header uses a string comparison algorithm. Using this header are two common use cases:
it can ensure that the modern ranges requested comes from the same resource than the past one. For GET and HEAD methods, utilized in combination with a Run header.if at a point a 416 (Range Not Satisfiable) reaction is returned, then it doesn’t coordinate.
If-Match can be utilized to anticipate the misplaced upgrade issue, For other methods, and in specific for PUT. It can check in case the alteration of a resource that the client needs to transfer will not override another alter that has been done since the first resource was gotten. the 412 (Precondition Fizzled) response is returned if the response is not requested.
Syntax
If-Match:<*;
If-Match:<etag_value>, <etag_value>, ...
Directives: This header accept two directives as mentioned above and described below:
<etag_value> This directive holds the value of the Etag list, values are in form of string of ASCII characters placed between double quotes. Used prefixed by W/ to indicate that they are “weak”.
*:
The asterisk directive could be a special value representing a resource.
Examples:
If-Match: *
If-Match: "afyr456nfk560hfef5bhoy007dfhgfd9h"
To check the HTTP headers If-Match in action go to Inspect Element -> Network check the request header
Supported Browsers: The browsers are compatible with HTTP header If-Match are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
Microsoft Edge
HTTP-headers
Picked
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
REST API (Introduction)
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
How to float three div side by side using CSS?
ReactJS | Router
How to get character array from string in JavaScript?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 May, 2020"
},
{
"code": null,
"e": 309,
"s": 28,
"text": "The HTTP headers If-Match is request-type header. It is used to make the request conditional. If it matches one of the listed conditional ETags then the server will send back the requested resource for PUT and other non-safe methods, it will only upload the resource in this case."
},
{
"code": null,
"e": 406,
"s": 309,
"text": "This ETag header uses a string comparison algorithm. Using this header are two common use cases:"
},
{
"code": null,
"e": 663,
"s": 406,
"text": "it can ensure that the modern ranges requested comes from the same resource than the past one. For GET and HEAD methods, utilized in combination with a Run header.if at a point a 416 (Range Not Satisfiable) reaction is returned, then it doesn’t coordinate."
},
{
"code": null,
"e": 1033,
"s": 663,
"text": "If-Match can be utilized to anticipate the misplaced upgrade issue, For other methods, and in specific for PUT. It can check in case the alteration of a resource that the client needs to transfer will not override another alter that has been done since the first resource was gotten. the 412 (Precondition Fizzled) response is returned if the response is not requested."
},
{
"code": null,
"e": 1040,
"s": 1033,
"text": "Syntax"
},
{
"code": null,
"e": 1094,
"s": 1040,
"text": "If-Match:<*;\nIf-Match:<etag_value>, <etag_value>, ..."
},
{
"code": null,
"e": 1180,
"s": 1094,
"text": "Directives: This header accept two directives as mentioned above and described below:"
},
{
"code": null,
"e": 1375,
"s": 1180,
"text": "<etag_value> This directive holds the value of the Etag list, values are in form of string of ASCII characters placed between double quotes. Used prefixed by W/ to indicate that they are “weak”."
},
{
"code": null,
"e": 1378,
"s": 1375,
"text": "*:"
},
{
"code": null,
"e": 1451,
"s": 1378,
"text": "The asterisk directive could be a special value representing a resource."
},
{
"code": null,
"e": 1461,
"s": 1451,
"text": "Examples:"
},
{
"code": null,
"e": 1473,
"s": 1461,
"text": "If-Match: *"
},
{
"code": null,
"e": 1519,
"s": 1473,
"text": "If-Match: \"afyr456nfk560hfef5bhoy007dfhgfd9h\""
},
{
"code": null,
"e": 1622,
"s": 1519,
"text": "To check the HTTP headers If-Match in action go to Inspect Element -> Network check the request header"
},
{
"code": null,
"e": 1714,
"s": 1622,
"text": "Supported Browsers: The browsers are compatible with HTTP header If-Match are listed below:"
},
{
"code": null,
"e": 1728,
"s": 1714,
"text": "Google Chrome"
},
{
"code": null,
"e": 1746,
"s": 1728,
"text": "Internet Explorer"
},
{
"code": null,
"e": 1754,
"s": 1746,
"text": "Firefox"
},
{
"code": null,
"e": 1760,
"s": 1754,
"text": "Opera"
},
{
"code": null,
"e": 1767,
"s": 1760,
"text": "Safari"
},
{
"code": null,
"e": 1782,
"s": 1767,
"text": "Microsoft Edge"
},
{
"code": null,
"e": 1795,
"s": 1782,
"text": "HTTP-headers"
},
{
"code": null,
"e": 1802,
"s": 1795,
"text": "Picked"
},
{
"code": null,
"e": 1819,
"s": 1802,
"text": "Web Technologies"
},
{
"code": null,
"e": 1917,
"s": 1819,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1978,
"s": 1917,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2021,
"s": 1978,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 2093,
"s": 2021,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 2133,
"s": 2093,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2157,
"s": 2133,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 2198,
"s": 2157,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 2240,
"s": 2198,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 2287,
"s": 2240,
"text": "How to float three div side by side using CSS?"
},
{
"code": null,
"e": 2304,
"s": 2287,
"text": "ReactJS | Router"
}
] |
p5.js | save() Function
|
23 Aug, 2021
The save() function in p5.js is used to save to the file system by prompting a download to the computer. This function can be used to save text, images, JSON, CSV, wav, or HTML files. The default option is to save the current canvas as an image.The first parameter of the function can be specified various values depending on the file to save. Examples include a pointer to the canvas element, an array of Strings, a JSON object, or an array, a p5.Table element for tables, a p5.Image element for images or a p5.SoundFile element for sounds.Note: It is not recommended to call this function inside the draw() loop, as it will prompt a new save dialog every draw call.
Syntax:
save( [objectOrFilename], [filename], [options] )
Parameters: This function accepts three parameter as mentioned above and described below.
objectOrFilename: This is an Object or String that is used to denote the object to save or the filename (if saving the canvas). If an Object is provided, it will save the file depending upon the object and filename. It is an optional parameter.
filename: It specifies the String that is used as the filename of the saved file. It is an optional parameter.
options: It is a Boolean value or String which provides additional options for the file to be saved. Incase of JSON files, a value of ‘true’ would save the JSON optimized for filesize, instead of readability. It is an optional parameter.
The examples below illustrate the save() function in p5.js:Example 1:
javascript
function setup() { createCanvas(500, 300); textSize(18); background("lightgreen"); text("Click on the buttons below to save different types of files", 20, 20); // Create a button for saving text saveTextBtn = createButton("Save Text"); saveTextBtn.position(30, 60); saveTextBtn.mousePressed(saveAsText); // Create a button for saving canvas image saveImageBtn = createButton("Save Canvas"); saveImageBtn.position(150, 60); saveImageBtn.mousePressed(saveAsCanvas); // Create a button for saving JSON saveJSONBtn = createButton("Save JSON"); saveJSONBtn.position(30, 100); saveJSONBtn.mousePressed(saveAsJSON); // Create a button for saving CSV saveCSVBtn = createButton("Save CSV"); saveCSVBtn.position(150, 100); saveCSVBtn.mousePressed(saveAsCSV);} function saveAsText() { let textToSave = ["Hello", "GeeksforGeeks!"]; save(textToSave, "output_text.txt");} function saveAsCanvas() { save("output_canvas.png");} function saveAsJSON() { let exampleObj = [ { name: "Samuel", age: 23, }, { name: "Axel", age: 15, }, ]; save(exampleObj, "output_text.json");} function saveAsCSV() { let exampleTable = new p5.Table(); let newRow = exampleTable.addRow(); exampleTable.addColumn("author"); exampleTable.addColumn("language"); newRow.setString("author", "Dennis Ritchie"); newRow.setString("language", "C"); save(exampleTable, "output_CSV.csv");}
Output:
Example 2:
javascript
function setup() { createCanvas(500, 300); textSize(22); text("Click on the button below to save the written text", 20, 20); // Create a textarea for the input of text inputArea = createElement("textarea"); inputArea.position(30, 50); inputArea.size(400, 120); // Create a button for saving text saveBtn = createButton("Save text to file"); saveBtn.position(30, 200); saveBtn.mousePressed(saveFile);} function saveFile() { // Get the value of the textarea // Split according to nextline characters stringList = inputArea.value().split("\n"); // Save the strings to file save(stringList, "output_file.txt");}
Output:
Online editor: https://editor.p5js.org/Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/Reference: https://p5js.org/reference/#/p5/save
simmytarika5
JavaScript-p5.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
Difference Between PUT and PATCH Request
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Aug, 2021"
},
{
"code": null,
"e": 697,
"s": 28,
"text": "The save() function in p5.js is used to save to the file system by prompting a download to the computer. This function can be used to save text, images, JSON, CSV, wav, or HTML files. The default option is to save the current canvas as an image.The first parameter of the function can be specified various values depending on the file to save. Examples include a pointer to the canvas element, an array of Strings, a JSON object, or an array, a p5.Table element for tables, a p5.Image element for images or a p5.SoundFile element for sounds.Note: It is not recommended to call this function inside the draw() loop, as it will prompt a new save dialog every draw call. "
},
{
"code": null,
"e": 706,
"s": 697,
"text": "Syntax: "
},
{
"code": null,
"e": 756,
"s": 706,
"text": "save( [objectOrFilename], [filename], [options] )"
},
{
"code": null,
"e": 848,
"s": 756,
"text": "Parameters: This function accepts three parameter as mentioned above and described below. "
},
{
"code": null,
"e": 1093,
"s": 848,
"text": "objectOrFilename: This is an Object or String that is used to denote the object to save or the filename (if saving the canvas). If an Object is provided, it will save the file depending upon the object and filename. It is an optional parameter."
},
{
"code": null,
"e": 1204,
"s": 1093,
"text": "filename: It specifies the String that is used as the filename of the saved file. It is an optional parameter."
},
{
"code": null,
"e": 1442,
"s": 1204,
"text": "options: It is a Boolean value or String which provides additional options for the file to be saved. Incase of JSON files, a value of ‘true’ would save the JSON optimized for filesize, instead of readability. It is an optional parameter."
},
{
"code": null,
"e": 1512,
"s": 1442,
"text": "The examples below illustrate the save() function in p5.js:Example 1:"
},
{
"code": null,
"e": 1523,
"s": 1512,
"text": "javascript"
},
{
"code": "function setup() { createCanvas(500, 300); textSize(18); background(\"lightgreen\"); text(\"Click on the buttons below to save different types of files\", 20, 20); // Create a button for saving text saveTextBtn = createButton(\"Save Text\"); saveTextBtn.position(30, 60); saveTextBtn.mousePressed(saveAsText); // Create a button for saving canvas image saveImageBtn = createButton(\"Save Canvas\"); saveImageBtn.position(150, 60); saveImageBtn.mousePressed(saveAsCanvas); // Create a button for saving JSON saveJSONBtn = createButton(\"Save JSON\"); saveJSONBtn.position(30, 100); saveJSONBtn.mousePressed(saveAsJSON); // Create a button for saving CSV saveCSVBtn = createButton(\"Save CSV\"); saveCSVBtn.position(150, 100); saveCSVBtn.mousePressed(saveAsCSV);} function saveAsText() { let textToSave = [\"Hello\", \"GeeksforGeeks!\"]; save(textToSave, \"output_text.txt\");} function saveAsCanvas() { save(\"output_canvas.png\");} function saveAsJSON() { let exampleObj = [ { name: \"Samuel\", age: 23, }, { name: \"Axel\", age: 15, }, ]; save(exampleObj, \"output_text.json\");} function saveAsCSV() { let exampleTable = new p5.Table(); let newRow = exampleTable.addRow(); exampleTable.addColumn(\"author\"); exampleTable.addColumn(\"language\"); newRow.setString(\"author\", \"Dennis Ritchie\"); newRow.setString(\"language\", \"C\"); save(exampleTable, \"output_CSV.csv\");}",
"e": 2933,
"s": 1523,
"text": null
},
{
"code": null,
"e": 2942,
"s": 2933,
"text": "Output: "
},
{
"code": null,
"e": 2953,
"s": 2942,
"text": "Example 2:"
},
{
"code": null,
"e": 2964,
"s": 2953,
"text": "javascript"
},
{
"code": "function setup() { createCanvas(500, 300); textSize(22); text(\"Click on the button below to save the written text\", 20, 20); // Create a textarea for the input of text inputArea = createElement(\"textarea\"); inputArea.position(30, 50); inputArea.size(400, 120); // Create a button for saving text saveBtn = createButton(\"Save text to file\"); saveBtn.position(30, 200); saveBtn.mousePressed(saveFile);} function saveFile() { // Get the value of the textarea // Split according to nextline characters stringList = inputArea.value().split(\"\\n\"); // Save the strings to file save(stringList, \"output_file.txt\");}",
"e": 3592,
"s": 2964,
"text": null
},
{
"code": null,
"e": 3601,
"s": 3592,
"text": "Output: "
},
{
"code": null,
"e": 3785,
"s": 3601,
"text": "Online editor: https://editor.p5js.org/Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/Reference: https://p5js.org/reference/#/p5/save"
},
{
"code": null,
"e": 3798,
"s": 3785,
"text": "simmytarika5"
},
{
"code": null,
"e": 3815,
"s": 3798,
"text": "JavaScript-p5.js"
},
{
"code": null,
"e": 3826,
"s": 3815,
"text": "JavaScript"
},
{
"code": null,
"e": 3843,
"s": 3826,
"text": "Web Technologies"
},
{
"code": null,
"e": 3941,
"s": 3843,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4002,
"s": 3941,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4074,
"s": 4002,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 4114,
"s": 4074,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 4167,
"s": 4114,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 4208,
"s": 4167,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 4241,
"s": 4208,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 4303,
"s": 4241,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 4364,
"s": 4303,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4414,
"s": 4364,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Python Program to perform cross join in Pandas
|
10 Jul, 2020
In Pandas, there are parameters to perform left, right, inner or outer merge and join on two DataFrames or Series. However there’s no possibility as of now to perform a cross join to merge or join two methods using how="cross" parameter.
Cross Join :
Example 1:
The above example is proven as follows
# importing pandas moduleimport pandas as pd # Define a dictionary with column Adata1 = {'A': [1, 2]} # Define another dictionary with column Bdata2 = {'B': ['a', 'b', 'c']} # Convert the dictionary into DataFrame df = pd.DataFrame(data1, index =[0, 1]) # Convert the dictionary into DataFrame df1 = pd.DataFrame(data2, index =[2, 3, 4]) # Now to perform cross join, we will create# a key column in both the DataFrames to # merge on that key.df['key'] = 1df1['key'] = 1 # to obtain the cross join we will merge # on the key and drop it.result = pd.merge(df, df1, on ='key').drop("key", 1) result
DataFrame 1: DataFrame 2 : Output :
Example 2:
Cross join on two DataFrames for user and product.
# importing pandas moduleimport pandas as pd # Define a dictionary containing user IDdata1 = {'Name': ["Rebecca", "Maryam", "Anita"], 'UserID': [1, 2, 3]} # Define a dictionary containing product ID data2 = {'ProductID': ['P1', 'P2', 'P3', 'P4']} # Convert the dictionary into DataFrame df = pd.DataFrame(data1, index =[0, 1, 2]) # Convert the dictionary into DataFrame df1 = pd.DataFrame(data2, index =[2, 3, 6, 7]) # Now to perform cross join, we will create# a key column in both the DataFrames to # merge on that key.df['key'] = 1df1['key'] = 1 # to obtain the cross join we will merge on # the key and drop it.result = pd.merge(df, df1, on ='key').drop("key", 1) result
DataFrame 1: DataFrame 2 : Output :
Example 3:
# importing pandas moduleimport pandas as pd # Define a dictionary with two columnsdata1 = {'col 1': [0, 1], 'col 2': [2, 3]} # Define another dictionary data2 = {'col 3': [5, 6], 'col 4': [7, 8]} # Convert the dictionary into DataFrame df = pd.DataFrame(data1, index =[0, 1]) # Convert the dictionary into DataFrame df1 = pd.DataFrame(data2, index =[2, 3]) # Now to perform cross join, we will create# a key column in both the DataFrames to# merge on that key.df['key'] = 1df1['key'] = 1 # to obtain the cross join we will merge on # the key and drop it.result = pd.merge(df, df1, on ='key').drop("key", 1) result
DataFrame 1: DataFrame 2 : Output :
pandas-dataframe-program
Python pandas-dataFrame
Python-pandas
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
Read a file line by line in Python
Python String | replace()
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 Program for Fibonacci numbers
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Jul, 2020"
},
{
"code": null,
"e": 266,
"s": 28,
"text": "In Pandas, there are parameters to perform left, right, inner or outer merge and join on two DataFrames or Series. However there’s no possibility as of now to perform a cross join to merge or join two methods using how=\"cross\" parameter."
},
{
"code": null,
"e": 279,
"s": 266,
"text": "Cross Join :"
},
{
"code": null,
"e": 290,
"s": 279,
"text": "Example 1:"
},
{
"code": null,
"e": 329,
"s": 290,
"text": "The above example is proven as follows"
},
{
"code": "# importing pandas moduleimport pandas as pd # Define a dictionary with column Adata1 = {'A': [1, 2]} # Define another dictionary with column Bdata2 = {'B': ['a', 'b', 'c']} # Convert the dictionary into DataFrame df = pd.DataFrame(data1, index =[0, 1]) # Convert the dictionary into DataFrame df1 = pd.DataFrame(data2, index =[2, 3, 4]) # Now to perform cross join, we will create# a key column in both the DataFrames to # merge on that key.df['key'] = 1df1['key'] = 1 # to obtain the cross join we will merge # on the key and drop it.result = pd.merge(df, df1, on ='key').drop(\"key\", 1) result",
"e": 945,
"s": 329,
"text": null
},
{
"code": null,
"e": 982,
"s": 945,
"text": "DataFrame 1: DataFrame 2 : Output : "
},
{
"code": null,
"e": 993,
"s": 982,
"text": "Example 2:"
},
{
"code": null,
"e": 1044,
"s": 993,
"text": "Cross join on two DataFrames for user and product."
},
{
"code": "# importing pandas moduleimport pandas as pd # Define a dictionary containing user IDdata1 = {'Name': [\"Rebecca\", \"Maryam\", \"Anita\"], 'UserID': [1, 2, 3]} # Define a dictionary containing product ID data2 = {'ProductID': ['P1', 'P2', 'P3', 'P4']} # Convert the dictionary into DataFrame df = pd.DataFrame(data1, index =[0, 1, 2]) # Convert the dictionary into DataFrame df1 = pd.DataFrame(data2, index =[2, 3, 6, 7]) # Now to perform cross join, we will create# a key column in both the DataFrames to # merge on that key.df['key'] = 1df1['key'] = 1 # to obtain the cross join we will merge on # the key and drop it.result = pd.merge(df, df1, on ='key').drop(\"key\", 1) result",
"e": 1745,
"s": 1044,
"text": null
},
{
"code": null,
"e": 1782,
"s": 1745,
"text": "DataFrame 1: DataFrame 2 : Output : "
},
{
"code": null,
"e": 1793,
"s": 1782,
"text": "Example 3:"
},
{
"code": "# importing pandas moduleimport pandas as pd # Define a dictionary with two columnsdata1 = {'col 1': [0, 1], 'col 2': [2, 3]} # Define another dictionary data2 = {'col 3': [5, 6], 'col 4': [7, 8]} # Convert the dictionary into DataFrame df = pd.DataFrame(data1, index =[0, 1]) # Convert the dictionary into DataFrame df1 = pd.DataFrame(data2, index =[2, 3]) # Now to perform cross join, we will create# a key column in both the DataFrames to# merge on that key.df['key'] = 1df1['key'] = 1 # to obtain the cross join we will merge on # the key and drop it.result = pd.merge(df, df1, on ='key').drop(\"key\", 1) result",
"e": 2442,
"s": 1793,
"text": null
},
{
"code": null,
"e": 2479,
"s": 2442,
"text": "DataFrame 1: DataFrame 2 : Output : "
},
{
"code": null,
"e": 2504,
"s": 2479,
"text": "pandas-dataframe-program"
},
{
"code": null,
"e": 2528,
"s": 2504,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 2542,
"s": 2528,
"text": "Python-pandas"
},
{
"code": null,
"e": 2549,
"s": 2542,
"text": "Python"
},
{
"code": null,
"e": 2565,
"s": 2549,
"text": "Python Programs"
},
{
"code": null,
"e": 2663,
"s": 2565,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2681,
"s": 2663,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2723,
"s": 2681,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2745,
"s": 2723,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2780,
"s": 2745,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2806,
"s": 2780,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2849,
"s": 2806,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 2871,
"s": 2849,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2910,
"s": 2871,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2948,
"s": 2910,
"text": "Python | Convert a list to dictionary"
}
] |
How to Zip a directory in PHP?
|
We can use PHP ZipArchive class in order to zipping and unzipping the folder in PHP. As of PHP 5.3, this class is inbuilt. For using in windows users need to enable php_zip.dll inside of php.ini.
<?php
//Enter the name of directory
$pathdir = "Directory Name/";
//Enter the name to creating zipped directory
$zipcreated = "test.zip";
//Create new zip class
$newzip = new ZipArchive;
if($newzip -> open($zipcreated, ZipArchive::CREATE ) === TRUE) {
$dir = opendir($pathdir);
while($file = readdir($dir)) {
if(is_file($pathdir.$file)) {
$newzip -> addFile($pathdir.$file, $file);
}
}
$newzip ->close();
}
?>
|
[
{
"code": null,
"e": 1383,
"s": 1187,
"text": "We can use PHP ZipArchive class in order to zipping and unzipping the folder in PHP. As of PHP 5.3, this class is inbuilt. For using in windows users need to enable php_zip.dll inside of php.ini."
},
{
"code": null,
"e": 1862,
"s": 1383,
"text": "<?php\n//Enter the name of directory\n $pathdir = \"Directory Name/\";\n//Enter the name to creating zipped directory\n $zipcreated = \"test.zip\";\n//Create new zip class\n $newzip = new ZipArchive;\n if($newzip -> open($zipcreated, ZipArchive::CREATE ) === TRUE) {\n $dir = opendir($pathdir);\n while($file = readdir($dir)) {\n if(is_file($pathdir.$file)) {\n $newzip -> addFile($pathdir.$file, $file);\n }\n }\n $newzip ->close();\n }\n?>"
}
] |
How to remove border radius from Select tag using Bootstrap ?
|
26 Jun, 2020
<select> Tag: The <select> component is used to make a drop-down list. The <select> component is most frequently used in a form, to gather user input. The name attribute is required to reference the form data after the form is submitted (in case you exclude the name attribute, no data from the drop-down list will be submitted). The id attribute is required to relate the drop-down list with a name. The <option> tag inside the <select> component characterize the accessible choices within the drop-down list.
Syntax:
<select>
<option>Option1</option>
<option>Option2</option>
.
.
.
<option>Option n</option>
</select>
Attributes:
autofocus: Indicates that the drop-down list ought to consequently get focus when the page loads. (value: autofocus)
disabled: Indicates that a drop-down list ought to be disabled. (value: disabled)
form: Characterizes which form the drop-down list has a place to. (value: form_id)
multiple: Indicates that multiple options can be chosen at once. (value: multiple)
name: Characterizes a name for the drop-down list. (value: name)
required: Indicates that the user is required to choose a value some time recently submitting the form. (value: required)
size: Characterizes the number of visible options in a drop-down list. (value: number)
We can remove border radius from Select tag by two methods as follows:
Method 1: Using CSS: Use some CSS property to remove the border radius.
Example:
HTML
<!DOCTYPE html><html lang="en"> <head> <title> Remove border radius from Select tag in css </title> <style type="text/css"> /* To remove border radius */ select { height: 20px; -webkit-border-radius: 0; border: 0; outline: 1px solid #ccc; outline-offset: -1px; } </style></head> <body> <center> <h3 style="color: green"><br /> GeeksforGeeks </h3><br /> <select> <option>Option1</option> <option>Option2</option> <option>Option3</option> <option>Option4</option> <option>Option5</option> </select> </center></body> </html>
Output:
Method 2: Using Bootstrap: The user-agent stylesheet for Chrome gives a border-radius of 5px to all the corners of a <select> component. Custom select menus require as it were a custom class, .custom-select to trigger the custom styles. Custom styles are restricted to the select’s starting appearance and cannot alter the option’s due to browser restrictions.
Example:
HTML
<!DOCTYPE html><html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content= "width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <script src="https://kit.fontawesome.com/577845f6a5.js" crossorigin="anonymous"> </script> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"> </script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"> </script> <title> Remove border radius from Select tag in bootstrap </title> <style type="text/css"> /* For default browser setting */ select:not([multiple]) { -webkit-appearance: none; -moz-appearance: none; padding: .5em; padding-right: 1.5em } /* To remove default border radius */ #mySelect { border-radius: 0 } /* Optional styling */ option { font-size: 1.1rem !important; font-weight: bold; text-transform: uppercase !important; color: #013208 !important; } </style></head> <body> <center> <br /> <h3 style="color: green"><br /> GeeksforGeeks </h3><br /> <select id="mySelect" class="custom-select" style="width:150px; background-color: lightgreen; font-weight:bold;color:#013208;"> <option value="1">G</option> <option value="2">E</option> <option value="3">E</option> <option value="4">K</option> <option value="5">S</option> <option value="6">F</option> <option value="7">O</option> <option value="8">R</option> <option value="9">G</option> <option value="10">E</option> <option value="11">E</option> <option value="12">K</option> <option value="13">S</option> </select> </center></body> </html>
Output:
We can use select tag and .custom-select class with form-control as follows
Example:
HTML
<!DOCTYPE html><html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content= "width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <script src="https://kit.fontawesome.com/577845f6a5.js" crossorigin="anonymous"> </script> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"> </script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"> </script> <title> Remove border radius from Select tag in bootstrap </title> <style type="text/css"> /* For default browser setting */ select:not([multiple]) { -webkit-appearance: none; -moz-appearance: none; padding: .5em; padding-right: 1.5em } /* To remove default border radius */ #mySelect { border-radius: 0 } </style></head> <body> <center> <br /> <h3 style="color: green"><br /> GeeksforGeeks </h3><br /> <form> <div class="form-group"> <label for="mySelect">Email address</label> <input type="email" class="form-control" id="mySelect" style="width:350px;" placeholder="name@example.com"> </div> <div class="form-group"> <label for="mySelect"> Select options </label><br /> <select class="form-control custom-select" style="width:150px;" id="mySelect"> <option>Option 1</option> <option>Option 2</option> <option>Option 3</option> <option>Option 4</option> <option>Option 5</option> </select> </div> </form> </center></body> </html>
Output:
Bootstrap-Misc
CSS-Misc
HTML-Misc
Picked
Bootstrap
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Jun, 2020"
},
{
"code": null,
"e": 539,
"s": 28,
"text": "<select> Tag: The <select> component is used to make a drop-down list. The <select> component is most frequently used in a form, to gather user input. The name attribute is required to reference the form data after the form is submitted (in case you exclude the name attribute, no data from the drop-down list will be submitted). The id attribute is required to relate the drop-down list with a name. The <option> tag inside the <select> component characterize the accessible choices within the drop-down list."
},
{
"code": null,
"e": 547,
"s": 539,
"text": "Syntax:"
},
{
"code": null,
"e": 674,
"s": 547,
"text": "<select>\n <option>Option1</option>\n <option>Option2</option>\n .\n .\n .\n <option>Option n</option>\n </select>\n"
},
{
"code": null,
"e": 686,
"s": 674,
"text": "Attributes:"
},
{
"code": null,
"e": 803,
"s": 686,
"text": "autofocus: Indicates that the drop-down list ought to consequently get focus when the page loads. (value: autofocus)"
},
{
"code": null,
"e": 885,
"s": 803,
"text": "disabled: Indicates that a drop-down list ought to be disabled. (value: disabled)"
},
{
"code": null,
"e": 968,
"s": 885,
"text": "form: Characterizes which form the drop-down list has a place to. (value: form_id)"
},
{
"code": null,
"e": 1051,
"s": 968,
"text": "multiple: Indicates that multiple options can be chosen at once. (value: multiple)"
},
{
"code": null,
"e": 1116,
"s": 1051,
"text": "name: Characterizes a name for the drop-down list. (value: name)"
},
{
"code": null,
"e": 1238,
"s": 1116,
"text": "required: Indicates that the user is required to choose a value some time recently submitting the form. (value: required)"
},
{
"code": null,
"e": 1325,
"s": 1238,
"text": "size: Characterizes the number of visible options in a drop-down list. (value: number)"
},
{
"code": null,
"e": 1396,
"s": 1325,
"text": "We can remove border radius from Select tag by two methods as follows:"
},
{
"code": null,
"e": 1468,
"s": 1396,
"text": "Method 1: Using CSS: Use some CSS property to remove the border radius."
},
{
"code": null,
"e": 1477,
"s": 1468,
"text": "Example:"
},
{
"code": null,
"e": 1482,
"s": 1477,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <title> Remove border radius from Select tag in css </title> <style type=\"text/css\"> /* To remove border radius */ select { height: 20px; -webkit-border-radius: 0; border: 0; outline: 1px solid #ccc; outline-offset: -1px; } </style></head> <body> <center> <h3 style=\"color: green\"><br /> GeeksforGeeks </h3><br /> <select> <option>Option1</option> <option>Option2</option> <option>Option3</option> <option>Option4</option> <option>Option5</option> </select> </center></body> </html>",
"e": 2109,
"s": 1482,
"text": null
},
{
"code": null,
"e": 2117,
"s": 2109,
"text": "Output:"
},
{
"code": null,
"e": 2478,
"s": 2117,
"text": "Method 2: Using Bootstrap: The user-agent stylesheet for Chrome gives a border-radius of 5px to all the corners of a <select> component. Custom select menus require as it were a custom class, .custom-select to trigger the custom styles. Custom styles are restricted to the select’s starting appearance and cannot alter the option’s due to browser restrictions."
},
{
"code": null,
"e": 2487,
"s": 2478,
"text": "Example:"
},
{
"code": null,
"e": 2492,
"s": 2487,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <!-- Required meta tags --> <meta charset=\"utf-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1, shrink-to-fit=no\"> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css\" integrity=\"sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk\" crossorigin=\"anonymous\"> <script src=\"https://kit.fontawesome.com/577845f6a5.js\" crossorigin=\"anonymous\"> </script> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.5.1.slim.min.js\" integrity=\"sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"> </script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js\" integrity=\"sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI\" crossorigin=\"anonymous\"> </script> <title> Remove border radius from Select tag in bootstrap </title> <style type=\"text/css\"> /* For default browser setting */ select:not([multiple]) { -webkit-appearance: none; -moz-appearance: none; padding: .5em; padding-right: 1.5em } /* To remove default border radius */ #mySelect { border-radius: 0 } /* Optional styling */ option { font-size: 1.1rem !important; font-weight: bold; text-transform: uppercase !important; color: #013208 !important; } </style></head> <body> <center> <br /> <h3 style=\"color: green\"><br /> GeeksforGeeks </h3><br /> <select id=\"mySelect\" class=\"custom-select\" style=\"width:150px; background-color: lightgreen; font-weight:bold;color:#013208;\"> <option value=\"1\">G</option> <option value=\"2\">E</option> <option value=\"3\">E</option> <option value=\"4\">K</option> <option value=\"5\">S</option> <option value=\"6\">F</option> <option value=\"7\">O</option> <option value=\"8\">R</option> <option value=\"9\">G</option> <option value=\"10\">E</option> <option value=\"11\">E</option> <option value=\"12\">K</option> <option value=\"13\">S</option> </select> </center></body> </html>",
"e": 5051,
"s": 2492,
"text": null
},
{
"code": null,
"e": 5059,
"s": 5051,
"text": "Output:"
},
{
"code": null,
"e": 5135,
"s": 5059,
"text": "We can use select tag and .custom-select class with form-control as follows"
},
{
"code": null,
"e": 5144,
"s": 5135,
"text": "Example:"
},
{
"code": null,
"e": 5149,
"s": 5144,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <!-- Required meta tags --> <meta charset=\"utf-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1, shrink-to-fit=no\"> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css\" integrity=\"sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk\" crossorigin=\"anonymous\"> <script src=\"https://kit.fontawesome.com/577845f6a5.js\" crossorigin=\"anonymous\"> </script> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.5.1.slim.min.js\" integrity=\"sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"> </script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js\" integrity=\"sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI\" crossorigin=\"anonymous\"> </script> <title> Remove border radius from Select tag in bootstrap </title> <style type=\"text/css\"> /* For default browser setting */ select:not([multiple]) { -webkit-appearance: none; -moz-appearance: none; padding: .5em; padding-right: 1.5em } /* To remove default border radius */ #mySelect { border-radius: 0 } </style></head> <body> <center> <br /> <h3 style=\"color: green\"><br /> GeeksforGeeks </h3><br /> <form> <div class=\"form-group\"> <label for=\"mySelect\">Email address</label> <input type=\"email\" class=\"form-control\" id=\"mySelect\" style=\"width:350px;\" placeholder=\"name@example.com\"> </div> <div class=\"form-group\"> <label for=\"mySelect\"> Select options </label><br /> <select class=\"form-control custom-select\" style=\"width:150px;\" id=\"mySelect\"> <option>Option 1</option> <option>Option 2</option> <option>Option 3</option> <option>Option 4</option> <option>Option 5</option> </select> </div> </form> </center></body> </html>",
"e": 7595,
"s": 5149,
"text": null
},
{
"code": null,
"e": 7603,
"s": 7595,
"text": "Output:"
},
{
"code": null,
"e": 7618,
"s": 7603,
"text": "Bootstrap-Misc"
},
{
"code": null,
"e": 7627,
"s": 7618,
"text": "CSS-Misc"
},
{
"code": null,
"e": 7637,
"s": 7627,
"text": "HTML-Misc"
},
{
"code": null,
"e": 7644,
"s": 7637,
"text": "Picked"
},
{
"code": null,
"e": 7654,
"s": 7644,
"text": "Bootstrap"
},
{
"code": null,
"e": 7658,
"s": 7654,
"text": "CSS"
},
{
"code": null,
"e": 7663,
"s": 7658,
"text": "HTML"
},
{
"code": null,
"e": 7680,
"s": 7663,
"text": "Web Technologies"
},
{
"code": null,
"e": 7707,
"s": 7680,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 7712,
"s": 7707,
"text": "HTML"
}
] |
Python | Titanic Data EDA using Seaborn
|
03 Aug, 2021
What is EDA? Exploratory Data Analysis (EDA) is a method used to analyze and summarize datasets. Majority of the EDA techniques involve the use of graphs.
Titanic Dataset – It is one of the most popular datasets used for understanding machine learning basics. It contains information of all the passengers aboard the RMS Titanic, which unfortunately was shipwrecked. This dataset can be used to predict whether a given passenger survived or not.
The csv file can be downloaded from Kaggle.
Code: Loading data using Pandas
Python3
#importing pandas libraryimport pandas as pd #loading datatitanic = pd.read_csv('...\input\train.csv')
Seaborn: It is a python library used to statistically visualize data. Seaborn, built over Matplotlib, provides a better interface and ease of usage. It can be installed using the following command, pip3 install seaborn
Code: Printing data head
Python3
# View first five rows of the datasettitanic.head()
Output :
Code: Checking the NULL values
Python3
titanic.isnull().sum()
Output :
The columns having null values are: Age, Cabin, Embarked. They need to be filled up with appropriate values later on.
Features: The titanic dataset has roughly the following types of features:
Categorical/Nominal: Variables that can be divided into multiple categories but having no order or priority. Eg. Embarked (C = Cherbourg; Q = Queenstown; S = Southampton)
Binary: A subtype of categorical features, where the variable has only two categories. Eg: Sex (Male/Female)
Ordinal: They are similar to categorical features but they have an order(i.e can be sorted). Eg. Pclass (1, 2, 3)
Continuous: They can take up any value between the minimum and maximum values in a column. Eg. Age, Fare
Count: They represent the count of a variable. Eg. SibSp, Parch
Useless: They don’t contribute to the final outcome of an ML model. Here, PassengerId, Name, Cabin and Ticket might fall into this category.
Code: Graphical Analysis
Python3
import seaborn as snsimport matplotlib.pyplot as plt # Countplotsns.catplot(x ="Sex", hue ="Survived",kind ="count", data = titanic)
Output :
Just by observing the graph, it can be approximated that the survival rate of men is around 20% and that of women is around 75%. Therefore, whether a passenger is a male or a female plays an important role in determining if one is going to survive.
Code : Pclass (Ordinal Feature) vs Survived
Python3
# Group the dataset by Pclass and Survived and then unstack themgroup = titanic.groupby(['Pclass', 'Survived'])pclass_survived = group.size().unstack() # Heatmap - Color encoded 2D representation of data.sns.heatmap(pclass_survived, annot = True, fmt ="d")
Output:
It helps in determining if higher-class passengers had more survival rate than the lower class ones or vice versa. Class 1 passengers have a higher survival chance compared to classes 2 and 3. It implies that Pclass contributes a lot to a passenger’s survival rate.
Code : Age (Continuous Feature) vs Survived
Python3
# Violinplot Displays distribution of data# across all levels of a category.sns.violinplot(x ="Sex", y ="Age", hue ="Survived",data = titanic, split = True)
Output :
This graph gives a summary of the age range of men, women and children who were saved. The survival rate is –
Good for children.
High for women in the age range 20-50.
Less for men as the age increases.
Since Age column is important, the missing values need to be filled, either by using the Name column(ascertaining age based on salutation – Mr, Mrs etc.) or by using a regressor. After this step, another column – Age_Range (based on age column) can be created and the data can be analyzed again.
Code : Factor plot for Family_Size (Count Feature) and Family Size.
Python3
# Adding a column Family_Sizetitanic['Family_Size'] = 0titanic['Family_Size'] = titanic['Parch']+titanic['SibSp'] # Adding a column Alonetitanic['Alone'] = 0titanic.loc[titanic.Family_Size == 0, 'Alone'] = 1 # Factorplot for Family_Sizesns.factorplot(x ='Family_Size', y ='Survived', data = titanic) # Factorplot for Alonesns.factorplot(x ='Alone', y ='Survived', data = titanic)
Family_Size denotes the number of people in a passenger’s family. It is calculated by summing the SibSp and Parch columns of a respective passenger. Also, another column Alone is added to check the chances of survival of a lone passenger against the one with a family.
Important observations –
If a passenger is alone, the survival rate is less.
If the family size is greater than 5, chances of survival decrease considerably.
Code : Bar Plot for Fare (Continuous Feature)
Python3
# Divide Fare into 4 binstitanic['Fare_Range'] = pd.qcut(titanic['Fare'], 4) # Barplot - Shows approximate values based# on the height of bars.sns.barplot(x ='Fare_Range', y ='Survived',data = titanic)
Output :
Fare denotes the fare paid by a passenger. As the values in this column are continuous, they need to be put in separate bins(as done for Age feature) to get a clear idea. It can be concluded that if a passenger paid a higher fare, the survival rate is more.
Code: Categorical Count Plots for Embarked Feature
Python3
# Countplotsns.catplot(x ='Embarked', hue ='Survived',kind ='count', col ='Pclass', data = titanic)
Some notable observations are:
Majority of the passengers boarded from S. So, the missing values can be filled with S.
Majority of class 3 passengers boarded from Q.
S looks lucky for class 1 and 2 passengers compared to class 3.
Conclusion :
The columns that can be dropped are: PassengerId, Name, Ticket, Cabin: They are strings, cannot be categorized and don’t contribute much to the outcome. Age, Fare: Instead, the respective range columns are retained.
PassengerId, Name, Ticket, Cabin: They are strings, cannot be categorized and don’t contribute much to the outcome.
Age, Fare: Instead, the respective range columns are retained.
The titanic data can be analyzed using many more graph techniques and also more column correlations, than, as described in this article.
Once the EDA is completed, the resultant dataset can be used for predictions.
arorakashish0911
Technical Scripter 2019
Machine Learning
Python
Technical Scripter
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Reinforcement learning
Search Algorithms in AI
Supervised and Unsupervised learning
ML | Monte Carlo Tree Search (MCTS)
Read JSON file using Python
Python map() function
Adding new column to existing DataFrame in Pandas
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Aug, 2021"
},
{
"code": null,
"e": 183,
"s": 28,
"text": "What is EDA? Exploratory Data Analysis (EDA) is a method used to analyze and summarize datasets. Majority of the EDA techniques involve the use of graphs."
},
{
"code": null,
"e": 475,
"s": 183,
"text": "Titanic Dataset – It is one of the most popular datasets used for understanding machine learning basics. It contains information of all the passengers aboard the RMS Titanic, which unfortunately was shipwrecked. This dataset can be used to predict whether a given passenger survived or not. "
},
{
"code": null,
"e": 519,
"s": 475,
"text": "The csv file can be downloaded from Kaggle."
},
{
"code": null,
"e": 552,
"s": 519,
"text": "Code: Loading data using Pandas "
},
{
"code": null,
"e": 560,
"s": 552,
"text": "Python3"
},
{
"code": "#importing pandas libraryimport pandas as pd #loading datatitanic = pd.read_csv('...\\input\\train.csv')",
"e": 663,
"s": 560,
"text": null
},
{
"code": null,
"e": 882,
"s": 663,
"text": "Seaborn: It is a python library used to statistically visualize data. Seaborn, built over Matplotlib, provides a better interface and ease of usage. It can be installed using the following command, pip3 install seaborn"
},
{
"code": null,
"e": 909,
"s": 882,
"text": "Code: Printing data head "
},
{
"code": null,
"e": 917,
"s": 909,
"text": "Python3"
},
{
"code": "# View first five rows of the datasettitanic.head()",
"e": 969,
"s": 917,
"text": null
},
{
"code": null,
"e": 979,
"s": 969,
"text": "Output : "
},
{
"code": null,
"e": 1011,
"s": 979,
"text": "Code: Checking the NULL values "
},
{
"code": null,
"e": 1019,
"s": 1011,
"text": "Python3"
},
{
"code": "titanic.isnull().sum()",
"e": 1042,
"s": 1019,
"text": null
},
{
"code": null,
"e": 1052,
"s": 1042,
"text": "Output : "
},
{
"code": null,
"e": 1170,
"s": 1052,
"text": "The columns having null values are: Age, Cabin, Embarked. They need to be filled up with appropriate values later on."
},
{
"code": null,
"e": 1245,
"s": 1170,
"text": "Features: The titanic dataset has roughly the following types of features:"
},
{
"code": null,
"e": 1416,
"s": 1245,
"text": "Categorical/Nominal: Variables that can be divided into multiple categories but having no order or priority. Eg. Embarked (C = Cherbourg; Q = Queenstown; S = Southampton)"
},
{
"code": null,
"e": 1525,
"s": 1416,
"text": "Binary: A subtype of categorical features, where the variable has only two categories. Eg: Sex (Male/Female)"
},
{
"code": null,
"e": 1639,
"s": 1525,
"text": "Ordinal: They are similar to categorical features but they have an order(i.e can be sorted). Eg. Pclass (1, 2, 3)"
},
{
"code": null,
"e": 1744,
"s": 1639,
"text": "Continuous: They can take up any value between the minimum and maximum values in a column. Eg. Age, Fare"
},
{
"code": null,
"e": 1808,
"s": 1744,
"text": "Count: They represent the count of a variable. Eg. SibSp, Parch"
},
{
"code": null,
"e": 1949,
"s": 1808,
"text": "Useless: They don’t contribute to the final outcome of an ML model. Here, PassengerId, Name, Cabin and Ticket might fall into this category."
},
{
"code": null,
"e": 1975,
"s": 1949,
"text": "Code: Graphical Analysis "
},
{
"code": null,
"e": 1983,
"s": 1975,
"text": "Python3"
},
{
"code": "import seaborn as snsimport matplotlib.pyplot as plt # Countplotsns.catplot(x =\"Sex\", hue =\"Survived\",kind =\"count\", data = titanic)",
"e": 2116,
"s": 1983,
"text": null
},
{
"code": null,
"e": 2125,
"s": 2116,
"text": "Output :"
},
{
"code": null,
"e": 2374,
"s": 2125,
"text": "Just by observing the graph, it can be approximated that the survival rate of men is around 20% and that of women is around 75%. Therefore, whether a passenger is a male or a female plays an important role in determining if one is going to survive."
},
{
"code": null,
"e": 2420,
"s": 2374,
"text": "Code : Pclass (Ordinal Feature) vs Survived "
},
{
"code": null,
"e": 2428,
"s": 2420,
"text": "Python3"
},
{
"code": "# Group the dataset by Pclass and Survived and then unstack themgroup = titanic.groupby(['Pclass', 'Survived'])pclass_survived = group.size().unstack() # Heatmap - Color encoded 2D representation of data.sns.heatmap(pclass_survived, annot = True, fmt =\"d\")",
"e": 2685,
"s": 2428,
"text": null
},
{
"code": null,
"e": 2694,
"s": 2685,
"text": "Output: "
},
{
"code": null,
"e": 2960,
"s": 2694,
"text": "It helps in determining if higher-class passengers had more survival rate than the lower class ones or vice versa. Class 1 passengers have a higher survival chance compared to classes 2 and 3. It implies that Pclass contributes a lot to a passenger’s survival rate."
},
{
"code": null,
"e": 3006,
"s": 2960,
"text": "Code : Age (Continuous Feature) vs Survived "
},
{
"code": null,
"e": 3014,
"s": 3006,
"text": "Python3"
},
{
"code": "# Violinplot Displays distribution of data# across all levels of a category.sns.violinplot(x =\"Sex\", y =\"Age\", hue =\"Survived\",data = titanic, split = True)",
"e": 3171,
"s": 3014,
"text": null
},
{
"code": null,
"e": 3181,
"s": 3171,
"text": "Output : "
},
{
"code": null,
"e": 3293,
"s": 3181,
"text": "This graph gives a summary of the age range of men, women and children who were saved. The survival rate is – "
},
{
"code": null,
"e": 3312,
"s": 3293,
"text": "Good for children."
},
{
"code": null,
"e": 3351,
"s": 3312,
"text": "High for women in the age range 20-50."
},
{
"code": null,
"e": 3386,
"s": 3351,
"text": "Less for men as the age increases."
},
{
"code": null,
"e": 3683,
"s": 3386,
"text": "Since Age column is important, the missing values need to be filled, either by using the Name column(ascertaining age based on salutation – Mr, Mrs etc.) or by using a regressor. After this step, another column – Age_Range (based on age column) can be created and the data can be analyzed again. "
},
{
"code": null,
"e": 3753,
"s": 3683,
"text": "Code : Factor plot for Family_Size (Count Feature) and Family Size. "
},
{
"code": null,
"e": 3761,
"s": 3753,
"text": "Python3"
},
{
"code": "# Adding a column Family_Sizetitanic['Family_Size'] = 0titanic['Family_Size'] = titanic['Parch']+titanic['SibSp'] # Adding a column Alonetitanic['Alone'] = 0titanic.loc[titanic.Family_Size == 0, 'Alone'] = 1 # Factorplot for Family_Sizesns.factorplot(x ='Family_Size', y ='Survived', data = titanic) # Factorplot for Alonesns.factorplot(x ='Alone', y ='Survived', data = titanic)",
"e": 4141,
"s": 3761,
"text": null
},
{
"code": null,
"e": 4410,
"s": 4141,
"text": "Family_Size denotes the number of people in a passenger’s family. It is calculated by summing the SibSp and Parch columns of a respective passenger. Also, another column Alone is added to check the chances of survival of a lone passenger against the one with a family."
},
{
"code": null,
"e": 4436,
"s": 4410,
"text": "Important observations – "
},
{
"code": null,
"e": 4488,
"s": 4436,
"text": "If a passenger is alone, the survival rate is less."
},
{
"code": null,
"e": 4569,
"s": 4488,
"text": "If the family size is greater than 5, chances of survival decrease considerably."
},
{
"code": null,
"e": 4617,
"s": 4569,
"text": "Code : Bar Plot for Fare (Continuous Feature) "
},
{
"code": null,
"e": 4625,
"s": 4617,
"text": "Python3"
},
{
"code": "# Divide Fare into 4 binstitanic['Fare_Range'] = pd.qcut(titanic['Fare'], 4) # Barplot - Shows approximate values based# on the height of bars.sns.barplot(x ='Fare_Range', y ='Survived',data = titanic)",
"e": 4827,
"s": 4625,
"text": null
},
{
"code": null,
"e": 4837,
"s": 4827,
"text": "Output : "
},
{
"code": null,
"e": 5095,
"s": 4837,
"text": "Fare denotes the fare paid by a passenger. As the values in this column are continuous, they need to be put in separate bins(as done for Age feature) to get a clear idea. It can be concluded that if a passenger paid a higher fare, the survival rate is more."
},
{
"code": null,
"e": 5148,
"s": 5095,
"text": "Code: Categorical Count Plots for Embarked Feature "
},
{
"code": null,
"e": 5156,
"s": 5148,
"text": "Python3"
},
{
"code": "# Countplotsns.catplot(x ='Embarked', hue ='Survived',kind ='count', col ='Pclass', data = titanic)",
"e": 5256,
"s": 5156,
"text": null
},
{
"code": null,
"e": 5288,
"s": 5256,
"text": "Some notable observations are: "
},
{
"code": null,
"e": 5376,
"s": 5288,
"text": "Majority of the passengers boarded from S. So, the missing values can be filled with S."
},
{
"code": null,
"e": 5423,
"s": 5376,
"text": "Majority of class 3 passengers boarded from Q."
},
{
"code": null,
"e": 5487,
"s": 5423,
"text": "S looks lucky for class 1 and 2 passengers compared to class 3."
},
{
"code": null,
"e": 5502,
"s": 5487,
"text": "Conclusion : "
},
{
"code": null,
"e": 5718,
"s": 5502,
"text": "The columns that can be dropped are: PassengerId, Name, Ticket, Cabin: They are strings, cannot be categorized and don’t contribute much to the outcome. Age, Fare: Instead, the respective range columns are retained."
},
{
"code": null,
"e": 5835,
"s": 5718,
"text": "PassengerId, Name, Ticket, Cabin: They are strings, cannot be categorized and don’t contribute much to the outcome. "
},
{
"code": null,
"e": 5898,
"s": 5835,
"text": "Age, Fare: Instead, the respective range columns are retained."
},
{
"code": null,
"e": 6035,
"s": 5898,
"text": "The titanic data can be analyzed using many more graph techniques and also more column correlations, than, as described in this article."
},
{
"code": null,
"e": 6113,
"s": 6035,
"text": "Once the EDA is completed, the resultant dataset can be used for predictions."
},
{
"code": null,
"e": 6130,
"s": 6113,
"text": "arorakashish0911"
},
{
"code": null,
"e": 6154,
"s": 6130,
"text": "Technical Scripter 2019"
},
{
"code": null,
"e": 6171,
"s": 6154,
"text": "Machine Learning"
},
{
"code": null,
"e": 6178,
"s": 6171,
"text": "Python"
},
{
"code": null,
"e": 6197,
"s": 6178,
"text": "Technical Scripter"
},
{
"code": null,
"e": 6214,
"s": 6197,
"text": "Machine Learning"
},
{
"code": null,
"e": 6312,
"s": 6214,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6335,
"s": 6312,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 6358,
"s": 6335,
"text": "Reinforcement learning"
},
{
"code": null,
"e": 6382,
"s": 6358,
"text": "Search Algorithms in AI"
},
{
"code": null,
"e": 6419,
"s": 6382,
"text": "Supervised and Unsupervised learning"
},
{
"code": null,
"e": 6455,
"s": 6419,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 6483,
"s": 6455,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 6505,
"s": 6483,
"text": "Python map() function"
},
{
"code": null,
"e": 6555,
"s": 6505,
"text": "Adding new column to existing DataFrame in Pandas"
}
] |
Truncate a String using filter in Vue.js
|
15 Jul, 2021
In this article, we are going to learn how to truncate strings using filters in VueJS. Filters are a functionality provided by Vue components that let you apply formatting and transformations to any part of your template dynamic data. The filter property of the component is an object. A single filter is a function that accepts a value and returns another value. The returned value is the one that’s actually printed in the Vue.js template.
The string extraction can be performed by applying a filter on the required string. There can be two approaches for writing the logic of the filter function:
Approach 1: In this approach, we use the JavaScript built-in methods split, slice and, join. The split method is used to split each character and convert them into a set of a character array. The slice method extracts the required portion of the string and returns it. The join method is used to convert an array of characters to a normal string. We will use all three methods together to truncate the string. The substr method can also be used to return a truncated string.
Example:
index.html
<html><head> <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"> </script></head><body> <div id='parent'> <p> <strong>Original String: </strong> {{st1}} </p> <p> <strong>Truncated String : </strong> {{ st1 | truncate(13) }} </p> </div> <script src='app.js'></script></body></html>
app.js
const parent = new Vue({ el: '#parent', data: { st1: 'GeekforGeeks is a computer science portal' }, filters: { truncate: function(data,num){ const reqdString = data.split("").slice(0, num).join(""); return reqdString; } }})
Output:
Approach 2: This method does not use any built-in JavaScript methods. The truncation is done by looping through the characters of the string for the required number of times and keep the required number of characters by appending them to the final string that would be returned.
index.html
<html><head> <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"> </script></head><body> <div id='parent'> <p> <strong>Original String: </strong> {{st1}} </p> <p><strong>Truncated String : </strong> {{ st1 | truncate(18) }} </p> </div> <script src='app.js'></script></body></html>
app.js
const parent = new Vue({ el: '#parent', data: { st1: 'GeekforGeeks is a computer science portal' }, filters: { truncate: function(data, num) { reqdString = '' for(let i=0; i<num; i++) { reqdString += data[i] } return reqdString; } }})
Output:
anikakapoor
Vue.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": "\n15 Jul, 2021"
},
{
"code": null,
"e": 470,
"s": 28,
"text": "In this article, we are going to learn how to truncate strings using filters in VueJS. Filters are a functionality provided by Vue components that let you apply formatting and transformations to any part of your template dynamic data. The filter property of the component is an object. A single filter is a function that accepts a value and returns another value. The returned value is the one that’s actually printed in the Vue.js template."
},
{
"code": null,
"e": 628,
"s": 470,
"text": "The string extraction can be performed by applying a filter on the required string. There can be two approaches for writing the logic of the filter function:"
},
{
"code": null,
"e": 1103,
"s": 628,
"text": "Approach 1: In this approach, we use the JavaScript built-in methods split, slice and, join. The split method is used to split each character and convert them into a set of a character array. The slice method extracts the required portion of the string and returns it. The join method is used to convert an array of characters to a normal string. We will use all three methods together to truncate the string. The substr method can also be used to return a truncated string."
},
{
"code": null,
"e": 1112,
"s": 1103,
"text": "Example:"
},
{
"code": null,
"e": 1123,
"s": 1112,
"text": "index.html"
},
{
"code": "<html><head> <script src=\"https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js\"> </script></head><body> <div id='parent'> <p> <strong>Original String: </strong> {{st1}} </p> <p> <strong>Truncated String : </strong> {{ st1 | truncate(13) }} </p> </div> <script src='app.js'></script></body></html>",
"e": 1501,
"s": 1123,
"text": null
},
{
"code": null,
"e": 1512,
"s": 1505,
"text": "app.js"
},
{
"code": "const parent = new Vue({ el: '#parent', data: { st1: 'GeekforGeeks is a computer science portal' }, filters: { truncate: function(data,num){ const reqdString = data.split(\"\").slice(0, num).join(\"\"); return reqdString; } }})",
"e": 1810,
"s": 1512,
"text": null
},
{
"code": null,
"e": 1822,
"s": 1814,
"text": "Output:"
},
{
"code": null,
"e": 2105,
"s": 1826,
"text": "Approach 2: This method does not use any built-in JavaScript methods. The truncation is done by looping through the characters of the string for the required number of times and keep the required number of characters by appending them to the final string that would be returned."
},
{
"code": null,
"e": 2118,
"s": 2107,
"text": "index.html"
},
{
"code": "<html><head> <script src=\"https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js\"> </script></head><body> <div id='parent'> <p> <strong>Original String: </strong> {{st1}} </p> <p><strong>Truncated String : </strong> {{ st1 | truncate(18) }} </p> </div> <script src='app.js'></script></body></html>",
"e": 2482,
"s": 2118,
"text": null
},
{
"code": null,
"e": 2493,
"s": 2486,
"text": "app.js"
},
{
"code": "const parent = new Vue({ el: '#parent', data: { st1: 'GeekforGeeks is a computer science portal' }, filters: { truncate: function(data, num) { reqdString = '' for(let i=0; i<num; i++) { reqdString += data[i] } return reqdString; } }})",
"e": 2825,
"s": 2493,
"text": null
},
{
"code": null,
"e": 2837,
"s": 2829,
"text": "Output:"
},
{
"code": null,
"e": 2853,
"s": 2841,
"text": "anikakapoor"
},
{
"code": null,
"e": 2860,
"s": 2853,
"text": "Vue.JS"
},
{
"code": null,
"e": 2877,
"s": 2860,
"text": "Web Technologies"
}
] |
Python | Pandas Series.tolist()
|
01 Oct, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas tolist() is used to convert a series to list. Initially the series is of type pandas.core.series.Series and applying tolist() method, it is converted to list data type.
Syntax: Series.tolist()
Return type: Converted series into List
To download the data set used in following example, click here.In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below.
Example:In this example, the data type of Name column is stored in a variable. After that it is converted using tolist() method and again data type is stored and printed.
# importing pandas module import pandas as pd # importing regex moduleimport re # making data frame data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") # removing null values to avoid errors data.dropna(inplace = True) # storing dtype before operationdtype_before = type(data["Salary"]) # converting to listsalary_list = data["Salary"].tolist() # storing dtype after operationdtype_after = type(salary_list) # printing dtypeprint("Data type before converting = {}\nData type after converting = {}".format(dtype_before, dtype_after)) # displaying listsalary_list
Output:As shown in the output image, the data type was converted from Series to List. The output of salary_list was in list format.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Oct, 2018"
},
{
"code": null,
"e": 242,
"s": 28,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 418,
"s": 242,
"text": "Pandas tolist() is used to convert a series to list. Initially the series is of type pandas.core.series.Series and applying tolist() method, it is converted to list data type."
},
{
"code": null,
"e": 442,
"s": 418,
"text": "Syntax: Series.tolist()"
},
{
"code": null,
"e": 482,
"s": 442,
"text": "Return type: Converted series into List"
},
{
"code": null,
"e": 692,
"s": 482,
"text": "To download the data set used in following example, click here.In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below."
},
{
"code": null,
"e": 863,
"s": 692,
"text": "Example:In this example, the data type of Name column is stored in a variable. After that it is converted using tolist() method and again data type is stored and printed."
},
{
"code": "# importing pandas module import pandas as pd # importing regex moduleimport re # making data frame data = pd.read_csv(\"https://media.geeksforgeeks.org/wp-content/uploads/nba.csv\") # removing null values to avoid errors data.dropna(inplace = True) # storing dtype before operationdtype_before = type(data[\"Salary\"]) # converting to listsalary_list = data[\"Salary\"].tolist() # storing dtype after operationdtype_after = type(salary_list) # printing dtypeprint(\"Data type before converting = {}\\nData type after converting = {}\".format(dtype_before, dtype_after)) # displaying listsalary_list",
"e": 1469,
"s": 863,
"text": null
},
{
"code": null,
"e": 1601,
"s": 1469,
"text": "Output:As shown in the output image, the data type was converted from Series to List. The output of salary_list was in list format."
},
{
"code": null,
"e": 1622,
"s": 1601,
"text": "Python pandas-series"
},
{
"code": null,
"e": 1651,
"s": 1622,
"text": "Python pandas-series-methods"
},
{
"code": null,
"e": 1665,
"s": 1651,
"text": "Python-pandas"
},
{
"code": null,
"e": 1672,
"s": 1665,
"text": "Python"
},
{
"code": null,
"e": 1770,
"s": 1672,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1788,
"s": 1770,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1830,
"s": 1788,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1852,
"s": 1830,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1884,
"s": 1852,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1913,
"s": 1884,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1940,
"s": 1913,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1961,
"s": 1940,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1984,
"s": 1961,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2015,
"s": 1984,
"text": "Python | os.path.join() method"
}
] |
How to Get a List of Class Attributes in Python?
|
30 Jan, 2020
A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it for maintaining its state. Class instances can also have methods (defined by its class) for modifying its state.
Example:
# Python program to demonstrate# classes class Student: # class variable stream = "COE" # Constructor def __init__(self, name, roll_no): self.name = name self.roll_no = roll_no # Driver's codea = Student("Shivam", 3425)b = Student("Sachin", 3624) print(a.stream)print(b.stream)print(a.name)print(b.name) # Class variables can be accessed# using class name also print(Student.stream)
Output :
COE
COE
Shivam
Sachin
COE
Note: For more information, refer to Python Classes and Objects.
It is important to know the attributes we are working with. For small data, it is easy to remember the names of the attributes but when working with huge data, it is difficult to memorize all the attributes. Luckily, we have some functions in Python available for this task.
Method 1: To get the list of all the attributes, methods along with some inherited magic methods of a class, we use a built-in called dir().
Example:
class Number : # Class Attributes one = 'first' two = 'second' three = 'third' def __init__(self, attr): self.attr = attr def show(self): print(self.one, self.two, self.three, self.attr) n = Number(2)n.show() # Passing both the object # and class as argument# to the dir methodprint('\nBy passing object of class')print(dir(n)) print('\nBy passing class itself ')print(dir(Number))
Output :
first second third 2
By passing object of class[‘__class__’, ‘__delattr__’, ‘__dict__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__gt__’, ‘__hash__’, ‘__init__’, ‘__init_subclass__’, ‘__le__’, ‘__lt__’, ‘__module__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’, ‘__weakref__’, ‘attr’, ‘one’, ‘show’, ‘three’, ‘two’]
By passing class itself[‘__class__’, ‘__delattr__’, ‘__dict__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__gt__’, ‘__hash__’, ‘__init__’, ‘__init_subclass__’, ‘__le__’, ‘__lt__’, ‘__module__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’, ‘__weakref__’, ‘one’, ‘show’, ‘three’, ‘two’]
Method 2: Another way of finding a list of attributes is by using the module inspect. This module provides a method called getmemebers() that returns a list of class attributes and methods.
Example 1:
import inspect class Number : # Class Attributes one = 'first' two = 'second' three = 'third' def __init__(self, attr): self.attr = attr def show(self): print(self.one, self.two, self.three, self.attr) # Driver's coden = Number(2)n.show() # getmembers() returns all the # members of an object for i in inspect.getmembers(n): # to remove private and protected # functions if not i[0].startswith('_'): # To remove other methods that # doesnot start with a underscore if not inspect.ismethod(i[1]): print(i)
Output :
first second third 2
('attr', 2)
('one', 'first')
('three', 'third')
('two', 'second')
Method 3: To find attributes we can also use magic method __dict__. This method only returns instance attributes.
Example:
class Number : # Class Attributes one = 'first' two = 'second' three = 'third' def __init__(self, attr): self.attr = attr def show(self): print(self.one, self.two, self.three, self.attr) # Driver's coden = Number(2)n.show() # using __dict__ to access attributes# of the object n along with their valuesprint(n.__dict__) # to only access attributesprint(n.__dict__.keys()) # to only access valuesprint(n.__dict__.values())
Output:
first second third 2
{'attr': 2}
dict_keys(['attr'])
dict_values([2])
Python-OOP
python-oop-concepts
Technical Scripter 2019
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Read a file line by line in Python
How to Install PIP on Windows ?
Python String | replace()
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n30 Jan, 2020"
},
{
"code": null,
"e": 471,
"s": 54,
"text": "A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it for maintaining its state. Class instances can also have methods (defined by its class) for modifying its state."
},
{
"code": null,
"e": 480,
"s": 471,
"text": "Example:"
},
{
"code": "# Python program to demonstrate# classes class Student: # class variable stream = \"COE\" # Constructor def __init__(self, name, roll_no): self.name = name self.roll_no = roll_no # Driver's codea = Student(\"Shivam\", 3425)b = Student(\"Sachin\", 3624) print(a.stream)print(b.stream)print(a.name)print(b.name) # Class variables can be accessed# using class name also print(Student.stream) ",
"e": 926,
"s": 480,
"text": null
},
{
"code": null,
"e": 935,
"s": 926,
"text": "Output :"
},
{
"code": null,
"e": 962,
"s": 935,
"text": "COE\nCOE\nShivam\nSachin\nCOE\n"
},
{
"code": null,
"e": 1027,
"s": 962,
"text": "Note: For more information, refer to Python Classes and Objects."
},
{
"code": null,
"e": 1302,
"s": 1027,
"text": "It is important to know the attributes we are working with. For small data, it is easy to remember the names of the attributes but when working with huge data, it is difficult to memorize all the attributes. Luckily, we have some functions in Python available for this task."
},
{
"code": null,
"e": 1443,
"s": 1302,
"text": "Method 1: To get the list of all the attributes, methods along with some inherited magic methods of a class, we use a built-in called dir()."
},
{
"code": null,
"e": 1452,
"s": 1443,
"text": "Example:"
},
{
"code": "class Number : # Class Attributes one = 'first' two = 'second' three = 'third' def __init__(self, attr): self.attr = attr def show(self): print(self.one, self.two, self.three, self.attr) n = Number(2)n.show() # Passing both the object # and class as argument# to the dir methodprint('\\nBy passing object of class')print(dir(n)) print('\\nBy passing class itself ')print(dir(Number))",
"e": 1905,
"s": 1452,
"text": null
},
{
"code": null,
"e": 1914,
"s": 1905,
"text": "Output :"
},
{
"code": null,
"e": 1935,
"s": 1914,
"text": "first second third 2"
},
{
"code": null,
"e": 2345,
"s": 1935,
"text": "By passing object of class[‘__class__’, ‘__delattr__’, ‘__dict__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__gt__’, ‘__hash__’, ‘__init__’, ‘__init_subclass__’, ‘__le__’, ‘__lt__’, ‘__module__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’, ‘__weakref__’, ‘attr’, ‘one’, ‘show’, ‘three’, ‘two’]"
},
{
"code": null,
"e": 2744,
"s": 2345,
"text": "By passing class itself[‘__class__’, ‘__delattr__’, ‘__dict__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__gt__’, ‘__hash__’, ‘__init__’, ‘__init_subclass__’, ‘__le__’, ‘__lt__’, ‘__module__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’, ‘__weakref__’, ‘one’, ‘show’, ‘three’, ‘two’]"
},
{
"code": null,
"e": 2934,
"s": 2744,
"text": "Method 2: Another way of finding a list of attributes is by using the module inspect. This module provides a method called getmemebers() that returns a list of class attributes and methods."
},
{
"code": null,
"e": 2945,
"s": 2934,
"text": "Example 1:"
},
{
"code": "import inspect class Number : # Class Attributes one = 'first' two = 'second' three = 'third' def __init__(self, attr): self.attr = attr def show(self): print(self.one, self.two, self.three, self.attr) # Driver's coden = Number(2)n.show() # getmembers() returns all the # members of an object for i in inspect.getmembers(n): # to remove private and protected # functions if not i[0].startswith('_'): # To remove other methods that # doesnot start with a underscore if not inspect.ismethod(i[1]): print(i)",
"e": 3586,
"s": 2945,
"text": null
},
{
"code": null,
"e": 3595,
"s": 3586,
"text": "Output :"
},
{
"code": null,
"e": 3683,
"s": 3595,
"text": "first second third 2\n('attr', 2)\n('one', 'first')\n('three', 'third')\n('two', 'second')\n"
},
{
"code": null,
"e": 3797,
"s": 3683,
"text": "Method 3: To find attributes we can also use magic method __dict__. This method only returns instance attributes."
},
{
"code": null,
"e": 3806,
"s": 3797,
"text": "Example:"
},
{
"code": "class Number : # Class Attributes one = 'first' two = 'second' three = 'third' def __init__(self, attr): self.attr = attr def show(self): print(self.one, self.two, self.three, self.attr) # Driver's coden = Number(2)n.show() # using __dict__ to access attributes# of the object n along with their valuesprint(n.__dict__) # to only access attributesprint(n.__dict__.keys()) # to only access valuesprint(n.__dict__.values())",
"e": 4295,
"s": 3806,
"text": null
},
{
"code": null,
"e": 4303,
"s": 4295,
"text": "Output:"
},
{
"code": null,
"e": 4374,
"s": 4303,
"text": "first second third 2\n{'attr': 2}\ndict_keys(['attr'])\ndict_values([2])\n"
},
{
"code": null,
"e": 4385,
"s": 4374,
"text": "Python-OOP"
},
{
"code": null,
"e": 4405,
"s": 4385,
"text": "python-oop-concepts"
},
{
"code": null,
"e": 4429,
"s": 4405,
"text": "Technical Scripter 2019"
},
{
"code": null,
"e": 4436,
"s": 4429,
"text": "Python"
},
{
"code": null,
"e": 4455,
"s": 4436,
"text": "Technical Scripter"
},
{
"code": null,
"e": 4553,
"s": 4455,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4571,
"s": 4553,
"text": "Python Dictionary"
},
{
"code": null,
"e": 4613,
"s": 4571,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 4648,
"s": 4613,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 4680,
"s": 4648,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4706,
"s": 4680,
"text": "Python String | replace()"
},
{
"code": null,
"e": 4735,
"s": 4706,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 4762,
"s": 4735,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4783,
"s": 4762,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 4806,
"s": 4783,
"text": "Introduction To PYTHON"
}
] |
How to Specify a Date Format on Creating a Table and Fill it in SQL?
|
28 Nov, 2021
Whenever we work with databases, we find that almost every single table contains a Date column. After all, the date of the data plays an important role while analyzing it. Storing dates in a specific or understandable format is very important. In this article, we are going to learn how we can specify a Date format on SQL Server.
Let’s create our demo database and table.
Step 1: Create a database
Use the following command to create a database.
Query:
CREATE DATABASE User_details;
Step 2:Use database
Query:
USE User_details;
Step 3: Table definition
We have the following GFG_user table in the database.
Query:
CREATE TABLE GFG_user(Id INT NOT NULL,Dt DATE,
Address VARCHAR(100),Dt_FORMATTED AS
(convert(varchar(255), dt, 104)),
PRIMARY KEY (Id) );
Output:
Here, we have created a column named Dt_FORMATTED where we are going to save our formatted Date.
Now, we see the CONVERT() function. The CONVERT() function simply converts a value of any type into a specified datatype.
Syntax:
CONVERT ( data_type ( length ) ,
expression , style )
By using this function, we are casting the string to a date. In the place of style argument, we have mentioned ‘104’. It is a numeric code to specify the date format.
Check this table to see different codes used for different formats:
Default dor datetime
and smalldatetime
mon dd yyy hh:
miAM (or PM)
1 = mm/dd/yy
101 = mm/dd/yyyy
2 = yy.mm.dd
102 = yyyy.mm.dd
3 = dd/mm/yy
103 = dd/mm/yyyy
4 = dd.mm.yy
104 = dd.mm.yyyy
11 = yy/mm/dd
111 = yyyy/mm/dd
12 = yymmdd
112 = yyyymmdd
Here, We have mentioned only the 10 most used formats.
Step 4: Insert values
The following command is used to insert values into the table.
Query:
SET DATEFORMAT dmy; INSERT INTO GFG_user
(Id, Dt, Address) VALUES ('1','23.11.2021',
'German');
In this query, we are using the DATEFORMAT setting.
Syntax:
SET DATEFORMAT format
When we are inserting the string, the server will try to convert the string to date before inserting it into the table. As it cannot tell if we are putting the month before the date or the date before the month. For example, suppose you are trying to insert 06.07.2000. The server is unable to detect if the date is the 6th of July or it is the 7th of June. Though it uses the localization settings of the user account that is operating to figure that out not mentioning the DATEFORMAT might give you an error as most of the times the account that is running the operation is set to USA format, that is – Month Day Year (mdy).
The error was caused because we wanted to save it as dmy, not mdy. However, using DATEFORMAT will help you to get rid of it.
Output:
We are done with our table, now let’s check if we are getting our desired output or not.
Step 5: View data of the table
Query:
SELECT * FROM GFG_user;
Output:
We have successfully got our German format Date in the Dt_FORMATTED column.
Picked
SQL-Query
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | Sub queries in From Clause
Window functions in SQL
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
What is Temporary Table in SQL?
SQL using Python
SQL Query to Convert VARCHAR to INT
SQL Query to Convert Rows to Columns in SQL Server
SQL | DROP, TRUNCATE
Introduction to NoSQL
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Nov, 2021"
},
{
"code": null,
"e": 359,
"s": 28,
"text": "Whenever we work with databases, we find that almost every single table contains a Date column. After all, the date of the data plays an important role while analyzing it. Storing dates in a specific or understandable format is very important. In this article, we are going to learn how we can specify a Date format on SQL Server."
},
{
"code": null,
"e": 401,
"s": 359,
"text": "Let’s create our demo database and table."
},
{
"code": null,
"e": 427,
"s": 401,
"text": "Step 1: Create a database"
},
{
"code": null,
"e": 475,
"s": 427,
"text": "Use the following command to create a database."
},
{
"code": null,
"e": 482,
"s": 475,
"text": "Query:"
},
{
"code": null,
"e": 513,
"s": 482,
"text": "CREATE DATABASE User_details; "
},
{
"code": null,
"e": 533,
"s": 513,
"text": "Step 2:Use database"
},
{
"code": null,
"e": 540,
"s": 533,
"text": "Query:"
},
{
"code": null,
"e": 559,
"s": 540,
"text": "USE User_details; "
},
{
"code": null,
"e": 584,
"s": 559,
"text": "Step 3: Table definition"
},
{
"code": null,
"e": 638,
"s": 584,
"text": "We have the following GFG_user table in the database."
},
{
"code": null,
"e": 646,
"s": 638,
"text": "Query: "
},
{
"code": null,
"e": 790,
"s": 646,
"text": "CREATE TABLE GFG_user(Id INT NOT NULL,Dt DATE, \nAddress VARCHAR(100),Dt_FORMATTED AS \n(convert(varchar(255), dt, 104)), \nPRIMARY KEY (Id) );"
},
{
"code": null,
"e": 798,
"s": 790,
"text": "Output:"
},
{
"code": null,
"e": 896,
"s": 798,
"text": "Here, we have created a column named Dt_FORMATTED where we are going to save our formatted Date. "
},
{
"code": null,
"e": 1018,
"s": 896,
"text": "Now, we see the CONVERT() function. The CONVERT() function simply converts a value of any type into a specified datatype."
},
{
"code": null,
"e": 1026,
"s": 1018,
"text": "Syntax:"
},
{
"code": null,
"e": 1084,
"s": 1026,
"text": "CONVERT ( data_type ( length ) ,\nexpression , style ) "
},
{
"code": null,
"e": 1251,
"s": 1084,
"text": "By using this function, we are casting the string to a date. In the place of style argument, we have mentioned ‘104’. It is a numeric code to specify the date format."
},
{
"code": null,
"e": 1319,
"s": 1251,
"text": "Check this table to see different codes used for different formats:"
},
{
"code": null,
"e": 1341,
"s": 1319,
"text": "Default dor datetime "
},
{
"code": null,
"e": 1359,
"s": 1341,
"text": "and smalldatetime"
},
{
"code": null,
"e": 1374,
"s": 1359,
"text": "mon dd yyy hh:"
},
{
"code": null,
"e": 1388,
"s": 1374,
"text": " miAM (or PM)"
},
{
"code": null,
"e": 1401,
"s": 1388,
"text": "1 = mm/dd/yy"
},
{
"code": null,
"e": 1418,
"s": 1401,
"text": "101 = mm/dd/yyyy"
},
{
"code": null,
"e": 1431,
"s": 1418,
"text": "2 = yy.mm.dd"
},
{
"code": null,
"e": 1448,
"s": 1431,
"text": "102 = yyyy.mm.dd"
},
{
"code": null,
"e": 1461,
"s": 1448,
"text": "3 = dd/mm/yy"
},
{
"code": null,
"e": 1478,
"s": 1461,
"text": "103 = dd/mm/yyyy"
},
{
"code": null,
"e": 1491,
"s": 1478,
"text": "4 = dd.mm.yy"
},
{
"code": null,
"e": 1508,
"s": 1491,
"text": "104 = dd.mm.yyyy"
},
{
"code": null,
"e": 1522,
"s": 1508,
"text": "11 = yy/mm/dd"
},
{
"code": null,
"e": 1539,
"s": 1522,
"text": "111 = yyyy/mm/dd"
},
{
"code": null,
"e": 1551,
"s": 1539,
"text": "12 = yymmdd"
},
{
"code": null,
"e": 1566,
"s": 1551,
"text": "112 = yyyymmdd"
},
{
"code": null,
"e": 1622,
"s": 1566,
"text": "Here, We have mentioned only the 10 most used formats. "
},
{
"code": null,
"e": 1644,
"s": 1622,
"text": "Step 4: Insert values"
},
{
"code": null,
"e": 1707,
"s": 1644,
"text": "The following command is used to insert values into the table."
},
{
"code": null,
"e": 1714,
"s": 1707,
"text": "Query:"
},
{
"code": null,
"e": 1813,
"s": 1714,
"text": "SET DATEFORMAT dmy; INSERT INTO GFG_user\n(Id, Dt, Address) VALUES ('1','23.11.2021',\n'German'); "
},
{
"code": null,
"e": 1865,
"s": 1813,
"text": "In this query, we are using the DATEFORMAT setting."
},
{
"code": null,
"e": 1873,
"s": 1865,
"text": "Syntax:"
},
{
"code": null,
"e": 1899,
"s": 1873,
"text": "SET DATEFORMAT format "
},
{
"code": null,
"e": 2527,
"s": 1899,
"text": " When we are inserting the string, the server will try to convert the string to date before inserting it into the table. As it cannot tell if we are putting the month before the date or the date before the month. For example, suppose you are trying to insert 06.07.2000. The server is unable to detect if the date is the 6th of July or it is the 7th of June. Though it uses the localization settings of the user account that is operating to figure that out not mentioning the DATEFORMAT might give you an error as most of the times the account that is running the operation is set to USA format, that is – Month Day Year (mdy)."
},
{
"code": null,
"e": 2652,
"s": 2527,
"text": "The error was caused because we wanted to save it as dmy, not mdy. However, using DATEFORMAT will help you to get rid of it."
},
{
"code": null,
"e": 2660,
"s": 2652,
"text": "Output:"
},
{
"code": null,
"e": 2749,
"s": 2660,
"text": "We are done with our table, now let’s check if we are getting our desired output or not."
},
{
"code": null,
"e": 2780,
"s": 2749,
"text": "Step 5: View data of the table"
},
{
"code": null,
"e": 2787,
"s": 2780,
"text": "Query:"
},
{
"code": null,
"e": 2812,
"s": 2787,
"text": "SELECT * FROM GFG_user; "
},
{
"code": null,
"e": 2820,
"s": 2812,
"text": "Output:"
},
{
"code": null,
"e": 2896,
"s": 2820,
"text": "We have successfully got our German format Date in the Dt_FORMATTED column."
},
{
"code": null,
"e": 2903,
"s": 2896,
"text": "Picked"
},
{
"code": null,
"e": 2913,
"s": 2903,
"text": "SQL-Query"
},
{
"code": null,
"e": 2924,
"s": 2913,
"text": "SQL-Server"
},
{
"code": null,
"e": 2928,
"s": 2924,
"text": "SQL"
},
{
"code": null,
"e": 2932,
"s": 2928,
"text": "SQL"
},
{
"code": null,
"e": 3030,
"s": 2932,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3096,
"s": 3030,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 3129,
"s": 3096,
"text": "SQL | Sub queries in From Clause"
},
{
"code": null,
"e": 3153,
"s": 3129,
"text": "Window functions in SQL"
},
{
"code": null,
"e": 3231,
"s": 3153,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 3263,
"s": 3231,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 3280,
"s": 3263,
"text": "SQL using Python"
},
{
"code": null,
"e": 3316,
"s": 3280,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 3367,
"s": 3316,
"text": "SQL Query to Convert Rows to Columns in SQL Server"
},
{
"code": null,
"e": 3388,
"s": 3367,
"text": "SQL | DROP, TRUNCATE"
}
] |
Java.lang.InheritableThreadLocal Class with Examples
|
22 May, 2018
The java.lang.InheritableThreadLocal class extends ThreadLocal to provide inheritance of values from parent thread to child thread: when a child thread is created, the child receives initial values for all inheritable thread-local variables for which the parent has values.
Parent thread, ThreadLocal variable by default is not available to child thread.Constructor :
InheritableThreadLocal gfg_tl = new InheritableThreadLocal();
It is the child class of ThreadLocal and hence all methods present in ThreadLocal by default available to InheritableThreadLocal.It contains only one method :Syntax :
public Object childValue(Object parentValue)
This method is called(overridden) within the parent thread before the child thread is started.
If we want to make parent thread, thread local variable value available to the child thread, then we should go for InheritableThreadLocal class.
By default, child thread value is exactly the same as parent thread value. But we can provide our own customized value for child thread by overriding childValue method.
Example:
// Java program to illustrate parent thread, ThreadLocal variable// by default not available to child thread class ParentThread extends Thread { public static ThreadLocal gfg_tl = new ThreadLocal(); public void run() { // setting the new value gfg_tl.set("parent data"); // returns the ThreadLocal value associated with current thread System.out.println("Parent Thread Value :" + gfg_tl.get()); ChildThread gfg_ct = new ChildThread(); gfg_ct.start(); }} class ChildThread extends Thread { public void run() { // returns the ThreadLocal value associated with current thread System.out.println("Child Thread Value :" + ParentThread.gfg_tl.get()); /* null (parent thread variable thread local value is not available to child thread ) */ }}class ThreadLocalDemo { public static void main(String[] args) { ParentThread gfg_pt = new ParentThread(); gfg_pt.start(); }}
Output:
Parent Thread Value:parent data
Child Thread Value:null (by default initialValue is null)
// Java program to illustrate inheritance of customized value// from parent thread to child thread class ParentThread extends Thread { // anonymous inner class for overriding childValue method. public static InheritableThreadLocal gfg_tl = new InheritableThreadLocal() { public Object childValue(Object parentValue) { return "child data"; } }; public void run() { // setting the new value gfg_tl.set("parent data"); // parent data System.out.println("Parent Thread Value :" + gfg_tl.get()); ChildThread gfg_ct = new ChildThread(); gfg_ct.start(); }}class ChildThread extends Thread { public void run() { // child data System.out.println("Child Thread Value :" + ParentThread.gfg_tl.get()); }}class ThreadLocalDemo { public static void main(String[] args) { ParentThread gfg_pt = new ParentThread(); gfg_pt.start(); }}
Output:
Parent Thread Value:parent data
Child Thread Value:child data
1st Scenario : In the above program if we replace InheritableThreadLocal with ThreadLocal and we are not overriding childValue method then the output is :
Output:
Parent Thread Value: parent data
Child Thread Value:null (by default initialValue is null)
2nd Scenario : In the above program if we are maintaining InheritableThreadLocal and we are not overriding childValue method, then the output is :
Output :
Parent Thread Value:parent data
Child Thread Value:parent data
3rd Scenario : In the above program if we are maintaining InheritableThreadLocal and we are also overriding childValue method, then the output is :
Output:
Parent Thread Value:parent data
Child Thread Value:child data
Java-Multithreading
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": "\n22 May, 2018"
},
{
"code": null,
"e": 302,
"s": 28,
"text": "The java.lang.InheritableThreadLocal class extends ThreadLocal to provide inheritance of values from parent thread to child thread: when a child thread is created, the child receives initial values for all inheritable thread-local variables for which the parent has values."
},
{
"code": null,
"e": 396,
"s": 302,
"text": "Parent thread, ThreadLocal variable by default is not available to child thread.Constructor :"
},
{
"code": null,
"e": 458,
"s": 396,
"text": "InheritableThreadLocal gfg_tl = new InheritableThreadLocal();"
},
{
"code": null,
"e": 625,
"s": 458,
"text": "It is the child class of ThreadLocal and hence all methods present in ThreadLocal by default available to InheritableThreadLocal.It contains only one method :Syntax :"
},
{
"code": null,
"e": 671,
"s": 625,
"text": "public Object childValue(Object parentValue) "
},
{
"code": null,
"e": 766,
"s": 671,
"text": "This method is called(overridden) within the parent thread before the child thread is started."
},
{
"code": null,
"e": 911,
"s": 766,
"text": "If we want to make parent thread, thread local variable value available to the child thread, then we should go for InheritableThreadLocal class."
},
{
"code": null,
"e": 1080,
"s": 911,
"text": "By default, child thread value is exactly the same as parent thread value. But we can provide our own customized value for child thread by overriding childValue method."
},
{
"code": null,
"e": 1089,
"s": 1080,
"text": "Example:"
},
{
"code": "// Java program to illustrate parent thread, ThreadLocal variable// by default not available to child thread class ParentThread extends Thread { public static ThreadLocal gfg_tl = new ThreadLocal(); public void run() { // setting the new value gfg_tl.set(\"parent data\"); // returns the ThreadLocal value associated with current thread System.out.println(\"Parent Thread Value :\" + gfg_tl.get()); ChildThread gfg_ct = new ChildThread(); gfg_ct.start(); }} class ChildThread extends Thread { public void run() { // returns the ThreadLocal value associated with current thread System.out.println(\"Child Thread Value :\" + ParentThread.gfg_tl.get()); /* null (parent thread variable thread local value is not available to child thread ) */ }}class ThreadLocalDemo { public static void main(String[] args) { ParentThread gfg_pt = new ParentThread(); gfg_pt.start(); }}",
"e": 2078,
"s": 1089,
"text": null
},
{
"code": null,
"e": 2177,
"s": 2078,
"text": "Output:\nParent Thread Value:parent data\nChild Thread Value:null (by default initialValue is null)\n"
},
{
"code": "// Java program to illustrate inheritance of customized value// from parent thread to child thread class ParentThread extends Thread { // anonymous inner class for overriding childValue method. public static InheritableThreadLocal gfg_tl = new InheritableThreadLocal() { public Object childValue(Object parentValue) { return \"child data\"; } }; public void run() { // setting the new value gfg_tl.set(\"parent data\"); // parent data System.out.println(\"Parent Thread Value :\" + gfg_tl.get()); ChildThread gfg_ct = new ChildThread(); gfg_ct.start(); }}class ChildThread extends Thread { public void run() { // child data System.out.println(\"Child Thread Value :\" + ParentThread.gfg_tl.get()); }}class ThreadLocalDemo { public static void main(String[] args) { ParentThread gfg_pt = new ParentThread(); gfg_pt.start(); }}",
"e": 3141,
"s": 2177,
"text": null
},
{
"code": null,
"e": 3213,
"s": 3141,
"text": "Output:\nParent Thread Value:parent data \nChild Thread Value:child data\n"
},
{
"code": null,
"e": 3368,
"s": 3213,
"text": "1st Scenario : In the above program if we replace InheritableThreadLocal with ThreadLocal and we are not overriding childValue method then the output is :"
},
{
"code": null,
"e": 3471,
"s": 3368,
"text": "Output:\nParent Thread Value: parent data \nChild Thread Value:null (by default initialValue is null)\n"
},
{
"code": null,
"e": 3618,
"s": 3471,
"text": "2nd Scenario : In the above program if we are maintaining InheritableThreadLocal and we are not overriding childValue method, then the output is :"
},
{
"code": null,
"e": 3692,
"s": 3618,
"text": "Output :\nParent Thread Value:parent data \nChild Thread Value:parent data\n"
},
{
"code": null,
"e": 3840,
"s": 3692,
"text": "3rd Scenario : In the above program if we are maintaining InheritableThreadLocal and we are also overriding childValue method, then the output is :"
},
{
"code": null,
"e": 3912,
"s": 3840,
"text": "Output:\nParent Thread Value:parent data \nChild Thread Value:child data\n"
},
{
"code": null,
"e": 3932,
"s": 3912,
"text": "Java-Multithreading"
},
{
"code": null,
"e": 3937,
"s": 3932,
"text": "Java"
},
{
"code": null,
"e": 3942,
"s": 3937,
"text": "Java"
}
] |
TCS NQT Coding Questions & How Coding Task Evaluated in TCS NQT
|
24 Jan, 2022
To know more about the TCS NQT: TCS NQT – National Qualifier Test
1. How to solve the Coding Section in TCS NQT 2022?
STEP by STEP guide to solving the coding section in TCS NQT 2022.
STEP 1: Understanding the storyYou are given 30 minutes to write a program and clear all the test cases. Of this, spend the first five to six minutes on understanding the story given and figuring out what needs to be calculated. If your English is not very strong, you need to spend more time in reading and understanding the task. Don’t jump into typing your program before you understand what is going on.
These are the points that you need to understand from the task.
There are coins of several denominations.
Initially, there are an Even number of coins of each type.
One of the coins is lost. When you remove 1 from an even number, we get an Odd number. So, finally we have many denominations occurring an Even number of times but one particular denomination occurring an Odd number of times.
The first input we get is the total number of coins. Let’s call this N.
In the second line we get only N-1 values because one of the coins is missing.
The output is the denomination (value) of the missing coin.
STEP 2: Reading the inputs Once you know what is needed, we need to think in terms of how you write the code. At this time we don’t know how to find the answer. But we know how to take the inputs. So, the first part of the program is to read the value of N, declare an array and read N-1 values into the array. Even though the task keeps changing, reading a set of values in a loop is required in many programs. You will need to practice several programs so that you won’t waste your time in simple tasks like this in the actual exam.
STEP 3: Cracking the core logic
The next step is to figure out how to convert this data into an answer. By the time we reach this step in the exam, we should have about 20 minutes left. Let’s race against the time. Consider the example given in the question. We see that the denomination Rs.2 appears two times, Rs.1 appears two times and Rs.5 appears three times. Why is it so? We know that originally all these are present an even number of times. But, one of the coins got lost and that is the number which appears an odd number of times. In this example, we can infer that originally, there were four coins with Rs. 5 but one of them fell down. That is why we finally have three Rs.5 coins instead of four Rs.5 coins. Here is a direct way of solving this problem. Towards the end of this article, we will see a more efficient way of solving the same problem.
Method 1:
Task 1: Read one coin at a time in the loop. Take its value. Let’s call this a[j].
Task 2: In an inner loop, go through each coin in the list and count how many times is V occurring. For this we first need to initialize count to zero. Whenever a[j] == a[i] is true, we need to increment the counter.
Task 3: Once the inner loop is completed, the value of count will tell us how many times has a[i] occurred in the array.
Task 4: We need to check if the count is Odd. We are told that only 1 denomination will occur an odd number of times. If we find it, we can print it and exit the program.
When we divide an Odd number with 2, we get 1 as remainder. This can be obtained using the % operator.
Method 2: Once we realize that we need to find the number which is occurring an Odd number of times, some of us can come up with an alternative method to identify it. This method is based on the EXOR operation which is a bit-wise operation performed using the ^ symbol. Here is the Truth table for XOR operations. Operands Result:
0 ^ 0 0
0 ^ 1 1
1 ^ 0 1
1 ^ 1 0
From the above Truth table, we can conclude that N ^ N = 0, 0 ^ N = N. Let’s say we have 3 integers A, B and C. Here are a few interesting results from EXOR.
A^A=0
A^B^A = A^A^B = B
A^B^C^B^A^C = 0
So, if we perform the EXOR operation on a series of numbers we will notice some interesting results.
If a particular number (say A) is occurring an Even number of times, the EXOR of all of them together is 0. i.e. A^A^A...^A =0 when the number is occurring an Even number of times.
If a number is occurring an Odd number of times, the EXOR of all the occurrences is same as the number itself. So, A^A^A^....^A= A when the number is occurring an Odd number of times.
The order in which we apply the EXOR operation doesn’t matter A^B=B^A.
Using these properties together, we can notice that when we take the EXOR of all the inputs, any number that occurs an even number of times will give an EXOR of 0. If
A is the number that occurs an Odd number of times, the overall EXOR for all its appearances will be equal to A. The overall result for all the other numbers will be zero. So, finally we get A^0 which is equal to A.
Once we know this, we can go ahead and implement this in the code. We just need to take a temporary variable to store the result. Let’s call this E and initialize it to 0. We then need to go through a loop and perform EXOR on all the given elements. The final value of EXOR is the answer we need. 2. What is TCS NQT 2022?
Step 4: Validating the code
The remaining time in the exam can be spent in verifying that the code clears all the test cases. In case it fails, you can try giving your own inputs to find out when it is failing and then try to correct the algorithm. In TCS NQT 2022, you might not have a big penalty if your code is slow. So, it makes a lot of sense for you to write working code before you worry about efficiency.
TCS NQT 2022(https://learning.tcsionhub.in/hub/national-qualifier-test/) is the exam conducted by TCS for recruiting freshers who are going to graduate in the year 2022. Make sure that you understand the Eligibility criteria for the test, the syllabus and test pattern.
3. What is the Coding section in NQT 2022?
The coding section of the TCS NQT 2022 has one question which is usually in the form a Case study or a Story. At the end of the Caselet, they will ask us to write a program which takes the input in a particular format and produces the output as per the required format. 4. What are the other rules for the Coding section?
You can attempt the coding task in any of the 5 languages given by TCS. These are C, C++, Java, Python and Perl. You have a total of 30 minutes to solve this question. Here are the most important points to know about before you attempt the coding section of TCS NQT 2022.
5. How is the coding task evaluated?
The TCS NQT 2022 is attempted by lakhs of students. The examiners are not going to read everyone’s code. Instead, they will use a computerized evaluation which will automatically assign score based ONLY ON THE OUTPUT. The main part of the coding section is “Test Cases”. Your code will be Validated against test cases. You will be given partial marks based on how many test cases are cleared.
6. Do I need to make my program so efficient?
While it is always good to write efficient programs you need to control your greed. Before you worry about efficiency, you need to ensure that your program clears at least some of the test cases. Finally, nobody reads your code – they just look at the number of test cases. Make sure that your code clears as many test cases as possible. However, if you know an efficient method, there is no reason for you to not use it. Go ahead, give it best shot. This is your playground.
7. In which language should I write the code?
The advantage of choosing C, C++ and Java over scripting languages is that the compiler is very strict. The probability of any mistakes being found by the compiler is very high which means the probability of validating against the test cases is also high. On the other hand, in scripting languages like Python or Perl the probability of finding mistakes by compiler is not fruitful. Some of your coding mistakes might percolate till the time you go into the compiler stage. As we keep telling, don’t try to learn a new programming language now. Stick with a language that you already know. Build your confidence by practicing multiple tasks using it.
8. Is it necessary to Validate Against Test Cases?
TCS NQT 2022 has introduced the facility of validating your solution code against the actual test cases. Make sure that your code is clearing them. Keep tweaking it until you are done. However, in the last 2 minutes you need to ensure that your code is stable. Stop making any further changes. Read your code a few times to ensure that you haven’t done anything stupid in your excitement.
9. Where can I get more questions like this?
You can prepare yourself for the TCS NQT with us by following this course TCS NQT Preparation Test Series.
TCS
TCS NQT
TCS-coding-questions
Interview Experiences
TCS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n24 Jan, 2022"
},
{
"code": null,
"e": 120,
"s": 54,
"text": "To know more about the TCS NQT: TCS NQT – National Qualifier Test"
},
{
"code": null,
"e": 173,
"s": 120,
"text": "1. How to solve the Coding Section in TCS NQT 2022? "
},
{
"code": null,
"e": 239,
"s": 173,
"text": "STEP by STEP guide to solving the coding section in TCS NQT 2022."
},
{
"code": null,
"e": 647,
"s": 239,
"text": "STEP 1: Understanding the storyYou are given 30 minutes to write a program and clear all the test cases. Of this, spend the first five to six minutes on understanding the story given and figuring out what needs to be calculated. If your English is not very strong, you need to spend more time in reading and understanding the task. Don’t jump into typing your program before you understand what is going on."
},
{
"code": null,
"e": 711,
"s": 647,
"text": "These are the points that you need to understand from the task."
},
{
"code": null,
"e": 753,
"s": 711,
"text": "There are coins of several denominations."
},
{
"code": null,
"e": 812,
"s": 753,
"text": "Initially, there are an Even number of coins of each type."
},
{
"code": null,
"e": 1038,
"s": 812,
"text": "One of the coins is lost. When you remove 1 from an even number, we get an Odd number. So, finally we have many denominations occurring an Even number of times but one particular denomination occurring an Odd number of times."
},
{
"code": null,
"e": 1110,
"s": 1038,
"text": "The first input we get is the total number of coins. Let’s call this N."
},
{
"code": null,
"e": 1189,
"s": 1110,
"text": "In the second line we get only N-1 values because one of the coins is missing."
},
{
"code": null,
"e": 1249,
"s": 1189,
"text": "The output is the denomination (value) of the missing coin."
},
{
"code": null,
"e": 1784,
"s": 1249,
"text": "STEP 2: Reading the inputs Once you know what is needed, we need to think in terms of how you write the code. At this time we don’t know how to find the answer. But we know how to take the inputs. So, the first part of the program is to read the value of N, declare an array and read N-1 values into the array. Even though the task keeps changing, reading a set of values in a loop is required in many programs. You will need to practice several programs so that you won’t waste your time in simple tasks like this in the actual exam."
},
{
"code": null,
"e": 1818,
"s": 1786,
"text": "STEP 3: Cracking the core logic"
},
{
"code": null,
"e": 2649,
"s": 1818,
"text": "The next step is to figure out how to convert this data into an answer. By the time we reach this step in the exam, we should have about 20 minutes left. Let’s race against the time. Consider the example given in the question. We see that the denomination Rs.2 appears two times, Rs.1 appears two times and Rs.5 appears three times. Why is it so? We know that originally all these are present an even number of times. But, one of the coins got lost and that is the number which appears an odd number of times. In this example, we can infer that originally, there were four coins with Rs. 5 but one of them fell down. That is why we finally have three Rs.5 coins instead of four Rs.5 coins. Here is a direct way of solving this problem. Towards the end of this article, we will see a more efficient way of solving the same problem."
},
{
"code": null,
"e": 2661,
"s": 2651,
"text": "Method 1:"
},
{
"code": null,
"e": 2744,
"s": 2661,
"text": "Task 1: Read one coin at a time in the loop. Take its value. Let’s call this a[j]."
},
{
"code": null,
"e": 2961,
"s": 2744,
"text": "Task 2: In an inner loop, go through each coin in the list and count how many times is V occurring. For this we first need to initialize count to zero. Whenever a[j] == a[i] is true, we need to increment the counter."
},
{
"code": null,
"e": 3083,
"s": 2961,
"text": "Task 3: Once the inner loop is completed, the value of count will tell us how many times has a[i] occurred in the array. "
},
{
"code": null,
"e": 3254,
"s": 3083,
"text": "Task 4: We need to check if the count is Odd. We are told that only 1 denomination will occur an odd number of times. If we find it, we can print it and exit the program."
},
{
"code": null,
"e": 3357,
"s": 3254,
"text": "When we divide an Odd number with 2, we get 1 as remainder. This can be obtained using the % operator."
},
{
"code": null,
"e": 3688,
"s": 3357,
"text": "Method 2: Once we realize that we need to find the number which is occurring an Odd number of times, some of us can come up with an alternative method to identify it. This method is based on the EXOR operation which is a bit-wise operation performed using the ^ symbol. Here is the Truth table for XOR operations. Operands Result:"
},
{
"code": null,
"e": 3723,
"s": 3688,
"text": "0 ^ 0 0 \n0 ^ 1 1 \n1 ^ 0 1 \n1 ^ 1 0"
},
{
"code": null,
"e": 3881,
"s": 3723,
"text": "From the above Truth table, we can conclude that N ^ N = 0, 0 ^ N = N. Let’s say we have 3 integers A, B and C. Here are a few interesting results from EXOR."
},
{
"code": null,
"e": 3923,
"s": 3881,
"text": "A^A=0 \nA^B^A = A^A^B = B \nA^B^C^B^A^C = 0"
},
{
"code": null,
"e": 4024,
"s": 3923,
"text": "So, if we perform the EXOR operation on a series of numbers we will notice some interesting results."
},
{
"code": null,
"e": 4205,
"s": 4024,
"text": "If a particular number (say A) is occurring an Even number of times, the EXOR of all of them together is 0. i.e. A^A^A...^A =0 when the number is occurring an Even number of times."
},
{
"code": null,
"e": 4389,
"s": 4205,
"text": "If a number is occurring an Odd number of times, the EXOR of all the occurrences is same as the number itself. So, A^A^A^....^A= A when the number is occurring an Odd number of times."
},
{
"code": null,
"e": 4460,
"s": 4389,
"text": "The order in which we apply the EXOR operation doesn’t matter A^B=B^A."
},
{
"code": null,
"e": 4627,
"s": 4460,
"text": "Using these properties together, we can notice that when we take the EXOR of all the inputs, any number that occurs an even number of times will give an EXOR of 0. If"
},
{
"code": null,
"e": 4843,
"s": 4627,
"text": "A is the number that occurs an Odd number of times, the overall EXOR for all its appearances will be equal to A. The overall result for all the other numbers will be zero. So, finally we get A^0 which is equal to A."
},
{
"code": null,
"e": 5165,
"s": 4843,
"text": "Once we know this, we can go ahead and implement this in the code. We just need to take a temporary variable to store the result. Let’s call this E and initialize it to 0. We then need to go through a loop and perform EXOR on all the given elements. The final value of EXOR is the answer we need. 2. What is TCS NQT 2022?"
},
{
"code": null,
"e": 5193,
"s": 5165,
"text": "Step 4: Validating the code"
},
{
"code": null,
"e": 5579,
"s": 5193,
"text": "The remaining time in the exam can be spent in verifying that the code clears all the test cases. In case it fails, you can try giving your own inputs to find out when it is failing and then try to correct the algorithm. In TCS NQT 2022, you might not have a big penalty if your code is slow. So, it makes a lot of sense for you to write working code before you worry about efficiency."
},
{
"code": null,
"e": 5851,
"s": 5581,
"text": "TCS NQT 2022(https://learning.tcsionhub.in/hub/national-qualifier-test/) is the exam conducted by TCS for recruiting freshers who are going to graduate in the year 2022. Make sure that you understand the Eligibility criteria for the test, the syllabus and test pattern."
},
{
"code": null,
"e": 5894,
"s": 5851,
"text": "3. What is the Coding section in NQT 2022?"
},
{
"code": null,
"e": 6216,
"s": 5894,
"text": "The coding section of the TCS NQT 2022 has one question which is usually in the form a Case study or a Story. At the end of the Caselet, they will ask us to write a program which takes the input in a particular format and produces the output as per the required format. 4. What are the other rules for the Coding section?"
},
{
"code": null,
"e": 6488,
"s": 6216,
"text": "You can attempt the coding task in any of the 5 languages given by TCS. These are C, C++, Java, Python and Perl. You have a total of 30 minutes to solve this question. Here are the most important points to know about before you attempt the coding section of TCS NQT 2022."
},
{
"code": null,
"e": 6525,
"s": 6488,
"text": "5. How is the coding task evaluated?"
},
{
"code": null,
"e": 6918,
"s": 6525,
"text": "The TCS NQT 2022 is attempted by lakhs of students. The examiners are not going to read everyone’s code. Instead, they will use a computerized evaluation which will automatically assign score based ONLY ON THE OUTPUT. The main part of the coding section is “Test Cases”. Your code will be Validated against test cases. You will be given partial marks based on how many test cases are cleared."
},
{
"code": null,
"e": 6964,
"s": 6918,
"text": "6. Do I need to make my program so efficient?"
},
{
"code": null,
"e": 7440,
"s": 6964,
"text": "While it is always good to write efficient programs you need to control your greed. Before you worry about efficiency, you need to ensure that your program clears at least some of the test cases. Finally, nobody reads your code – they just look at the number of test cases. Make sure that your code clears as many test cases as possible. However, if you know an efficient method, there is no reason for you to not use it. Go ahead, give it best shot. This is your playground."
},
{
"code": null,
"e": 7486,
"s": 7440,
"text": "7. In which language should I write the code?"
},
{
"code": null,
"e": 8137,
"s": 7486,
"text": "The advantage of choosing C, C++ and Java over scripting languages is that the compiler is very strict. The probability of any mistakes being found by the compiler is very high which means the probability of validating against the test cases is also high. On the other hand, in scripting languages like Python or Perl the probability of finding mistakes by compiler is not fruitful. Some of your coding mistakes might percolate till the time you go into the compiler stage. As we keep telling, don’t try to learn a new programming language now. Stick with a language that you already know. Build your confidence by practicing multiple tasks using it."
},
{
"code": null,
"e": 8190,
"s": 8139,
"text": "8. Is it necessary to Validate Against Test Cases?"
},
{
"code": null,
"e": 8579,
"s": 8190,
"text": "TCS NQT 2022 has introduced the facility of validating your solution code against the actual test cases. Make sure that your code is clearing them. Keep tweaking it until you are done. However, in the last 2 minutes you need to ensure that your code is stable. Stop making any further changes. Read your code a few times to ensure that you haven’t done anything stupid in your excitement."
},
{
"code": null,
"e": 8626,
"s": 8581,
"text": "9. Where can I get more questions like this?"
},
{
"code": null,
"e": 8733,
"s": 8626,
"text": "You can prepare yourself for the TCS NQT with us by following this course TCS NQT Preparation Test Series."
},
{
"code": null,
"e": 8737,
"s": 8733,
"text": "TCS"
},
{
"code": null,
"e": 8745,
"s": 8737,
"text": "TCS NQT"
},
{
"code": null,
"e": 8766,
"s": 8745,
"text": "TCS-coding-questions"
},
{
"code": null,
"e": 8788,
"s": 8766,
"text": "Interview Experiences"
},
{
"code": null,
"e": 8792,
"s": 8788,
"text": "TCS"
}
] |
How to remove all white spaces from a string in PHP ?
|
27 May, 2020
Given a string element containing some spaces and the task is to remove all the spaces from the given string str in PHP. In order to do this task, we have the following methods in PHP:
Method 1: Using str_replace() Method: The str_replace() method is used to replace all the occurrences of the search string (” “) by replacing string (“”) in the given string str.
Syntax:
str_replace($searchVal, $replaceVal, $subjectVal, $count)
Example :
PHP
<?php// PHP program to remove all white// spaces from a string // Declare a string$str = " Geeks for Geeks "; // Using str_replace() function // to removes all whitespaces $str = str_replace(' ', '', $str); // Printing the resultecho $str; ?>
GeeksforGeeks
Method 2: Using str_ireplace() Method: The str_ireplace() method is used to replace all the occurrences of the search string (” “) by replacing string (“”) in the given string str. The difference between str_replace and str_ireplace is that str_ireplace is a case-insensitive.
Syntax:
str_ireplace($searchVal, $replaceVal, $subjectVal, $count)
Example :
PHP
<?php// PHP program to remove all// white spaces from a string $str = " Geeks for Geeks "; // Using str_ireplace() function // to remove all whitespaces $str = str_ireplace (' ', '', $str); // Printing the resultecho $str; ?>
GeeksforGeeks
Method 3: Using preg_replace() Method: The preg_replace() method is used to perform a regular expression for search and replace the content.
Syntax:
preg_replace( $pattern, $replacement, $subject, $limit, $count )
Example :
PHP
<?php// PHP program to remove all// white spaces from a string $str = " Geeks for Geeks "; // Using preg_replace() function // to remove all whitespaces $str = preg_replace('/\s+/', '', $str); // Printing the resultecho $str; ?>
GeeksforGeeks
PHP-string
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 May, 2020"
},
{
"code": null,
"e": 213,
"s": 28,
"text": "Given a string element containing some spaces and the task is to remove all the spaces from the given string str in PHP. In order to do this task, we have the following methods in PHP:"
},
{
"code": null,
"e": 392,
"s": 213,
"text": "Method 1: Using str_replace() Method: The str_replace() method is used to replace all the occurrences of the search string (” “) by replacing string (“”) in the given string str."
},
{
"code": null,
"e": 400,
"s": 392,
"text": "Syntax:"
},
{
"code": null,
"e": 459,
"s": 400,
"text": "str_replace($searchVal, $replaceVal, $subjectVal, $count)\n"
},
{
"code": null,
"e": 469,
"s": 459,
"text": "Example :"
},
{
"code": null,
"e": 473,
"s": 469,
"text": "PHP"
},
{
"code": "<?php// PHP program to remove all white// spaces from a string // Declare a string$str = \" Geeks for Geeks \"; // Using str_replace() function // to removes all whitespaces $str = str_replace(' ', '', $str); // Printing the resultecho $str; ?>",
"e": 728,
"s": 473,
"text": null
},
{
"code": null,
"e": 742,
"s": 728,
"text": "GeeksforGeeks"
},
{
"code": null,
"e": 1019,
"s": 742,
"text": "Method 2: Using str_ireplace() Method: The str_ireplace() method is used to replace all the occurrences of the search string (” “) by replacing string (“”) in the given string str. The difference between str_replace and str_ireplace is that str_ireplace is a case-insensitive."
},
{
"code": null,
"e": 1027,
"s": 1019,
"text": "Syntax:"
},
{
"code": null,
"e": 1087,
"s": 1027,
"text": "str_ireplace($searchVal, $replaceVal, $subjectVal, $count)\n"
},
{
"code": null,
"e": 1097,
"s": 1087,
"text": "Example :"
},
{
"code": null,
"e": 1101,
"s": 1097,
"text": "PHP"
},
{
"code": "<?php// PHP program to remove all// white spaces from a string $str = \" Geeks for Geeks \"; // Using str_ireplace() function // to remove all whitespaces $str = str_ireplace (' ', '', $str); // Printing the resultecho $str; ?>",
"e": 1341,
"s": 1101,
"text": null
},
{
"code": null,
"e": 1355,
"s": 1341,
"text": "GeeksforGeeks"
},
{
"code": null,
"e": 1496,
"s": 1355,
"text": "Method 3: Using preg_replace() Method: The preg_replace() method is used to perform a regular expression for search and replace the content."
},
{
"code": null,
"e": 1504,
"s": 1496,
"text": "Syntax:"
},
{
"code": null,
"e": 1570,
"s": 1504,
"text": "preg_replace( $pattern, $replacement, $subject, $limit, $count )\n"
},
{
"code": null,
"e": 1580,
"s": 1570,
"text": "Example :"
},
{
"code": null,
"e": 1584,
"s": 1580,
"text": "PHP"
},
{
"code": "<?php// PHP program to remove all// white spaces from a string $str = \" Geeks for Geeks \"; // Using preg_replace() function // to remove all whitespaces $str = preg_replace('/\\s+/', '', $str); // Printing the resultecho $str; ?>",
"e": 1827,
"s": 1584,
"text": null
},
{
"code": null,
"e": 1841,
"s": 1827,
"text": "GeeksforGeeks"
},
{
"code": null,
"e": 1852,
"s": 1841,
"text": "PHP-string"
},
{
"code": null,
"e": 1856,
"s": 1852,
"text": "PHP"
},
{
"code": null,
"e": 1869,
"s": 1856,
"text": "PHP Programs"
},
{
"code": null,
"e": 1886,
"s": 1869,
"text": "Web Technologies"
},
{
"code": null,
"e": 1913,
"s": 1886,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 1917,
"s": 1913,
"text": "PHP"
}
] |
How to Clone a Map in Java
|
21 Jan, 2019
Given a map, the task is to clone that map.
Following are the 5 different ways to Clone a Map in Java.
Example:
{1=Geeks, 2=For, 3=Geeks}
Method 1: Naive method1. Create an object for the class map.2. Put the elements into the map using the put() method.3. Again create another object for the class map.4. Now finally iterate the map and call put method to clone the initial map.Below is the implementation of the above approach:Implementation:// Program to clone a Map in Java// Naive Method import java.util.*; class GFG { public static void main(String[] args) { // Creating an object for class Map Map<Integer, String> hash_Map = new HashMap<Integer, String>(); // putting elements into the map hash_Map.put(1, "Geeks"); hash_Map.put(2, "For"); hash_Map.put(3, "Geeks"); // Creating a new object for // class Map to clone a map Map<Integer, String> new_map = new HashMap<Integer, String>(); // using iterator for (Map.Entry<Integer, String> entry : hash_Map.entrySet()) { new_map.put(entry.getKey(), entry.getValue()); } System.out.println(new_map); }}Output:{1=Geeks, 2=For, 3=Geeks}
Below is the implementation of the above approach:
Implementation:
// Program to clone a Map in Java// Naive Method import java.util.*; class GFG { public static void main(String[] args) { // Creating an object for class Map Map<Integer, String> hash_Map = new HashMap<Integer, String>(); // putting elements into the map hash_Map.put(1, "Geeks"); hash_Map.put(2, "For"); hash_Map.put(3, "Geeks"); // Creating a new object for // class Map to clone a map Map<Integer, String> new_map = new HashMap<Integer, String>(); // using iterator for (Map.Entry<Integer, String> entry : hash_Map.entrySet()) { new_map.put(entry.getKey(), entry.getValue()); } System.out.println(new_map); }}
{1=Geeks, 2=For, 3=Geeks}
Method 2: Using putAll().1. Create an object for the class map.2. Put the elements into the map using the put() method.3. Again create another object for the class map.4. Now finally use putAll() method to clone the initial map.Below is the implementation of the above approach:Implementation:// Program to clone a Map in Java// putAll Method import java.util.*; class GFG { public static void main(String[] args) { // Creating an object for class Map Map<Integer, String> hash_Map = new HashMap<Integer, String>(); // Putting elements into the map hash_Map.put(1, "Geeks"); hash_Map.put(2, "For"); hash_Map.put(3, "Geeks"); // Creating a new object // for class Map to clone a map Map<Integer, String> new_map = new HashMap<Integer, String>(); // using putAll method new_map.putAll(hash_Map); System.out.println(new_map); }}Output:{1=Geeks, 2=For, 3=Geeks}
Below is the implementation of the above approach:
Implementation:
// Program to clone a Map in Java// putAll Method import java.util.*; class GFG { public static void main(String[] args) { // Creating an object for class Map Map<Integer, String> hash_Map = new HashMap<Integer, String>(); // Putting elements into the map hash_Map.put(1, "Geeks"); hash_Map.put(2, "For"); hash_Map.put(3, "Geeks"); // Creating a new object // for class Map to clone a map Map<Integer, String> new_map = new HashMap<Integer, String>(); // using putAll method new_map.putAll(hash_Map); System.out.println(new_map); }}
{1=Geeks, 2=For, 3=Geeks}
Method 3: Copy Constructor.1. Create an object for the class map.2. Put the elements into the map using the put() method.3. Again create another object for the class map.4. Now finally use the copy constructor(It is a special constructor used for creating a new object as a copy of an existing object) to clone the initial map.Below is the implementation of the above approach:Implementation:// Program to clone a Map in Java// Copy Constructor import java.util.*; class GFG { public static void main(String[] args) { // Creating an object for class Map Map<Integer, String> hash_Map = new HashMap<Integer, String>(); // putting elements into the map hash_Map.put(1, "Geeks"); hash_Map.put(2, "For"); hash_Map.put(3, "Geeks"); // Creating a new object // for class Map to clone a map Map<Integer, String> new_map = new HashMap<Integer, String>(); new_map = new HashMap<>(hash_Map); System.out.println(new_map); }}Output:{1=Geeks, 2=For, 3=Geeks}
Below is the implementation of the above approach:
Implementation:
// Program to clone a Map in Java// Copy Constructor import java.util.*; class GFG { public static void main(String[] args) { // Creating an object for class Map Map<Integer, String> hash_Map = new HashMap<Integer, String>(); // putting elements into the map hash_Map.put(1, "Geeks"); hash_Map.put(2, "For"); hash_Map.put(3, "Geeks"); // Creating a new object // for class Map to clone a map Map<Integer, String> new_map = new HashMap<Integer, String>(); new_map = new HashMap<>(hash_Map); System.out.println(new_map); }}
{1=Geeks, 2=For, 3=Geeks}
Method 4: Java 81. Create an object for the class map.2. Put the elements into the map using the put() method.3. Again create another object for the class map.4. Now finally use Stream API from Java 8 to clone the initial map.Below is the implementation of the above approach:Implementation:// Program to clone a Map in Java// Using java8 import java.util.*;import java.util.stream.Collectors; class GFG { public static void main(String[] args) { // Creating an object for class Map Map<Integer, String> hash_Map = new HashMap<Integer, String>(); // putting elements into the map hash_Map.put(1, "Geeks"); hash_Map.put(2, "For"); hash_Map.put(3, "Geeks"); // Creating a new object // for class Map to clone a map Map<Integer, String> new_map = new HashMap<Integer, String>(); new_map = hash_Map.entrySet() .stream() .collect( Collectors .toMap(Map.Entry::getKey, Map.Entry::getValue)); System.out.println(new_map); }}Output:{1=Geeks, 2=For, 3=Geeks}
Explanation:It is also similar to above methods, but here we use Stream API from java 8 to clone the original map.
Below is the implementation of the above approach:
Implementation:
// Program to clone a Map in Java// Using java8 import java.util.*;import java.util.stream.Collectors; class GFG { public static void main(String[] args) { // Creating an object for class Map Map<Integer, String> hash_Map = new HashMap<Integer, String>(); // putting elements into the map hash_Map.put(1, "Geeks"); hash_Map.put(2, "For"); hash_Map.put(3, "Geeks"); // Creating a new object // for class Map to clone a map Map<Integer, String> new_map = new HashMap<Integer, String>(); new_map = hash_Map.entrySet() .stream() .collect( Collectors .toMap(Map.Entry::getKey, Map.Entry::getValue)); System.out.println(new_map); }}
{1=Geeks, 2=For, 3=Geeks}
Explanation:It is also similar to above methods, but here we use Stream API from java 8 to clone the original map.
Method 5: JSON1. Create an object for the class map.2. Put the elements into the map using the put() method.3. Again create another object for the class map.4. Now finally use Google’s GSON library to clone the initial map.Below is the implementation of the above approach:Implementation:// Program to clone a Map in Java// JSON Method import java.util.*;import java.util.stream.Collectors;import com.google.gson.Gson; class GFG { public static void main(String[] args) { // Creating an object for class Map Map<Integer, String> hash_Map = new HashMap<Integer, String>(); // putting elements into the map hash_Map.put(1, "Geeks"); hash_Map.put(2, "For"); hash_Map.put(3, "Geeks"); // Creating a new object // for class Map to clone a map Map<Integer, String> new_map = new HashMap<Integer, String>(); Gson gson = new Gson(); String jsonString = gson.toJson(hash_Map); new_map = gson.fromJson(jsonString, Map.class); System.out.println(new_map); }}Output:{1=Geeks, 2=For, 3=Geeks}
Explanation:It is also similar to the above methods, but here we use Google’s GSON library to clone the original map. Here initially we convert Map to a JSON string and later we convert that string to a new map.
Below is the implementation of the above approach:
Implementation:
// Program to clone a Map in Java// JSON Method import java.util.*;import java.util.stream.Collectors;import com.google.gson.Gson; class GFG { public static void main(String[] args) { // Creating an object for class Map Map<Integer, String> hash_Map = new HashMap<Integer, String>(); // putting elements into the map hash_Map.put(1, "Geeks"); hash_Map.put(2, "For"); hash_Map.put(3, "Geeks"); // Creating a new object // for class Map to clone a map Map<Integer, String> new_map = new HashMap<Integer, String>(); Gson gson = new Gson(); String jsonString = gson.toJson(hash_Map); new_map = gson.fromJson(jsonString, Map.class); System.out.println(new_map); }}
{1=Geeks, 2=For, 3=Geeks}
Explanation:It is also similar to the above methods, but here we use Google’s GSON library to clone the original map. Here initially we convert Map to a JSON string and later we convert that string to a new map.
Java-HashMap
java-map
Java-Map-Programs
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n21 Jan, 2019"
},
{
"code": null,
"e": 98,
"s": 54,
"text": "Given a map, the task is to clone that map."
},
{
"code": null,
"e": 157,
"s": 98,
"text": "Following are the 5 different ways to Clone a Map in Java."
},
{
"code": null,
"e": 166,
"s": 157,
"text": "Example:"
},
{
"code": null,
"e": 193,
"s": 166,
"text": "{1=Geeks, 2=For, 3=Geeks}\n"
},
{
"code": null,
"e": 1311,
"s": 193,
"text": "Method 1: Naive method1. Create an object for the class map.2. Put the elements into the map using the put() method.3. Again create another object for the class map.4. Now finally iterate the map and call put method to clone the initial map.Below is the implementation of the above approach:Implementation:// Program to clone a Map in Java// Naive Method import java.util.*; class GFG { public static void main(String[] args) { // Creating an object for class Map Map<Integer, String> hash_Map = new HashMap<Integer, String>(); // putting elements into the map hash_Map.put(1, \"Geeks\"); hash_Map.put(2, \"For\"); hash_Map.put(3, \"Geeks\"); // Creating a new object for // class Map to clone a map Map<Integer, String> new_map = new HashMap<Integer, String>(); // using iterator for (Map.Entry<Integer, String> entry : hash_Map.entrySet()) { new_map.put(entry.getKey(), entry.getValue()); } System.out.println(new_map); }}Output:{1=Geeks, 2=For, 3=Geeks}\n"
},
{
"code": null,
"e": 1362,
"s": 1311,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1378,
"s": 1362,
"text": "Implementation:"
},
{
"code": "// Program to clone a Map in Java// Naive Method import java.util.*; class GFG { public static void main(String[] args) { // Creating an object for class Map Map<Integer, String> hash_Map = new HashMap<Integer, String>(); // putting elements into the map hash_Map.put(1, \"Geeks\"); hash_Map.put(2, \"For\"); hash_Map.put(3, \"Geeks\"); // Creating a new object for // class Map to clone a map Map<Integer, String> new_map = new HashMap<Integer, String>(); // using iterator for (Map.Entry<Integer, String> entry : hash_Map.entrySet()) { new_map.put(entry.getKey(), entry.getValue()); } System.out.println(new_map); }}",
"e": 2157,
"s": 1378,
"text": null
},
{
"code": null,
"e": 2184,
"s": 2157,
"text": "{1=Geeks, 2=For, 3=Geeks}\n"
},
{
"code": null,
"e": 3170,
"s": 2184,
"text": "Method 2: Using putAll().1. Create an object for the class map.2. Put the elements into the map using the put() method.3. Again create another object for the class map.4. Now finally use putAll() method to clone the initial map.Below is the implementation of the above approach:Implementation:// Program to clone a Map in Java// putAll Method import java.util.*; class GFG { public static void main(String[] args) { // Creating an object for class Map Map<Integer, String> hash_Map = new HashMap<Integer, String>(); // Putting elements into the map hash_Map.put(1, \"Geeks\"); hash_Map.put(2, \"For\"); hash_Map.put(3, \"Geeks\"); // Creating a new object // for class Map to clone a map Map<Integer, String> new_map = new HashMap<Integer, String>(); // using putAll method new_map.putAll(hash_Map); System.out.println(new_map); }}Output:{1=Geeks, 2=For, 3=Geeks}\n"
},
{
"code": null,
"e": 3221,
"s": 3170,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 3237,
"s": 3221,
"text": "Implementation:"
},
{
"code": "// Program to clone a Map in Java// putAll Method import java.util.*; class GFG { public static void main(String[] args) { // Creating an object for class Map Map<Integer, String> hash_Map = new HashMap<Integer, String>(); // Putting elements into the map hash_Map.put(1, \"Geeks\"); hash_Map.put(2, \"For\"); hash_Map.put(3, \"Geeks\"); // Creating a new object // for class Map to clone a map Map<Integer, String> new_map = new HashMap<Integer, String>(); // using putAll method new_map.putAll(hash_Map); System.out.println(new_map); }}",
"e": 3897,
"s": 3237,
"text": null
},
{
"code": null,
"e": 3924,
"s": 3897,
"text": "{1=Geeks, 2=For, 3=Geeks}\n"
},
{
"code": null,
"e": 4989,
"s": 3924,
"text": "Method 3: Copy Constructor.1. Create an object for the class map.2. Put the elements into the map using the put() method.3. Again create another object for the class map.4. Now finally use the copy constructor(It is a special constructor used for creating a new object as a copy of an existing object) to clone the initial map.Below is the implementation of the above approach:Implementation:// Program to clone a Map in Java// Copy Constructor import java.util.*; class GFG { public static void main(String[] args) { // Creating an object for class Map Map<Integer, String> hash_Map = new HashMap<Integer, String>(); // putting elements into the map hash_Map.put(1, \"Geeks\"); hash_Map.put(2, \"For\"); hash_Map.put(3, \"Geeks\"); // Creating a new object // for class Map to clone a map Map<Integer, String> new_map = new HashMap<Integer, String>(); new_map = new HashMap<>(hash_Map); System.out.println(new_map); }}Output:{1=Geeks, 2=For, 3=Geeks}\n"
},
{
"code": null,
"e": 5040,
"s": 4989,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 5056,
"s": 5040,
"text": "Implementation:"
},
{
"code": "// Program to clone a Map in Java// Copy Constructor import java.util.*; class GFG { public static void main(String[] args) { // Creating an object for class Map Map<Integer, String> hash_Map = new HashMap<Integer, String>(); // putting elements into the map hash_Map.put(1, \"Geeks\"); hash_Map.put(2, \"For\"); hash_Map.put(3, \"Geeks\"); // Creating a new object // for class Map to clone a map Map<Integer, String> new_map = new HashMap<Integer, String>(); new_map = new HashMap<>(hash_Map); System.out.println(new_map); }}",
"e": 5696,
"s": 5056,
"text": null
},
{
"code": null,
"e": 5723,
"s": 5696,
"text": "{1=Geeks, 2=For, 3=Geeks}\n"
},
{
"code": null,
"e": 7031,
"s": 5723,
"text": "Method 4: Java 81. Create an object for the class map.2. Put the elements into the map using the put() method.3. Again create another object for the class map.4. Now finally use Stream API from Java 8 to clone the initial map.Below is the implementation of the above approach:Implementation:// Program to clone a Map in Java// Using java8 import java.util.*;import java.util.stream.Collectors; class GFG { public static void main(String[] args) { // Creating an object for class Map Map<Integer, String> hash_Map = new HashMap<Integer, String>(); // putting elements into the map hash_Map.put(1, \"Geeks\"); hash_Map.put(2, \"For\"); hash_Map.put(3, \"Geeks\"); // Creating a new object // for class Map to clone a map Map<Integer, String> new_map = new HashMap<Integer, String>(); new_map = hash_Map.entrySet() .stream() .collect( Collectors .toMap(Map.Entry::getKey, Map.Entry::getValue)); System.out.println(new_map); }}Output:{1=Geeks, 2=For, 3=Geeks}\nExplanation:It is also similar to above methods, but here we use Stream API from java 8 to clone the original map."
},
{
"code": null,
"e": 7082,
"s": 7031,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 7098,
"s": 7082,
"text": "Implementation:"
},
{
"code": "// Program to clone a Map in Java// Using java8 import java.util.*;import java.util.stream.Collectors; class GFG { public static void main(String[] args) { // Creating an object for class Map Map<Integer, String> hash_Map = new HashMap<Integer, String>(); // putting elements into the map hash_Map.put(1, \"Geeks\"); hash_Map.put(2, \"For\"); hash_Map.put(3, \"Geeks\"); // Creating a new object // for class Map to clone a map Map<Integer, String> new_map = new HashMap<Integer, String>(); new_map = hash_Map.entrySet() .stream() .collect( Collectors .toMap(Map.Entry::getKey, Map.Entry::getValue)); System.out.println(new_map); }}",
"e": 7968,
"s": 7098,
"text": null
},
{
"code": null,
"e": 7995,
"s": 7968,
"text": "{1=Geeks, 2=For, 3=Geeks}\n"
},
{
"code": null,
"e": 8110,
"s": 7995,
"text": "Explanation:It is also similar to above methods, but here we use Stream API from java 8 to clone the original map."
},
{
"code": null,
"e": 9438,
"s": 8110,
"text": "Method 5: JSON1. Create an object for the class map.2. Put the elements into the map using the put() method.3. Again create another object for the class map.4. Now finally use Google’s GSON library to clone the initial map.Below is the implementation of the above approach:Implementation:// Program to clone a Map in Java// JSON Method import java.util.*;import java.util.stream.Collectors;import com.google.gson.Gson; class GFG { public static void main(String[] args) { // Creating an object for class Map Map<Integer, String> hash_Map = new HashMap<Integer, String>(); // putting elements into the map hash_Map.put(1, \"Geeks\"); hash_Map.put(2, \"For\"); hash_Map.put(3, \"Geeks\"); // Creating a new object // for class Map to clone a map Map<Integer, String> new_map = new HashMap<Integer, String>(); Gson gson = new Gson(); String jsonString = gson.toJson(hash_Map); new_map = gson.fromJson(jsonString, Map.class); System.out.println(new_map); }}Output:{1=Geeks, 2=For, 3=Geeks}\nExplanation:It is also similar to the above methods, but here we use Google’s GSON library to clone the original map. Here initially we convert Map to a JSON string and later we convert that string to a new map."
},
{
"code": null,
"e": 9489,
"s": 9438,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 9505,
"s": 9489,
"text": "Implementation:"
},
{
"code": "// Program to clone a Map in Java// JSON Method import java.util.*;import java.util.stream.Collectors;import com.google.gson.Gson; class GFG { public static void main(String[] args) { // Creating an object for class Map Map<Integer, String> hash_Map = new HashMap<Integer, String>(); // putting elements into the map hash_Map.put(1, \"Geeks\"); hash_Map.put(2, \"For\"); hash_Map.put(3, \"Geeks\"); // Creating a new object // for class Map to clone a map Map<Integer, String> new_map = new HashMap<Integer, String>(); Gson gson = new Gson(); String jsonString = gson.toJson(hash_Map); new_map = gson.fromJson(jsonString, Map.class); System.out.println(new_map); }}",
"e": 10301,
"s": 9505,
"text": null
},
{
"code": null,
"e": 10328,
"s": 10301,
"text": "{1=Geeks, 2=For, 3=Geeks}\n"
},
{
"code": null,
"e": 10540,
"s": 10328,
"text": "Explanation:It is also similar to the above methods, but here we use Google’s GSON library to clone the original map. Here initially we convert Map to a JSON string and later we convert that string to a new map."
},
{
"code": null,
"e": 10553,
"s": 10540,
"text": "Java-HashMap"
},
{
"code": null,
"e": 10562,
"s": 10553,
"text": "java-map"
},
{
"code": null,
"e": 10580,
"s": 10562,
"text": "Java-Map-Programs"
},
{
"code": null,
"e": 10587,
"s": 10580,
"text": "Picked"
},
{
"code": null,
"e": 10592,
"s": 10587,
"text": "Java"
},
{
"code": null,
"e": 10597,
"s": 10592,
"text": "Java"
}
] |
How to Get substring from a column in PySpark Dataframe ?
|
09 Sep, 2021
In this article, we are going to see how to get the substring from the PySpark Dataframe column and how to create the new column and put the substring in that newly created column.
We can get the substring of the column using substring() and substr() function.
Syntax: substring(str,pos,len)
df.col_name.substr(start, length)
Parameter:
str – It can be string or name of the column from which we are getting the substring.
start and pos – Through this parameter we can give the starting position from where substring is start.
length and len – It is the length of the substring from the starting position.
Let’s create a dataframe.
Python3
# importing necessary librariesfrom pyspark.sql import SparkSessionfrom pyspark.sql.functions import col, substring # function to create new SparkSessiondef create_session(): spk = SparkSession.builder \ .master("local") \ .appName("Substring.com") \ .getOrCreate() return spk def create_df(spark, data, schema): df1 = spark.createDataFrame(data, schema) return df1 if __name__ == "__main__": input_data = [("India", +91, 2701, 2020), ("United States of America", +1, 1301, 2020), ("Israel", +972, 3102, 2020), ("Dubai", +971, 2901, 2020), ("Russia", 7, 3101, 2020)] # calling function to create SparkSession spark = create_session() schema = ["Country", "Country Code", "Data", "Year"] # calling function to create dataframe df = create_df(spark, input_data, schema) df.show()
Output:
Example 1: Using substring() getting the substring and creating new column using withColumn() function.
Python
if __name__ == "__main__": # creating Month column and get the # substring from the Data column # creating Date column and get the # substring from the Data column df = df.withColumn( "Month", substring("Data", 1, 2)).withColumn( "Date", substring("Data", 3, 4)) # dropping the Data column from the # Dataframe df = df.drop("Data") # printing Dataframe schema to get the # column names df.printSchema() # visualizing the dataframe df.show(truncate=False)
Output:
Example 2: Creating New_Country column by getting the substring using substr() function.
Python
if __name__ == "__main__": # Creating the new column New_Country # and store the substring using substr() df = df.withColumn("New_Country", df.Country.substr(0, 12)) # printing Dataframe schema to get the # column names df.printSchema() # visualizing the dataframe df.show(truncate=False)
Output:
Example 3: Using substring() with select() function.
Python
if __name__ == "__main__": input_data = [("India", +91, "AidanButler"), ("United States of America", +1, "ConerFlores"), ("Israel", +972, "RosseBryant"), ("Dubai", +971, "JuliaSimmon"), ("Russia", 7, "AliceBailey")] # calling function to create SparkSession spark = create_session() schema = ["Country", "Country Code", "Name"] # calling function to create dataframe df = create_df(spark, input_data, schema) # Selecting the column using select() # function and getting substring # using substring() df2 = df.select('Name', substring('Name', 1, 5).alias('First Name'), substring('Name', 6, 6).alias('Last Name')) # printing Dataframe schema to get the column names df2.printSchema() # visualizing the dataframe df2.show(truncate=False)
Output:
Example 4: Using substring() with selectExpr() function.
Python
if __name__ == "__main__": input_data = [("India", +91, "AidanButler"), ("United States of America", +1, "ConerFlores"), ("Israel", +972, "RosseBryant"), ("Dubai", +971, "JuliaSimmon"), ("Russia", 7, "AliceBailey")] # calling function to create SparkSession spark = create_session() schema = ["Country", "Country Code", "Name"] # calling function to create dataframe df = create_df(spark, input_data, schema) # Selecting the column using selectExpr() # function and getting substring using substring() df2 = df.selectExpr('Name', 'substring(Name, 1,5) as First_Name', 'substring(Name, 6,6) as Last_Name') # printing Dataframe schema to get the column names df2.printSchema() # visualizing the dataframe df2.show(truncate=False)
Output:
anikaseth98
gabaa406
adnanirshad158
varshagumber28
Picked
Python-Pyspark
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Sep, 2021"
},
{
"code": null,
"e": 209,
"s": 28,
"text": "In this article, we are going to see how to get the substring from the PySpark Dataframe column and how to create the new column and put the substring in that newly created column."
},
{
"code": null,
"e": 289,
"s": 209,
"text": "We can get the substring of the column using substring() and substr() function."
},
{
"code": null,
"e": 320,
"s": 289,
"text": "Syntax: substring(str,pos,len)"
},
{
"code": null,
"e": 354,
"s": 320,
"text": "df.col_name.substr(start, length)"
},
{
"code": null,
"e": 365,
"s": 354,
"text": "Parameter:"
},
{
"code": null,
"e": 451,
"s": 365,
"text": "str – It can be string or name of the column from which we are getting the substring."
},
{
"code": null,
"e": 555,
"s": 451,
"text": "start and pos – Through this parameter we can give the starting position from where substring is start."
},
{
"code": null,
"e": 634,
"s": 555,
"text": "length and len – It is the length of the substring from the starting position."
},
{
"code": null,
"e": 660,
"s": 634,
"text": "Let’s create a dataframe."
},
{
"code": null,
"e": 668,
"s": 660,
"text": "Python3"
},
{
"code": "# importing necessary librariesfrom pyspark.sql import SparkSessionfrom pyspark.sql.functions import col, substring # function to create new SparkSessiondef create_session(): spk = SparkSession.builder \\ .master(\"local\") \\ .appName(\"Substring.com\") \\ .getOrCreate() return spk def create_df(spark, data, schema): df1 = spark.createDataFrame(data, schema) return df1 if __name__ == \"__main__\": input_data = [(\"India\", +91, 2701, 2020), (\"United States of America\", +1, 1301, 2020), (\"Israel\", +972, 3102, 2020), (\"Dubai\", +971, 2901, 2020), (\"Russia\", 7, 3101, 2020)] # calling function to create SparkSession spark = create_session() schema = [\"Country\", \"Country Code\", \"Data\", \"Year\"] # calling function to create dataframe df = create_df(spark, input_data, schema) df.show()",
"e": 1587,
"s": 668,
"text": null
},
{
"code": null,
"e": 1595,
"s": 1587,
"text": "Output:"
},
{
"code": null,
"e": 1699,
"s": 1595,
"text": "Example 1: Using substring() getting the substring and creating new column using withColumn() function."
},
{
"code": null,
"e": 1706,
"s": 1699,
"text": "Python"
},
{
"code": "if __name__ == \"__main__\": # creating Month column and get the # substring from the Data column # creating Date column and get the # substring from the Data column df = df.withColumn( \"Month\", substring(\"Data\", 1, 2)).withColumn( \"Date\", substring(\"Data\", 3, 4)) # dropping the Data column from the # Dataframe df = df.drop(\"Data\") # printing Dataframe schema to get the # column names df.printSchema() # visualizing the dataframe df.show(truncate=False)",
"e": 2216,
"s": 1706,
"text": null
},
{
"code": null,
"e": 2224,
"s": 2216,
"text": "Output:"
},
{
"code": null,
"e": 2313,
"s": 2224,
"text": "Example 2: Creating New_Country column by getting the substring using substr() function."
},
{
"code": null,
"e": 2320,
"s": 2313,
"text": "Python"
},
{
"code": "if __name__ == \"__main__\": # Creating the new column New_Country # and store the substring using substr() df = df.withColumn(\"New_Country\", df.Country.substr(0, 12)) # printing Dataframe schema to get the # column names df.printSchema() # visualizing the dataframe df.show(truncate=False)",
"e": 2636,
"s": 2320,
"text": null
},
{
"code": null,
"e": 2644,
"s": 2636,
"text": "Output:"
},
{
"code": null,
"e": 2697,
"s": 2644,
"text": "Example 3: Using substring() with select() function."
},
{
"code": null,
"e": 2704,
"s": 2697,
"text": "Python"
},
{
"code": "if __name__ == \"__main__\": input_data = [(\"India\", +91, \"AidanButler\"), (\"United States of America\", +1, \"ConerFlores\"), (\"Israel\", +972, \"RosseBryant\"), (\"Dubai\", +971, \"JuliaSimmon\"), (\"Russia\", 7, \"AliceBailey\")] # calling function to create SparkSession spark = create_session() schema = [\"Country\", \"Country Code\", \"Name\"] # calling function to create dataframe df = create_df(spark, input_data, schema) # Selecting the column using select() # function and getting substring # using substring() df2 = df.select('Name', substring('Name', 1, 5).alias('First Name'), substring('Name', 6, 6).alias('Last Name')) # printing Dataframe schema to get the column names df2.printSchema() # visualizing the dataframe df2.show(truncate=False)",
"e": 3613,
"s": 2704,
"text": null
},
{
"code": null,
"e": 3621,
"s": 3613,
"text": "Output:"
},
{
"code": null,
"e": 3678,
"s": 3621,
"text": "Example 4: Using substring() with selectExpr() function."
},
{
"code": null,
"e": 3685,
"s": 3678,
"text": "Python"
},
{
"code": "if __name__ == \"__main__\": input_data = [(\"India\", +91, \"AidanButler\"), (\"United States of America\", +1, \"ConerFlores\"), (\"Israel\", +972, \"RosseBryant\"), (\"Dubai\", +971, \"JuliaSimmon\"), (\"Russia\", 7, \"AliceBailey\")] # calling function to create SparkSession spark = create_session() schema = [\"Country\", \"Country Code\", \"Name\"] # calling function to create dataframe df = create_df(spark, input_data, schema) # Selecting the column using selectExpr() # function and getting substring using substring() df2 = df.selectExpr('Name', 'substring(Name, 1,5) as First_Name', 'substring(Name, 6,6) as Last_Name') # printing Dataframe schema to get the column names df2.printSchema() # visualizing the dataframe df2.show(truncate=False)",
"e": 4550,
"s": 3685,
"text": null
},
{
"code": null,
"e": 4558,
"s": 4550,
"text": "Output:"
},
{
"code": null,
"e": 4570,
"s": 4558,
"text": "anikaseth98"
},
{
"code": null,
"e": 4579,
"s": 4570,
"text": "gabaa406"
},
{
"code": null,
"e": 4594,
"s": 4579,
"text": "adnanirshad158"
},
{
"code": null,
"e": 4609,
"s": 4594,
"text": "varshagumber28"
},
{
"code": null,
"e": 4616,
"s": 4609,
"text": "Picked"
},
{
"code": null,
"e": 4631,
"s": 4616,
"text": "Python-Pyspark"
},
{
"code": null,
"e": 4638,
"s": 4631,
"text": "Python"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.