title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
How to remove a committed file from the Git repository?
|
Git allows you to delete a file from the repository using any of the following methods −
Using the Linux rm command
Using the Linux rm command
Using the git rm command
Using the git rm command
Scenario 1 − Use the Linux rm command
The syntax of the Linux rm command is −
$ git rm <file_name>
Let us assume that a file “file1.python” exists in the repository. Use the Linux rm command to delete the file − “file1.python”.
$ git rm file1.python
Let us first verify if the file has been removed from the working directory. This can be verified by using the Linux ls command.
$ ls
The output suggests that the file has been removed from the working directory.
dell@DESKTOP−N961NR5 MINGW64 /e/tut_repo (master)
$ Is
Let us now verify if the file has also been removed from the staging area.
Use the git command ls−files to verify this.
$ git ls−files
The output of the above code is −
file1.python
It is clear from the output that the file has not been removed from the staging area. This means changes like adding, renaming or deleting a file performed using Linux commands will not be automatically staged. Such changes should be explicitly staged using the git add command and then committed.
$ git add file1.python
Execute the ls−files command. The status of the operation can also be verified using the git status command.
$ git ls−files
$ git status
The output of the above commands is shown in the screenshot.
On branch master
Changes to be committed:
(use “git restore --staged <file>...” to unstage)
deleted:file1.python
The file is removed from the staging area. Let us now finally commit the change.
$ git commit -m ‘removed unused python file’
The file is permanently deleted from the repository. Refer the screenshot below for output.
[master 81e32c4] removed unused python file
1 file changed, 2 deletions (-)
delete mode 100644 file1.python
Scenario 2 − Use the git rm command
The syntax of the git rm command is
git rm <file_name>
Assuming that a file “file1.js” exists in the repository, let us use the git rm command to delete the file.
$ git rm file1.js
Let us use the git ls−files command to verify if the file has been removed from the staging area.
$ git ls−files
We can also use the git status command to verify if the file has been removed from the staging area.
$ git status
It is clear from the output that files removed using the git rm command are deleted from the working area and also from the staging area. Refer screenshot below for the output.
On branch master
Changes to be committed:
(use “git restore −−staged <file>...” to unstage)
deleted:file1.js
Let us now commit the change and verify the output.
$ git commit −m ‘remove unused js file’
The output suggests that the file has been permanently deleted from the repository.
[master dc7861e] removed unused js file
1 file changed, 1 deletion(−)
delete mode 100644 file1.js
|
[
{
"code": null,
"e": 1151,
"s": 1062,
"text": "Git allows you to delete a file from the repository using any of the following methods −"
},
{
"code": null,
"e": 1178,
"s": 1151,
"text": "Using the Linux rm command"
},
{
"code": null,
"e": 1205,
"s": 1178,
"text": "Using the Linux rm command"
},
{
"code": null,
"e": 1230,
"s": 1205,
"text": "Using the git rm command"
},
{
"code": null,
"e": 1255,
"s": 1230,
"text": "Using the git rm command"
},
{
"code": null,
"e": 1293,
"s": 1255,
"text": "Scenario 1 − Use the Linux rm command"
},
{
"code": null,
"e": 1333,
"s": 1293,
"text": "The syntax of the Linux rm command is −"
},
{
"code": null,
"e": 1354,
"s": 1333,
"text": "$ git rm <file_name>"
},
{
"code": null,
"e": 1483,
"s": 1354,
"text": "Let us assume that a file “file1.python” exists in the repository. Use the Linux rm command to delete the file − “file1.python”."
},
{
"code": null,
"e": 1505,
"s": 1483,
"text": "$ git rm file1.python"
},
{
"code": null,
"e": 1634,
"s": 1505,
"text": "Let us first verify if the file has been removed from the working directory. This can be verified by using the Linux ls command."
},
{
"code": null,
"e": 1639,
"s": 1634,
"text": "$ ls"
},
{
"code": null,
"e": 1718,
"s": 1639,
"text": "The output suggests that the file has been removed from the working directory."
},
{
"code": null,
"e": 1773,
"s": 1718,
"text": "dell@DESKTOP−N961NR5 MINGW64 /e/tut_repo (master)\n$ Is"
},
{
"code": null,
"e": 1848,
"s": 1773,
"text": "Let us now verify if the file has also been removed from the staging area."
},
{
"code": null,
"e": 1893,
"s": 1848,
"text": "Use the git command ls−files to verify this."
},
{
"code": null,
"e": 1908,
"s": 1893,
"text": "$ git ls−files"
},
{
"code": null,
"e": 1942,
"s": 1908,
"text": "The output of the above code is −"
},
{
"code": null,
"e": 1955,
"s": 1942,
"text": "file1.python"
},
{
"code": null,
"e": 2253,
"s": 1955,
"text": "It is clear from the output that the file has not been removed from the staging area. This means changes like adding, renaming or deleting a file performed using Linux commands will not be automatically staged. Such changes should be explicitly staged using the git add command and then committed."
},
{
"code": null,
"e": 2276,
"s": 2253,
"text": "$ git add file1.python"
},
{
"code": null,
"e": 2385,
"s": 2276,
"text": "Execute the ls−files command. The status of the operation can also be verified using the git status command."
},
{
"code": null,
"e": 2413,
"s": 2385,
"text": "$ git ls−files\n$ git status"
},
{
"code": null,
"e": 2474,
"s": 2413,
"text": "The output of the above commands is shown in the screenshot."
},
{
"code": null,
"e": 2596,
"s": 2474,
"text": "On branch master\nChanges to be committed:\n (use “git restore --staged <file>...” to unstage)\n deleted:file1.python"
},
{
"code": null,
"e": 2677,
"s": 2596,
"text": "The file is removed from the staging area. Let us now finally commit the change."
},
{
"code": null,
"e": 2722,
"s": 2677,
"text": "$ git commit -m ‘removed unused python file’"
},
{
"code": null,
"e": 2814,
"s": 2722,
"text": "The file is permanently deleted from the repository. Refer the screenshot below for output."
},
{
"code": null,
"e": 2922,
"s": 2814,
"text": "[master 81e32c4] removed unused python file\n1 file changed, 2 deletions (-)\ndelete mode 100644 file1.python"
},
{
"code": null,
"e": 2958,
"s": 2922,
"text": "Scenario 2 − Use the git rm command"
},
{
"code": null,
"e": 2994,
"s": 2958,
"text": "The syntax of the git rm command is"
},
{
"code": null,
"e": 3013,
"s": 2994,
"text": "git rm <file_name>"
},
{
"code": null,
"e": 3121,
"s": 3013,
"text": "Assuming that a file “file1.js” exists in the repository, let us use the git rm command to delete the file."
},
{
"code": null,
"e": 3139,
"s": 3121,
"text": "$ git rm file1.js"
},
{
"code": null,
"e": 3237,
"s": 3139,
"text": "Let us use the git ls−files command to verify if the file has been removed from the staging area."
},
{
"code": null,
"e": 3252,
"s": 3237,
"text": "$ git ls−files"
},
{
"code": null,
"e": 3353,
"s": 3252,
"text": "We can also use the git status command to verify if the file has been removed from the staging area."
},
{
"code": null,
"e": 3366,
"s": 3353,
"text": "$ git status"
},
{
"code": null,
"e": 3543,
"s": 3366,
"text": "It is clear from the output that files removed using the git rm command are deleted from the working area and also from the staging area. Refer screenshot below for the output."
},
{
"code": null,
"e": 3661,
"s": 3543,
"text": "On branch master\nChanges to be committed:\n (use “git restore −−staged <file>...” to unstage)\n deleted:file1.js"
},
{
"code": null,
"e": 3713,
"s": 3661,
"text": "Let us now commit the change and verify the output."
},
{
"code": null,
"e": 3753,
"s": 3713,
"text": "$ git commit −m ‘remove unused js file’"
},
{
"code": null,
"e": 3837,
"s": 3753,
"text": "The output suggests that the file has been permanently deleted from the repository."
},
{
"code": null,
"e": 3935,
"s": 3837,
"text": "[master dc7861e] removed unused js file\n1 file changed, 1 deletion(−)\ndelete mode 100644 file1.js"
}
] |
C++ Program to Implement Shell Sort
|
The shell sorting technique is based on the insertion sort. In the insertion sort sometimes we need to shift large block to insert item in the correct location. Using shell sort, we can avoid large number of shifting. The sorting is done with specific interval. After each pass the interval is reduced to make smaller interval.
Time Complexity: O(n log n) for best case, and for other cases, it depends on the gap sequence.
Time Complexity: O(n log n) for best case, and for other cases, it depends on the gap sequence.
Space Complexity: O(1)
Space Complexity: O(1)
Input − The unsorted list: 23 56 97 21 35 689 854 12 47 66
Output − Array after Sorting: 12 21 23 35 47 56 66 97 689 854
Input: An array of data, and the total number in the array
Output: The sorted Array
Begin
for gap := size / 2, when gap > 0 and gap is updated with gap / 2 do
for j:= gap to size– 1 do
for k := j-gap to 0, decrease by gap value do
if array[k+gap] >= array[k]
break
else
swap array[k + gap] with array[k]
done
done
done
End
#include<iostream>
using namespace std;
void swapping(int &a, int &b) { //swap the content of a and b
int temp;
temp = a;
a = b;
b = temp;
}
void display(int *array, int size) {
for(int i = 0; i<size; i++)
cout << array[i] << " ";
cout << endl;
}
void shellSort(int *arr, int n) {
int gap, j, k;
for(gap = n/2; gap > 0; gap = gap / 2) { //initially gap = n/2,
decreasing by gap /2
for(j = gap; j<n; j++) {
for(k = j-gap; k>=0; k -= gap) {
if(arr[k+gap] >= arr[k])
break;
else
swapping(arr[k+gap], arr[k]);
}
}
}
}
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n]; //create an array with given number of elements
cout << "Enter elements:" << endl;
for(int i = 0; i<n; i++) {
cin >> arr[i];
}
cout << "Array before Sorting: ";
display(arr, n);
shellSort(arr, n);
cout << "Array after Sorting: ";
display(arr, n);
}
Enter the number of elements: 10
Enter elements:
23 56 97 21 35 689 854 12 47 66
Array before Sorting: 23 56 97 21 35 689 854 12 47 66
Array after Sorting: 12 21 23 35 47 56 66 97 689 854
|
[
{
"code": null,
"e": 1390,
"s": 1062,
"text": "The shell sorting technique is based on the insertion sort. In the insertion sort sometimes we need to shift large block to insert item in the correct location. Using shell sort, we can avoid large number of shifting. The sorting is done with specific interval. After each pass the interval is reduced to make smaller interval."
},
{
"code": null,
"e": 1486,
"s": 1390,
"text": "Time Complexity: O(n log n) for best case, and for other cases, it depends on the gap sequence."
},
{
"code": null,
"e": 1582,
"s": 1486,
"text": "Time Complexity: O(n log n) for best case, and for other cases, it depends on the gap sequence."
},
{
"code": null,
"e": 1605,
"s": 1582,
"text": "Space Complexity: O(1)"
},
{
"code": null,
"e": 1628,
"s": 1605,
"text": "Space Complexity: O(1)"
},
{
"code": null,
"e": 1749,
"s": 1628,
"text": "Input − The unsorted list: 23 56 97 21 35 689 854 12 47 66\nOutput − Array after Sorting: 12 21 23 35 47 56 66 97 689 854"
},
{
"code": null,
"e": 1808,
"s": 1749,
"text": "Input: An array of data, and the total number in the array"
},
{
"code": null,
"e": 1833,
"s": 1808,
"text": "Output: The sorted Array"
},
{
"code": null,
"e": 2162,
"s": 1833,
"text": "Begin\n for gap := size / 2, when gap > 0 and gap is updated with gap / 2 do\n for j:= gap to size– 1 do\n for k := j-gap to 0, decrease by gap value do\n if array[k+gap] >= array[k]\n break\n else\n swap array[k + gap] with array[k]\n done\n done\n done\nEnd"
},
{
"code": null,
"e": 3192,
"s": 2162,
"text": "#include<iostream>\nusing namespace std;\nvoid swapping(int &a, int &b) { //swap the content of a and b\n int temp;\n temp = a;\n a = b;\n b = temp;\n}\nvoid display(int *array, int size) {\n for(int i = 0; i<size; i++)\n cout << array[i] << \" \";\n cout << endl;\n}\nvoid shellSort(int *arr, int n) {\n int gap, j, k;\n for(gap = n/2; gap > 0; gap = gap / 2) { //initially gap = n/2,\n decreasing by gap /2\n for(j = gap; j<n; j++) {\n for(k = j-gap; k>=0; k -= gap) {\n if(arr[k+gap] >= arr[k])\n break;\n else\n swapping(arr[k+gap], arr[k]);\n }\n }\n }\n}\nint main() {\n int n;\n cout << \"Enter the number of elements: \";\n cin >> n;\n int arr[n]; //create an array with given number of elements\n cout << \"Enter elements:\" << endl;\n for(int i = 0; i<n; i++) {\n cin >> arr[i];\n }\n cout << \"Array before Sorting: \";\n display(arr, n);\n shellSort(arr, n);\n cout << \"Array after Sorting: \";\n display(arr, n);\n}"
},
{
"code": null,
"e": 3380,
"s": 3192,
"text": "Enter the number of elements: 10\nEnter elements:\n23 56 97 21 35 689 854 12 47 66\nArray before Sorting: 23 56 97 21 35 689 854 12 47 66\nArray after Sorting: 12 21 23 35 47 56 66 97 689 854"
}
] |
Spring MVC - Generate XML Example
|
The following example shows how to generate XML using the Spring Web MVC Framework. To begin with, let us have a working Eclipse IDE in place and stick to the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework.
package com.tutorialspoint;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "user")
public class User {
private String name;
private int id;
public String getName() {
return name;
}
@XmlElement
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
@XmlElement
public void setId(int id) {
this.id = id;
}
}
package com.tutorialspoint;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping(value="{name}", method = RequestMethod.GET)
public @ResponseBody User getUser(@PathVariable String name) {
User user = new User();
user.setName(name);
user.setId(1);
return user;
}
}
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc = "http://www.springframework.org/schema/mvc"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package = "com.tutorialspoint" />
<mvc:annotation-driven />
</beans>
Here, we have created an XML Mapped POJO User and in the UserController, we have returned the User. Spring automatically handles the XML conversion based on RequestMapping.
Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save your TestWeb.war file in Tomcat's webapps folder.
Now, start the Tomcat server and make sure you are able to access other webpages from the webapps folder using a standard browser. Try a URL – http://localhost:8080/TestWeb/mahesh and we will see the following screen.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3046,
"s": 2791,
"text": "The following example shows how to generate XML using the Spring Web MVC Framework. To begin with, let us have a working Eclipse IDE in place and stick to the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework."
},
{
"code": null,
"e": 3519,
"s": 3046,
"text": "package com.tutorialspoint;\n\nimport javax.xml.bind.annotation.XmlElement;\nimport javax.xml.bind.annotation.XmlRootElement;\n\n@XmlRootElement(name = \"user\")\npublic class User {\n private String name;\n private int id;\n public String getName() {\n return name;\n }\n @XmlElement\n public void setName(String name) {\n this.name = name;\n }\n public int getId() {\n return id;\n }\n @XmlElement\n public void setId(int id) {\n this.id = id;\n }\t\n}"
},
{
"code": null,
"e": 4149,
"s": 3519,
"text": "package com.tutorialspoint;\n\nimport org.springframework.stereotype.Controller;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\nimport org.springframework.web.bind.annotation.ResponseBody;\n\n@Controller\n@RequestMapping(\"/user\")\npublic class UserController {\n\t\n @RequestMapping(value=\"{name}\", method = RequestMethod.GET)\n public @ResponseBody User getUser(@PathVariable String name) {\n\n User user = new User();\n\n user.setName(name);\n user.setId(1);\n return user;\n }\n}"
},
{
"code": null,
"e": 4881,
"s": 4149,
"text": "<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:context = \"http://www.springframework.org/schema/context\" \n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xmlns:mvc = \"http://www.springframework.org/schema/mvc\"\n xsi:schemaLocation = \"\n http://www.springframework.org/schema/beans \n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\n http://www.springframework.org/schema/context \n http://www.springframework.org/schema/context/spring-context-3.0.xsd\n http://www.springframework.org/schema/mvc\n http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd\">\n <context:component-scan base-package = \"com.tutorialspoint\" />\n <mvc:annotation-driven />\n</beans>"
},
{
"code": null,
"e": 5054,
"s": 4881,
"text": "Here, we have created an XML Mapped POJO User and in the UserController, we have returned the User. Spring automatically handles the XML conversion based on RequestMapping."
},
{
"code": null,
"e": 5264,
"s": 5054,
"text": "Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save your TestWeb.war file in Tomcat's webapps folder."
},
{
"code": null,
"e": 5482,
"s": 5264,
"text": "Now, start the Tomcat server and make sure you are able to access other webpages from the webapps folder using a standard browser. Try a URL – http://localhost:8080/TestWeb/mahesh and we will see the following screen."
},
{
"code": null,
"e": 5489,
"s": 5482,
"text": " Print"
},
{
"code": null,
"e": 5500,
"s": 5489,
"text": " Add Notes"
}
] |
Sum of Bitwise And of all pairs in a given array - GeeksforGeeks
|
21 Apr, 2022
Given an array “arr[0..n-1]” of integers, calculate sum of “arr[i] & arr[j]” for all the pairs in the given where i < j. Here & is bitwise AND operator. Expected time complexity is O(n). Examples :
Input: arr[] = {5, 10, 15}
Output: 15
Required Value = (5 & 10) + (5 & 15) + (10 & 15)
= 0 + 5 + 10
= 15
Input: arr[] = {1, 2, 3, 4}
Output: 3
Required Value = (1 & 2) + (1 & 3) + (1 & 4) +
(2 & 3) + (2 & 4) + (3 & 4)
= 0 + 1 + 0 + 2 + 0 + 0
= 3
A Brute Force approach is to run two loops and time complexity is O(n2).
C++
C
Java
Python3
C#
PHP
Javascript
// A Simple C++ program to compute sum of bitwise AND// of all pairs#include <bits/stdc++.h>using namespace std; // Returns value of "arr[0] & arr[1] + arr[0] & arr[2] +// ... arr[i] & arr[j] + ..... arr[n-2] & arr[n-1]"int pairAndSum(int arr[], int n){ int ans = 0; // Initialize result // Consider all pairs (arr[i], arr[j) such that // i < j for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) ans += arr[i] & arr[j]; return ans;} // Driver program to test above functionint main(){ int arr[] = { 5, 10, 15 }; int n = sizeof(arr) / sizeof(arr[0]); cout << pairAndSum(arr, n) << endl; return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// A Simple C++ program to compute sum of bitwise AND// of all pairs#include <stdio.h> // Returns value of "arr[0] & arr[1] + arr[0] & arr[2] +// ... arr[i] & arr[j] + ..... arr[n-2] & arr[n-1]"int pairAndSum(int arr[], int n){ int ans = 0; // Initialize result // Consider all pairs (arr[i], arr[j) such that // i < j for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) ans += arr[i] & arr[j]; return ans;} // Driver program to test above functionint main(){ int arr[] = { 5, 10, 15 }; int n = sizeof(arr) / sizeof(arr[0]); printf("%d\n",pairAndSum(arr, n)); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// A Simple Java program to compute// sum of bitwise AND of all pairsimport java.io.*; class GFG { // Returns value of "arr[0] & arr[1] + // arr[0] & arr[2] + ... arr[i] & arr[j] + // ..... arr[n-2] & arr[n-1]" static int pairAndSum(int arr[], int n) { int ans = 0; // Initialize result // Consider all pairs (arr[i], arr[j) // such that i < j for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) ans += arr[i] & arr[j]; return ans; } // Driver program to test above function public static void main(String args[]) { int arr[] = { 5, 10, 15 }; int n = arr.length; System.out.println(pairAndSum(arr, n)); }} // This code is contributed by Aditya Kumar (adityakumar129)
# A Simple Python 3 program to compute# sum of bitwise AND of all pairs # Returns value of "arr[0] & arr[1] +# arr[0] & arr[2] + ... arr[i] & arr[j] +# ..... arr[n-2] & arr[n-1]"def pairAndSum(arr, n) : ans = 0 # Initialize result # Consider all pairs (arr[i], arr[j) # such that i < j for i in range(0,n) : for j in range((i+1),n) : ans = ans + arr[i] & arr[j] return ans # Driver program to test above functionarr = [5, 10, 15]n = len(arr)print(pairAndSum(arr, n)) # This code is contributed by Nikita Tiwari.
// A Simple C# program to compute// sum of bitwise AND of all pairsusing System; class GFG { // Returns value of "arr[0] & arr[1] + // arr[0] & arr[2] + ... arr[i] & arr[j] + // ..... arr[n-2] & arr[n-1]" static int pairAndSum(int []arr, int n) { int ans = 0; // Initialize result // Consider all pairs (arr[i], arr[j) // such that i < j for (int i = 0; i < n; i++) for (int j = i+1; j < n; j++) ans += arr[i] & arr[j]; return ans; } // Driver program to test above function public static void Main() { int []arr = {5, 10, 15}; int n = arr.Length; Console.Write(pairAndSum(arr, n) ); }} // This code is contributed by nitin mittal.
<?php// A Simple PHP program to// compute sum of bitwise// AND of all pairs // Returns value of "arr[0] &// arr[1] + arr[0] & arr[2] +// ... arr[i] & arr[j] + .....// arr[n-2] & arr[n-1]" function pairAndSum($arr, $n){ // Initialize result $ans = 0; // Consider all pairs (arr[i], // arr[j) such that i < j for ($i = 0; $i < $n; $i++) for ( $j = $i + 1; $j < $n; $j++) $ans += $arr[$i] & $arr[$j]; return $ans;} // Driver Code$arr = array(5, 10, 15);$n = sizeof($arr) ;echo pairAndSum($arr, $n), "\n"; // This code is contributed by m_kit?>
<script> // A Simple Javascript program to compute // sum of bitwise AND of all pairs // Returns value of "arr[0] & arr[1] + // arr[0] & arr[2] + ... arr[i] & arr[j] + // ..... arr[n-2] & arr[n-1]" function pairAndSum(arr, n) { let ans = 0; // Initialize result // Consider all pairs (arr[i], arr[j) // such that i < j for (let i = 0; i < n; i++) for (let j = i+1; j < n; j++) ans += arr[i] & arr[j]; return ans; } let arr = [5, 10, 15]; let n = arr.length; document.write(pairAndSum(arr, n)); </script>
Output :
15
Time Complexity: O(n2)
Auxiliary Space: O(1)
An Efficient Solution can solve this problem in O(n) time. The assumption here is that integers are represented using 32 bits.The idea is to count number of set bits at every i’th position (i>=0 && i<=31). Any i’th bit of the AND of two numbers is 1 iff the corresponding bit in both the numbers is equal to 1. Let k be the count of set bits at i’th position. Total number of pairs with i’th set bit would be kC2 = k*(k-1)/2 (Count k means there are k numbers which have i’th set bit). Every such pair adds 2i to total sum. Similarly, we work for all other places and add the sum to our final answer.This idea is similar to this. Below is the implementation.
C++
C
Java
Python3
C#
PHP
Javascript
// An efficient C++ program to compute sum of bitwise AND// of all pairs#include <bits/stdc++.h>using namespace std; // Returns value of "arr[0] & arr[1] + arr[0] & arr[2] +// ... arr[i] & arr[j] + ..... arr[n-2] & arr[n-1]"int pairAndSum(int arr[], int n){ int ans = 0; // Initialize result // Traverse over all bits for (int i = 0; i < 32; i++) { // Count number of elements with i'th bit set int k = 0; // Initialize the count for (int j = 0; j < n; j++) if ((arr[j] & (1 << i))) k++; // There are k set bits, means k(k-1)/2 pairs. // Every pair adds 2^i to the answer. Therefore, // we add "2^i * [k*(k-1)/2]" to the answer. ans += (1 << i) * (k * (k - 1) / 2); } return ans;} // Driver program to test above functionint main(){ int arr[] = { 5, 10, 15 }; int n = sizeof(arr) / sizeof(arr[0]); cout << pairAndSum(arr, n) << endl; return 0;}
// An efficient C++ program to compute sum of bitwise AND// of all pairs#include <stdio.h> // Returns value of "arr[0] & arr[1] + arr[0] & arr[2] +// ... arr[i] & arr[j] + ..... arr[n-2] & arr[n-1]"int pairAndSum(int arr[], int n){ int ans = 0; // Initialize result // Traverse over all bits for (int i = 0; i < 32; i++) { // Count number of elements with i'th bit set int k = 0; // Initialize the count for (int j = 0; j < n; j++) if ((arr[j] & (1 << i))) k++; // There are k set bits, means k(k-1)/2 pairs. // Every pair adds 2^i to the answer. Therefore, // we add "2^i * [k*(k-1)/2]" to the answer. ans += (1 << i) * (k * (k - 1) / 2); } return ans;} // Driver program to test above functionint main(){ int arr[] = { 5, 10, 15 }; int n = sizeof(arr) / sizeof(arr[0]); printf("%d\n",pairAndSum(arr, n)); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// An efficient Java program to compute// sum of bitwise AND of all pairsimport java.io.*; class GFG { // Returns value of "arr[0] & arr[1] + // arr[0] & arr[2] + ... arr[i] & arr[j] + // ..... arr[n-2] & arr[n-1]" static int pairAndSum(int arr[], int n) { int ans = 0; // Initialize result // Traverse over all bits for (int i = 0; i < 32; i++) { // Count number of elements with i'th bit set // Initialize the count int k = 0; for (int j = 0; j < n; j++) { if ((arr[j] & (1 << i)) != 0) k++; } // There are k set bits, means k(k-1)/2 pairs. // Every pair adds 2^i to the answer. Therefore, // we add "2^i * [k*(k-1)/2]" to the answer. ans += (1 << i) * (k * (k - 1) / 2); } return ans; } // Driver program to test above function public static void main(String args[]) { int arr[] = { 5, 10, 15 }; int n = arr.length; System.out.println(pairAndSum(arr, n)); }} // An efficient C++ program to compute sum of bitwise AND// of all pairs#include <stdio.h> // Returns value of "arr[0] & arr[1] + arr[0] & arr[2] +// ... arr[i] & arr[j] + ..... arr[n-2] & arr[n-1]"int pairAndSum(int arr[], int n){ int ans = 0; // Initialize result // Traverse over all bits for (int i = 0; i < 32; i++) { // Count number of elements with i'th bit set int k = 0; // Initialize the count for (int j = 0; j < n; j++) if ((arr[j] & (1 << i))) k++; // There are k set bits, means k(k-1)/2 pairs. // Every pair adds 2^i to the answer. Therefore, // we add "2^i * [k*(k-1)/2]" to the answer. ans += (1 << i) * (k * (k - 1) / 2); } return ans;} // Driver program to test above functionint main(){ int arr[] = { 5, 10, 15 }; int n = sizeof(arr) / sizeof(arr[0]); printf("%d\n",pairAndSum(arr, n)); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
# An efficient Python 3 program to# compute sum of bitwise AND of all pairs # Returns value of "arr[0] & arr[1] +# arr[0] & arr[2] + ... arr[i] & arr[j] +# ..... arr[n-2] & arr[n-1]"def pairAndSum(arr, n) : ans = 0 # Initialize result # Traverse over all bits for i in range(0,32) : # Count number of elements with i'th bit set # Initialize the count k = 0 for j in range(0,n) : if ( (arr[j] & (1 << i)) ) : k = k + 1 # There are k set bits, means k(k-1)/2 pairs. # Every pair adds 2^i to the answer. Therefore, # we add "2^i * [k*(k-1)/2]" to the answer. ans = ans + (1 << i) * (k * (k - 1) // 2) return ans # Driver program to test above functionarr = [5, 10, 15]n = len(arr)print(pairAndSum(arr, n)) # This code is contributed by Nikita Tiwari.
// An efficient C# program to compute// sum of bitwise AND of all pairsusing System; class GFG { // Returns value of "arr[0] & arr[1] + // arr[0] & arr[2] + ... arr[i] & arr[j] + // ..... arr[n-2] & arr[n-1]" static int pairAndSum(int []arr, int n) { int ans = 0; // Initialize result // Traverse over all bits for (int i = 0; i < 32; i++) { // Count number of elements with // i'th bit set Initialize the count int k = 0; for (int j = 0; j < n; j++) { if ((arr[j] & (1 << i))!=0) k++; } // There are k set bits, means // k(k-1)/2 pairs. Every pair // adds 2^i to the answer. // Therefore, we add "2^i * // [k*(k-1)/2]" to the answer. ans += (1 << i) * (k * (k - 1)/2); } return ans; } // Driver program to test above function public static void Main() { int []arr = new int[]{5, 10, 15}; int n = arr.Length; Console.Write(pairAndSum(arr, n)); }} /* This code is contributed by smitha*/
<?php// An efficient PHP program to// compute sum of bitwise AND// of all pairs // Returns value of "arr[0] &// arr[1] + arr[0] & arr[2] +// ... arr[i] & arr[j] + .....// arr[n-2] & arr[n-1]"function pairAndSum($arr, $n){ // Initialize result $ans = 0; // Traverse over all bits for ($i = 0; $i < 32; $i++) { // Count number of elements // with i'th bit set // Initialize the count $k = 0; for ($j = 0; $j < $n; $j++) if (($arr[$j] & (1 << $i)) ) $k++; // There are k set bits, // means k(k-1)/2 pairs. // Every pair adds 2^i to // the answer. Therefore, // we add "2^i * [k*(k-1)/2]" // to the answer. $ans += (1 << $i) * ($k * ($k - 1) / 2); } return $ans;} // Driver Code $arr = array(5, 10, 15); $n = sizeof($arr); echo pairAndSum($arr, $n) ; // This code is contributed by nitin mittal.?>
<script> // An efficient Javascript program to compute // sum of bitwise AND of all pairs // Returns value of "arr[0] & arr[1] + // arr[0] & arr[2] + ... arr[i] & arr[j] + // ..... arr[n-2] & arr[n-1]" function pairAndSum(arr, n) { let ans = 0; // Initialize result // Traverse over all bits for (let i = 0; i < 32; i++) { // Count number of elements with // i'th bit set Initialize the count let k = 0; for (let j = 0; j < n; j++) { if ((arr[j] & (1 << i))!=0) k++; } // There are k set bits, means // k(k-1)/2 pairs. Every pair // adds 2^i to the answer. // Therefore, we add "2^i * // [k*(k-1)/2]" to the answer. ans += (1 << i) * (k * (k - 1)/2); } return ans; } let arr = [5, 10, 15]; let n = arr.length; document.write(pairAndSum(arr, n)); // This code is contributed by rameshtravel07.</script>
Output:
15
Time Complexity: O(n)
Auxiliary Space: O(1)
This article is contributed by Ekta Goel. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Nikita tiwari
nitin mittal
Smitha Dinesh Semwal
jit_t
decode2207
rameshtravel07
souravmahato348
Bit Magic
Mathematical
Mathematical
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Cyclic Redundancy Check and Modulo-2 Division
Little and Big Endian Mystery
Add two numbers without using arithmetic operators
Binary representation of a given number
Find the element that appears once
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
|
[
{
"code": null,
"e": 25003,
"s": 24975,
"text": "\n21 Apr, 2022"
},
{
"code": null,
"e": 25203,
"s": 25003,
"text": "Given an array “arr[0..n-1]” of integers, calculate sum of “arr[i] & arr[j]” for all the pairs in the given where i < j. Here & is bitwise AND operator. Expected time complexity is O(n). Examples : "
},
{
"code": null,
"e": 25532,
"s": 25203,
"text": "Input: arr[] = {5, 10, 15}\nOutput: 15\nRequired Value = (5 & 10) + (5 & 15) + (10 & 15) \n = 0 + 5 + 10 \n = 15\n\nInput: arr[] = {1, 2, 3, 4}\nOutput: 3\nRequired Value = (1 & 2) + (1 & 3) + (1 & 4) + \n (2 & 3) + (2 & 4) + (3 & 4) \n = 0 + 1 + 0 + 2 + 0 + 0\n = 3"
},
{
"code": null,
"e": 25609,
"s": 25534,
"text": "A Brute Force approach is to run two loops and time complexity is O(n2). "
},
{
"code": null,
"e": 25613,
"s": 25609,
"text": "C++"
},
{
"code": null,
"e": 25615,
"s": 25613,
"text": "C"
},
{
"code": null,
"e": 25620,
"s": 25615,
"text": "Java"
},
{
"code": null,
"e": 25628,
"s": 25620,
"text": "Python3"
},
{
"code": null,
"e": 25631,
"s": 25628,
"text": "C#"
},
{
"code": null,
"e": 25635,
"s": 25631,
"text": "PHP"
},
{
"code": null,
"e": 25646,
"s": 25635,
"text": "Javascript"
},
{
"code": "// A Simple C++ program to compute sum of bitwise AND// of all pairs#include <bits/stdc++.h>using namespace std; // Returns value of \"arr[0] & arr[1] + arr[0] & arr[2] +// ... arr[i] & arr[j] + ..... arr[n-2] & arr[n-1]\"int pairAndSum(int arr[], int n){ int ans = 0; // Initialize result // Consider all pairs (arr[i], arr[j) such that // i < j for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) ans += arr[i] & arr[j]; return ans;} // Driver program to test above functionint main(){ int arr[] = { 5, 10, 15 }; int n = sizeof(arr) / sizeof(arr[0]); cout << pairAndSum(arr, n) << endl; return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 26360,
"s": 25646,
"text": null
},
{
"code": "// A Simple C++ program to compute sum of bitwise AND// of all pairs#include <stdio.h> // Returns value of \"arr[0] & arr[1] + arr[0] & arr[2] +// ... arr[i] & arr[j] + ..... arr[n-2] & arr[n-1]\"int pairAndSum(int arr[], int n){ int ans = 0; // Initialize result // Consider all pairs (arr[i], arr[j) such that // i < j for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) ans += arr[i] & arr[j]; return ans;} // Driver program to test above functionint main(){ int arr[] = { 5, 10, 15 }; int n = sizeof(arr) / sizeof(arr[0]); printf(\"%d\\n\",pairAndSum(arr, n)); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 27047,
"s": 26360,
"text": null
},
{
"code": "// A Simple Java program to compute// sum of bitwise AND of all pairsimport java.io.*; class GFG { // Returns value of \"arr[0] & arr[1] + // arr[0] & arr[2] + ... arr[i] & arr[j] + // ..... arr[n-2] & arr[n-1]\" static int pairAndSum(int arr[], int n) { int ans = 0; // Initialize result // Consider all pairs (arr[i], arr[j) // such that i < j for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) ans += arr[i] & arr[j]; return ans; } // Driver program to test above function public static void main(String args[]) { int arr[] = { 5, 10, 15 }; int n = arr.length; System.out.println(pairAndSum(arr, n)); }} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 27838,
"s": 27047,
"text": null
},
{
"code": "# A Simple Python 3 program to compute# sum of bitwise AND of all pairs # Returns value of \"arr[0] & arr[1] +# arr[0] & arr[2] + ... arr[i] & arr[j] +# ..... arr[n-2] & arr[n-1]\"def pairAndSum(arr, n) : ans = 0 # Initialize result # Consider all pairs (arr[i], arr[j) # such that i < j for i in range(0,n) : for j in range((i+1),n) : ans = ans + arr[i] & arr[j] return ans # Driver program to test above functionarr = [5, 10, 15]n = len(arr)print(pairAndSum(arr, n)) # This code is contributed by Nikita Tiwari.",
"e": 28385,
"s": 27838,
"text": null
},
{
"code": "// A Simple C# program to compute// sum of bitwise AND of all pairsusing System; class GFG { // Returns value of \"arr[0] & arr[1] + // arr[0] & arr[2] + ... arr[i] & arr[j] + // ..... arr[n-2] & arr[n-1]\" static int pairAndSum(int []arr, int n) { int ans = 0; // Initialize result // Consider all pairs (arr[i], arr[j) // such that i < j for (int i = 0; i < n; i++) for (int j = i+1; j < n; j++) ans += arr[i] & arr[j]; return ans; } // Driver program to test above function public static void Main() { int []arr = {5, 10, 15}; int n = arr.Length; Console.Write(pairAndSum(arr, n) ); }} // This code is contributed by nitin mittal.",
"e": 29155,
"s": 28385,
"text": null
},
{
"code": "<?php// A Simple PHP program to// compute sum of bitwise// AND of all pairs // Returns value of \"arr[0] &// arr[1] + arr[0] & arr[2] +// ... arr[i] & arr[j] + .....// arr[n-2] & arr[n-1]\" function pairAndSum($arr, $n){ // Initialize result $ans = 0; // Consider all pairs (arr[i], // arr[j) such that i < j for ($i = 0; $i < $n; $i++) for ( $j = $i + 1; $j < $n; $j++) $ans += $arr[$i] & $arr[$j]; return $ans;} // Driver Code$arr = array(5, 10, 15);$n = sizeof($arr) ;echo pairAndSum($arr, $n), \"\\n\"; // This code is contributed by m_kit?>",
"e": 29730,
"s": 29155,
"text": null
},
{
"code": "<script> // A Simple Javascript program to compute // sum of bitwise AND of all pairs // Returns value of \"arr[0] & arr[1] + // arr[0] & arr[2] + ... arr[i] & arr[j] + // ..... arr[n-2] & arr[n-1]\" function pairAndSum(arr, n) { let ans = 0; // Initialize result // Consider all pairs (arr[i], arr[j) // such that i < j for (let i = 0; i < n; i++) for (let j = i+1; j < n; j++) ans += arr[i] & arr[j]; return ans; } let arr = [5, 10, 15]; let n = arr.length; document.write(pairAndSum(arr, n)); </script>",
"e": 30362,
"s": 29730,
"text": null
},
{
"code": null,
"e": 30372,
"s": 30362,
"text": "Output : "
},
{
"code": null,
"e": 30375,
"s": 30372,
"text": "15"
},
{
"code": null,
"e": 30398,
"s": 30375,
"text": "Time Complexity: O(n2)"
},
{
"code": null,
"e": 30420,
"s": 30398,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 31080,
"s": 30420,
"text": "An Efficient Solution can solve this problem in O(n) time. The assumption here is that integers are represented using 32 bits.The idea is to count number of set bits at every i’th position (i>=0 && i<=31). Any i’th bit of the AND of two numbers is 1 iff the corresponding bit in both the numbers is equal to 1. Let k be the count of set bits at i’th position. Total number of pairs with i’th set bit would be kC2 = k*(k-1)/2 (Count k means there are k numbers which have i’th set bit). Every such pair adds 2i to total sum. Similarly, we work for all other places and add the sum to our final answer.This idea is similar to this. Below is the implementation. "
},
{
"code": null,
"e": 31084,
"s": 31080,
"text": "C++"
},
{
"code": null,
"e": 31086,
"s": 31084,
"text": "C"
},
{
"code": null,
"e": 31091,
"s": 31086,
"text": "Java"
},
{
"code": null,
"e": 31099,
"s": 31091,
"text": "Python3"
},
{
"code": null,
"e": 31102,
"s": 31099,
"text": "C#"
},
{
"code": null,
"e": 31106,
"s": 31102,
"text": "PHP"
},
{
"code": null,
"e": 31117,
"s": 31106,
"text": "Javascript"
},
{
"code": "// An efficient C++ program to compute sum of bitwise AND// of all pairs#include <bits/stdc++.h>using namespace std; // Returns value of \"arr[0] & arr[1] + arr[0] & arr[2] +// ... arr[i] & arr[j] + ..... arr[n-2] & arr[n-1]\"int pairAndSum(int arr[], int n){ int ans = 0; // Initialize result // Traverse over all bits for (int i = 0; i < 32; i++) { // Count number of elements with i'th bit set int k = 0; // Initialize the count for (int j = 0; j < n; j++) if ((arr[j] & (1 << i))) k++; // There are k set bits, means k(k-1)/2 pairs. // Every pair adds 2^i to the answer. Therefore, // we add \"2^i * [k*(k-1)/2]\" to the answer. ans += (1 << i) * (k * (k - 1) / 2); } return ans;} // Driver program to test above functionint main(){ int arr[] = { 5, 10, 15 }; int n = sizeof(arr) / sizeof(arr[0]); cout << pairAndSum(arr, n) << endl; return 0;}",
"e": 32067,
"s": 31117,
"text": null
},
{
"code": "// An efficient C++ program to compute sum of bitwise AND// of all pairs#include <stdio.h> // Returns value of \"arr[0] & arr[1] + arr[0] & arr[2] +// ... arr[i] & arr[j] + ..... arr[n-2] & arr[n-1]\"int pairAndSum(int arr[], int n){ int ans = 0; // Initialize result // Traverse over all bits for (int i = 0; i < 32; i++) { // Count number of elements with i'th bit set int k = 0; // Initialize the count for (int j = 0; j < n; j++) if ((arr[j] & (1 << i))) k++; // There are k set bits, means k(k-1)/2 pairs. // Every pair adds 2^i to the answer. Therefore, // we add \"2^i * [k*(k-1)/2]\" to the answer. ans += (1 << i) * (k * (k - 1) / 2); } return ans;} // Driver program to test above functionint main(){ int arr[] = { 5, 10, 15 }; int n = sizeof(arr) / sizeof(arr[0]); printf(\"%d\\n\",pairAndSum(arr, n)); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 33048,
"s": 32067,
"text": null
},
{
"code": "// An efficient Java program to compute// sum of bitwise AND of all pairsimport java.io.*; class GFG { // Returns value of \"arr[0] & arr[1] + // arr[0] & arr[2] + ... arr[i] & arr[j] + // ..... arr[n-2] & arr[n-1]\" static int pairAndSum(int arr[], int n) { int ans = 0; // Initialize result // Traverse over all bits for (int i = 0; i < 32; i++) { // Count number of elements with i'th bit set // Initialize the count int k = 0; for (int j = 0; j < n; j++) { if ((arr[j] & (1 << i)) != 0) k++; } // There are k set bits, means k(k-1)/2 pairs. // Every pair adds 2^i to the answer. Therefore, // we add \"2^i * [k*(k-1)/2]\" to the answer. ans += (1 << i) * (k * (k - 1) / 2); } return ans; } // Driver program to test above function public static void main(String args[]) { int arr[] = { 5, 10, 15 }; int n = arr.length; System.out.println(pairAndSum(arr, n)); }} // An efficient C++ program to compute sum of bitwise AND// of all pairs#include <stdio.h> // Returns value of \"arr[0] & arr[1] + arr[0] & arr[2] +// ... arr[i] & arr[j] + ..... arr[n-2] & arr[n-1]\"int pairAndSum(int arr[], int n){ int ans = 0; // Initialize result // Traverse over all bits for (int i = 0; i < 32; i++) { // Count number of elements with i'th bit set int k = 0; // Initialize the count for (int j = 0; j < n; j++) if ((arr[j] & (1 << i))) k++; // There are k set bits, means k(k-1)/2 pairs. // Every pair adds 2^i to the answer. Therefore, // we add \"2^i * [k*(k-1)/2]\" to the answer. ans += (1 << i) * (k * (k - 1) / 2); } return ans;} // Driver program to test above functionint main(){ int arr[] = { 5, 10, 15 }; int n = sizeof(arr) / sizeof(arr[0]); printf(\"%d\\n\",pairAndSum(arr, n)); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 35114,
"s": 33048,
"text": null
},
{
"code": "# An efficient Python 3 program to# compute sum of bitwise AND of all pairs # Returns value of \"arr[0] & arr[1] +# arr[0] & arr[2] + ... arr[i] & arr[j] +# ..... arr[n-2] & arr[n-1]\"def pairAndSum(arr, n) : ans = 0 # Initialize result # Traverse over all bits for i in range(0,32) : # Count number of elements with i'th bit set # Initialize the count k = 0 for j in range(0,n) : if ( (arr[j] & (1 << i)) ) : k = k + 1 # There are k set bits, means k(k-1)/2 pairs. # Every pair adds 2^i to the answer. Therefore, # we add \"2^i * [k*(k-1)/2]\" to the answer. ans = ans + (1 << i) * (k * (k - 1) // 2) return ans # Driver program to test above functionarr = [5, 10, 15]n = len(arr)print(pairAndSum(arr, n)) # This code is contributed by Nikita Tiwari.",
"e": 35976,
"s": 35114,
"text": null
},
{
"code": "// An efficient C# program to compute// sum of bitwise AND of all pairsusing System; class GFG { // Returns value of \"arr[0] & arr[1] + // arr[0] & arr[2] + ... arr[i] & arr[j] + // ..... arr[n-2] & arr[n-1]\" static int pairAndSum(int []arr, int n) { int ans = 0; // Initialize result // Traverse over all bits for (int i = 0; i < 32; i++) { // Count number of elements with // i'th bit set Initialize the count int k = 0; for (int j = 0; j < n; j++) { if ((arr[j] & (1 << i))!=0) k++; } // There are k set bits, means // k(k-1)/2 pairs. Every pair // adds 2^i to the answer. // Therefore, we add \"2^i * // [k*(k-1)/2]\" to the answer. ans += (1 << i) * (k * (k - 1)/2); } return ans; } // Driver program to test above function public static void Main() { int []arr = new int[]{5, 10, 15}; int n = arr.Length; Console.Write(pairAndSum(arr, n)); }} /* This code is contributed by smitha*/",
"e": 37156,
"s": 35976,
"text": null
},
{
"code": "<?php// An efficient PHP program to// compute sum of bitwise AND// of all pairs // Returns value of \"arr[0] &// arr[1] + arr[0] & arr[2] +// ... arr[i] & arr[j] + .....// arr[n-2] & arr[n-1]\"function pairAndSum($arr, $n){ // Initialize result $ans = 0; // Traverse over all bits for ($i = 0; $i < 32; $i++) { // Count number of elements // with i'th bit set // Initialize the count $k = 0; for ($j = 0; $j < $n; $j++) if (($arr[$j] & (1 << $i)) ) $k++; // There are k set bits, // means k(k-1)/2 pairs. // Every pair adds 2^i to // the answer. Therefore, // we add \"2^i * [k*(k-1)/2]\" // to the answer. $ans += (1 << $i) * ($k * ($k - 1) / 2); } return $ans;} // Driver Code $arr = array(5, 10, 15); $n = sizeof($arr); echo pairAndSum($arr, $n) ; // This code is contributed by nitin mittal.?>",
"e": 38106,
"s": 37156,
"text": null
},
{
"code": "<script> // An efficient Javascript program to compute // sum of bitwise AND of all pairs // Returns value of \"arr[0] & arr[1] + // arr[0] & arr[2] + ... arr[i] & arr[j] + // ..... arr[n-2] & arr[n-1]\" function pairAndSum(arr, n) { let ans = 0; // Initialize result // Traverse over all bits for (let i = 0; i < 32; i++) { // Count number of elements with // i'th bit set Initialize the count let k = 0; for (let j = 0; j < n; j++) { if ((arr[j] & (1 << i))!=0) k++; } // There are k set bits, means // k(k-1)/2 pairs. Every pair // adds 2^i to the answer. // Therefore, we add \"2^i * // [k*(k-1)/2]\" to the answer. ans += (1 << i) * (k * (k - 1)/2); } return ans; } let arr = [5, 10, 15]; let n = arr.length; document.write(pairAndSum(arr, n)); // This code is contributed by rameshtravel07.</script>",
"e": 39190,
"s": 38106,
"text": null
},
{
"code": null,
"e": 39200,
"s": 39190,
"text": "Output: "
},
{
"code": null,
"e": 39203,
"s": 39200,
"text": "15"
},
{
"code": null,
"e": 39225,
"s": 39203,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 39247,
"s": 39225,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 39415,
"s": 39247,
"text": "This article is contributed by Ekta Goel. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 39429,
"s": 39415,
"text": "Nikita tiwari"
},
{
"code": null,
"e": 39442,
"s": 39429,
"text": "nitin mittal"
},
{
"code": null,
"e": 39463,
"s": 39442,
"text": "Smitha Dinesh Semwal"
},
{
"code": null,
"e": 39469,
"s": 39463,
"text": "jit_t"
},
{
"code": null,
"e": 39480,
"s": 39469,
"text": "decode2207"
},
{
"code": null,
"e": 39495,
"s": 39480,
"text": "rameshtravel07"
},
{
"code": null,
"e": 39511,
"s": 39495,
"text": "souravmahato348"
},
{
"code": null,
"e": 39521,
"s": 39511,
"text": "Bit Magic"
},
{
"code": null,
"e": 39534,
"s": 39521,
"text": "Mathematical"
},
{
"code": null,
"e": 39547,
"s": 39534,
"text": "Mathematical"
},
{
"code": null,
"e": 39557,
"s": 39547,
"text": "Bit Magic"
},
{
"code": null,
"e": 39655,
"s": 39557,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39664,
"s": 39655,
"text": "Comments"
},
{
"code": null,
"e": 39677,
"s": 39664,
"text": "Old Comments"
},
{
"code": null,
"e": 39723,
"s": 39677,
"text": "Cyclic Redundancy Check and Modulo-2 Division"
},
{
"code": null,
"e": 39753,
"s": 39723,
"text": "Little and Big Endian Mystery"
},
{
"code": null,
"e": 39804,
"s": 39753,
"text": "Add two numbers without using arithmetic operators"
},
{
"code": null,
"e": 39844,
"s": 39804,
"text": "Binary representation of a given number"
},
{
"code": null,
"e": 39879,
"s": 39844,
"text": "Find the element that appears once"
},
{
"code": null,
"e": 39909,
"s": 39879,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 39969,
"s": 39909,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 39984,
"s": 39969,
"text": "C++ Data Types"
},
{
"code": null,
"e": 40027,
"s": 39984,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
How to convert a DataFrame row into character vector in R? - GeeksforGeeks
|
21 Apr, 2021
If we want to turn a dataframe row into a character vector then we can use as.character() method In R, we can construct a character vector by enclosing the vector values in double quotation marks, but if we want to create a character vector from data frame row values, we can use the as character function.For example, if we have a data frame df then the values in the first row of the df can be turned into character vector using as.character(df[1,]).
Syntax: as.character(df[rownum, ])
Example 1: Here we are going to turn dataframe row into a character vector.
Here we will create a dataframe and then convert it to a vector.
R
# creating dataframedata <- data.frame(x1 = 1:5, x2 = letters[1:5], x3 = 6:10) # converting first row into character vectorfirst_row_vector = as.character(data[1, ]); print(first_row_vector)
Output:
[1] "1" "1" "6"
Example 2: Converting row-wise dataframe into the vector.
R
data <- data.frame(x1 = c("rahul", "vikas") , x2 = letters[1:2], x3 = c(1,2)) first_row_vector = as.character(data[2, ]); print("dataFrame")print(data) print("character vector of first row is" )print(first_row_vector)
Output:
Picked
R Vector-Programs
R-Vectors
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to Change Axis Scales in R Plots?
Replace Specific Characters in String in R
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
Convert Matrix to Dataframe in R
|
[
{
"code": null,
"e": 26597,
"s": 26569,
"text": "\n21 Apr, 2021"
},
{
"code": null,
"e": 27050,
"s": 26597,
"text": "If we want to turn a dataframe row into a character vector then we can use as.character() method In R, we can construct a character vector by enclosing the vector values in double quotation marks, but if we want to create a character vector from data frame row values, we can use the as character function.For example, if we have a data frame df then the values in the first row of the df can be turned into character vector using as.character(df[1,])."
},
{
"code": null,
"e": 27085,
"s": 27050,
"text": "Syntax: as.character(df[rownum, ])"
},
{
"code": null,
"e": 27161,
"s": 27085,
"text": "Example 1: Here we are going to turn dataframe row into a character vector."
},
{
"code": null,
"e": 27226,
"s": 27161,
"text": "Here we will create a dataframe and then convert it to a vector."
},
{
"code": null,
"e": 27228,
"s": 27226,
"text": "R"
},
{
"code": "# creating dataframedata <- data.frame(x1 = 1:5, x2 = letters[1:5], x3 = 6:10) # converting first row into character vectorfirst_row_vector = as.character(data[1, ]); print(first_row_vector)",
"e": 27469,
"s": 27228,
"text": null
},
{
"code": null,
"e": 27477,
"s": 27469,
"text": "Output:"
},
{
"code": null,
"e": 27493,
"s": 27477,
"text": "[1] \"1\" \"1\" \"6\""
},
{
"code": null,
"e": 27551,
"s": 27493,
"text": "Example 2: Converting row-wise dataframe into the vector."
},
{
"code": null,
"e": 27553,
"s": 27551,
"text": "R"
},
{
"code": "data <- data.frame(x1 = c(\"rahul\", \"vikas\") , x2 = letters[1:2], x3 = c(1,2)) first_row_vector = as.character(data[2, ]); print(\"dataFrame\")print(data) print(\"character vector of first row is\" )print(first_row_vector)",
"e": 27820,
"s": 27553,
"text": null
},
{
"code": null,
"e": 27828,
"s": 27820,
"text": "Output:"
},
{
"code": null,
"e": 27835,
"s": 27828,
"text": "Picked"
},
{
"code": null,
"e": 27853,
"s": 27835,
"text": "R Vector-Programs"
},
{
"code": null,
"e": 27863,
"s": 27853,
"text": "R-Vectors"
},
{
"code": null,
"e": 27874,
"s": 27863,
"text": "R Language"
},
{
"code": null,
"e": 27885,
"s": 27874,
"text": "R Programs"
},
{
"code": null,
"e": 27983,
"s": 27885,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28035,
"s": 27983,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 28070,
"s": 28035,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 28128,
"s": 28070,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 28166,
"s": 28128,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 28209,
"s": 28166,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 28267,
"s": 28209,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 28310,
"s": 28267,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 28359,
"s": 28310,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 28409,
"s": 28359,
"text": "How to filter R dataframe by multiple conditions?"
}
] |
Best Way to Add Bootstrap 4 to Project - GeeksforGeeks
|
10 Sep, 2021
New developer generally face problems while implementing or adding bootstrap to their projects. The problem mainly occurs to implement the bootstrap all over the project (that is on all the required files) without adding the stylesheet and script on every page of the project.
In this article, we have provided a simplified way to the same.
<!DOCTYPE html><html> <head> <style> .green { color: green; } .yellow { color: yellow; } .red { color: red; } .blue { color: blue; } .grey { color: grey; } </style></head> <body> <h1>Geeksforgeeks</h1> <p class="green">This text is in green color</p> <p class="yellow">This text is in yellow color</p> <p class="red">This text is in red color</p> <p class="blue">This text is in blue color</p> <p class="grey">This tag is in grey color</p> </body> </html>
Without using Bootstrap
Adding Bootstrap to our project: We can change the font color and styles using Bootstrap. The general way to do this is to add stylesheets and script in our head tab of the code as shown.
HTML
<!DOCTYPE html><html lang="en"> <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head> <body> <h1>GeeksforGeeks</h1> <p class="text-primary">This text is in blue color.</p> <p class="text-success">This text is in green color.</p> <p class="text-warning"> This text is in yellow color.</p> <p class="text-danger">This text is in red color.</p> <p class="text-secondary">This text is in grey color.</p></body> </html>
Bootstrap applied
You can note that the font of the same program is changed, not only font the spacing, placement size is also changed that means the Bootstrap 4 CDN has been applied.
Another way of adding Bootstrap to our project: In the above example, we saw that we need to add so many additional lines of code on every file of our project to apply bootstrap on that specific file. But this becomes exhausting when we have too many files to manage in our project.
Problem: If our project contains 30 files out of which we have to apply bootstrap on 18 files, then the above mentioned traditional method becomes too much load for the developer.
Solution: The same thing said above can be achieved just by writing one line of code in our file and setting the stylesheets and the scripts into some other file.
Explanation:
Step 1: Create a folder such as “components” in your ‘Web Pages’ folder of your project and also create a JSP file of your desired name such as “css-js.jsp” in components folder and clear all the prewritten code in the css-js.jsp file as shown.
All the prewritten code is removed
Step 2:
<!– For CSS –><link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css” integrity=”sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm” crossorigin=”anonymous”><link rel=”stylesheet” href=”https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css” integrity=”sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN” crossorigin=”anonymous”>
<!– For JavaScript –><script src=”https://code.jquery.com/jquery-3.5.1.min.js” integrity=”sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=” crossorigin=”anonymous”></script><script src=”https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js” integrity=”sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q” crossorigin=”anonymous”></script><script src=”https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js” integrity=”sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl” crossorigin=”anonymous”><>/script>
Copy the above quoted code into the “css-js.jsp” file. (The code provided are the stylesheets for the application of CSS and <script> tag for JavaScript )
Save the file
Stylesheets and script is copied to css-js file
Step 3: To apply the bootstrap on any page of your project you just need to include the “css-js.jsp” file in your head tag.
For example: <@include file=” components/css-js.jsp ”/>
HTML
<!DOCTYPE html><html> <head> <!-- This line will copy the entire code placed in the mentioned file(css-js.jsp) to here (file in which bootstrap has to be applied) --> <@include file="components/css-js.jsp" /></head> <body> <h1>GeeksforGeeks</h1> <p class="text-primary">This text is in blue color.</p> <p class="text-success">This text is in green color.</p> <p class="text-warning"> This text is in yellow color.</p> <p class="text-danger">This text is in red color.</p> <p class="text-secondary">This text is in grey color.</p></body> </html>
The “include” line will add the code written in the css-js.jsp file to the file in which it is written (You can understand this as – the whole code is given a name, and now we are using that name everywhere we require instead of putting the whole code.)
That is instead of writing the whole quoted code (stylesheets and scripts) in every file you need to just write one line of code( that is include the file where the stylesheet and script is kept “components/css-js.jsp” in this example).
Bootstrap applied
You can apply bootstrap on any file just by including the css-js.jsp file than to write the whole stylesheet on every page/file.
Additional Step 4: You need to follow this step only if you want to make your custom styles and write JavaScript code.
Step 4.1 Create two files with the Cascading Style Sheet (.css) and JavaScript File (.js) extension.
Step 4.2 Add these files in the “css-js.jsp” file using the below quoted text. This is also shown in the image below.
// Under CSS Section
<link rel="stylesheet" href ="style.css"/>
// Under JavaScript section
<script src="script.js"></script>
style.css and script.js is included in the css-js.jsp file.
Now, you can add your code in these files and have a play with them. To get the stylesheets and script to add in your file you can visit –
Bootstrap Documentation
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
Bootstrap-Questions
HTML-Questions
Bootstrap
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set Bootstrap Timepicker using datetimepicker library ?
How to Show Images on Click using HTML ?
How to Use Bootstrap with React?
How to keep gap between columns using Bootstrap?
Tailwind CSS vs Bootstrap
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
|
[
{
"code": null,
"e": 26973,
"s": 26945,
"text": "\n10 Sep, 2021"
},
{
"code": null,
"e": 27250,
"s": 26973,
"text": "New developer generally face problems while implementing or adding bootstrap to their projects. The problem mainly occurs to implement the bootstrap all over the project (that is on all the required files) without adding the stylesheet and script on every page of the project."
},
{
"code": null,
"e": 27314,
"s": 27250,
"text": "In this article, we have provided a simplified way to the same."
},
{
"code": "<!DOCTYPE html><html> <head> <style> .green { color: green; } .yellow { color: yellow; } .red { color: red; } .blue { color: blue; } .grey { color: grey; } </style></head> <body> <h1>Geeksforgeeks</h1> <p class=\"green\">This text is in green color</p> <p class=\"yellow\">This text is in yellow color</p> <p class=\"red\">This text is in red color</p> <p class=\"blue\">This text is in blue color</p> <p class=\"grey\">This tag is in grey color</p> </body> </html>",
"e": 27971,
"s": 27314,
"text": null
},
{
"code": null,
"e": 27995,
"s": 27971,
"text": "Without using Bootstrap"
},
{
"code": null,
"e": 28183,
"s": 27995,
"text": "Adding Bootstrap to our project: We can change the font color and styles using Bootstrap. The general way to do this is to add stylesheets and script in our head tab of the code as shown."
},
{
"code": null,
"e": 28188,
"s": 28183,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head> <body> <h1>GeeksforGeeks</h1> <p class=\"text-primary\">This text is in blue color.</p> <p class=\"text-success\">This text is in green color.</p> <p class=\"text-warning\"> This text is in yellow color.</p> <p class=\"text-danger\">This text is in red color.</p> <p class=\"text-secondary\">This text is in grey color.</p></body> </html>",
"e": 29002,
"s": 28188,
"text": null
},
{
"code": null,
"e": 29020,
"s": 29002,
"text": "Bootstrap applied"
},
{
"code": null,
"e": 29186,
"s": 29020,
"text": "You can note that the font of the same program is changed, not only font the spacing, placement size is also changed that means the Bootstrap 4 CDN has been applied."
},
{
"code": null,
"e": 29469,
"s": 29186,
"text": "Another way of adding Bootstrap to our project: In the above example, we saw that we need to add so many additional lines of code on every file of our project to apply bootstrap on that specific file. But this becomes exhausting when we have too many files to manage in our project."
},
{
"code": null,
"e": 29649,
"s": 29469,
"text": "Problem: If our project contains 30 files out of which we have to apply bootstrap on 18 files, then the above mentioned traditional method becomes too much load for the developer."
},
{
"code": null,
"e": 29812,
"s": 29649,
"text": "Solution: The same thing said above can be achieved just by writing one line of code in our file and setting the stylesheets and the scripts into some other file."
},
{
"code": null,
"e": 29825,
"s": 29812,
"text": "Explanation:"
},
{
"code": null,
"e": 30070,
"s": 29825,
"text": "Step 1: Create a folder such as “components” in your ‘Web Pages’ folder of your project and also create a JSP file of your desired name such as “css-js.jsp” in components folder and clear all the prewritten code in the css-js.jsp file as shown."
},
{
"code": null,
"e": 30105,
"s": 30070,
"text": "All the prewritten code is removed"
},
{
"code": null,
"e": 30113,
"s": 30105,
"text": "Step 2:"
},
{
"code": null,
"e": 30553,
"s": 30113,
"text": "<!– For CSS –><link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css” integrity=”sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm” crossorigin=”anonymous”><link rel=”stylesheet” href=”https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css” integrity=”sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN” crossorigin=”anonymous”>"
},
{
"code": null,
"e": 31135,
"s": 30553,
"text": "<!– For JavaScript –><script src=”https://code.jquery.com/jquery-3.5.1.min.js” integrity=”sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=” crossorigin=”anonymous”></script><script src=”https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js” integrity=”sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q” crossorigin=”anonymous”></script><script src=”https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js” integrity=”sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl” crossorigin=”anonymous”><>/script>"
},
{
"code": null,
"e": 31290,
"s": 31135,
"text": "Copy the above quoted code into the “css-js.jsp” file. (The code provided are the stylesheets for the application of CSS and <script> tag for JavaScript )"
},
{
"code": null,
"e": 31304,
"s": 31290,
"text": "Save the file"
},
{
"code": null,
"e": 31352,
"s": 31304,
"text": "Stylesheets and script is copied to css-js file"
},
{
"code": null,
"e": 31478,
"s": 31352,
"text": "Step 3: To apply the bootstrap on any page of your project you just need to include the “css-js.jsp” file in your head tag. "
},
{
"code": null,
"e": 31534,
"s": 31478,
"text": "For example: <@include file=” components/css-js.jsp ”/>"
},
{
"code": null,
"e": 31539,
"s": 31534,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <!-- This line will copy the entire code placed in the mentioned file(css-js.jsp) to here (file in which bootstrap has to be applied) --> <@include file=\"components/css-js.jsp\" /></head> <body> <h1>GeeksforGeeks</h1> <p class=\"text-primary\">This text is in blue color.</p> <p class=\"text-success\">This text is in green color.</p> <p class=\"text-warning\"> This text is in yellow color.</p> <p class=\"text-danger\">This text is in red color.</p> <p class=\"text-secondary\">This text is in grey color.</p></body> </html>",
"e": 32128,
"s": 31539,
"text": null
},
{
"code": null,
"e": 32382,
"s": 32128,
"text": "The “include” line will add the code written in the css-js.jsp file to the file in which it is written (You can understand this as – the whole code is given a name, and now we are using that name everywhere we require instead of putting the whole code.)"
},
{
"code": null,
"e": 32619,
"s": 32382,
"text": "That is instead of writing the whole quoted code (stylesheets and scripts) in every file you need to just write one line of code( that is include the file where the stylesheet and script is kept “components/css-js.jsp” in this example)."
},
{
"code": null,
"e": 32637,
"s": 32619,
"text": "Bootstrap applied"
},
{
"code": null,
"e": 32766,
"s": 32637,
"text": "You can apply bootstrap on any file just by including the css-js.jsp file than to write the whole stylesheet on every page/file."
},
{
"code": null,
"e": 32885,
"s": 32766,
"text": "Additional Step 4: You need to follow this step only if you want to make your custom styles and write JavaScript code."
},
{
"code": null,
"e": 32986,
"s": 32885,
"text": "Step 4.1 Create two files with the Cascading Style Sheet (.css) and JavaScript File (.js) extension."
},
{
"code": null,
"e": 33104,
"s": 32986,
"text": "Step 4.2 Add these files in the “css-js.jsp” file using the below quoted text. This is also shown in the image below."
},
{
"code": null,
"e": 33232,
"s": 33104,
"text": "// Under CSS Section \n<link rel=\"stylesheet\" href =\"style.css\"/>\n\n// Under JavaScript section\n<script src=\"script.js\"></script>"
},
{
"code": null,
"e": 33292,
"s": 33232,
"text": "style.css and script.js is included in the css-js.jsp file."
},
{
"code": null,
"e": 33431,
"s": 33292,
"text": "Now, you can add your code in these files and have a play with them. To get the stylesheets and script to add in your file you can visit –"
},
{
"code": null,
"e": 33455,
"s": 33431,
"text": "Bootstrap Documentation"
},
{
"code": null,
"e": 33592,
"s": 33455,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 33612,
"s": 33592,
"text": "Bootstrap-Questions"
},
{
"code": null,
"e": 33627,
"s": 33612,
"text": "HTML-Questions"
},
{
"code": null,
"e": 33637,
"s": 33627,
"text": "Bootstrap"
},
{
"code": null,
"e": 33642,
"s": 33637,
"text": "HTML"
},
{
"code": null,
"e": 33659,
"s": 33642,
"text": "Web Technologies"
},
{
"code": null,
"e": 33664,
"s": 33659,
"text": "HTML"
},
{
"code": null,
"e": 33762,
"s": 33664,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33825,
"s": 33762,
"text": "How to set Bootstrap Timepicker using datetimepicker library ?"
},
{
"code": null,
"e": 33866,
"s": 33825,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 33899,
"s": 33866,
"text": "How to Use Bootstrap with React?"
},
{
"code": null,
"e": 33948,
"s": 33899,
"text": "How to keep gap between columns using Bootstrap?"
},
{
"code": null,
"e": 33974,
"s": 33948,
"text": "Tailwind CSS vs Bootstrap"
},
{
"code": null,
"e": 34024,
"s": 33974,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 34086,
"s": 34024,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 34134,
"s": 34086,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 34194,
"s": 34134,
"text": "How to set the default value for an HTML <select> element ?"
}
] |
Program to convert a given number to words - GeeksforGeeks
|
23 Mar, 2022
Write code to convert a given number into words. For example, if “1234” is given as input, output should be “one thousand two hundred thirty four”.
Following is the implementation for the same. The code supports numbers up-to 4 digits, i.e., numbers from 0 to 9999. Idea is to create arrays that store individual parts of output strings. One array is used for single digits, one for numbers from 10 to 19, one for 20, 30, 40, 50, .. etc, and one for powers of 10. The given number is divided in two parts: first two digits and last two digits, and the two parts are printed separately.
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program for above approach#include <bits/stdc++.h>using namespace std; /* A function that prints given number in words */void convert_to_words(char* num){ int len = strlen( num); // Get number of digits in given number /* Base cases */ if (len == 0) { cout << "empty string" << endl; return; } if (len > 4) { cout <<"Length more than 4 is not supported\n" << endl; return; } /* The first string is not used, it is to make array indexing simple */ char* single_digits[] = { "zero", "one", "two ", "three ", "four", "five ", "six", "seven", "eight ", "nine " }; /* The first string is not used, it is to make array indexing simple */ char* two_digits[] = { "", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; /* The first two string are not used, they are to make array indexing simple*/ char* tens_multiple[] = { "", "", "twenty ", "thirty", "forty", "fifty", "sixty", "seventy", "eighty ", "ninety " }; char* tens_power[] = { "hundred ", "thousand " }; /* Used for debugging purpose only */ cout << endl; cout << num << ": "; /* For single digit number */ if (len == 1) { cout << single_digits[*num - '0'] << endl; return; } /* Iterate while num is not '\0' */ while (*num != '\0') { /* Code path for first 2 digits */ if (len >= 3) { if (*num - '0' != 0) { cout << single_digits[*num - '0']; cout << tens_power[len - 3]; // here len can // be 3 or 4 } --len; } /* Code path for last 2 digits */ else { /* Need to explicitly handle 10-19. Sum of the two digits is used as index of "two_digits" array of strings */ if (*num == '1') { int sum = *num - '0' + *(num + 1) - '0'; cout << two_digits[sum] << endl; return; } /* Need to explicitly handle 20 */ else if (*num == '2' && *(num + 1) == '0') { cout <<"twenty" << endl; return; } /* Rest of the two digit numbers i.e., 21 to 99 */ else { int i = *num - '0'; if (i > 0) cout << tens_multiple[i] << " "; else cout << ""; ++num; if (*num != '0') cout << single_digits[*num - '0']; } } ++num; }} // Driver Codeint main(){ convert_to_words("9923"); convert_to_words("523"); convert_to_words("89"); convert_to_words("8");} // This code is contributed by sanjoy_62.
/* C program to print a given number in words. The programhandles numbers from 0 to 9999 */#include <stdio.h>#include <stdlib.h>#include <string.h> /* A function that prints given number in words */void convert_to_words(char* num){ int len = strlen( num); // Get number of digits in given number /* Base cases */ if (len == 0) { fprintf(stderr, "empty string\n"); return; } if (len > 4) { fprintf(stderr, "Length more than 4 is not supported\n"); return; } /* The first string is not used, it is to make array indexing simple */ char* single_digits[] = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; /* The first string is not used, it is to make array indexing simple */ char* two_digits[] = { "", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; /* The first two string are not used, they are to make array indexing simple*/ char* tens_multiple[] = { "", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" }; char* tens_power[] = { "hundred", "thousand" }; /* Used for debugging purpose only */ printf("\n%s: ", num); /* For single digit number */ if (len == 1) { printf("%s\n", single_digits[*num - '0']); return; } /* Iterate while num is not '\0' */ while (*num != '\0') { /* Code path for first 2 digits */ if (len >= 3) { if (*num - '0' != 0) { printf("%s ", single_digits[*num - '0']); printf("%s ", tens_power[len - 3]); // here len can // be 3 or 4 } --len; } /* Code path for last 2 digits */ else { /* Need to explicitly handle 10-19. Sum of the two digits is used as index of "two_digits" array of strings */ if (*num == '1') { int sum = *num - '0' + *(num + 1) - '0'; printf("%s\n", two_digits[sum]); return; } /* Need to explicitly handle 20 */ else if (*num == '2' && *(num + 1) == '0') { printf("twenty\n"); return; } /* Rest of the two digit numbers i.e., 21 to 99 */ else { int i = *num - '0'; printf("%s ", i ? tens_multiple[i] : ""); ++num; if (*num != '0') printf("%s ", single_digits[*num - '0']); } } ++num; }} /* Driver program to test above function */int main(void){ convert_to_words("9923"); convert_to_words("523"); convert_to_words("89"); convert_to_words("8"); return 0;}
// Java program to print a given number in words. The// program handles numbers from 0 to 9999 class GFG { // A function that prints // given number in words static void convert_to_words(char[] num) { // Get number of digits // in given number int len = num.length; // Base cases if (len == 0) { System.out.println("empty string"); return; } if (len > 4) { System.out.println( "Length more than 4 is not supported"); return; } /* The first string is not used, it is to make array indexing simple */ String[] single_digits = new String[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; /* The first string is not used, it is to make array indexing simple */ String[] two_digits = new String[] { "", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; /* The first two string are not used, they are to * make array indexing simple*/ String[] tens_multiple = new String[] { "", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" }; String[] tens_power = new String[] { "hundred", "thousand" }; /* Used for debugging purpose only */ System.out.print(String.valueOf(num) + ": "); /* For single digit number */ if (len == 1) { System.out.println(single_digits[num[0] - '0']); return; } /* Iterate while num is not '\0' */ int x = 0; while (x < num.length) { /* Code path for first 2 digits */ if (len >= 3) { if (num[x] - '0' != 0) { System.out.print( single_digits[num[x] - '0'] + " "); System.out.print(tens_power[len - 3] + " "); // here len can be 3 or 4 } --len; } /* Code path for last 2 digits */ else { /* Need to explicitly handle 10-19. Sum of the two digits is used as index of "two_digits" array of strings */ if (num[x] - '0' == 1) { int sum = num[x] - '0' + num[x + 1] - '0'; System.out.println(two_digits[sum]); return; } /* Need to explicitly handle 20 */ else if (num[x] - '0' == 2 && num[x + 1] - '0' == 0) { System.out.println("twenty"); return; } /* Rest of the two digit numbers i.e., 21 to 99 */ else { int i = (num[x] - '0'); if (i > 0) System.out.print(tens_multiple[i] + " "); else System.out.print(""); ++x; if (num[x] - '0' != 0) System.out.println( single_digits[num[x] - '0']); } } ++x; } } // Driver Code public static void main(String[] args) { convert_to_words("9923".toCharArray()); convert_to_words("523".toCharArray()); convert_to_words("89".toCharArray()); convert_to_words("8".toCharArray()); }}// This code is contributed// by Mithun Kumar
# Python program to print a given number in# words. The program handles numbers# from 0 to 9999 # A function that prints# given number in words def convert_to_words(num): # Get number of digits # in given number l = len(num) # Base cases if (l == 0): print("empty string") return if (l > 4): print("Length more than 4 is not supported") return # The first string is not used, # it is to make array indexing simple single_digits = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"] # The first string is not used, # it is to make array indexing simple two_digits = ["", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"] # The first two string are not used, # they are to make array indexing simple tens_multiple = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] tens_power = ["hundred", "thousand"] # Used for debugging purpose only print(num, ":", end=" ") # For single digit number if (l == 1): print(single_digits[ord(num[0]) - 48]) return # Iterate while num is not '\0' x = 0 while (x < len(num)): # Code path for first 2 digits if (l >= 3): if (ord(num[x]) - 48 != 0): print(single_digits[ord(num[x]) - 48], end=" ") print(tens_power[l - 3], end=" ") # here len can be 3 or 4 l -= 1 # Code path for last 2 digits else: # Need to explicitly handle # 10-19. Sum of the two digits # is used as index of "two_digits" # array of strings if (ord(num[x]) - 48 == 1): sum = (ord(num[x]) - 48 + ord(num[x+1]) - 48) print(two_digits[sum]) return # Need to explicitly handle 20 elif (ord(num[x]) - 48 == 2 and ord(num[x + 1]) - 48 == 0): print("twenty") return # Rest of the two digit # numbers i.e., 21 to 99 else: i = ord(num[x]) - 48 if(i > 0): print(tens_multiple[i], end=" ") else: print("", end="") x += 1 if(ord(num[x]) - 48 != 0): print(single_digits[ord(num[x]) - 48]) x += 1 # Driver Codeconvert_to_words("9923") # Four Digitsconvert_to_words("523") # Three Digitsconvert_to_words("89") # Two Digitsconvert_to_words("8") # One Digits # This code is contributed# by Mithun Kumar
// C# program to print a given// number in words. The program// handles numbers from 0 to 9999using System; class GFG { // A function that prints // given number in words static void convert_to_words(char[] num) { // Get number of digits // in given number int len = num.Length; // Base cases if (len == 0) { Console.WriteLine("empty string"); return; } if (len > 4) { Console.WriteLine("Length more than " + "4 is not supported"); return; } /* The first string is not used, it is to make array indexing simple */ string[] single_digits = new string[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; /* The first string is not used, it is to make array indexing simple */ string[] two_digits = new string[] { "", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; /* The first two string are not used, they are to make array indexing simple*/ string[] tens_multiple = new string[] { "", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" }; string[] tens_power = new string[] { "hundred", "thousand" }; /* Used for debugging purpose only */ Console.Write((new string(num)) + ": "); /* For single digit number */ if (len == 1) { Console.WriteLine(single_digits[num[0] - '0']); return; } /* Iterate while num is not '\0' */ int x = 0; while (x < num.Length) { /* Code path for first 2 digits */ if (len >= 3) { if (num[x] - '0' != 0) { Console.Write( single_digits[num[x] - '0'] + " "); Console.Write(tens_power[len - 3] + " "); // here len can be 3 or 4 } --len; } /* Code path for last 2 digits */ else { /* Need to explicitly handle 10-19. Sum of the two digits is used as index of "two_digits" array of strings */ if (num[x] - '0' == 1) { int sum = num[x] - '0' + num[x + 1] - '0'; Console.WriteLine(two_digits[sum]); return; } /* Need to explicitly handle 20 */ else if (num[x] - '0' == 2 && num[x + 1] - '0' == 0) { Console.WriteLine("twenty"); return; } /* Rest of the two digit numbers i.e., 21 to 99 */ else { int i = (num[x] - '0'); if (i > 0) Console.Write(tens_multiple[i] + " "); else Console.Write(""); ++x; if (num[x] - '0' != 0) Console.WriteLine( single_digits[num[x] - '0']); } } ++x; } } // Driver Code public static void Main() { convert_to_words("9923".ToCharArray()); convert_to_words("523".ToCharArray()); convert_to_words("89".ToCharArray()); convert_to_words("8".ToCharArray()); }} // This code is contributed// by Mits
<?php// PHP program to print a given// number in words. The// program handles numbers// from 0 to 9999 // A function that prints// given number in wordsfunction convert_to_words($num){ // Get number of digits // in given number $len = strlen($num); // Base cases if ($len == 0) { echo "empty string\n"; return; } if ($len > 4) { echo "Length more than 4 " . "is not supported\n"; return; } /* The first string is not used, it is to make array indexing simple */ $single_digits = array("zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"); /* The first string is not used, it is to make array indexing simple */ $two_digits = array("", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"); /* The first two string are not used, they are to make array indexing simple*/ $tens_multiple = array("", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"); $tens_power = array("hundred", "thousand"); /* Used for debugging purpose only */ echo $num.": "; /* For single digit number */ if ($len == 1) { echo $single_digits[$num[0] - '0'] . " \n"; return; } /* Iterate while num is not '\0' */ $x = 0; while ($x < strlen($num)) { /* Code path for first 2 digits */ if ($len >= 3) { if ($num[$x]-'0' != 0) { echo $single_digits[$num[$x] - '0'] . " "; echo $tens_power[$len - 3] . " "; // here len can be 3 or 4 } --$len; } /* Code path for last 2 digits */ else { /* Need to explicitly handle 10-19. Sum of the two digits is used as index of "two_digits" array of strings */ if ($num[$x] - '0' == 1) { $sum = $num[$x] - '0' + $num[$x] - '0'; echo $two_digits[$sum] . " \n"; return; } /* Need to explicitly handle 20 */ else if ($num[$x] - '0' == 2 && $num[$x + 1] - '0' == 0) { echo "twenty\n"; return; } /* Rest of the two digit numbers i.e., 21 to 99 */ else { $i = $num[$x] - '0'; if($i > 0) echo $tens_multiple[$i] . " "; else echo ""; ++$x; if ($num[$x] - '0' != 0) echo $single_digits[$num[$x] - '0'] . " \n"; } } ++$x; }} // Driver Codeconvert_to_words("9923");convert_to_words("523");convert_to_words("89");convert_to_words("8"); // This code is contributed// by Mithun Kumar?>
<script> // JavaScript program to document.write a given number in// words. The program handles numbers// from 0 to 9999 // A function that document.writes// given number in wordsfunction convert_to_words(num){ // Get number of digits // in given number let l = num.length // Base cases if (l == 0){ document.write("empty string","</br>") return } if (l > 4){ document.write("Length more than 4 is not supported","</br>") return } // The first string is not used, // it is to make array indexing simple let single_digits = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"] // The first string is not used, // it is to make array indexing simple let two_digits = ["", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"] // The first two string are not used, // they are to make array indexing simple let tens_multiple = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] let tens_power = ["hundred", "thousand"] // Used for debugging purpose only document.write(num, ":"," ") // For single digit number if (l == 1){ document.write(single_digits[num.charCodeAt(0) - 48],"</br>") return } // Iterate while num is not '\0' let x = 0 while (x < num.length){ // Code path for first 2 digits if (l >= 3){ if (num.charCodeAt(x) - 48 != 0){ document.write(single_digits[num.charCodeAt(x) - 48]," ") document.write(tens_power[l - 3]," ") // here len can be 3 or 4 } l -= 1 } // Code path for last 2 digits else{ // Need to explicitly handle // 10-19. Sum of the two digits // is used as index of "two_digits" // array of strings if (num.charCodeAt(x) - 48 == 1){ sum = (num.charCodeAt(x) - 48 + num.charCodeAt(x+1) - 48) document.write(two_digits[sum],"</br>") return } // Need to explicitly handle 20 else if (num.charCodeAt(x) - 48 == 2 && num.charCodeAt(x + 1) - 48 == 0){ document.write("twenty","</br>") return } // Rest of the two digit // numbers i.e., 21 to 99 else{ i = num.charCodeAt(x) - 48 if(i > 0) document.write(tens_multiple[i], end=" ") else document.write("", end="") x += 1 if(num.charCodeAt(x) - 48 != 0) document.write(single_digits[num.charCodeAt(x) - 48],"</br>") } } x += 1 } } // Driver Codeconvert_to_words("9923") // Four Digitsconvert_to_words("523") // Three Digitsconvert_to_words("89") // Two Digitsconvert_to_words("8") // One Digits // This code is contributed by shinjanpatra </script>
Output:
9923: nine thousand nine hundred twenty three
523: five hundred twenty three
89: eighty nine
8989: eight thousand nine hundred eighty nine
This article is compiled by Narendra Kangralkar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Mithun Kumar
bjayashankar2102
saurabhsharma28
nknanthu13
yeddlapurishivasai
simranarora5sos
sanjoy_62
shinjanpatra
Amazon
Microsoft
Oracle
Zoho
Arrays
Mathematical
Zoho
Amazon
Microsoft
Oracle
Arrays
Mathematical
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
Program for Fibonacci numbers
C++ Data Types
Write a program to print all permutations of a given string
Set in C++ Standard Template Library (STL)
Program to find GCD or HCF of two numbers
|
[
{
"code": null,
"e": 24402,
"s": 24374,
"text": "\n23 Mar, 2022"
},
{
"code": null,
"e": 24550,
"s": 24402,
"text": "Write code to convert a given number into words. For example, if “1234” is given as input, output should be “one thousand two hundred thirty four”."
},
{
"code": null,
"e": 24989,
"s": 24550,
"text": "Following is the implementation for the same. The code supports numbers up-to 4 digits, i.e., numbers from 0 to 9999. Idea is to create arrays that store individual parts of output strings. One array is used for single digits, one for numbers from 10 to 19, one for 20, 30, 40, 50, .. etc, and one for powers of 10. The given number is divided in two parts: first two digits and last two digits, and the two parts are printed separately. "
},
{
"code": null,
"e": 24993,
"s": 24989,
"text": "C++"
},
{
"code": null,
"e": 24995,
"s": 24993,
"text": "C"
},
{
"code": null,
"e": 25000,
"s": 24995,
"text": "Java"
},
{
"code": null,
"e": 25008,
"s": 25000,
"text": "Python3"
},
{
"code": null,
"e": 25011,
"s": 25008,
"text": "C#"
},
{
"code": null,
"e": 25015,
"s": 25011,
"text": "PHP"
},
{
"code": null,
"e": 25026,
"s": 25015,
"text": "Javascript"
},
{
"code": "// C++ program for above approach#include <bits/stdc++.h>using namespace std; /* A function that prints given number in words */void convert_to_words(char* num){ int len = strlen( num); // Get number of digits in given number /* Base cases */ if (len == 0) { cout << \"empty string\" << endl; return; } if (len > 4) { cout <<\"Length more than 4 is not supported\\n\" << endl; return; } /* The first string is not used, it is to make array indexing simple */ char* single_digits[] = { \"zero\", \"one\", \"two \", \"three \", \"four\", \"five \", \"six\", \"seven\", \"eight \", \"nine \" }; /* The first string is not used, it is to make array indexing simple */ char* two_digits[] = { \"\", \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\" }; /* The first two string are not used, they are to make array indexing simple*/ char* tens_multiple[] = { \"\", \"\", \"twenty \", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty \", \"ninety \" }; char* tens_power[] = { \"hundred \", \"thousand \" }; /* Used for debugging purpose only */ cout << endl; cout << num << \": \"; /* For single digit number */ if (len == 1) { cout << single_digits[*num - '0'] << endl; return; } /* Iterate while num is not '\\0' */ while (*num != '\\0') { /* Code path for first 2 digits */ if (len >= 3) { if (*num - '0' != 0) { cout << single_digits[*num - '0']; cout << tens_power[len - 3]; // here len can // be 3 or 4 } --len; } /* Code path for last 2 digits */ else { /* Need to explicitly handle 10-19. Sum of the two digits is used as index of \"two_digits\" array of strings */ if (*num == '1') { int sum = *num - '0' + *(num + 1) - '0'; cout << two_digits[sum] << endl; return; } /* Need to explicitly handle 20 */ else if (*num == '2' && *(num + 1) == '0') { cout <<\"twenty\" << endl; return; } /* Rest of the two digit numbers i.e., 21 to 99 */ else { int i = *num - '0'; if (i > 0) cout << tens_multiple[i] << \" \"; else cout << \"\"; ++num; if (*num != '0') cout << single_digits[*num - '0']; } } ++num; }} // Driver Codeint main(){ convert_to_words(\"9923\"); convert_to_words(\"523\"); convert_to_words(\"89\"); convert_to_words(\"8\");} // This code is contributed by sanjoy_62.",
"e": 27658,
"s": 25026,
"text": null
},
{
"code": "/* C program to print a given number in words. The programhandles numbers from 0 to 9999 */#include <stdio.h>#include <stdlib.h>#include <string.h> /* A function that prints given number in words */void convert_to_words(char* num){ int len = strlen( num); // Get number of digits in given number /* Base cases */ if (len == 0) { fprintf(stderr, \"empty string\\n\"); return; } if (len > 4) { fprintf(stderr, \"Length more than 4 is not supported\\n\"); return; } /* The first string is not used, it is to make array indexing simple */ char* single_digits[] = { \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\" }; /* The first string is not used, it is to make array indexing simple */ char* two_digits[] = { \"\", \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\" }; /* The first two string are not used, they are to make array indexing simple*/ char* tens_multiple[] = { \"\", \"\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\" }; char* tens_power[] = { \"hundred\", \"thousand\" }; /* Used for debugging purpose only */ printf(\"\\n%s: \", num); /* For single digit number */ if (len == 1) { printf(\"%s\\n\", single_digits[*num - '0']); return; } /* Iterate while num is not '\\0' */ while (*num != '\\0') { /* Code path for first 2 digits */ if (len >= 3) { if (*num - '0' != 0) { printf(\"%s \", single_digits[*num - '0']); printf(\"%s \", tens_power[len - 3]); // here len can // be 3 or 4 } --len; } /* Code path for last 2 digits */ else { /* Need to explicitly handle 10-19. Sum of the two digits is used as index of \"two_digits\" array of strings */ if (*num == '1') { int sum = *num - '0' + *(num + 1) - '0'; printf(\"%s\\n\", two_digits[sum]); return; } /* Need to explicitly handle 20 */ else if (*num == '2' && *(num + 1) == '0') { printf(\"twenty\\n\"); return; } /* Rest of the two digit numbers i.e., 21 to 99 */ else { int i = *num - '0'; printf(\"%s \", i ? tens_multiple[i] : \"\"); ++num; if (*num != '0') printf(\"%s \", single_digits[*num - '0']); } } ++num; }} /* Driver program to test above function */int main(void){ convert_to_words(\"9923\"); convert_to_words(\"523\"); convert_to_words(\"89\"); convert_to_words(\"8\"); return 0;}",
"e": 30726,
"s": 27658,
"text": null
},
{
"code": "// Java program to print a given number in words. The// program handles numbers from 0 to 9999 class GFG { // A function that prints // given number in words static void convert_to_words(char[] num) { // Get number of digits // in given number int len = num.length; // Base cases if (len == 0) { System.out.println(\"empty string\"); return; } if (len > 4) { System.out.println( \"Length more than 4 is not supported\"); return; } /* The first string is not used, it is to make array indexing simple */ String[] single_digits = new String[] { \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\" }; /* The first string is not used, it is to make array indexing simple */ String[] two_digits = new String[] { \"\", \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\" }; /* The first two string are not used, they are to * make array indexing simple*/ String[] tens_multiple = new String[] { \"\", \"\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\" }; String[] tens_power = new String[] { \"hundred\", \"thousand\" }; /* Used for debugging purpose only */ System.out.print(String.valueOf(num) + \": \"); /* For single digit number */ if (len == 1) { System.out.println(single_digits[num[0] - '0']); return; } /* Iterate while num is not '\\0' */ int x = 0; while (x < num.length) { /* Code path for first 2 digits */ if (len >= 3) { if (num[x] - '0' != 0) { System.out.print( single_digits[num[x] - '0'] + \" \"); System.out.print(tens_power[len - 3] + \" \"); // here len can be 3 or 4 } --len; } /* Code path for last 2 digits */ else { /* Need to explicitly handle 10-19. Sum of the two digits is used as index of \"two_digits\" array of strings */ if (num[x] - '0' == 1) { int sum = num[x] - '0' + num[x + 1] - '0'; System.out.println(two_digits[sum]); return; } /* Need to explicitly handle 20 */ else if (num[x] - '0' == 2 && num[x + 1] - '0' == 0) { System.out.println(\"twenty\"); return; } /* Rest of the two digit numbers i.e., 21 to 99 */ else { int i = (num[x] - '0'); if (i > 0) System.out.print(tens_multiple[i] + \" \"); else System.out.print(\"\"); ++x; if (num[x] - '0' != 0) System.out.println( single_digits[num[x] - '0']); } } ++x; } } // Driver Code public static void main(String[] args) { convert_to_words(\"9923\".toCharArray()); convert_to_words(\"523\".toCharArray()); convert_to_words(\"89\".toCharArray()); convert_to_words(\"8\".toCharArray()); }}// This code is contributed// by Mithun Kumar",
"e": 34526,
"s": 30726,
"text": null
},
{
"code": "# Python program to print a given number in# words. The program handles numbers# from 0 to 9999 # A function that prints# given number in words def convert_to_words(num): # Get number of digits # in given number l = len(num) # Base cases if (l == 0): print(\"empty string\") return if (l > 4): print(\"Length more than 4 is not supported\") return # The first string is not used, # it is to make array indexing simple single_digits = [\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\"] # The first string is not used, # it is to make array indexing simple two_digits = [\"\", \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"] # The first two string are not used, # they are to make array indexing simple tens_multiple = [\"\", \"\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"] tens_power = [\"hundred\", \"thousand\"] # Used for debugging purpose only print(num, \":\", end=\" \") # For single digit number if (l == 1): print(single_digits[ord(num[0]) - 48]) return # Iterate while num is not '\\0' x = 0 while (x < len(num)): # Code path for first 2 digits if (l >= 3): if (ord(num[x]) - 48 != 0): print(single_digits[ord(num[x]) - 48], end=\" \") print(tens_power[l - 3], end=\" \") # here len can be 3 or 4 l -= 1 # Code path for last 2 digits else: # Need to explicitly handle # 10-19. Sum of the two digits # is used as index of \"two_digits\" # array of strings if (ord(num[x]) - 48 == 1): sum = (ord(num[x]) - 48 + ord(num[x+1]) - 48) print(two_digits[sum]) return # Need to explicitly handle 20 elif (ord(num[x]) - 48 == 2 and ord(num[x + 1]) - 48 == 0): print(\"twenty\") return # Rest of the two digit # numbers i.e., 21 to 99 else: i = ord(num[x]) - 48 if(i > 0): print(tens_multiple[i], end=\" \") else: print(\"\", end=\"\") x += 1 if(ord(num[x]) - 48 != 0): print(single_digits[ord(num[x]) - 48]) x += 1 # Driver Codeconvert_to_words(\"9923\") # Four Digitsconvert_to_words(\"523\") # Three Digitsconvert_to_words(\"89\") # Two Digitsconvert_to_words(\"8\") # One Digits # This code is contributed# by Mithun Kumar",
"e": 37376,
"s": 34526,
"text": null
},
{
"code": "// C# program to print a given// number in words. The program// handles numbers from 0 to 9999using System; class GFG { // A function that prints // given number in words static void convert_to_words(char[] num) { // Get number of digits // in given number int len = num.Length; // Base cases if (len == 0) { Console.WriteLine(\"empty string\"); return; } if (len > 4) { Console.WriteLine(\"Length more than \" + \"4 is not supported\"); return; } /* The first string is not used, it is to make array indexing simple */ string[] single_digits = new string[] { \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\" }; /* The first string is not used, it is to make array indexing simple */ string[] two_digits = new string[] { \"\", \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\" }; /* The first two string are not used, they are to make array indexing simple*/ string[] tens_multiple = new string[] { \"\", \"\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\" }; string[] tens_power = new string[] { \"hundred\", \"thousand\" }; /* Used for debugging purpose only */ Console.Write((new string(num)) + \": \"); /* For single digit number */ if (len == 1) { Console.WriteLine(single_digits[num[0] - '0']); return; } /* Iterate while num is not '\\0' */ int x = 0; while (x < num.Length) { /* Code path for first 2 digits */ if (len >= 3) { if (num[x] - '0' != 0) { Console.Write( single_digits[num[x] - '0'] + \" \"); Console.Write(tens_power[len - 3] + \" \"); // here len can be 3 or 4 } --len; } /* Code path for last 2 digits */ else { /* Need to explicitly handle 10-19. Sum of the two digits is used as index of \"two_digits\" array of strings */ if (num[x] - '0' == 1) { int sum = num[x] - '0' + num[x + 1] - '0'; Console.WriteLine(two_digits[sum]); return; } /* Need to explicitly handle 20 */ else if (num[x] - '0' == 2 && num[x + 1] - '0' == 0) { Console.WriteLine(\"twenty\"); return; } /* Rest of the two digit numbers i.e., 21 to 99 */ else { int i = (num[x] - '0'); if (i > 0) Console.Write(tens_multiple[i] + \" \"); else Console.Write(\"\"); ++x; if (num[x] - '0' != 0) Console.WriteLine( single_digits[num[x] - '0']); } } ++x; } } // Driver Code public static void Main() { convert_to_words(\"9923\".ToCharArray()); convert_to_words(\"523\".ToCharArray()); convert_to_words(\"89\".ToCharArray()); convert_to_words(\"8\".ToCharArray()); }} // This code is contributed// by Mits",
"e": 41134,
"s": 37376,
"text": null
},
{
"code": "<?php// PHP program to print a given// number in words. The// program handles numbers// from 0 to 9999 // A function that prints// given number in wordsfunction convert_to_words($num){ // Get number of digits // in given number $len = strlen($num); // Base cases if ($len == 0) { echo \"empty string\\n\"; return; } if ($len > 4) { echo \"Length more than 4 \" . \"is not supported\\n\"; return; } /* The first string is not used, it is to make array indexing simple */ $single_digits = array(\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\"); /* The first string is not used, it is to make array indexing simple */ $two_digits = array(\"\", \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"); /* The first two string are not used, they are to make array indexing simple*/ $tens_multiple = array(\"\", \"\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"); $tens_power = array(\"hundred\", \"thousand\"); /* Used for debugging purpose only */ echo $num.\": \"; /* For single digit number */ if ($len == 1) { echo $single_digits[$num[0] - '0'] . \" \\n\"; return; } /* Iterate while num is not '\\0' */ $x = 0; while ($x < strlen($num)) { /* Code path for first 2 digits */ if ($len >= 3) { if ($num[$x]-'0' != 0) { echo $single_digits[$num[$x] - '0'] . \" \"; echo $tens_power[$len - 3] . \" \"; // here len can be 3 or 4 } --$len; } /* Code path for last 2 digits */ else { /* Need to explicitly handle 10-19. Sum of the two digits is used as index of \"two_digits\" array of strings */ if ($num[$x] - '0' == 1) { $sum = $num[$x] - '0' + $num[$x] - '0'; echo $two_digits[$sum] . \" \\n\"; return; } /* Need to explicitly handle 20 */ else if ($num[$x] - '0' == 2 && $num[$x + 1] - '0' == 0) { echo \"twenty\\n\"; return; } /* Rest of the two digit numbers i.e., 21 to 99 */ else { $i = $num[$x] - '0'; if($i > 0) echo $tens_multiple[$i] . \" \"; else echo \"\"; ++$x; if ($num[$x] - '0' != 0) echo $single_digits[$num[$x] - '0'] . \" \\n\"; } } ++$x; }} // Driver Codeconvert_to_words(\"9923\");convert_to_words(\"523\");convert_to_words(\"89\");convert_to_words(\"8\"); // This code is contributed// by Mithun Kumar?>",
"e": 44333,
"s": 41134,
"text": null
},
{
"code": "<script> // JavaScript program to document.write a given number in// words. The program handles numbers// from 0 to 9999 // A function that document.writes// given number in wordsfunction convert_to_words(num){ // Get number of digits // in given number let l = num.length // Base cases if (l == 0){ document.write(\"empty string\",\"</br>\") return } if (l > 4){ document.write(\"Length more than 4 is not supported\",\"</br>\") return } // The first string is not used, // it is to make array indexing simple let single_digits = [\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\"] // The first string is not used, // it is to make array indexing simple let two_digits = [\"\", \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"] // The first two string are not used, // they are to make array indexing simple let tens_multiple = [\"\", \"\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"] let tens_power = [\"hundred\", \"thousand\"] // Used for debugging purpose only document.write(num, \":\",\" \") // For single digit number if (l == 1){ document.write(single_digits[num.charCodeAt(0) - 48],\"</br>\") return } // Iterate while num is not '\\0' let x = 0 while (x < num.length){ // Code path for first 2 digits if (l >= 3){ if (num.charCodeAt(x) - 48 != 0){ document.write(single_digits[num.charCodeAt(x) - 48],\" \") document.write(tens_power[l - 3],\" \") // here len can be 3 or 4 } l -= 1 } // Code path for last 2 digits else{ // Need to explicitly handle // 10-19. Sum of the two digits // is used as index of \"two_digits\" // array of strings if (num.charCodeAt(x) - 48 == 1){ sum = (num.charCodeAt(x) - 48 + num.charCodeAt(x+1) - 48) document.write(two_digits[sum],\"</br>\") return } // Need to explicitly handle 20 else if (num.charCodeAt(x) - 48 == 2 && num.charCodeAt(x + 1) - 48 == 0){ document.write(\"twenty\",\"</br>\") return } // Rest of the two digit // numbers i.e., 21 to 99 else{ i = num.charCodeAt(x) - 48 if(i > 0) document.write(tens_multiple[i], end=\" \") else document.write(\"\", end=\"\") x += 1 if(num.charCodeAt(x) - 48 != 0) document.write(single_digits[num.charCodeAt(x) - 48],\"</br>\") } } x += 1 } } // Driver Codeconvert_to_words(\"9923\") // Four Digitsconvert_to_words(\"523\") // Three Digitsconvert_to_words(\"89\") // Two Digitsconvert_to_words(\"8\") // One Digits // This code is contributed by shinjanpatra </script>",
"e": 47532,
"s": 44333,
"text": null
},
{
"code": null,
"e": 47540,
"s": 47532,
"text": "Output:"
},
{
"code": null,
"e": 47679,
"s": 47540,
"text": "9923: nine thousand nine hundred twenty three\n523: five hundred twenty three\n89: eighty nine\n8989: eight thousand nine hundred eighty nine"
},
{
"code": null,
"e": 47853,
"s": 47679,
"text": "This article is compiled by Narendra Kangralkar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 47866,
"s": 47853,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 47883,
"s": 47866,
"text": "bjayashankar2102"
},
{
"code": null,
"e": 47899,
"s": 47883,
"text": "saurabhsharma28"
},
{
"code": null,
"e": 47910,
"s": 47899,
"text": "nknanthu13"
},
{
"code": null,
"e": 47929,
"s": 47910,
"text": "yeddlapurishivasai"
},
{
"code": null,
"e": 47945,
"s": 47929,
"text": "simranarora5sos"
},
{
"code": null,
"e": 47955,
"s": 47945,
"text": "sanjoy_62"
},
{
"code": null,
"e": 47968,
"s": 47955,
"text": "shinjanpatra"
},
{
"code": null,
"e": 47975,
"s": 47968,
"text": "Amazon"
},
{
"code": null,
"e": 47985,
"s": 47975,
"text": "Microsoft"
},
{
"code": null,
"e": 47992,
"s": 47985,
"text": "Oracle"
},
{
"code": null,
"e": 47997,
"s": 47992,
"text": "Zoho"
},
{
"code": null,
"e": 48004,
"s": 47997,
"text": "Arrays"
},
{
"code": null,
"e": 48017,
"s": 48004,
"text": "Mathematical"
},
{
"code": null,
"e": 48022,
"s": 48017,
"text": "Zoho"
},
{
"code": null,
"e": 48029,
"s": 48022,
"text": "Amazon"
},
{
"code": null,
"e": 48039,
"s": 48029,
"text": "Microsoft"
},
{
"code": null,
"e": 48046,
"s": 48039,
"text": "Oracle"
},
{
"code": null,
"e": 48053,
"s": 48046,
"text": "Arrays"
},
{
"code": null,
"e": 48066,
"s": 48053,
"text": "Mathematical"
},
{
"code": null,
"e": 48164,
"s": 48066,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 48173,
"s": 48164,
"text": "Comments"
},
{
"code": null,
"e": 48186,
"s": 48173,
"text": "Old Comments"
},
{
"code": null,
"e": 48234,
"s": 48186,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 48278,
"s": 48234,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 48301,
"s": 48278,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 48333,
"s": 48301,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 48347,
"s": 48333,
"text": "Linear Search"
},
{
"code": null,
"e": 48377,
"s": 48347,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 48392,
"s": 48377,
"text": "C++ Data Types"
},
{
"code": null,
"e": 48452,
"s": 48392,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 48495,
"s": 48452,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Belief Propagation in Bayesian Networks | by Phillip Wenig | Towards Data Science
|
In this article, I’ll be using Belief Propagation (BP) with some example data. I presume that you already know about Bayesian Networks (BN). This post explains how to calculate beliefs of different variables in a BN which help reason.
I created a repository with the code for BP on GitHub which I’ll be using to explain the algorithm.
To start right off, imagine we have a poly-tree which is a graph without loops. For instance, a graph depicted in the following illustration. We have 4 variables “Rain”, “Sprinkler”, “Holmes” and “Watson” with directed edges “Rain” to “Holmes”, “Rain” to “Watson” and “Sprinkler” to “Holmes”. The Bayesian Network models the story of Holmes and Watson being neighbors. One morning Holmes goes outside his house and recognizes that the grass is wet. Either it rained or he forgot to turn off the sprinkler. So he goes to his neighbor Watson to see whether his grass is wet, too. As he sees that it is indeed wet he is quite sure that he didn’t forget the sprinkler but that it rained. So the information flowed from Watson to the sprinkler. This flow of information is modeled with BP in BNs.
In BP, we let the variables talk with each other to exchange their beliefs about each other. There are 2 kinds of messages: message from parents to children and messages from children to parents. In total, we only have to use 5 formulas to do BP. In my explanations, I will use different names for certain formulas and variables as I found some sources quite misleading.
Likelihood holds information about observations of children, e.g. the likelihood for Holmes’ grass without observing is 1 for wet and 1 for not wet. If wet grass is observed, the likelihood changes to 1 for wet and 0 for not wet. These unit vectors are not normalized.
The likelihood function is basically a product of all the incoming messages sent by a variable’s children. It returns a likelihood vector containing the likelihood values for each possible value of a variable. In case of “rain” it has a cardinality of two, for the two states “yes” and “no”.
If a variable does not have children as it is a leaf node in a graph and is not observed, its likelihood vector will be a unit vector, all ones for all its possible values, e.g. as we haven’t observed Holmes’ grass in the beginning we set its likelihood vector to [1, 1] for “not wet” and “wet”, respectively.
In Python (numpy) code it looks like that.
def likelihood(self): incoming_children_messages = np.array([ c.message_to_parent(self) for c in self.children ]) return incoming_children_messages.prod(axis=0)
Priors are the probabilities of certain events which are already known in the beginning, e.g. it rains with a probability of 20%. If the priors are unknown, the following formula is calculating it. It’s a bit more complicated but I’ll try. The prior is giving you the unconditional probability of the respective variable. Hence, we need to include the conditional one as well.
The conditional probabilities are also given in our example. In the formula, “P(X|W)” corresponds to that. Moreover, we need to use the incoming messages from all parents, which is the “φ” in the formula. The index is showing the message direction — from parent “K” to current variable “X”. These two parts (conditional probability and message from parents) are used as they both give information about the variables probability. On the one hand, we see the probability given some parents’ values, on the other hand we see the messages of those parents. Without observation, those messages correspond to the parents priors. Hence, here, are calculating the marginals of “X” and get rid of the conditional variables.
For each parent’s message there exists a corresponding part in the conditional probability. Hence, we can perform the dot product for each message with the conditional probabilities table, which is self.m in this snippet.
def priors(self): parents_messages = [ p.message_to_child(self) for p in self.parents ] return reduce(np.dot, [self.m.transpose()]+parents_messages)
The belief is the posterior probability after we observed certain events. It is basically the normalized product of likelihood and priors.
We take the probabilities we knew beforehand and introduce new knowledge received from the children. This way, we generate a new belief about our variable. If a variable has both, parents and children, the belief is the updated probability (posterior) incorporating information from below and above. So each incoming message is taken into account. The “α” is a normalizing constant, as the product of likelihood and prior can be in sum greater than 1. This is a shorthand form for a division with the sum of all possible states of the variables.
In this Python snippet the normalizing part gets clearer.
def belief(self): unnormalized = self.likelihood() * self.priors() normalized = unnormalized/unnormalized.sum() return normalized
In order to calculate the likelihood of a variable, we need to consider all incoming messages from a variable’s children, which are represented by the lambda in the likelihood function.
This formula is pretty messed up, but better to understand when looking at some Python code. In general we are marginalizing out K from P(X|U) whereas X is the sender (children), K is the receiver (parent) and U is all parents of X including K. If we imagine a conditional probability table for X, for each entry we take the corresponding activations of the parents and multiply the respective incoming messages φ without K itself. Then, we multiply that value with X’s likelihood. In the end we sum over all values with the same value for K and are left with a vector being the message from X to K.
So a message to a parent takes into account all incoming messages, no matter if they were sent by children or parents (except for the parent receiving the message), and considers the probabilities given certain parents’ values. Hence, a variable setting with high probability forwards incoming messages easier than low probabilities. An incoming message is rated by the conditional probability of that message’s setting.
I hope that the Python code clarifies it a bit further.
def message_to_parent(self, parent): likelihood = self.likelihood() parents_priors = np.array([ p.message_to_child(self) for p in self.parents if p != parent ]) parent_i = self.parents.index(parent) stack = np.vstack([ np.dot( self.m.take(r, axis=parent_i).transpose(), parents_priors.prod(axis=0) ) for r in range(parent.cardinality) ]) return np.dot(stack, likelihood)
or given the Holmes example:
message = np.zeros(rain.cardinality)for r in rain: for s in sprinkler: for h in holmes: message[r] = probas[r, s, h] \ * sprinkler_message[s] \ * likelihood[h]
To calculate the message by parents sent to their children two ways exist. Either all messages received from the other children multiplied with the current node’s prior are multiplied together or the current node’s belief is getting divided by the corresponding child’s message to the parent.
We consider this formula to be called Kappa with the index telling us the direction of the message (from X to K).
If we look at the formula for the belief, we see that this formula is the product of the likelihood and the prior. The likelihood, however, is the product of all incoming messages. Hence, the belief divided by the incoming message from K results in the product of all incoming messages — except for the one we divided by — and the prior. That way, we can explain the equality between the two ways calculating Kappa. The intuition behind the message to the children is similar to the message to a parent. You take into account all incoming messages (so consider all information you can get) and send the aggregation to the next node.
The alpha is again a normalizing constant. If a parent node has only one child, it cannot gather messages from other children as there are none. Hence, it will only return its prior.
def message_to_child(self, child): children_messages = [] for c in self.children: if c != child: children_messages.append(c.message_to_parent(self)) if len(children_messages) > 0: unnormalized = (children_messages * self.get_priors()) unnormalized = unnormalized.prod(axis=0) message = unnormalized/unnormalized.sum() return message return self.get_priors()
Using my repository which I mentioned in the beginning, we can now use the Holmes example and calculate the beliefs of different situations.
In order to use the library, we need to import it together with the NumPy library.
import numpy as npfrom node import Node
We imported the Node class of the repository which represents a single node in a BN. In the next step, we actually create nodes which represent the single probability variables: “Holmes’ grass is wet”, “Rained”, “Forgot sprinkler” and “Watson’s grass is wet”. When creating a node, you have to provide a name. Afterwards you need to set some properties like the cardinality and priors or likelihood if exists.
rain = Node("rain")rain.cardinality = 2rain.priors = np.array([0.8, 0.2]) # no=0 yes=1sprinkler = Node("sprinkler")sprinkler.cardinality = 2sprinkler.priors = np.array([0.9, 0.1]) # no=0 yes=1
For nodes without children, this is straight forward. For other nodes, which do have parents and no priors already available, we need to define a conditional probability table (CPT) which defines the probability of the variable given all possible inputs from the parents. This CPT is called “m” in the code.
m = np.zeros((2, 2, 2)) # rain, sprinkler, holmes' grassm[1, 1, 1] = 1m[0, 1, 1] = 0.9 # <-- herem[0, 1, 0] = 0.1m[1, 0, 1] = 1m[0, 0, 0] = 1holmes = Node("holmes")holmes.cardinality = 2holmes.m = mholmes.likelihood = np.array([1, 1])m = np.zeros((2, 2)) # rain, watson's grassm[1, 1] = 1m[0, 1] = 0.2m[0, 0] = 0.8watson = Node("watson")watson.cardinality = 2watson.m = mwatson.likelihood = np.array([1, 1])
As you can see, “m” takes the values of the parents in the first dimensions of the matrix and the value of the actual variable in the last, e.g. (“here” in code comment) the probability of the grass being wet (1) if it didn’t rain (0) and the sprinkler was forgotten (1) is 0.9. The likelihood of the grass being wet is 1, 1 which means that both states have the same likelihood.
Next, we have to connect the nodes to define the causalities. The Node class has a method called “add_parent” which can connect a variable to a parent variable.
holmes.add_parent(rain)holmes.add_parent(sprinkler)watson.add_parent(rain)
In the next steps, we are pretending Holmes’ grass is wet (hence, likelihood [0,1]). Then, we want to know whether Watson’s grass is also wet (or how likely it is to be wet).
holmes.likelihood = np.array([0, 1])holmes.message_to_parent(rain)holmes.message_to_parent(sprinkler)watson.get_belief() # array([0.21176471, 0.78823529])
We see that the belief of Watson’s grass being wet is indeed tending towards being wet (0.21 vs 0.79). Hence, the BN expects Watson’s grass to be wet as there is the connection over the rain node through which the belief was propagated.
The toolset of BNs can be really helpful in reasoning cases as the following. I am really excited about the whole research field of causal inference and think that a lot of progress will be made also regarding deep learning and general artificial intelligence.
Example taken from here.
|
[
{
"code": null,
"e": 407,
"s": 172,
"text": "In this article, I’ll be using Belief Propagation (BP) with some example data. I presume that you already know about Bayesian Networks (BN). This post explains how to calculate beliefs of different variables in a BN which help reason."
},
{
"code": null,
"e": 507,
"s": 407,
"text": "I created a repository with the code for BP on GitHub which I’ll be using to explain the algorithm."
},
{
"code": null,
"e": 1299,
"s": 507,
"text": "To start right off, imagine we have a poly-tree which is a graph without loops. For instance, a graph depicted in the following illustration. We have 4 variables “Rain”, “Sprinkler”, “Holmes” and “Watson” with directed edges “Rain” to “Holmes”, “Rain” to “Watson” and “Sprinkler” to “Holmes”. The Bayesian Network models the story of Holmes and Watson being neighbors. One morning Holmes goes outside his house and recognizes that the grass is wet. Either it rained or he forgot to turn off the sprinkler. So he goes to his neighbor Watson to see whether his grass is wet, too. As he sees that it is indeed wet he is quite sure that he didn’t forget the sprinkler but that it rained. So the information flowed from Watson to the sprinkler. This flow of information is modeled with BP in BNs."
},
{
"code": null,
"e": 1670,
"s": 1299,
"text": "In BP, we let the variables talk with each other to exchange their beliefs about each other. There are 2 kinds of messages: message from parents to children and messages from children to parents. In total, we only have to use 5 formulas to do BP. In my explanations, I will use different names for certain formulas and variables as I found some sources quite misleading."
},
{
"code": null,
"e": 1939,
"s": 1670,
"text": "Likelihood holds information about observations of children, e.g. the likelihood for Holmes’ grass without observing is 1 for wet and 1 for not wet. If wet grass is observed, the likelihood changes to 1 for wet and 0 for not wet. These unit vectors are not normalized."
},
{
"code": null,
"e": 2231,
"s": 1939,
"text": "The likelihood function is basically a product of all the incoming messages sent by a variable’s children. It returns a likelihood vector containing the likelihood values for each possible value of a variable. In case of “rain” it has a cardinality of two, for the two states “yes” and “no”."
},
{
"code": null,
"e": 2541,
"s": 2231,
"text": "If a variable does not have children as it is a leaf node in a graph and is not observed, its likelihood vector will be a unit vector, all ones for all its possible values, e.g. as we haven’t observed Holmes’ grass in the beginning we set its likelihood vector to [1, 1] for “not wet” and “wet”, respectively."
},
{
"code": null,
"e": 2584,
"s": 2541,
"text": "In Python (numpy) code it looks like that."
},
{
"code": null,
"e": 2761,
"s": 2584,
"text": "def likelihood(self): incoming_children_messages = np.array([ c.message_to_parent(self) for c in self.children ]) return incoming_children_messages.prod(axis=0)"
},
{
"code": null,
"e": 3138,
"s": 2761,
"text": "Priors are the probabilities of certain events which are already known in the beginning, e.g. it rains with a probability of 20%. If the priors are unknown, the following formula is calculating it. It’s a bit more complicated but I’ll try. The prior is giving you the unconditional probability of the respective variable. Hence, we need to include the conditional one as well."
},
{
"code": null,
"e": 3854,
"s": 3138,
"text": "The conditional probabilities are also given in our example. In the formula, “P(X|W)” corresponds to that. Moreover, we need to use the incoming messages from all parents, which is the “φ” in the formula. The index is showing the message direction — from parent “K” to current variable “X”. These two parts (conditional probability and message from parents) are used as they both give information about the variables probability. On the one hand, we see the probability given some parents’ values, on the other hand we see the messages of those parents. Without observation, those messages correspond to the parents priors. Hence, here, are calculating the marginals of “X” and get rid of the conditional variables."
},
{
"code": null,
"e": 4076,
"s": 3854,
"text": "For each parent’s message there exists a corresponding part in the conditional probability. Hence, we can perform the dot product for each message with the conditional probabilities table, which is self.m in this snippet."
},
{
"code": null,
"e": 4245,
"s": 4076,
"text": "def priors(self): parents_messages = [ p.message_to_child(self) for p in self.parents ] return reduce(np.dot, [self.m.transpose()]+parents_messages)"
},
{
"code": null,
"e": 4384,
"s": 4245,
"text": "The belief is the posterior probability after we observed certain events. It is basically the normalized product of likelihood and priors."
},
{
"code": null,
"e": 4930,
"s": 4384,
"text": "We take the probabilities we knew beforehand and introduce new knowledge received from the children. This way, we generate a new belief about our variable. If a variable has both, parents and children, the belief is the updated probability (posterior) incorporating information from below and above. So each incoming message is taken into account. The “α” is a normalizing constant, as the product of likelihood and prior can be in sum greater than 1. This is a shorthand form for a division with the sum of all possible states of the variables."
},
{
"code": null,
"e": 4988,
"s": 4930,
"text": "In this Python snippet the normalizing part gets clearer."
},
{
"code": null,
"e": 5130,
"s": 4988,
"text": "def belief(self): unnormalized = self.likelihood() * self.priors() normalized = unnormalized/unnormalized.sum() return normalized"
},
{
"code": null,
"e": 5316,
"s": 5130,
"text": "In order to calculate the likelihood of a variable, we need to consider all incoming messages from a variable’s children, which are represented by the lambda in the likelihood function."
},
{
"code": null,
"e": 5916,
"s": 5316,
"text": "This formula is pretty messed up, but better to understand when looking at some Python code. In general we are marginalizing out K from P(X|U) whereas X is the sender (children), K is the receiver (parent) and U is all parents of X including K. If we imagine a conditional probability table for X, for each entry we take the corresponding activations of the parents and multiply the respective incoming messages φ without K itself. Then, we multiply that value with X’s likelihood. In the end we sum over all values with the same value for K and are left with a vector being the message from X to K."
},
{
"code": null,
"e": 6337,
"s": 5916,
"text": "So a message to a parent takes into account all incoming messages, no matter if they were sent by children or parents (except for the parent receiving the message), and considers the probabilities given certain parents’ values. Hence, a variable setting with high probability forwards incoming messages easier than low probabilities. An incoming message is rated by the conditional probability of that message’s setting."
},
{
"code": null,
"e": 6393,
"s": 6337,
"text": "I hope that the Python code clarifies it a bit further."
},
{
"code": null,
"e": 6852,
"s": 6393,
"text": "def message_to_parent(self, parent): likelihood = self.likelihood() parents_priors = np.array([ p.message_to_child(self) for p in self.parents if p != parent ]) parent_i = self.parents.index(parent) stack = np.vstack([ np.dot( self.m.take(r, axis=parent_i).transpose(), parents_priors.prod(axis=0) ) for r in range(parent.cardinality) ]) return np.dot(stack, likelihood)"
},
{
"code": null,
"e": 6881,
"s": 6852,
"text": "or given the Holmes example:"
},
{
"code": null,
"e": 7086,
"s": 6881,
"text": "message = np.zeros(rain.cardinality)for r in rain: for s in sprinkler: for h in holmes: message[r] = probas[r, s, h] \\ * sprinkler_message[s] \\ * likelihood[h]"
},
{
"code": null,
"e": 7379,
"s": 7086,
"text": "To calculate the message by parents sent to their children two ways exist. Either all messages received from the other children multiplied with the current node’s prior are multiplied together or the current node’s belief is getting divided by the corresponding child’s message to the parent."
},
{
"code": null,
"e": 7493,
"s": 7379,
"text": "We consider this formula to be called Kappa with the index telling us the direction of the message (from X to K)."
},
{
"code": null,
"e": 8126,
"s": 7493,
"text": "If we look at the formula for the belief, we see that this formula is the product of the likelihood and the prior. The likelihood, however, is the product of all incoming messages. Hence, the belief divided by the incoming message from K results in the product of all incoming messages — except for the one we divided by — and the prior. That way, we can explain the equality between the two ways calculating Kappa. The intuition behind the message to the children is similar to the message to a parent. You take into account all incoming messages (so consider all information you can get) and send the aggregation to the next node."
},
{
"code": null,
"e": 8309,
"s": 8126,
"text": "The alpha is again a normalizing constant. If a parent node has only one child, it cannot gather messages from other children as there are none. Hence, it will only return its prior."
},
{
"code": null,
"e": 8725,
"s": 8309,
"text": "def message_to_child(self, child): children_messages = [] for c in self.children: if c != child: children_messages.append(c.message_to_parent(self)) if len(children_messages) > 0: unnormalized = (children_messages * self.get_priors()) unnormalized = unnormalized.prod(axis=0) message = unnormalized/unnormalized.sum() return message return self.get_priors()"
},
{
"code": null,
"e": 8866,
"s": 8725,
"text": "Using my repository which I mentioned in the beginning, we can now use the Holmes example and calculate the beliefs of different situations."
},
{
"code": null,
"e": 8949,
"s": 8866,
"text": "In order to use the library, we need to import it together with the NumPy library."
},
{
"code": null,
"e": 8989,
"s": 8949,
"text": "import numpy as npfrom node import Node"
},
{
"code": null,
"e": 9399,
"s": 8989,
"text": "We imported the Node class of the repository which represents a single node in a BN. In the next step, we actually create nodes which represent the single probability variables: “Holmes’ grass is wet”, “Rained”, “Forgot sprinkler” and “Watson’s grass is wet”. When creating a node, you have to provide a name. Afterwards you need to set some properties like the cardinality and priors or likelihood if exists."
},
{
"code": null,
"e": 9594,
"s": 9399,
"text": "rain = Node(\"rain\")rain.cardinality = 2rain.priors = np.array([0.8, 0.2]) # no=0 yes=1sprinkler = Node(\"sprinkler\")sprinkler.cardinality = 2sprinkler.priors = np.array([0.9, 0.1]) # no=0 yes=1"
},
{
"code": null,
"e": 9902,
"s": 9594,
"text": "For nodes without children, this is straight forward. For other nodes, which do have parents and no priors already available, we need to define a conditional probability table (CPT) which defines the probability of the variable given all possible inputs from the parents. This CPT is called “m” in the code."
},
{
"code": null,
"e": 10312,
"s": 9902,
"text": "m = np.zeros((2, 2, 2)) # rain, sprinkler, holmes' grassm[1, 1, 1] = 1m[0, 1, 1] = 0.9 # <-- herem[0, 1, 0] = 0.1m[1, 0, 1] = 1m[0, 0, 0] = 1holmes = Node(\"holmes\")holmes.cardinality = 2holmes.m = mholmes.likelihood = np.array([1, 1])m = np.zeros((2, 2)) # rain, watson's grassm[1, 1] = 1m[0, 1] = 0.2m[0, 0] = 0.8watson = Node(\"watson\")watson.cardinality = 2watson.m = mwatson.likelihood = np.array([1, 1])"
},
{
"code": null,
"e": 10692,
"s": 10312,
"text": "As you can see, “m” takes the values of the parents in the first dimensions of the matrix and the value of the actual variable in the last, e.g. (“here” in code comment) the probability of the grass being wet (1) if it didn’t rain (0) and the sprinkler was forgotten (1) is 0.9. The likelihood of the grass being wet is 1, 1 which means that both states have the same likelihood."
},
{
"code": null,
"e": 10853,
"s": 10692,
"text": "Next, we have to connect the nodes to define the causalities. The Node class has a method called “add_parent” which can connect a variable to a parent variable."
},
{
"code": null,
"e": 10928,
"s": 10853,
"text": "holmes.add_parent(rain)holmes.add_parent(sprinkler)watson.add_parent(rain)"
},
{
"code": null,
"e": 11103,
"s": 10928,
"text": "In the next steps, we are pretending Holmes’ grass is wet (hence, likelihood [0,1]). Then, we want to know whether Watson’s grass is also wet (or how likely it is to be wet)."
},
{
"code": null,
"e": 11259,
"s": 11103,
"text": "holmes.likelihood = np.array([0, 1])holmes.message_to_parent(rain)holmes.message_to_parent(sprinkler)watson.get_belief() # array([0.21176471, 0.78823529])"
},
{
"code": null,
"e": 11496,
"s": 11259,
"text": "We see that the belief of Watson’s grass being wet is indeed tending towards being wet (0.21 vs 0.79). Hence, the BN expects Watson’s grass to be wet as there is the connection over the rain node through which the belief was propagated."
},
{
"code": null,
"e": 11757,
"s": 11496,
"text": "The toolset of BNs can be really helpful in reasoning cases as the following. I am really excited about the whole research field of causal inference and think that a lot of progress will be made also regarding deep learning and general artificial intelligence."
}
] |
Javascript Program To Check Whether The Length Of Given Linked List Is Even Or Odd - GeeksforGeeks
|
10 Jan, 2022
Given a linked list, the task is to make a function which checks whether the length of the linked list is even or odd.Examples:
Input : 1->2->3->4->NULL
Output : Even
Input : 1->2->3->4->5->NULL
Output : Odd
Method 1: Count the codes linearly Traverse the entire Linked List and keep counting the number of nodes. As soon as the loop is finished, we can check if the count is even or odd. You may try it yourself.Method 2: Stepping 2 nodes at a time Approach:
1. Take a pointer and move that pointer two nodes at a time
2. At the end, if the pointer is NULL then length is Even, else Odd.
Javascript
<script>// JavaScript program to check length // of a given linklist // Defining structureclass Node { constructor() { this.data = 0; this.next = null; }} // Function to check the length of // linklistfunction LinkedListLength(head) { while (head != null && head.next != null) { head = head.next.next; } if (head == null) return 0; return 1;} // Push functionfunction push(head, info) { // Allocating node node = new Node(); // Info into node node.data = info; // Next of new node to head node.next = (head); // head points to new node (head) = node;} // Driver codehead = null; // Adding elements to Linked Listpush(head, 4);push(head, 5);push(head, 7);push(head, 2);push(head, 9);push(head, 6);push(head, 1);push(head, 2);push(head, 0);push(head, 5);push(head, 5);var check = LinkedListLength(head); // Checking for length of linklistif (check == 0) { document.write("Odd");} else{ document.write("Even");}// This code is contributed by umadevi9616</script>
Output:
Odd
Time Complexity: O(n) Space Complexity: O(1)
Please refer complete article on Check whether the length of given linked list is Even or Odd for more details!
Linked List
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Circular Singly Linked List | Insertion
Given a linked list which is sorted, how will you insert in sorted way
Swap nodes in a linked list without swapping data
Delete a node in a Doubly Linked List
Circular Linked List | Set 2 (Traversal)
Insert a node at a specific position in a linked list
Program to implement Singly Linked List in C++ using class
Priority Queue using Linked List
Insertion Sort for Singly Linked List
Real-time application of Data Structures
|
[
{
"code": null,
"e": 24934,
"s": 24906,
"text": "\n10 Jan, 2022"
},
{
"code": null,
"e": 25062,
"s": 24934,
"text": "Given a linked list, the task is to make a function which checks whether the length of the linked list is even or odd.Examples:"
},
{
"code": null,
"e": 25143,
"s": 25062,
"text": "Input : 1->2->3->4->NULL\nOutput : Even\n\nInput : 1->2->3->4->5->NULL\nOutput : Odd"
},
{
"code": null,
"e": 25395,
"s": 25143,
"text": "Method 1: Count the codes linearly Traverse the entire Linked List and keep counting the number of nodes. As soon as the loop is finished, we can check if the count is even or odd. You may try it yourself.Method 2: Stepping 2 nodes at a time Approach:"
},
{
"code": null,
"e": 25524,
"s": 25395,
"text": "1. Take a pointer and move that pointer two nodes at a time\n2. At the end, if the pointer is NULL then length is Even, else Odd."
},
{
"code": null,
"e": 25535,
"s": 25524,
"text": "Javascript"
},
{
"code": "<script>// JavaScript program to check length // of a given linklist // Defining structureclass Node { constructor() { this.data = 0; this.next = null; }} // Function to check the length of // linklistfunction LinkedListLength(head) { while (head != null && head.next != null) { head = head.next.next; } if (head == null) return 0; return 1;} // Push functionfunction push(head, info) { // Allocating node node = new Node(); // Info into node node.data = info; // Next of new node to head node.next = (head); // head points to new node (head) = node;} // Driver codehead = null; // Adding elements to Linked Listpush(head, 4);push(head, 5);push(head, 7);push(head, 2);push(head, 9);push(head, 6);push(head, 1);push(head, 2);push(head, 0);push(head, 5);push(head, 5);var check = LinkedListLength(head); // Checking for length of linklistif (check == 0) { document.write(\"Odd\");} else{ document.write(\"Even\");}// This code is contributed by umadevi9616</script>",
"e": 26601,
"s": 25535,
"text": null
},
{
"code": null,
"e": 26611,
"s": 26601,
"text": "Output: "
},
{
"code": null,
"e": 26615,
"s": 26611,
"text": "Odd"
},
{
"code": null,
"e": 26660,
"s": 26615,
"text": "Time Complexity: O(n) Space Complexity: O(1)"
},
{
"code": null,
"e": 26772,
"s": 26660,
"text": "Please refer complete article on Check whether the length of given linked list is Even or Odd for more details!"
},
{
"code": null,
"e": 26784,
"s": 26772,
"text": "Linked List"
},
{
"code": null,
"e": 26796,
"s": 26784,
"text": "Linked List"
},
{
"code": null,
"e": 26894,
"s": 26796,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26934,
"s": 26894,
"text": "Circular Singly Linked List | Insertion"
},
{
"code": null,
"e": 27005,
"s": 26934,
"text": "Given a linked list which is sorted, how will you insert in sorted way"
},
{
"code": null,
"e": 27055,
"s": 27005,
"text": "Swap nodes in a linked list without swapping data"
},
{
"code": null,
"e": 27093,
"s": 27055,
"text": "Delete a node in a Doubly Linked List"
},
{
"code": null,
"e": 27134,
"s": 27093,
"text": "Circular Linked List | Set 2 (Traversal)"
},
{
"code": null,
"e": 27188,
"s": 27134,
"text": "Insert a node at a specific position in a linked list"
},
{
"code": null,
"e": 27247,
"s": 27188,
"text": "Program to implement Singly Linked List in C++ using class"
},
{
"code": null,
"e": 27280,
"s": 27247,
"text": "Priority Queue using Linked List"
},
{
"code": null,
"e": 27318,
"s": 27280,
"text": "Insertion Sort for Singly Linked List"
}
] |
Maximum number of mangoes that can be bought - GeeksforGeeks
|
30 Jun, 2021
Given two integers W and C, representing the number of watermelons and coins, the task is to find the maximum number of mangoes that can be bought given that each mango costs 1 watermelon and X coins and y coins can be earned selling a watermelon.
Examples:
Input: W = 10, C = 10, X = 1, Y = 1Output: 10Explanation: The most optimal way is to use 10 watermelons and 10 coins to buy 10 mangoes. Hence, the maximum number of mangoes that can be bought is 10.
Input: W = 4, C = 8, X = 4, Y = 4Output: 3Explanation: The most optimal way is to sell one watermelon. Then, the number of coins increases by 4. Therefore, the total number of coins becomes 12. Therefore, 3 watermelons and 12 coins can be used to buy 3 mangoes. Hence, the maximum number of mangoes that can be bought is 3.
Approach: This problem can be solved using binary search. The idea is to find the maximum number of mangoes in the search space. Follow the steps below to solve the problem:
Initialize a variable ans as 0 to store the required result.
Initialize two variables l as 0, r as W to store the boundary regions of the search space for binary search.
Loop while l≤r and perform the following steps:Store the middle value in a variable mid as (l+r)/2.Check if mid number of mangoes can be bought using the given value of W, C, x, and y.If true, then update ans to mid and search in the right part of mid by updating l to mid+1. Otherwise, update the value of r to mid-1.
Store the middle value in a variable mid as (l+r)/2.
Check if mid number of mangoes can be bought using the given value of W, C, x, and y.
If true, then update ans to mid and search in the right part of mid by updating l to mid+1. Otherwise, update the value of r to mid-1.
Print the value of ans as the result.
Below is the implementation of the above approach:
C++14
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to check if mid number// of mangoes can be boughtbool check(int n, int m, int x, int y, int vl){ // Store the coins int temp = m; // If watermelons needed are greater // than given watermelons if (vl > n) return false; // Store remaining watermelons if vl // watermelons are used to buy mangoes int ex = n - vl; // Store the value of coins if these // watermelon get sold ex *= y; // Increment coins by ex temp += ex; // Number of mangoes that can be buyed // if only x coins needed for one mango int cr = temp / x; // If the condition is satisfied, // return true if (cr >= vl) return true; // Otherwise return false return false;} // Function to find the maximum number of mangoes// that can be bought by selling watermelonsint maximizeMangoes(int n, int m, int x, int y){ // Initialize the boundary values int l = 0, r = n; // Store the required result int ans = 0; // Binary Search while (l <= r) { // Store the mid value int mid = l + (r - l) / 2; // Check if it is possible to // buy mid number of mangoes if (check(n, m, x, y, mid)) { ans = mid; l = mid + 1; } // Otherwise, update r to mid -1 else r = mid - 1; } // Return the result return ans;} // Driver Codeint main(){ // Given Input int W = 4, C = 8, x = 4, y = 4; // Function Call cout << maximizeMangoes(W, C, x, y); return 0;}
// Java program for the above approachclass GFG{ // Function to check if mid number// of mangoes can be boughtstatic boolean check(int n, int m, int x, int y, int vl){ // Store the coins int temp = m; // If watermelons needed are greater // than given watermelons if (vl > n) return false; // Store remaining watermelons if vl // watermelons are used to buy mangoes int ex = n - vl; // Store the value of coins if these // watermelon get sold ex *= y; // Increment coins by ex temp += ex; // Number of mangoes that can be buyed // if only x coins needed for one mango int cr = temp / x; // If the condition is satisfied, // return true if (cr >= vl) return true; // Otherwise return false return false;} // Function to find the maximum number// of mangoes that can be bought by// selling watermelonsstatic int maximizeMangoes(int n, int m, int x, int y){ // Initialize the boundary values int l = 0, r = n; // Store the required result int ans = 0; // Binary Search while (l <= r) { // Store the mid value int mid = l + (r - l) / 2; // Check if it is possible to // buy mid number of mangoes if (check(n, m, x, y, mid)) { ans = mid; l = mid + 1; } // Otherwise, update r to mid -1 else r = mid - 1; } // Return the result return ans;} // Driver codepublic static void main(String[] args){ // Given Input int W = 4, C = 8, x = 4, y = 4; // Function Call System.out.println(maximizeMangoes(W, C, x, y));}} // This code is contributed by abhinavjain194
# Python3 program for the above approach # Function to check if mid number# of mangoes can be boughtdef check(n, m, x, y, vl): # Store the coins temp = m # If watermelons needed are greater # than given watermelons if (vl > n): return False # Store remaining watermelons if vl # watermelons are used to buy mangoes ex = n - vl # Store the value of coins if these # watermelon get sold ex *= y # Increment coins by ex temp += ex # Number of mangoes that can be buyed # if only x coins needed for one mango cr = temp // x # If the condition is satisfied, # return true if (cr >= vl): return True # Otherwise return false return False # Function to find the maximum number of mangoes# that can be bought by selling watermelonsdef maximizeMangoes(n, m, x, y): # Initialize the boundary values l = 0 r = n # Store the required result ans = 0 # Binary Search while (l <= r): # Store the mid value mid = l + (r - l) // 2 # Check if it is possible to # buy mid number of mangoes if (check(n, m, x, y, mid)): ans = mid l = mid + 1 # Otherwise, update r to mid -1 else: r = mid - 1 # Return the result return ans # Driver Codeif __name__ == '__main__': # Given Input W = 4 C = 8 x = 4 y = 4 # Function Call print(maximizeMangoes(W, C, x, y)) # This code is contributed by bgangwar59
// C# program for the above approachusing System; class GFG{ // Function to check if mid number// of mangoes can be boughtstatic bool check(int n, int m, int x, int y, int vl){ // Store the coins int temp = m; // If watermelons needed are greater // than given watermelons if (vl > n) return false; // Store remaining watermelons if vl // watermelons are used to buy mangoes int ex = n - vl; // Store the value of coins if these // watermelon get sold ex *= y; // Increment coins by ex temp += ex; // Number of mangoes that can be buyed // if only x coins needed for one mango int cr = temp / x; // If the condition is satisfied, // return true if (cr >= vl) return true; // Otherwise return false return false;} // Function to find the maximum number of mangoes// that can be bought by selling watermelonsstatic int maximizeMangoes(int n, int m, int x, int y){ // Initialize the boundary values int l = 0, r = n; // Store the required result int ans = 0; // Binary Search while (l <= r) { // Store the mid value int mid = l + (r - l) / 2; // Check if it is possible to // buy mid number of mangoes if (check(n, m, x, y, mid)) { ans = mid; l = mid + 1; } // Otherwise, update r to mid -1 else r = mid - 1; } // Return the result return ans;} // Driver Codepublic static void Main(){ // Given Input int W = 4, C = 8, x = 4, y = 4; // Function Call Console.Write(maximizeMangoes(W, C, x, y));}} // This code is contributed by ukasp
<script>// Javascript program for the above approach // Function to check if mid number// of mangoes can be boughtfunction check(n, m, x, y,vl){ // Store the coins var temp = m; // If watermelons needed are greater // than given watermelons if (vl > n) return false; // Store remaining watermelons if vl // watermelons are used to buy mangoes var ex = n - vl; // Store the value of coins if these // watermelon get sold ex *= y; // Increment coins by ex temp += ex; // Number of mangoes that can be buyed // if only x coins needed for one mango var cr = parseInt(temp / x); // If the condition is satisfied, // return true if (cr >= vl) return true; // Otherwise return false return false;} // Function to find the maximum number of mangoes// that can be bought by selling watermelonsfunction maximizeMangoes(n, m, x, y){ // Initialize the boundary values var l = 0, r = n; // Store the required result var ans = 0; // Binary Search while (l <= r) { // Store the mid value var mid = l + parseInt((r - l) / 2); // Check if it is possible to // buy mid number of mangoes if (check(n, m, x, y, mid)) { ans = mid; l = mid + 1; } // Otherwise, update r to mid -1 else r = mid - 1; } // Return the result return ans;}var W = 4, C = 8, x = 4, y = 4; // Function Calldocument.write( maximizeMangoes(W, C, x, y)); //This code is contributed by SoumikMondal</script>
3
Time Complexity: O(log(W))Auxiliary Space: O(1)
ukasp
abhinavjain194
bgangwar59
SoumikMondal
Binary Search
Divide and Conquer
Mathematical
Searching
Searching
Mathematical
Divide and Conquer
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Binary Search In JavaScript
K-th Element of Two Sorted Arrays
Find a Fixed Point (Value equal to index) in a given array
Binary Search (bisect) in Python
Convex Hull using Divide and Conquer Algorithm
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
|
[
{
"code": null,
"e": 24914,
"s": 24886,
"text": "\n30 Jun, 2021"
},
{
"code": null,
"e": 25162,
"s": 24914,
"text": "Given two integers W and C, representing the number of watermelons and coins, the task is to find the maximum number of mangoes that can be bought given that each mango costs 1 watermelon and X coins and y coins can be earned selling a watermelon."
},
{
"code": null,
"e": 25172,
"s": 25162,
"text": "Examples:"
},
{
"code": null,
"e": 25371,
"s": 25172,
"text": "Input: W = 10, C = 10, X = 1, Y = 1Output: 10Explanation: The most optimal way is to use 10 watermelons and 10 coins to buy 10 mangoes. Hence, the maximum number of mangoes that can be bought is 10."
},
{
"code": null,
"e": 25695,
"s": 25371,
"text": "Input: W = 4, C = 8, X = 4, Y = 4Output: 3Explanation: The most optimal way is to sell one watermelon. Then, the number of coins increases by 4. Therefore, the total number of coins becomes 12. Therefore, 3 watermelons and 12 coins can be used to buy 3 mangoes. Hence, the maximum number of mangoes that can be bought is 3."
},
{
"code": null,
"e": 25869,
"s": 25695,
"text": "Approach: This problem can be solved using binary search. The idea is to find the maximum number of mangoes in the search space. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 25930,
"s": 25869,
"text": "Initialize a variable ans as 0 to store the required result."
},
{
"code": null,
"e": 26039,
"s": 25930,
"text": "Initialize two variables l as 0, r as W to store the boundary regions of the search space for binary search."
},
{
"code": null,
"e": 26358,
"s": 26039,
"text": "Loop while l≤r and perform the following steps:Store the middle value in a variable mid as (l+r)/2.Check if mid number of mangoes can be bought using the given value of W, C, x, and y.If true, then update ans to mid and search in the right part of mid by updating l to mid+1. Otherwise, update the value of r to mid-1."
},
{
"code": null,
"e": 26411,
"s": 26358,
"text": "Store the middle value in a variable mid as (l+r)/2."
},
{
"code": null,
"e": 26497,
"s": 26411,
"text": "Check if mid number of mangoes can be bought using the given value of W, C, x, and y."
},
{
"code": null,
"e": 26632,
"s": 26497,
"text": "If true, then update ans to mid and search in the right part of mid by updating l to mid+1. Otherwise, update the value of r to mid-1."
},
{
"code": null,
"e": 26670,
"s": 26632,
"text": "Print the value of ans as the result."
},
{
"code": null,
"e": 26721,
"s": 26670,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26727,
"s": 26721,
"text": "C++14"
},
{
"code": null,
"e": 26732,
"s": 26727,
"text": "Java"
},
{
"code": null,
"e": 26740,
"s": 26732,
"text": "Python3"
},
{
"code": null,
"e": 26743,
"s": 26740,
"text": "C#"
},
{
"code": null,
"e": 26754,
"s": 26743,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to check if mid number// of mangoes can be boughtbool check(int n, int m, int x, int y, int vl){ // Store the coins int temp = m; // If watermelons needed are greater // than given watermelons if (vl > n) return false; // Store remaining watermelons if vl // watermelons are used to buy mangoes int ex = n - vl; // Store the value of coins if these // watermelon get sold ex *= y; // Increment coins by ex temp += ex; // Number of mangoes that can be buyed // if only x coins needed for one mango int cr = temp / x; // If the condition is satisfied, // return true if (cr >= vl) return true; // Otherwise return false return false;} // Function to find the maximum number of mangoes// that can be bought by selling watermelonsint maximizeMangoes(int n, int m, int x, int y){ // Initialize the boundary values int l = 0, r = n; // Store the required result int ans = 0; // Binary Search while (l <= r) { // Store the mid value int mid = l + (r - l) / 2; // Check if it is possible to // buy mid number of mangoes if (check(n, m, x, y, mid)) { ans = mid; l = mid + 1; } // Otherwise, update r to mid -1 else r = mid - 1; } // Return the result return ans;} // Driver Codeint main(){ // Given Input int W = 4, C = 8, x = 4, y = 4; // Function Call cout << maximizeMangoes(W, C, x, y); return 0;}",
"e": 28364,
"s": 26754,
"text": null
},
{
"code": "// Java program for the above approachclass GFG{ // Function to check if mid number// of mangoes can be boughtstatic boolean check(int n, int m, int x, int y, int vl){ // Store the coins int temp = m; // If watermelons needed are greater // than given watermelons if (vl > n) return false; // Store remaining watermelons if vl // watermelons are used to buy mangoes int ex = n - vl; // Store the value of coins if these // watermelon get sold ex *= y; // Increment coins by ex temp += ex; // Number of mangoes that can be buyed // if only x coins needed for one mango int cr = temp / x; // If the condition is satisfied, // return true if (cr >= vl) return true; // Otherwise return false return false;} // Function to find the maximum number// of mangoes that can be bought by// selling watermelonsstatic int maximizeMangoes(int n, int m, int x, int y){ // Initialize the boundary values int l = 0, r = n; // Store the required result int ans = 0; // Binary Search while (l <= r) { // Store the mid value int mid = l + (r - l) / 2; // Check if it is possible to // buy mid number of mangoes if (check(n, m, x, y, mid)) { ans = mid; l = mid + 1; } // Otherwise, update r to mid -1 else r = mid - 1; } // Return the result return ans;} // Driver codepublic static void main(String[] args){ // Given Input int W = 4, C = 8, x = 4, y = 4; // Function Call System.out.println(maximizeMangoes(W, C, x, y));}} // This code is contributed by abhinavjain194",
"e": 30112,
"s": 28364,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to check if mid number# of mangoes can be boughtdef check(n, m, x, y, vl): # Store the coins temp = m # If watermelons needed are greater # than given watermelons if (vl > n): return False # Store remaining watermelons if vl # watermelons are used to buy mangoes ex = n - vl # Store the value of coins if these # watermelon get sold ex *= y # Increment coins by ex temp += ex # Number of mangoes that can be buyed # if only x coins needed for one mango cr = temp // x # If the condition is satisfied, # return true if (cr >= vl): return True # Otherwise return false return False # Function to find the maximum number of mangoes# that can be bought by selling watermelonsdef maximizeMangoes(n, m, x, y): # Initialize the boundary values l = 0 r = n # Store the required result ans = 0 # Binary Search while (l <= r): # Store the mid value mid = l + (r - l) // 2 # Check if it is possible to # buy mid number of mangoes if (check(n, m, x, y, mid)): ans = mid l = mid + 1 # Otherwise, update r to mid -1 else: r = mid - 1 # Return the result return ans # Driver Codeif __name__ == '__main__': # Given Input W = 4 C = 8 x = 4 y = 4 # Function Call print(maximizeMangoes(W, C, x, y)) # This code is contributed by bgangwar59",
"e": 31625,
"s": 30112,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ // Function to check if mid number// of mangoes can be boughtstatic bool check(int n, int m, int x, int y, int vl){ // Store the coins int temp = m; // If watermelons needed are greater // than given watermelons if (vl > n) return false; // Store remaining watermelons if vl // watermelons are used to buy mangoes int ex = n - vl; // Store the value of coins if these // watermelon get sold ex *= y; // Increment coins by ex temp += ex; // Number of mangoes that can be buyed // if only x coins needed for one mango int cr = temp / x; // If the condition is satisfied, // return true if (cr >= vl) return true; // Otherwise return false return false;} // Function to find the maximum number of mangoes// that can be bought by selling watermelonsstatic int maximizeMangoes(int n, int m, int x, int y){ // Initialize the boundary values int l = 0, r = n; // Store the required result int ans = 0; // Binary Search while (l <= r) { // Store the mid value int mid = l + (r - l) / 2; // Check if it is possible to // buy mid number of mangoes if (check(n, m, x, y, mid)) { ans = mid; l = mid + 1; } // Otherwise, update r to mid -1 else r = mid - 1; } // Return the result return ans;} // Driver Codepublic static void Main(){ // Given Input int W = 4, C = 8, x = 4, y = 4; // Function Call Console.Write(maximizeMangoes(W, C, x, y));}} // This code is contributed by ukasp",
"e": 33339,
"s": 31625,
"text": null
},
{
"code": "<script>// Javascript program for the above approach // Function to check if mid number// of mangoes can be boughtfunction check(n, m, x, y,vl){ // Store the coins var temp = m; // If watermelons needed are greater // than given watermelons if (vl > n) return false; // Store remaining watermelons if vl // watermelons are used to buy mangoes var ex = n - vl; // Store the value of coins if these // watermelon get sold ex *= y; // Increment coins by ex temp += ex; // Number of mangoes that can be buyed // if only x coins needed for one mango var cr = parseInt(temp / x); // If the condition is satisfied, // return true if (cr >= vl) return true; // Otherwise return false return false;} // Function to find the maximum number of mangoes// that can be bought by selling watermelonsfunction maximizeMangoes(n, m, x, y){ // Initialize the boundary values var l = 0, r = n; // Store the required result var ans = 0; // Binary Search while (l <= r) { // Store the mid value var mid = l + parseInt((r - l) / 2); // Check if it is possible to // buy mid number of mangoes if (check(n, m, x, y, mid)) { ans = mid; l = mid + 1; } // Otherwise, update r to mid -1 else r = mid - 1; } // Return the result return ans;}var W = 4, C = 8, x = 4, y = 4; // Function Calldocument.write( maximizeMangoes(W, C, x, y)); //This code is contributed by SoumikMondal</script>",
"e": 34903,
"s": 33339,
"text": null
},
{
"code": null,
"e": 34905,
"s": 34903,
"text": "3"
},
{
"code": null,
"e": 34955,
"s": 34907,
"text": "Time Complexity: O(log(W))Auxiliary Space: O(1)"
},
{
"code": null,
"e": 34963,
"s": 34957,
"text": "ukasp"
},
{
"code": null,
"e": 34978,
"s": 34963,
"text": "abhinavjain194"
},
{
"code": null,
"e": 34989,
"s": 34978,
"text": "bgangwar59"
},
{
"code": null,
"e": 35002,
"s": 34989,
"text": "SoumikMondal"
},
{
"code": null,
"e": 35016,
"s": 35002,
"text": "Binary Search"
},
{
"code": null,
"e": 35035,
"s": 35016,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 35048,
"s": 35035,
"text": "Mathematical"
},
{
"code": null,
"e": 35058,
"s": 35048,
"text": "Searching"
},
{
"code": null,
"e": 35068,
"s": 35058,
"text": "Searching"
},
{
"code": null,
"e": 35081,
"s": 35068,
"text": "Mathematical"
},
{
"code": null,
"e": 35100,
"s": 35081,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 35114,
"s": 35100,
"text": "Binary Search"
},
{
"code": null,
"e": 35212,
"s": 35114,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35221,
"s": 35212,
"text": "Comments"
},
{
"code": null,
"e": 35234,
"s": 35221,
"text": "Old Comments"
},
{
"code": null,
"e": 35262,
"s": 35234,
"text": "Binary Search In JavaScript"
},
{
"code": null,
"e": 35296,
"s": 35262,
"text": "K-th Element of Two Sorted Arrays"
},
{
"code": null,
"e": 35355,
"s": 35296,
"text": "Find a Fixed Point (Value equal to index) in a given array"
},
{
"code": null,
"e": 35388,
"s": 35355,
"text": "Binary Search (bisect) in Python"
},
{
"code": null,
"e": 35435,
"s": 35388,
"text": "Convex Hull using Divide and Conquer Algorithm"
},
{
"code": null,
"e": 35465,
"s": 35435,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 35525,
"s": 35465,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 35540,
"s": 35525,
"text": "C++ Data Types"
},
{
"code": null,
"e": 35583,
"s": 35540,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Output of C programs | Set 55 - GeeksforGeeks
|
06 Sep, 2017
1. What will be the output of the following program?
#include <stdio.h>int main(){ int a = 03489; printf("%d", a); return (0);}
Options:1. 18652. runtime error3. Syntax error4. 0
The answer is option(3).
Explanation:
Any integral value prefix with 0 acts as octal number but the allowed digits is 0 to 7. But here 8 and 9 is there, which result in syntax error.
2. What will be the output of the following program?
#include <stdio.h>int main(){ char c; int i; c = 'B'; i = c - 'A'; printf("%d", i); return (0);}
Options:1. 52. 13. incompatible type declaration4. -5
The answer is option(2).
Explanation : Here i declared as integer. So, it will manipulate the ASCII values.Since the ASCII value of B is 66 and ASCII value of A is 65. Therefore i = c-‘A’ = 1.
3. What will be the output of the following program?
#include <stdio.h>int main(){ printf("GEEKS"); main(); return (0);}
Options:1. GEEKS2. run-time error3. GEEKS infinitely4. compile time error
The answer is option(3).
Explanation:Because main() function is calling itself repeatedly.
4. what will be the output of the following program?
#include <stdio.h>int main(){ int n, i = 5; n = - - i--; printf("%d%d", n, i); return (0);}
Options:1. 542. 443. 454. 55
The answer is option(1).
Explanation:Here minus*minus acts as plus before the i in the statement n=- -i–.Reference: https://www.geeksforgeeks.org/unary-operators-cc/
5. what will be the output of the following program?
#include <stdio.h>int main(){ int a = 10; printf("%d", a++ * a++); return (0);}
Options:1. 1002. 1103. 1054. No output
The answer is option(2).
Explanation:Here a++ is post increment. so when it gets a++ then for the value of a changed to 11 in a buffer but still a=10. when it gets called one more time, a will be 11. so it will be 11*10=110.
6. what will be the output of the following program?
#include <stdio.h>int main(){ int a = 20, b = 8, c; c = a != 5 || b == 4; printf("c=%d", c); return (0);}
Options:1. c=02. No output3. compile time4. c=1
The answer is option(4).
Explanation:In the above program logical OR operator takes place.Here a!=5 is true which return 1 and rest of the code will not going to be execute because in logical OR if the first condition is true then the rest code will be not execute.
This article is contributed by Bishal Kumar Dubey. 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.
C-Output
Misc
Misc
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Advantages and Disadvantages of OOP
Challenges in Internet of things (IoT)
Consensus Algorithms in Blockchain
Election algorithm and distributed processing
Transmission Impairment in Data Communication
Lex Program to count number of words
Bubble Sort algorithm using JavaScript
How to insert elements in C++ STL List ?
Characteristics of Internet of Things
Properties of Fourier Transform
|
[
{
"code": null,
"e": 24672,
"s": 24644,
"text": "\n06 Sep, 2017"
},
{
"code": null,
"e": 24725,
"s": 24672,
"text": "1. What will be the output of the following program?"
},
{
"code": "#include <stdio.h>int main(){ int a = 03489; printf(\"%d\", a); return (0);}",
"e": 24809,
"s": 24725,
"text": null
},
{
"code": null,
"e": 24860,
"s": 24809,
"text": "Options:1. 18652. runtime error3. Syntax error4. 0"
},
{
"code": null,
"e": 24899,
"s": 24860,
"text": " The answer is option(3).\nExplanation:"
},
{
"code": null,
"e": 25044,
"s": 24899,
"text": "Any integral value prefix with 0 acts as octal number but the allowed digits is 0 to 7. But here 8 and 9 is there, which result in syntax error."
},
{
"code": null,
"e": 25097,
"s": 25044,
"text": "2. What will be the output of the following program?"
},
{
"code": "#include <stdio.h>int main(){ char c; int i; c = 'B'; i = c - 'A'; printf(\"%d\", i); return (0);}",
"e": 25212,
"s": 25097,
"text": null
},
{
"code": null,
"e": 25266,
"s": 25212,
"text": "Options:1. 52. 13. incompatible type declaration4. -5"
},
{
"code": null,
"e": 25291,
"s": 25266,
"text": "The answer is option(2)."
},
{
"code": null,
"e": 25459,
"s": 25291,
"text": "Explanation : Here i declared as integer. So, it will manipulate the ASCII values.Since the ASCII value of B is 66 and ASCII value of A is 65. Therefore i = c-‘A’ = 1."
},
{
"code": null,
"e": 25512,
"s": 25459,
"text": "3. What will be the output of the following program?"
},
{
"code": "#include <stdio.h>int main(){ printf(\"GEEKS\"); main(); return (0);}",
"e": 25589,
"s": 25512,
"text": null
},
{
"code": null,
"e": 25663,
"s": 25589,
"text": "Options:1. GEEKS2. run-time error3. GEEKS infinitely4. compile time error"
},
{
"code": null,
"e": 25689,
"s": 25663,
"text": " The answer is option(3)."
},
{
"code": null,
"e": 25755,
"s": 25689,
"text": "Explanation:Because main() function is calling itself repeatedly."
},
{
"code": null,
"e": 25808,
"s": 25755,
"text": "4. what will be the output of the following program?"
},
{
"code": "#include <stdio.h>int main(){ int n, i = 5; n = - - i--; printf(\"%d%d\", n, i); return (0);}",
"e": 25912,
"s": 25808,
"text": null
},
{
"code": null,
"e": 25941,
"s": 25912,
"text": "Options:1. 542. 443. 454. 55"
},
{
"code": null,
"e": 25967,
"s": 25941,
"text": " The answer is option(1)."
},
{
"code": null,
"e": 26108,
"s": 25967,
"text": "Explanation:Here minus*minus acts as plus before the i in the statement n=- -i–.Reference: https://www.geeksforgeeks.org/unary-operators-cc/"
},
{
"code": null,
"e": 26161,
"s": 26108,
"text": "5. what will be the output of the following program?"
},
{
"code": "#include <stdio.h>int main(){ int a = 10; printf(\"%d\", a++ * a++); return (0);}",
"e": 26250,
"s": 26161,
"text": null
},
{
"code": null,
"e": 26289,
"s": 26250,
"text": "Options:1. 1002. 1103. 1054. No output"
},
{
"code": null,
"e": 26315,
"s": 26289,
"text": " The answer is option(2)."
},
{
"code": null,
"e": 26515,
"s": 26315,
"text": "Explanation:Here a++ is post increment. so when it gets a++ then for the value of a changed to 11 in a buffer but still a=10. when it gets called one more time, a will be 11. so it will be 11*10=110."
},
{
"code": null,
"e": 26568,
"s": 26515,
"text": "6. what will be the output of the following program?"
},
{
"code": "#include <stdio.h>int main(){ int a = 20, b = 8, c; c = a != 5 || b == 4; printf(\"c=%d\", c); return (0);}",
"e": 26686,
"s": 26568,
"text": null
},
{
"code": null,
"e": 26734,
"s": 26686,
"text": "Options:1. c=02. No output3. compile time4. c=1"
},
{
"code": null,
"e": 26760,
"s": 26734,
"text": " The answer is option(4)."
},
{
"code": null,
"e": 27001,
"s": 26760,
"text": "Explanation:In the above program logical OR operator takes place.Here a!=5 is true which return 1 and rest of the code will not going to be execute because in logical OR if the first condition is true then the rest code will be not execute."
},
{
"code": null,
"e": 27307,
"s": 27001,
"text": "This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 27432,
"s": 27307,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 27441,
"s": 27432,
"text": "C-Output"
},
{
"code": null,
"e": 27446,
"s": 27441,
"text": "Misc"
},
{
"code": null,
"e": 27451,
"s": 27446,
"text": "Misc"
},
{
"code": null,
"e": 27456,
"s": 27451,
"text": "Misc"
},
{
"code": null,
"e": 27554,
"s": 27456,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27563,
"s": 27554,
"text": "Comments"
},
{
"code": null,
"e": 27576,
"s": 27563,
"text": "Old Comments"
},
{
"code": null,
"e": 27612,
"s": 27576,
"text": "Advantages and Disadvantages of OOP"
},
{
"code": null,
"e": 27651,
"s": 27612,
"text": "Challenges in Internet of things (IoT)"
},
{
"code": null,
"e": 27686,
"s": 27651,
"text": "Consensus Algorithms in Blockchain"
},
{
"code": null,
"e": 27732,
"s": 27686,
"text": "Election algorithm and distributed processing"
},
{
"code": null,
"e": 27778,
"s": 27732,
"text": "Transmission Impairment in Data Communication"
},
{
"code": null,
"e": 27815,
"s": 27778,
"text": "Lex Program to count number of words"
},
{
"code": null,
"e": 27854,
"s": 27815,
"text": "Bubble Sort algorithm using JavaScript"
},
{
"code": null,
"e": 27895,
"s": 27854,
"text": "How to insert elements in C++ STL List ?"
},
{
"code": null,
"e": 27933,
"s": 27895,
"text": "Characteristics of Internet of Things"
}
] |
Koa.js - Hello World
|
Once we have set up the development, it is time to start developing our first app using Koa. Create a new file called app.js and type the following in it.
var koa = require('koa');
var app = new koa();
app.use(function* (){
this.body = 'Hello world!';
});
app.listen(3000, function(){
console.log('Server running on https://localhost:3000')
});
Save the file, go to your terminal and type.
$ nodemon app.js
This will start the server. To test this app, open your browser and go to https://localhost:3000 and you should receive the following message.
The first line imports Koa in our file. We have access to its API through the variable Koa. We use it to create an application and assign it to var app.
app.use(function) − This function is a middleware, which gets called whenever our server gets a request. We'll learn more about middleware in the subsequent chapters. The callback function is a generator, which we'll see in the next chapter. The context of this generator is called context in Koa. This context is used to access and modify the request and response objects. We are setting the body of this response to be Hello world!.
app.listen(port, function) − This function binds and listens for connections on the specified port. Port is the only required parameter here. The callback function is executed, if the app runs successfully.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2261,
"s": 2106,
"text": "Once we have set up the development, it is time to start developing our first app using Koa. Create a new file called app.js and type the following in it."
},
{
"code": null,
"e": 2459,
"s": 2261,
"text": "var koa = require('koa');\nvar app = new koa();\n\napp.use(function* (){\n this.body = 'Hello world!';\n});\n\napp.listen(3000, function(){\n console.log('Server running on https://localhost:3000')\n});"
},
{
"code": null,
"e": 2504,
"s": 2459,
"text": "Save the file, go to your terminal and type."
},
{
"code": null,
"e": 2522,
"s": 2504,
"text": "$ nodemon app.js\n"
},
{
"code": null,
"e": 2665,
"s": 2522,
"text": "This will start the server. To test this app, open your browser and go to https://localhost:3000 and you should receive the following message."
},
{
"code": null,
"e": 2818,
"s": 2665,
"text": "The first line imports Koa in our file. We have access to its API through the variable Koa. We use it to create an application and assign it to var app."
},
{
"code": null,
"e": 3253,
"s": 2818,
"text": "app.use(function) − This function is a middleware, which gets called whenever our server gets a request. We'll learn more about middleware in the subsequent chapters. The callback function is a generator, which we'll see in the next chapter. The context of this generator is called context in Koa. This context is used to access and modify the request and response objects. We are setting the body of this response to be Hello world!."
},
{
"code": null,
"e": 3460,
"s": 3253,
"text": "app.listen(port, function) − This function binds and listens for connections on the specified port. Port is the only required parameter here. The callback function is executed, if the app runs successfully."
},
{
"code": null,
"e": 3467,
"s": 3460,
"text": " Print"
},
{
"code": null,
"e": 3478,
"s": 3467,
"text": " Add Notes"
}
] |
How To enable GZIP Compression in PHP?
|
GZIP Compression is a simple, effective way to save bandwidth and speed up PHP application. The mechanism runs behind the GZIP compression is described below −
The browser/client request for a file to the server.
The server sends a .zip file to the browser (index.html.zip) rather than plain old index.html in response, due to which the download time and bandwidth decreases.
After the execution of the above step, the browser downloads the zipped file, extracts it, and then shows it to the user. This loads the webpage very quickly.
In the Apache server, we have to Add the following to .htaccess file to enable GZIP compression.
# compress text, html, javascript, css, xml:
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xmlin
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
# Or, compress certain file types by extension:
<files *.html>
SetOutputFilter DEFLATE
</files>
In PHP files we can enable GZIP compression.
<?php
if (substr_count($_SERVER[‘HTTP_ACCEPT_ENCODING’], ‘gzip’))
ob_start(“ob_gzhandler”);
else ob_start();
?>
|
[
{
"code": null,
"e": 1222,
"s": 1062,
"text": "GZIP Compression is a simple, effective way to save bandwidth and speed up PHP application. The mechanism runs behind the GZIP compression is described below −"
},
{
"code": null,
"e": 1275,
"s": 1222,
"text": "The browser/client request for a file to the server."
},
{
"code": null,
"e": 1438,
"s": 1275,
"text": "The server sends a .zip file to the browser (index.html.zip) rather than plain old index.html in response, due to which the download time and bandwidth decreases."
},
{
"code": null,
"e": 1597,
"s": 1438,
"text": "After the execution of the above step, the browser downloads the zipped file, extracts it, and then shows it to the user. This loads the webpage very quickly."
},
{
"code": null,
"e": 1694,
"s": 1597,
"text": "In the Apache server, we have to Add the following to .htaccess file to enable GZIP compression."
},
{
"code": null,
"e": 2252,
"s": 1694,
"text": "# compress text, html, javascript, css, xml:\nAddOutputFilterByType DEFLATE text/plain\nAddOutputFilterByType DEFLATE text/html\nAddOutputFilterByType DEFLATE text/xmlin\nAddOutputFilterByType DEFLATE text/css\nAddOutputFilterByType DEFLATE application/xml\nAddOutputFilterByType DEFLATE application/xhtml+xml\nAddOutputFilterByType DEFLATE application/rss+xml\nAddOutputFilterByType DEFLATE application/javascript\nAddOutputFilterByType DEFLATE application/x-javascript\n# Or, compress certain file types by extension:\n<files *.html>\nSetOutputFilter DEFLATE\n</files>"
},
{
"code": null,
"e": 2297,
"s": 2252,
"text": "In PHP files we can enable GZIP compression."
},
{
"code": null,
"e": 2418,
"s": 2297,
"text": "<?php\n if (substr_count($_SERVER[‘HTTP_ACCEPT_ENCODING’], ‘gzip’))\n ob_start(“ob_gzhandler”);\n else ob_start();\n?>"
}
] |
Date toLocaleDateString() Method
|
Javascript date toLocaleDateString() method converts a date to a string, returning the "date" portion using the operating system's locale's conventions.
Its syntax is as follows −
Date.toLocaleString()
Returns the "date" portion using the operating system's locale's conventions.
Try the following example.
<html>
<head>
<title>JavaScript toLocaleDateString Method</title>
</head>
<body>
<script type = "text/javascript">
var dt = new Date(1993, 6, 28, 14, 39, 7);
document.write( "Formated Date : " + dt.toLocaleDateString() );
</script>
</body>
</html>
Formated Date : 7/28/1993
25 Lectures
2.5 hours
Anadi Sharma
74 Lectures
10 hours
Lets Kode It
72 Lectures
4.5 hours
Frahaan Hussain
70 Lectures
4.5 hours
Frahaan Hussain
46 Lectures
6 hours
Eduonix Learning Solutions
88 Lectures
14 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2619,
"s": 2466,
"text": "Javascript date toLocaleDateString() method converts a date to a string, returning the \"date\" portion using the operating system's locale's conventions."
},
{
"code": null,
"e": 2646,
"s": 2619,
"text": "Its syntax is as follows −"
},
{
"code": null,
"e": 2669,
"s": 2646,
"text": "Date.toLocaleString()\n"
},
{
"code": null,
"e": 2747,
"s": 2669,
"text": "Returns the \"date\" portion using the operating system's locale's conventions."
},
{
"code": null,
"e": 2774,
"s": 2747,
"text": "Try the following example."
},
{
"code": null,
"e": 3090,
"s": 2774,
"text": "<html> \n <head>\n <title>JavaScript toLocaleDateString Method</title>\n </head>\n \n <body> \n <script type = \"text/javascript\">\n var dt = new Date(1993, 6, 28, 14, 39, 7);\n document.write( \"Formated Date : \" + dt.toLocaleDateString() ); \n </script> \n </body>\n</html>"
},
{
"code": null,
"e": 3118,
"s": 3090,
"text": "Formated Date : 7/28/1993 \n"
},
{
"code": null,
"e": 3153,
"s": 3118,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3167,
"s": 3153,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3201,
"s": 3167,
"text": "\n 74 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 3215,
"s": 3201,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3250,
"s": 3215,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3267,
"s": 3250,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3302,
"s": 3267,
"text": "\n 70 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3319,
"s": 3302,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3352,
"s": 3319,
"text": "\n 46 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3380,
"s": 3352,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3414,
"s": 3380,
"text": "\n 88 Lectures \n 14 hours \n"
},
{
"code": null,
"e": 3442,
"s": 3414,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3449,
"s": 3442,
"text": " Print"
},
{
"code": null,
"e": 3460,
"s": 3449,
"text": " Add Notes"
}
] |
How to convert a comma separated String into an ArrayList in Java?
|
To convert a comma separated String into an ArrayList
Split the String into an array of Strings using the split() method.Now, convert the obtained String array to list using the asList() method of the Arrays class.
Split the String into an array of Strings using the split() method.
Now, convert the obtained String array to list using the asList() method of the Arrays class.
Live Demo
import java.util.Arrays;
import java.util.List;
public class Sample {
public static void main(String[] args) {
String myString = "JavaFx,Java,WebGL,OpenCV";
String[] myArray = myString.split(",");
System.out.println("Contents of the array ::"+Arrays.toString(myArray));
List <String> myList = Arrays.asList(myArray);
}
}
Contents of the array ::[JavaFx, Java, WebGL, OpenCV]
|
[
{
"code": null,
"e": 1116,
"s": 1062,
"text": "To convert a comma separated String into an ArrayList"
},
{
"code": null,
"e": 1277,
"s": 1116,
"text": "Split the String into an array of Strings using the split() method.Now, convert the obtained String array to list using the asList() method of the Arrays class."
},
{
"code": null,
"e": 1345,
"s": 1277,
"text": "Split the String into an array of Strings using the split() method."
},
{
"code": null,
"e": 1439,
"s": 1345,
"text": "Now, convert the obtained String array to list using the asList() method of the Arrays class."
},
{
"code": null,
"e": 1450,
"s": 1439,
"text": " Live Demo"
},
{
"code": null,
"e": 1802,
"s": 1450,
"text": "import java.util.Arrays;\nimport java.util.List;\n\npublic class Sample {\n public static void main(String[] args) {\n String myString = \"JavaFx,Java,WebGL,OpenCV\";\n String[] myArray = myString.split(\",\");\n System.out.println(\"Contents of the array ::\"+Arrays.toString(myArray));\n List <String> myList = Arrays.asList(myArray);\n }\n}"
},
{
"code": null,
"e": 1856,
"s": 1802,
"text": "Contents of the array ::[JavaFx, Java, WebGL, OpenCV]"
}
] |
SQL Case Study: Investigating a Drop in User Engagement | by Terence Shin | Towards Data Science
|
ProblemBrainstorming Potential CausesDataAnalysis: Event-level AggregationAnalysis: User-level AggregationAnalysis: Engagement by GeographyAnalysis: Email activity and CTRsAnalysis: Clickthrough rates by deviceAnalysis: Weekly digest vs re-engagement emailsSummaryRecommendationFurther Steps
Problem
Brainstorming Potential Causes
Data
Analysis: Event-level Aggregation
Analysis: User-level Aggregation
Analysis: Engagement by Geography
Analysis: Email activity and CTRs
Analysis: Clickthrough rates by device
Analysis: Weekly digest vs re-engagement emails
Summary
Recommendation
Further Steps
This case can be found here if you would like to try it yourself or follow along.
Yammer is a social network for communicating with coworkers. Individuals share documents, updates, and ideas by posting them in groups. Yammer is free to use indefinitely, but companies must pay license fees if they want access to administrative controls, including integration with user management systems like ActiveDirectory.
Yammer noticed a drop in Weekly Active Users, “the number of users who logged at least one engagement event during the week starting on that date”. Engagement is defined as having made some type of server call by interacting with the product (shown in the data as events of type “engagement”.
My goal is to determine the cause of the dip in the image below.
Potential causes of a dip in engagement include the following:
Product-related issues. There may have been a bug in the product that deterred users from using the product. Similarly, Yammer may have released a product update around the beginning of August, which a significant number of users did not like.
Time of the year. August may simply be a month when a lot of users go on vacation. This may be the case if a significant portion of users are parents, as they tend to go on vacations before September when school starts.
Competitors. It’s possible that a competitor launched a competing product at the beginning of August, or a competitor released significant updates to an existing product that caused users to churn.
Data is not being tracked properly. It’s possible that the data pipelines are not working, and thus, the data is not being tracked properly. This is a problem caused internally and would require the help of data engineers to fix.
Marketing event. When large promotions are launched, it’s normal that a company will attract lower quality customers because of the discounts provided. Therefore, it’s a possibility that the dip in August is the aftereffect of a large marketing event in July.
Each row represents one user, with information associated with each user.
Each row represents an event, which is an action that a user has taken on Yammer. These events include login events, messaging events, search events, events logged as users progress through a signup funnel, and events around received emails.
This table contains data on events related to sent emails. It is similar in structure to the events table above.
The final table is a lookup table that is used to create rolling time periods.
The first thing I wanted to see was what events are categorized as ‘engagement’.
SELECT DISTINCT event_name, event_typeFROM tutorial.yammer_eventsORDER BY event_type, event_name ASC
The events categorized as ‘engagement’ are as follows:
home_page
like_message
login
search_autocomplete
search_click_result_1
search_click_result_2
search_click_result_3
search_click_result_4
search_click_result_5
search_click_result_6
search_click_result_7
search_click_result_8
search_click_result_9
search_click_result_10
search_run
send_message
view_inbox
with one as (SELECT EXTRACT('month' FROM occurred_at) as month, count(event_name) as event_countFROM tutorial.yammer_eventsGROUP BY month)SELECT *, (event_count - LAG(event_count) OVER (ORDER BY month ASC)) as diffFROM one
Using the query above, we can deduce that the difference in engagements between July and August is 18,037.
The next thing I wanted to do was count the number of occurrences of each ‘engagement’ event month over month, to see if there’s any significant event(s) that caused the dip after July 28.
with two as (with one as (SELECT CONCAT( EXTRACT('month' FROM occurred_at), '-', EXTRACT('year' FROM occurred_at)) as month_year, event_name, count(event_name) as event_countFROM tutorial.yammer_eventsWHERE event_type = 'engagement'GROUP BY event_name, month_year)SELECT *, CASE WHEN month_year = '5-2014' THEN 0 WHEN month_year != '5-2014' THEN (event_count - LAG(event_count) OVER (ORDER BY event_name ASC, month_year ASC)) ELSE NULL END AS abs_changeFROM one)SELECT *FROM twoWHERE month_year = '8-2014' AND abs_change < 0ORDER BY abs_change asc
The dip in engagement was largely attributed to home_page, like_message_ view_inbox, send_message, and login. It seems like the drop in all of these events are simply related to the fact that users are logging in less.
Next, I wanted to analyze the data on a user level to see if the drop was due to a drop in users or a drop in the number of engagements/user.
SELECT EXTRACT('month' from occurred_at) as month, count(DISTINCT user_id) as num_usersFROM tutorial.yammer_eventsWHERE event_type = 'engagement'GROUP BY month
Using the code above, I found the number of distinct active users on a monthly basis.
We can see that the number of users declined from 3058 in July to 2795 in August, a drop of 8.6%. This is likely the cause of the decline in engagement events, specifically homepage, like_message, view_inbox, send_message, and login.
I also looked to see if the engagement per user declined as well.
SELECT EXTRACT('month' from occurred_at) as month, count(event_name) as num_events, count(DISTINCT user_id) as num_users, count(event_name)/count(DISTINCT user_id) as events_per_userFROM tutorial.yammer_eventsWHERE event_type = 'engagement'GROUP BY month
The number of events per user fell from 30 to 26, representing a drop in engagement by 13%, which is also a fairly significant number.
Therefore, we need to find out why there was a drop in active users and also a drop in engagement per user.
SELECT action, EXTRACT('month' FROM occurred_at) AS month, count(action) as num_emailsFROM tutorial.yammer_emailsGROUP BYaction, monthORDER BYaction, month
I wanted to take an aggregated look at the email activity to see if there was a change in emails sent, click-through rates (CTRs), or something else that may have caused a reduction inactive users.
Immediately, I noticed that there was a steady increase in the number of emails sent (weekly digest and re-engagement) and emails opened, but there was a decrease in clickthrough rates. From July to August, there was a 6.5% increase in emails open but a 27% decline in clickthrough rates.
I wanted to take a deeper look into the clickthrough rates and see if the decline had anything to do with the devices. It could have had to do with the type of operating system (IOS vs Android) or mobile vs desktop.
with emails as(SELECT *, CONCAT(EXTRACT('day' FROM occurred_at), '-', EXTRACT('month' FROM occurred_at), '-', EXTRACT('year' FROM occurred_at)) as date, EXTRACT('month' FROM occurred_at) as monthFROM tutorial.yammer_emails emails), events as ( SELECT DISTINCT user_id, CONCAT(EXTRACT('day' FROM occurred_at), '-', EXTRACT('month' FROM occurred_at), '-', EXTRACT('year' FROM occurred_at)) as date, device, EXTRACT('month' FROM occurred_at) as month FROM tutorial.yammer_events ORDER BY user_id ASC)SELECT device, emails.month, count(emails.user_id)FROM emailsLEFT JOIN events ON emails.user_id = events.user_id AND emails.date = events.dateWHERE action = 'email_clickthrough'GROUP BY device, emails.month
Using the query above, I noticed that the clickthrough rates on laptops and computers were stable from July to August, but not the tablets and cellphones.
By categorizing the device names into ‘mobile’, ‘tablet’, and ‘laptop’, I could determine if this is truly the case.
with emails as(SELECT *, CONCAT(EXTRACT('day' FROM occurred_at), '-', EXTRACT('month' FROM occurred_at), '-', EXTRACT('year' FROM occurred_at)) as date, EXTRACT('month' FROM occurred_at) as monthFROM tutorial.yammer_emails emails), events as ( SELECT DISTINCT user_id, CONCAT(EXTRACT('day' FROM occurred_at), '-', EXTRACT('month' FROM occurred_at), '-', EXTRACT('year' FROM occurred_at)) as date, device, EXTRACT('month' FROM occurred_at) as month FROM tutorial.yammer_events ORDER BY user_id ASC)SELECT CASE WHEN device IN ('amazon fire phone', 'nexus 10', 'iphone 5', 'nexus 7', 'iphone 5s', 'nexus 5', 'htc one', 'iphone 4s', 'samsung galaxy note', 'nokia lumia 635', 'samsung galaxy s4') THEN 'mobile' WHEN device IN ('ipad mini', 'samsung galaxy tablet', 'kindle fire', 'ipad air') THEN 'tablet_ipad' WHEN device IN ('dell inspiron desktop', 'macbook pro', 'asus chromebook', 'windows surface', 'macbook air', 'lenovo thinkpad', 'mac mini', 'acer aspire desktop', 'acer aspire notebook', 'dell inspiron notebook', 'hp pavilion desktop') THEN 'laptop_comp' ELSE null end as device_type, emails.month, count(emails.user_id)FROM emailsLEFT JOIN events ON emails.user_id = events.user_id AND emails.date = events.dateWHERE action = 'email_clickthrough'GROUP BY device_type, emails.month
Indeed, it seems to be the case that the drop in clickthrough rates was attributed specifically to mobile devices and tablets.
So far, I’ve determined that the lack of engagement is due to a decrease in email clickthrough rates from July to August. To gather more information, I want to see if we can narrow the problem even further by email type.
with one as (SELECT *, EXTRACT('month' from occurred_at) as month, CASE WHEN (LEAD(action, 1) OVER (PARTITION BY user_id ORDER BY occurred_at ASC)) = 'email_open' THEN 1 ELSE 0 END AS opened_email, CASE WHEN (LEAD(action, 2) OVER (PARTITION BY user_id ORDER BY occurred_at ASC)) = 'email_clickthrough' THEN 1 ELSE 0 END AS clicked_emailFROM tutorial.yammer_emails)SELECT action, month, count(action), sum(opened_email) as num_open, sum(clicked_email) as num_clickedFROM oneWHERE action in ('sent_weekly_digest','sent_reengagement_email')GROUP BY action, monthORDER BY action, month
It’s evident that the drop in clicks is due to the weekly digest email and not the re-engagement email.
Through my analysis, I can conclude the following:
The drop in engagement was mainly attributed to a drop in five engagement events (home_page, like_message_ view_inbox, send_message, and login).
I then found that the decrease in events was caused by a reduction in total active users MoM, as well as a decrease in engagement per user.
After I took an aggregated look at the emails table and I noticed that there was a significant decrease in click-through rates from July to August even though there was an increase in the number of emails opened.
By segmenting the clickthrough rates by device type (mobile, tablet, laptop), I noticed that the drop in clickthrough rates was attributed to mobile and tablet devices.
Lastly, the decline in click-through rates is attributed to the weekly digest email and not the re-engagement email.
My recommendation is to immediately take a deeper look into the weekly digest emails specifically for mobile devices and tablets. It’s possible that there’s a technical problem, making it difficult for users to click the email or simply a UX problem, where the content and layout of the email are not enticing users to click. A good first step would be to see what changes have been made from July to August and working backward.
Some other things that could’ve been looked at include the following:
Check to see if the change is attributed to a small number of users (Pareo principle)
Cohort analysis to see if the cause is due to a short user lifecycle
Analysis by language
Analysis by geography
Founder of ShinTwin | Let’s connect on LinkedIn
|
[
{
"code": null,
"e": 464,
"s": 172,
"text": "ProblemBrainstorming Potential CausesDataAnalysis: Event-level AggregationAnalysis: User-level AggregationAnalysis: Engagement by GeographyAnalysis: Email activity and CTRsAnalysis: Clickthrough rates by deviceAnalysis: Weekly digest vs re-engagement emailsSummaryRecommendationFurther Steps"
},
{
"code": null,
"e": 472,
"s": 464,
"text": "Problem"
},
{
"code": null,
"e": 503,
"s": 472,
"text": "Brainstorming Potential Causes"
},
{
"code": null,
"e": 508,
"s": 503,
"text": "Data"
},
{
"code": null,
"e": 542,
"s": 508,
"text": "Analysis: Event-level Aggregation"
},
{
"code": null,
"e": 575,
"s": 542,
"text": "Analysis: User-level Aggregation"
},
{
"code": null,
"e": 609,
"s": 575,
"text": "Analysis: Engagement by Geography"
},
{
"code": null,
"e": 643,
"s": 609,
"text": "Analysis: Email activity and CTRs"
},
{
"code": null,
"e": 682,
"s": 643,
"text": "Analysis: Clickthrough rates by device"
},
{
"code": null,
"e": 730,
"s": 682,
"text": "Analysis: Weekly digest vs re-engagement emails"
},
{
"code": null,
"e": 738,
"s": 730,
"text": "Summary"
},
{
"code": null,
"e": 753,
"s": 738,
"text": "Recommendation"
},
{
"code": null,
"e": 767,
"s": 753,
"text": "Further Steps"
},
{
"code": null,
"e": 849,
"s": 767,
"text": "This case can be found here if you would like to try it yourself or follow along."
},
{
"code": null,
"e": 1178,
"s": 849,
"text": "Yammer is a social network for communicating with coworkers. Individuals share documents, updates, and ideas by posting them in groups. Yammer is free to use indefinitely, but companies must pay license fees if they want access to administrative controls, including integration with user management systems like ActiveDirectory."
},
{
"code": null,
"e": 1471,
"s": 1178,
"text": "Yammer noticed a drop in Weekly Active Users, “the number of users who logged at least one engagement event during the week starting on that date”. Engagement is defined as having made some type of server call by interacting with the product (shown in the data as events of type “engagement”."
},
{
"code": null,
"e": 1536,
"s": 1471,
"text": "My goal is to determine the cause of the dip in the image below."
},
{
"code": null,
"e": 1599,
"s": 1536,
"text": "Potential causes of a dip in engagement include the following:"
},
{
"code": null,
"e": 1843,
"s": 1599,
"text": "Product-related issues. There may have been a bug in the product that deterred users from using the product. Similarly, Yammer may have released a product update around the beginning of August, which a significant number of users did not like."
},
{
"code": null,
"e": 2063,
"s": 1843,
"text": "Time of the year. August may simply be a month when a lot of users go on vacation. This may be the case if a significant portion of users are parents, as they tend to go on vacations before September when school starts."
},
{
"code": null,
"e": 2261,
"s": 2063,
"text": "Competitors. It’s possible that a competitor launched a competing product at the beginning of August, or a competitor released significant updates to an existing product that caused users to churn."
},
{
"code": null,
"e": 2491,
"s": 2261,
"text": "Data is not being tracked properly. It’s possible that the data pipelines are not working, and thus, the data is not being tracked properly. This is a problem caused internally and would require the help of data engineers to fix."
},
{
"code": null,
"e": 2751,
"s": 2491,
"text": "Marketing event. When large promotions are launched, it’s normal that a company will attract lower quality customers because of the discounts provided. Therefore, it’s a possibility that the dip in August is the aftereffect of a large marketing event in July."
},
{
"code": null,
"e": 2825,
"s": 2751,
"text": "Each row represents one user, with information associated with each user."
},
{
"code": null,
"e": 3067,
"s": 2825,
"text": "Each row represents an event, which is an action that a user has taken on Yammer. These events include login events, messaging events, search events, events logged as users progress through a signup funnel, and events around received emails."
},
{
"code": null,
"e": 3180,
"s": 3067,
"text": "This table contains data on events related to sent emails. It is similar in structure to the events table above."
},
{
"code": null,
"e": 3259,
"s": 3180,
"text": "The final table is a lookup table that is used to create rolling time periods."
},
{
"code": null,
"e": 3340,
"s": 3259,
"text": "The first thing I wanted to see was what events are categorized as ‘engagement’."
},
{
"code": null,
"e": 3441,
"s": 3340,
"text": "SELECT DISTINCT event_name, event_typeFROM tutorial.yammer_eventsORDER BY event_type, event_name ASC"
},
{
"code": null,
"e": 3496,
"s": 3441,
"text": "The events categorized as ‘engagement’ are as follows:"
},
{
"code": null,
"e": 3506,
"s": 3496,
"text": "home_page"
},
{
"code": null,
"e": 3519,
"s": 3506,
"text": "like_message"
},
{
"code": null,
"e": 3525,
"s": 3519,
"text": "login"
},
{
"code": null,
"e": 3545,
"s": 3525,
"text": "search_autocomplete"
},
{
"code": null,
"e": 3567,
"s": 3545,
"text": "search_click_result_1"
},
{
"code": null,
"e": 3589,
"s": 3567,
"text": "search_click_result_2"
},
{
"code": null,
"e": 3611,
"s": 3589,
"text": "search_click_result_3"
},
{
"code": null,
"e": 3633,
"s": 3611,
"text": "search_click_result_4"
},
{
"code": null,
"e": 3655,
"s": 3633,
"text": "search_click_result_5"
},
{
"code": null,
"e": 3677,
"s": 3655,
"text": "search_click_result_6"
},
{
"code": null,
"e": 3699,
"s": 3677,
"text": "search_click_result_7"
},
{
"code": null,
"e": 3721,
"s": 3699,
"text": "search_click_result_8"
},
{
"code": null,
"e": 3743,
"s": 3721,
"text": "search_click_result_9"
},
{
"code": null,
"e": 3766,
"s": 3743,
"text": "search_click_result_10"
},
{
"code": null,
"e": 3777,
"s": 3766,
"text": "search_run"
},
{
"code": null,
"e": 3790,
"s": 3777,
"text": "send_message"
},
{
"code": null,
"e": 3801,
"s": 3790,
"text": "view_inbox"
},
{
"code": null,
"e": 4031,
"s": 3801,
"text": "with one as (SELECT EXTRACT('month' FROM occurred_at) as month, count(event_name) as event_countFROM tutorial.yammer_eventsGROUP BY month)SELECT *, (event_count - LAG(event_count) OVER (ORDER BY month ASC)) as diffFROM one"
},
{
"code": null,
"e": 4138,
"s": 4031,
"text": "Using the query above, we can deduce that the difference in engagements between July and August is 18,037."
},
{
"code": null,
"e": 4327,
"s": 4138,
"text": "The next thing I wanted to do was count the number of occurrences of each ‘engagement’ event month over month, to see if there’s any significant event(s) that caused the dip after July 28."
},
{
"code": null,
"e": 4904,
"s": 4327,
"text": "with two as (with one as (SELECT CONCAT( EXTRACT('month' FROM occurred_at), '-', EXTRACT('year' FROM occurred_at)) as month_year, event_name, count(event_name) as event_countFROM tutorial.yammer_eventsWHERE event_type = 'engagement'GROUP BY event_name, month_year)SELECT *, CASE WHEN month_year = '5-2014' THEN 0 WHEN month_year != '5-2014' THEN (event_count - LAG(event_count) OVER (ORDER BY event_name ASC, month_year ASC)) ELSE NULL END AS abs_changeFROM one)SELECT *FROM twoWHERE month_year = '8-2014' AND abs_change < 0ORDER BY abs_change asc"
},
{
"code": null,
"e": 5123,
"s": 4904,
"text": "The dip in engagement was largely attributed to home_page, like_message_ view_inbox, send_message, and login. It seems like the drop in all of these events are simply related to the fact that users are logging in less."
},
{
"code": null,
"e": 5265,
"s": 5123,
"text": "Next, I wanted to analyze the data on a user level to see if the drop was due to a drop in users or a drop in the number of engagements/user."
},
{
"code": null,
"e": 5427,
"s": 5265,
"text": "SELECT EXTRACT('month' from occurred_at) as month, count(DISTINCT user_id) as num_usersFROM tutorial.yammer_eventsWHERE event_type = 'engagement'GROUP BY month"
},
{
"code": null,
"e": 5513,
"s": 5427,
"text": "Using the code above, I found the number of distinct active users on a monthly basis."
},
{
"code": null,
"e": 5747,
"s": 5513,
"text": "We can see that the number of users declined from 3058 in July to 2795 in August, a drop of 8.6%. This is likely the cause of the decline in engagement events, specifically homepage, like_message, view_inbox, send_message, and login."
},
{
"code": null,
"e": 5813,
"s": 5747,
"text": "I also looked to see if the engagement per user declined as well."
},
{
"code": null,
"e": 6072,
"s": 5813,
"text": "SELECT EXTRACT('month' from occurred_at) as month, count(event_name) as num_events, count(DISTINCT user_id) as num_users, count(event_name)/count(DISTINCT user_id) as events_per_userFROM tutorial.yammer_eventsWHERE event_type = 'engagement'GROUP BY month"
},
{
"code": null,
"e": 6207,
"s": 6072,
"text": "The number of events per user fell from 30 to 26, representing a drop in engagement by 13%, which is also a fairly significant number."
},
{
"code": null,
"e": 6315,
"s": 6207,
"text": "Therefore, we need to find out why there was a drop in active users and also a drop in engagement per user."
},
{
"code": null,
"e": 6474,
"s": 6315,
"text": "SELECT action, EXTRACT('month' FROM occurred_at) AS month, count(action) as num_emailsFROM tutorial.yammer_emailsGROUP BYaction, monthORDER BYaction, month"
},
{
"code": null,
"e": 6672,
"s": 6474,
"text": "I wanted to take an aggregated look at the email activity to see if there was a change in emails sent, click-through rates (CTRs), or something else that may have caused a reduction inactive users."
},
{
"code": null,
"e": 6961,
"s": 6672,
"text": "Immediately, I noticed that there was a steady increase in the number of emails sent (weekly digest and re-engagement) and emails opened, but there was a decrease in clickthrough rates. From July to August, there was a 6.5% increase in emails open but a 27% decline in clickthrough rates."
},
{
"code": null,
"e": 7177,
"s": 6961,
"text": "I wanted to take a deeper look into the clickthrough rates and see if the decline had anything to do with the devices. It could have had to do with the type of operating system (IOS vs Android) or mobile vs desktop."
},
{
"code": null,
"e": 7909,
"s": 7177,
"text": "with emails as(SELECT *, CONCAT(EXTRACT('day' FROM occurred_at), '-', EXTRACT('month' FROM occurred_at), '-', EXTRACT('year' FROM occurred_at)) as date, EXTRACT('month' FROM occurred_at) as monthFROM tutorial.yammer_emails emails), events as ( SELECT DISTINCT user_id, CONCAT(EXTRACT('day' FROM occurred_at), '-', EXTRACT('month' FROM occurred_at), '-', EXTRACT('year' FROM occurred_at)) as date, device, EXTRACT('month' FROM occurred_at) as month FROM tutorial.yammer_events ORDER BY user_id ASC)SELECT device, emails.month, count(emails.user_id)FROM emailsLEFT JOIN events ON emails.user_id = events.user_id AND emails.date = events.dateWHERE action = 'email_clickthrough'GROUP BY device, emails.month"
},
{
"code": null,
"e": 8064,
"s": 7909,
"text": "Using the query above, I noticed that the clickthrough rates on laptops and computers were stable from July to August, but not the tablets and cellphones."
},
{
"code": null,
"e": 8181,
"s": 8064,
"text": "By categorizing the device names into ‘mobile’, ‘tablet’, and ‘laptop’, I could determine if this is truly the case."
},
{
"code": null,
"e": 9509,
"s": 8181,
"text": "with emails as(SELECT *, CONCAT(EXTRACT('day' FROM occurred_at), '-', EXTRACT('month' FROM occurred_at), '-', EXTRACT('year' FROM occurred_at)) as date, EXTRACT('month' FROM occurred_at) as monthFROM tutorial.yammer_emails emails), events as ( SELECT DISTINCT user_id, CONCAT(EXTRACT('day' FROM occurred_at), '-', EXTRACT('month' FROM occurred_at), '-', EXTRACT('year' FROM occurred_at)) as date, device, EXTRACT('month' FROM occurred_at) as month FROM tutorial.yammer_events ORDER BY user_id ASC)SELECT CASE WHEN device IN ('amazon fire phone', 'nexus 10', 'iphone 5', 'nexus 7', 'iphone 5s', 'nexus 5', 'htc one', 'iphone 4s', 'samsung galaxy note', 'nokia lumia 635', 'samsung galaxy s4') THEN 'mobile' WHEN device IN ('ipad mini', 'samsung galaxy tablet', 'kindle fire', 'ipad air') THEN 'tablet_ipad' WHEN device IN ('dell inspiron desktop', 'macbook pro', 'asus chromebook', 'windows surface', 'macbook air', 'lenovo thinkpad', 'mac mini', 'acer aspire desktop', 'acer aspire notebook', 'dell inspiron notebook', 'hp pavilion desktop') THEN 'laptop_comp' ELSE null end as device_type, emails.month, count(emails.user_id)FROM emailsLEFT JOIN events ON emails.user_id = events.user_id AND emails.date = events.dateWHERE action = 'email_clickthrough'GROUP BY device_type, emails.month"
},
{
"code": null,
"e": 9636,
"s": 9509,
"text": "Indeed, it seems to be the case that the drop in clickthrough rates was attributed specifically to mobile devices and tablets."
},
{
"code": null,
"e": 9857,
"s": 9636,
"text": "So far, I’ve determined that the lack of engagement is due to a decrease in email clickthrough rates from July to August. To gather more information, I want to see if we can narrow the problem even further by email type."
},
{
"code": null,
"e": 10456,
"s": 9857,
"text": "with one as (SELECT *, EXTRACT('month' from occurred_at) as month, CASE WHEN (LEAD(action, 1) OVER (PARTITION BY user_id ORDER BY occurred_at ASC)) = 'email_open' THEN 1 ELSE 0 END AS opened_email, CASE WHEN (LEAD(action, 2) OVER (PARTITION BY user_id ORDER BY occurred_at ASC)) = 'email_clickthrough' THEN 1 ELSE 0 END AS clicked_emailFROM tutorial.yammer_emails)SELECT action, month, count(action), sum(opened_email) as num_open, sum(clicked_email) as num_clickedFROM oneWHERE action in ('sent_weekly_digest','sent_reengagement_email')GROUP BY action, monthORDER BY action, month"
},
{
"code": null,
"e": 10560,
"s": 10456,
"text": "It’s evident that the drop in clicks is due to the weekly digest email and not the re-engagement email."
},
{
"code": null,
"e": 10611,
"s": 10560,
"text": "Through my analysis, I can conclude the following:"
},
{
"code": null,
"e": 10756,
"s": 10611,
"text": "The drop in engagement was mainly attributed to a drop in five engagement events (home_page, like_message_ view_inbox, send_message, and login)."
},
{
"code": null,
"e": 10896,
"s": 10756,
"text": "I then found that the decrease in events was caused by a reduction in total active users MoM, as well as a decrease in engagement per user."
},
{
"code": null,
"e": 11109,
"s": 10896,
"text": "After I took an aggregated look at the emails table and I noticed that there was a significant decrease in click-through rates from July to August even though there was an increase in the number of emails opened."
},
{
"code": null,
"e": 11278,
"s": 11109,
"text": "By segmenting the clickthrough rates by device type (mobile, tablet, laptop), I noticed that the drop in clickthrough rates was attributed to mobile and tablet devices."
},
{
"code": null,
"e": 11395,
"s": 11278,
"text": "Lastly, the decline in click-through rates is attributed to the weekly digest email and not the re-engagement email."
},
{
"code": null,
"e": 11825,
"s": 11395,
"text": "My recommendation is to immediately take a deeper look into the weekly digest emails specifically for mobile devices and tablets. It’s possible that there’s a technical problem, making it difficult for users to click the email or simply a UX problem, where the content and layout of the email are not enticing users to click. A good first step would be to see what changes have been made from July to August and working backward."
},
{
"code": null,
"e": 11895,
"s": 11825,
"text": "Some other things that could’ve been looked at include the following:"
},
{
"code": null,
"e": 11981,
"s": 11895,
"text": "Check to see if the change is attributed to a small number of users (Pareo principle)"
},
{
"code": null,
"e": 12050,
"s": 11981,
"text": "Cohort analysis to see if the cause is due to a short user lifecycle"
},
{
"code": null,
"e": 12071,
"s": 12050,
"text": "Analysis by language"
},
{
"code": null,
"e": 12093,
"s": 12071,
"text": "Analysis by geography"
}
] |
Program to print matrix elements in spiral order in python
|
Suppose we have a 2D matrix mat. We have to print the matrix elements in a spiral way. At first starting from the first row (mat[0, 0]), print the whole content and then follow the last column to print, then the last row, and so on, thus it prints the elements in a spiral fashion.
So, if the input is like
then the output will be [7, 10, 9, 1, 3, 4, 5, 11, 9, 9, 2, 9, 6, 2, 9, 2, 1, 7]
To solve this, we will follow these steps:
d := 0
top := 0, down := row count of matrix – 1, left := 0, right := column count of matrix - 1
c := 0
res := a new list
direction := 0
while top <= down and left <= right, doif direction is same as 0, thenfor i in range left to right + 1, doinsert matrix[top, i] into restop := top + 1if direction is same as 1, thenfor i in range top to down + 1, doinsert matrix[i, right] into resright := right - 1if direction is same as 2, thenfor i in range right to left - 1, decrease by 1, doinsert matrix[down, i] into resdown := down - 1if direction is same as 3, thenfor i in range down to top - 1, decrease by 1, doinsert matrix[i, left] into resleft := left + 1
if direction is same as 0, thenfor i in range left to right + 1, doinsert matrix[top, i] into restop := top + 1
for i in range left to right + 1, doinsert matrix[top, i] into res
insert matrix[top, i] into res
top := top + 1
if direction is same as 1, thenfor i in range top to down + 1, doinsert matrix[i, right] into resright := right - 1
for i in range top to down + 1, doinsert matrix[i, right] into res
insert matrix[i, right] into res
right := right - 1
if direction is same as 2, thenfor i in range right to left - 1, decrease by 1, doinsert matrix[down, i] into resdown := down - 1
for i in range right to left - 1, decrease by 1, doinsert matrix[down, i] into res
insert matrix[down, i] into res
down := down - 1
if direction is same as 3, thenfor i in range down to top - 1, decrease by 1, doinsert matrix[i, left] into resleft := left + 1
for i in range down to top - 1, decrease by 1, doinsert matrix[i, left] into res
insert matrix[i, left] into res
left := left + 1
direction :=(direction + 1) mod 4
return res
Let us see the following implementation to get better understanding:
Live Demo
class Solution:
def solve(self, matrix):
d = 0
top = 0
down = len(matrix) - 1
left = 0
right = len(matrix[0]) - 1
c = 0
res = []
direction = 0
while top <= down and left <= right:
if direction == 0:
for i in range(left, right + 1):
res.append(matrix[top][i])
top += 1
if direction == 1:
for i in range(top, down + 1):
res.append(matrix[i][right])
right -= 1
if direction == 2:
for i in range(right, left - 1, -1):
res.append(matrix[down][i])
down -= 1
if direction == 3:
for i in range(down, top - 1, -1):
res.append(matrix[i][left])
left += 1
direction = (direction + 1) % 4
return res
ob = Solution()
matrix = [
[7, 10, 9],
[2, 9, 1],
[6, 2, 3],
[9, 1, 4],
[2, 7, 5],
[9, 9, 11]
]
print(ob.solve(matrix))
[
[7, 10, 9],
[2, 9, 1], [6, 2, 3],
[9, 1, 4], [2, 7, 5],
[9, 9, 11]]
[2, 9, 1],
[9, 1, 4],
[9, 9, 11]
[7, 10, 9, 1, 3, 4, 5, 11, 9, 9, 2, 9, 6, 2, 9, 2, 1, 7]
|
[
{
"code": null,
"e": 1344,
"s": 1062,
"text": "Suppose we have a 2D matrix mat. We have to print the matrix elements in a spiral way. At first starting from the first row (mat[0, 0]), print the whole content and then follow the last column to print, then the last row, and so on, thus it prints the elements in a spiral fashion."
},
{
"code": null,
"e": 1369,
"s": 1344,
"text": "So, if the input is like"
},
{
"code": null,
"e": 1450,
"s": 1369,
"text": "then the output will be [7, 10, 9, 1, 3, 4, 5, 11, 9, 9, 2, 9, 6, 2, 9, 2, 1, 7]"
},
{
"code": null,
"e": 1493,
"s": 1450,
"text": "To solve this, we will follow these steps:"
},
{
"code": null,
"e": 1500,
"s": 1493,
"text": "d := 0"
},
{
"code": null,
"e": 1590,
"s": 1500,
"text": "top := 0, down := row count of matrix – 1, left := 0, right := column count of matrix - 1"
},
{
"code": null,
"e": 1597,
"s": 1590,
"text": "c := 0"
},
{
"code": null,
"e": 1615,
"s": 1597,
"text": "res := a new list"
},
{
"code": null,
"e": 1630,
"s": 1615,
"text": "direction := 0"
},
{
"code": null,
"e": 2152,
"s": 1630,
"text": "while top <= down and left <= right, doif direction is same as 0, thenfor i in range left to right + 1, doinsert matrix[top, i] into restop := top + 1if direction is same as 1, thenfor i in range top to down + 1, doinsert matrix[i, right] into resright := right - 1if direction is same as 2, thenfor i in range right to left - 1, decrease by 1, doinsert matrix[down, i] into resdown := down - 1if direction is same as 3, thenfor i in range down to top - 1, decrease by 1, doinsert matrix[i, left] into resleft := left + 1"
},
{
"code": null,
"e": 2264,
"s": 2152,
"text": "if direction is same as 0, thenfor i in range left to right + 1, doinsert matrix[top, i] into restop := top + 1"
},
{
"code": null,
"e": 2331,
"s": 2264,
"text": "for i in range left to right + 1, doinsert matrix[top, i] into res"
},
{
"code": null,
"e": 2362,
"s": 2331,
"text": "insert matrix[top, i] into res"
},
{
"code": null,
"e": 2377,
"s": 2362,
"text": "top := top + 1"
},
{
"code": null,
"e": 2493,
"s": 2377,
"text": "if direction is same as 1, thenfor i in range top to down + 1, doinsert matrix[i, right] into resright := right - 1"
},
{
"code": null,
"e": 2560,
"s": 2493,
"text": "for i in range top to down + 1, doinsert matrix[i, right] into res"
},
{
"code": null,
"e": 2593,
"s": 2560,
"text": "insert matrix[i, right] into res"
},
{
"code": null,
"e": 2612,
"s": 2593,
"text": "right := right - 1"
},
{
"code": null,
"e": 2742,
"s": 2612,
"text": "if direction is same as 2, thenfor i in range right to left - 1, decrease by 1, doinsert matrix[down, i] into resdown := down - 1"
},
{
"code": null,
"e": 2825,
"s": 2742,
"text": "for i in range right to left - 1, decrease by 1, doinsert matrix[down, i] into res"
},
{
"code": null,
"e": 2857,
"s": 2825,
"text": "insert matrix[down, i] into res"
},
{
"code": null,
"e": 2874,
"s": 2857,
"text": "down := down - 1"
},
{
"code": null,
"e": 3002,
"s": 2874,
"text": "if direction is same as 3, thenfor i in range down to top - 1, decrease by 1, doinsert matrix[i, left] into resleft := left + 1"
},
{
"code": null,
"e": 3083,
"s": 3002,
"text": "for i in range down to top - 1, decrease by 1, doinsert matrix[i, left] into res"
},
{
"code": null,
"e": 3115,
"s": 3083,
"text": "insert matrix[i, left] into res"
},
{
"code": null,
"e": 3132,
"s": 3115,
"text": "left := left + 1"
},
{
"code": null,
"e": 3166,
"s": 3132,
"text": "direction :=(direction + 1) mod 4"
},
{
"code": null,
"e": 3177,
"s": 3166,
"text": "return res"
},
{
"code": null,
"e": 3246,
"s": 3177,
"text": "Let us see the following implementation to get better understanding:"
},
{
"code": null,
"e": 3256,
"s": 3246,
"text": "Live Demo"
},
{
"code": null,
"e": 4253,
"s": 3256,
"text": "class Solution:\n def solve(self, matrix):\n d = 0\n top = 0\n down = len(matrix) - 1\n left = 0\n right = len(matrix[0]) - 1\n c = 0\n res = []\n direction = 0\n while top <= down and left <= right:\n if direction == 0:\n for i in range(left, right + 1):\n res.append(matrix[top][i])\n top += 1\n\n if direction == 1:\n for i in range(top, down + 1):\n res.append(matrix[i][right])\n right -= 1\n\n if direction == 2:\n for i in range(right, left - 1, -1):\n res.append(matrix[down][i])\n down -= 1\n\n if direction == 3:\n for i in range(down, top - 1, -1):\n res.append(matrix[i][left])\n left += 1\n\n direction = (direction + 1) % 4\n return res\n\nob = Solution()\nmatrix = [\n [7, 10, 9],\n [2, 9, 1],\n [6, 2, 3],\n [9, 1, 4],\n [2, 7, 5],\n [9, 9, 11]\n]\nprint(ob.solve(matrix))"
},
{
"code": null,
"e": 4345,
"s": 4253,
"text": "[ \n[7, 10, 9], \n[2, 9, 1], [6, 2, 3], \n[9, 1, 4], [2, 7, 5], \n[9, 9, 11]]"
},
{
"code": null,
"e": 4360,
"s": 4345,
"text": "[2, 9, 1], "
},
{
"code": null,
"e": 4375,
"s": 4360,
"text": "[9, 1, 4], "
},
{
"code": null,
"e": 4386,
"s": 4375,
"text": "[9, 9, 11]"
},
{
"code": null,
"e": 4443,
"s": 4386,
"text": "[7, 10, 9, 1, 3, 4, 5, 11, 9, 9, 2, 9, 6, 2, 9, 2, 1, 7]"
}
] |
Scala Collections - Reduce Method
|
reduce() method is a member of TraversableOnce trait, it is used to collapse elements of collections. It is similar to fold method but it does not take initial value.
The following is the syntax of reduce method.
def reduce[A1 >: A](op: (A1, A1) ? A1): A1
Here, reduce method takes associative binary operator function as a parameter. This method returns the resultant value.
Below is an example program of showing how to use fold method −
object Demo {
def main(args: Array[String]) = {
val list = List(1, 2, 3 ,4)
//apply operation to get sum of all elements of the list
val result = list.reduce(_ + _)
//print result
println(result)
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
10
82 Lectures
7 hours
Arnab Chakraborty
23 Lectures
1.5 hours
Mukund Kumar Mishra
52 Lectures
1.5 hours
Bigdata Engineer
76 Lectures
5.5 hours
Bigdata Engineer
69 Lectures
7.5 hours
Bigdata Engineer
46 Lectures
4.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3050,
"s": 2882,
"text": "reduce() method is a member of TraversableOnce trait, it is used to collapse elements of collections. It is similar to fold method but it does not take initial value."
},
{
"code": null,
"e": 3096,
"s": 3050,
"text": "The following is the syntax of reduce method."
},
{
"code": null,
"e": 3140,
"s": 3096,
"text": "def reduce[A1 >: A](op: (A1, A1) ? A1): A1\n"
},
{
"code": null,
"e": 3260,
"s": 3140,
"text": "Here, reduce method takes associative binary operator function as a parameter. This method returns the resultant value."
},
{
"code": null,
"e": 3324,
"s": 3260,
"text": "Below is an example program of showing how to use fold method −"
},
{
"code": null,
"e": 3566,
"s": 3324,
"text": "object Demo {\n def main(args: Array[String]) = {\n val list = List(1, 2, 3 ,4)\n //apply operation to get sum of all elements of the list\n val result = list.reduce(_ + _)\n //print result\n println(result) \n }\n}"
},
{
"code": null,
"e": 3673,
"s": 3566,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 3707,
"s": 3673,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 3711,
"s": 3707,
"text": "10\n"
},
{
"code": null,
"e": 3744,
"s": 3711,
"text": "\n 82 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3763,
"s": 3744,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3798,
"s": 3763,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3819,
"s": 3798,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 3854,
"s": 3819,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3872,
"s": 3854,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 3907,
"s": 3872,
"text": "\n 76 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3925,
"s": 3907,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 3960,
"s": 3925,
"text": "\n 69 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 3978,
"s": 3960,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 4013,
"s": 3978,
"text": "\n 46 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4036,
"s": 4013,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 4043,
"s": 4036,
"text": " Print"
},
{
"code": null,
"e": 4054,
"s": 4043,
"text": " Add Notes"
}
] |
BigDecimal precision() Method in Java - GeeksforGeeks
|
04 Dec, 2018
The java.math.BigDecimal.precision() method returns the precision of this BigDecimal. The precision refers to the number of digits in the unscaled value.
Syntax:
public int precision()
Parameters: This method does not accept any parameters.
Return Value: This method returns an integer which denotes the precision of this BigDecimal object.
Examples:
Input : 198.176
Output : 6
Input : 721111.111
Output : 9
Below programs illustrate the java.math.BigDecimal.precision() function in Java:Program 1:
import java.math.*;import java.io.*; class GFG { public static void main(String[] args) { // create 2 BigDecimal Objects BigDecimal b1, b2; // Assigning values to b1, b2 b1 = new BigDecimal("198.176"); b2 = new BigDecimal("721111.111"); // Display their respective precision System.out.println("The precision of " + b1 + " is " + b1.precision()); System.out.println("The precision of " + b2 + " is " + b2.precision()); }}
The precision of 198.176 is 6
The precision of 721111.111 is 9
Program 2:
// Java program to illustrate// precision() Functionimport java.math.*;import java.io.*; class GFG { public static void main(String[] args) { // Creating a BigDecimal Object BigDecimal num; // Assigning value 0.1 + 0.1 + 0.1 to num num = new BigDecimal("0.1") .add(new BigDecimal("0.1")) .add(new BigDecimal("0.1")); // Display the BigDecimal value and its precision System.out.println("The precision of " + num + " is " + num.precision()); }}
The precision of 0.3 is 1
Reference: https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#precision()
Java-BigDecimal
Java-Functions
java-math
Java-math-package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
HashMap in Java with Examples
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
Interfaces in Java
ArrayList in Java
How to iterate any Map in Java
Multidimensional Arrays in Java
LinkedList in Java
Stack Class in Java
Multithreading in Java
|
[
{
"code": null,
"e": 24476,
"s": 24448,
"text": "\n04 Dec, 2018"
},
{
"code": null,
"e": 24630,
"s": 24476,
"text": "The java.math.BigDecimal.precision() method returns the precision of this BigDecimal. The precision refers to the number of digits in the unscaled value."
},
{
"code": null,
"e": 24638,
"s": 24630,
"text": "Syntax:"
},
{
"code": null,
"e": 24661,
"s": 24638,
"text": "public int precision()"
},
{
"code": null,
"e": 24717,
"s": 24661,
"text": "Parameters: This method does not accept any parameters."
},
{
"code": null,
"e": 24817,
"s": 24717,
"text": "Return Value: This method returns an integer which denotes the precision of this BigDecimal object."
},
{
"code": null,
"e": 24827,
"s": 24817,
"text": "Examples:"
},
{
"code": null,
"e": 24886,
"s": 24827,
"text": "Input : 198.176\nOutput : 6\n\nInput : 721111.111\nOutput : 9\n"
},
{
"code": null,
"e": 24977,
"s": 24886,
"text": "Below programs illustrate the java.math.BigDecimal.precision() function in Java:Program 1:"
},
{
"code": "import java.math.*;import java.io.*; class GFG { public static void main(String[] args) { // create 2 BigDecimal Objects BigDecimal b1, b2; // Assigning values to b1, b2 b1 = new BigDecimal(\"198.176\"); b2 = new BigDecimal(\"721111.111\"); // Display their respective precision System.out.println(\"The precision of \" + b1 + \" is \" + b1.precision()); System.out.println(\"The precision of \" + b2 + \" is \" + b2.precision()); }}",
"e": 25469,
"s": 24977,
"text": null
},
{
"code": null,
"e": 25533,
"s": 25469,
"text": "The precision of 198.176 is 6\nThe precision of 721111.111 is 9\n"
},
{
"code": null,
"e": 25544,
"s": 25533,
"text": "Program 2:"
},
{
"code": "// Java program to illustrate// precision() Functionimport java.math.*;import java.io.*; class GFG { public static void main(String[] args) { // Creating a BigDecimal Object BigDecimal num; // Assigning value 0.1 + 0.1 + 0.1 to num num = new BigDecimal(\"0.1\") .add(new BigDecimal(\"0.1\")) .add(new BigDecimal(\"0.1\")); // Display the BigDecimal value and its precision System.out.println(\"The precision of \" + num + \" is \" + num.precision()); }}",
"e": 26085,
"s": 25544,
"text": null
},
{
"code": null,
"e": 26112,
"s": 26085,
"text": "The precision of 0.3 is 1\n"
},
{
"code": null,
"e": 26203,
"s": 26112,
"text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#precision()"
},
{
"code": null,
"e": 26219,
"s": 26203,
"text": "Java-BigDecimal"
},
{
"code": null,
"e": 26234,
"s": 26219,
"text": "Java-Functions"
},
{
"code": null,
"e": 26244,
"s": 26234,
"text": "java-math"
},
{
"code": null,
"e": 26262,
"s": 26244,
"text": "Java-math-package"
},
{
"code": null,
"e": 26267,
"s": 26262,
"text": "Java"
},
{
"code": null,
"e": 26272,
"s": 26267,
"text": "Java"
},
{
"code": null,
"e": 26370,
"s": 26272,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26379,
"s": 26370,
"text": "Comments"
},
{
"code": null,
"e": 26392,
"s": 26379,
"text": "Old Comments"
},
{
"code": null,
"e": 26422,
"s": 26392,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 26454,
"s": 26422,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 26505,
"s": 26454,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 26524,
"s": 26505,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 26542,
"s": 26524,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 26573,
"s": 26542,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 26605,
"s": 26573,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 26624,
"s": 26605,
"text": "LinkedList in Java"
},
{
"code": null,
"e": 26644,
"s": 26624,
"text": "Stack Class in Java"
}
] |
Exploring WhatsApp data. Using whatstk library to gain insights... | by Lucas Rodés-Guirao | Towards Data Science
|
Analyzing data can be fascinating, fun, and can give really interesting insights about a certain topic. When this data is connected to us or our context it becomes even more fascinating to analyze it, because this information was always close and present, yet it was never looked at from an analytic perspective.
To this end, our interaction with others via social networks is a good source of data. Nowadays we use social networks and the Internet on a daily basis for work or leisure purposes. These have turned out to be really helpful, by making some processes more efficient and even easing long-distance relationships. They have impacted the way we communicate, even re-shaping how we socially behave. Social Networks register, now more than ever, how and what we communicate.
In this regard, WhatsApp has emerged as one of the most widely used Apps to chat with others [1]. In this post, I will try to show how we can easily extract and analyze data from a WhatsApp chat using python.
The outline of this post is as follows
Exporting a WhatsApp chat from your phone
Using python library whatstk
Conclusions
The process of exporting your chat from your mobile phone is fairly easy. However, it changes depending on your mobile OS (see clip below).
Make sure to select the Without Media option when exporting the chat. Once generated, you can send it to yourself via mail, and download/save it onto your computer.
On Android, several files might be exported. We are only interested in the text file (i.e. txt extension file). On iOS, the chat is exported as a zip. Once you have downloaded it onto your computer, unzip it to obtain the txt.
whatstk is a GPLv3-licensed python library, which I have helped develop, providing tools to explore, analyze, and visualize WhatsApp chats. It works with multiple chat formats and uses pandas and plotly to process and visualize the data, respectively.
At the time of writing this post, the last stable version is 0.4.1. To install it, simply use pip.
$ pip install whatstk
Requires at least Python 3.7.
We will start by loading the chat into python using class WhatsAppChat and its method from_source. For this demo, I will be using a chat that I randomly generated using library tools. An excerpt is shown below:
[2019-04-16 02:09] +1 123 456 789: Et labore proident laboris do labore ex. [2019-04-16 03:01] Mary: Reprehenderit id aute consectetur aliquip nostrud culpa, fugiat ex deserunt magna, nostrud officia id aliquip in fugiat. 🇩🇰[2019-04-17 12:56] John: Amet magna officia ullamco pariatur ipsum cupidatat, laborum sint nostrud adipiscing sit. ✈[2019-04-17 13:30] Mary: Cillum aute et cupidatat ipsum, occaecat lorem sint tempor ullamco elit. 🏊🏻[2019-04-17 15:09] John: Eiusmod irure laboris dolore anim, velit velit proident qui commodo. [2019-04-17 17:55] Mary: Aute sed quis deserunt, veniam non veniam qui ipsum velit, aliqua sunt eu incididunt incididunt duis. 🤨
In your case, change the value of parameter filepath so it points to your exported chat. The chat is automatically parsed, loaded as a DataFrame and stored as class attribute df.
Note: If you cannot load your chat this way, you may have to specify the format of your chat header manually using hformat input argument. For our chat, it would be something like:
Firstly, we will obtain some basic information on the chat activity.
We can get the timestamp of the first and last sent messages, which give us an initial time context. Next, we obtain the number of messages sent by each user as well as the volume of messages sent in each of the days that the chat was active. To accomplish this, we exploit the tools given by pandas, specifically its groupby method.
init_date = chat.df.min()
end_date = chat.df.max()
print(f"First date is: {init_date}\nLast date is: {end_date}")
First date is: 2019-04-16 02:09:00
Last date is: 2020-06-13 00:00:00
chat.df.groupby('username').agg('count')
# Day with the most number of messages sent
chat.df.groupby(chat.df.date).agg(num_messages=('message', 'count')).sort_values(by='num_messages', ascending=False)
235 rows × 1 columns
We observe that the recorded chat started on the 16th April 2019 and ended on the 13th June 2020. Also, seems like Giuseppe and the 1st of July 2019 were quite active!
Now, let’s take a closer look at the number of messages sent by each user. For this, we use class FigureBuilder, which eases the process of generating and displaying plotly-based visualizations.
We use cumulative counts, which means that for a given day D, we count all the interventions from each user prior to it.
Although a user sends lots of messages it does not necessarily imply that they was the one sending more characters. To find out who was the one sending the most number of characters we can use function’s argument msg_len=False.
We will now take a look at the length of the messages sent by each user since some tend to send fewer but longer messages while others send several and short messages (that is me).
Finally, the last plot illustrates how users interact with one another. In particular, it shows a matrix, which counts the number of responses sent from a user A to a user B. The library makes the assumption that a message n is always a response to the previous message n-1. While this might be far from being true it still manages to capture some sort of reality.
In this post, we have seen how we can load a WhatsApp chat in python as a DataFrame and visualize relevant insights with plotly. The visualizations have been generated using whatstk tools, but, once the chat is loaded, the possibilities are endless.
I personally find this really interesting, as I end up working with a unique, dynamic, and accessible dataset each time I explore and analyze a WhatsApp chat.
You can check the code from this post here.
July 30, 2020: Article published. whatstk version v0.3.1
May 27, 2021: Fix broken links. whatstk version v0.4.1
[1] Birgit Bucher, WhatsApp, WeChat and Facebook Messenger Apps — Global Messenger Usage, Penetration and Statistics, Messenger People 2020, blog post
|
[
{
"code": null,
"e": 485,
"s": 172,
"text": "Analyzing data can be fascinating, fun, and can give really interesting insights about a certain topic. When this data is connected to us or our context it becomes even more fascinating to analyze it, because this information was always close and present, yet it was never looked at from an analytic perspective."
},
{
"code": null,
"e": 955,
"s": 485,
"text": "To this end, our interaction with others via social networks is a good source of data. Nowadays we use social networks and the Internet on a daily basis for work or leisure purposes. These have turned out to be really helpful, by making some processes more efficient and even easing long-distance relationships. They have impacted the way we communicate, even re-shaping how we socially behave. Social Networks register, now more than ever, how and what we communicate."
},
{
"code": null,
"e": 1164,
"s": 955,
"text": "In this regard, WhatsApp has emerged as one of the most widely used Apps to chat with others [1]. In this post, I will try to show how we can easily extract and analyze data from a WhatsApp chat using python."
},
{
"code": null,
"e": 1203,
"s": 1164,
"text": "The outline of this post is as follows"
},
{
"code": null,
"e": 1245,
"s": 1203,
"text": "Exporting a WhatsApp chat from your phone"
},
{
"code": null,
"e": 1274,
"s": 1245,
"text": "Using python library whatstk"
},
{
"code": null,
"e": 1286,
"s": 1274,
"text": "Conclusions"
},
{
"code": null,
"e": 1426,
"s": 1286,
"text": "The process of exporting your chat from your mobile phone is fairly easy. However, it changes depending on your mobile OS (see clip below)."
},
{
"code": null,
"e": 1591,
"s": 1426,
"text": "Make sure to select the Without Media option when exporting the chat. Once generated, you can send it to yourself via mail, and download/save it onto your computer."
},
{
"code": null,
"e": 1818,
"s": 1591,
"text": "On Android, several files might be exported. We are only interested in the text file (i.e. txt extension file). On iOS, the chat is exported as a zip. Once you have downloaded it onto your computer, unzip it to obtain the txt."
},
{
"code": null,
"e": 2070,
"s": 1818,
"text": "whatstk is a GPLv3-licensed python library, which I have helped develop, providing tools to explore, analyze, and visualize WhatsApp chats. It works with multiple chat formats and uses pandas and plotly to process and visualize the data, respectively."
},
{
"code": null,
"e": 2169,
"s": 2070,
"text": "At the time of writing this post, the last stable version is 0.4.1. To install it, simply use pip."
},
{
"code": null,
"e": 2191,
"s": 2169,
"text": "$ pip install whatstk"
},
{
"code": null,
"e": 2221,
"s": 2191,
"text": "Requires at least Python 3.7."
},
{
"code": null,
"e": 2432,
"s": 2221,
"text": "We will start by loading the chat into python using class WhatsAppChat and its method from_source. For this demo, I will be using a chat that I randomly generated using library tools. An excerpt is shown below:"
},
{
"code": null,
"e": 3095,
"s": 2432,
"text": "[2019-04-16 02:09] +1 123 456 789: Et labore proident laboris do labore ex. [2019-04-16 03:01] Mary: Reprehenderit id aute consectetur aliquip nostrud culpa, fugiat ex deserunt magna, nostrud officia id aliquip in fugiat. 🇩🇰[2019-04-17 12:56] John: Amet magna officia ullamco pariatur ipsum cupidatat, laborum sint nostrud adipiscing sit. ✈[2019-04-17 13:30] Mary: Cillum aute et cupidatat ipsum, occaecat lorem sint tempor ullamco elit. 🏊🏻[2019-04-17 15:09] John: Eiusmod irure laboris dolore anim, velit velit proident qui commodo. [2019-04-17 17:55] Mary: Aute sed quis deserunt, veniam non veniam qui ipsum velit, aliqua sunt eu incididunt incididunt duis. 🤨"
},
{
"code": null,
"e": 3274,
"s": 3095,
"text": "In your case, change the value of parameter filepath so it points to your exported chat. The chat is automatically parsed, loaded as a DataFrame and stored as class attribute df."
},
{
"code": null,
"e": 3455,
"s": 3274,
"text": "Note: If you cannot load your chat this way, you may have to specify the format of your chat header manually using hformat input argument. For our chat, it would be something like:"
},
{
"code": null,
"e": 3524,
"s": 3455,
"text": "Firstly, we will obtain some basic information on the chat activity."
},
{
"code": null,
"e": 3858,
"s": 3524,
"text": "We can get the timestamp of the first and last sent messages, which give us an initial time context. Next, we obtain the number of messages sent by each user as well as the volume of messages sent in each of the days that the chat was active. To accomplish this, we exploit the tools given by pandas, specifically its groupby method."
},
{
"code": null,
"e": 3973,
"s": 3858,
"text": "init_date = chat.df.min()\nend_date = chat.df.max()\nprint(f\"First date is: {init_date}\\nLast date is: {end_date}\")\n"
},
{
"code": null,
"e": 4043,
"s": 3973,
"text": "First date is: 2019-04-16 02:09:00\nLast date is: 2020-06-13 00:00:00\n"
},
{
"code": null,
"e": 4085,
"s": 4043,
"text": "chat.df.groupby('username').agg('count')\n"
},
{
"code": null,
"e": 4247,
"s": 4085,
"text": "# Day with the most number of messages sent\nchat.df.groupby(chat.df.date).agg(num_messages=('message', 'count')).sort_values(by='num_messages', ascending=False)\n"
},
{
"code": null,
"e": 4268,
"s": 4247,
"text": "235 rows × 1 columns"
},
{
"code": null,
"e": 4439,
"s": 4271,
"text": "We observe that the recorded chat started on the 16th April 2019 and ended on the 13th June 2020. Also, seems like Giuseppe and the 1st of July 2019 were quite active!"
},
{
"code": null,
"e": 4634,
"s": 4439,
"text": "Now, let’s take a closer look at the number of messages sent by each user. For this, we use class FigureBuilder, which eases the process of generating and displaying plotly-based visualizations."
},
{
"code": null,
"e": 4755,
"s": 4634,
"text": "We use cumulative counts, which means that for a given day D, we count all the interventions from each user prior to it."
},
{
"code": null,
"e": 4983,
"s": 4755,
"text": "Although a user sends lots of messages it does not necessarily imply that they was the one sending more characters. To find out who was the one sending the most number of characters we can use function’s argument msg_len=False."
},
{
"code": null,
"e": 5164,
"s": 4983,
"text": "We will now take a look at the length of the messages sent by each user since some tend to send fewer but longer messages while others send several and short messages (that is me)."
},
{
"code": null,
"e": 5529,
"s": 5164,
"text": "Finally, the last plot illustrates how users interact with one another. In particular, it shows a matrix, which counts the number of responses sent from a user A to a user B. The library makes the assumption that a message n is always a response to the previous message n-1. While this might be far from being true it still manages to capture some sort of reality."
},
{
"code": null,
"e": 5779,
"s": 5529,
"text": "In this post, we have seen how we can load a WhatsApp chat in python as a DataFrame and visualize relevant insights with plotly. The visualizations have been generated using whatstk tools, but, once the chat is loaded, the possibilities are endless."
},
{
"code": null,
"e": 5938,
"s": 5779,
"text": "I personally find this really interesting, as I end up working with a unique, dynamic, and accessible dataset each time I explore and analyze a WhatsApp chat."
},
{
"code": null,
"e": 5982,
"s": 5938,
"text": "You can check the code from this post here."
},
{
"code": null,
"e": 6039,
"s": 5982,
"text": "July 30, 2020: Article published. whatstk version v0.3.1"
},
{
"code": null,
"e": 6094,
"s": 6039,
"text": "May 27, 2021: Fix broken links. whatstk version v0.4.1"
}
] |
Controlling the Position of Table Caption using CSS
|
The CSS caption-side property is used to vertically position the table caption box. It can take top and bottom as values. By default, table caption is placed at the top.
The syntax of CSS list-style property is as follows−
Selector {
caption-side: /*value*/
}
The following examples illustrate the CSS caption-side property.
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
table * {
border: ridge skyblue;
padding: 0.5rem;
}
table {
margin: 20px;
box-shadow: 0 0 6px 3px indianred;
empty-cells: show;
}
caption {
border-top-style: none;
caption-side: bottom;
border-color: darkkhaki;
border-radius: 50%;
}
</style>
</head>
<body>
<table id="demo">
<caption>Demo</caption>
<tr>
<th colspan="3">Table</th>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
</table>
</body>
</html>
This gives the following output −
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
table {
margin: auto;
border: double black 13px;
border-radius: 6px;
}
td, th {
border-left: 1px solid black;
border-top: 1px solid black;
}
th {
background-color: lightblue;
border-top: none;
}
td:first-child, th:first-child {
border-left: none;
}
caption {
margin-top: 3px;
background-color: purple;
caption-side: bottom;
color: white;
border-radius: 20%;
}
</style>
</head>
<body>
<h2>Demo Table</h2>
<table>
<caption>Demo</caption>
<tr>
<th colspan="4">Table</th>
</tr>
<tr>
<td>One...</td>
<td>Two...</td>
<td>Three</td>
<td>Four</td>
</tr>
<tr>
<td>Five</td>
<td>Six</td>
<td>Seven</td>
<td>Eight</td>
</tr>
</table>
</body>
</html>
This gives the following output −
|
[
{
"code": null,
"e": 1232,
"s": 1062,
"text": "The CSS caption-side property is used to vertically position the table caption box. It can take top and bottom as values. By default, table caption is placed at the top."
},
{
"code": null,
"e": 1285,
"s": 1232,
"text": "The syntax of CSS list-style property is as follows−"
},
{
"code": null,
"e": 1325,
"s": 1285,
"text": "Selector {\n caption-side: /*value*/\n}"
},
{
"code": null,
"e": 1390,
"s": 1325,
"text": "The following examples illustrate the CSS caption-side property."
},
{
"code": null,
"e": 1401,
"s": 1390,
"text": " Live Demo"
},
{
"code": null,
"e": 1931,
"s": 1401,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\ntable * {\n border: ridge skyblue;\n padding: 0.5rem;\n}\ntable {\n margin: 20px;\n box-shadow: 0 0 6px 3px indianred;\n empty-cells: show;\n}\ncaption {\n border-top-style: none;\n caption-side: bottom;\n border-color: darkkhaki;\n border-radius: 50%;\n}\n</style>\n</head>\n<body>\n<table id=\"demo\">\n<caption>Demo</caption>\n<tr>\n<th colspan=\"3\">Table</th>\n</tr>\n<tr>\n<td></td>\n<td></td>\n</tr>\n<tr>\n<td></td>\n<td></td>\n<td></td>\n</tr>\n<tr>\n<td></td>\n<td></td>\n</tr>\n</table>\n</body>\n</html>"
},
{
"code": null,
"e": 1965,
"s": 1931,
"text": "This gives the following output −"
},
{
"code": null,
"e": 1976,
"s": 1965,
"text": " Live Demo"
},
{
"code": null,
"e": 2692,
"s": 1976,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\ntable {\n margin: auto;\n border: double black 13px;\n border-radius: 6px;\n}\ntd, th {\n border-left: 1px solid black;\n border-top: 1px solid black;\n}\nth {\n background-color: lightblue;\n border-top: none;\n}\ntd:first-child, th:first-child {\n border-left: none;\n}\ncaption {\n margin-top: 3px;\n background-color: purple;\n caption-side: bottom;\n color: white;\n border-radius: 20%;\n}\n</style>\n</head>\n<body>\n<h2>Demo Table</h2>\n<table>\n<caption>Demo</caption>\n<tr>\n<th colspan=\"4\">Table</th>\n</tr>\n<tr>\n<td>One...</td>\n<td>Two...</td>\n<td>Three</td>\n<td>Four</td>\n</tr>\n<tr>\n<td>Five</td>\n<td>Six</td>\n<td>Seven</td>\n<td>Eight</td>\n</tr>\n</table>\n</body>\n</html>"
},
{
"code": null,
"e": 2726,
"s": 2692,
"text": "This gives the following output −"
}
] |
\arcsin - Tex Command
|
\arcsin - Used to draw arcsin.
{ \arcsin(x) }
\arcsin command is used to draw arcsin.
\arcsin(x)
arcsin(x)
\arcsin(x)
arcsin(x)
\arcsin(x)
14 Lectures
52 mins
Ashraf Said
11 Lectures
1 hours
Ashraf Said
9 Lectures
1 hours
Emenwa Global, Ejike IfeanyiChukwu
29 Lectures
2.5 hours
Mohammad Nauman
14 Lectures
1 hours
Daniel Stern
15 Lectures
47 mins
Nishant Kumar
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 8017,
"s": 7986,
"text": "\\arcsin - Used to draw arcsin."
},
{
"code": null,
"e": 8032,
"s": 8017,
"text": "{ \\arcsin(x) }"
},
{
"code": null,
"e": 8072,
"s": 8032,
"text": "\\arcsin command is used to draw arcsin."
},
{
"code": null,
"e": 8100,
"s": 8072,
"text": "\n\\arcsin(x) \n\narcsin(x)\n\n\n"
},
{
"code": null,
"e": 8126,
"s": 8100,
"text": "\\arcsin(x) \n\narcsin(x)\n\n"
},
{
"code": null,
"e": 8138,
"s": 8126,
"text": "\\arcsin(x) "
},
{
"code": null,
"e": 8170,
"s": 8138,
"text": "\n 14 Lectures \n 52 mins\n"
},
{
"code": null,
"e": 8183,
"s": 8170,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8216,
"s": 8183,
"text": "\n 11 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8229,
"s": 8216,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8261,
"s": 8229,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8297,
"s": 8261,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 8332,
"s": 8297,
"text": "\n 29 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8349,
"s": 8332,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 8382,
"s": 8349,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8396,
"s": 8382,
"text": " Daniel Stern"
},
{
"code": null,
"e": 8428,
"s": 8396,
"text": "\n 15 Lectures \n 47 mins\n"
},
{
"code": null,
"e": 8443,
"s": 8428,
"text": " Nishant Kumar"
},
{
"code": null,
"e": 8450,
"s": 8443,
"text": " Print"
},
{
"code": null,
"e": 8461,
"s": 8450,
"text": " Add Notes"
}
] |
Matplotlib.pyplot.disconnect() in Python - GeeksforGeeks
|
21 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface.
The disconnect() function in pyplot module of matplotlib library is used to disconnect the callback with id cid.
Syntax: matplotlib.pyplot.disconnect(cid)
Parameters: This method accept the following parameters that are described below:
cid: This parameter is used to disconnect the callback.
Below examples illustrate the matplotlib.pyplot.disconnect() function in matplotlib.pyplot:
Example #1:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt fig, ax = plt.subplots()ax.plot(np.random.rand(10)) def onclick(event): print('% s click: button =% d, x =% d, y =% d,\ xdata =% f, ydata =% f' % ('double' if event.dblclick else 'single', event.button, event.x, event.y, event.xdata, event.ydata)) cid = fig.canvas.mpl_connect('button_press_event', onclick)fig.canvas.mpl_disconnect(cid) plt.suptitle('matplotlib.pyplot.disconnect()\function Example', fontweight ="bold") plt.show()
Output:
Example #2:
# Implementation of matplotlib functionfrom matplotlib.backend_bases import MouseButtonimport matplotlib.pyplot as pltimport numpy as np t = np.arange(0.0, 1.0, 0.01)s = np.sin(2 * np.pi * t)fig, ax = plt.subplots()ax.plot(t, s) def gfg1(event): # get the x and y pixel coords x, y = event.x, event.y if event.inaxes: # the axes instance ax = event.inaxes print('Coordinates : % f and\ % f' % (event.xdata, event.ydata)) def gfg2(event): if event.button is MouseButton.LEFT: print('Successfully disconnected') plt.disconnect(binding_id) binding_id = plt.connect('motion_notify_event', gfg1) plt.connect('button_press_event', gfg2) plt.suptitle('matplotlib.pyplot.disconnect()\function Example', fontweight ="bold")plt.show()
Output:Figure shown
Background result after click on figure
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
Python Classes and Objects
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Pandas dataframe.groupby()
Create a directory in Python
|
[
{
"code": null,
"e": 24212,
"s": 24184,
"text": "\n21 Apr, 2020"
},
{
"code": null,
"e": 24407,
"s": 24212,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface."
},
{
"code": null,
"e": 24520,
"s": 24407,
"text": "The disconnect() function in pyplot module of matplotlib library is used to disconnect the callback with id cid."
},
{
"code": null,
"e": 24562,
"s": 24520,
"text": "Syntax: matplotlib.pyplot.disconnect(cid)"
},
{
"code": null,
"e": 24644,
"s": 24562,
"text": "Parameters: This method accept the following parameters that are described below:"
},
{
"code": null,
"e": 24700,
"s": 24644,
"text": "cid: This parameter is used to disconnect the callback."
},
{
"code": null,
"e": 24792,
"s": 24700,
"text": "Below examples illustrate the matplotlib.pyplot.disconnect() function in matplotlib.pyplot:"
},
{
"code": null,
"e": 24804,
"s": 24792,
"text": "Example #1:"
},
{
"code": "# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt fig, ax = plt.subplots()ax.plot(np.random.rand(10)) def onclick(event): print('% s click: button =% d, x =% d, y =% d,\\ xdata =% f, ydata =% f' % ('double' if event.dblclick else 'single', event.button, event.x, event.y, event.xdata, event.ydata)) cid = fig.canvas.mpl_connect('button_press_event', onclick)fig.canvas.mpl_disconnect(cid) plt.suptitle('matplotlib.pyplot.disconnect()\\function Example', fontweight =\"bold\") plt.show()",
"e": 25426,
"s": 24804,
"text": null
},
{
"code": null,
"e": 25434,
"s": 25426,
"text": "Output:"
},
{
"code": null,
"e": 25446,
"s": 25434,
"text": "Example #2:"
},
{
"code": "# Implementation of matplotlib functionfrom matplotlib.backend_bases import MouseButtonimport matplotlib.pyplot as pltimport numpy as np t = np.arange(0.0, 1.0, 0.01)s = np.sin(2 * np.pi * t)fig, ax = plt.subplots()ax.plot(t, s) def gfg1(event): # get the x and y pixel coords x, y = event.x, event.y if event.inaxes: # the axes instance ax = event.inaxes print('Coordinates : % f and\\ % f' % (event.xdata, event.ydata)) def gfg2(event): if event.button is MouseButton.LEFT: print('Successfully disconnected') plt.disconnect(binding_id) binding_id = plt.connect('motion_notify_event', gfg1) plt.connect('button_press_event', gfg2) plt.suptitle('matplotlib.pyplot.disconnect()\\function Example', fontweight =\"bold\")plt.show()",
"e": 26284,
"s": 25446,
"text": null
},
{
"code": null,
"e": 26304,
"s": 26284,
"text": "Output:Figure shown"
},
{
"code": null,
"e": 26344,
"s": 26304,
"text": "Background result after click on figure"
},
{
"code": null,
"e": 26362,
"s": 26344,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 26369,
"s": 26362,
"text": "Python"
},
{
"code": null,
"e": 26467,
"s": 26369,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26476,
"s": 26467,
"text": "Comments"
},
{
"code": null,
"e": 26489,
"s": 26476,
"text": "Old Comments"
},
{
"code": null,
"e": 26521,
"s": 26489,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26577,
"s": 26521,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26598,
"s": 26577,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 26637,
"s": 26598,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26679,
"s": 26637,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26706,
"s": 26679,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 26737,
"s": 26706,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26779,
"s": 26737,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26815,
"s": 26779,
"text": "Python | Pandas dataframe.groupby()"
}
] |
A Very Precise & Fast Way to Pull Google Trends Data Automatically | by JZ Lu | Towards Data Science
|
A one-stop-shop script to automatically pull google trends by exact keywords using Pytrends
COVID-19 has provided a boon for “Google Trends” usage in the U.S. (see chart below). After all, it’s a free publicly available tool that provides access to actual search requests across google search engine. More companies have leveraged Google Trends to gain insights on category trend, consumer top searched queries, competitors’ performance amid the “black swan” pandemic event.
Each Google Trends request consists of 5 unique parameters:
KEYWORDS: Your keywords go here. You can use the prompt under the drop-down box to select the correct keywords.
COUNTRY: Companies with an international footprint could use this function to get trends across countries.
DATE INTERVAL: Choose the time range of the trend. Please note that google trends data is normalized based on location and time. Thus, different time ranges will yield various results.
CATEGORY: Indicate what categories you prefer to search the keywords.
SEARCH TYPE: Select the source of the search, i.e. Google Search, Image Search, News Search, Google Shopping, and YouTube Search.
CHALLENGES:
There are two main challenges to pull Google trends data in scale.
1. Individual keyword by keyword manually pulling is time-consuming.
Although Google Trends provides the “Compare” function to compare keywords, the downside is that it scales the results from 0 to 100 based on the most popular term entered. The less popular keyword will lose sensitivity quickly if you compare it with a popular one. For example, if you compare “Nike” brand with “Supreme” brand, you will basically get a flat line for “Supreme”. In this situation, you’ll get big errors when reporting “Supreme” search growth trend. Thus, it is suggested to pull “Nike” trend and “Supreme” trend individually and separately.
You can still afford the time until you have too many keywords to pull. E.g. when to compare 50 apparel and footwear brands, you need to download 50 excels and combine them together.
2. Current available automation python methods don’t query exact keywords, meaning they’re not accurate.
There are many available methods to pull google trend data using python. However, none of them builds automatic codes that could pull EXACT KEYWORDS. It’s not unusual that words often have multiple meanings. For example, “Patagonia” could either be a clothing company or a region in South American. Simply search “Patagonia” will give us ambiguous results as it contains both search terms. We need to make sure we search the right keywords.
GOAL:
The goal is to provide a solution to pull google trends data for multiple keywords exactly, individually, and automatically.
Specifically, we’ll pull google trends data for six apparel/footwear brands (Nike, Adidas, Under Armour, Zara, H&M, Louis Vuitton) in three countries (US, UK, Germany). Using Python, there are four steps to achieve this:
Step 1: Install pytrends API
Step 2: Get exact keywords
Step 3: Pull Google trends data by exact keywords by country
Step 4: Visualize Google trends
First of all, we need to install that package called “pytrends”, which is designed to pull google trends using python. Simply execute the following code from your Terminal. You could find the comprehensive documentation of the pytrends API here.
pip install pytrends
We will then import the necessary packages.
import pandas as pdimport pytrendsfrom pytrends.request import TrendReqpytrend = TrendReq()
As discussed earlier, we need to be precise on the keywords to avoid ambiguity. Pytrends provides a function called pytrend.suggestions that could return several suggestions for a keyword. Usually, the first suggestion is the most popular one. “mid” column contains those exact keywords we’d like to search.
KEYWORDS=['Nike','Adidas','Under Armour','Zara','H&M','Louis Vuitton'] KEYWORDS_CODES=[pytrend.suggestions(keyword=i)[0] for i in KEYWORDS] df_CODES= pd.DataFrame(KEYWORDS_CODES)df_CODES
Next, we’ll set those 5 parameters.
EXACT_KEYWORDS=df_CODES['mid'].to_list()DATE_INTERVAL='2020-01-01 2020-05-01'COUNTRY=["US","GB","DE"] #Use this link for iso country codeCATEGORY=0 # Use this link to select categoriesSEARCH_TYPE='' #default is 'web searches',others include 'images','news','youtube','froogle' (google shopping)
Then, we’ll write codes to pull google trends data by exact keywords by country using the above parameters.
Individual_EXACT_KEYWORD = list(zip(*[iter(EXACT_KEYWORDS)]*1))Individual_EXACT_KEYWORD = [list(x) for x in Individual_EXACT_KEYWORD]dicti = {}i = 1for Country in COUNTRY: for keyword in Individual_EXACT_KEYWORD: pytrend.build_payload(kw_list=keyword, timeframe = DATE_INTERVAL, geo = Country, cat=CATEGORY, gprop=SEARCH_TYPE) dicti[i] = pytrend.interest_over_time() i+=1df_trends = pd.concat(dicti, axis=1)
And we will do some cleaning work and change those exact keywords back to readable brand names.
df_trends.columns = df_trends.columns.droplevel(0) #drop outside headerdf_trends = df_trends.drop('isPartial', axis = 1) #drop "isPartial"df_trends.reset_index(level=0,inplace=True) #reset_indexdf_trends.columns=['date','Nike-US','Adidas-US','Under Armour-US','Zara-US','H&M-US','Louis Vuitton-US','Nike-UK','Adidas-UK','Under Armour-UK','Zara-UK','H&M-UK','Louis Vuitton-UK','Nike-Germany','Adidas-Germany','Under Armour-Germany','Zara-Germany','H&M-Germany','Louis Vuitton-Germany'] #change column names
In the blink of an eye, we get our google trends data. Finally, let’s visualize Louis Vuitton's google trends across countries. As we could see, Louis Vuitton clearly gets hard hit by COVID-19, just like many other brands and industries.
import seaborn as snssns.set(color_codes=True)dx = df_trends.plot(figsize = (12,8),x="date", y=['Louis Vuitton-US','Louis Vuitton-UK','Louis Vuitton-Germany'], kind="line", title = "Louis Vuitton Google Trends")dx.set_xlabel('Date')dx.set_ylabel('Trends Index')dx.tick_params(axis='both', which='both', labelsize=10)
Google Trends tool usages see surging growth as companies closely monitor shifting consumer behavior during COVID -19. To help with this, we build a light application to pull Google Trends data precisely and automatically.
Finally, stay positive, thanks for reading!
|
[
{
"code": null,
"e": 264,
"s": 172,
"text": "A one-stop-shop script to automatically pull google trends by exact keywords using Pytrends"
},
{
"code": null,
"e": 647,
"s": 264,
"text": "COVID-19 has provided a boon for “Google Trends” usage in the U.S. (see chart below). After all, it’s a free publicly available tool that provides access to actual search requests across google search engine. More companies have leveraged Google Trends to gain insights on category trend, consumer top searched queries, competitors’ performance amid the “black swan” pandemic event."
},
{
"code": null,
"e": 707,
"s": 647,
"text": "Each Google Trends request consists of 5 unique parameters:"
},
{
"code": null,
"e": 819,
"s": 707,
"text": "KEYWORDS: Your keywords go here. You can use the prompt under the drop-down box to select the correct keywords."
},
{
"code": null,
"e": 926,
"s": 819,
"text": "COUNTRY: Companies with an international footprint could use this function to get trends across countries."
},
{
"code": null,
"e": 1111,
"s": 926,
"text": "DATE INTERVAL: Choose the time range of the trend. Please note that google trends data is normalized based on location and time. Thus, different time ranges will yield various results."
},
{
"code": null,
"e": 1181,
"s": 1111,
"text": "CATEGORY: Indicate what categories you prefer to search the keywords."
},
{
"code": null,
"e": 1311,
"s": 1181,
"text": "SEARCH TYPE: Select the source of the search, i.e. Google Search, Image Search, News Search, Google Shopping, and YouTube Search."
},
{
"code": null,
"e": 1323,
"s": 1311,
"text": "CHALLENGES:"
},
{
"code": null,
"e": 1390,
"s": 1323,
"text": "There are two main challenges to pull Google trends data in scale."
},
{
"code": null,
"e": 1459,
"s": 1390,
"text": "1. Individual keyword by keyword manually pulling is time-consuming."
},
{
"code": null,
"e": 2017,
"s": 1459,
"text": "Although Google Trends provides the “Compare” function to compare keywords, the downside is that it scales the results from 0 to 100 based on the most popular term entered. The less popular keyword will lose sensitivity quickly if you compare it with a popular one. For example, if you compare “Nike” brand with “Supreme” brand, you will basically get a flat line for “Supreme”. In this situation, you’ll get big errors when reporting “Supreme” search growth trend. Thus, it is suggested to pull “Nike” trend and “Supreme” trend individually and separately."
},
{
"code": null,
"e": 2200,
"s": 2017,
"text": "You can still afford the time until you have too many keywords to pull. E.g. when to compare 50 apparel and footwear brands, you need to download 50 excels and combine them together."
},
{
"code": null,
"e": 2305,
"s": 2200,
"text": "2. Current available automation python methods don’t query exact keywords, meaning they’re not accurate."
},
{
"code": null,
"e": 2746,
"s": 2305,
"text": "There are many available methods to pull google trend data using python. However, none of them builds automatic codes that could pull EXACT KEYWORDS. It’s not unusual that words often have multiple meanings. For example, “Patagonia” could either be a clothing company or a region in South American. Simply search “Patagonia” will give us ambiguous results as it contains both search terms. We need to make sure we search the right keywords."
},
{
"code": null,
"e": 2752,
"s": 2746,
"text": "GOAL:"
},
{
"code": null,
"e": 2877,
"s": 2752,
"text": "The goal is to provide a solution to pull google trends data for multiple keywords exactly, individually, and automatically."
},
{
"code": null,
"e": 3098,
"s": 2877,
"text": "Specifically, we’ll pull google trends data for six apparel/footwear brands (Nike, Adidas, Under Armour, Zara, H&M, Louis Vuitton) in three countries (US, UK, Germany). Using Python, there are four steps to achieve this:"
},
{
"code": null,
"e": 3127,
"s": 3098,
"text": "Step 1: Install pytrends API"
},
{
"code": null,
"e": 3154,
"s": 3127,
"text": "Step 2: Get exact keywords"
},
{
"code": null,
"e": 3215,
"s": 3154,
"text": "Step 3: Pull Google trends data by exact keywords by country"
},
{
"code": null,
"e": 3247,
"s": 3215,
"text": "Step 4: Visualize Google trends"
},
{
"code": null,
"e": 3493,
"s": 3247,
"text": "First of all, we need to install that package called “pytrends”, which is designed to pull google trends using python. Simply execute the following code from your Terminal. You could find the comprehensive documentation of the pytrends API here."
},
{
"code": null,
"e": 3514,
"s": 3493,
"text": "pip install pytrends"
},
{
"code": null,
"e": 3558,
"s": 3514,
"text": "We will then import the necessary packages."
},
{
"code": null,
"e": 3650,
"s": 3558,
"text": "import pandas as pdimport pytrendsfrom pytrends.request import TrendReqpytrend = TrendReq()"
},
{
"code": null,
"e": 3958,
"s": 3650,
"text": "As discussed earlier, we need to be precise on the keywords to avoid ambiguity. Pytrends provides a function called pytrend.suggestions that could return several suggestions for a keyword. Usually, the first suggestion is the most popular one. “mid” column contains those exact keywords we’d like to search."
},
{
"code": null,
"e": 4145,
"s": 3958,
"text": "KEYWORDS=['Nike','Adidas','Under Armour','Zara','H&M','Louis Vuitton'] KEYWORDS_CODES=[pytrend.suggestions(keyword=i)[0] for i in KEYWORDS] df_CODES= pd.DataFrame(KEYWORDS_CODES)df_CODES"
},
{
"code": null,
"e": 4181,
"s": 4145,
"text": "Next, we’ll set those 5 parameters."
},
{
"code": null,
"e": 4476,
"s": 4181,
"text": "EXACT_KEYWORDS=df_CODES['mid'].to_list()DATE_INTERVAL='2020-01-01 2020-05-01'COUNTRY=[\"US\",\"GB\",\"DE\"] #Use this link for iso country codeCATEGORY=0 # Use this link to select categoriesSEARCH_TYPE='' #default is 'web searches',others include 'images','news','youtube','froogle' (google shopping)"
},
{
"code": null,
"e": 4584,
"s": 4476,
"text": "Then, we’ll write codes to pull google trends data by exact keywords by country using the above parameters."
},
{
"code": null,
"e": 5136,
"s": 4584,
"text": "Individual_EXACT_KEYWORD = list(zip(*[iter(EXACT_KEYWORDS)]*1))Individual_EXACT_KEYWORD = [list(x) for x in Individual_EXACT_KEYWORD]dicti = {}i = 1for Country in COUNTRY: for keyword in Individual_EXACT_KEYWORD: pytrend.build_payload(kw_list=keyword, timeframe = DATE_INTERVAL, geo = Country, cat=CATEGORY, gprop=SEARCH_TYPE) dicti[i] = pytrend.interest_over_time() i+=1df_trends = pd.concat(dicti, axis=1)"
},
{
"code": null,
"e": 5232,
"s": 5136,
"text": "And we will do some cleaning work and change those exact keywords back to readable brand names."
},
{
"code": null,
"e": 5738,
"s": 5232,
"text": "df_trends.columns = df_trends.columns.droplevel(0) #drop outside headerdf_trends = df_trends.drop('isPartial', axis = 1) #drop \"isPartial\"df_trends.reset_index(level=0,inplace=True) #reset_indexdf_trends.columns=['date','Nike-US','Adidas-US','Under Armour-US','Zara-US','H&M-US','Louis Vuitton-US','Nike-UK','Adidas-UK','Under Armour-UK','Zara-UK','H&M-UK','Louis Vuitton-UK','Nike-Germany','Adidas-Germany','Under Armour-Germany','Zara-Germany','H&M-Germany','Louis Vuitton-Germany'] #change column names"
},
{
"code": null,
"e": 5976,
"s": 5738,
"text": "In the blink of an eye, we get our google trends data. Finally, let’s visualize Louis Vuitton's google trends across countries. As we could see, Louis Vuitton clearly gets hard hit by COVID-19, just like many other brands and industries."
},
{
"code": null,
"e": 6293,
"s": 5976,
"text": "import seaborn as snssns.set(color_codes=True)dx = df_trends.plot(figsize = (12,8),x=\"date\", y=['Louis Vuitton-US','Louis Vuitton-UK','Louis Vuitton-Germany'], kind=\"line\", title = \"Louis Vuitton Google Trends\")dx.set_xlabel('Date')dx.set_ylabel('Trends Index')dx.tick_params(axis='both', which='both', labelsize=10)"
},
{
"code": null,
"e": 6516,
"s": 6293,
"text": "Google Trends tool usages see surging growth as companies closely monitor shifting consumer behavior during COVID -19. To help with this, we build a light application to pull Google Trends data precisely and automatically."
}
] |
Parallel Programming in Python with Message Passing Interface (mpi4py) | by Konrad Hafen | Towards Data Science
|
Did you know you can write parallel Python code that will run on your laptop and on a super computer? You can, and it’s not as difficult as you might expect. If you already write code for asynchronous parallelization then you won’t even have to do much restructuring.
High Performance Computing (HPC) distributes pieces of jobs across thousands of CPUs (in contrast to the 4–8 on your laptop) to achieve dramatic performance increases. CPUs communicate and pass data using Message Passing Interface (MPI). The same principle is used on your laptop when you write code that distributes pieces of jobs to multiple cores to run simultaneously. This article will demonstrate how to use MPI with Python to write code that can be run in parallel on your laptop, or a super computer.
You will need to install a MPI application for your operating system. For Windows users I recommend installing MPI directly from Microsoft. For Mac and Linux users I suggest installing OpenMPI. Windows users must add the the MPI installation directory to the Path variable.
To test your install, type mpiexec (Windows) or mpirun (Mac/Linux, but check the install docs) in a terminal window and press ‘Enter’. This will generate a message with usage information if you have installed properly. While you’re at the terminal, also type python and press ‘Enter’. This should start an interactive Python session. If it does not you need to install or configure Python.
mpi4py is a Python module that allows you to interact with your MPI application (mpiexec or mpirun). Install it the same as any Python module (pip install mpi4py, etc.).
Once you have MPI and mpi4py installed you’re ready to get started!
Running a Python script with MPI is a little different than you’re likely used to. With mpiexec and mpirun each line of code will be run by each processor, unless specified otherwise. Let’s make a ‘hello world’ example to demonstrate the MPI basics.
Create a new python script (.py file). Import mpi4py and use MPI.COMM_WORLD to get information about all the processors available to run your script (this number is passed to the MPI app when calling the script). COMM_WORLD gives access to the number of processes (ranks/processors) available to distribute work across, and information about each processor. size gives the total number of ranks, or processors, allocated to run our script. rank gives the identifier of the processor currently executing the code. The print statement below will print once for each processor used in the job.
Execute this script by opening a terminal, navigating to the directory containing the script, and executing the command:
mpiexec -n 4 python mpi_hello_world.py
n -4 specifies the number of processors to use. In this instance I’m using 4 processors, which means the print statement will execute 4 times. Notice that the ranks don’t print out in numerical order, so you’ll need to make sure your code can run asynchronously. In other words, it’s not possible to know which processor will start or complete first, so your code will need to be structured in a way that results don’t depend on values that may be calculated on a different processor.
Hello world from rank 2 of 4Hello world from rank 3 of 4Hello world from rank 0 of 4Hello world from rank 1 of 4
Now, update the script so that it prints out different messages for different ranks. This is done using logical statements (if, elif, else).
We now get different messages for ranks 0 and 1.
First rankHello world from rank 0 of 4Not first or second rankHello world from rank 2 of 4Not first or second rankHello world from rank 3 of 4Second rankHello world from rank 1 of 4
The send and recv functions send data from one processor to another and receive data from a processor, respectively. Many data types can be passed with these functions. The example is going to focus specifically on sending and receiving numpy arrays. The Send and Recv functions (notice capital ‘S’ and ‘R’) are specific to numpy arrays. For examples of basic send and recv see the mpi4py documentation.
In a previous article I demonstrated parallel processing with the multiprocessing module. We’ll use the same function in this example.
towardsdatascience.com
Create two new Python scripts in the same directory. Name one my_function.py and the other mpi_my_function.py. In my_function.py implement the function from the article linked above. Your script should look like this. This is a simple function, with a pause to simulate a long run time.
These paragraphs explain the parallelization procedure for my_function. The code is given in the gist below (with comments). In mpi_my_function.py import my_function, mpi4py, and numpy. Then get the size and rank from MPI.COMM_WORLD. Use numpy to create random parameter values for my_function. The params variable will be available on all processors. Now divide up the list of parameters, assigning a chunk of the array to each process (or rank). I’ve specifically made the number of rows in params (15) oddly divisible by the number of processors (4) so that we have to do a little extra math to break up params. Now each processor has a variable indexing the start and stop locations of its chunk in the params array.
We want to final result to be an array with the parameter values and function result for each parameter set. Create an empty array, local_results with the same number of rows as the parameter array and one extra column to store the results. Then run my_function for each parameter set and save the result in the result array (local_results).Now each processor has results for its chunk of the params array.
The results must be gathered to create a final array with results for each of the original parameter combinations. Send the local_results arrays from each rank to rank ‘0’, where they are combined to a single array. When using Send specify the rank to send to , dest, and specify a tag (unique integer) so the receiving rank knows which value to retrieve (this is important if you end up executing more than one Send).
For the receiving rank (0), loop through all the other ranks, create an empty array the size of the array to be received, and retrieve the sent values from each rank with Recv, specifying the rank to receive from and the tag. Once the array is retrieved, add it to the existing values. Print out the final array to make sure it looks correct. And we’re done!
Run the script above with:
mpiexec -n 4 python mpi_my_function.py
The result should resemble:
results[[7.58886620e+00 5.62618310e+01 9.09064771e+01 3.33107541e+03] [2.76707037e+01 4.03218572e+01 2.20310537e+01 3.08951805e+04] [7.82729169e+01 9.40939134e+01 7.24046134e+01 5.76552834e+05] [9.88496826e+01 6.91320832e+00 1.59490375e+01 6.75667032e+04] [8.94286742e+01 8.88605014e+01 5.31814181e+01 7.10713954e+05] [3.83757552e+01 4.64666288e+01 3.72791712e+01 6.84686177e+04] [9.33796247e+01 1.71058163e+01 2.94036272e+00 1.49161456e+05] [1.49763382e+01 6.77803268e+01 7.62249839e+01 1.52787224e+04] [7.42368720e+01 8.45623531e+01 6.27481273e+01 4.66095445e+05] [6.76429554e+01 5.95075836e+01 9.82287031e+00 2.72290902e+05] [4.94157194e+00 7.38840592e+01 3.70077813e+00 1.80788546e+03] [2.71179540e+01 2.94973140e+00 2.86632603e+01 2.19784685e+03] [2.92793532e+01 9.90621647e+01 9.45343344e+01 8.50185987e+04] [1.20975353e+01 8.89643839e+01 7.13313160e+01 1.30913009e+04] [8.45193908e+01 4.89884544e+01 5.67737042e+01 3.50007141e+05]]
You’ve probably noticed it took 43 lines of code to run a 4 line function in parallel. Seems like a bit of overkill. We parallelized a simple function, but this is actually a more complicated example because of the manipulation required to get the desired output format. This example serves as a parallelization template for more elaborate functions. Generally, I’ll write a Python module that runs my models/analyses, then setup and call one function (that does everything) from the module in the parallelization script (43-line gist above). You can run really complex analyses without adding much code to the script we’ve created here. Once you get this code working on your personal machine it can be run on most super computers without much additional work.
|
[
{
"code": null,
"e": 440,
"s": 172,
"text": "Did you know you can write parallel Python code that will run on your laptop and on a super computer? You can, and it’s not as difficult as you might expect. If you already write code for asynchronous parallelization then you won’t even have to do much restructuring."
},
{
"code": null,
"e": 949,
"s": 440,
"text": "High Performance Computing (HPC) distributes pieces of jobs across thousands of CPUs (in contrast to the 4–8 on your laptop) to achieve dramatic performance increases. CPUs communicate and pass data using Message Passing Interface (MPI). The same principle is used on your laptop when you write code that distributes pieces of jobs to multiple cores to run simultaneously. This article will demonstrate how to use MPI with Python to write code that can be run in parallel on your laptop, or a super computer."
},
{
"code": null,
"e": 1223,
"s": 949,
"text": "You will need to install a MPI application for your operating system. For Windows users I recommend installing MPI directly from Microsoft. For Mac and Linux users I suggest installing OpenMPI. Windows users must add the the MPI installation directory to the Path variable."
},
{
"code": null,
"e": 1613,
"s": 1223,
"text": "To test your install, type mpiexec (Windows) or mpirun (Mac/Linux, but check the install docs) in a terminal window and press ‘Enter’. This will generate a message with usage information if you have installed properly. While you’re at the terminal, also type python and press ‘Enter’. This should start an interactive Python session. If it does not you need to install or configure Python."
},
{
"code": null,
"e": 1783,
"s": 1613,
"text": "mpi4py is a Python module that allows you to interact with your MPI application (mpiexec or mpirun). Install it the same as any Python module (pip install mpi4py, etc.)."
},
{
"code": null,
"e": 1851,
"s": 1783,
"text": "Once you have MPI and mpi4py installed you’re ready to get started!"
},
{
"code": null,
"e": 2101,
"s": 1851,
"text": "Running a Python script with MPI is a little different than you’re likely used to. With mpiexec and mpirun each line of code will be run by each processor, unless specified otherwise. Let’s make a ‘hello world’ example to demonstrate the MPI basics."
},
{
"code": null,
"e": 2692,
"s": 2101,
"text": "Create a new python script (.py file). Import mpi4py and use MPI.COMM_WORLD to get information about all the processors available to run your script (this number is passed to the MPI app when calling the script). COMM_WORLD gives access to the number of processes (ranks/processors) available to distribute work across, and information about each processor. size gives the total number of ranks, or processors, allocated to run our script. rank gives the identifier of the processor currently executing the code. The print statement below will print once for each processor used in the job."
},
{
"code": null,
"e": 2813,
"s": 2692,
"text": "Execute this script by opening a terminal, navigating to the directory containing the script, and executing the command:"
},
{
"code": null,
"e": 2852,
"s": 2813,
"text": "mpiexec -n 4 python mpi_hello_world.py"
},
{
"code": null,
"e": 3337,
"s": 2852,
"text": "n -4 specifies the number of processors to use. In this instance I’m using 4 processors, which means the print statement will execute 4 times. Notice that the ranks don’t print out in numerical order, so you’ll need to make sure your code can run asynchronously. In other words, it’s not possible to know which processor will start or complete first, so your code will need to be structured in a way that results don’t depend on values that may be calculated on a different processor."
},
{
"code": null,
"e": 3450,
"s": 3337,
"text": "Hello world from rank 2 of 4Hello world from rank 3 of 4Hello world from rank 0 of 4Hello world from rank 1 of 4"
},
{
"code": null,
"e": 3591,
"s": 3450,
"text": "Now, update the script so that it prints out different messages for different ranks. This is done using logical statements (if, elif, else)."
},
{
"code": null,
"e": 3640,
"s": 3591,
"text": "We now get different messages for ranks 0 and 1."
},
{
"code": null,
"e": 3822,
"s": 3640,
"text": "First rankHello world from rank 0 of 4Not first or second rankHello world from rank 2 of 4Not first or second rankHello world from rank 3 of 4Second rankHello world from rank 1 of 4"
},
{
"code": null,
"e": 4226,
"s": 3822,
"text": "The send and recv functions send data from one processor to another and receive data from a processor, respectively. Many data types can be passed with these functions. The example is going to focus specifically on sending and receiving numpy arrays. The Send and Recv functions (notice capital ‘S’ and ‘R’) are specific to numpy arrays. For examples of basic send and recv see the mpi4py documentation."
},
{
"code": null,
"e": 4361,
"s": 4226,
"text": "In a previous article I demonstrated parallel processing with the multiprocessing module. We’ll use the same function in this example."
},
{
"code": null,
"e": 4384,
"s": 4361,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 4671,
"s": 4384,
"text": "Create two new Python scripts in the same directory. Name one my_function.py and the other mpi_my_function.py. In my_function.py implement the function from the article linked above. Your script should look like this. This is a simple function, with a pause to simulate a long run time."
},
{
"code": null,
"e": 5392,
"s": 4671,
"text": "These paragraphs explain the parallelization procedure for my_function. The code is given in the gist below (with comments). In mpi_my_function.py import my_function, mpi4py, and numpy. Then get the size and rank from MPI.COMM_WORLD. Use numpy to create random parameter values for my_function. The params variable will be available on all processors. Now divide up the list of parameters, assigning a chunk of the array to each process (or rank). I’ve specifically made the number of rows in params (15) oddly divisible by the number of processors (4) so that we have to do a little extra math to break up params. Now each processor has a variable indexing the start and stop locations of its chunk in the params array."
},
{
"code": null,
"e": 5799,
"s": 5392,
"text": "We want to final result to be an array with the parameter values and function result for each parameter set. Create an empty array, local_results with the same number of rows as the parameter array and one extra column to store the results. Then run my_function for each parameter set and save the result in the result array (local_results).Now each processor has results for its chunk of the params array."
},
{
"code": null,
"e": 6218,
"s": 5799,
"text": "The results must be gathered to create a final array with results for each of the original parameter combinations. Send the local_results arrays from each rank to rank ‘0’, where they are combined to a single array. When using Send specify the rank to send to , dest, and specify a tag (unique integer) so the receiving rank knows which value to retrieve (this is important if you end up executing more than one Send)."
},
{
"code": null,
"e": 6577,
"s": 6218,
"text": "For the receiving rank (0), loop through all the other ranks, create an empty array the size of the array to be received, and retrieve the sent values from each rank with Recv, specifying the rank to receive from and the tag. Once the array is retrieved, add it to the existing values. Print out the final array to make sure it looks correct. And we’re done!"
},
{
"code": null,
"e": 6604,
"s": 6577,
"text": "Run the script above with:"
},
{
"code": null,
"e": 6643,
"s": 6604,
"text": "mpiexec -n 4 python mpi_my_function.py"
},
{
"code": null,
"e": 6671,
"s": 6643,
"text": "The result should resemble:"
},
{
"code": null,
"e": 7610,
"s": 6671,
"text": "results[[7.58886620e+00 5.62618310e+01 9.09064771e+01 3.33107541e+03] [2.76707037e+01 4.03218572e+01 2.20310537e+01 3.08951805e+04] [7.82729169e+01 9.40939134e+01 7.24046134e+01 5.76552834e+05] [9.88496826e+01 6.91320832e+00 1.59490375e+01 6.75667032e+04] [8.94286742e+01 8.88605014e+01 5.31814181e+01 7.10713954e+05] [3.83757552e+01 4.64666288e+01 3.72791712e+01 6.84686177e+04] [9.33796247e+01 1.71058163e+01 2.94036272e+00 1.49161456e+05] [1.49763382e+01 6.77803268e+01 7.62249839e+01 1.52787224e+04] [7.42368720e+01 8.45623531e+01 6.27481273e+01 4.66095445e+05] [6.76429554e+01 5.95075836e+01 9.82287031e+00 2.72290902e+05] [4.94157194e+00 7.38840592e+01 3.70077813e+00 1.80788546e+03] [2.71179540e+01 2.94973140e+00 2.86632603e+01 2.19784685e+03] [2.92793532e+01 9.90621647e+01 9.45343344e+01 8.50185987e+04] [1.20975353e+01 8.89643839e+01 7.13313160e+01 1.30913009e+04] [8.45193908e+01 4.89884544e+01 5.67737042e+01 3.50007141e+05]]"
}
] |
Counting Sort
|
Counting sort is a stable sorting technique, which is used to sort objects according to the keys that are small numbers. It counts the number of keys whose key values are same. This sorting technique is effective when the difference between different keys are not so big, otherwise, it can increase the space complexity.
Time Complexity: O(n+r)
Space Complexity: O(n+r)
Input:
A list of unsorted data: 2 5 6 2 3 10 3 6 7 8
Output:
Array before Sorting: 2 5 6 2 3 10 3 6 7 8
Array after Sorting: 2 2 3 3 5 6 6 7 8 10
counting sort(array, size)
Input: An array of data, and the total number in the array
Output: The sorted Array
Begin
max = get maximum element from array.
define count array of size [max+1]
for i := 0 to max do
count[i] = 0 //set all elements in the count array to 0
done
for i := 1 to size do
increase count of each number which have found in the array
done
for i := 1 to max do
count[i] = count[i] + count[i+1] //find cumulative frequency
done
for i := size to 1 decrease by 1 do
store the number in the output array
decrease count[i]
done
return the output array
End
#include<iostream>
#include<algorithm>
using namespace std;
void display(int *array, int size) {
for(int i = 1; i<=size; i++)
cout << array[i] << " ";
cout << endl;
}
int getMax(int array[], int size) {
int max = array[1];
for(int i = 2; i<=size; i++) {
if(array[i] > max)
max = array[i];
}
return max; //the max element from the array
}
void countSort(int *array, int size) {
int output[size+1];
int max = getMax(array, size);
int count[max+1]; //create count array (max+1 number of elements)
for(int i = 0; i<=max; i++)
count[i] = 0; //initialize count array to all zero
for(int i = 1; i <=size; i++)
count[array[i]]++; //increase number count in count array.
for(int i = 1; i<=max; i++)
count[i] += count[i-1]; //find cumulative frequency
for(int i = size; i>=1; i--) {
output[count[array[i]]] = array[i];
count[array[i]] -= 1; //decrease count for same numbers
}
for(int i = 1; i<=size; i++) {
array[i] = output[i]; //store output array to main array
}
}
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n+1]; //create an array with given number of elements
cout << "Enter elements:" << endl;
for(int i = 1; i<=n; i++) {
cin >> arr[i];
}
cout << "Array before Sorting: ";
display(arr, n);
countSort(arr, n);
cout << "Array after Sorting: ";
display(arr, n);
}
Enter the number of elements: 10
Enter elements:
2 5 6 2 3 10 3 6 7 8
Array before Sorting: 2 5 6 2 3 10 3 6 7 8
Array after Sorting: 2 2 3 3 5 6 6 7 8 10
|
[
{
"code": null,
"e": 1383,
"s": 1062,
"text": "Counting sort is a stable sorting technique, which is used to sort objects according to the keys that are small numbers. It counts the number of keys whose key values are same. This sorting technique is effective when the difference between different keys are not so big, otherwise, it can increase the space complexity."
},
{
"code": null,
"e": 1407,
"s": 1383,
"text": "Time Complexity: O(n+r)"
},
{
"code": null,
"e": 1432,
"s": 1407,
"text": "Space Complexity: O(n+r)"
},
{
"code": null,
"e": 1578,
"s": 1432,
"text": "Input:\nA list of unsorted data: 2 5 6 2 3 10 3 6 7 8\nOutput:\nArray before Sorting: 2 5 6 2 3 10 3 6 7 8\nArray after Sorting: 2 2 3 3 5 6 6 7 8 10"
},
{
"code": null,
"e": 1605,
"s": 1578,
"text": "counting sort(array, size)"
},
{
"code": null,
"e": 1664,
"s": 1605,
"text": "Input: An array of data, and the total number in the array"
},
{
"code": null,
"e": 1689,
"s": 1664,
"text": "Output: The sorted Array"
},
{
"code": null,
"e": 2216,
"s": 1689,
"text": "Begin\n max = get maximum element from array.\n define count array of size [max+1]\n\n for i := 0 to max do\n count[i] = 0 //set all elements in the count array to 0\n done\n\n for i := 1 to size do\n increase count of each number which have found in the array\n done\n\n for i := 1 to max do\n count[i] = count[i] + count[i+1] //find cumulative frequency\n done\n\n for i := size to 1 decrease by 1 do\n store the number in the output array\n decrease count[i]\n done\n\n return the output array\nEnd"
},
{
"code": null,
"e": 3668,
"s": 2216,
"text": "#include<iostream>\n#include<algorithm>\nusing namespace std;\n\nvoid display(int *array, int size) {\n for(int i = 1; i<=size; i++)\n cout << array[i] << \" \";\n cout << endl;\n}\n\nint getMax(int array[], int size) {\n int max = array[1];\n for(int i = 2; i<=size; i++) {\n if(array[i] > max)\n max = array[i];\n }\n\n return max; //the max element from the array\n}\n\nvoid countSort(int *array, int size) {\n int output[size+1];\n int max = getMax(array, size);\n int count[max+1]; //create count array (max+1 number of elements)\n\n for(int i = 0; i<=max; i++)\n count[i] = 0; //initialize count array to all zero\n for(int i = 1; i <=size; i++)\n count[array[i]]++; //increase number count in count array.\n for(int i = 1; i<=max; i++)\n count[i] += count[i-1]; //find cumulative frequency\n\n for(int i = size; i>=1; i--) {\n output[count[array[i]]] = array[i];\n count[array[i]] -= 1; //decrease count for same numbers\n }\n\n for(int i = 1; i<=size; i++) {\n array[i] = output[i]; //store output array to main array\n }\n}\n\nint main() {\n int n;\n cout << \"Enter the number of elements: \";\n cin >> n;\n int arr[n+1]; //create an array with given number of elements\n cout << \"Enter elements:\" << endl;\n\n for(int i = 1; i<=n; i++) {\n cin >> arr[i];\n }\n\n cout << \"Array before Sorting: \";\n display(arr, n);\n countSort(arr, n);\n cout << \"Array after Sorting: \";\n display(arr, n);\n}"
},
{
"code": null,
"e": 3823,
"s": 3668,
"text": "Enter the number of elements: 10\nEnter elements:\n2 5 6 2 3 10 3 6 7 8\nArray before Sorting: 2 5 6 2 3 10 3 6 7 8\nArray after Sorting: 2 2 3 3 5 6 6 7 8 10"
}
] |
Change the outline color for histogram bars using ggplot2 in R.
|
To change the outlines color of histogram bars using ggplot2, we can use col argument inside geom_histogram function of ggplot2 package.
For Example, if we have a data frame called df that contains a column say X then we can create the histogram of X with different outline color of bars using the below command −
ggplot(df,aes(X))+geom_histogram(bins=30,col=I("red"))
Following snippet creates a sample data frame −
x<-rnorm(20000)
df<-data.frame(x)
head(df,20)
The following dataframe is created −
x
1 -1.31426410
2 -2.62316895
3 -0.19231545
4 0.89701476
5 -0.10409584
6 0.23481007
7 1.53117888
8 -0.63855632
9 0.85309492
10 0.04791316
11 0.37854603
12 1.24928336
13 -0.65170883
14 2.58938742
15 -0.82602063
16 0.97524621
17 0.36930032
18 0.07720108
19 -0.66050878
20 0.66199644
To load the ggplot2 package and to create a histogram of x, on the above created data frame, add the following code to the above snippet −
x<-rnorm(20000)
library(ggplot2)
ggplot(df,aes(x))+geom_histogram(bins=30)
If you execute all the above given snippets as a single program, it generates the following Output −
To create a histogram of x with red colored outline of bars, on the above created data frame, add the following code to the above snippet −
x<-rnorm(20000)
library(ggplot2)
ggplot(df,aes(x))+geom_histogram(bins=30,col=I("red"))
If you execute all the above given snippets as a single program, it generates the following Output −
|
[
{
"code": null,
"e": 1199,
"s": 1062,
"text": "To change the outlines color of histogram bars using ggplot2, we can use col argument inside geom_histogram function of ggplot2 package."
},
{
"code": null,
"e": 1376,
"s": 1199,
"text": "For Example, if we have a data frame called df that contains a column say X then we can create the histogram of X with different outline color of bars using the below command −"
},
{
"code": null,
"e": 1431,
"s": 1376,
"text": "ggplot(df,aes(X))+geom_histogram(bins=30,col=I(\"red\"))"
},
{
"code": null,
"e": 1479,
"s": 1431,
"text": "Following snippet creates a sample data frame −"
},
{
"code": null,
"e": 1525,
"s": 1479,
"text": "x<-rnorm(20000)\ndf<-data.frame(x)\nhead(df,20)"
},
{
"code": null,
"e": 1562,
"s": 1525,
"text": "The following dataframe is created −"
},
{
"code": null,
"e": 1874,
"s": 1562,
"text": " x\n 1 -1.31426410\n 2 -2.62316895\n 3 -0.19231545\n 4 0.89701476\n 5 -0.10409584\n 6 0.23481007\n 7 1.53117888\n 8 -0.63855632\n 9 0.85309492\n10 0.04791316\n11 0.37854603\n12 1.24928336\n13 -0.65170883\n14 2.58938742\n15 -0.82602063\n16 0.97524621\n17 0.36930032\n18 0.07720108\n19 -0.66050878\n20 0.66199644"
},
{
"code": null,
"e": 2013,
"s": 1874,
"text": "To load the ggplot2 package and to create a histogram of x, on the above created data frame, add the following code to the above snippet −"
},
{
"code": null,
"e": 2089,
"s": 2013,
"text": "x<-rnorm(20000)\n\nlibrary(ggplot2)\nggplot(df,aes(x))+geom_histogram(bins=30)"
},
{
"code": null,
"e": 2190,
"s": 2089,
"text": "If you execute all the above given snippets as a single program, it generates the following Output −"
},
{
"code": null,
"e": 2330,
"s": 2190,
"text": "To create a histogram of x with red colored outline of bars, on the above created data frame, add the following code to the above snippet −"
},
{
"code": null,
"e": 2419,
"s": 2330,
"text": "x<-rnorm(20000)\n\nlibrary(ggplot2)\nggplot(df,aes(x))+geom_histogram(bins=30,col=I(\"red\"))"
},
{
"code": null,
"e": 2520,
"s": 2419,
"text": "If you execute all the above given snippets as a single program, it generates the following Output −"
}
] |
How can we extract the numbers from an input string in Java?
|
The java.lang.String class gives a considerable measure of methods to deal with a string. By the assistance of these methods, one can perform operations on the string like trimming, concatenating, converting and comparing. We can extract the numbers from a given string by using the replaceAll() method of a String class.
import java.util.Scanner;
public class StringExtractTest {
public static void main(String[] args) {
String input;
String numbers;
Scanner scanner = new Scanner(System.in);
System.out.print(" Please enter a string from the keyboard that contains numbers: ");
input = scanner.nextLine();
numbers = input.replaceAll("[^0-9]", "");
System.out.println("The Numbers are: " + numbers);
}
}
Please enter a string from the keyboard that contains numbers: Welcome to Tutorials Point 1234567890
The Numbers are: 1234567890
|
[
{
"code": null,
"e": 1384,
"s": 1062,
"text": "The java.lang.String class gives a considerable measure of methods to deal with a string. By the assistance of these methods, one can perform operations on the string like trimming, concatenating, converting and comparing. We can extract the numbers from a given string by using the replaceAll() method of a String class."
},
{
"code": null,
"e": 1816,
"s": 1384,
"text": "import java.util.Scanner;\npublic class StringExtractTest {\n public static void main(String[] args) {\n String input;\n String numbers;\n Scanner scanner = new Scanner(System.in);\n System.out.print(\" Please enter a string from the keyboard that contains numbers: \");\n input = scanner.nextLine();\n numbers = input.replaceAll(\"[^0-9]\", \"\"); \n System.out.println(\"The Numbers are: \" + numbers);\n }\n}"
},
{
"code": null,
"e": 1945,
"s": 1816,
"text": "Please enter a string from the keyboard that contains numbers: Welcome to Tutorials Point 1234567890\nThe Numbers are: 1234567890"
}
] |
Time series forecasting: from naive to ARIMA and beyond | by Mahbubul Alam | Towards Data Science
|
Building another power plant in the next five years requires forecasts of future demand;
Scheduling staff in a call center next week requires forecasts of next weeks’ call volumes;
Stocking an inventory of retails requires forecasts of stock requirements.
Indeed, short and medium term forecasting is an essential part of business decisions across industries. And historical data is an essential input into this forecasting process.
Time series datasets are the most widely generated and used kind of data in any business. They are used both in understanding the past and predicting the future. In this article, I’ll discuss how various forecasting methods are applied to time series datasets with relevant case studies and examples. The purpose of this post is not to evaluate which model is good or bad, rather to demonstrate the many different ways we can do forecasting in practice. The article is organized in 2 broad sections:
(1) First, I will provide an overview of time series data and how to decompose difference time series components;
(2) Then I will provide examples of different forecasting techniques with associated implementation method
So what is a time series data? A time series is a sequence of observations recorded in discrete time points. They can be recorded in hourly (e.g. air temperature), daily (e.g. DJI Average), monthly (e.g. sales) or yearly (e.g. GDP) time intervals. Time series are applied in a wide range of cases in all disciplines including statistics, mathematics, astronomy and engineering. Time series plotting is one of the most basic plotting exercises implemented during the exploratory data analysis (EDA) phase in data science and analytics.
Let’s take a look at the following figure.
Few properties are obvious even in naked eyes:
it’s a time series plotthere is an upward trendthe observations have seasonality (ups and downs in a regular interval)
it’s a time series plot
there is an upward trend
the observations have seasonality (ups and downs in a regular interval)
In fact, if we decompose this data we will see these components like below.
Forecasting into the future can be as simple as extrapolating the trend of historical observations, to applying complex algorithms. Here I present different techniques most commonly used in business applications. I am demonstrating these techniques in R environment using two statistical and visualization packages:
# install packageslibrary("forecast")library("ggplot2")
After importing data ( a retail sales dataset) and converting it into a time series object, here is how it looks like.
# import datasetretaildata = readxl::read_excel("../retail.xlsx", skip=1)# convert dataset into a time series objectretailts = ts(retaildata, start = c(1982,4), frequency = 12 )# plot the time series object with autoplot() function that comes with forecast() packageautoplot(retailts)
First I’ll explain some simple techniques to forecast this time series object. Although these simple techniques are not often used in practice, but it’s good to know how they came about, then we will go into more complicated techniques.
Simple forecasting techniques are used as benchmarks. They provide a general understanding of historical data and to build intuition upon which to add additional layers complexity. Several such techniques are common in literature such as: mean model, naive forecast, random walk, drift method etc. A mean model, for example, takes the mean of previous observations and uses that for forecasting. That is:
forecast value = average of training data
A random walk, on the other hand, would predict the next value, Ŷ(t), that equals to the previous value plus a constant change.
Ŷ(t) = Y(t-1) + α
The value of naive forecast is set based upon the value of last observation. And like other simple methods, it provides a ballpark number as an initial estimate until further research is done. Below is an implementation of a seasonal naive forecast model.
# subsetting train and test data using window()function retailtstrain = window(retailts, end = c(2010,3))retailtstest = window(retailts, start = c(2010,4))# model buildingretailtstrain_snaive = snaive(retailtstrain, h=50)# plotingautoplot(retailts)+autolayer(retailtstrain_snaive, series = "S Naive", PI = FALSE)
# Accuracy testaccuracy(retailtstrain_snaive, retailtstest)
Exponential smoothing has few variants depending on the data type. A simple exponential smoothing is used for non-seasonal data without a clear trend, whereas Holt-Winter method is for data with trend and seasonality. It is applied in a stationary time series, where smoothing is controlled by parameter alpha (0~1), where lower values mean lower weights placed on recent observations. Below is an implementation of Holt-Winter Exponential Smoothing using the same dataset.
# Holt Winter Exponential Smoothing# Two variations: additive for roughly constant seasonal variation, otherwise multiplicative methoddata = window(retailts, start=2000)data_add = hw(data, seasonal="additive")data_mult = hw(data, seasonal="multiplicative")autoplot(data, series = "original data")+autolayer(data_add, series = "additive", PI=FALSE)+autolayer(data_mult, series = "multiplicative", PI=FALSE)
# model summary and performancedata_add[["model"]]
Auto Regressive Integrated Moving Average (ARIMA) is arguably the most popular and widely used statistical forecasting technique. As the name suggests, this family of techniques has 3 components: a) an “autoregression” component that models the relationship between the series and it’s lagged observations; b) a “moving average” model that models the forecast as a function of lagged forecast errors; and c) an “integrated” component that makes the series stationary.
The model takes in the following parameter values:
p that defines the number of lags;
d that specifies the number of differences used; and
q that defines the size of moving average window
An implementation of ARIMA model to make forecasts using the time series object is as follows:
# implementing auto.arima() to forecastretailts_arima = auto.arima(retailts, seasonal=TRUE, stepwise = FALSE, approximation = FALSE)retailts_arima %>% forecast(h=10) %>% autoplot()
Finally, there are some outside box techniques such as agent-based and system dynamic modeling. Developed at MIT’s Sloan School of Management in the 1950s, system dynamics is a methodological approach to model the behavior of complex systems, where change in one component leads to change in others. This approach is widely applied in industries such as healthcare, disease research, public transportation, business management and revenue forecasting. The most famous application of system dynamics probably is in the modeling Limits to Growth by the Club of Rome.
A system dynamic model represents a complex system in terms of stocks & flows and their interactions via feedback loops to predict the behavior of the system. Let’s say a bank account has a “Stock” of $100. Every month $20 is deposited (represented by “Flow” 1) and an amount of $15/month is withdrawn (represented by “Flow” 2):
In this example, future value of the stock (i.e. account deposit) is modeled as s function of future flows (i.e. deposits and withdrawals). This paper provides a case study of implementing a system dynamic model for forecasting in the construction industry.
Rob Hyndman’s website https://robjhyndman.com/ is an one-stop solution to all forecasting problems in R. Also check out the open access book https://otexts.com/fpp2/ that has theoretical discussion as well as the R implementation with examples.“A Little Book of R for Time Series” has everything in simplified forms. http://www.calvin.edu/~stob/courses/m344/S15/a-little-book-of-r-for-time-series.pdfIf you are into Python then check out the link below. There is also a reference to a book on python implementations of time series. https://machinelearningmastery.com/time-series-forecasting-methods-in-python-cheat-sheet/
Rob Hyndman’s website https://robjhyndman.com/ is an one-stop solution to all forecasting problems in R. Also check out the open access book https://otexts.com/fpp2/ that has theoretical discussion as well as the R implementation with examples.
“A Little Book of R for Time Series” has everything in simplified forms. http://www.calvin.edu/~stob/courses/m344/S15/a-little-book-of-r-for-time-series.pdf
If you are into Python then check out the link below. There is also a reference to a book on python implementations of time series. https://machinelearningmastery.com/time-series-forecasting-methods-in-python-cheat-sheet/
|
[
{
"code": null,
"e": 261,
"s": 172,
"text": "Building another power plant in the next five years requires forecasts of future demand;"
},
{
"code": null,
"e": 353,
"s": 261,
"text": "Scheduling staff in a call center next week requires forecasts of next weeks’ call volumes;"
},
{
"code": null,
"e": 428,
"s": 353,
"text": "Stocking an inventory of retails requires forecasts of stock requirements."
},
{
"code": null,
"e": 605,
"s": 428,
"text": "Indeed, short and medium term forecasting is an essential part of business decisions across industries. And historical data is an essential input into this forecasting process."
},
{
"code": null,
"e": 1105,
"s": 605,
"text": "Time series datasets are the most widely generated and used kind of data in any business. They are used both in understanding the past and predicting the future. In this article, I’ll discuss how various forecasting methods are applied to time series datasets with relevant case studies and examples. The purpose of this post is not to evaluate which model is good or bad, rather to demonstrate the many different ways we can do forecasting in practice. The article is organized in 2 broad sections:"
},
{
"code": null,
"e": 1219,
"s": 1105,
"text": "(1) First, I will provide an overview of time series data and how to decompose difference time series components;"
},
{
"code": null,
"e": 1326,
"s": 1219,
"text": "(2) Then I will provide examples of different forecasting techniques with associated implementation method"
},
{
"code": null,
"e": 1861,
"s": 1326,
"text": "So what is a time series data? A time series is a sequence of observations recorded in discrete time points. They can be recorded in hourly (e.g. air temperature), daily (e.g. DJI Average), monthly (e.g. sales) or yearly (e.g. GDP) time intervals. Time series are applied in a wide range of cases in all disciplines including statistics, mathematics, astronomy and engineering. Time series plotting is one of the most basic plotting exercises implemented during the exploratory data analysis (EDA) phase in data science and analytics."
},
{
"code": null,
"e": 1904,
"s": 1861,
"text": "Let’s take a look at the following figure."
},
{
"code": null,
"e": 1951,
"s": 1904,
"text": "Few properties are obvious even in naked eyes:"
},
{
"code": null,
"e": 2070,
"s": 1951,
"text": "it’s a time series plotthere is an upward trendthe observations have seasonality (ups and downs in a regular interval)"
},
{
"code": null,
"e": 2094,
"s": 2070,
"text": "it’s a time series plot"
},
{
"code": null,
"e": 2119,
"s": 2094,
"text": "there is an upward trend"
},
{
"code": null,
"e": 2191,
"s": 2119,
"text": "the observations have seasonality (ups and downs in a regular interval)"
},
{
"code": null,
"e": 2267,
"s": 2191,
"text": "In fact, if we decompose this data we will see these components like below."
},
{
"code": null,
"e": 2583,
"s": 2267,
"text": "Forecasting into the future can be as simple as extrapolating the trend of historical observations, to applying complex algorithms. Here I present different techniques most commonly used in business applications. I am demonstrating these techniques in R environment using two statistical and visualization packages:"
},
{
"code": null,
"e": 2639,
"s": 2583,
"text": "# install packageslibrary(\"forecast\")library(\"ggplot2\")"
},
{
"code": null,
"e": 2758,
"s": 2639,
"text": "After importing data ( a retail sales dataset) and converting it into a time series object, here is how it looks like."
},
{
"code": null,
"e": 3043,
"s": 2758,
"text": "# import datasetretaildata = readxl::read_excel(\"../retail.xlsx\", skip=1)# convert dataset into a time series objectretailts = ts(retaildata, start = c(1982,4), frequency = 12 )# plot the time series object with autoplot() function that comes with forecast() packageautoplot(retailts)"
},
{
"code": null,
"e": 3280,
"s": 3043,
"text": "First I’ll explain some simple techniques to forecast this time series object. Although these simple techniques are not often used in practice, but it’s good to know how they came about, then we will go into more complicated techniques."
},
{
"code": null,
"e": 3685,
"s": 3280,
"text": "Simple forecasting techniques are used as benchmarks. They provide a general understanding of historical data and to build intuition upon which to add additional layers complexity. Several such techniques are common in literature such as: mean model, naive forecast, random walk, drift method etc. A mean model, for example, takes the mean of previous observations and uses that for forecasting. That is:"
},
{
"code": null,
"e": 3727,
"s": 3685,
"text": "forecast value = average of training data"
},
{
"code": null,
"e": 3856,
"s": 3727,
"text": "A random walk, on the other hand, would predict the next value, Ŷ(t), that equals to the previous value plus a constant change."
},
{
"code": null,
"e": 3875,
"s": 3856,
"text": "Ŷ(t) = Y(t-1) + α"
},
{
"code": null,
"e": 4131,
"s": 3875,
"text": "The value of naive forecast is set based upon the value of last observation. And like other simple methods, it provides a ballpark number as an initial estimate until further research is done. Below is an implementation of a seasonal naive forecast model."
},
{
"code": null,
"e": 4444,
"s": 4131,
"text": "# subsetting train and test data using window()function retailtstrain = window(retailts, end = c(2010,3))retailtstest = window(retailts, start = c(2010,4))# model buildingretailtstrain_snaive = snaive(retailtstrain, h=50)# plotingautoplot(retailts)+autolayer(retailtstrain_snaive, series = \"S Naive\", PI = FALSE)"
},
{
"code": null,
"e": 4504,
"s": 4444,
"text": "# Accuracy testaccuracy(retailtstrain_snaive, retailtstest)"
},
{
"code": null,
"e": 4978,
"s": 4504,
"text": "Exponential smoothing has few variants depending on the data type. A simple exponential smoothing is used for non-seasonal data without a clear trend, whereas Holt-Winter method is for data with trend and seasonality. It is applied in a stationary time series, where smoothing is controlled by parameter alpha (0~1), where lower values mean lower weights placed on recent observations. Below is an implementation of Holt-Winter Exponential Smoothing using the same dataset."
},
{
"code": null,
"e": 5384,
"s": 4978,
"text": "# Holt Winter Exponential Smoothing# Two variations: additive for roughly constant seasonal variation, otherwise multiplicative methoddata = window(retailts, start=2000)data_add = hw(data, seasonal=\"additive\")data_mult = hw(data, seasonal=\"multiplicative\")autoplot(data, series = \"original data\")+autolayer(data_add, series = \"additive\", PI=FALSE)+autolayer(data_mult, series = \"multiplicative\", PI=FALSE)"
},
{
"code": null,
"e": 5435,
"s": 5384,
"text": "# model summary and performancedata_add[[\"model\"]]"
},
{
"code": null,
"e": 5903,
"s": 5435,
"text": "Auto Regressive Integrated Moving Average (ARIMA) is arguably the most popular and widely used statistical forecasting technique. As the name suggests, this family of techniques has 3 components: a) an “autoregression” component that models the relationship between the series and it’s lagged observations; b) a “moving average” model that models the forecast as a function of lagged forecast errors; and c) an “integrated” component that makes the series stationary."
},
{
"code": null,
"e": 5954,
"s": 5903,
"text": "The model takes in the following parameter values:"
},
{
"code": null,
"e": 5989,
"s": 5954,
"text": "p that defines the number of lags;"
},
{
"code": null,
"e": 6042,
"s": 5989,
"text": "d that specifies the number of differences used; and"
},
{
"code": null,
"e": 6091,
"s": 6042,
"text": "q that defines the size of moving average window"
},
{
"code": null,
"e": 6186,
"s": 6091,
"text": "An implementation of ARIMA model to make forecasts using the time series object is as follows:"
},
{
"code": null,
"e": 6367,
"s": 6186,
"text": "# implementing auto.arima() to forecastretailts_arima = auto.arima(retailts, seasonal=TRUE, stepwise = FALSE, approximation = FALSE)retailts_arima %>% forecast(h=10) %>% autoplot()"
},
{
"code": null,
"e": 6932,
"s": 6367,
"text": "Finally, there are some outside box techniques such as agent-based and system dynamic modeling. Developed at MIT’s Sloan School of Management in the 1950s, system dynamics is a methodological approach to model the behavior of complex systems, where change in one component leads to change in others. This approach is widely applied in industries such as healthcare, disease research, public transportation, business management and revenue forecasting. The most famous application of system dynamics probably is in the modeling Limits to Growth by the Club of Rome."
},
{
"code": null,
"e": 7261,
"s": 6932,
"text": "A system dynamic model represents a complex system in terms of stocks & flows and their interactions via feedback loops to predict the behavior of the system. Let’s say a bank account has a “Stock” of $100. Every month $20 is deposited (represented by “Flow” 1) and an amount of $15/month is withdrawn (represented by “Flow” 2):"
},
{
"code": null,
"e": 7519,
"s": 7261,
"text": "In this example, future value of the stock (i.e. account deposit) is modeled as s function of future flows (i.e. deposits and withdrawals). This paper provides a case study of implementing a system dynamic model for forecasting in the construction industry."
},
{
"code": null,
"e": 8141,
"s": 7519,
"text": "Rob Hyndman’s website https://robjhyndman.com/ is an one-stop solution to all forecasting problems in R. Also check out the open access book https://otexts.com/fpp2/ that has theoretical discussion as well as the R implementation with examples.“A Little Book of R for Time Series” has everything in simplified forms. http://www.calvin.edu/~stob/courses/m344/S15/a-little-book-of-r-for-time-series.pdfIf you are into Python then check out the link below. There is also a reference to a book on python implementations of time series. https://machinelearningmastery.com/time-series-forecasting-methods-in-python-cheat-sheet/"
},
{
"code": null,
"e": 8386,
"s": 8141,
"text": "Rob Hyndman’s website https://robjhyndman.com/ is an one-stop solution to all forecasting problems in R. Also check out the open access book https://otexts.com/fpp2/ that has theoretical discussion as well as the R implementation with examples."
},
{
"code": null,
"e": 8543,
"s": 8386,
"text": "“A Little Book of R for Time Series” has everything in simplified forms. http://www.calvin.edu/~stob/courses/m344/S15/a-little-book-of-r-for-time-series.pdf"
}
] |
Difference between Schema and Instance in DBMS
|
22 Sep, 2021
1. Instances : Instances are the collection of information stored at a particular moment. The instances can be changed by certain CRUD operations as like addition, deletion of data. It may be noted that any search query will not make any kind of changes in the instances.
Example – Let’s say a table teacher in our database whose name is School, suppose the table has 50 records so the instance of the database has 50 records for now and tomorrow we are going to add another fifty records so tomorrow the instance have total 100 records. This is called an instance.
2. Schema : Schema is the overall description of the database. The basic structure of how the data will be stored in the database is called schema.
Schema is of three types: Logical Schema, Physical Schema and view Schema.
Logical Schema – It describes the database designed at logical level.Physical Schema – It describes the database designed at physical level.View Schema – It defines the design of the database at the view level.
Logical Schema – It describes the database designed at logical level.
Physical Schema – It describes the database designed at physical level.
View Schema – It defines the design of the database at the view level.
Example – Let’s say a table teacher in our database name school, the teacher table require the name, dob, doj in their table so we design a structure as :
Teacher table
name: String
doj: date
dob: date
Above given is the schema of the table teacher.
Difference between Schema and Instance :
ak9319770552
Picked
DBMS
Difference Between
GATE CS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between DELETE, DROP and TRUNCATE
Difference between Clustered and Non-clustered index
CTE in SQL
Indexing in Databases | Set 1
SQL Interview Questions
Class method vs Static method in Python
Difference between BFS and DFS
Differences between Black Box Testing vs White Box Testing
Difference Between Method Overloading and Method Overriding in Java
Differences between TCP and UDP
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Sep, 2021"
},
{
"code": null,
"e": 325,
"s": 52,
"text": "1. Instances : Instances are the collection of information stored at a particular moment. The instances can be changed by certain CRUD operations as like addition, deletion of data. It may be noted that any search query will not make any kind of changes in the instances. "
},
{
"code": null,
"e": 620,
"s": 325,
"text": "Example – Let’s say a table teacher in our database whose name is School, suppose the table has 50 records so the instance of the database has 50 records for now and tomorrow we are going to add another fifty records so tomorrow the instance have total 100 records. This is called an instance. "
},
{
"code": null,
"e": 769,
"s": 620,
"text": "2. Schema : Schema is the overall description of the database. The basic structure of how the data will be stored in the database is called schema. "
},
{
"code": null,
"e": 847,
"s": 771,
"text": "Schema is of three types: Logical Schema, Physical Schema and view Schema. "
},
{
"code": null,
"e": 1059,
"s": 847,
"text": "Logical Schema – It describes the database designed at logical level.Physical Schema – It describes the database designed at physical level.View Schema – It defines the design of the database at the view level. "
},
{
"code": null,
"e": 1129,
"s": 1059,
"text": "Logical Schema – It describes the database designed at logical level."
},
{
"code": null,
"e": 1201,
"s": 1129,
"text": "Physical Schema – It describes the database designed at physical level."
},
{
"code": null,
"e": 1273,
"s": 1201,
"text": "View Schema – It defines the design of the database at the view level. "
},
{
"code": null,
"e": 1430,
"s": 1273,
"text": "Example – Let’s say a table teacher in our database name school, the teacher table require the name, dob, doj in their table so we design a structure as : "
},
{
"code": null,
"e": 1478,
"s": 1430,
"text": "Teacher table\nname: String\ndoj: date\ndob: date "
},
{
"code": null,
"e": 1527,
"s": 1478,
"text": "Above given is the schema of the table teacher. "
},
{
"code": null,
"e": 1569,
"s": 1527,
"text": "Difference between Schema and Instance : "
},
{
"code": null,
"e": 1582,
"s": 1569,
"text": "ak9319770552"
},
{
"code": null,
"e": 1589,
"s": 1582,
"text": "Picked"
},
{
"code": null,
"e": 1594,
"s": 1589,
"text": "DBMS"
},
{
"code": null,
"e": 1613,
"s": 1594,
"text": "Difference Between"
},
{
"code": null,
"e": 1621,
"s": 1613,
"text": "GATE CS"
},
{
"code": null,
"e": 1626,
"s": 1621,
"text": "DBMS"
},
{
"code": null,
"e": 1724,
"s": 1626,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1769,
"s": 1724,
"text": "Difference between DELETE, DROP and TRUNCATE"
},
{
"code": null,
"e": 1822,
"s": 1769,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 1833,
"s": 1822,
"text": "CTE in SQL"
},
{
"code": null,
"e": 1863,
"s": 1833,
"text": "Indexing in Databases | Set 1"
},
{
"code": null,
"e": 1887,
"s": 1863,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 1927,
"s": 1887,
"text": "Class method vs Static method in Python"
},
{
"code": null,
"e": 1958,
"s": 1927,
"text": "Difference between BFS and DFS"
},
{
"code": null,
"e": 2017,
"s": 1958,
"text": "Differences between Black Box Testing vs White Box Testing"
},
{
"code": null,
"e": 2085,
"s": 2017,
"text": "Difference Between Method Overloading and Method Overriding in Java"
}
] |
Next Smaller Element
|
10 Jun, 2022
Given an array, print the Next Smaller Element (NSE) for every element. The NSE for an element x is the first smaller element on the right side of x in array. Elements for which no smaller element exist (on right side), consider NSE as -1. Examples: a) For any array, rightmost element always has NSE as -1. b) For an array which is sorted in increasing order, all elements have NSE as -1. c) For the input array [4, 8, 5, 2, 25}, the NSE for each element are as follows.
Element NSE
4 --> 2
8 --> 5
5 --> 2
2 --> -1
25 --> -1
d) For the input array [13, 7, 6, 12}, the next smaller elements for each element are as follows.
Element NSE
13 --> 7
7 --> 6
6 --> -1
12 --> -1
Method 1 (Simple) Use two loops: The outer loop picks all the elements one by one. The inner loop looks for the first smaller element for the element picked by outer loop. If a smaller element is found then that element is printed as next, otherwise, -1 is printed.Thanks to Sachin for providing following code.
C++
C
Java
Python
C#
PHP
Javascript
// Simple C++ program to print// next smaller elements in a given array#include "bits/stdc++.h"using namespace std; /* prints element and NSE pairfor all elements of arr[] of size n */void printNSE(int arr[], int n){ int next, i, j; for (i = 0; i < n; i++) { next = -1; for (j = i + 1; j < n; j++) { if (arr[i] > arr[j]) { next = arr[j]; break; } } cout << arr[i] << " -- " << next << endl; }} // Driver Codeint main(){ int arr[]= {11, 13, 21, 3}; int n = sizeof(arr) / sizeof(arr[0]); printNSE(arr, n); return 0;} // This code is contributed by shivanisinghss2110
// Simple C program to print next smaller elements// in a given array#include<stdio.h> /* prints element and NSE pair for all elements ofarr[] of size n */void printNSE(int arr[], int n){ int next, i, j; for (i=0; i<n; i++) { next = -1; for (j = i+1; j<n; j++) { if (arr[i] > arr[j]) { next = arr[j]; break; } } printf("%d -- %d\n", arr[i], next); }} int main(){ int arr[]= {11, 13, 21, 3}; int n = sizeof(arr)/sizeof(arr[0]); printNSE(arr, n); return 0;}
// Simple Java program to print next// smaller elements in a given array class Main { /* prints element and NSE pair for all elements of arr[] of size n */ static void printNSE(int arr[], int n) { int next, i, j; for (i = 0; i < n; i++) { next = -1; for (j = i + 1; j < n; j++) { if (arr[i] > arr[j]) { next = arr[j]; break; } } System.out.println(arr[i] + " -- " + next); } } public static void main(String args[]) { int arr[] = { 11, 13, 21, 3 }; int n = arr.length; printNSE(arr, n); }}
# Function to print element and NSE pair for all elements of listdef printNSE(arr): for i in range(0, len(arr), 1): next = -1 for j in range(i + 1, len(arr), 1): if arr[i] > arr[j]: next = arr[j] break print(str(arr[i]) + " -- " + str(next)) # Driver program to test above functionarr = [11, 13, 21, 3]printNSE(arr) # This code is contributed by Sunny Karira
// Simple C# program to print next// smaller elements in a given arrayusing System; class GFG { /* prints element and NSE pair for all elements of arr[] of size n */ static void printNSE(int[] arr, int n) { int next, i, j; for (i = 0; i < n; i++) { next = -1; for (j = i + 1; j < n; j++) { if (arr[i] > arr[j]) { next = arr[j]; break; } } Console.WriteLine(arr[i] + " -- " + next); } } // driver code public static void Main() { int[] arr = { 11, 13, 21, 3 }; int n = arr.Length; printNSE(arr, n); }} // This code is contributed by Sam007
<?php// Simple PHP program to print next// smaller elements in a given array /* prints element and NSE pair for all elements of arr[] of size n */function printNSE($arr, $n){ for ($i = 0; $i < $n; $i++) { $next = -1; for ($j = $i + 1; $j < $n; $j++) { if ($arr[$i] > $arr[$j]) { $next = $arr[$j]; break; } } echo $arr[$i]." -- ". $next."\n"; }} // Driver Code $arr= array(11, 13, 21, 3); $n = count($arr); printNSE($arr, $n); // This code is contributed by Sam007?>
<script> // Simple Javascript program to print// next smaller elements in a given array /* prints element and NSE pairfor all elements of arr[] of size n */function printNSE(arr, n){ var next, i, j; for (i = 0; i < n; i++) { next = -1; for (j = i + 1; j < n; j++) { if (arr[i] > arr[j]) { next = arr[j]; break; } } document.write( arr[i] + " -- " + next+"<br>" ); }} // Driver Codevar arr= [11, 13, 21, 3]; var n = arr.length;printNSE(arr, n); </script>
11 -- 3
13 -- 3
21 -- 3
3 -- -1
Time Complexity:
The worst case occurs when all elements are sorted in decreasing order.
Auxiliary Space: O(1)
As constant extra space is used
Method 2 (Using Segment Tree and Binary Search)
This method is also pretty simple if one knows Segment trees and Binary Search. Lets consider an array and lets suppose NSE for is , we simply need to binary search for in range to . will be the first index , such that range minimum of elements from index to () is lesser than .
C++
#include <bits/stdc++.h>using namespace std; // Program to find next smaller element for all elements in// an array, using segment tree and binary search // --------Segment Tree Starts Here----------------- vector<int> seg_tree; // combine function for combining two nodes of the tree, in// this case we need to take min of twoint combine(int a, int b) { return min(a, b); } // build function, builds seg_tree based on vector parameter// arrvoid build(vector<int>& arr, int node, int tl, int tr){ // if current range consists only of one element, then // node should be this element if (tl == tr) { seg_tree[node] = arr[tl]; } else { // divide the build operations into two parts int tm = (tr - tl) / 2 + tl; build(arr, 2 * node, tl, tm); build(arr, 2 * node + 1, tm + 1, tr); // combine the results from two parts, and store it // into current node seg_tree[node] = combine(seg_tree[2 * node], seg_tree[2 * node + 1]); }} // query function, returns minimum in the range [l, r]int query(int node, int tl, int tr, int l, int r){ // if range is invalid, then return infinity if (l > r) { return INT32_MAX; } // if range completely aligns with a segment tree node, // then value of this node should be returned if (l == tl && r == tr) { return seg_tree[node]; } // else divide the query into two parts int tm = (tr - tl) / 2 + tl; int q1 = query(2 * node, tl, tm, l, min(r, tm)); int q2 = query(2 * node + 1, tm + 1, tr, max(l, tm + 1), r); // and combine the results from the two parts and return // it return combine(q1, q2);} // --------Segment Tree Ends Here----------------- void printNSE(vector<int> arr, int n){ seg_tree = vector<int>(4 * n); // build segment tree initially build(arr, 1, 0, n - 1); int q, l, r, mid, ans; for (int i = 0; i < n; i++) { // binary search for ans in range [i + 1, n - 1], // initially ans is -1 representing there is no NSE // for this element l = i + 1; r = n - 1; ans = -1; while (l <= r) { mid = (r - l) / 2 + l; // q is the minimum element in range [l, mid] q = query(1, 0, n - 1, l, mid); // if the minimum element in range [l, mid] is // less than arr[i], then mid can be answer, we // mark it, and look for a better answer in left // half. Else if q is greater than arr[i], mid // can't be an answer, we should search in right // half if (q < arr[i]) { ans = arr[mid]; r = mid - 1; } else { l = mid + 1; } } // print NSE for arr[i] cout << arr[i] << " ---> " << ans << "\n"; }} // Driver program to test above functionsint main(){ vector<int> arr = { 11, 13, 21, 3 }; printNSE(arr, 4); return 0;}
11 ---> 3
13 ---> 3
21 ---> 3
3 ---> -1
Time Complexity :
For each of array elements we do a binary search, which includes steps, and each step costs operations [range minimum queries].
Auxiliary Space: O(N)
As extra space is used for storing the elements of the segment tree.
Method 3 (Using Segment Tree and Coordinate Compression)
In this approach, we build a segment tree on indices of compressed array elements:
Somewhere along the lines, we would build a array such-that is the smallest index at which is present in input array.Its easy to see that we need to compress the input array so as to build this array because if exceeds (memory limit of online judge) chances are we would get a segmentation fault.To compress we sort the input array, and then for each new value seen in array we map it to a corresponding smaller value, if possible. Use these mapped values to generate a array with same order as input array.So now that we are done with compression, we can begin with the query part:Suppose in previous step, we compressed the array to distinct values. Initially set , this signifies no value is processed at any index as of now.Traverse the compressed array in reverse order, this would imply that in past we would have only processed elements that are on the right side.For , query (and store in ) the smallest index of values using segment tree, this must be the NSE for !Update the index of to .We stored the index of NSEs for all array elements, we can easily print NSEs themselves as shown in code.
Somewhere along the lines, we would build a array such-that is the smallest index at which is present in input array.
Its easy to see that we need to compress the input array so as to build this array because if exceeds (memory limit of online judge) chances are we would get a segmentation fault.
To compress we sort the input array, and then for each new value seen in array we map it to a corresponding smaller value, if possible. Use these mapped values to generate a array with same order as input array.
So now that we are done with compression, we can begin with the query part:Suppose in previous step, we compressed the array to distinct values. Initially set , this signifies no value is processed at any index as of now.Traverse the compressed array in reverse order, this would imply that in past we would have only processed elements that are on the right side.For , query (and store in ) the smallest index of values using segment tree, this must be the NSE for !Update the index of to .
Suppose in previous step, we compressed the array to distinct values. Initially set , this signifies no value is processed at any index as of now.
Traverse the compressed array in reverse order, this would imply that in past we would have only processed elements that are on the right side.For , query (and store in ) the smallest index of values using segment tree, this must be the NSE for !Update the index of to .
For , query (and store in ) the smallest index of values using segment tree, this must be the NSE for !
Update the index of to .
We stored the index of NSEs for all array elements, we can easily print NSEs themselves as shown in code.
Note: In implementation we use INT32_MAX instead of -1 because storing INT32_MAX doesn’t affect our min-segment tree and still serves the purpose of identifying unprocessed values.
As extra space is used for storing the elements of the segment tree.
C++
#include <bits/stdc++.h>using namespace std; // Program to find next smaller element for all elements in// an array, using segment tree and coordinate compression // --------Segment Tree Starts Here----------------- vector<int> seg_tree; // combine function for combining two nodes of the tree, in// this case we need to take min of twoint combine(int a, int b) { return min(a, b); } // build function, builds seg_tree based on vector parameter// arrvoid build(vector<int>& arr, int node, int tl, int tr){ // if current range consists only of one element, then // node should be this element if (tl == tr) { seg_tree[node] = arr[tl]; } else { // divide the build operations into two parts int tm = (tr - tl) / 2 + tl; build(arr, 2 * node, tl, tm); build(arr, 2 * node + 1, tm + 1, tr); // combine the results from two parts, and store it // into current node seg_tree[node] = combine(seg_tree[2 * node], seg_tree[2 * node + 1]); }} // update function, used to make a point update, update// arr[pos] to new_val and make required changes to segtreevoid update(int node, int tl, int tr, int pos, int new_val){ // if current range only contains one point, this must // be arr[pos], update the corresponding node to new_val if (tl == tr) { seg_tree[node] = new_val; } else { // else divide the range into two parts int tm = (tr - tl) / 2 + tl; // if pos lies in first half, update this half, else // update second half if (pos <= tm) { update(2 * node, tl, tm, pos, new_val); } else { update(2 * node + 1, tm + 1, tr, pos, new_val); } // combine results from both halfs seg_tree[node] = combine(seg_tree[2 * node], seg_tree[2 * node + 1]); }} // query function, returns minimum in the range [l, r]int query(int node, int tl, int tr, int l, int r){ // if range is invalid, then return infinity if (l > r) { return INT32_MAX; } // if range completely aligns with a segment tree node, // then value of this node should be returned if (l == tl && r == tr) { return seg_tree[node]; } // else divide the query into two parts int tm = (tr - tl) / 2 + tl; int q1 = query(2 * node, tl, tm, l, min(r, tm)); int q2 = query(2 * node + 1, tm + 1, tr, max(l, tm + 1), r); // and combine the results from the two parts and return // it return combine(q1, q2);} // --------Segment Tree Ends Here----------------- void printNSE(vector<int> original, int n){ vector<int> sorted(n); map<int, int> encode; // -------Coordinate Compression Starts Here ------ // created a temporary sorted array out of original for (int i = 0; i < n; i++) { sorted[i] = original[i]; } sort(sorted.begin(), sorted.end()); // encode each value to a new value in sorted array int ctr = 0; for (int i = 0; i < n; i++) { if (encode.count(sorted[i]) == 0) { encode[sorted[i]] = ctr++; } } // use encode to compress original array vector<int> compressed(n); for (int i = 0; i < n; i++) { compressed[i] = encode[original[i]]; } // -------Coordinate Compression Ends Here ------ // Create an aux array of size ctr, and build a segtree // based on this array vector<int> aux(ctr, INT32_MAX); seg_tree = vector<int>(4 * ctr); build(aux, 1, 0, ctr - 1); // For each compressed[i], query for index of NSE and // update segment tree vector<int> ans(n); for (int i = n - 1; i >= 0; i--) { ans[i] = query(1, 0, ctr - 1, 0, compressed[i] - 1); update(1, 0, ctr - 1, compressed[i], i); } // Print -1 if NSE doesn't exist, otherwise print NSE // itself for (int i = 0; i < n; i++) { cout << original[i] << " ---> "; if (ans[i] == INT32_MAX) { cout << -1; } else { cout << original[ans[i]]; } cout << "\n"; }} // Driver program to test above functionsint main(){ vector<int> arr = { 11, 13, 21, 3 }; printNSE(arr, 4); return 0;}
11 ---> 3
13 ---> 3
21 ---> 3
3 ---> -1
Time Complexity:
Auxiliary Space: O(N)
Method 4 (Using Stack) This problem is similar to next greater element. Here we maintain items in increasing order in the stack (instead of decreasing in next greater element problem).
Push the first element to stack.Pick rest of the elements one by one and follow following steps in loop.Mark the current element as next.If stack is not empty, then compare next with stack top. If next is smaller than top then next is the NSE for the top. Keep popping from the stack while top is greater than next. next becomes the NSE for all such popped elementsPush next into the stackAfter the loop in step 2 is over, pop all the elements from stack and print -1 as next element for them.
Push the first element to stack.
Pick rest of the elements one by one and follow following steps in loop.Mark the current element as next.If stack is not empty, then compare next with stack top. If next is smaller than top then next is the NSE for the top. Keep popping from the stack while top is greater than next. next becomes the NSE for all such popped elementsPush next into the stack
Mark the current element as next.
If stack is not empty, then compare next with stack top. If next is smaller than top then next is the NSE for the top. Keep popping from the stack while top is greater than next. next becomes the NSE for all such popped elements
Push next into the stack
After the loop in step 2 is over, pop all the elements from stack and print -1 as next element for them.
Note: To achieve same order, we use a stack of pairs, where first element is the value and second element is index of array element.
C++
Java
Python3
C#
Javascript
// A Stack based C++ program to find next// smaller element for all array elements#include <bits/stdc++.h>using namespace std; // prints NSE for elements of array arr[] of size n void printNSE(int arr[], int n){ stack<pair<int, int> > s; vector<int> ans(n); // iterate for rest of the elements for (int i = 0; i < n; i++) { int next = arr[i]; // if stack is empty then this element can't be NSE // for any other element, so just push it to stack // so that we can find NSE for it, and continue if (s.empty()) { s.push({ next, i }); continue; } // while stack is not empty and the top element is // greater than next // a) NSE for top is next, use top's index to // maintain original order // b) pop the top element from stack while (!s.empty() && s.top().first > next) { ans[s.top().second] = next; s.pop(); } // push next to stack so that we can find NSE for it s.push({ next, i }); } // After iterating over the loop, the remaining elements // in stack do not have any NSE, so set -1 for them while (!s.empty()) { ans[s.top().second] = -1; s.pop(); } for (int i = 0; i < n; i++) { cout << arr[i] << " ---> " << ans[i] << endl; }} // Driver program to test above functionsint main(){ int arr[] = { 11, 13, 21, 3 }; int n = sizeof(arr) / sizeof(arr[0]); printNSE(arr, n); return 0;}
// A Stack based Java program to find next// smaller element for all array elements// in same order as input.import java.io.*;import java.lang.*;import java.util.*; class GFG { /* prints element and NSE pair for all elements of arr[] of size n */ public static void printNSE(int arr[], int n) { Stack<Integer> s = new Stack<Integer>(); HashMap<Integer, Integer> mp = new HashMap<Integer, Integer>(); /* push the first element to stack */ s.push(arr[0]); // iterate for rest of the elements for (int i = 1; i < n; i++) { if (s.empty()) { s.push(arr[i]); continue; } /* if stack is not empty, then pop an element from stack. If the popped element is greater than next, then a) print the pair b) keep popping while elements are greater and stack is not empty */ while (s.empty() == false && s.peek() > arr[i]) { mp.put(s.peek(), arr[i]); s.pop(); } /* push next to stack so that we can find next smaller for it */ s.push(arr[i]); } /* After iterating over the loop, the remaining elements in stack do not have the next smaller element, so print -1 for them */ while (s.empty() == false) { mp.put(s.peek(), -1); s.pop(); } for (int i = 0; i < n; i++) System.out.println(arr[i] + " ---> " + mp.get(arr[i])); } /* Driver program to test above functions */ public static void main(String[] args) { int arr[] = { 11, 13, 21, 3 }; int n = arr.length; printNSE(arr, n); }}
# A Stack based Python3 program to find next# smaller element for all array elements# in same order as input.using System; """ prints element and NSE pair for allelements of arr[] of size n """ def printNSE(arr, n): s = [] mp = {} # push the first element to stack s.append(arr[0]) # iterate for rest of the elements for i in range(1, n): if (len(s) == 0): s.append(arr[i]) continue """ if stack is not empty, then pop an element from stack. If the popped element is greater than next, then a) print the pair b) keep popping while elements are greater and stack is not empty """ while (len(s) != 0 and s[-1] > arr[i]): mp[s[-1]] = arr[i] s.pop() """ push next to stack so that we can find next smaller for it """ s.append(arr[i]) """ After iterating over the loop, the remaining elements in stack do not have the next smaller element, so print -1 for them """ while (len(s) != 0): mp[s[-1]] = -1 s.pop() for i in range(n): print(arr[i], "--->", mp[arr[i]]) arr = [11, 13, 21, 3]n = len(arr)printNSE(arr, n) # This code is contributed by decode2207.
// A Stack based C# program to find next// smaller element for all array elements// in same order as input.using System;using System;using System.Collections.Generic; class GFG { /* prints element and NSE pair for all elements of arr[] of size n */ public static void printNSE(int[] arr, int n) { Stack<int> s = new Stack<int>(); Dictionary<int, int> mp = new Dictionary<int, int>(); /* push the first element to stack */ s.Push(arr[0]); // iterate for rest of the elements for (int i = 1; i < n; i++) { if (s.Count == 0) { s.Push(arr[i]); continue; } /* if stack is not empty, then pop an element from stack. If the popped element is greater than next, then a) print the pair b) keep popping while elements are greater and stack is not empty */ while (s.Count != 0 && s.Peek() > arr[i]) { mp.Add(s.Peek(), arr[i]); s.Pop(); } /* push next to stack so that we can find next smaller for it */ s.Push(arr[i]); } /* After iterating over the loop, the remaining elements in stack do not have the next smaller element, so print -1 for them */ while (s.Count != 0) { mp.Add(s.Peek(), -1); s.Pop(); } for (int i = 0; i < n; i++) Console.WriteLine(arr[i] + " ---> " + mp[arr[i]]); } // Driver code public static void Main() { int[] arr = { 11, 13, 21, 3 }; int n = arr.Length; printNSE(arr, n); }}// This code is contributed by// 29AjayKumar
<script> // A Stack based Javascript program to find next // smaller element for all array elements // in same order as input. /* prints element and NSE pair for all elements of arr[] of size n */ function printNSE(arr, n) { let s = []; let mp = new Map(); /* push the first element to stack */ s.push(arr[0]); // iterate for rest of the elements for (let i = 1; i < n; i++) { if (s.length==0) { s.push(arr[i]); continue; } /* if stack is not empty, then pop an element from stack. If the popped element is greater than next, then a) print the pair b) keep popping while elements are greater and stack is not empty */ while (s.length != 0 && s[s.length - 1] > arr[i]) { mp[s[s.length - 1]] = arr[i]; s.pop(); } /* push next to stack so that we can find next smaller for it */ s.push(arr[i]); } /* After iterating over the loop, the remaining elements in stack do not have the next smaller element, so print -1 for them */ while (s.length != 0) { mp[s[s.length - 1]] = -1; s.pop(); } for (let i = 0; i < n; i++) document.write(arr[i] + " ---> " + mp[arr[i]] + "</br>"); } let arr = [11, 13, 21, 3]; let n = arr.length; printNSE(arr, n); // This code is contributed by divyesh072019.</script>
11 ---> 3
13 ---> 3
21 ---> 3
3 ---> -1
Time Complexity:
As we use only single for loop and all the elements in the stack are push and poped atmost once.
Auxiliary Space: O(N)
As extra space is used for storing the elements of the stack.
nabaneet247
princiraj1992
29AjayKumar
shivanisinghss2110
birlaritik113
rvriteshwar167
itsok
patel2127
decode2207
divyesh072019
sarvjot
abhijeet19403
cpp-stack
Arrays
Searching
Stack
Arrays
Searching
Stack
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in Java
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Introduction to Arrays
K'th Smallest/Largest Element in Unsorted Array | Set 1
Subset Sum Problem | DP-25
Binary Search
K'th Smallest/Largest Element in Unsorted Array | Set 1
Search an element in a sorted and rotated array
Find the Missing Number
Search, insert and delete in an unsorted array
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n10 Jun, 2022"
},
{
"code": null,
"e": 526,
"s": 54,
"text": "Given an array, print the Next Smaller Element (NSE) for every element. The NSE for an element x is the first smaller element on the right side of x in array. Elements for which no smaller element exist (on right side), consider NSE as -1. Examples: a) For any array, rightmost element always has NSE as -1. b) For an array which is sorted in increasing order, all elements have NSE as -1. c) For the input array [4, 8, 5, 2, 25}, the NSE for each element are as follows."
},
{
"code": null,
"e": 641,
"s": 526,
"text": "Element NSE\n 4 --> 2\n 8 --> 5\n 5 --> 2\n 2 --> -1\n 25 --> -1"
},
{
"code": null,
"e": 741,
"s": 641,
"text": "d) For the input array [13, 7, 6, 12}, the next smaller elements for each element are as follows. "
},
{
"code": null,
"e": 842,
"s": 741,
"text": " Element NSE\n 13 --> 7\n 7 --> 6\n 6 --> -1\n 12 --> -1"
},
{
"code": null,
"e": 1156,
"s": 842,
"text": "Method 1 (Simple) Use two loops: The outer loop picks all the elements one by one. The inner loop looks for the first smaller element for the element picked by outer loop. If a smaller element is found then that element is printed as next, otherwise, -1 is printed.Thanks to Sachin for providing following code. "
},
{
"code": null,
"e": 1160,
"s": 1156,
"text": "C++"
},
{
"code": null,
"e": 1162,
"s": 1160,
"text": "C"
},
{
"code": null,
"e": 1167,
"s": 1162,
"text": "Java"
},
{
"code": null,
"e": 1174,
"s": 1167,
"text": "Python"
},
{
"code": null,
"e": 1177,
"s": 1174,
"text": "C#"
},
{
"code": null,
"e": 1181,
"s": 1177,
"text": "PHP"
},
{
"code": null,
"e": 1192,
"s": 1181,
"text": "Javascript"
},
{
"code": "// Simple C++ program to print// next smaller elements in a given array#include \"bits/stdc++.h\"using namespace std; /* prints element and NSE pairfor all elements of arr[] of size n */void printNSE(int arr[], int n){ int next, i, j; for (i = 0; i < n; i++) { next = -1; for (j = i + 1; j < n; j++) { if (arr[i] > arr[j]) { next = arr[j]; break; } } cout << arr[i] << \" -- \" << next << endl; }} // Driver Codeint main(){ int arr[]= {11, 13, 21, 3}; int n = sizeof(arr) / sizeof(arr[0]); printNSE(arr, n); return 0;} // This code is contributed by shivanisinghss2110",
"e": 1891,
"s": 1192,
"text": null
},
{
"code": "// Simple C program to print next smaller elements// in a given array#include<stdio.h> /* prints element and NSE pair for all elements ofarr[] of size n */void printNSE(int arr[], int n){ int next, i, j; for (i=0; i<n; i++) { next = -1; for (j = i+1; j<n; j++) { if (arr[i] > arr[j]) { next = arr[j]; break; } } printf(\"%d -- %d\\n\", arr[i], next); }} int main(){ int arr[]= {11, 13, 21, 3}; int n = sizeof(arr)/sizeof(arr[0]); printNSE(arr, n); return 0;}",
"e": 2469,
"s": 1891,
"text": null
},
{
"code": "// Simple Java program to print next// smaller elements in a given array class Main { /* prints element and NSE pair for all elements of arr[] of size n */ static void printNSE(int arr[], int n) { int next, i, j; for (i = 0; i < n; i++) { next = -1; for (j = i + 1; j < n; j++) { if (arr[i] > arr[j]) { next = arr[j]; break; } } System.out.println(arr[i] + \" -- \" + next); } } public static void main(String args[]) { int arr[] = { 11, 13, 21, 3 }; int n = arr.length; printNSE(arr, n); }}",
"e": 3139,
"s": 2469,
"text": null
},
{
"code": "# Function to print element and NSE pair for all elements of listdef printNSE(arr): for i in range(0, len(arr), 1): next = -1 for j in range(i + 1, len(arr), 1): if arr[i] > arr[j]: next = arr[j] break print(str(arr[i]) + \" -- \" + str(next)) # Driver program to test above functionarr = [11, 13, 21, 3]printNSE(arr) # This code is contributed by Sunny Karira",
"e": 3578,
"s": 3139,
"text": null
},
{
"code": "// Simple C# program to print next// smaller elements in a given arrayusing System; class GFG { /* prints element and NSE pair for all elements of arr[] of size n */ static void printNSE(int[] arr, int n) { int next, i, j; for (i = 0; i < n; i++) { next = -1; for (j = i + 1; j < n; j++) { if (arr[i] > arr[j]) { next = arr[j]; break; } } Console.WriteLine(arr[i] + \" -- \" + next); } } // driver code public static void Main() { int[] arr = { 11, 13, 21, 3 }; int n = arr.Length; printNSE(arr, n); }} // This code is contributed by Sam007",
"e": 4301,
"s": 3578,
"text": null
},
{
"code": "<?php// Simple PHP program to print next// smaller elements in a given array /* prints element and NSE pair for all elements of arr[] of size n */function printNSE($arr, $n){ for ($i = 0; $i < $n; $i++) { $next = -1; for ($j = $i + 1; $j < $n; $j++) { if ($arr[$i] > $arr[$j]) { $next = $arr[$j]; break; } } echo $arr[$i].\" -- \". $next.\"\\n\"; }} // Driver Code $arr= array(11, 13, 21, 3); $n = count($arr); printNSE($arr, $n); // This code is contributed by Sam007?>",
"e": 4902,
"s": 4301,
"text": null
},
{
"code": "<script> // Simple Javascript program to print// next smaller elements in a given array /* prints element and NSE pairfor all elements of arr[] of size n */function printNSE(arr, n){ var next, i, j; for (i = 0; i < n; i++) { next = -1; for (j = i + 1; j < n; j++) { if (arr[i] > arr[j]) { next = arr[j]; break; } } document.write( arr[i] + \" -- \" + next+\"<br>\" ); }} // Driver Codevar arr= [11, 13, 21, 3]; var n = arr.length;printNSE(arr, n); </script>",
"e": 5479,
"s": 4902,
"text": null
},
{
"code": null,
"e": 5511,
"s": 5479,
"text": "11 -- 3\n13 -- 3\n21 -- 3\n3 -- -1"
},
{
"code": null,
"e": 5529,
"s": 5511,
"text": "Time Complexity: "
},
{
"code": null,
"e": 5601,
"s": 5529,
"text": "The worst case occurs when all elements are sorted in decreasing order."
},
{
"code": null,
"e": 5624,
"s": 5601,
"text": "Auxiliary Space: O(1) "
},
{
"code": null,
"e": 5656,
"s": 5624,
"text": "As constant extra space is used"
},
{
"code": null,
"e": 5705,
"s": 5656,
"text": "Method 2 (Using Segment Tree and Binary Search) "
},
{
"code": null,
"e": 5991,
"s": 5705,
"text": "This method is also pretty simple if one knows Segment trees and Binary Search. Lets consider an array and lets suppose NSE for is , we simply need to binary search for in range to . will be the first index , such that range minimum of elements from index to () is lesser than ."
},
{
"code": null,
"e": 5995,
"s": 5991,
"text": "C++"
},
{
"code": "#include <bits/stdc++.h>using namespace std; // Program to find next smaller element for all elements in// an array, using segment tree and binary search // --------Segment Tree Starts Here----------------- vector<int> seg_tree; // combine function for combining two nodes of the tree, in// this case we need to take min of twoint combine(int a, int b) { return min(a, b); } // build function, builds seg_tree based on vector parameter// arrvoid build(vector<int>& arr, int node, int tl, int tr){ // if current range consists only of one element, then // node should be this element if (tl == tr) { seg_tree[node] = arr[tl]; } else { // divide the build operations into two parts int tm = (tr - tl) / 2 + tl; build(arr, 2 * node, tl, tm); build(arr, 2 * node + 1, tm + 1, tr); // combine the results from two parts, and store it // into current node seg_tree[node] = combine(seg_tree[2 * node], seg_tree[2 * node + 1]); }} // query function, returns minimum in the range [l, r]int query(int node, int tl, int tr, int l, int r){ // if range is invalid, then return infinity if (l > r) { return INT32_MAX; } // if range completely aligns with a segment tree node, // then value of this node should be returned if (l == tl && r == tr) { return seg_tree[node]; } // else divide the query into two parts int tm = (tr - tl) / 2 + tl; int q1 = query(2 * node, tl, tm, l, min(r, tm)); int q2 = query(2 * node + 1, tm + 1, tr, max(l, tm + 1), r); // and combine the results from the two parts and return // it return combine(q1, q2);} // --------Segment Tree Ends Here----------------- void printNSE(vector<int> arr, int n){ seg_tree = vector<int>(4 * n); // build segment tree initially build(arr, 1, 0, n - 1); int q, l, r, mid, ans; for (int i = 0; i < n; i++) { // binary search for ans in range [i + 1, n - 1], // initially ans is -1 representing there is no NSE // for this element l = i + 1; r = n - 1; ans = -1; while (l <= r) { mid = (r - l) / 2 + l; // q is the minimum element in range [l, mid] q = query(1, 0, n - 1, l, mid); // if the minimum element in range [l, mid] is // less than arr[i], then mid can be answer, we // mark it, and look for a better answer in left // half. Else if q is greater than arr[i], mid // can't be an answer, we should search in right // half if (q < arr[i]) { ans = arr[mid]; r = mid - 1; } else { l = mid + 1; } } // print NSE for arr[i] cout << arr[i] << \" ---> \" << ans << \"\\n\"; }} // Driver program to test above functionsint main(){ vector<int> arr = { 11, 13, 21, 3 }; printNSE(arr, 4); return 0;}",
"e": 9011,
"s": 5995,
"text": null
},
{
"code": null,
"e": 9051,
"s": 9011,
"text": "11 ---> 3\n13 ---> 3\n21 ---> 3\n3 ---> -1"
},
{
"code": null,
"e": 9070,
"s": 9051,
"text": "Time Complexity : "
},
{
"code": null,
"e": 9201,
"s": 9070,
"text": " For each of array elements we do a binary search, which includes steps, and each step costs operations [range minimum queries]."
},
{
"code": null,
"e": 9223,
"s": 9201,
"text": "Auxiliary Space: O(N)"
},
{
"code": null,
"e": 9292,
"s": 9223,
"text": "As extra space is used for storing the elements of the segment tree."
},
{
"code": null,
"e": 9349,
"s": 9292,
"text": "Method 3 (Using Segment Tree and Coordinate Compression)"
},
{
"code": null,
"e": 9432,
"s": 9349,
"text": "In this approach, we build a segment tree on indices of compressed array elements:"
},
{
"code": null,
"e": 10544,
"s": 9432,
"text": "Somewhere along the lines, we would build a array such-that is the smallest index at which is present in input array.Its easy to see that we need to compress the input array so as to build this array because if exceeds (memory limit of online judge) chances are we would get a segmentation fault.To compress we sort the input array, and then for each new value seen in array we map it to a corresponding smaller value, if possible. Use these mapped values to generate a array with same order as input array.So now that we are done with compression, we can begin with the query part:Suppose in previous step, we compressed the array to distinct values. Initially set , this signifies no value is processed at any index as of now.Traverse the compressed array in reverse order, this would imply that in past we would have only processed elements that are on the right side.For , query (and store in ) the smallest index of values using segment tree, this must be the NSE for !Update the index of to .We stored the index of NSEs for all array elements, we can easily print NSEs themselves as shown in code."
},
{
"code": null,
"e": 10664,
"s": 10544,
"text": "Somewhere along the lines, we would build a array such-that is the smallest index at which is present in input array."
},
{
"code": null,
"e": 10846,
"s": 10664,
"text": "Its easy to see that we need to compress the input array so as to build this array because if exceeds (memory limit of online judge) chances are we would get a segmentation fault."
},
{
"code": null,
"e": 11059,
"s": 10846,
"text": "To compress we sort the input array, and then for each new value seen in array we map it to a corresponding smaller value, if possible. Use these mapped values to generate a array with same order as input array."
},
{
"code": null,
"e": 11554,
"s": 11059,
"text": "So now that we are done with compression, we can begin with the query part:Suppose in previous step, we compressed the array to distinct values. Initially set , this signifies no value is processed at any index as of now.Traverse the compressed array in reverse order, this would imply that in past we would have only processed elements that are on the right side.For , query (and store in ) the smallest index of values using segment tree, this must be the NSE for !Update the index of to ."
},
{
"code": null,
"e": 11702,
"s": 11554,
"text": "Suppose in previous step, we compressed the array to distinct values. Initially set , this signifies no value is processed at any index as of now."
},
{
"code": null,
"e": 11975,
"s": 11702,
"text": "Traverse the compressed array in reverse order, this would imply that in past we would have only processed elements that are on the right side.For , query (and store in ) the smallest index of values using segment tree, this must be the NSE for !Update the index of to ."
},
{
"code": null,
"e": 12080,
"s": 11975,
"text": "For , query (and store in ) the smallest index of values using segment tree, this must be the NSE for !"
},
{
"code": null,
"e": 12106,
"s": 12080,
"text": "Update the index of to ."
},
{
"code": null,
"e": 12212,
"s": 12106,
"text": "We stored the index of NSEs for all array elements, we can easily print NSEs themselves as shown in code."
},
{
"code": null,
"e": 12393,
"s": 12212,
"text": "Note: In implementation we use INT32_MAX instead of -1 because storing INT32_MAX doesn’t affect our min-segment tree and still serves the purpose of identifying unprocessed values."
},
{
"code": null,
"e": 12462,
"s": 12393,
"text": "As extra space is used for storing the elements of the segment tree."
},
{
"code": null,
"e": 12466,
"s": 12462,
"text": "C++"
},
{
"code": "#include <bits/stdc++.h>using namespace std; // Program to find next smaller element for all elements in// an array, using segment tree and coordinate compression // --------Segment Tree Starts Here----------------- vector<int> seg_tree; // combine function for combining two nodes of the tree, in// this case we need to take min of twoint combine(int a, int b) { return min(a, b); } // build function, builds seg_tree based on vector parameter// arrvoid build(vector<int>& arr, int node, int tl, int tr){ // if current range consists only of one element, then // node should be this element if (tl == tr) { seg_tree[node] = arr[tl]; } else { // divide the build operations into two parts int tm = (tr - tl) / 2 + tl; build(arr, 2 * node, tl, tm); build(arr, 2 * node + 1, tm + 1, tr); // combine the results from two parts, and store it // into current node seg_tree[node] = combine(seg_tree[2 * node], seg_tree[2 * node + 1]); }} // update function, used to make a point update, update// arr[pos] to new_val and make required changes to segtreevoid update(int node, int tl, int tr, int pos, int new_val){ // if current range only contains one point, this must // be arr[pos], update the corresponding node to new_val if (tl == tr) { seg_tree[node] = new_val; } else { // else divide the range into two parts int tm = (tr - tl) / 2 + tl; // if pos lies in first half, update this half, else // update second half if (pos <= tm) { update(2 * node, tl, tm, pos, new_val); } else { update(2 * node + 1, tm + 1, tr, pos, new_val); } // combine results from both halfs seg_tree[node] = combine(seg_tree[2 * node], seg_tree[2 * node + 1]); }} // query function, returns minimum in the range [l, r]int query(int node, int tl, int tr, int l, int r){ // if range is invalid, then return infinity if (l > r) { return INT32_MAX; } // if range completely aligns with a segment tree node, // then value of this node should be returned if (l == tl && r == tr) { return seg_tree[node]; } // else divide the query into two parts int tm = (tr - tl) / 2 + tl; int q1 = query(2 * node, tl, tm, l, min(r, tm)); int q2 = query(2 * node + 1, tm + 1, tr, max(l, tm + 1), r); // and combine the results from the two parts and return // it return combine(q1, q2);} // --------Segment Tree Ends Here----------------- void printNSE(vector<int> original, int n){ vector<int> sorted(n); map<int, int> encode; // -------Coordinate Compression Starts Here ------ // created a temporary sorted array out of original for (int i = 0; i < n; i++) { sorted[i] = original[i]; } sort(sorted.begin(), sorted.end()); // encode each value to a new value in sorted array int ctr = 0; for (int i = 0; i < n; i++) { if (encode.count(sorted[i]) == 0) { encode[sorted[i]] = ctr++; } } // use encode to compress original array vector<int> compressed(n); for (int i = 0; i < n; i++) { compressed[i] = encode[original[i]]; } // -------Coordinate Compression Ends Here ------ // Create an aux array of size ctr, and build a segtree // based on this array vector<int> aux(ctr, INT32_MAX); seg_tree = vector<int>(4 * ctr); build(aux, 1, 0, ctr - 1); // For each compressed[i], query for index of NSE and // update segment tree vector<int> ans(n); for (int i = n - 1; i >= 0; i--) { ans[i] = query(1, 0, ctr - 1, 0, compressed[i] - 1); update(1, 0, ctr - 1, compressed[i], i); } // Print -1 if NSE doesn't exist, otherwise print NSE // itself for (int i = 0; i < n; i++) { cout << original[i] << \" ---> \"; if (ans[i] == INT32_MAX) { cout << -1; } else { cout << original[ans[i]]; } cout << \"\\n\"; }} // Driver program to test above functionsint main(){ vector<int> arr = { 11, 13, 21, 3 }; printNSE(arr, 4); return 0;}",
"e": 16697,
"s": 12466,
"text": null
},
{
"code": null,
"e": 16737,
"s": 16697,
"text": "11 ---> 3\n13 ---> 3\n21 ---> 3\n3 ---> -1"
},
{
"code": null,
"e": 16756,
"s": 16737,
"text": "Time Complexity: "
},
{
"code": null,
"e": 16778,
"s": 16756,
"text": "Auxiliary Space: O(N)"
},
{
"code": null,
"e": 16963,
"s": 16778,
"text": "Method 4 (Using Stack) This problem is similar to next greater element. Here we maintain items in increasing order in the stack (instead of decreasing in next greater element problem)."
},
{
"code": null,
"e": 17457,
"s": 16963,
"text": "Push the first element to stack.Pick rest of the elements one by one and follow following steps in loop.Mark the current element as next.If stack is not empty, then compare next with stack top. If next is smaller than top then next is the NSE for the top. Keep popping from the stack while top is greater than next. next becomes the NSE for all such popped elementsPush next into the stackAfter the loop in step 2 is over, pop all the elements from stack and print -1 as next element for them."
},
{
"code": null,
"e": 17490,
"s": 17457,
"text": "Push the first element to stack."
},
{
"code": null,
"e": 17848,
"s": 17490,
"text": "Pick rest of the elements one by one and follow following steps in loop.Mark the current element as next.If stack is not empty, then compare next with stack top. If next is smaller than top then next is the NSE for the top. Keep popping from the stack while top is greater than next. next becomes the NSE for all such popped elementsPush next into the stack"
},
{
"code": null,
"e": 17882,
"s": 17848,
"text": "Mark the current element as next."
},
{
"code": null,
"e": 18111,
"s": 17882,
"text": "If stack is not empty, then compare next with stack top. If next is smaller than top then next is the NSE for the top. Keep popping from the stack while top is greater than next. next becomes the NSE for all such popped elements"
},
{
"code": null,
"e": 18136,
"s": 18111,
"text": "Push next into the stack"
},
{
"code": null,
"e": 18241,
"s": 18136,
"text": "After the loop in step 2 is over, pop all the elements from stack and print -1 as next element for them."
},
{
"code": null,
"e": 18375,
"s": 18241,
"text": "Note: To achieve same order, we use a stack of pairs, where first element is the value and second element is index of array element. "
},
{
"code": null,
"e": 18379,
"s": 18375,
"text": "C++"
},
{
"code": null,
"e": 18384,
"s": 18379,
"text": "Java"
},
{
"code": null,
"e": 18392,
"s": 18384,
"text": "Python3"
},
{
"code": null,
"e": 18395,
"s": 18392,
"text": "C#"
},
{
"code": null,
"e": 18406,
"s": 18395,
"text": "Javascript"
},
{
"code": "// A Stack based C++ program to find next// smaller element for all array elements#include <bits/stdc++.h>using namespace std; // prints NSE for elements of array arr[] of size n void printNSE(int arr[], int n){ stack<pair<int, int> > s; vector<int> ans(n); // iterate for rest of the elements for (int i = 0; i < n; i++) { int next = arr[i]; // if stack is empty then this element can't be NSE // for any other element, so just push it to stack // so that we can find NSE for it, and continue if (s.empty()) { s.push({ next, i }); continue; } // while stack is not empty and the top element is // greater than next // a) NSE for top is next, use top's index to // maintain original order // b) pop the top element from stack while (!s.empty() && s.top().first > next) { ans[s.top().second] = next; s.pop(); } // push next to stack so that we can find NSE for it s.push({ next, i }); } // After iterating over the loop, the remaining elements // in stack do not have any NSE, so set -1 for them while (!s.empty()) { ans[s.top().second] = -1; s.pop(); } for (int i = 0; i < n; i++) { cout << arr[i] << \" ---> \" << ans[i] << endl; }} // Driver program to test above functionsint main(){ int arr[] = { 11, 13, 21, 3 }; int n = sizeof(arr) / sizeof(arr[0]); printNSE(arr, n); return 0;}",
"e": 19918,
"s": 18406,
"text": null
},
{
"code": "// A Stack based Java program to find next// smaller element for all array elements// in same order as input.import java.io.*;import java.lang.*;import java.util.*; class GFG { /* prints element and NSE pair for all elements of arr[] of size n */ public static void printNSE(int arr[], int n) { Stack<Integer> s = new Stack<Integer>(); HashMap<Integer, Integer> mp = new HashMap<Integer, Integer>(); /* push the first element to stack */ s.push(arr[0]); // iterate for rest of the elements for (int i = 1; i < n; i++) { if (s.empty()) { s.push(arr[i]); continue; } /* if stack is not empty, then pop an element from stack. If the popped element is greater than next, then a) print the pair b) keep popping while elements are greater and stack is not empty */ while (s.empty() == false && s.peek() > arr[i]) { mp.put(s.peek(), arr[i]); s.pop(); } /* push next to stack so that we can find next smaller for it */ s.push(arr[i]); } /* After iterating over the loop, the remaining elements in stack do not have the next smaller element, so print -1 for them */ while (s.empty() == false) { mp.put(s.peek(), -1); s.pop(); } for (int i = 0; i < n; i++) System.out.println(arr[i] + \" ---> \" + mp.get(arr[i])); } /* Driver program to test above functions */ public static void main(String[] args) { int arr[] = { 11, 13, 21, 3 }; int n = arr.length; printNSE(arr, n); }}",
"e": 21687,
"s": 19918,
"text": null
},
{
"code": "# A Stack based Python3 program to find next# smaller element for all array elements# in same order as input.using System; \"\"\" prints element and NSE pair for allelements of arr[] of size n \"\"\" def printNSE(arr, n): s = [] mp = {} # push the first element to stack s.append(arr[0]) # iterate for rest of the elements for i in range(1, n): if (len(s) == 0): s.append(arr[i]) continue \"\"\" if stack is not empty, then pop an element from stack. If the popped element is greater than next, then a) print the pair b) keep popping while elements are greater and stack is not empty \"\"\" while (len(s) != 0 and s[-1] > arr[i]): mp[s[-1]] = arr[i] s.pop() \"\"\" push next to stack so that we can find next smaller for it \"\"\" s.append(arr[i]) \"\"\" After iterating over the loop, the remaining elements in stack do not have the next smaller element, so print -1 for them \"\"\" while (len(s) != 0): mp[s[-1]] = -1 s.pop() for i in range(n): print(arr[i], \"--->\", mp[arr[i]]) arr = [11, 13, 21, 3]n = len(arr)printNSE(arr, n) # This code is contributed by decode2207.",
"e": 22926,
"s": 21687,
"text": null
},
{
"code": "// A Stack based C# program to find next// smaller element for all array elements// in same order as input.using System;using System;using System.Collections.Generic; class GFG { /* prints element and NSE pair for all elements of arr[] of size n */ public static void printNSE(int[] arr, int n) { Stack<int> s = new Stack<int>(); Dictionary<int, int> mp = new Dictionary<int, int>(); /* push the first element to stack */ s.Push(arr[0]); // iterate for rest of the elements for (int i = 1; i < n; i++) { if (s.Count == 0) { s.Push(arr[i]); continue; } /* if stack is not empty, then pop an element from stack. If the popped element is greater than next, then a) print the pair b) keep popping while elements are greater and stack is not empty */ while (s.Count != 0 && s.Peek() > arr[i]) { mp.Add(s.Peek(), arr[i]); s.Pop(); } /* push next to stack so that we can find next smaller for it */ s.Push(arr[i]); } /* After iterating over the loop, the remaining elements in stack do not have the next smaller element, so print -1 for them */ while (s.Count != 0) { mp.Add(s.Peek(), -1); s.Pop(); } for (int i = 0; i < n; i++) Console.WriteLine(arr[i] + \" ---> \" + mp[arr[i]]); } // Driver code public static void Main() { int[] arr = { 11, 13, 21, 3 }; int n = arr.Length; printNSE(arr, n); }}// This code is contributed by// 29AjayKumar",
"e": 24692,
"s": 22926,
"text": null
},
{
"code": "<script> // A Stack based Javascript program to find next // smaller element for all array elements // in same order as input. /* prints element and NSE pair for all elements of arr[] of size n */ function printNSE(arr, n) { let s = []; let mp = new Map(); /* push the first element to stack */ s.push(arr[0]); // iterate for rest of the elements for (let i = 1; i < n; i++) { if (s.length==0) { s.push(arr[i]); continue; } /* if stack is not empty, then pop an element from stack. If the popped element is greater than next, then a) print the pair b) keep popping while elements are greater and stack is not empty */ while (s.length != 0 && s[s.length - 1] > arr[i]) { mp[s[s.length - 1]] = arr[i]; s.pop(); } /* push next to stack so that we can find next smaller for it */ s.push(arr[i]); } /* After iterating over the loop, the remaining elements in stack do not have the next smaller element, so print -1 for them */ while (s.length != 0) { mp[s[s.length - 1]] = -1; s.pop(); } for (let i = 0; i < n; i++) document.write(arr[i] + \" ---> \" + mp[arr[i]] + \"</br>\"); } let arr = [11, 13, 21, 3]; let n = arr.length; printNSE(arr, n); // This code is contributed by divyesh072019.</script>",
"e": 26317,
"s": 24692,
"text": null
},
{
"code": null,
"e": 26357,
"s": 26317,
"text": "11 ---> 3\n13 ---> 3\n21 ---> 3\n3 ---> -1"
},
{
"code": null,
"e": 26375,
"s": 26357,
"text": "Time Complexity: "
},
{
"code": null,
"e": 26472,
"s": 26375,
"text": "As we use only single for loop and all the elements in the stack are push and poped atmost once."
},
{
"code": null,
"e": 26494,
"s": 26472,
"text": "Auxiliary Space: O(N)"
},
{
"code": null,
"e": 26557,
"s": 26494,
"text": "As extra space is used for storing the elements of the stack. "
},
{
"code": null,
"e": 26569,
"s": 26557,
"text": "nabaneet247"
},
{
"code": null,
"e": 26583,
"s": 26569,
"text": "princiraj1992"
},
{
"code": null,
"e": 26595,
"s": 26583,
"text": "29AjayKumar"
},
{
"code": null,
"e": 26614,
"s": 26595,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 26628,
"s": 26614,
"text": "birlaritik113"
},
{
"code": null,
"e": 26643,
"s": 26628,
"text": "rvriteshwar167"
},
{
"code": null,
"e": 26649,
"s": 26643,
"text": "itsok"
},
{
"code": null,
"e": 26659,
"s": 26649,
"text": "patel2127"
},
{
"code": null,
"e": 26670,
"s": 26659,
"text": "decode2207"
},
{
"code": null,
"e": 26684,
"s": 26670,
"text": "divyesh072019"
},
{
"code": null,
"e": 26692,
"s": 26684,
"text": "sarvjot"
},
{
"code": null,
"e": 26706,
"s": 26692,
"text": "abhijeet19403"
},
{
"code": null,
"e": 26716,
"s": 26706,
"text": "cpp-stack"
},
{
"code": null,
"e": 26723,
"s": 26716,
"text": "Arrays"
},
{
"code": null,
"e": 26733,
"s": 26723,
"text": "Searching"
},
{
"code": null,
"e": 26739,
"s": 26733,
"text": "Stack"
},
{
"code": null,
"e": 26746,
"s": 26739,
"text": "Arrays"
},
{
"code": null,
"e": 26756,
"s": 26746,
"text": "Searching"
},
{
"code": null,
"e": 26762,
"s": 26756,
"text": "Stack"
},
{
"code": null,
"e": 26860,
"s": 26762,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26892,
"s": 26860,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 26977,
"s": 26892,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 27000,
"s": 26977,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 27056,
"s": 27000,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 1"
},
{
"code": null,
"e": 27083,
"s": 27056,
"text": "Subset Sum Problem | DP-25"
},
{
"code": null,
"e": 27097,
"s": 27083,
"text": "Binary Search"
},
{
"code": null,
"e": 27153,
"s": 27097,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 1"
},
{
"code": null,
"e": 27201,
"s": 27153,
"text": "Search an element in a sorted and rotated array"
},
{
"code": null,
"e": 27225,
"s": 27201,
"text": "Find the Missing Number"
}
] |
Priority Queue in Reverse Order in Java
|
11 Aug, 2021
A PriorityQueue is used when the objects are supposed to be processed based on the priority. It is known that a Queue follows the First-In-First-Out algorithm, but sometimes the elements of the queue are needed to be processed according to the priority, that’s when the PriorityQueue comes into play. The PriorityQueue is based on the priority heap. The elements of the priority queue are ordered according to the natural ordering, or by a Comparator provided at queue construction time, depending on which constructor is used.
Declaration:
public class PriorityQueue<E> extends AbstractQueue<E> implements Serializable
where E is the type of elements held in this queue
Types of PriorityQueue
Max Priority Queue
Min Priority Queue
Example of Default Priority Queue
Java
// Java program to demonstrate the// working of default PriorityQueueimport java.util.*; class PriorityQueueDemo { // Main Method public static void main(String args[]) { // Creating empty priority queue PriorityQueue<Integer> pQueue = new PriorityQueue<Integer>(); // Adding items to the pQueue using add() pQueue.add(10); pQueue.add(20); pQueue.add(15); pQueue.add(5); // Printing the top element of PriorityQueue System.out.println(pQueue.peek()); // Printing the top element and removing it // from the PriorityQueue container System.out.println(pQueue.poll()); // Printing the top element again System.out.println(pQueue.peek()); }}
5
5
10
In Java, Priority Queue, by default implement min Priority Queue, If we need to change the order of Priority Queue from min to max Priority Queue, then we use some methods as follows:
Using default Comparator Collections.reverseOrder()
Using custom Comparator
Using lambda expression
Method 1: Using default Comparator Collections.reverseOrder()
The Collections.reverseOrder() method is used to get a reverse behavior of the default comparator. This is a by default comparator in java.util package.
Example:
Java
// Java program to demonstrate the// working of PriorityQueue in reverse orderimport java.util.*; class PriorityQueueDemo { // Main Method public static void main(String args[]) { // Creating empty priority queue PriorityQueue<Integer> pQueue = new PriorityQueue<Integer>( Collections.reverseOrder()); // Adding items to the pQueue using add() pQueue.add(10); pQueue.add(20); pQueue.add(15); pQueue.add(5); // Printing the top element of PriorityQueue System.out.println(pQueue.peek()); // Printing the top element and removing it // from the PriorityQueue container System.out.println(pQueue.poll()); // Printing the top element again System.out.println(pQueue.peek()); }}
20
20
15
Method 2: Using custom Comparator
The java.util.PriorityQueue.comparator() method shares an important function of setting and returning the comparator that can be used to order the elements in a PriorityQueue. The method returns a null value if the queue follows the natural ordering pattern of the elements.
Example:
Java
// Java program to demonstrate the// working of PriorityQueue in reverse order import java.util.*; public class PriorityQueueDemo { // Main Method public static void main(String[] args) { // Creating empty priority queue // with custom Comparator PriorityQueue<Integer> pQueue = new PriorityQueue<Integer>( new Comparator<Integer>() { // Compare method for place element in // reverse order public int compare(Integer a, Integer b) { if (a < b) return 1; if (a > b) return -1; return 0; } }); // Adding items to the pQueue using add() pQueue.add(10); pQueue.add(15); pQueue.add(20); pQueue.add(5); // Printing the top element of PriorityQueue System.out.println(pQueue.peek()); // Printing the top element and removing it // from the PriorityQueue container System.out.println(pQueue.poll()); // Printing the top element again System.out.println(pQueue.peek()); }}
20
20
15
Method 3: Using lambda expression
Lambda expression since Java 8 has come to use, lambda function names its input parameters a and b and returns (b-a), which is basically what the int comparator class does except it returns a-b.
Example:
Java
// Java program to demonstrate the// working of PriorityQueue in reverse orderimport java.util.*; class PriorityQueueDemo { // Main Method public static void main(String args[]) { // Creating empty priority queue PriorityQueue<Integer> pQueue = new PriorityQueue<Integer>((a, b) -> b - a); // Adding items to the pQueue using add() pQueue.add(10); pQueue.add(20); pQueue.add(15); pQueue.add(5); // Printing the top element of PriorityQueue System.out.println(pQueue.peek()); // Printing the top element and removing it // from the PriorityQueue container System.out.println(pQueue.poll()); // Printing the top element again System.out.println(pQueue.peek()); }}
20
20
15
adnanirshad158
Java-Collections
java-priority-queue
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n11 Aug, 2021"
},
{
"code": null,
"e": 582,
"s": 52,
"text": "A PriorityQueue is used when the objects are supposed to be processed based on the priority. It is known that a Queue follows the First-In-First-Out algorithm, but sometimes the elements of the queue are needed to be processed according to the priority, that’s when the PriorityQueue comes into play. The PriorityQueue is based on the priority heap. The elements of the priority queue are ordered according to the natural ordering, or by a Comparator provided at queue construction time, depending on which constructor is used. "
},
{
"code": null,
"e": 595,
"s": 582,
"text": "Declaration:"
},
{
"code": null,
"e": 674,
"s": 595,
"text": "public class PriorityQueue<E> extends AbstractQueue<E> implements Serializable"
},
{
"code": null,
"e": 725,
"s": 674,
"text": "where E is the type of elements held in this queue"
},
{
"code": null,
"e": 748,
"s": 725,
"text": "Types of PriorityQueue"
},
{
"code": null,
"e": 767,
"s": 748,
"text": "Max Priority Queue"
},
{
"code": null,
"e": 786,
"s": 767,
"text": "Min Priority Queue"
},
{
"code": null,
"e": 820,
"s": 786,
"text": "Example of Default Priority Queue"
},
{
"code": null,
"e": 825,
"s": 820,
"text": "Java"
},
{
"code": "// Java program to demonstrate the// working of default PriorityQueueimport java.util.*; class PriorityQueueDemo { // Main Method public static void main(String args[]) { // Creating empty priority queue PriorityQueue<Integer> pQueue = new PriorityQueue<Integer>(); // Adding items to the pQueue using add() pQueue.add(10); pQueue.add(20); pQueue.add(15); pQueue.add(5); // Printing the top element of PriorityQueue System.out.println(pQueue.peek()); // Printing the top element and removing it // from the PriorityQueue container System.out.println(pQueue.poll()); // Printing the top element again System.out.println(pQueue.peek()); }}",
"e": 1589,
"s": 825,
"text": null
},
{
"code": null,
"e": 1596,
"s": 1589,
"text": "5\n5\n10"
},
{
"code": null,
"e": 1781,
"s": 1596,
"text": "In Java, Priority Queue, by default implement min Priority Queue, If we need to change the order of Priority Queue from min to max Priority Queue, then we use some methods as follows: "
},
{
"code": null,
"e": 1833,
"s": 1781,
"text": "Using default Comparator Collections.reverseOrder()"
},
{
"code": null,
"e": 1857,
"s": 1833,
"text": "Using custom Comparator"
},
{
"code": null,
"e": 1881,
"s": 1857,
"text": "Using lambda expression"
},
{
"code": null,
"e": 1943,
"s": 1881,
"text": "Method 1: Using default Comparator Collections.reverseOrder()"
},
{
"code": null,
"e": 2096,
"s": 1943,
"text": "The Collections.reverseOrder() method is used to get a reverse behavior of the default comparator. This is a by default comparator in java.util package."
},
{
"code": null,
"e": 2106,
"s": 2096,
"text": "Example: "
},
{
"code": null,
"e": 2111,
"s": 2106,
"text": "Java"
},
{
"code": "// Java program to demonstrate the// working of PriorityQueue in reverse orderimport java.util.*; class PriorityQueueDemo { // Main Method public static void main(String args[]) { // Creating empty priority queue PriorityQueue<Integer> pQueue = new PriorityQueue<Integer>( Collections.reverseOrder()); // Adding items to the pQueue using add() pQueue.add(10); pQueue.add(20); pQueue.add(15); pQueue.add(5); // Printing the top element of PriorityQueue System.out.println(pQueue.peek()); // Printing the top element and removing it // from the PriorityQueue container System.out.println(pQueue.poll()); // Printing the top element again System.out.println(pQueue.peek()); }}",
"e": 2926,
"s": 2111,
"text": null
},
{
"code": null,
"e": 2935,
"s": 2926,
"text": "20\n20\n15"
},
{
"code": null,
"e": 2969,
"s": 2935,
"text": "Method 2: Using custom Comparator"
},
{
"code": null,
"e": 3244,
"s": 2969,
"text": "The java.util.PriorityQueue.comparator() method shares an important function of setting and returning the comparator that can be used to order the elements in a PriorityQueue. The method returns a null value if the queue follows the natural ordering pattern of the elements."
},
{
"code": null,
"e": 3254,
"s": 3244,
"text": "Example: "
},
{
"code": null,
"e": 3259,
"s": 3254,
"text": "Java"
},
{
"code": "// Java program to demonstrate the// working of PriorityQueue in reverse order import java.util.*; public class PriorityQueueDemo { // Main Method public static void main(String[] args) { // Creating empty priority queue // with custom Comparator PriorityQueue<Integer> pQueue = new PriorityQueue<Integer>( new Comparator<Integer>() { // Compare method for place element in // reverse order public int compare(Integer a, Integer b) { if (a < b) return 1; if (a > b) return -1; return 0; } }); // Adding items to the pQueue using add() pQueue.add(10); pQueue.add(15); pQueue.add(20); pQueue.add(5); // Printing the top element of PriorityQueue System.out.println(pQueue.peek()); // Printing the top element and removing it // from the PriorityQueue container System.out.println(pQueue.poll()); // Printing the top element again System.out.println(pQueue.peek()); }}",
"e": 4526,
"s": 3259,
"text": null
},
{
"code": null,
"e": 4535,
"s": 4526,
"text": "20\n20\n15"
},
{
"code": null,
"e": 4569,
"s": 4535,
"text": "Method 3: Using lambda expression"
},
{
"code": null,
"e": 4764,
"s": 4569,
"text": "Lambda expression since Java 8 has come to use, lambda function names its input parameters a and b and returns (b-a), which is basically what the int comparator class does except it returns a-b."
},
{
"code": null,
"e": 4774,
"s": 4764,
"text": "Example: "
},
{
"code": null,
"e": 4779,
"s": 4774,
"text": "Java"
},
{
"code": "// Java program to demonstrate the// working of PriorityQueue in reverse orderimport java.util.*; class PriorityQueueDemo { // Main Method public static void main(String args[]) { // Creating empty priority queue PriorityQueue<Integer> pQueue = new PriorityQueue<Integer>((a, b) -> b - a); // Adding items to the pQueue using add() pQueue.add(10); pQueue.add(20); pQueue.add(15); pQueue.add(5); // Printing the top element of PriorityQueue System.out.println(pQueue.peek()); // Printing the top element and removing it // from the PriorityQueue container System.out.println(pQueue.poll()); // Printing the top element again System.out.println(pQueue.peek()); }}",
"e": 5567,
"s": 4779,
"text": null
},
{
"code": null,
"e": 5576,
"s": 5567,
"text": "20\n20\n15"
},
{
"code": null,
"e": 5593,
"s": 5578,
"text": "adnanirshad158"
},
{
"code": null,
"e": 5610,
"s": 5593,
"text": "Java-Collections"
},
{
"code": null,
"e": 5630,
"s": 5610,
"text": "java-priority-queue"
},
{
"code": null,
"e": 5635,
"s": 5630,
"text": "Java"
},
{
"code": null,
"e": 5640,
"s": 5635,
"text": "Java"
},
{
"code": null,
"e": 5657,
"s": 5640,
"text": "Java-Collections"
},
{
"code": null,
"e": 5755,
"s": 5657,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5770,
"s": 5755,
"text": "Stream In Java"
},
{
"code": null,
"e": 5791,
"s": 5770,
"text": "Introduction to Java"
},
{
"code": null,
"e": 5812,
"s": 5791,
"text": "Constructors in Java"
},
{
"code": null,
"e": 5831,
"s": 5812,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 5848,
"s": 5831,
"text": "Generics in Java"
},
{
"code": null,
"e": 5878,
"s": 5848,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 5904,
"s": 5878,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 5920,
"s": 5904,
"text": "Strings in Java"
},
{
"code": null,
"e": 5957,
"s": 5920,
"text": "Differences between JDK, JRE and JVM"
}
] |
DateFormat getDateInstance() Method in Java with Examples
|
24 Jan, 2022
DateFormat class of java.text package is an abstract class that is used to format and parse dates for any locale. It allows us to format date to text and parse text to date. DateFormat class provides many functionalities to obtain, format, parse default date/time.
Note: DateFormat class extends Format class that means it is a subclass of Format class. Since DateFormat class is an abstract class, therefore, it can be used for date/time formatting subclasses, which format and parses dates or times in a language-independent manner.
Package-view:
java.text Package
DateFormat Class
getDateInstance() Method
getDateInstance() Method of DateFormat class in Java is used to get the date formatter. This date formatter comes with the default formatting style for a default locale.
Syntax:
public static final DateFormat getDateInstance()
Return Type: Returns a date formatted in a particular format.
Example 1:
Java
// Java Program to Illustrate getDateInstance() Method// of DateFormat Class // Importing required classesimport java.text.*;import java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] argv) { // Initializing the first formatter // using getDateInstance() method DateFormat DFormat = DateFormat.getDateInstance(); System.out.println("Object: " + DFormat); // Formatting the string String str = DFormat.format(new Date()); // Printing the string date on console System.out.println(str); }}
Object: java.text.SimpleDateFormat@ce9bf0a5
Mar 27, 2019
Example 2:
Java
// Java Program to Illustrate getDateInstance() Method// of DateFormat Class // Importing required classesimport java.text.*;import java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) throws InterruptedException { // Initializing SimpleDateFormat by // creating object of SimpleDateFormat class SimpleDateFormat SDFormat = new SimpleDateFormat("MM/dd/yyyy"); // Printing the formats Date date = new Date(); String str_Date1 = SDFormat.format(date); // Displaying the original date System.out.println("The Original: " + (str_Date1)); // Initializing the Date formatter DateFormat DFormat = DateFormat.getDateInstance(); System.out.println("Object: " + DFormat); // Formatting the string String str = DFormat.format(new Date()); // Printing the string date on console System.out.println(str); }}
The Original: 01/11/2022
Object: java.text.SimpleDateFormat@ad508834
Jan 11, 2022
solankimayank
Java-DateFormat
Java-Functions
Java-text package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Stream In Java
Collections in Java
Multidimensional Arrays in Java
Singleton Class in Java
Stack Class in Java
Set in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Jan, 2022"
},
{
"code": null,
"e": 293,
"s": 28,
"text": "DateFormat class of java.text package is an abstract class that is used to format and parse dates for any locale. It allows us to format date to text and parse text to date. DateFormat class provides many functionalities to obtain, format, parse default date/time."
},
{
"code": null,
"e": 565,
"s": 293,
"text": "Note: DateFormat class extends Format class that means it is a subclass of Format class. Since DateFormat class is an abstract class, therefore, it can be used for date/time formatting subclasses, which format and parses dates or times in a language-independent manner. "
},
{
"code": null,
"e": 579,
"s": 565,
"text": "Package-view:"
},
{
"code": null,
"e": 651,
"s": 579,
"text": "java.text Package\n DateFormat Class\n getDateInstance() Method"
},
{
"code": null,
"e": 821,
"s": 651,
"text": "getDateInstance() Method of DateFormat class in Java is used to get the date formatter. This date formatter comes with the default formatting style for a default locale."
},
{
"code": null,
"e": 830,
"s": 821,
"text": "Syntax: "
},
{
"code": null,
"e": 879,
"s": 830,
"text": "public static final DateFormat getDateInstance()"
},
{
"code": null,
"e": 941,
"s": 879,
"text": "Return Type: Returns a date formatted in a particular format."
},
{
"code": null,
"e": 952,
"s": 941,
"text": "Example 1:"
},
{
"code": null,
"e": 957,
"s": 952,
"text": "Java"
},
{
"code": "// Java Program to Illustrate getDateInstance() Method// of DateFormat Class // Importing required classesimport java.text.*;import java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] argv) { // Initializing the first formatter // using getDateInstance() method DateFormat DFormat = DateFormat.getDateInstance(); System.out.println(\"Object: \" + DFormat); // Formatting the string String str = DFormat.format(new Date()); // Printing the string date on console System.out.println(str); }}",
"e": 1566,
"s": 957,
"text": null
},
{
"code": null,
"e": 1623,
"s": 1566,
"text": "Object: java.text.SimpleDateFormat@ce9bf0a5\nMar 27, 2019"
},
{
"code": null,
"e": 1636,
"s": 1625,
"text": "Example 2:"
},
{
"code": null,
"e": 1641,
"s": 1636,
"text": "Java"
},
{
"code": "// Java Program to Illustrate getDateInstance() Method// of DateFormat Class // Importing required classesimport java.text.*;import java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) throws InterruptedException { // Initializing SimpleDateFormat by // creating object of SimpleDateFormat class SimpleDateFormat SDFormat = new SimpleDateFormat(\"MM/dd/yyyy\"); // Printing the formats Date date = new Date(); String str_Date1 = SDFormat.format(date); // Displaying the original date System.out.println(\"The Original: \" + (str_Date1)); // Initializing the Date formatter DateFormat DFormat = DateFormat.getDateInstance(); System.out.println(\"Object: \" + DFormat); // Formatting the string String str = DFormat.format(new Date()); // Printing the string date on console System.out.println(str); }}",
"e": 2632,
"s": 1641,
"text": null
},
{
"code": null,
"e": 2714,
"s": 2632,
"text": "The Original: 01/11/2022\nObject: java.text.SimpleDateFormat@ad508834\nJan 11, 2022"
},
{
"code": null,
"e": 2728,
"s": 2714,
"text": "solankimayank"
},
{
"code": null,
"e": 2744,
"s": 2728,
"text": "Java-DateFormat"
},
{
"code": null,
"e": 2759,
"s": 2744,
"text": "Java-Functions"
},
{
"code": null,
"e": 2777,
"s": 2759,
"text": "Java-text package"
},
{
"code": null,
"e": 2782,
"s": 2777,
"text": "Java"
},
{
"code": null,
"e": 2787,
"s": 2782,
"text": "Java"
},
{
"code": null,
"e": 2885,
"s": 2787,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2916,
"s": 2885,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 2935,
"s": 2916,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 2965,
"s": 2935,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 2983,
"s": 2965,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 2998,
"s": 2983,
"text": "Stream In Java"
},
{
"code": null,
"e": 3018,
"s": 2998,
"text": "Collections in Java"
},
{
"code": null,
"e": 3050,
"s": 3018,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 3074,
"s": 3050,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 3094,
"s": 3074,
"text": "Stack Class in Java"
}
] |
How to input multiple values from user in one line in Java?
|
To input multiple values from user in one line, the code is as follows −
Live Demo
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
System.out.print("Enter two floating point values : ");
Scanner my_scan = new Scanner(System.in);
double double_val = my_scan.nextFloat();
int int_val = my_scan.nextInt();
System.out.println("The floating point value is : " + double_val + " and the integer value is : "
+ int_val);
}
}
56.789 99
Enter two floating point values : The floating point value is : 56.78900146484375 and the integer
value is : 99
A class named Demo contains the main function, inside which a Scanner class object is created, and
two values, one double and one integer values are parsed. The values are taken from the standard
input and then displayed on the console.
The Scanner object parses the input directly, without splitting it into multiple strings. In addition to
this, the user can input the data on a single line or on multiple lines.
|
[
{
"code": null,
"e": 1260,
"s": 1187,
"text": "To input multiple values from user in one line, the code is as follows −"
},
{
"code": null,
"e": 1271,
"s": 1260,
"text": " Live Demo"
},
{
"code": null,
"e": 1686,
"s": 1271,
"text": "import java.util.Scanner;\npublic class Demo {\n public static void main(String[] args) {\n System.out.print(\"Enter two floating point values : \");\n Scanner my_scan = new Scanner(System.in);\n double double_val = my_scan.nextFloat();\n int int_val = my_scan.nextInt();\n System.out.println(\"The floating point value is : \" + double_val + \" and the integer value is : \"\n + int_val);\n }\n}"
},
{
"code": null,
"e": 1696,
"s": 1686,
"text": "56.789 99"
},
{
"code": null,
"e": 1808,
"s": 1696,
"text": "Enter two floating point values : The floating point value is : 56.78900146484375 and the integer\nvalue is : 99"
},
{
"code": null,
"e": 2045,
"s": 1808,
"text": "A class named Demo contains the main function, inside which a Scanner class object is created, and\ntwo values, one double and one integer values are parsed. The values are taken from the standard\ninput and then displayed on the console."
},
{
"code": null,
"e": 2223,
"s": 2045,
"text": "The Scanner object parses the input directly, without splitting it into multiple strings. In addition to\nthis, the user can input the data on a single line or on multiple lines."
}
] |
How to Find Duplicate Values in Excel Using VLOOKUP?
|
06 Jun, 2021
In this article, we will look into how we can use the VLOOKUP to find duplicate values in Excel.
To do so follow the below steps:
Let’s make two columns of different section to check VLOOKUP formula on columns:
Created Two Columns
Here is the formula we are going to use:
=VLOOKUP(List1,List2,TRUE,FALSE)
In this formula, the List-1 names will be searched in List-2. If there exists any duplicate name, the formula will return the name from List-1. Let`s look closely at our example for better clarification.
In C2 we will write this formula =VLOOKUP(A2:A10,B2:B10,TRUE,FALSE) and then press enter.
Now, we will see this result:
Here Himesh is duplicate value
Here the Himesh is found because the VLOOKUP function searches this name from Section A to Section B. When the same name is found it will output the result from Section A.
Now drag the list and see all values.
Here we drag the formulated Cells
The #N/A results are found because, in those particular cells, the names from column A are not found in column B.
In the Result column, you’re seeing a total of 2 duplicate values ( Himesh, Pragya). #N/A values are representing the unique values of column Section A.
We can also use the VLOOKUP to find duplicate values between two Excel worksheets. To do so follow the below steps:
Make two excel workbooks Section A and Section B.
Two Workbooks
In the B2 of Section B type the below code and press enter:-
=IF(ISERROR(VLOOKUP(A2,'Section A'!A1:A10,1,0)),"Unique","Duplicate")
Section A and Section B on different workbooks
We can also use the VLOOKUP to find duplicate values between two Excel workbooks. To do so follow the below steps:
Now we create a new Section A in a new Workbook with different values.
New Workbook
And In our main workbook which we were working (in our last example), create another worksheet titled Sheet 1 and again create a list of products.
Another workbook named Sheet1
Now in cell C2 of Sheet1, write down the following formula and press enter.
=IF(ISERROR(VLOOKUP(B2,[VL]Section A!$A$2:$A$10,1,0)),"Unique", "Duplicate")
You will get the result as Unique because value does not exist in Section A.
Result
Now Drag Down the formulated cell to see out the result of the whole column.
Picked
Excel
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n06 Jun, 2021"
},
{
"code": null,
"e": 149,
"s": 52,
"text": "In this article, we will look into how we can use the VLOOKUP to find duplicate values in Excel."
},
{
"code": null,
"e": 183,
"s": 149,
"text": " To do so follow the below steps:"
},
{
"code": null,
"e": 264,
"s": 183,
"text": "Let’s make two columns of different section to check VLOOKUP formula on columns:"
},
{
"code": null,
"e": 285,
"s": 264,
"text": "Created Two Columns "
},
{
"code": null,
"e": 326,
"s": 285,
"text": "Here is the formula we are going to use:"
},
{
"code": null,
"e": 359,
"s": 326,
"text": "=VLOOKUP(List1,List2,TRUE,FALSE)"
},
{
"code": null,
"e": 563,
"s": 359,
"text": "In this formula, the List-1 names will be searched in List-2. If there exists any duplicate name, the formula will return the name from List-1. Let`s look closely at our example for better clarification."
},
{
"code": null,
"e": 653,
"s": 563,
"text": "In C2 we will write this formula =VLOOKUP(A2:A10,B2:B10,TRUE,FALSE) and then press enter."
},
{
"code": null,
"e": 683,
"s": 653,
"text": "Now, we will see this result:"
},
{
"code": null,
"e": 714,
"s": 683,
"text": "Here Himesh is duplicate value"
},
{
"code": null,
"e": 886,
"s": 714,
"text": "Here the Himesh is found because the VLOOKUP function searches this name from Section A to Section B. When the same name is found it will output the result from Section A."
},
{
"code": null,
"e": 924,
"s": 886,
"text": "Now drag the list and see all values."
},
{
"code": null,
"e": 958,
"s": 924,
"text": "Here we drag the formulated Cells"
},
{
"code": null,
"e": 1072,
"s": 958,
"text": "The #N/A results are found because, in those particular cells, the names from column A are not found in column B."
},
{
"code": null,
"e": 1225,
"s": 1072,
"text": "In the Result column, you’re seeing a total of 2 duplicate values ( Himesh, Pragya). #N/A values are representing the unique values of column Section A."
},
{
"code": null,
"e": 1341,
"s": 1225,
"text": "We can also use the VLOOKUP to find duplicate values between two Excel worksheets. To do so follow the below steps:"
},
{
"code": null,
"e": 1391,
"s": 1341,
"text": "Make two excel workbooks Section A and Section B."
},
{
"code": null,
"e": 1405,
"s": 1391,
"text": "Two Workbooks"
},
{
"code": null,
"e": 1466,
"s": 1405,
"text": "In the B2 of Section B type the below code and press enter:-"
},
{
"code": null,
"e": 1536,
"s": 1466,
"text": "=IF(ISERROR(VLOOKUP(A2,'Section A'!A1:A10,1,0)),\"Unique\",\"Duplicate\")"
},
{
"code": null,
"e": 1583,
"s": 1536,
"text": "Section A and Section B on different workbooks"
},
{
"code": null,
"e": 1698,
"s": 1583,
"text": "We can also use the VLOOKUP to find duplicate values between two Excel workbooks. To do so follow the below steps:"
},
{
"code": null,
"e": 1769,
"s": 1698,
"text": "Now we create a new Section A in a new Workbook with different values."
},
{
"code": null,
"e": 1782,
"s": 1769,
"text": "New Workbook"
},
{
"code": null,
"e": 1929,
"s": 1782,
"text": "And In our main workbook which we were working (in our last example), create another worksheet titled Sheet 1 and again create a list of products."
},
{
"code": null,
"e": 1959,
"s": 1929,
"text": "Another workbook named Sheet1"
},
{
"code": null,
"e": 2035,
"s": 1959,
"text": "Now in cell C2 of Sheet1, write down the following formula and press enter."
},
{
"code": null,
"e": 2112,
"s": 2035,
"text": "=IF(ISERROR(VLOOKUP(B2,[VL]Section A!$A$2:$A$10,1,0)),\"Unique\", \"Duplicate\")"
},
{
"code": null,
"e": 2189,
"s": 2112,
"text": "You will get the result as Unique because value does not exist in Section A."
},
{
"code": null,
"e": 2196,
"s": 2189,
"text": "Result"
},
{
"code": null,
"e": 2273,
"s": 2196,
"text": "Now Drag Down the formulated cell to see out the result of the whole column."
},
{
"code": null,
"e": 2280,
"s": 2273,
"text": "Picked"
},
{
"code": null,
"e": 2286,
"s": 2280,
"text": "Excel"
}
] |
Python Bokeh – Plotting a Line Graph
|
03 Jul, 2020
Bokeh is a Python interactive data visualization. It renders its plots using HTML and JavaScript. It targets modern web browsers for presentation providing elegant, concise construction of novel graphics with high-performance interactivity.
Bokeh can be used to plot a line graph. Plotting a line graph can be done using the line() method of the plotting module.
Syntax : line(parameters)
Parameters :
x : x-coordinates of the points to be plotted
y : y-coordinates of the points to be plotted
line_alpha : percentage value of line alpha, default is 1
line_cap : value of line cap for the line, default is butt
line_color : color of the line, default is black
line_dash : value of line dash such as :soliddasheddotteddotdashdashdotdefault is solid
solid
dashed
dotted
dotdash
dashdot
default is solid
line_dash_offset : value of line dash offset, default is 0
line_join : value of line join, default in bevel
line_width : value of the width of the line, default is 1
name : user-supplied name for the model
tags : user-supplied values for this model
Other Parameters :
alpha : sets all alpha keyword arguments at once
color : sets all color keyword arguments at once
legend_field : name of a column in the data source that should be used
legend_group : name of a column in the data source that should be used
legend_label : labels the legend entry
muted : determines whether the glyph should be rendered as muted or not, default is False
name : optional user-supplied name to attach to the renderer
source : user-supplied data source
view : view for filtering the data source
visible : determines whether the glyph should be rendered or not, default is True
x_range_name : name of an extra range to use for mapping x-coordinates
y_range_name : name of an extra range to use for mapping y-coordinates
level : specifies the render level order for this glyph
Returns : an object of class GlyphRenderer
Example 1 :In this example we will be using the default values for plotting the graph.
# importing the modulesfrom bokeh.plotting import figure, output_file, show # file to save the modeloutput_file("gfg.html") # instantiating the figure objectgraph = figure(title = "Bokeh Line Graph") # the points to be plottedx = [1, 2, 3, 4, 5]y = [1, 6, 8, 2, 3] # plotting the line graphgraph.line(x, y) # displaying the modelshow(graph)
Output : Example 2 :In this example we will be plotting a line graph with dotted lines alongside other parameters.
# importing the modulesfrom bokeh.plotting import figure, output_file, show # file to save the modeloutput_file("gfg.html") # instantiating the figure objectgraph = figure(title = "Bokeh Line Graph") # name of the x-axisgraph.xaxis.axis_label = "x-axis" # name of the y-axisgraph.yaxis.axis_label = "y-axis" # the points to be plottedx = [1, 2, 3, 4, 5]y = [5, 2, 1, 7, 1] # color of the lineline_color = "red" # type of lineline_dash = "dotted" # offset of line dashline_dash_offset = 1 # name of the legendlegend_label = "Sample Line" # plotting the line graph for AAPLgraph.line(x, y, line_color = line_color, line_dash = line_dash, line_dash_offset = line_dash_offset, legend_label = legend_label) # displaying the modelshow(graph)
Output : Example 3 :Now we will see how to plot multiple lines in the same graph. We will generate the points using the random() function.
# importing the modulesfrom bokeh.plotting import figure, output_file, showimport random # file to save the modeloutput_file("gfg.html") # instantiating the figure objectgraph = figure(title = "Bokeh Line Graph") # name of the x-axisgraph.xaxis.axis_label = "x-axis" # name of the y-axisgraph.yaxis.axis_label = "y-axis" # plotting line 1# generating the points to be plottedx = []y = []for i in range(100): x.append(i)for i in range(100): y.append(1 + random.random()) # parameters of line 1line_color = "red"line_dash = "solid"legend_label = "Line 1" # plotting the linegraph.line(x, y, line_color = line_color, line_dash = line_dash, legend_label = legend_label) # plotting line 2# generating the points to be plottedx = []y = []for i in range(100): x.append(i)for i in range(100): y.append(random.random()) # parameters of line 2line_color = "green"line_dash = "dotdash"line_dash_offset = 1legend_label = "Line 2" # plotting the linegraph.line(x, y, line_color = line_color, line_dash = line_dash, line_dash_offset = line_dash_offset, legend_label = legend_label) # displaying the modelshow(graph)
Output :
Data Visualization
Python-Bokeh
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Different ways to create Pandas Dataframe
Taking input in Python
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Jul, 2020"
},
{
"code": null,
"e": 269,
"s": 28,
"text": "Bokeh is a Python interactive data visualization. It renders its plots using HTML and JavaScript. It targets modern web browsers for presentation providing elegant, concise construction of novel graphics with high-performance interactivity."
},
{
"code": null,
"e": 391,
"s": 269,
"text": "Bokeh can be used to plot a line graph. Plotting a line graph can be done using the line() method of the plotting module."
},
{
"code": null,
"e": 417,
"s": 391,
"text": "Syntax : line(parameters)"
},
{
"code": null,
"e": 430,
"s": 417,
"text": "Parameters :"
},
{
"code": null,
"e": 476,
"s": 430,
"text": "x : x-coordinates of the points to be plotted"
},
{
"code": null,
"e": 522,
"s": 476,
"text": "y : y-coordinates of the points to be plotted"
},
{
"code": null,
"e": 580,
"s": 522,
"text": "line_alpha : percentage value of line alpha, default is 1"
},
{
"code": null,
"e": 639,
"s": 580,
"text": "line_cap : value of line cap for the line, default is butt"
},
{
"code": null,
"e": 688,
"s": 639,
"text": "line_color : color of the line, default is black"
},
{
"code": null,
"e": 776,
"s": 688,
"text": "line_dash : value of line dash such as :soliddasheddotteddotdashdashdotdefault is solid"
},
{
"code": null,
"e": 782,
"s": 776,
"text": "solid"
},
{
"code": null,
"e": 789,
"s": 782,
"text": "dashed"
},
{
"code": null,
"e": 796,
"s": 789,
"text": "dotted"
},
{
"code": null,
"e": 804,
"s": 796,
"text": "dotdash"
},
{
"code": null,
"e": 812,
"s": 804,
"text": "dashdot"
},
{
"code": null,
"e": 829,
"s": 812,
"text": "default is solid"
},
{
"code": null,
"e": 888,
"s": 829,
"text": "line_dash_offset : value of line dash offset, default is 0"
},
{
"code": null,
"e": 937,
"s": 888,
"text": "line_join : value of line join, default in bevel"
},
{
"code": null,
"e": 995,
"s": 937,
"text": "line_width : value of the width of the line, default is 1"
},
{
"code": null,
"e": 1035,
"s": 995,
"text": "name : user-supplied name for the model"
},
{
"code": null,
"e": 1078,
"s": 1035,
"text": "tags : user-supplied values for this model"
},
{
"code": null,
"e": 1097,
"s": 1078,
"text": "Other Parameters :"
},
{
"code": null,
"e": 1146,
"s": 1097,
"text": "alpha : sets all alpha keyword arguments at once"
},
{
"code": null,
"e": 1195,
"s": 1146,
"text": "color : sets all color keyword arguments at once"
},
{
"code": null,
"e": 1266,
"s": 1195,
"text": "legend_field : name of a column in the data source that should be used"
},
{
"code": null,
"e": 1337,
"s": 1266,
"text": "legend_group : name of a column in the data source that should be used"
},
{
"code": null,
"e": 1376,
"s": 1337,
"text": "legend_label : labels the legend entry"
},
{
"code": null,
"e": 1466,
"s": 1376,
"text": "muted : determines whether the glyph should be rendered as muted or not, default is False"
},
{
"code": null,
"e": 1527,
"s": 1466,
"text": "name : optional user-supplied name to attach to the renderer"
},
{
"code": null,
"e": 1562,
"s": 1527,
"text": "source : user-supplied data source"
},
{
"code": null,
"e": 1604,
"s": 1562,
"text": "view : view for filtering the data source"
},
{
"code": null,
"e": 1686,
"s": 1604,
"text": "visible : determines whether the glyph should be rendered or not, default is True"
},
{
"code": null,
"e": 1757,
"s": 1686,
"text": "x_range_name : name of an extra range to use for mapping x-coordinates"
},
{
"code": null,
"e": 1828,
"s": 1757,
"text": "y_range_name : name of an extra range to use for mapping y-coordinates"
},
{
"code": null,
"e": 1884,
"s": 1828,
"text": "level : specifies the render level order for this glyph"
},
{
"code": null,
"e": 1927,
"s": 1884,
"text": "Returns : an object of class GlyphRenderer"
},
{
"code": null,
"e": 2014,
"s": 1927,
"text": "Example 1 :In this example we will be using the default values for plotting the graph."
},
{
"code": "# importing the modulesfrom bokeh.plotting import figure, output_file, show # file to save the modeloutput_file(\"gfg.html\") # instantiating the figure objectgraph = figure(title = \"Bokeh Line Graph\") # the points to be plottedx = [1, 2, 3, 4, 5]y = [1, 6, 8, 2, 3] # plotting the line graphgraph.line(x, y) # displaying the modelshow(graph)",
"e": 2364,
"s": 2014,
"text": null
},
{
"code": null,
"e": 2479,
"s": 2364,
"text": "Output : Example 2 :In this example we will be plotting a line graph with dotted lines alongside other parameters."
},
{
"code": "# importing the modulesfrom bokeh.plotting import figure, output_file, show # file to save the modeloutput_file(\"gfg.html\") # instantiating the figure objectgraph = figure(title = \"Bokeh Line Graph\") # name of the x-axisgraph.xaxis.axis_label = \"x-axis\" # name of the y-axisgraph.yaxis.axis_label = \"y-axis\" # the points to be plottedx = [1, 2, 3, 4, 5]y = [5, 2, 1, 7, 1] # color of the lineline_color = \"red\" # type of lineline_dash = \"dotted\" # offset of line dashline_dash_offset = 1 # name of the legendlegend_label = \"Sample Line\" # plotting the line graph for AAPLgraph.line(x, y, line_color = line_color, line_dash = line_dash, line_dash_offset = line_dash_offset, legend_label = legend_label) # displaying the modelshow(graph)",
"e": 3269,
"s": 2479,
"text": null
},
{
"code": null,
"e": 3408,
"s": 3269,
"text": "Output : Example 3 :Now we will see how to plot multiple lines in the same graph. We will generate the points using the random() function."
},
{
"code": "# importing the modulesfrom bokeh.plotting import figure, output_file, showimport random # file to save the modeloutput_file(\"gfg.html\") # instantiating the figure objectgraph = figure(title = \"Bokeh Line Graph\") # name of the x-axisgraph.xaxis.axis_label = \"x-axis\" # name of the y-axisgraph.yaxis.axis_label = \"y-axis\" # plotting line 1# generating the points to be plottedx = []y = []for i in range(100): x.append(i)for i in range(100): y.append(1 + random.random()) # parameters of line 1line_color = \"red\"line_dash = \"solid\"legend_label = \"Line 1\" # plotting the linegraph.line(x, y, line_color = line_color, line_dash = line_dash, legend_label = legend_label) # plotting line 2# generating the points to be plottedx = []y = []for i in range(100): x.append(i)for i in range(100): y.append(random.random()) # parameters of line 2line_color = \"green\"line_dash = \"dotdash\"line_dash_offset = 1legend_label = \"Line 2\" # plotting the linegraph.line(x, y, line_color = line_color, line_dash = line_dash, line_dash_offset = line_dash_offset, legend_label = legend_label) # displaying the modelshow(graph)",
"e": 4605,
"s": 3408,
"text": null
},
{
"code": null,
"e": 4614,
"s": 4605,
"text": "Output :"
},
{
"code": null,
"e": 4633,
"s": 4614,
"text": "Data Visualization"
},
{
"code": null,
"e": 4646,
"s": 4633,
"text": "Python-Bokeh"
},
{
"code": null,
"e": 4653,
"s": 4646,
"text": "Python"
},
{
"code": null,
"e": 4751,
"s": 4653,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4779,
"s": 4751,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 4829,
"s": 4779,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 4851,
"s": 4829,
"text": "Python map() function"
},
{
"code": null,
"e": 4895,
"s": 4851,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 4913,
"s": 4895,
"text": "Python Dictionary"
},
{
"code": null,
"e": 4955,
"s": 4913,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 4978,
"s": 4955,
"text": "Taking input in Python"
},
{
"code": null,
"e": 5000,
"s": 4978,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 5035,
"s": 5000,
"text": "Read a file line by line in Python"
}
] |
Static and Dynamic data structures in Java with Examples
|
31 May, 2022
Data structure is a way of storing and organising data efficiently such that the required operations on them can be performed efficiently with respect to time as well as memory. Simply, Data Structure is used to reduce complexity (mostly the time complexity) of the code.
Data structures can be two types:
In the Static data structure, the size of the structure is fixed. The content of the data structure can be modified but without changing the memory space allocated to it.
Examples of Static Data Structures:
ArrayAn array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. An array is a group of like-typed variables that are referred to by a common name. Arrays in Java work differently than they do in C/C++.Syntax:// Declaration
type var-name[];
OR
type[] var-name;
// Initialization
var-name = new type [size];
Implementation:// Java program to illustrate creating an array// of integers, puts some values in the array,// and prints each value to standard output. class GFG { public static void main(String[] args) { // declares an Array of integers. int[] arr; // allocating memory for 5 integers. arr = new int[5]; // initialize the first // element of the array arr[0] = 10; // initialize the second // element of the array arr[1] = 20; // so on... arr[2] = 30; arr[3] = 40; arr[4] = 50; // accessing the elements // of the specified array for (int i = 0; i < arr.length; i++) System.out.println( "Element at index " + i + " : " + arr[i]); }}Output:Element at index 0 : 10
Element at index 1 : 20
Element at index 2 : 30
Element at index 3 : 40
Element at index 4 : 50
Problem with above Array implementation:Once we create the Array we cannot alter the size of the array. So the size of the array is unalterable.
ArrayAn array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. An array is a group of like-typed variables that are referred to by a common name. Arrays in Java work differently than they do in C/C++.Syntax:// Declaration
type var-name[];
OR
type[] var-name;
// Initialization
var-name = new type [size];
Implementation:// Java program to illustrate creating an array// of integers, puts some values in the array,// and prints each value to standard output. class GFG { public static void main(String[] args) { // declares an Array of integers. int[] arr; // allocating memory for 5 integers. arr = new int[5]; // initialize the first // element of the array arr[0] = 10; // initialize the second // element of the array arr[1] = 20; // so on... arr[2] = 30; arr[3] = 40; arr[4] = 50; // accessing the elements // of the specified array for (int i = 0; i < arr.length; i++) System.out.println( "Element at index " + i + " : " + arr[i]); }}Output:Element at index 0 : 10
Element at index 1 : 20
Element at index 2 : 30
Element at index 3 : 40
Element at index 4 : 50
Problem with above Array implementation:Once we create the Array we cannot alter the size of the array. So the size of the array is unalterable.
An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. An array is a group of like-typed variables that are referred to by a common name. Arrays in Java work differently than they do in C/C++.
Syntax:
// Declaration
type var-name[];
OR
type[] var-name;
// Initialization
var-name = new type [size];
Implementation:
// Java program to illustrate creating an array// of integers, puts some values in the array,// and prints each value to standard output. class GFG { public static void main(String[] args) { // declares an Array of integers. int[] arr; // allocating memory for 5 integers. arr = new int[5]; // initialize the first // element of the array arr[0] = 10; // initialize the second // element of the array arr[1] = 20; // so on... arr[2] = 30; arr[3] = 40; arr[4] = 50; // accessing the elements // of the specified array for (int i = 0; i < arr.length; i++) System.out.println( "Element at index " + i + " : " + arr[i]); }}
Element at index 0 : 10
Element at index 1 : 20
Element at index 2 : 30
Element at index 3 : 40
Element at index 4 : 50
Problem with above Array implementation:Once we create the Array we cannot alter the size of the array. So the size of the array is unalterable.
In Dynamic data structure, the size of the structure is not fixed and can be modified during the operations performed on it. Dynamic data structures are designed to facilitate change of data structures in the run time.
Examples of Dynamic Data Structures:
Singly Linked ListLinked List are linear data structures where the elements are not stored in contiguous locations and every element is a separate object with a data part and address part. The elements are linked using pointers and addresses. Each element is known as a node. Due to the dynamicity and ease of insertions and deletions, they are preferred over the arrays.// Java code for Linked List implementation import java.util.*; public class Test { public static void main(String args[]) { // Creating object of class linked list LinkedList<String> object = new LinkedList<String>(); // Adding elements to the linked list object.add("A"); object.add("B"); object.addLast("C"); object.addFirst("D"); object.add(2, "E"); object.add("F"); object.add("G"); System.out.println("Linked list : " + object); // Removing elements from the linked list object.remove("B"); object.remove(3); object.removeFirst(); object.removeLast(); System.out.println( "Linked list after deletion: " + object); // Finding elements in the linked list boolean status = object.contains("E"); if (status) System.out.println( "List contains the element 'E' "); else System.out.println( "List doesn't contain the element 'E'"); // Number of elements in the linked list int size = object.size(); System.out.println( "Size of linked list = " + size); // Get and set elements from linked list Object element = object.get(2); System.out.println( "Element returned by get() : " + element); object.set(2, "Y"); System.out.println( "Linked list after change : " + object); }}Output:Linked list : [D, A, E, B, C, F, G]
Linked list after deletion: [A, E, F]
List contains the element 'E'
Size of linked list = 3
Element returned by get() : F
Linked list after change : [A, E, Y]
Doubly Linked ListA Doubly Linked List (DLL) contains an extra pointer, typically called the previous pointer, together with next pointer and data which are there in a singly linked list.// Java program to demonstrate DLL // Class for Doubly Linked Listpublic class DLL { Node head; // head of list /* Doubly Linked list Node*/ class Node { int data; Node prev; Node next; // Constructor to create a new node // next and prev is by default // initialized as null Node(int d) { data = d; } } // Adding a node at the front of the list public void push(int new_data) { /* 1. allocate node * 2. put in the data */ Node new_Node = new Node(new_data); /* 3. Make next of new node as head and previous as NULL */ new_Node.next = head; new_Node.prev = null; /* 4. change prev of head node to new node */ if (head != null) head.prev = new_Node; /* 5. move the head to point to the new node */ head = new_Node; } /* Given a node as prev_node, insert a new node after the given node */ public void InsertAfter( Node prev_Node, int new_data) { /*1. check if the given prev_node is NULL */ if (prev_Node == null) { System.out.println( "The given previous node" + " cannot be NULL "); return; } /* 2. allocate node * 3. put in the data */ Node new_node = new Node(new_data); /* 4. Make next of new node as next of prev_node */ new_node.next = prev_Node.next; /* 5. Make the next of prev_node as new_node */ prev_Node.next = new_node; /* 6. Make prev_node as previous of new_node */ new_node.prev = prev_Node; /* 7. Change previous of new_node's next node */ if (new_node.next != null) new_node.next.prev = new_node; } // Add a node at the end of the list void append(int new_data) { /* 1. allocate node * 2. put in the data */ Node new_node = new Node(new_data); Node last = head; /* used in step 5*/ /* 3. This new node is going to be the last node, so * make next of it as NULL*/ new_node.next = null; /* 4. If the Linked List is empty, * then make the new * node as head */ if (head == null) { new_node.prev = null; head = new_node; return; } /* 5. Else traverse till the last node */ while (last.next != null) last = last.next; /* 6. Change the next of last node */ last.next = new_node; /* 7. Make last node as previous of new node */ new_node.prev = last; } // This function prints contents // of linked list starting // from the given node public void printlist(Node node) { Node last = null; System.out.println( "Traversal in forward Direction"); while (node != null) { System.out.print(node.data + " "); last = node; node = node.next; } System.out.println(); System.out.println( "Traversal in reverse direction"); while (last != null) { System.out.print(last.data + " "); last = last.prev; } } /* Driver program to test above functions*/ public static void main(String[] args) { /* Start with the empty list */ DLL dll = new DLL(); // Insert 6. So linked list becomes 6->NULL dll.append(6); // Insert 7 at the beginning. // So linked list becomes 7->6->NULL dll.push(7); // Insert 1 at the beginning. // So linked list becomes 1->7->6->NULL dll.push(1); // Insert 4 at the end. // So linked list becomes // 1->7->6->4->NULL dll.append(4); // Insert 8, after 7. // So linked list becomes // 1->7->8->6->4->NULL dll.InsertAfter(dll.head.next, 8); System.out.println("Created DLL is: "); dll.printlist(dll.head); }}Output:Created DLL is:
Traversal in forward Direction
1 7 8 6 4
Traversal in reverse direction
4 6 8 7 1
VectorThe Vector class implements a growable array of objects. Vectors basically fall in legacy classes but now it is fully compatible with collections. Vector implements a dynamic array that means it can grow or shrink as required. Like an array, it contains components that can be accessed using an integer index.// Java code illustrating Vector data structure import java.util.*; class Vector_demo { public static void main(String[] arg) { // Create default vector Vector v = new Vector(); v.add(1); v.add(2); v.add("geeks"); v.add("forGeeks"); v.add(3); System.out.println("Vector is " + v); }}Output:Vector is [1, 2, geeks, forGeeks, 3]
StackJava Collection framework provides a Stack class which models and implements a Stack data structure. The class is based on the basic principle of last-in-first-out. In addition to the basic push and pop operations, the class provides three more functions of empty, search and peek. The class can also be said to extend Vector and treats the class as a stack with the five mentioned functions. The class can also be referred to as the subclass of Vector.// Java code for stack implementation import java.io.*;import java.util.*; public class stack_implementation { public static void main(String a[]) { Stack<Integer> stack = new Stack<>(); stack.push(1); stack.push(2); stack.push(3); stack.push(4); int n = stack.size(); for (int i = 0; i < n; i++) { System.out.println(stack.pop()); } }}Output:4
3
2
1
Related articles:Stack implementation using ArrayStack implementation using Singly Linked ListStack implementation using QueueQueueThe Queue interface is available in java.util package and extends the Collection interface. The queue collection is used to hold the elements about to be processed and provides various operations like the insertion, removal etc. It is an ordered list of objects with its use limited to insert elements at the end of the list and deleting elements from the start of list i.e. it follows the FIFO or the First-In-First-Out principle.// Java program to demonstrate working// of Queue interface in Java import java.util.LinkedList;import java.util.Queue; public class QueueExample { public static void main(String[] args) { Queue<Integer> q = new LinkedList<>(); // Adds elements {0, 1, 2, 3, 4} to queue for (int i = 0; i < 5; i++) q.add(i); // Display contents of the queue. System.out.println("Elements of queue-" + q); // To remove the head of queue. int removedele = q.remove(); System.out.println("removed element-" + removedele); System.out.println(q); // To view the head of queue int head = q.peek(); System.out.println("head of queue-" + head); // Rest all methods of collection interface, // Like size and contains can be // used with this implementation. int size = q.size(); System.out.println("Size of queue-" + size); }}Output:Elements of queue-[0, 1, 2, 3, 4]
removed element-0
[1, 2, 3, 4]
head of queue-1
Size of queue-4
Related articles:Queue implementation using ArrayQueue implementation using Singly Linked ListQueue implementation using StackTreeA Tree is a data structure that stores values inside entities called Nodes. Nodes are connected through lines referred to as edges. Each node stores a value inside it.Terminology:Root is the topmost node of the tree.Parent is a node that has one or more Nodes attached to it.Edge is the link joining the two nodes.Child is a node that has a parent nodeLeaf is a node that doesn’t have any child node attached to it, it is the bottommost node of a tree.// Java program for different tree traversals /* Class containing left and right child of current node and key value*/class Node { int key; Node left, right; public Node(int item) { key = item; left = right = null; }} class BinaryTree { // Root of Binary Tree Node root; BinaryTree() { root = null; } /* Given a binary tree, print its nodes according to the "bottom-up" postorder traversal. */ void printPostorder(Node node) { if (node == null) return; // first recur on left subtree printPostorder(node.left); // then recur on right subtree printPostorder(node.right); // now deal with the node System.out.print(node.key + " "); } /* Given a binary tree, print its nodes in inorder*/ void printInorder(Node node) { if (node == null) return; /* first recur on left child */ printInorder(node.left); /* then print the data of node */ System.out.print(node.key + " "); /* now recur on right child */ printInorder(node.right); } /* Given a binary tree, print its nodes in preorder*/ void printPreorder(Node node) { if (node == null) return; /* first print data of node */ System.out.print(node.key + " "); /* then recur on left sutree */ printPreorder(node.left); /* now recur on right subtree */ printPreorder(node.right); } // Wrappers over above recursive functions void printPostorder() { printPostorder(root); } void printInorder() { printInorder(root); } void printPreorder() { printPreorder(root); } // Driver method public static void main(String[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); System.out.println( "Preorder traversal of binary tree is "); tree.printPreorder(); System.out.println( "\nInorder traversal of binary tree is "); tree.printInorder(); System.out.println( "\nPostorder traversal of binary tree is "); tree.printPostorder(); }}Output:Preorder traversal of binary tree is
1 2 4 5 3
Inorder traversal of binary tree is
4 2 5 1 3
Postorder traversal of binary tree is
4 5 2 3 1
Singly Linked ListLinked List are linear data structures where the elements are not stored in contiguous locations and every element is a separate object with a data part and address part. The elements are linked using pointers and addresses. Each element is known as a node. Due to the dynamicity and ease of insertions and deletions, they are preferred over the arrays.// Java code for Linked List implementation import java.util.*; public class Test { public static void main(String args[]) { // Creating object of class linked list LinkedList<String> object = new LinkedList<String>(); // Adding elements to the linked list object.add("A"); object.add("B"); object.addLast("C"); object.addFirst("D"); object.add(2, "E"); object.add("F"); object.add("G"); System.out.println("Linked list : " + object); // Removing elements from the linked list object.remove("B"); object.remove(3); object.removeFirst(); object.removeLast(); System.out.println( "Linked list after deletion: " + object); // Finding elements in the linked list boolean status = object.contains("E"); if (status) System.out.println( "List contains the element 'E' "); else System.out.println( "List doesn't contain the element 'E'"); // Number of elements in the linked list int size = object.size(); System.out.println( "Size of linked list = " + size); // Get and set elements from linked list Object element = object.get(2); System.out.println( "Element returned by get() : " + element); object.set(2, "Y"); System.out.println( "Linked list after change : " + object); }}Output:Linked list : [D, A, E, B, C, F, G]
Linked list after deletion: [A, E, F]
List contains the element 'E'
Size of linked list = 3
Element returned by get() : F
Linked list after change : [A, E, Y]
Linked List are linear data structures where the elements are not stored in contiguous locations and every element is a separate object with a data part and address part. The elements are linked using pointers and addresses. Each element is known as a node. Due to the dynamicity and ease of insertions and deletions, they are preferred over the arrays.
// Java code for Linked List implementation import java.util.*; public class Test { public static void main(String args[]) { // Creating object of class linked list LinkedList<String> object = new LinkedList<String>(); // Adding elements to the linked list object.add("A"); object.add("B"); object.addLast("C"); object.addFirst("D"); object.add(2, "E"); object.add("F"); object.add("G"); System.out.println("Linked list : " + object); // Removing elements from the linked list object.remove("B"); object.remove(3); object.removeFirst(); object.removeLast(); System.out.println( "Linked list after deletion: " + object); // Finding elements in the linked list boolean status = object.contains("E"); if (status) System.out.println( "List contains the element 'E' "); else System.out.println( "List doesn't contain the element 'E'"); // Number of elements in the linked list int size = object.size(); System.out.println( "Size of linked list = " + size); // Get and set elements from linked list Object element = object.get(2); System.out.println( "Element returned by get() : " + element); object.set(2, "Y"); System.out.println( "Linked list after change : " + object); }}
Linked list : [D, A, E, B, C, F, G]
Linked list after deletion: [A, E, F]
List contains the element 'E'
Size of linked list = 3
Element returned by get() : F
Linked list after change : [A, E, Y]
Doubly Linked ListA Doubly Linked List (DLL) contains an extra pointer, typically called the previous pointer, together with next pointer and data which are there in a singly linked list.// Java program to demonstrate DLL // Class for Doubly Linked Listpublic class DLL { Node head; // head of list /* Doubly Linked list Node*/ class Node { int data; Node prev; Node next; // Constructor to create a new node // next and prev is by default // initialized as null Node(int d) { data = d; } } // Adding a node at the front of the list public void push(int new_data) { /* 1. allocate node * 2. put in the data */ Node new_Node = new Node(new_data); /* 3. Make next of new node as head and previous as NULL */ new_Node.next = head; new_Node.prev = null; /* 4. change prev of head node to new node */ if (head != null) head.prev = new_Node; /* 5. move the head to point to the new node */ head = new_Node; } /* Given a node as prev_node, insert a new node after the given node */ public void InsertAfter( Node prev_Node, int new_data) { /*1. check if the given prev_node is NULL */ if (prev_Node == null) { System.out.println( "The given previous node" + " cannot be NULL "); return; } /* 2. allocate node * 3. put in the data */ Node new_node = new Node(new_data); /* 4. Make next of new node as next of prev_node */ new_node.next = prev_Node.next; /* 5. Make the next of prev_node as new_node */ prev_Node.next = new_node; /* 6. Make prev_node as previous of new_node */ new_node.prev = prev_Node; /* 7. Change previous of new_node's next node */ if (new_node.next != null) new_node.next.prev = new_node; } // Add a node at the end of the list void append(int new_data) { /* 1. allocate node * 2. put in the data */ Node new_node = new Node(new_data); Node last = head; /* used in step 5*/ /* 3. This new node is going to be the last node, so * make next of it as NULL*/ new_node.next = null; /* 4. If the Linked List is empty, * then make the new * node as head */ if (head == null) { new_node.prev = null; head = new_node; return; } /* 5. Else traverse till the last node */ while (last.next != null) last = last.next; /* 6. Change the next of last node */ last.next = new_node; /* 7. Make last node as previous of new node */ new_node.prev = last; } // This function prints contents // of linked list starting // from the given node public void printlist(Node node) { Node last = null; System.out.println( "Traversal in forward Direction"); while (node != null) { System.out.print(node.data + " "); last = node; node = node.next; } System.out.println(); System.out.println( "Traversal in reverse direction"); while (last != null) { System.out.print(last.data + " "); last = last.prev; } } /* Driver program to test above functions*/ public static void main(String[] args) { /* Start with the empty list */ DLL dll = new DLL(); // Insert 6. So linked list becomes 6->NULL dll.append(6); // Insert 7 at the beginning. // So linked list becomes 7->6->NULL dll.push(7); // Insert 1 at the beginning. // So linked list becomes 1->7->6->NULL dll.push(1); // Insert 4 at the end. // So linked list becomes // 1->7->6->4->NULL dll.append(4); // Insert 8, after 7. // So linked list becomes // 1->7->8->6->4->NULL dll.InsertAfter(dll.head.next, 8); System.out.println("Created DLL is: "); dll.printlist(dll.head); }}Output:Created DLL is:
Traversal in forward Direction
1 7 8 6 4
Traversal in reverse direction
4 6 8 7 1
A Doubly Linked List (DLL) contains an extra pointer, typically called the previous pointer, together with next pointer and data which are there in a singly linked list.
// Java program to demonstrate DLL // Class for Doubly Linked Listpublic class DLL { Node head; // head of list /* Doubly Linked list Node*/ class Node { int data; Node prev; Node next; // Constructor to create a new node // next and prev is by default // initialized as null Node(int d) { data = d; } } // Adding a node at the front of the list public void push(int new_data) { /* 1. allocate node * 2. put in the data */ Node new_Node = new Node(new_data); /* 3. Make next of new node as head and previous as NULL */ new_Node.next = head; new_Node.prev = null; /* 4. change prev of head node to new node */ if (head != null) head.prev = new_Node; /* 5. move the head to point to the new node */ head = new_Node; } /* Given a node as prev_node, insert a new node after the given node */ public void InsertAfter( Node prev_Node, int new_data) { /*1. check if the given prev_node is NULL */ if (prev_Node == null) { System.out.println( "The given previous node" + " cannot be NULL "); return; } /* 2. allocate node * 3. put in the data */ Node new_node = new Node(new_data); /* 4. Make next of new node as next of prev_node */ new_node.next = prev_Node.next; /* 5. Make the next of prev_node as new_node */ prev_Node.next = new_node; /* 6. Make prev_node as previous of new_node */ new_node.prev = prev_Node; /* 7. Change previous of new_node's next node */ if (new_node.next != null) new_node.next.prev = new_node; } // Add a node at the end of the list void append(int new_data) { /* 1. allocate node * 2. put in the data */ Node new_node = new Node(new_data); Node last = head; /* used in step 5*/ /* 3. This new node is going to be the last node, so * make next of it as NULL*/ new_node.next = null; /* 4. If the Linked List is empty, * then make the new * node as head */ if (head == null) { new_node.prev = null; head = new_node; return; } /* 5. Else traverse till the last node */ while (last.next != null) last = last.next; /* 6. Change the next of last node */ last.next = new_node; /* 7. Make last node as previous of new node */ new_node.prev = last; } // This function prints contents // of linked list starting // from the given node public void printlist(Node node) { Node last = null; System.out.println( "Traversal in forward Direction"); while (node != null) { System.out.print(node.data + " "); last = node; node = node.next; } System.out.println(); System.out.println( "Traversal in reverse direction"); while (last != null) { System.out.print(last.data + " "); last = last.prev; } } /* Driver program to test above functions*/ public static void main(String[] args) { /* Start with the empty list */ DLL dll = new DLL(); // Insert 6. So linked list becomes 6->NULL dll.append(6); // Insert 7 at the beginning. // So linked list becomes 7->6->NULL dll.push(7); // Insert 1 at the beginning. // So linked list becomes 1->7->6->NULL dll.push(1); // Insert 4 at the end. // So linked list becomes // 1->7->6->4->NULL dll.append(4); // Insert 8, after 7. // So linked list becomes // 1->7->8->6->4->NULL dll.InsertAfter(dll.head.next, 8); System.out.println("Created DLL is: "); dll.printlist(dll.head); }}
Created DLL is:
Traversal in forward Direction
1 7 8 6 4
Traversal in reverse direction
4 6 8 7 1
VectorThe Vector class implements a growable array of objects. Vectors basically fall in legacy classes but now it is fully compatible with collections. Vector implements a dynamic array that means it can grow or shrink as required. Like an array, it contains components that can be accessed using an integer index.// Java code illustrating Vector data structure import java.util.*; class Vector_demo { public static void main(String[] arg) { // Create default vector Vector v = new Vector(); v.add(1); v.add(2); v.add("geeks"); v.add("forGeeks"); v.add(3); System.out.println("Vector is " + v); }}Output:Vector is [1, 2, geeks, forGeeks, 3]
The Vector class implements a growable array of objects. Vectors basically fall in legacy classes but now it is fully compatible with collections. Vector implements a dynamic array that means it can grow or shrink as required. Like an array, it contains components that can be accessed using an integer index.
// Java code illustrating Vector data structure import java.util.*; class Vector_demo { public static void main(String[] arg) { // Create default vector Vector v = new Vector(); v.add(1); v.add(2); v.add("geeks"); v.add("forGeeks"); v.add(3); System.out.println("Vector is " + v); }}
Output:
Vector is [1, 2, geeks, forGeeks, 3]
StackJava Collection framework provides a Stack class which models and implements a Stack data structure. The class is based on the basic principle of last-in-first-out. In addition to the basic push and pop operations, the class provides three more functions of empty, search and peek. The class can also be said to extend Vector and treats the class as a stack with the five mentioned functions. The class can also be referred to as the subclass of Vector.// Java code for stack implementation import java.io.*;import java.util.*; public class stack_implementation { public static void main(String a[]) { Stack<Integer> stack = new Stack<>(); stack.push(1); stack.push(2); stack.push(3); stack.push(4); int n = stack.size(); for (int i = 0; i < n; i++) { System.out.println(stack.pop()); } }}Output:4
3
2
1
Related articles:Stack implementation using ArrayStack implementation using Singly Linked ListStack implementation using Queue
Java Collection framework provides a Stack class which models and implements a Stack data structure. The class is based on the basic principle of last-in-first-out. In addition to the basic push and pop operations, the class provides three more functions of empty, search and peek. The class can also be said to extend Vector and treats the class as a stack with the five mentioned functions. The class can also be referred to as the subclass of Vector.
// Java code for stack implementation import java.io.*;import java.util.*; public class stack_implementation { public static void main(String a[]) { Stack<Integer> stack = new Stack<>(); stack.push(1); stack.push(2); stack.push(3); stack.push(4); int n = stack.size(); for (int i = 0; i < n; i++) { System.out.println(stack.pop()); } }}
4
3
2
1
Related articles:
Stack implementation using Array
Stack implementation using Singly Linked List
Stack implementation using Queue
QueueThe Queue interface is available in java.util package and extends the Collection interface. The queue collection is used to hold the elements about to be processed and provides various operations like the insertion, removal etc. It is an ordered list of objects with its use limited to insert elements at the end of the list and deleting elements from the start of list i.e. it follows the FIFO or the First-In-First-Out principle.// Java program to demonstrate working// of Queue interface in Java import java.util.LinkedList;import java.util.Queue; public class QueueExample { public static void main(String[] args) { Queue<Integer> q = new LinkedList<>(); // Adds elements {0, 1, 2, 3, 4} to queue for (int i = 0; i < 5; i++) q.add(i); // Display contents of the queue. System.out.println("Elements of queue-" + q); // To remove the head of queue. int removedele = q.remove(); System.out.println("removed element-" + removedele); System.out.println(q); // To view the head of queue int head = q.peek(); System.out.println("head of queue-" + head); // Rest all methods of collection interface, // Like size and contains can be // used with this implementation. int size = q.size(); System.out.println("Size of queue-" + size); }}Output:Elements of queue-[0, 1, 2, 3, 4]
removed element-0
[1, 2, 3, 4]
head of queue-1
Size of queue-4
Related articles:Queue implementation using ArrayQueue implementation using Singly Linked ListQueue implementation using Stack
The Queue interface is available in java.util package and extends the Collection interface. The queue collection is used to hold the elements about to be processed and provides various operations like the insertion, removal etc. It is an ordered list of objects with its use limited to insert elements at the end of the list and deleting elements from the start of list i.e. it follows the FIFO or the First-In-First-Out principle.
// Java program to demonstrate working// of Queue interface in Java import java.util.LinkedList;import java.util.Queue; public class QueueExample { public static void main(String[] args) { Queue<Integer> q = new LinkedList<>(); // Adds elements {0, 1, 2, 3, 4} to queue for (int i = 0; i < 5; i++) q.add(i); // Display contents of the queue. System.out.println("Elements of queue-" + q); // To remove the head of queue. int removedele = q.remove(); System.out.println("removed element-" + removedele); System.out.println(q); // To view the head of queue int head = q.peek(); System.out.println("head of queue-" + head); // Rest all methods of collection interface, // Like size and contains can be // used with this implementation. int size = q.size(); System.out.println("Size of queue-" + size); }}
Elements of queue-[0, 1, 2, 3, 4]
removed element-0
[1, 2, 3, 4]
head of queue-1
Size of queue-4
Related articles:
Queue implementation using Array
Queue implementation using Singly Linked List
Queue implementation using Stack
TreeA Tree is a data structure that stores values inside entities called Nodes. Nodes are connected through lines referred to as edges. Each node stores a value inside it.Terminology:Root is the topmost node of the tree.Parent is a node that has one or more Nodes attached to it.Edge is the link joining the two nodes.Child is a node that has a parent nodeLeaf is a node that doesn’t have any child node attached to it, it is the bottommost node of a tree.// Java program for different tree traversals /* Class containing left and right child of current node and key value*/class Node { int key; Node left, right; public Node(int item) { key = item; left = right = null; }} class BinaryTree { // Root of Binary Tree Node root; BinaryTree() { root = null; } /* Given a binary tree, print its nodes according to the "bottom-up" postorder traversal. */ void printPostorder(Node node) { if (node == null) return; // first recur on left subtree printPostorder(node.left); // then recur on right subtree printPostorder(node.right); // now deal with the node System.out.print(node.key + " "); } /* Given a binary tree, print its nodes in inorder*/ void printInorder(Node node) { if (node == null) return; /* first recur on left child */ printInorder(node.left); /* then print the data of node */ System.out.print(node.key + " "); /* now recur on right child */ printInorder(node.right); } /* Given a binary tree, print its nodes in preorder*/ void printPreorder(Node node) { if (node == null) return; /* first print data of node */ System.out.print(node.key + " "); /* then recur on left sutree */ printPreorder(node.left); /* now recur on right subtree */ printPreorder(node.right); } // Wrappers over above recursive functions void printPostorder() { printPostorder(root); } void printInorder() { printInorder(root); } void printPreorder() { printPreorder(root); } // Driver method public static void main(String[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); System.out.println( "Preorder traversal of binary tree is "); tree.printPreorder(); System.out.println( "\nInorder traversal of binary tree is "); tree.printInorder(); System.out.println( "\nPostorder traversal of binary tree is "); tree.printPostorder(); }}Output:Preorder traversal of binary tree is
1 2 4 5 3
Inorder traversal of binary tree is
4 2 5 1 3
Postorder traversal of binary tree is
4 5 2 3 1
A Tree is a data structure that stores values inside entities called Nodes. Nodes are connected through lines referred to as edges. Each node stores a value inside it.Terminology:
Root is the topmost node of the tree.
Parent is a node that has one or more Nodes attached to it.
Edge is the link joining the two nodes.
Child is a node that has a parent node
Leaf is a node that doesn’t have any child node attached to it, it is the bottommost node of a tree.
// Java program for different tree traversals /* Class containing left and right child of current node and key value*/class Node { int key; Node left, right; public Node(int item) { key = item; left = right = null; }} class BinaryTree { // Root of Binary Tree Node root; BinaryTree() { root = null; } /* Given a binary tree, print its nodes according to the "bottom-up" postorder traversal. */ void printPostorder(Node node) { if (node == null) return; // first recur on left subtree printPostorder(node.left); // then recur on right subtree printPostorder(node.right); // now deal with the node System.out.print(node.key + " "); } /* Given a binary tree, print its nodes in inorder*/ void printInorder(Node node) { if (node == null) return; /* first recur on left child */ printInorder(node.left); /* then print the data of node */ System.out.print(node.key + " "); /* now recur on right child */ printInorder(node.right); } /* Given a binary tree, print its nodes in preorder*/ void printPreorder(Node node) { if (node == null) return; /* first print data of node */ System.out.print(node.key + " "); /* then recur on left sutree */ printPreorder(node.left); /* now recur on right subtree */ printPreorder(node.right); } // Wrappers over above recursive functions void printPostorder() { printPostorder(root); } void printInorder() { printInorder(root); } void printPreorder() { printPreorder(root); } // Driver method public static void main(String[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); System.out.println( "Preorder traversal of binary tree is "); tree.printPreorder(); System.out.println( "\nInorder traversal of binary tree is "); tree.printInorder(); System.out.println( "\nPostorder traversal of binary tree is "); tree.printPostorder(); }}
Preorder traversal of binary tree is
1 2 4 5 3
Inorder traversal of binary tree is
4 2 5 1 3
Postorder traversal of binary tree is
4 5 2 3 1
Akanksha_Rai
mihirmer2000
Java-Arrays
java-queue
Java-Stack
Java-Vector
Advanced Data Structure
Algorithms
Arrays
Data Structures
Java
Linked List
Queue
Stack
Tree
Data Structures
Linked List
Arrays
Stack
Java
Queue
Tree
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 May, 2022"
},
{
"code": null,
"e": 300,
"s": 28,
"text": "Data structure is a way of storing and organising data efficiently such that the required operations on them can be performed efficiently with respect to time as well as memory. Simply, Data Structure is used to reduce complexity (mostly the time complexity) of the code."
},
{
"code": null,
"e": 334,
"s": 300,
"text": "Data structures can be two types:"
},
{
"code": null,
"e": 505,
"s": 334,
"text": "In the Static data structure, the size of the structure is fixed. The content of the data structure can be modified but without changing the memory space allocated to it."
},
{
"code": null,
"e": 541,
"s": 505,
"text": "Examples of Static Data Structures:"
},
{
"code": null,
"e": 2025,
"s": 541,
"text": "ArrayAn array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. An array is a group of like-typed variables that are referred to by a common name. Arrays in Java work differently than they do in C/C++.Syntax:// Declaration\ntype var-name[];\nOR\ntype[] var-name;\n\n// Initialization\nvar-name = new type [size];\nImplementation:// Java program to illustrate creating an array// of integers, puts some values in the array,// and prints each value to standard output. class GFG { public static void main(String[] args) { // declares an Array of integers. int[] arr; // allocating memory for 5 integers. arr = new int[5]; // initialize the first // element of the array arr[0] = 10; // initialize the second // element of the array arr[1] = 20; // so on... arr[2] = 30; arr[3] = 40; arr[4] = 50; // accessing the elements // of the specified array for (int i = 0; i < arr.length; i++) System.out.println( \"Element at index \" + i + \" : \" + arr[i]); }}Output:Element at index 0 : 10\nElement at index 1 : 20\nElement at index 2 : 30\nElement at index 3 : 40\nElement at index 4 : 50\nProblem with above Array implementation:Once we create the Array we cannot alter the size of the array. So the size of the array is unalterable."
},
{
"code": null,
"e": 3509,
"s": 2025,
"text": "ArrayAn array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. An array is a group of like-typed variables that are referred to by a common name. Arrays in Java work differently than they do in C/C++.Syntax:// Declaration\ntype var-name[];\nOR\ntype[] var-name;\n\n// Initialization\nvar-name = new type [size];\nImplementation:// Java program to illustrate creating an array// of integers, puts some values in the array,// and prints each value to standard output. class GFG { public static void main(String[] args) { // declares an Array of integers. int[] arr; // allocating memory for 5 integers. arr = new int[5]; // initialize the first // element of the array arr[0] = 10; // initialize the second // element of the array arr[1] = 20; // so on... arr[2] = 30; arr[3] = 40; arr[4] = 50; // accessing the elements // of the specified array for (int i = 0; i < arr.length; i++) System.out.println( \"Element at index \" + i + \" : \" + arr[i]); }}Output:Element at index 0 : 10\nElement at index 1 : 20\nElement at index 2 : 30\nElement at index 3 : 40\nElement at index 4 : 50\nProblem with above Array implementation:Once we create the Array we cannot alter the size of the array. So the size of the array is unalterable."
},
{
"code": null,
"e": 3797,
"s": 3509,
"text": "An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. An array is a group of like-typed variables that are referred to by a common name. Arrays in Java work differently than they do in C/C++."
},
{
"code": null,
"e": 3805,
"s": 3797,
"text": "Syntax:"
},
{
"code": null,
"e": 3905,
"s": 3805,
"text": "// Declaration\ntype var-name[];\nOR\ntype[] var-name;\n\n// Initialization\nvar-name = new type [size];\n"
},
{
"code": null,
"e": 3921,
"s": 3905,
"text": "Implementation:"
},
{
"code": "// Java program to illustrate creating an array// of integers, puts some values in the array,// and prints each value to standard output. class GFG { public static void main(String[] args) { // declares an Array of integers. int[] arr; // allocating memory for 5 integers. arr = new int[5]; // initialize the first // element of the array arr[0] = 10; // initialize the second // element of the array arr[1] = 20; // so on... arr[2] = 30; arr[3] = 40; arr[4] = 50; // accessing the elements // of the specified array for (int i = 0; i < arr.length; i++) System.out.println( \"Element at index \" + i + \" : \" + arr[i]); }}",
"e": 4721,
"s": 3921,
"text": null
},
{
"code": null,
"e": 4842,
"s": 4721,
"text": "Element at index 0 : 10\nElement at index 1 : 20\nElement at index 2 : 30\nElement at index 3 : 40\nElement at index 4 : 50\n"
},
{
"code": null,
"e": 4987,
"s": 4842,
"text": "Problem with above Array implementation:Once we create the Array we cannot alter the size of the array. So the size of the array is unalterable."
},
{
"code": null,
"e": 5206,
"s": 4987,
"text": "In Dynamic data structure, the size of the structure is not fixed and can be modified during the operations performed on it. Dynamic data structures are designed to facilitate change of data structures in the run time."
},
{
"code": null,
"e": 5243,
"s": 5206,
"text": "Examples of Dynamic Data Structures:"
},
{
"code": null,
"e": 18155,
"s": 5243,
"text": "Singly Linked ListLinked List are linear data structures where the elements are not stored in contiguous locations and every element is a separate object with a data part and address part. The elements are linked using pointers and addresses. Each element is known as a node. Due to the dynamicity and ease of insertions and deletions, they are preferred over the arrays.// Java code for Linked List implementation import java.util.*; public class Test { public static void main(String args[]) { // Creating object of class linked list LinkedList<String> object = new LinkedList<String>(); // Adding elements to the linked list object.add(\"A\"); object.add(\"B\"); object.addLast(\"C\"); object.addFirst(\"D\"); object.add(2, \"E\"); object.add(\"F\"); object.add(\"G\"); System.out.println(\"Linked list : \" + object); // Removing elements from the linked list object.remove(\"B\"); object.remove(3); object.removeFirst(); object.removeLast(); System.out.println( \"Linked list after deletion: \" + object); // Finding elements in the linked list boolean status = object.contains(\"E\"); if (status) System.out.println( \"List contains the element 'E' \"); else System.out.println( \"List doesn't contain the element 'E'\"); // Number of elements in the linked list int size = object.size(); System.out.println( \"Size of linked list = \" + size); // Get and set elements from linked list Object element = object.get(2); System.out.println( \"Element returned by get() : \" + element); object.set(2, \"Y\"); System.out.println( \"Linked list after change : \" + object); }}Output:Linked list : [D, A, E, B, C, F, G]\nLinked list after deletion: [A, E, F]\nList contains the element 'E' \nSize of linked list = 3\nElement returned by get() : F\nLinked list after change : [A, E, Y]\nDoubly Linked ListA Doubly Linked List (DLL) contains an extra pointer, typically called the previous pointer, together with next pointer and data which are there in a singly linked list.// Java program to demonstrate DLL // Class for Doubly Linked Listpublic class DLL { Node head; // head of list /* Doubly Linked list Node*/ class Node { int data; Node prev; Node next; // Constructor to create a new node // next and prev is by default // initialized as null Node(int d) { data = d; } } // Adding a node at the front of the list public void push(int new_data) { /* 1. allocate node * 2. put in the data */ Node new_Node = new Node(new_data); /* 3. Make next of new node as head and previous as NULL */ new_Node.next = head; new_Node.prev = null; /* 4. change prev of head node to new node */ if (head != null) head.prev = new_Node; /* 5. move the head to point to the new node */ head = new_Node; } /* Given a node as prev_node, insert a new node after the given node */ public void InsertAfter( Node prev_Node, int new_data) { /*1. check if the given prev_node is NULL */ if (prev_Node == null) { System.out.println( \"The given previous node\" + \" cannot be NULL \"); return; } /* 2. allocate node * 3. put in the data */ Node new_node = new Node(new_data); /* 4. Make next of new node as next of prev_node */ new_node.next = prev_Node.next; /* 5. Make the next of prev_node as new_node */ prev_Node.next = new_node; /* 6. Make prev_node as previous of new_node */ new_node.prev = prev_Node; /* 7. Change previous of new_node's next node */ if (new_node.next != null) new_node.next.prev = new_node; } // Add a node at the end of the list void append(int new_data) { /* 1. allocate node * 2. put in the data */ Node new_node = new Node(new_data); Node last = head; /* used in step 5*/ /* 3. This new node is going to be the last node, so * make next of it as NULL*/ new_node.next = null; /* 4. If the Linked List is empty, * then make the new * node as head */ if (head == null) { new_node.prev = null; head = new_node; return; } /* 5. Else traverse till the last node */ while (last.next != null) last = last.next; /* 6. Change the next of last node */ last.next = new_node; /* 7. Make last node as previous of new node */ new_node.prev = last; } // This function prints contents // of linked list starting // from the given node public void printlist(Node node) { Node last = null; System.out.println( \"Traversal in forward Direction\"); while (node != null) { System.out.print(node.data + \" \"); last = node; node = node.next; } System.out.println(); System.out.println( \"Traversal in reverse direction\"); while (last != null) { System.out.print(last.data + \" \"); last = last.prev; } } /* Driver program to test above functions*/ public static void main(String[] args) { /* Start with the empty list */ DLL dll = new DLL(); // Insert 6. So linked list becomes 6->NULL dll.append(6); // Insert 7 at the beginning. // So linked list becomes 7->6->NULL dll.push(7); // Insert 1 at the beginning. // So linked list becomes 1->7->6->NULL dll.push(1); // Insert 4 at the end. // So linked list becomes // 1->7->6->4->NULL dll.append(4); // Insert 8, after 7. // So linked list becomes // 1->7->8->6->4->NULL dll.InsertAfter(dll.head.next, 8); System.out.println(\"Created DLL is: \"); dll.printlist(dll.head); }}Output:Created DLL is: \nTraversal in forward Direction\n1 7 8 6 4 \nTraversal in reverse direction\n4 6 8 7 1\nVectorThe Vector class implements a growable array of objects. Vectors basically fall in legacy classes but now it is fully compatible with collections. Vector implements a dynamic array that means it can grow or shrink as required. Like an array, it contains components that can be accessed using an integer index.// Java code illustrating Vector data structure import java.util.*; class Vector_demo { public static void main(String[] arg) { // Create default vector Vector v = new Vector(); v.add(1); v.add(2); v.add(\"geeks\"); v.add(\"forGeeks\"); v.add(3); System.out.println(\"Vector is \" + v); }}Output:Vector is [1, 2, geeks, forGeeks, 3]\nStackJava Collection framework provides a Stack class which models and implements a Stack data structure. The class is based on the basic principle of last-in-first-out. In addition to the basic push and pop operations, the class provides three more functions of empty, search and peek. The class can also be said to extend Vector and treats the class as a stack with the five mentioned functions. The class can also be referred to as the subclass of Vector.// Java code for stack implementation import java.io.*;import java.util.*; public class stack_implementation { public static void main(String a[]) { Stack<Integer> stack = new Stack<>(); stack.push(1); stack.push(2); stack.push(3); stack.push(4); int n = stack.size(); for (int i = 0; i < n; i++) { System.out.println(stack.pop()); } }}Output:4\n3\n2\n1\nRelated articles:Stack implementation using ArrayStack implementation using Singly Linked ListStack implementation using QueueQueueThe Queue interface is available in java.util package and extends the Collection interface. The queue collection is used to hold the elements about to be processed and provides various operations like the insertion, removal etc. It is an ordered list of objects with its use limited to insert elements at the end of the list and deleting elements from the start of list i.e. it follows the FIFO or the First-In-First-Out principle.// Java program to demonstrate working// of Queue interface in Java import java.util.LinkedList;import java.util.Queue; public class QueueExample { public static void main(String[] args) { Queue<Integer> q = new LinkedList<>(); // Adds elements {0, 1, 2, 3, 4} to queue for (int i = 0; i < 5; i++) q.add(i); // Display contents of the queue. System.out.println(\"Elements of queue-\" + q); // To remove the head of queue. int removedele = q.remove(); System.out.println(\"removed element-\" + removedele); System.out.println(q); // To view the head of queue int head = q.peek(); System.out.println(\"head of queue-\" + head); // Rest all methods of collection interface, // Like size and contains can be // used with this implementation. int size = q.size(); System.out.println(\"Size of queue-\" + size); }}Output:Elements of queue-[0, 1, 2, 3, 4]\nremoved element-0\n[1, 2, 3, 4]\nhead of queue-1\nSize of queue-4\nRelated articles:Queue implementation using ArrayQueue implementation using Singly Linked ListQueue implementation using StackTreeA Tree is a data structure that stores values inside entities called Nodes. Nodes are connected through lines referred to as edges. Each node stores a value inside it.Terminology:Root is the topmost node of the tree.Parent is a node that has one or more Nodes attached to it.Edge is the link joining the two nodes.Child is a node that has a parent nodeLeaf is a node that doesn’t have any child node attached to it, it is the bottommost node of a tree.// Java program for different tree traversals /* Class containing left and right child of current node and key value*/class Node { int key; Node left, right; public Node(int item) { key = item; left = right = null; }} class BinaryTree { // Root of Binary Tree Node root; BinaryTree() { root = null; } /* Given a binary tree, print its nodes according to the \"bottom-up\" postorder traversal. */ void printPostorder(Node node) { if (node == null) return; // first recur on left subtree printPostorder(node.left); // then recur on right subtree printPostorder(node.right); // now deal with the node System.out.print(node.key + \" \"); } /* Given a binary tree, print its nodes in inorder*/ void printInorder(Node node) { if (node == null) return; /* first recur on left child */ printInorder(node.left); /* then print the data of node */ System.out.print(node.key + \" \"); /* now recur on right child */ printInorder(node.right); } /* Given a binary tree, print its nodes in preorder*/ void printPreorder(Node node) { if (node == null) return; /* first print data of node */ System.out.print(node.key + \" \"); /* then recur on left sutree */ printPreorder(node.left); /* now recur on right subtree */ printPreorder(node.right); } // Wrappers over above recursive functions void printPostorder() { printPostorder(root); } void printInorder() { printInorder(root); } void printPreorder() { printPreorder(root); } // Driver method public static void main(String[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); System.out.println( \"Preorder traversal of binary tree is \"); tree.printPreorder(); System.out.println( \"\\nInorder traversal of binary tree is \"); tree.printInorder(); System.out.println( \"\\nPostorder traversal of binary tree is \"); tree.printPostorder(); }}Output:Preorder traversal of binary tree is\n1 2 4 5 3 \nInorder traversal of binary tree is\n4 2 5 1 3 \nPostorder traversal of binary tree is\n4 5 2 3 1\n"
},
{
"code": null,
"e": 20293,
"s": 18155,
"text": "Singly Linked ListLinked List are linear data structures where the elements are not stored in contiguous locations and every element is a separate object with a data part and address part. The elements are linked using pointers and addresses. Each element is known as a node. Due to the dynamicity and ease of insertions and deletions, they are preferred over the arrays.// Java code for Linked List implementation import java.util.*; public class Test { public static void main(String args[]) { // Creating object of class linked list LinkedList<String> object = new LinkedList<String>(); // Adding elements to the linked list object.add(\"A\"); object.add(\"B\"); object.addLast(\"C\"); object.addFirst(\"D\"); object.add(2, \"E\"); object.add(\"F\"); object.add(\"G\"); System.out.println(\"Linked list : \" + object); // Removing elements from the linked list object.remove(\"B\"); object.remove(3); object.removeFirst(); object.removeLast(); System.out.println( \"Linked list after deletion: \" + object); // Finding elements in the linked list boolean status = object.contains(\"E\"); if (status) System.out.println( \"List contains the element 'E' \"); else System.out.println( \"List doesn't contain the element 'E'\"); // Number of elements in the linked list int size = object.size(); System.out.println( \"Size of linked list = \" + size); // Get and set elements from linked list Object element = object.get(2); System.out.println( \"Element returned by get() : \" + element); object.set(2, \"Y\"); System.out.println( \"Linked list after change : \" + object); }}Output:Linked list : [D, A, E, B, C, F, G]\nLinked list after deletion: [A, E, F]\nList contains the element 'E' \nSize of linked list = 3\nElement returned by get() : F\nLinked list after change : [A, E, Y]\n"
},
{
"code": null,
"e": 20647,
"s": 20293,
"text": "Linked List are linear data structures where the elements are not stored in contiguous locations and every element is a separate object with a data part and address part. The elements are linked using pointers and addresses. Each element is known as a node. Due to the dynamicity and ease of insertions and deletions, they are preferred over the arrays."
},
{
"code": "// Java code for Linked List implementation import java.util.*; public class Test { public static void main(String args[]) { // Creating object of class linked list LinkedList<String> object = new LinkedList<String>(); // Adding elements to the linked list object.add(\"A\"); object.add(\"B\"); object.addLast(\"C\"); object.addFirst(\"D\"); object.add(2, \"E\"); object.add(\"F\"); object.add(\"G\"); System.out.println(\"Linked list : \" + object); // Removing elements from the linked list object.remove(\"B\"); object.remove(3); object.removeFirst(); object.removeLast(); System.out.println( \"Linked list after deletion: \" + object); // Finding elements in the linked list boolean status = object.contains(\"E\"); if (status) System.out.println( \"List contains the element 'E' \"); else System.out.println( \"List doesn't contain the element 'E'\"); // Number of elements in the linked list int size = object.size(); System.out.println( \"Size of linked list = \" + size); // Get and set elements from linked list Object element = object.get(2); System.out.println( \"Element returned by get() : \" + element); object.set(2, \"Y\"); System.out.println( \"Linked list after change : \" + object); }}",
"e": 22211,
"s": 20647,
"text": null
},
{
"code": null,
"e": 22408,
"s": 22211,
"text": "Linked list : [D, A, E, B, C, F, G]\nLinked list after deletion: [A, E, F]\nList contains the element 'E' \nSize of linked list = 3\nElement returned by get() : F\nLinked list after change : [A, E, Y]\n"
},
{
"code": null,
"e": 26773,
"s": 22408,
"text": "Doubly Linked ListA Doubly Linked List (DLL) contains an extra pointer, typically called the previous pointer, together with next pointer and data which are there in a singly linked list.// Java program to demonstrate DLL // Class for Doubly Linked Listpublic class DLL { Node head; // head of list /* Doubly Linked list Node*/ class Node { int data; Node prev; Node next; // Constructor to create a new node // next and prev is by default // initialized as null Node(int d) { data = d; } } // Adding a node at the front of the list public void push(int new_data) { /* 1. allocate node * 2. put in the data */ Node new_Node = new Node(new_data); /* 3. Make next of new node as head and previous as NULL */ new_Node.next = head; new_Node.prev = null; /* 4. change prev of head node to new node */ if (head != null) head.prev = new_Node; /* 5. move the head to point to the new node */ head = new_Node; } /* Given a node as prev_node, insert a new node after the given node */ public void InsertAfter( Node prev_Node, int new_data) { /*1. check if the given prev_node is NULL */ if (prev_Node == null) { System.out.println( \"The given previous node\" + \" cannot be NULL \"); return; } /* 2. allocate node * 3. put in the data */ Node new_node = new Node(new_data); /* 4. Make next of new node as next of prev_node */ new_node.next = prev_Node.next; /* 5. Make the next of prev_node as new_node */ prev_Node.next = new_node; /* 6. Make prev_node as previous of new_node */ new_node.prev = prev_Node; /* 7. Change previous of new_node's next node */ if (new_node.next != null) new_node.next.prev = new_node; } // Add a node at the end of the list void append(int new_data) { /* 1. allocate node * 2. put in the data */ Node new_node = new Node(new_data); Node last = head; /* used in step 5*/ /* 3. This new node is going to be the last node, so * make next of it as NULL*/ new_node.next = null; /* 4. If the Linked List is empty, * then make the new * node as head */ if (head == null) { new_node.prev = null; head = new_node; return; } /* 5. Else traverse till the last node */ while (last.next != null) last = last.next; /* 6. Change the next of last node */ last.next = new_node; /* 7. Make last node as previous of new node */ new_node.prev = last; } // This function prints contents // of linked list starting // from the given node public void printlist(Node node) { Node last = null; System.out.println( \"Traversal in forward Direction\"); while (node != null) { System.out.print(node.data + \" \"); last = node; node = node.next; } System.out.println(); System.out.println( \"Traversal in reverse direction\"); while (last != null) { System.out.print(last.data + \" \"); last = last.prev; } } /* Driver program to test above functions*/ public static void main(String[] args) { /* Start with the empty list */ DLL dll = new DLL(); // Insert 6. So linked list becomes 6->NULL dll.append(6); // Insert 7 at the beginning. // So linked list becomes 7->6->NULL dll.push(7); // Insert 1 at the beginning. // So linked list becomes 1->7->6->NULL dll.push(1); // Insert 4 at the end. // So linked list becomes // 1->7->6->4->NULL dll.append(4); // Insert 8, after 7. // So linked list becomes // 1->7->8->6->4->NULL dll.InsertAfter(dll.head.next, 8); System.out.println(\"Created DLL is: \"); dll.printlist(dll.head); }}Output:Created DLL is: \nTraversal in forward Direction\n1 7 8 6 4 \nTraversal in reverse direction\n4 6 8 7 1\n"
},
{
"code": null,
"e": 26943,
"s": 26773,
"text": "A Doubly Linked List (DLL) contains an extra pointer, typically called the previous pointer, together with next pointer and data which are there in a singly linked list."
},
{
"code": "// Java program to demonstrate DLL // Class for Doubly Linked Listpublic class DLL { Node head; // head of list /* Doubly Linked list Node*/ class Node { int data; Node prev; Node next; // Constructor to create a new node // next and prev is by default // initialized as null Node(int d) { data = d; } } // Adding a node at the front of the list public void push(int new_data) { /* 1. allocate node * 2. put in the data */ Node new_Node = new Node(new_data); /* 3. Make next of new node as head and previous as NULL */ new_Node.next = head; new_Node.prev = null; /* 4. change prev of head node to new node */ if (head != null) head.prev = new_Node; /* 5. move the head to point to the new node */ head = new_Node; } /* Given a node as prev_node, insert a new node after the given node */ public void InsertAfter( Node prev_Node, int new_data) { /*1. check if the given prev_node is NULL */ if (prev_Node == null) { System.out.println( \"The given previous node\" + \" cannot be NULL \"); return; } /* 2. allocate node * 3. put in the data */ Node new_node = new Node(new_data); /* 4. Make next of new node as next of prev_node */ new_node.next = prev_Node.next; /* 5. Make the next of prev_node as new_node */ prev_Node.next = new_node; /* 6. Make prev_node as previous of new_node */ new_node.prev = prev_Node; /* 7. Change previous of new_node's next node */ if (new_node.next != null) new_node.next.prev = new_node; } // Add a node at the end of the list void append(int new_data) { /* 1. allocate node * 2. put in the data */ Node new_node = new Node(new_data); Node last = head; /* used in step 5*/ /* 3. This new node is going to be the last node, so * make next of it as NULL*/ new_node.next = null; /* 4. If the Linked List is empty, * then make the new * node as head */ if (head == null) { new_node.prev = null; head = new_node; return; } /* 5. Else traverse till the last node */ while (last.next != null) last = last.next; /* 6. Change the next of last node */ last.next = new_node; /* 7. Make last node as previous of new node */ new_node.prev = last; } // This function prints contents // of linked list starting // from the given node public void printlist(Node node) { Node last = null; System.out.println( \"Traversal in forward Direction\"); while (node != null) { System.out.print(node.data + \" \"); last = node; node = node.next; } System.out.println(); System.out.println( \"Traversal in reverse direction\"); while (last != null) { System.out.print(last.data + \" \"); last = last.prev; } } /* Driver program to test above functions*/ public static void main(String[] args) { /* Start with the empty list */ DLL dll = new DLL(); // Insert 6. So linked list becomes 6->NULL dll.append(6); // Insert 7 at the beginning. // So linked list becomes 7->6->NULL dll.push(7); // Insert 1 at the beginning. // So linked list becomes 1->7->6->NULL dll.push(1); // Insert 4 at the end. // So linked list becomes // 1->7->6->4->NULL dll.append(4); // Insert 8, after 7. // So linked list becomes // 1->7->8->6->4->NULL dll.InsertAfter(dll.head.next, 8); System.out.println(\"Created DLL is: \"); dll.printlist(dll.head); }}",
"e": 31014,
"s": 26943,
"text": null
},
{
"code": null,
"e": 31115,
"s": 31014,
"text": "Created DLL is: \nTraversal in forward Direction\n1 7 8 6 4 \nTraversal in reverse direction\n4 6 8 7 1\n"
},
{
"code": null,
"e": 31831,
"s": 31115,
"text": "VectorThe Vector class implements a growable array of objects. Vectors basically fall in legacy classes but now it is fully compatible with collections. Vector implements a dynamic array that means it can grow or shrink as required. Like an array, it contains components that can be accessed using an integer index.// Java code illustrating Vector data structure import java.util.*; class Vector_demo { public static void main(String[] arg) { // Create default vector Vector v = new Vector(); v.add(1); v.add(2); v.add(\"geeks\"); v.add(\"forGeeks\"); v.add(3); System.out.println(\"Vector is \" + v); }}Output:Vector is [1, 2, geeks, forGeeks, 3]\n"
},
{
"code": null,
"e": 32141,
"s": 31831,
"text": "The Vector class implements a growable array of objects. Vectors basically fall in legacy classes but now it is fully compatible with collections. Vector implements a dynamic array that means it can grow or shrink as required. Like an array, it contains components that can be accessed using an integer index."
},
{
"code": "// Java code illustrating Vector data structure import java.util.*; class Vector_demo { public static void main(String[] arg) { // Create default vector Vector v = new Vector(); v.add(1); v.add(2); v.add(\"geeks\"); v.add(\"forGeeks\"); v.add(3); System.out.println(\"Vector is \" + v); }}",
"e": 32498,
"s": 32141,
"text": null
},
{
"code": null,
"e": 32506,
"s": 32498,
"text": "Output:"
},
{
"code": null,
"e": 32544,
"s": 32506,
"text": "Vector is [1, 2, geeks, forGeeks, 3]\n"
},
{
"code": null,
"e": 33562,
"s": 32544,
"text": "StackJava Collection framework provides a Stack class which models and implements a Stack data structure. The class is based on the basic principle of last-in-first-out. In addition to the basic push and pop operations, the class provides three more functions of empty, search and peek. The class can also be said to extend Vector and treats the class as a stack with the five mentioned functions. The class can also be referred to as the subclass of Vector.// Java code for stack implementation import java.io.*;import java.util.*; public class stack_implementation { public static void main(String a[]) { Stack<Integer> stack = new Stack<>(); stack.push(1); stack.push(2); stack.push(3); stack.push(4); int n = stack.size(); for (int i = 0; i < n; i++) { System.out.println(stack.pop()); } }}Output:4\n3\n2\n1\nRelated articles:Stack implementation using ArrayStack implementation using Singly Linked ListStack implementation using Queue"
},
{
"code": null,
"e": 34016,
"s": 33562,
"text": "Java Collection framework provides a Stack class which models and implements a Stack data structure. The class is based on the basic principle of last-in-first-out. In addition to the basic push and pop operations, the class provides three more functions of empty, search and peek. The class can also be said to extend Vector and treats the class as a stack with the five mentioned functions. The class can also be referred to as the subclass of Vector."
},
{
"code": "// Java code for stack implementation import java.io.*;import java.util.*; public class stack_implementation { public static void main(String a[]) { Stack<Integer> stack = new Stack<>(); stack.push(1); stack.push(2); stack.push(3); stack.push(4); int n = stack.size(); for (int i = 0; i < n; i++) { System.out.println(stack.pop()); } }}",
"e": 34435,
"s": 34016,
"text": null
},
{
"code": null,
"e": 34444,
"s": 34435,
"text": "4\n3\n2\n1\n"
},
{
"code": null,
"e": 34462,
"s": 34444,
"text": "Related articles:"
},
{
"code": null,
"e": 34495,
"s": 34462,
"text": "Stack implementation using Array"
},
{
"code": null,
"e": 34541,
"s": 34495,
"text": "Stack implementation using Singly Linked List"
},
{
"code": null,
"e": 34574,
"s": 34541,
"text": "Stack implementation using Queue"
},
{
"code": null,
"e": 36272,
"s": 34574,
"text": "QueueThe Queue interface is available in java.util package and extends the Collection interface. The queue collection is used to hold the elements about to be processed and provides various operations like the insertion, removal etc. It is an ordered list of objects with its use limited to insert elements at the end of the list and deleting elements from the start of list i.e. it follows the FIFO or the First-In-First-Out principle.// Java program to demonstrate working// of Queue interface in Java import java.util.LinkedList;import java.util.Queue; public class QueueExample { public static void main(String[] args) { Queue<Integer> q = new LinkedList<>(); // Adds elements {0, 1, 2, 3, 4} to queue for (int i = 0; i < 5; i++) q.add(i); // Display contents of the queue. System.out.println(\"Elements of queue-\" + q); // To remove the head of queue. int removedele = q.remove(); System.out.println(\"removed element-\" + removedele); System.out.println(q); // To view the head of queue int head = q.peek(); System.out.println(\"head of queue-\" + head); // Rest all methods of collection interface, // Like size and contains can be // used with this implementation. int size = q.size(); System.out.println(\"Size of queue-\" + size); }}Output:Elements of queue-[0, 1, 2, 3, 4]\nremoved element-0\n[1, 2, 3, 4]\nhead of queue-1\nSize of queue-4\nRelated articles:Queue implementation using ArrayQueue implementation using Singly Linked ListQueue implementation using Stack"
},
{
"code": null,
"e": 36704,
"s": 36272,
"text": "The Queue interface is available in java.util package and extends the Collection interface. The queue collection is used to hold the elements about to be processed and provides various operations like the insertion, removal etc. It is an ordered list of objects with its use limited to insert elements at the end of the list and deleting elements from the start of list i.e. it follows the FIFO or the First-In-First-Out principle."
},
{
"code": "// Java program to demonstrate working// of Queue interface in Java import java.util.LinkedList;import java.util.Queue; public class QueueExample { public static void main(String[] args) { Queue<Integer> q = new LinkedList<>(); // Adds elements {0, 1, 2, 3, 4} to queue for (int i = 0; i < 5; i++) q.add(i); // Display contents of the queue. System.out.println(\"Elements of queue-\" + q); // To remove the head of queue. int removedele = q.remove(); System.out.println(\"removed element-\" + removedele); System.out.println(q); // To view the head of queue int head = q.peek(); System.out.println(\"head of queue-\" + head); // Rest all methods of collection interface, // Like size and contains can be // used with this implementation. int size = q.size(); System.out.println(\"Size of queue-\" + size); }}",
"e": 37736,
"s": 36704,
"text": null
},
{
"code": null,
"e": 37834,
"s": 37736,
"text": "Elements of queue-[0, 1, 2, 3, 4]\nremoved element-0\n[1, 2, 3, 4]\nhead of queue-1\nSize of queue-4\n"
},
{
"code": null,
"e": 37852,
"s": 37834,
"text": "Related articles:"
},
{
"code": null,
"e": 37885,
"s": 37852,
"text": "Queue implementation using Array"
},
{
"code": null,
"e": 37931,
"s": 37885,
"text": "Queue implementation using Singly Linked List"
},
{
"code": null,
"e": 37964,
"s": 37931,
"text": "Queue implementation using Stack"
},
{
"code": null,
"e": 40946,
"s": 37964,
"text": "TreeA Tree is a data structure that stores values inside entities called Nodes. Nodes are connected through lines referred to as edges. Each node stores a value inside it.Terminology:Root is the topmost node of the tree.Parent is a node that has one or more Nodes attached to it.Edge is the link joining the two nodes.Child is a node that has a parent nodeLeaf is a node that doesn’t have any child node attached to it, it is the bottommost node of a tree.// Java program for different tree traversals /* Class containing left and right child of current node and key value*/class Node { int key; Node left, right; public Node(int item) { key = item; left = right = null; }} class BinaryTree { // Root of Binary Tree Node root; BinaryTree() { root = null; } /* Given a binary tree, print its nodes according to the \"bottom-up\" postorder traversal. */ void printPostorder(Node node) { if (node == null) return; // first recur on left subtree printPostorder(node.left); // then recur on right subtree printPostorder(node.right); // now deal with the node System.out.print(node.key + \" \"); } /* Given a binary tree, print its nodes in inorder*/ void printInorder(Node node) { if (node == null) return; /* first recur on left child */ printInorder(node.left); /* then print the data of node */ System.out.print(node.key + \" \"); /* now recur on right child */ printInorder(node.right); } /* Given a binary tree, print its nodes in preorder*/ void printPreorder(Node node) { if (node == null) return; /* first print data of node */ System.out.print(node.key + \" \"); /* then recur on left sutree */ printPreorder(node.left); /* now recur on right subtree */ printPreorder(node.right); } // Wrappers over above recursive functions void printPostorder() { printPostorder(root); } void printInorder() { printInorder(root); } void printPreorder() { printPreorder(root); } // Driver method public static void main(String[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); System.out.println( \"Preorder traversal of binary tree is \"); tree.printPreorder(); System.out.println( \"\\nInorder traversal of binary tree is \"); tree.printInorder(); System.out.println( \"\\nPostorder traversal of binary tree is \"); tree.printPostorder(); }}Output:Preorder traversal of binary tree is\n1 2 4 5 3 \nInorder traversal of binary tree is\n4 2 5 1 3 \nPostorder traversal of binary tree is\n4 5 2 3 1\n"
},
{
"code": null,
"e": 41126,
"s": 40946,
"text": "A Tree is a data structure that stores values inside entities called Nodes. Nodes are connected through lines referred to as edges. Each node stores a value inside it.Terminology:"
},
{
"code": null,
"e": 41164,
"s": 41126,
"text": "Root is the topmost node of the tree."
},
{
"code": null,
"e": 41224,
"s": 41164,
"text": "Parent is a node that has one or more Nodes attached to it."
},
{
"code": null,
"e": 41264,
"s": 41224,
"text": "Edge is the link joining the two nodes."
},
{
"code": null,
"e": 41303,
"s": 41264,
"text": "Child is a node that has a parent node"
},
{
"code": null,
"e": 41404,
"s": 41303,
"text": "Leaf is a node that doesn’t have any child node attached to it, it is the bottommost node of a tree."
},
{
"code": "// Java program for different tree traversals /* Class containing left and right child of current node and key value*/class Node { int key; Node left, right; public Node(int item) { key = item; left = right = null; }} class BinaryTree { // Root of Binary Tree Node root; BinaryTree() { root = null; } /* Given a binary tree, print its nodes according to the \"bottom-up\" postorder traversal. */ void printPostorder(Node node) { if (node == null) return; // first recur on left subtree printPostorder(node.left); // then recur on right subtree printPostorder(node.right); // now deal with the node System.out.print(node.key + \" \"); } /* Given a binary tree, print its nodes in inorder*/ void printInorder(Node node) { if (node == null) return; /* first recur on left child */ printInorder(node.left); /* then print the data of node */ System.out.print(node.key + \" \"); /* now recur on right child */ printInorder(node.right); } /* Given a binary tree, print its nodes in preorder*/ void printPreorder(Node node) { if (node == null) return; /* first print data of node */ System.out.print(node.key + \" \"); /* then recur on left sutree */ printPreorder(node.left); /* now recur on right subtree */ printPreorder(node.right); } // Wrappers over above recursive functions void printPostorder() { printPostorder(root); } void printInorder() { printInorder(root); } void printPreorder() { printPreorder(root); } // Driver method public static void main(String[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); System.out.println( \"Preorder traversal of binary tree is \"); tree.printPreorder(); System.out.println( \"\\nInorder traversal of binary tree is \"); tree.printInorder(); System.out.println( \"\\nPostorder traversal of binary tree is \"); tree.printPostorder(); }}",
"e": 43780,
"s": 41404,
"text": null
},
{
"code": null,
"e": 43924,
"s": 43780,
"text": "Preorder traversal of binary tree is\n1 2 4 5 3 \nInorder traversal of binary tree is\n4 2 5 1 3 \nPostorder traversal of binary tree is\n4 5 2 3 1\n"
},
{
"code": null,
"e": 43937,
"s": 43924,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 43950,
"s": 43937,
"text": "mihirmer2000"
},
{
"code": null,
"e": 43962,
"s": 43950,
"text": "Java-Arrays"
},
{
"code": null,
"e": 43973,
"s": 43962,
"text": "java-queue"
},
{
"code": null,
"e": 43984,
"s": 43973,
"text": "Java-Stack"
},
{
"code": null,
"e": 43996,
"s": 43984,
"text": "Java-Vector"
},
{
"code": null,
"e": 44020,
"s": 43996,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 44031,
"s": 44020,
"text": "Algorithms"
},
{
"code": null,
"e": 44038,
"s": 44031,
"text": "Arrays"
},
{
"code": null,
"e": 44054,
"s": 44038,
"text": "Data Structures"
},
{
"code": null,
"e": 44059,
"s": 44054,
"text": "Java"
},
{
"code": null,
"e": 44071,
"s": 44059,
"text": "Linked List"
},
{
"code": null,
"e": 44077,
"s": 44071,
"text": "Queue"
},
{
"code": null,
"e": 44083,
"s": 44077,
"text": "Stack"
},
{
"code": null,
"e": 44088,
"s": 44083,
"text": "Tree"
},
{
"code": null,
"e": 44104,
"s": 44088,
"text": "Data Structures"
},
{
"code": null,
"e": 44116,
"s": 44104,
"text": "Linked List"
},
{
"code": null,
"e": 44123,
"s": 44116,
"text": "Arrays"
},
{
"code": null,
"e": 44129,
"s": 44123,
"text": "Stack"
},
{
"code": null,
"e": 44134,
"s": 44129,
"text": "Java"
},
{
"code": null,
"e": 44140,
"s": 44134,
"text": "Queue"
},
{
"code": null,
"e": 44145,
"s": 44140,
"text": "Tree"
},
{
"code": null,
"e": 44156,
"s": 44145,
"text": "Algorithms"
}
] |
Throwable Class in Java with Examples
|
24 Sep, 2021
Classes and Objects are basic concepts of Object-Oriented Programming which revolve around the real-life entities. A class is a user-defined blueprint or prototype from which objects are created. It represents the set of properties or methods that are common to all objects of one type. In this article, we will discuss the Throwable class, its constructors and different methods available in this class.
The Throwable class is the superclass of every error and exception in the Java language. Only objects that are one of the subclasses this class are thrown by any “Java Virtual Machine” or may be thrown by the Java throw statement. For the motives of checking of exceptions during compile-time, Throwable and any subclass of Throwable which is not also a subclass of either Error or RuntimeException are considered as checked exceptions.
Throwable class is the root class of Java Exception Hierarchy and is inherited by two subclasses: 1.Exception 2.Error The throwable class implements Serializable Interface and the direct known classes to Throwable are Error and Exception. Throwable contains a snapshot of the execution stack of its thread at the time it was created. It can also contain a message string that gives more information about the error. It can also suppress other throwables from being propagated.
If a user wants to create his own, custom throwable, then he/she can extend Throwable class.
Example: Class MyThrowable extends Throwable{ //Here the user can create his own custom throwable }Class GFG{ Public void test() throws MyThrowable{ // the custom throwable created can be used as follows throw new MyThrowable(); } }
The class declaration for java.lang.Throwable class is as follows:
Java
public class Throwable extends Object implements Serializable
Constructors: Any class can have any one of the three or all the three types of constructors. They are default, parameterized and non-parameterized constructors. This class primarily has the following constructors defined:
Public Constructors
Throwable(): It is a non-parameterized constructor which constructs a new Throwable with null as its detailed message.Throwable(String message): It is a parameterized constructor which constructs a new Throwable with the specific detailed message.Throwable(String message, Throwable cause): It is a parameterized constructor which constructs a new Throwable with the specific detailed message and a cause.Throwable(Throwable cause): It is a parameterized constructor which constructs a new Throwable with the specific cause and a detailed message of the cause by converting the case to the String using toString() method.
Throwable(): It is a non-parameterized constructor which constructs a new Throwable with null as its detailed message.
Throwable(String message): It is a parameterized constructor which constructs a new Throwable with the specific detailed message.
Throwable(String message, Throwable cause): It is a parameterized constructor which constructs a new Throwable with the specific detailed message and a cause.
Throwable(Throwable cause): It is a parameterized constructor which constructs a new Throwable with the specific cause and a detailed message of the cause by converting the case to the String using toString() method.
Protected constructors 1. Throwable(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace):It Constructs a new throwable with the specified detail message, cause, suppression enabled or disabled, and writable stack trace enabled or disabled.The parameters are:- message – the detail message. cause – the cause. (A null value is permitted, and indicates that the cause is nonexistent or unknown.) enableSuppression – whether or not suppression is enabled or disabled writableStackTrace – whether or not the stack trace should be writable.
Methods: Apart from the above mentioned constructors, there are also many predefined methods available in the throwable class. They are:
1. addSuppressed(Throwable exception): This method appends the specified exception to the exceptions that were suppressed in order to deliver this exception. Syntax: Public final void addSuppressed(Throwable exception) Returns: This method does not returns anything.2. fillInStackTrace():Fills in the execution stack trace. This method records information about the current state of the stack frames for the current thread within the current Throwable object. Syntax: public Throwable fillInStackTrace () Returns: a reference to the current Throwable instance.3. getCause(): It returns the cause that was supplied via one of the constructors requiring a Throwable , or that was set after creation with the initCause() method. Syntax: public Throwable getCause () Returns: the cause of current Throwable. If the cause is nonexistent or unknown, it returns null.4. getLocalizedMessage(): This method creates a localized description of current Throwable. Syntax: public String getLocalizedMessage () Returns: The localized description of current Throwable5. getMessage():Returns the detail message string of current throwable. Syntax: public String getMessage () Returns: the detailed message string of current Throwable instance( may also return null)6. getStackTrace(): This method provides programmatic access to the stack trace information printed by printStackTrace(). It returns an array of stack trace elements, each representing one stack frame. The zeroth element of the array (assume that the array’s length is non-zero) is the last method invocation in the sequence. It also represents as the top of the stack and is the point at which this throwable was created and thrown. The last element of the array (assuming the array’s length is non-zero) is the first method invocation in the sequence and it represents the bottom of the stack. Syntax: public StackTraceElement[] getStackTrace () Returns: an array of stack trace elements representing the stack trace related to current Throwable.7. getSuppressed():Returns an array containing all of the exceptions that were suppressed, in order to deliver this exception. If no exceptions were suppressed or suppression is disabled, an empty array is returned. Syntax: public final Throwable[] getSuppressed () Returns: an array containing all of the exceptions that were suppressed to deliver this exception.8. initCause(Throwable cause):Initializes the cause of current Throwable to the specified value. This method can be called at most once. It is generally called from within the constructor, or immediately after creating the throwable. Syntax: public Throwable initCause (Throwable cause) Parameters: Throwable cause- the cause of current Throwable. Throws: 1.IllegalArgumentException: This exception is thrown if cause is the current throwable, because a throwable cannot be its own cause. 2. IllegalStateException: It occurs if this method has already been called on current throwable. Returns: a reference to current Throwable instance.9. printStackTrace():Prints the current throwable and its backtrace to the standard error stream. Syntax: public void printStackTrace ()Returns: This method returns nothing.10. printStackTrace(PrintWriter s):Prints current throwable and its backtrace to the specified print writer. Syntax: public void printStackTrace (PrintWriter s) Parameters: PrintWriter- It is the PrintWriter to use for output Returns: This method returns nothing.11. printStackTrace(PrintStream s):Prints current throwable and its backtrace to the specified print stream. Syntax: public void printStackTrace (PrintStream s) Parameters: PrintStream- It is the PrintStream to use for output Returns: This method returns nothing.12. setStackTrace(StackTraceElement[] stackTrace):This method sets the stack trace elements that will be returned by getStackTrace() and printed by printStackTrace() and related methods. Syntax: public void setStackTrace (StackTraceElement[] stackTrace) Parameter: StackTraceElement- These are the stack trace elements to be associated with current Throwable. Throws: NullPointerException- if stackTrace is null or if any of the elements of stackTrace are null Returns: This method returns nothing.13. toString(): This method returns a short description of current throwable. Syntax: public String toString ()Returns: a string representation of current throwable.
Below program demonstrates the toString() method of Throwable class:
Java
// Java program to demonstrate// the toString() Method. import java.io.*; class GFG { // Main Method public static void main(String[] args) throws Exception { try { testException(); } catch (Throwable e) { // Print using tostring() System.out.println("Exception: " + e.toString()); } } // Method which throws Exception public static void testException() throws Exception { throw new Exception( "New Exception Thrown"); }}
Exception:
java.lang.Exception:
New Exception Thrown
Below program demonstrate the getMessage() method of java.lang.Throwable Class:
Java
// Java program to demonstrate// the getMessage() Method. import java.io.*; class GFG { // Main Method public static void main(String[] args) throws Exception { try { // Divide the numbers divide(2, 0); } catch (ArithmeticException e) { System.out.println( "Message String = " + e.getMessage()); } } // Method which divides two numbers public static void divide(int a, int b) throws ArithmeticException { int c = a / b; System.out.println("Result:" + c); }}
Message String = / by zero
Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Throwable.html/
aman1699
anikakapoor
Java-Classes
Java-lang package
java-Throwable
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Collections in Java
Multidimensional Arrays in Java
Stream In Java
Singleton Class in Java
Set in Java
Stack Class in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Sep, 2021"
},
{
"code": null,
"e": 434,
"s": 28,
"text": "Classes and Objects are basic concepts of Object-Oriented Programming which revolve around the real-life entities. A class is a user-defined blueprint or prototype from which objects are created. It represents the set of properties or methods that are common to all objects of one type. In this article, we will discuss the Throwable class, its constructors and different methods available in this class. "
},
{
"code": null,
"e": 871,
"s": 434,
"text": "The Throwable class is the superclass of every error and exception in the Java language. Only objects that are one of the subclasses this class are thrown by any “Java Virtual Machine” or may be thrown by the Java throw statement. For the motives of checking of exceptions during compile-time, Throwable and any subclass of Throwable which is not also a subclass of either Error or RuntimeException are considered as checked exceptions."
},
{
"code": null,
"e": 1349,
"s": 871,
"text": "Throwable class is the root class of Java Exception Hierarchy and is inherited by two subclasses: 1.Exception 2.Error The throwable class implements Serializable Interface and the direct known classes to Throwable are Error and Exception. Throwable contains a snapshot of the execution stack of its thread at the time it was created. It can also contain a message string that gives more information about the error. It can also suppress other throwables from being propagated. "
},
{
"code": null,
"e": 1443,
"s": 1349,
"text": "If a user wants to create his own, custom throwable, then he/she can extend Throwable class. "
},
{
"code": null,
"e": 1677,
"s": 1443,
"text": "Example: Class MyThrowable extends Throwable{ //Here the user can create his own custom throwable }Class GFG{ Public void test() throws MyThrowable{ // the custom throwable created can be used as follows throw new MyThrowable(); } } "
},
{
"code": null,
"e": 1745,
"s": 1677,
"text": "The class declaration for java.lang.Throwable class is as follows: "
},
{
"code": null,
"e": 1750,
"s": 1745,
"text": "Java"
},
{
"code": "public class Throwable extends Object implements Serializable",
"e": 1818,
"s": 1750,
"text": null
},
{
"code": null,
"e": 2042,
"s": 1818,
"text": "Constructors: Any class can have any one of the three or all the three types of constructors. They are default, parameterized and non-parameterized constructors. This class primarily has the following constructors defined: "
},
{
"code": null,
"e": 2064,
"s": 2042,
"text": "Public Constructors "
},
{
"code": null,
"e": 2686,
"s": 2064,
"text": "Throwable(): It is a non-parameterized constructor which constructs a new Throwable with null as its detailed message.Throwable(String message): It is a parameterized constructor which constructs a new Throwable with the specific detailed message.Throwable(String message, Throwable cause): It is a parameterized constructor which constructs a new Throwable with the specific detailed message and a cause.Throwable(Throwable cause): It is a parameterized constructor which constructs a new Throwable with the specific cause and a detailed message of the cause by converting the case to the String using toString() method."
},
{
"code": null,
"e": 2805,
"s": 2686,
"text": "Throwable(): It is a non-parameterized constructor which constructs a new Throwable with null as its detailed message."
},
{
"code": null,
"e": 2935,
"s": 2805,
"text": "Throwable(String message): It is a parameterized constructor which constructs a new Throwable with the specific detailed message."
},
{
"code": null,
"e": 3094,
"s": 2935,
"text": "Throwable(String message, Throwable cause): It is a parameterized constructor which constructs a new Throwable with the specific detailed message and a cause."
},
{
"code": null,
"e": 3311,
"s": 3094,
"text": "Throwable(Throwable cause): It is a parameterized constructor which constructs a new Throwable with the specific cause and a detailed message of the cause by converting the case to the String using toString() method."
},
{
"code": null,
"e": 3882,
"s": 3311,
"text": "Protected constructors 1. Throwable(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace):It Constructs a new throwable with the specified detail message, cause, suppression enabled or disabled, and writable stack trace enabled or disabled.The parameters are:- message – the detail message. cause – the cause. (A null value is permitted, and indicates that the cause is nonexistent or unknown.) enableSuppression – whether or not suppression is enabled or disabled writableStackTrace – whether or not the stack trace should be writable."
},
{
"code": null,
"e": 4020,
"s": 3882,
"text": "Methods: Apart from the above mentioned constructors, there are also many predefined methods available in the throwable class. They are: "
},
{
"code": null,
"e": 8381,
"s": 4020,
"text": "1. addSuppressed(Throwable exception): This method appends the specified exception to the exceptions that were suppressed in order to deliver this exception. Syntax: Public final void addSuppressed(Throwable exception) Returns: This method does not returns anything.2. fillInStackTrace():Fills in the execution stack trace. This method records information about the current state of the stack frames for the current thread within the current Throwable object. Syntax: public Throwable fillInStackTrace () Returns: a reference to the current Throwable instance.3. getCause(): It returns the cause that was supplied via one of the constructors requiring a Throwable , or that was set after creation with the initCause() method. Syntax: public Throwable getCause () Returns: the cause of current Throwable. If the cause is nonexistent or unknown, it returns null.4. getLocalizedMessage(): This method creates a localized description of current Throwable. Syntax: public String getLocalizedMessage () Returns: The localized description of current Throwable5. getMessage():Returns the detail message string of current throwable. Syntax: public String getMessage () Returns: the detailed message string of current Throwable instance( may also return null)6. getStackTrace(): This method provides programmatic access to the stack trace information printed by printStackTrace(). It returns an array of stack trace elements, each representing one stack frame. The zeroth element of the array (assume that the array’s length is non-zero) is the last method invocation in the sequence. It also represents as the top of the stack and is the point at which this throwable was created and thrown. The last element of the array (assuming the array’s length is non-zero) is the first method invocation in the sequence and it represents the bottom of the stack. Syntax: public StackTraceElement[] getStackTrace () Returns: an array of stack trace elements representing the stack trace related to current Throwable.7. getSuppressed():Returns an array containing all of the exceptions that were suppressed, in order to deliver this exception. If no exceptions were suppressed or suppression is disabled, an empty array is returned. Syntax: public final Throwable[] getSuppressed () Returns: an array containing all of the exceptions that were suppressed to deliver this exception.8. initCause(Throwable cause):Initializes the cause of current Throwable to the specified value. This method can be called at most once. It is generally called from within the constructor, or immediately after creating the throwable. Syntax: public Throwable initCause (Throwable cause) Parameters: Throwable cause- the cause of current Throwable. Throws: 1.IllegalArgumentException: This exception is thrown if cause is the current throwable, because a throwable cannot be its own cause. 2. IllegalStateException: It occurs if this method has already been called on current throwable. Returns: a reference to current Throwable instance.9. printStackTrace():Prints the current throwable and its backtrace to the standard error stream. Syntax: public void printStackTrace ()Returns: This method returns nothing.10. printStackTrace(PrintWriter s):Prints current throwable and its backtrace to the specified print writer. Syntax: public void printStackTrace (PrintWriter s) Parameters: PrintWriter- It is the PrintWriter to use for output Returns: This method returns nothing.11. printStackTrace(PrintStream s):Prints current throwable and its backtrace to the specified print stream. Syntax: public void printStackTrace (PrintStream s) Parameters: PrintStream- It is the PrintStream to use for output Returns: This method returns nothing.12. setStackTrace(StackTraceElement[] stackTrace):This method sets the stack trace elements that will be returned by getStackTrace() and printed by printStackTrace() and related methods. Syntax: public void setStackTrace (StackTraceElement[] stackTrace) Parameter: StackTraceElement- These are the stack trace elements to be associated with current Throwable. Throws: NullPointerException- if stackTrace is null or if any of the elements of stackTrace are null Returns: This method returns nothing.13. toString(): This method returns a short description of current throwable. Syntax: public String toString ()Returns: a string representation of current throwable."
},
{
"code": null,
"e": 8450,
"s": 8381,
"text": "Below program demonstrates the toString() method of Throwable class:"
},
{
"code": null,
"e": 8455,
"s": 8450,
"text": "Java"
},
{
"code": "// Java program to demonstrate// the toString() Method. import java.io.*; class GFG { // Main Method public static void main(String[] args) throws Exception { try { testException(); } catch (Throwable e) { // Print using tostring() System.out.println(\"Exception: \" + e.toString()); } } // Method which throws Exception public static void testException() throws Exception { throw new Exception( \"New Exception Thrown\"); }}",
"e": 9031,
"s": 8455,
"text": null
},
{
"code": null,
"e": 9086,
"s": 9031,
"text": "Exception:\n java.lang.Exception:\n New Exception Thrown"
},
{
"code": null,
"e": 9169,
"s": 9088,
"text": "Below program demonstrate the getMessage() method of java.lang.Throwable Class: "
},
{
"code": null,
"e": 9174,
"s": 9169,
"text": "Java"
},
{
"code": "// Java program to demonstrate// the getMessage() Method. import java.io.*; class GFG { // Main Method public static void main(String[] args) throws Exception { try { // Divide the numbers divide(2, 0); } catch (ArithmeticException e) { System.out.println( \"Message String = \" + e.getMessage()); } } // Method which divides two numbers public static void divide(int a, int b) throws ArithmeticException { int c = a / b; System.out.println(\"Result:\" + c); }}",
"e": 9782,
"s": 9174,
"text": null
},
{
"code": null,
"e": 9809,
"s": 9782,
"text": "Message String = / by zero"
},
{
"code": null,
"e": 9891,
"s": 9811,
"text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Throwable.html/ "
},
{
"code": null,
"e": 9900,
"s": 9891,
"text": "aman1699"
},
{
"code": null,
"e": 9912,
"s": 9900,
"text": "anikakapoor"
},
{
"code": null,
"e": 9925,
"s": 9912,
"text": "Java-Classes"
},
{
"code": null,
"e": 9943,
"s": 9925,
"text": "Java-lang package"
},
{
"code": null,
"e": 9958,
"s": 9943,
"text": "java-Throwable"
},
{
"code": null,
"e": 9963,
"s": 9958,
"text": "Java"
},
{
"code": null,
"e": 9968,
"s": 9963,
"text": "Java"
},
{
"code": null,
"e": 10066,
"s": 9968,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10097,
"s": 10066,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 10116,
"s": 10097,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 10146,
"s": 10116,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 10164,
"s": 10146,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 10184,
"s": 10164,
"text": "Collections in Java"
},
{
"code": null,
"e": 10216,
"s": 10184,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 10231,
"s": 10216,
"text": "Stream In Java"
},
{
"code": null,
"e": 10255,
"s": 10231,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 10267,
"s": 10255,
"text": "Set in Java"
}
] |
Hello World in Dart Programming
|
A Hello World program is the first program that you learn whenever you are learning a new programming language. It might be a simple program but it is a great entry point as you get to know how a program works in Dart, how to run a dart file. It provides a way to test the systems and environment that you are using.
An important prerequisite before running a Hello World in Dart is to have the Dart SDK installed on your local machine. You can install the Dart SDK from this link.
The first thing that you need to do is open the terminal or cmd (if you are on Windows) and then run the following command −
touch hello_world.dart
The above command will work on macOS and Linux operating systems. For windows, you can use any text editor of your choice and then save the file with the .dart extension.
The program will look something like this −
Live Demo
void main(){
print("Hello World");
}
Hello World
It looks very simple, in fact, it is. Though we need to understand some of the keywords that we used in the above program to understand it better.
main - the entry point of our program.
main - the entry point of our program.
void - the keyword that tells the compiler that we are not returning anything from the function.
void - the keyword that tells the compiler that we are not returning anything from the function.
print - the print function is used to print (output) whatever we put inside the parentheses.
print - the print function is used to print (output) whatever we put inside the parentheses.
|
[
{
"code": null,
"e": 1504,
"s": 1187,
"text": "A Hello World program is the first program that you learn whenever you are learning a new programming language. It might be a simple program but it is a great entry point as you get to know how a program works in Dart, how to run a dart file. It provides a way to test the systems and environment that you are using."
},
{
"code": null,
"e": 1669,
"s": 1504,
"text": "An important prerequisite before running a Hello World in Dart is to have the Dart SDK installed on your local machine. You can install the Dart SDK from this link."
},
{
"code": null,
"e": 1794,
"s": 1669,
"text": "The first thing that you need to do is open the terminal or cmd (if you are on Windows) and then run the following command −"
},
{
"code": null,
"e": 1817,
"s": 1794,
"text": "touch hello_world.dart"
},
{
"code": null,
"e": 1988,
"s": 1817,
"text": "The above command will work on macOS and Linux operating systems. For windows, you can use any text editor of your choice and then save the file with the .dart extension."
},
{
"code": null,
"e": 2032,
"s": 1988,
"text": "The program will look something like this −"
},
{
"code": null,
"e": 2043,
"s": 2032,
"text": " Live Demo"
},
{
"code": null,
"e": 2083,
"s": 2043,
"text": "void main(){\n print(\"Hello World\");\n}"
},
{
"code": null,
"e": 2095,
"s": 2083,
"text": "Hello World"
},
{
"code": null,
"e": 2242,
"s": 2095,
"text": "It looks very simple, in fact, it is. Though we need to understand some of the keywords that we used in the above program to understand it better."
},
{
"code": null,
"e": 2281,
"s": 2242,
"text": "main - the entry point of our program."
},
{
"code": null,
"e": 2320,
"s": 2281,
"text": "main - the entry point of our program."
},
{
"code": null,
"e": 2417,
"s": 2320,
"text": "void - the keyword that tells the compiler that we are not returning anything from the function."
},
{
"code": null,
"e": 2514,
"s": 2417,
"text": "void - the keyword that tells the compiler that we are not returning anything from the function."
},
{
"code": null,
"e": 2607,
"s": 2514,
"text": "print - the print function is used to print (output) whatever we put inside the parentheses."
},
{
"code": null,
"e": 2700,
"s": 2607,
"text": "print - the print function is used to print (output) whatever we put inside the parentheses."
}
] |
Python iter() method
|
11 Apr, 2022
python iter() method returns the iterator object, it is used to convert an iterable to the iterator.
Syntax : iter(obj, sentinel)
Parameters :
obj : Object which has to be converted to iterable ( usually an iterator ).
sentinel : value used to represent end of sequence.
Returns : Iterator object
Iteration object remembers iteration count via internal count variable.
Once the iteration is complete, it raises a StopIteration exception and the iteration count cannot be reassigned to 0.
Therefore, it can be used to traverse the container just once.
Python3
# Python3 code to demonstrate# working of iter() # initializing listlis1 = [1, 2, 3, 4, 5] # printing typeprint("The list is of type : " + str(type(lis1))) # converting list using iter()lis1 = iter(lis1) # printing typeprint("The iterator is of type : " + str(type(lis1))) # using next() to print iterator valuesprint(next(lis1))print(next(lis1))print(next(lis1))print(next(lis1))print(next(lis1))
The list is of type : <class 'list'>
The iterator is of type : <class 'list_iterator'>
1
2
3
4
5
Python3
# Python 3 code to demonstrate# property of iter() # initializing listlis1 = [1, 2, 3, 4, 5] # converting list using iter()lis1 = iter(lis1) # prints thisprint("Values at 1st iteration : ")for i in range(0, 5): print(next(lis1)) # doesn't print thisprint("Values at 2nd iteration : ")for i in range(0, 5): print(next(lis1))
Expected Output:
Values at 1st iteration :
1
2
3
4
5
Values at 2nd iteration :
Actual Exception (Error):
Traceback (most recent call last):
File "/home/0d0e86c6115170d7cd9083bcef1f22ef.py", line 18, in
print (next(lis1))
StopIteration
kumar_satyam
arshadali02177
Python-Built-in-functions
python-list
python-list-functions
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
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
Convert integer to string in Python
Introduction To PYTHON
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Apr, 2022"
},
{
"code": null,
"e": 129,
"s": 28,
"text": "python iter() method returns the iterator object, it is used to convert an iterable to the iterator."
},
{
"code": null,
"e": 158,
"s": 129,
"text": "Syntax : iter(obj, sentinel)"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Parameters : "
},
{
"code": null,
"e": 248,
"s": 172,
"text": "obj : Object which has to be converted to iterable ( usually an iterator )."
},
{
"code": null,
"e": 300,
"s": 248,
"text": "sentinel : value used to represent end of sequence."
},
{
"code": null,
"e": 326,
"s": 300,
"text": "Returns : Iterator object"
},
{
"code": null,
"e": 398,
"s": 326,
"text": "Iteration object remembers iteration count via internal count variable."
},
{
"code": null,
"e": 517,
"s": 398,
"text": "Once the iteration is complete, it raises a StopIteration exception and the iteration count cannot be reassigned to 0."
},
{
"code": null,
"e": 580,
"s": 517,
"text": "Therefore, it can be used to traverse the container just once."
},
{
"code": null,
"e": 588,
"s": 580,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate# working of iter() # initializing listlis1 = [1, 2, 3, 4, 5] # printing typeprint(\"The list is of type : \" + str(type(lis1))) # converting list using iter()lis1 = iter(lis1) # printing typeprint(\"The iterator is of type : \" + str(type(lis1))) # using next() to print iterator valuesprint(next(lis1))print(next(lis1))print(next(lis1))print(next(lis1))print(next(lis1))",
"e": 986,
"s": 588,
"text": null
},
{
"code": null,
"e": 1084,
"s": 986,
"text": "The list is of type : <class 'list'>\nThe iterator is of type : <class 'list_iterator'>\n1\n2\n3\n4\n5\n"
},
{
"code": null,
"e": 1092,
"s": 1084,
"text": "Python3"
},
{
"code": "# Python 3 code to demonstrate# property of iter() # initializing listlis1 = [1, 2, 3, 4, 5] # converting list using iter()lis1 = iter(lis1) # prints thisprint(\"Values at 1st iteration : \")for i in range(0, 5): print(next(lis1)) # doesn't print thisprint(\"Values at 2nd iteration : \")for i in range(0, 5): print(next(lis1))",
"e": 1422,
"s": 1092,
"text": null
},
{
"code": null,
"e": 1440,
"s": 1422,
"text": "Expected Output: "
},
{
"code": null,
"e": 1504,
"s": 1440,
"text": "Values at 1st iteration : \n1\n2\n3\n4\n5\nValues at 2nd iteration : "
},
{
"code": null,
"e": 1531,
"s": 1504,
"text": "Actual Exception (Error): "
},
{
"code": null,
"e": 1668,
"s": 1531,
"text": "Traceback (most recent call last):\n File \"/home/0d0e86c6115170d7cd9083bcef1f22ef.py\", line 18, in \n print (next(lis1))\nStopIteration"
},
{
"code": null,
"e": 1681,
"s": 1668,
"text": "kumar_satyam"
},
{
"code": null,
"e": 1696,
"s": 1681,
"text": "arshadali02177"
},
{
"code": null,
"e": 1722,
"s": 1696,
"text": "Python-Built-in-functions"
},
{
"code": null,
"e": 1734,
"s": 1722,
"text": "python-list"
},
{
"code": null,
"e": 1756,
"s": 1734,
"text": "python-list-functions"
},
{
"code": null,
"e": 1763,
"s": 1756,
"text": "Python"
},
{
"code": null,
"e": 1775,
"s": 1763,
"text": "python-list"
},
{
"code": null,
"e": 1873,
"s": 1775,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1891,
"s": 1873,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1933,
"s": 1891,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1968,
"s": 1933,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1994,
"s": 1968,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2026,
"s": 1994,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2055,
"s": 2026,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2082,
"s": 2055,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2103,
"s": 2082,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2139,
"s": 2103,
"text": "Convert integer to string in Python"
}
] |
FileInputStream close() Method in Java with Examples
|
01 Dec, 2021
FileInputStream class is helpful to read data from a file in the form of a sequence of bytes. FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader.
After any operation to the file, we have to close that file. For that purpose, we have a close method. We will learn that in this article. The FileInputStream.close() method closes this file input stream and releases any system resources associated with the stream.
Syntax:
FileInputStream.close()
Return Value: The method does not return any value.
Exception: IOException − If any I/O error occurs.
Step 1: Attach a file to a FileInputStream as this will enable us to close the file as shown below as follows:
FileInputStream fileInputStream =new FileInputStream(“file.txt”);
Step 2: To close the file, we have to call the close() method using the above instance.
fileInputStream.close();
Approach:
1. We will first read a file and then close it.
2. After closing a file, we will again try to read it.
Java
// Java program to demonstrate the working// of the FileInputStream close() method import java.io.File;import java.io.FileInputStream; public class abc { public static void main(String[] args) { // Creating file object and specifying path File file = new File("file.txt"); try { FileInputStream input = new FileInputStream(file); int character; // read character by character by default // read() function return int between // 0 and 255. while ((character = input.read()) != -1) { System.out.print((char)character); } input.close(); System.out.println("File is Closed"); System.out.println( "Now we will again try to read"); while ((character = input.read()) != -1) { System.out.print((char)character); } } catch (Exception e) { System.out.println( "File is closed. Cannot be read"); e.printStackTrace(); } }}
Output
GeeksforGeeks is a computer science portal
File is Closed
Now we will again try to read
File is closed. Cannot be read
java.io.IOException: Stream Closed
at java.base/java.io.FileInputStream.read0(Native Method)
at java.base/java.io.FileInputStream.read(Unknown Source)
at abc.main(abc.java:28)
Note: This code will not run on an online IDE as it requires a file on the system.
Java-FileInputStream
Java-Functions
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Java Programming Examples
Functional Interfaces in Java
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Dec, 2021"
},
{
"code": null,
"e": 262,
"s": 28,
"text": "FileInputStream class is helpful to read data from a file in the form of a sequence of bytes. FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader."
},
{
"code": null,
"e": 528,
"s": 262,
"text": "After any operation to the file, we have to close that file. For that purpose, we have a close method. We will learn that in this article. The FileInputStream.close() method closes this file input stream and releases any system resources associated with the stream."
},
{
"code": null,
"e": 536,
"s": 528,
"text": "Syntax:"
},
{
"code": null,
"e": 560,
"s": 536,
"text": "FileInputStream.close()"
},
{
"code": null,
"e": 612,
"s": 560,
"text": "Return Value: The method does not return any value."
},
{
"code": null,
"e": 662,
"s": 612,
"text": "Exception: IOException − If any I/O error occurs."
},
{
"code": null,
"e": 773,
"s": 662,
"text": "Step 1: Attach a file to a FileInputStream as this will enable us to close the file as shown below as follows:"
},
{
"code": null,
"e": 840,
"s": 773,
"text": "FileInputStream fileInputStream =new FileInputStream(“file.txt”);"
},
{
"code": null,
"e": 928,
"s": 840,
"text": "Step 2: To close the file, we have to call the close() method using the above instance."
},
{
"code": null,
"e": 954,
"s": 928,
"text": "fileInputStream.close(); "
},
{
"code": null,
"e": 964,
"s": 954,
"text": "Approach:"
},
{
"code": null,
"e": 1012,
"s": 964,
"text": "1. We will first read a file and then close it."
},
{
"code": null,
"e": 1067,
"s": 1012,
"text": "2. After closing a file, we will again try to read it."
},
{
"code": null,
"e": 1072,
"s": 1067,
"text": "Java"
},
{
"code": "// Java program to demonstrate the working// of the FileInputStream close() method import java.io.File;import java.io.FileInputStream; public class abc { public static void main(String[] args) { // Creating file object and specifying path File file = new File(\"file.txt\"); try { FileInputStream input = new FileInputStream(file); int character; // read character by character by default // read() function return int between // 0 and 255. while ((character = input.read()) != -1) { System.out.print((char)character); } input.close(); System.out.println(\"File is Closed\"); System.out.println( \"Now we will again try to read\"); while ((character = input.read()) != -1) { System.out.print((char)character); } } catch (Exception e) { System.out.println( \"File is closed. Cannot be read\"); e.printStackTrace(); } }}",
"e": 2175,
"s": 1072,
"text": null
},
{
"code": null,
"e": 2182,
"s": 2175,
"text": "Output"
},
{
"code": null,
"e": 2498,
"s": 2182,
"text": "GeeksforGeeks is a computer science portal\nFile is Closed\nNow we will again try to read\nFile is closed. Cannot be read\njava.io.IOException: Stream Closed\n at java.base/java.io.FileInputStream.read0(Native Method)\n at java.base/java.io.FileInputStream.read(Unknown Source)\n at abc.main(abc.java:28)"
},
{
"code": null,
"e": 2581,
"s": 2498,
"text": "Note: This code will not run on an online IDE as it requires a file on the system."
},
{
"code": null,
"e": 2602,
"s": 2581,
"text": "Java-FileInputStream"
},
{
"code": null,
"e": 2617,
"s": 2602,
"text": "Java-Functions"
},
{
"code": null,
"e": 2624,
"s": 2617,
"text": "Picked"
},
{
"code": null,
"e": 2629,
"s": 2624,
"text": "Java"
},
{
"code": null,
"e": 2634,
"s": 2629,
"text": "Java"
},
{
"code": null,
"e": 2732,
"s": 2634,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2747,
"s": 2732,
"text": "Stream In Java"
},
{
"code": null,
"e": 2768,
"s": 2747,
"text": "Introduction to Java"
},
{
"code": null,
"e": 2789,
"s": 2768,
"text": "Constructors in Java"
},
{
"code": null,
"e": 2808,
"s": 2789,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 2825,
"s": 2808,
"text": "Generics in Java"
},
{
"code": null,
"e": 2851,
"s": 2825,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 2881,
"s": 2851,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 2897,
"s": 2881,
"text": "Strings in Java"
},
{
"code": null,
"e": 2934,
"s": 2897,
"text": "Differences between JDK, JRE and JVM"
}
] |
Java @Retention Annotations
|
10 May, 2022
In Java, annotations are used to attach meta-data to a program element such as a class, method, instances, etc. Some annotations are used to annotate other annotations. These types of annotations are known as meta-annotations. @Retention is also a meta-annotation that comes with some retention policies. These retention policies determine at which point an annotation is discarded. There are three types of retention policies: SOURCE, CLASS, and RUNTIME.
RetentionPolicy.SOURCE: The annotations annotated using the SOURCE retention policy are discarded at runtime.
RetentionPolicy.CLASS: The annotations annotated using the CLASS retention policy are recorded in the .class file but are discarded during runtime. CLASS is the default retention policy in Java.
RetentionPolicy.RUNTIME: The annotations annotated using the RUNTIME retention policy are retained during runtime and can be accessed in our program during runtime.
Implementation:
Here we will be creating three custom annotations with retention policies such as SOURCE, CLASS, and RUNTIME. These custom annotations are later used to annotate three classes, namely A, B, and C. In the main method, we check if the annotations are attached to classes at runtime or not.
Example
Java
// Java Program to Illustrate Retention Annotations // Importing required classes from java.lang packageimport java.lang.annotation.Annotation;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy; // Here we will be creating 3 annotations with// RetentionPolicy as SOURCE, CLASS, & RUNTIME // Retention Annotation 1@Retention(RetentionPolicy.SOURCE) // Interface@interface SourceRetention{ String value() default "Source Retention";} // Retention Annotation 2@Retention(RetentionPolicy.CLASS) // Interface@interface ClassRetention{ String value() default "Class Retention";} // Retention Annotation 3@Retention(RetentionPolicy.RUNTIME) // Interface@interface RuntimeRetention{ String value() default "Runtime Retention";} // Annotating classes A, B, and C// with our custom annotations@SourceRetentionclass A {} @ClassRetentionclass B {} @RuntimeRetentionclass C {}; // Main classpublic class RetentionPolicyDemo { // Main driver method public static void main(String[] args) { // Obtaining the array of annotations used to // annotate class A, B, and C. Array a and b will be // empty as their annotation are attached before // runtime while array c will contain the // RuntimeRetention annotation as it was marked with // RUNTIME retention policy Annotation a[] = new A().getClass().getAnnotations(); Annotation b[] = new B().getClass().getAnnotations(); Annotation c[] = new C().getClass().getAnnotations(); // Printing the number of retained annotations of // each class at runtime System.out.println( "Number of annotations attached to " + "class A at Runtime: " + a.length); System.out.println( "Number of annotations attached to " + "class B at Runtime: " + b.length); System.out.println( "Number of annotations attached to " + "class C at Runtime: " + c.length); // Since the class C is annotated with an annotation // which has retention policy as runtime so it // can be accessed during runtime while annotations // of other two classes are discarded before runtime // so they can't be accessed System.out.println( "Annotation attached to class C: " + c[0]); }}
Number of annotations attached to class A at Runtime: 0
Number of annotations attached to class B at Runtime: 0
Number of annotations attached to class C at Runtime: 1
Annotation attached to class C: @RuntimeRetention(value="Runtime Retention")
varshagumber28
simmytarika5
Java-Annotation
Picked
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": "\n10 May, 2022"
},
{
"code": null,
"e": 484,
"s": 28,
"text": "In Java, annotations are used to attach meta-data to a program element such as a class, method, instances, etc. Some annotations are used to annotate other annotations. These types of annotations are known as meta-annotations. @Retention is also a meta-annotation that comes with some retention policies. These retention policies determine at which point an annotation is discarded. There are three types of retention policies: SOURCE, CLASS, and RUNTIME."
},
{
"code": null,
"e": 594,
"s": 484,
"text": "RetentionPolicy.SOURCE: The annotations annotated using the SOURCE retention policy are discarded at runtime."
},
{
"code": null,
"e": 789,
"s": 594,
"text": "RetentionPolicy.CLASS: The annotations annotated using the CLASS retention policy are recorded in the .class file but are discarded during runtime. CLASS is the default retention policy in Java."
},
{
"code": null,
"e": 954,
"s": 789,
"text": "RetentionPolicy.RUNTIME: The annotations annotated using the RUNTIME retention policy are retained during runtime and can be accessed in our program during runtime."
},
{
"code": null,
"e": 970,
"s": 954,
"text": "Implementation:"
},
{
"code": null,
"e": 1258,
"s": 970,
"text": "Here we will be creating three custom annotations with retention policies such as SOURCE, CLASS, and RUNTIME. These custom annotations are later used to annotate three classes, namely A, B, and C. In the main method, we check if the annotations are attached to classes at runtime or not."
},
{
"code": null,
"e": 1266,
"s": 1258,
"text": "Example"
},
{
"code": null,
"e": 1271,
"s": 1266,
"text": "Java"
},
{
"code": "// Java Program to Illustrate Retention Annotations // Importing required classes from java.lang packageimport java.lang.annotation.Annotation;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy; // Here we will be creating 3 annotations with// RetentionPolicy as SOURCE, CLASS, & RUNTIME // Retention Annotation 1@Retention(RetentionPolicy.SOURCE) // Interface@interface SourceRetention{ String value() default \"Source Retention\";} // Retention Annotation 2@Retention(RetentionPolicy.CLASS) // Interface@interface ClassRetention{ String value() default \"Class Retention\";} // Retention Annotation 3@Retention(RetentionPolicy.RUNTIME) // Interface@interface RuntimeRetention{ String value() default \"Runtime Retention\";} // Annotating classes A, B, and C// with our custom annotations@SourceRetentionclass A {} @ClassRetentionclass B {} @RuntimeRetentionclass C {}; // Main classpublic class RetentionPolicyDemo { // Main driver method public static void main(String[] args) { // Obtaining the array of annotations used to // annotate class A, B, and C. Array a and b will be // empty as their annotation are attached before // runtime while array c will contain the // RuntimeRetention annotation as it was marked with // RUNTIME retention policy Annotation a[] = new A().getClass().getAnnotations(); Annotation b[] = new B().getClass().getAnnotations(); Annotation c[] = new C().getClass().getAnnotations(); // Printing the number of retained annotations of // each class at runtime System.out.println( \"Number of annotations attached to \" + \"class A at Runtime: \" + a.length); System.out.println( \"Number of annotations attached to \" + \"class B at Runtime: \" + b.length); System.out.println( \"Number of annotations attached to \" + \"class C at Runtime: \" + c.length); // Since the class C is annotated with an annotation // which has retention policy as runtime so it // can be accessed during runtime while annotations // of other two classes are discarded before runtime // so they can't be accessed System.out.println( \"Annotation attached to class C: \" + c[0]); }}",
"e": 3650,
"s": 1271,
"text": null
},
{
"code": null,
"e": 3898,
"s": 3653,
"text": "Number of annotations attached to class A at Runtime: 0\nNumber of annotations attached to class B at Runtime: 0\nNumber of annotations attached to class C at Runtime: 1\nAnnotation attached to class C: @RuntimeRetention(value=\"Runtime Retention\")"
},
{
"code": null,
"e": 3915,
"s": 3900,
"text": "varshagumber28"
},
{
"code": null,
"e": 3928,
"s": 3915,
"text": "simmytarika5"
},
{
"code": null,
"e": 3944,
"s": 3928,
"text": "Java-Annotation"
},
{
"code": null,
"e": 3951,
"s": 3944,
"text": "Picked"
},
{
"code": null,
"e": 3956,
"s": 3951,
"text": "Java"
},
{
"code": null,
"e": 3961,
"s": 3956,
"text": "Java"
}
] |
Python | User groups with Custom permissions in Django
|
31 May, 2022
Let’s consider a trip booking service, how they work with different plans and packages. There is a list of product which subscriber gets on subscribing to different packages, provided by the company. Generally, the idea they follow is the level-wise distribution of different products.
Let’s see the different packages available on tour booking service :
Starter plan : In this package, subscriber will get the facility of non-AC bus travel and 1-day stay in a non-AC room only. Let’s say the trip is from Delhi to Haridwar(a religious place in Uttarakhand).Golden Plan : It will be somewhat costly than the Starter Plan. In this plan, subscriber will be given 2-day stay in a non-AC room, travelling in a AC bus and the trip will be from Delhi to Haridwar, Rishikesh and Mussoorie.Diamond Plan: This is the most costly plan, in which subscriber will be provided 3-day plan with AC bus and AC room stay, along with the trip to Haridwar, Rishikesh and Mussoorie and also trip to the Water Park.
Starter plan : In this package, subscriber will get the facility of non-AC bus travel and 1-day stay in a non-AC room only. Let’s say the trip is from Delhi to Haridwar(a religious place in Uttarakhand).
Golden Plan : It will be somewhat costly than the Starter Plan. In this plan, subscriber will be given 2-day stay in a non-AC room, travelling in a AC bus and the trip will be from Delhi to Haridwar, Rishikesh and Mussoorie.
Diamond Plan: This is the most costly plan, in which subscriber will be provided 3-day plan with AC bus and AC room stay, along with the trip to Haridwar, Rishikesh and Mussoorie and also trip to the Water Park.
Our main objective is to design and write code for the back-end in a very efficient way(following the DRY Principle).There are multiple methods of implementing this in Django but the most suitable and efficient method is Grouping the Users and defining the permissions of these groups. User of that particular group will automatically inherit the permission of that particular group. Let’s define the User model first :
Create a Django application users. In models.py file, under ‘users’ app directory, write this code.
Python3
# importing necessary django classesfrom django.contrib.auth.models import AbstractUserfrom django.utils import timezonefrom django.db import models # User classclass User(AbstractUser): # Define the extra fields # related to User here first_name = models.CharField(_('First Name of User'), blank = True, max_length = 20) last_name = models.CharField(_('Last Name of User'), blank = True, max_length = 20) # More User fields according to need # define the custom permissions # related to User. class Meta: permissions = ( ("can_go_in_non_ac_bus", "To provide non-AC Bus facility"), ("can_go_in_ac_bus", "To provide AC-Bus facility"), ("can_stay_ac-room", "To provide staying at AC room"), ("can_stay_ac-room", "To provide staying at Non-AC room"), ("can_go_dehradoon", "Trip to Dehradoon"), ("can_go_mussoorie", "Trip to Mussoorie"), ("can_go_haridwaar", "Trip to Haridwaar"), ("can_go_rishikesh", "Trip to Rishikesh"), # Add other custom permissions according to need.
After migrating the models written above, we have two option for making the group.
Django Admin Panel : In Admin Panel you will see Group in bold letter, Click on that and make 3-different group named level0, level1, level3 . Also, define the custom permissions according to the need.By Programmatically creating a group with permissions: Open python shell using python manage.py shell.
Django Admin Panel : In Admin Panel you will see Group in bold letter, Click on that and make 3-different group named level0, level1, level3 . Also, define the custom permissions according to the need.
By Programmatically creating a group with permissions: Open python shell using python manage.py shell.
Python3
# importing group class from djangofrom django.contrib.auth.models import Group, Permissionfrom django.contrib.contenttypes.models import ContentType # import User modelfrom users.models import User new_group, created = Group.objects.get_or_create(name ='new_group') # Code to add permission to groupct = ContentType.objects.get_for_model(User) # If I want to add 'Can go Haridwar' permission to level0 ?permission = Permission.objects.create(codename ='can_go_haridwar', name ='Can go to Haridwar', content_type = ct)new_group.permissions.add(permission)
We will set different set of permissions in the same way to all the three groups. Until then, we have made groups and linked it with custom permissions.
Now, check that a particular user is accessing the appropriate functionality like, put a limit that level0 does not access the functionalities of level1 users or level2 user and so on. To do this, check the permission on every view function made.To be very careful here, for the function based view we will simply use the custom decorator.
For example :
Python
@group_required('level0')def my_view(request): ...
For more details, refer this.Things get a bit complex when we talk about class-based views, we can not simply just add a decorator function, but we have to make a permission-mixing class.
For example :
Python
class GroupRequiredMixin(object): ............... ....Class Definition..... class DemoView(GroupRequiredMixin, View): group_required = [u'admin', u'manager'] # View code...
For more details, refer this.
References : 1. https://docs.djangoproject.com/en/1.11/topics/class-based-views/mixins/ 2. http://bradmontgomery.blogspot.in/2009/04/restricting-access-by-group-in-django.html 3. https://simpleisbetterthancomplex.com/2015/12/07/working-with-django-view-decorators.html 4. https://micropyramid.com/blog/custom-decorators-to-check-user-roles-and-permissions-in-django/
adnanirshad158
simmytarika5
akankshaarora2122
Python Django
Python
Web Technologies
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()
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": 52,
"s": 24,
"text": "\n31 May, 2022"
},
{
"code": null,
"e": 338,
"s": 52,
"text": "Let’s consider a trip booking service, how they work with different plans and packages. There is a list of product which subscriber gets on subscribing to different packages, provided by the company. Generally, the idea they follow is the level-wise distribution of different products."
},
{
"code": null,
"e": 407,
"s": 338,
"text": "Let’s see the different packages available on tour booking service :"
},
{
"code": null,
"e": 1046,
"s": 407,
"text": "Starter plan : In this package, subscriber will get the facility of non-AC bus travel and 1-day stay in a non-AC room only. Let’s say the trip is from Delhi to Haridwar(a religious place in Uttarakhand).Golden Plan : It will be somewhat costly than the Starter Plan. In this plan, subscriber will be given 2-day stay in a non-AC room, travelling in a AC bus and the trip will be from Delhi to Haridwar, Rishikesh and Mussoorie.Diamond Plan: This is the most costly plan, in which subscriber will be provided 3-day plan with AC bus and AC room stay, along with the trip to Haridwar, Rishikesh and Mussoorie and also trip to the Water Park."
},
{
"code": null,
"e": 1250,
"s": 1046,
"text": "Starter plan : In this package, subscriber will get the facility of non-AC bus travel and 1-day stay in a non-AC room only. Let’s say the trip is from Delhi to Haridwar(a religious place in Uttarakhand)."
},
{
"code": null,
"e": 1475,
"s": 1250,
"text": "Golden Plan : It will be somewhat costly than the Starter Plan. In this plan, subscriber will be given 2-day stay in a non-AC room, travelling in a AC bus and the trip will be from Delhi to Haridwar, Rishikesh and Mussoorie."
},
{
"code": null,
"e": 1687,
"s": 1475,
"text": "Diamond Plan: This is the most costly plan, in which subscriber will be provided 3-day plan with AC bus and AC room stay, along with the trip to Haridwar, Rishikesh and Mussoorie and also trip to the Water Park."
},
{
"code": null,
"e": 2107,
"s": 1687,
"text": "Our main objective is to design and write code for the back-end in a very efficient way(following the DRY Principle).There are multiple methods of implementing this in Django but the most suitable and efficient method is Grouping the Users and defining the permissions of these groups. User of that particular group will automatically inherit the permission of that particular group. Let’s define the User model first :"
},
{
"code": null,
"e": 2209,
"s": 2107,
"text": "Create a Django application users. In models.py file, under ‘users’ app directory, write this code. "
},
{
"code": null,
"e": 2217,
"s": 2209,
"text": "Python3"
},
{
"code": "# importing necessary django classesfrom django.contrib.auth.models import AbstractUserfrom django.utils import timezonefrom django.db import models # User classclass User(AbstractUser): # Define the extra fields # related to User here first_name = models.CharField(_('First Name of User'), blank = True, max_length = 20) last_name = models.CharField(_('Last Name of User'), blank = True, max_length = 20) # More User fields according to need # define the custom permissions # related to User. class Meta: permissions = ( (\"can_go_in_non_ac_bus\", \"To provide non-AC Bus facility\"), (\"can_go_in_ac_bus\", \"To provide AC-Bus facility\"), (\"can_stay_ac-room\", \"To provide staying at AC room\"), (\"can_stay_ac-room\", \"To provide staying at Non-AC room\"), (\"can_go_dehradoon\", \"Trip to Dehradoon\"), (\"can_go_mussoorie\", \"Trip to Mussoorie\"), (\"can_go_haridwaar\", \"Trip to Haridwaar\"), (\"can_go_rishikesh\", \"Trip to Rishikesh\"), # Add other custom permissions according to need.",
"e": 3425,
"s": 2217,
"text": null
},
{
"code": null,
"e": 3510,
"s": 3425,
"text": " After migrating the models written above, we have two option for making the group."
},
{
"code": null,
"e": 3814,
"s": 3510,
"text": "Django Admin Panel : In Admin Panel you will see Group in bold letter, Click on that and make 3-different group named level0, level1, level3 . Also, define the custom permissions according to the need.By Programmatically creating a group with permissions: Open python shell using python manage.py shell."
},
{
"code": null,
"e": 4016,
"s": 3814,
"text": "Django Admin Panel : In Admin Panel you will see Group in bold letter, Click on that and make 3-different group named level0, level1, level3 . Also, define the custom permissions according to the need."
},
{
"code": null,
"e": 4119,
"s": 4016,
"text": "By Programmatically creating a group with permissions: Open python shell using python manage.py shell."
},
{
"code": null,
"e": 4127,
"s": 4119,
"text": "Python3"
},
{
"code": "# importing group class from djangofrom django.contrib.auth.models import Group, Permissionfrom django.contrib.contenttypes.models import ContentType # import User modelfrom users.models import User new_group, created = Group.objects.get_or_create(name ='new_group') # Code to add permission to groupct = ContentType.objects.get_for_model(User) # If I want to add 'Can go Haridwar' permission to level0 ?permission = Permission.objects.create(codename ='can_go_haridwar', name ='Can go to Haridwar', content_type = ct)new_group.permissions.add(permission)",
"e": 4769,
"s": 4127,
"text": null
},
{
"code": null,
"e": 4923,
"s": 4769,
"text": " We will set different set of permissions in the same way to all the three groups. Until then, we have made groups and linked it with custom permissions."
},
{
"code": null,
"e": 5264,
"s": 4923,
"text": "Now, check that a particular user is accessing the appropriate functionality like, put a limit that level0 does not access the functionalities of level1 users or level2 user and so on. To do this, check the permission on every view function made.To be very careful here, for the function based view we will simply use the custom decorator. "
},
{
"code": null,
"e": 5280,
"s": 5264,
"text": "For example : "
},
{
"code": null,
"e": 5287,
"s": 5280,
"text": "Python"
},
{
"code": "@group_required('level0')def my_view(request): ...",
"e": 5341,
"s": 5287,
"text": null
},
{
"code": null,
"e": 5529,
"s": 5341,
"text": "For more details, refer this.Things get a bit complex when we talk about class-based views, we can not simply just add a decorator function, but we have to make a permission-mixing class."
},
{
"code": null,
"e": 5545,
"s": 5529,
"text": "For example : "
},
{
"code": null,
"e": 5552,
"s": 5545,
"text": "Python"
},
{
"code": "class GroupRequiredMixin(object): ............... ....Class Definition..... class DemoView(GroupRequiredMixin, View): group_required = [u'admin', u'manager'] # View code...",
"e": 5737,
"s": 5552,
"text": null
},
{
"code": null,
"e": 5767,
"s": 5737,
"text": "For more details, refer this."
},
{
"code": null,
"e": 6135,
"s": 5767,
"text": "References : 1. https://docs.djangoproject.com/en/1.11/topics/class-based-views/mixins/ 2. http://bradmontgomery.blogspot.in/2009/04/restricting-access-by-group-in-django.html 3. https://simpleisbetterthancomplex.com/2015/12/07/working-with-django-view-decorators.html 4. https://micropyramid.com/blog/custom-decorators-to-check-user-roles-and-permissions-in-django/ "
},
{
"code": null,
"e": 6150,
"s": 6135,
"text": "adnanirshad158"
},
{
"code": null,
"e": 6163,
"s": 6150,
"text": "simmytarika5"
},
{
"code": null,
"e": 6181,
"s": 6163,
"text": "akankshaarora2122"
},
{
"code": null,
"e": 6195,
"s": 6181,
"text": "Python Django"
},
{
"code": null,
"e": 6202,
"s": 6195,
"text": "Python"
},
{
"code": null,
"e": 6219,
"s": 6202,
"text": "Web Technologies"
},
{
"code": null,
"e": 6317,
"s": 6219,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6335,
"s": 6317,
"text": "Python Dictionary"
},
{
"code": null,
"e": 6377,
"s": 6335,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 6399,
"s": 6377,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 6434,
"s": 6399,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 6460,
"s": 6434,
"text": "Python String | replace()"
},
{
"code": null,
"e": 6493,
"s": 6460,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 6555,
"s": 6493,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 6616,
"s": 6555,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 6666,
"s": 6616,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
GATE | GATE CS 2020 | Question 65 - GeeksforGeeks
|
26 May, 2021
Consider a TCP connection between a client and a server with the following specifications; the round trip time is 6 ms, the size of the receiver advertised window is 50 KB, slow-start threshold at the client is 32 KB, and the maximum segment size is 2 KB. The connection is established at time t=0. Assume that there are no timeouts and errors during transmission.
Then the size of the congestion window (in KB) at time t+60 ms after all acknowledgements are processed is _________ .
Note – This question was Numerical Type.(A) 33(B) 44(C) 55(D) 50Answer: (B)Explanation: Given,
Threshold = 32 Kb,
MSS = 2KB,
RTT = 6ms
Here, t + 60 is nothing but at the 10 RTT (60/6 = 10).
Now,
1st transmission: 2 KB
2nd transmission: 4 KB
3rd transmission: 8 KB
4th transmission: 16 KB
5th transmission: 32 KB (Threshold reached)
6th transmission: 34 KB
7th transmission: 36 KB
8th transmission: 38 KB
9th transmission: 40 KB
10th transmission: 42 KB
Now, after receiving acknowledgements of 10th transmission RTT = 10*6 = 60 ms.
And, after receiving acknowledgements of 10th transmission RTT (means at 11th transmission),The congestion window size will be 44 KB.
Option (B) is correct.Quiz of this Question
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | GATE-CS-2000 | Question 41
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
|
[
{
"code": null,
"e": 25829,
"s": 25801,
"text": "\n26 May, 2021"
},
{
"code": null,
"e": 26194,
"s": 25829,
"text": "Consider a TCP connection between a client and a server with the following specifications; the round trip time is 6 ms, the size of the receiver advertised window is 50 KB, slow-start threshold at the client is 32 KB, and the maximum segment size is 2 KB. The connection is established at time t=0. Assume that there are no timeouts and errors during transmission."
},
{
"code": null,
"e": 26313,
"s": 26194,
"text": "Then the size of the congestion window (in KB) at time t+60 ms after all acknowledgements are processed is _________ ."
},
{
"code": null,
"e": 26408,
"s": 26313,
"text": "Note – This question was Numerical Type.(A) 33(B) 44(C) 55(D) 50Answer: (B)Explanation: Given,"
},
{
"code": null,
"e": 26451,
"s": 26408,
"text": "Threshold = 32 Kb, \nMSS = 2KB, \nRTT = 6ms "
},
{
"code": null,
"e": 26506,
"s": 26451,
"text": "Here, t + 60 is nothing but at the 10 RTT (60/6 = 10)."
},
{
"code": null,
"e": 26511,
"s": 26506,
"text": "Now,"
},
{
"code": null,
"e": 26770,
"s": 26511,
"text": "1st transmission: 2 KB\n2nd transmission: 4 KB\n3rd transmission: 8 KB\n4th transmission: 16 KB\n5th transmission: 32 KB (Threshold reached)\n6th transmission: 34 KB\n7th transmission: 36 KB\n8th transmission: 38 KB\n9th transmission: 40 KB\n10th transmission: 42 KB "
},
{
"code": null,
"e": 26849,
"s": 26770,
"text": "Now, after receiving acknowledgements of 10th transmission RTT = 10*6 = 60 ms."
},
{
"code": null,
"e": 26983,
"s": 26849,
"text": "And, after receiving acknowledgements of 10th transmission RTT (means at 11th transmission),The congestion window size will be 44 KB."
},
{
"code": null,
"e": 27027,
"s": 26983,
"text": "Option (B) is correct.Quiz of this Question"
},
{
"code": null,
"e": 27032,
"s": 27027,
"text": "GATE"
},
{
"code": null,
"e": 27130,
"s": 27032,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27164,
"s": 27130,
"text": "GATE | Gate IT 2007 | Question 25"
},
{
"code": null,
"e": 27198,
"s": 27164,
"text": "GATE | GATE-CS-2001 | Question 39"
},
{
"code": null,
"e": 27231,
"s": 27198,
"text": "GATE | GATE-CS-2005 | Question 6"
},
{
"code": null,
"e": 27267,
"s": 27231,
"text": "GATE | GATE MOCK 2017 | Question 21"
},
{
"code": null,
"e": 27301,
"s": 27267,
"text": "GATE | GATE-CS-2006 | Question 47"
},
{
"code": null,
"e": 27337,
"s": 27301,
"text": "GATE | GATE MOCK 2017 | Question 24"
},
{
"code": null,
"e": 27371,
"s": 27337,
"text": "GATE | GATE-CS-2000 | Question 41"
},
{
"code": null,
"e": 27405,
"s": 27371,
"text": "GATE | Gate IT 2008 | Question 43"
},
{
"code": null,
"e": 27439,
"s": 27405,
"text": "GATE | GATE-CS-2009 | Question 38"
}
] |
Matplotlib.axes.Axes.set_ybound() in Python - GeeksforGeeks
|
19 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.set_ybound() function in axes module of matplotlib library is used to set the lower and upper numerical bounds of the y-axis.
Syntax: Axes.set_ybound(self, lower=None, upper=None)
Parameters: This method accepts the following parameters.
lower, upper: These parameters are the lower and upper bounds. If None, the respective axis bound is not modified.
Returns:This method returns the following
lower, upper :This returns the new lower and upper y-axis bounds.
Note: This function can be used in place of set_ylim in various conditions.
Below examples illustrate the matplotlib.axes.Axes.set_ybound() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib functionfrom matplotlib.widgets import Cursorimport numpy as npimport matplotlib.pyplot as plt np.random.seed(19680801) fig, ax = plt.subplots() x, y = 4*(np.random.rand(2, 50) - .5)ax.plot(x, y, 'g')ax.set_ybound(-4, 4) ax.set_title('matplotlib.axes.Axes.set_ybound() Example\n', fontsize = 14, fontweight ='bold')plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np fig1, ax1 = plt.subplots()fig2, ax2 = plt.subplots()ax1.set(xlim =(-0.5, 1.5), ylim =(-0.5, 1.5), autoscale_on = False) ax2.set(xlim =(0.5, 0.75), ylim =(0.5, 0.75), autoscale_on = False) x, y, s, c = np.random.rand(4, 200)s *= 200 ax1.scatter(x, y, s, c)ax2.scatter(x, y, s, c) def GFG(event): if event.button != 1: return x, y = event.xdata, event.ydata ax2.set_xbound(x - 0.1, x + 0.1) ax2.set_ybound(y - 0.2, y + 0.2) fig2.canvas.draw() fig1.canvas.mpl_connect('button_press_event', GFG) ax1.set_title('matplotlib.axes.Axes.set_ybound()\ Example\n Original Window ', fontsize = 14, fontweight ='bold') ax2.set_title('Zoomed window ', 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.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
|
[
{
"code": null,
"e": 25647,
"s": 25619,
"text": "\n19 Apr, 2020"
},
{
"code": null,
"e": 25947,
"s": 25647,
"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": 26082,
"s": 25947,
"text": "The Axes.set_ybound() function in axes module of matplotlib library is used to set the lower and upper numerical bounds of the y-axis."
},
{
"code": null,
"e": 26136,
"s": 26082,
"text": "Syntax: Axes.set_ybound(self, lower=None, upper=None)"
},
{
"code": null,
"e": 26194,
"s": 26136,
"text": "Parameters: This method accepts the following parameters."
},
{
"code": null,
"e": 26309,
"s": 26194,
"text": "lower, upper: These parameters are the lower and upper bounds. If None, the respective axis bound is not modified."
},
{
"code": null,
"e": 26351,
"s": 26309,
"text": "Returns:This method returns the following"
},
{
"code": null,
"e": 26417,
"s": 26351,
"text": "lower, upper :This returns the new lower and upper y-axis bounds."
},
{
"code": null,
"e": 26493,
"s": 26417,
"text": "Note: This function can be used in place of set_ylim in various conditions."
},
{
"code": null,
"e": 26586,
"s": 26493,
"text": "Below examples illustrate the matplotlib.axes.Axes.set_ybound() function in matplotlib.axes:"
},
{
"code": null,
"e": 26597,
"s": 26586,
"text": "Example 1:"
},
{
"code": "# Implementation of matplotlib functionfrom matplotlib.widgets import Cursorimport numpy as npimport matplotlib.pyplot as plt np.random.seed(19680801) fig, ax = plt.subplots() x, y = 4*(np.random.rand(2, 50) - .5)ax.plot(x, y, 'g')ax.set_ybound(-4, 4) ax.set_title('matplotlib.axes.Axes.set_ybound() Example\\n', fontsize = 14, fontweight ='bold')plt.show()",
"e": 26981,
"s": 26597,
"text": null
},
{
"code": null,
"e": 26989,
"s": 26981,
"text": "Output:"
},
{
"code": null,
"e": 27000,
"s": 26989,
"text": "Example 2:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np fig1, ax1 = plt.subplots()fig2, ax2 = plt.subplots()ax1.set(xlim =(-0.5, 1.5), ylim =(-0.5, 1.5), autoscale_on = False) ax2.set(xlim =(0.5, 0.75), ylim =(0.5, 0.75), autoscale_on = False) x, y, s, c = np.random.rand(4, 200)s *= 200 ax1.scatter(x, y, s, c)ax2.scatter(x, y, s, c) def GFG(event): if event.button != 1: return x, y = event.xdata, event.ydata ax2.set_xbound(x - 0.1, x + 0.1) ax2.set_ybound(y - 0.2, y + 0.2) fig2.canvas.draw() fig1.canvas.mpl_connect('button_press_event', GFG) ax1.set_title('matplotlib.axes.Axes.set_ybound()\\ Example\\n Original Window ', fontsize = 14, fontweight ='bold') ax2.set_title('Zoomed window ', fontsize = 14, fontweight ='bold')plt.show()",
"e": 27854,
"s": 27000,
"text": null
},
{
"code": null,
"e": 27862,
"s": 27854,
"text": "Output:"
},
{
"code": null,
"e": 27880,
"s": 27862,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 27887,
"s": 27880,
"text": "Python"
},
{
"code": null,
"e": 27985,
"s": 27887,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28017,
"s": 27985,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28059,
"s": 28017,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28101,
"s": 28059,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28157,
"s": 28101,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28184,
"s": 28157,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28215,
"s": 28184,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28244,
"s": 28215,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 28266,
"s": 28244,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28302,
"s": 28266,
"text": "Python | Pandas dataframe.groupby()"
}
] |
LINQ | Query Syntax - GeeksforGeeks
|
21 May, 2019
LINQ query syntax is consist of a set of query keywords defined into the .NET Framework version 3.5 or Higher. This allows the programmer or developers to write the commands similar to SQL style in the code(C# or VB.NET) without using quotes. It is also know as the Query Expression Syntax. In LINQ, you can write the query to IEnumerable collection or IQueryable data sources using the following ways:
Query SyntaxMethod Syntax
Query Syntax
Method Syntax
Here, we will discuss the Query Syntax only.
The LINQ query syntax begins with from keyword and ends with the Select or GroupBy keyword. After from keyword you can use different types of Standard Query Operations like filtering, grouping, etc. according to your need. In LINQ, 50 different types of Standard Query Operators are available.
Creating first LINQ Query using Query Syntax in C#
Step 1: First add System.Linq namespace in your code.using System.Linq;
using System.Linq;
Step 2: Next, create data source on which you want to perform operations. For example:List my_list = new List(){
"This is my Dog",
"Name of my Dog is Robin",
"This is my Cat",
"Name of the cat is Mewmew"
};
List my_list = new List(){
"This is my Dog",
"Name of my Dog is Robin",
"This is my Cat",
"Name of the cat is Mewmew"
};
Step 3: Now create the query using the query keywords like select, from, etc. For example:
var res = from l in my_list
where l.Contains("my")
select l;
Here res is the query variable which stores the result of the query expression. The from clause is used to specify the data source, i.e, my_list, where clause applies the filter, i.e, l.Contains(“my”) and select clause provides the type of the returned items. And l is the range variable.
var res = from l in my_list
where l.Contains("my")
select l;
Here res is the query variable which stores the result of the query expression. The from clause is used to specify the data source, i.e, my_list, where clause applies the filter, i.e, l.Contains(“my”) and select clause provides the type of the returned items. And l is the range variable.
Step 4: Last step is to execute the query by using a foreach loop. For example:foreach(var q in res)
{
Console.WriteLine(q);
}
foreach(var q in res)
{
Console.WriteLine(q);
}
Example:
// Create first Query in C#using System;using System.Linq;using System.Collections.Generic; class GFG { // Main Method static public void Main() { // Data source List<string> my_list = new List<string>() { "This is my Dog", "Name of my Dog is Robin", "This is my Cat", "Name of the cat is Mewmew" }; // Creating LINQ Query var res = from l in my_list where l.Contains("my") select l; // Executing LINQ Query foreach(var q in res) { Console.WriteLine(q); } }}
Output:
This is my Dog
Name of my Dog is Robin
This is my Cat
CSharp LINQ
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Delegates
C# | Method Overriding
C# | Abstract Classes
Difference between Ref and Out keywords in C#
C# | Class and Object
Extension Method in C#
C# | Constructors
C# | String.IndexOf( ) Method | Set - 1
C# | Replace() Method
|
[
{
"code": null,
"e": 25663,
"s": 25635,
"text": "\n21 May, 2019"
},
{
"code": null,
"e": 26066,
"s": 25663,
"text": "LINQ query syntax is consist of a set of query keywords defined into the .NET Framework version 3.5 or Higher. This allows the programmer or developers to write the commands similar to SQL style in the code(C# or VB.NET) without using quotes. It is also know as the Query Expression Syntax. In LINQ, you can write the query to IEnumerable collection or IQueryable data sources using the following ways:"
},
{
"code": null,
"e": 26092,
"s": 26066,
"text": "Query SyntaxMethod Syntax"
},
{
"code": null,
"e": 26105,
"s": 26092,
"text": "Query Syntax"
},
{
"code": null,
"e": 26119,
"s": 26105,
"text": "Method Syntax"
},
{
"code": null,
"e": 26164,
"s": 26119,
"text": "Here, we will discuss the Query Syntax only."
},
{
"code": null,
"e": 26458,
"s": 26164,
"text": "The LINQ query syntax begins with from keyword and ends with the Select or GroupBy keyword. After from keyword you can use different types of Standard Query Operations like filtering, grouping, etc. according to your need. In LINQ, 50 different types of Standard Query Operators are available."
},
{
"code": null,
"e": 26509,
"s": 26458,
"text": "Creating first LINQ Query using Query Syntax in C#"
},
{
"code": null,
"e": 26581,
"s": 26509,
"text": "Step 1: First add System.Linq namespace in your code.using System.Linq;"
},
{
"code": null,
"e": 26600,
"s": 26581,
"text": "using System.Linq;"
},
{
"code": null,
"e": 26844,
"s": 26600,
"text": "Step 2: Next, create data source on which you want to perform operations. For example:List my_list = new List(){\n \"This is my Dog\",\n \"Name of my Dog is Robin\",\n \"This is my Cat\",\n \"Name of the cat is Mewmew\"\n };\n"
},
{
"code": null,
"e": 27002,
"s": 26844,
"text": "List my_list = new List(){\n \"This is my Dog\",\n \"Name of my Dog is Robin\",\n \"This is my Cat\",\n \"Name of the cat is Mewmew\"\n };\n"
},
{
"code": null,
"e": 27475,
"s": 27002,
"text": "Step 3: Now create the query using the query keywords like select, from, etc. For example: \nvar res = from l in my_list\n where l.Contains(\"my\")\n select l;\nHere res is the query variable which stores the result of the query expression. The from clause is used to specify the data source, i.e, my_list, where clause applies the filter, i.e, l.Contains(“my”) and select clause provides the type of the returned items. And l is the range variable."
},
{
"code": null,
"e": 27570,
"s": 27475,
"text": " \nvar res = from l in my_list\n where l.Contains(\"my\")\n select l;\n"
},
{
"code": null,
"e": 27859,
"s": 27570,
"text": "Here res is the query variable which stores the result of the query expression. The from clause is used to specify the data source, i.e, my_list, where clause applies the filter, i.e, l.Contains(“my”) and select clause provides the type of the returned items. And l is the range variable."
},
{
"code": null,
"e": 27996,
"s": 27859,
"text": "Step 4: Last step is to execute the query by using a foreach loop. For example:foreach(var q in res)\n{\n Console.WriteLine(q);\n}\n"
},
{
"code": null,
"e": 28054,
"s": 27996,
"text": "foreach(var q in res)\n{\n Console.WriteLine(q);\n}\n"
},
{
"code": null,
"e": 28063,
"s": 28054,
"text": "Example:"
},
{
"code": "// Create first Query in C#using System;using System.Linq;using System.Collections.Generic; class GFG { // Main Method static public void Main() { // Data source List<string> my_list = new List<string>() { \"This is my Dog\", \"Name of my Dog is Robin\", \"This is my Cat\", \"Name of the cat is Mewmew\" }; // Creating LINQ Query var res = from l in my_list where l.Contains(\"my\") select l; // Executing LINQ Query foreach(var q in res) { Console.WriteLine(q); } }}",
"e": 28719,
"s": 28063,
"text": null
},
{
"code": null,
"e": 28727,
"s": 28719,
"text": "Output:"
},
{
"code": null,
"e": 28782,
"s": 28727,
"text": "This is my Dog\nName of my Dog is Robin\nThis is my Cat\n"
},
{
"code": null,
"e": 28794,
"s": 28782,
"text": "CSharp LINQ"
},
{
"code": null,
"e": 28797,
"s": 28794,
"text": "C#"
},
{
"code": null,
"e": 28895,
"s": 28797,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28923,
"s": 28895,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 28938,
"s": 28923,
"text": "C# | Delegates"
},
{
"code": null,
"e": 28961,
"s": 28938,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 28983,
"s": 28961,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 29029,
"s": 28983,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 29051,
"s": 29029,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 29074,
"s": 29051,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 29092,
"s": 29074,
"text": "C# | Constructors"
},
{
"code": null,
"e": 29132,
"s": 29092,
"text": "C# | String.IndexOf( ) Method | Set - 1"
}
] |
Elements of an array that are not divisible by any element of another array - GeeksforGeeks
|
30 Apr, 2021
Given two arrays A[] and B[], write an efficient code to determine if every element of B[] is divisible by at least 1 element of A[]. Display those elements of B[], which are not divisible by any of the elements in A[]. Examples :
Input : A[] = {100, 200, 400, 100, 600}
B[] = {45, 90, 48, 1000, 3000}
Output : 45, 90, 48
The output elements are those that are
not divisible by any element of A[].
Method I (Naive Implementation)
Iterate through every single element of B[].
Check if it is divisible by at least 1 element of A[] or not. If not divisible by any, then print it.
C++
Java
Python3
C#
PHP
Javascript
// C++ code for naive implementation#include<iostream>using namespace std; // Function for checking the condition// with 2 loopsvoid printNonDivisible(int A[], int B[], int n, int m){ for (int i = 0; i < m; i++) { int j = 0; for (j = 0; j < n; j++) if( B[i] % A[j] == 0 ) break; // If none of the elements in A[] // divided B[i] if (j == n) cout << B[i] << endl; }} // Driver codeint main(){ int A[] = {100, 200, 400, 100}; int n = sizeof(A)/sizeof(A[0]); int B[] = {190, 200, 87, 600, 800}; int m = sizeof(B)/sizeof(B[0]); printNonDivisible(A, B, n, m); return 0;}
// Java code for naive implementationimport java.io.*; public class GFG { // Function for checking the condition// with 2 loopsstatic void printNonDivisible(int []A, int []B, int n, int m){ for (int i = 0; i < m; i++) { int j = 0; for (j = 0; j < n; j++) if( B[i] % A[j] == 0 ) break; // If none of the elements // in A[] divided B[i] if (j == n) System.out.println(B[i]); }} // Driver code static public void main (String[] args) { int []A = {100, 200, 400, 100}; int n = A.length; int []B = {190, 200, 87, 600, 800}; int m = B.length; printNonDivisible(A, B, n, m); }} // This code is contributed by vt_m .
# Python3 code for naive implementationimport math as mt # Function for checking the condition# with 2 loopsdef printNonDivisible(A, B, n, m): for i in range(m): j = 0 for j in range(n): if(B[i] % A[j] == 0): break # If none of the elements in A[] # divided B[i] if (j == n - 1): print(B[i]) # Driver codeA = [100, 200, 400, 100]n = len(A)B = [190, 200, 87, 600, 800]m = len(B)printNonDivisible(A, B, n, m) # This code is contributed by## mohit kumar 29
// C# code for naive implementationusing System; public class GFG { // Function for checking the// condition with 2 loopsstatic void printNonDivisible(int []A, int []B, int n, int m){ for (int i = 0; i < m; i++) { int j = 0; for (j = 0; j < n; j++) if( B[i] % A[j] == 0 ) break; // If none of the elements // in A[] divided B[i] if (j == n) Console.WriteLine(B[i]); }} // Driver code static public void Main () { int []A = {100, 200, 400, 100}; int n = A.Length; int []B = {190, 200, 87, 600, 800}; int m = B.Length; printNonDivisible(A, B, n, m); }} // This code is contributed by vt_m .
<?php// PHP code for naive implementation // Function for checking// the condition with 2 loopsfunction printNonDivisible($A, $B, $n, $m){ for ($i = 0; $i < $m; $i++) { $j = 0; for ($j = 0; $j < $n; $j++) if( $B[$i] % $A[$j] == 0 ) break; // If none of the elements // in A[] divided B[i] if ($j == $n) echo $B[$i], "\n"; }} // Driver code$A= array (100, 200, 400, 100);$n = sizeof($A);$B = array (190, 200, 87, 600, 800);$m = sizeof($B); printNonDivisible($A, $B, $n, $m); // This code is contributed by ajit?>
<script> // Javascript code for naive implementation // Function for checking the // condition with 2 loops function printNonDivisible(A, B, n, m) { for (let i = 0; i < m; i++) { let j = 0; for (j = 0; j < n; j++) if( B[i] % A[j] == 0 ) break; // If none of the elements // in A[] divided B[i] if (j == n) document.write(B[i] + "</br>"); } } let A = [100, 200, 400, 100]; let n = A.length; let B = [190, 200, 87, 600, 800]; let m = B.length; printNonDivisible(A, B, n, m); </script>
Output :
190
87
Time Complexity :- O(n*m) Auxiliary Space :- O(1) Method 2 (Efficient when elements in are small)
Maintain an array mark[] to mark the multiples of the numbers in A[].
Mark all the multiples of all the elements in A[], till a max of B[].
Check if mark[B[i]] value for every element n in B[] is not 0 and print if not marked.
C++
Java
Python3
C#
PHP
Javascript
// CPP code for improved implementation#include<bits/stdc++.h>using namespace std; // Function for printing all elements of B[]// that are not divisible by any element of A[]void printNonDivisible(int A[], int B[], int n, int m){ // Find maximum element in B[] int maxB = 0; for (int i = 0; i < m; i++) if (B[i] > maxB) maxB = B[i]; // Initialize all multiples as marked int mark[maxB]; memset(mark, 0, sizeof(mark)); // Marking the multiples of all the // elements of the array. for (int i = 0; i < n; i++) for (int x = A[i]; x <= maxB; x += A[i]) mark[x]++; // Print not marked elements for (int i = 0; i < m; i++) if (! mark[B[i]]) cout << B[i] << endl;} // Driver functionint main(){ int A[] = {100, 200, 400, 100}; int n = sizeof(A)/sizeof(A[0]); int B[] = {190, 200, 87, 600, 800}; int m = sizeof(B)/sizeof(B[0]); printNonDivisible(A, B, n, m); return 0;}
// Java code for improved implementationimport java.io.*; class GFG{ // Function for printing all elements of B[]// that are not divisible by any element of A[]static void printNonDivisible(int []A, int []B, int n,int m){ // Find maximum element in B[] int maxB = 0; for (int i = 0; i < m; i++) if (B[i] > maxB) maxB = B[i]; // Initialize all multiples as marked int [] mark = new int[maxB + 1]; for(int i = 0; i < maxB; i++) mark[i]=0; // Marking the multiples of all the // elements of the array. for (int i = 0; i < n; i++) for (int x = A[i]; x <= maxB; x += A[i]) mark[x]++; // Print not marked elements for (int i = 0; i < m; i++) if (mark[B[i]] == 0) System.out.println(B[i]);} // Driver codestatic public void main(String[] args){ int []A= {100, 200, 400, 100}; int n = A.length; int []B= {190, 200, 87, 600, 800}; int m = B.length; printNonDivisible(A, B, n, m);}} // This code is contributed by Mohit Kumar.
# Python 3 code for improved implementation # Function for printing all elements of B[]# that are not divisible by any element of A[]def printNonDivisible(A, B, n, m): # Find maximum element in B[] maxB = 0 for i in range(0, m, 1): if (B[i] > maxB): maxB = B[i] # Initialize all multiples as marked mark = [0 for i in range(maxB)] # Marking the multiples of all # the elements of the array. for i in range(0, n, 1): for x in range(A[i], maxB, A[i]): mark[x] += 1 # Print not marked elements for i in range(0, m - 1, 1): if (mark[B[i]] == 0): print(B[i]) # Driver Codeif __name__ == '__main__': A = [100, 200, 400, 100] n = len(A) B = [190, 200, 87, 600, 800] m = len(B) printNonDivisible(A, B, n, m) # This code is contributed by# Shashank_Sharma
// C# code for improved implementationusing System; class GFG{ // Function for printing all elements of []B// that are not divisible by any element of []Astatic void printNonDivisible(int []A, int []B, int n, int m){ // Find maximum element in []B int maxB = 0; for (int i = 0; i < m; i++) if (B[i] > maxB) maxB = B[i]; // Initialize all multiples as marked int [] mark = new int[maxB + 1]; for(int i = 0; i < maxB; i++) mark[i] = 0; // Marking the multiples of all the // elements of the array. for (int i = 0; i < n; i++) for (int x = A[i]; x <= maxB; x += A[i]) mark[x]++; // Print not marked elements for (int i = 0; i < m; i++) if (mark[B[i]] == 0) Console.WriteLine(B[i]);} // Driver codestatic public void Main(String[] args){ int []A= {100, 200, 400, 100}; int n = A.Length; int []B= {190, 200, 87, 600, 800}; int m = B.Length; printNonDivisible(A, B, n, m);}} // This code is contributed by Rajput-Ji
<?php// PHP code for improved implementation // Function for printing all elements of B[]// that are not divisible by any element of A[]function printNonDivisible($A, $B, $n, $m){ // Find maximum element in B[] $maxB = 0; for ($i = 0; $i < $m; $i++) { if ($B[$i] > $maxB) $maxB = $B[$i]; } // Initialize all multiples as marked $mark = array(); for ($i = 0; $i < $maxB; $i++) { $mark[] = "0"; } // Marking the multiples of all // the elements of the array. for ($i = 0; $i < $n; $i++) { for ($x = $A[$i]; $x < $maxB; $x += $A[$i]) { $mark[$x] += 1; } } // Print not marked elements for ($i = 0; $i < $m - 1; $i++) { if ($mark[$B[$i]] == 0) echo "$B[$i]\n"; }} // Driver Code$A = array(100, 200, 400, 100);$n = count($A);$B = array(190, 200, 87, 600, 800);$m = count($B);printNonDivisible($A, $B, $n, $m); // This code is contributed by// Srathore?>
<script> // Javascript code for improved implementation // Function for printing all elements of []B // that are not divisible by any element of []A function printNonDivisible(A, B, n, m) { // Find maximum element in []B let maxB = 0; for (let i = 0; i < m; i++) if (B[i] > maxB) maxB = B[i]; // Initialize all multiples as marked let mark = new Array(maxB + 1); for(let i = 0; i < maxB; i++) mark[i] = 0; // Marking the multiples of all the // elements of the array. for (let i = 0; i < n; i++) for (let x = A[i]; x <= maxB; x += A[i]) mark[x]++; // Print not marked elements for (let i = 0; i < m; i++) if (mark[B[i]] == 0) document.write(B[i] + "</br>"); } let A= [100, 200, 400, 100]; let n = A.length; let B= [190, 200, 87, 600, 800]; let m = B.length; printNonDivisible(A, B, n, m); </script>
Output :
190
87
Time Complexity :- O(m + n*(max(B[]/min(A[]))) Auxiliary Space :- O(n) + O(m) + O(max(B[])) This article is contributed by Sakshi Tiwari .If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
vt_m
jit_t
Shashank_Sharma
mohit kumar 29
sapnasingh4991
nidhi_biet
Rajput-Ji
decode2207
divyesh072019
divisibility
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count pairs with given sum
Chocolate Distribution Problem
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
Find duplicates in O(n) time and O(1) extra space | Set 1
Find subarray with given sum | Set 1 (Nonnegative Numbers)
Remove duplicates from sorted array
Move all negative numbers to beginning and positive to end with constant extra space
Merge Overlapping Intervals
|
[
{
"code": null,
"e": 26065,
"s": 26037,
"text": "\n30 Apr, 2021"
},
{
"code": null,
"e": 26298,
"s": 26065,
"text": "Given two arrays A[] and B[], write an efficient code to determine if every element of B[] is divisible by at least 1 element of A[]. Display those elements of B[], which are not divisible by any of the elements in A[]. Examples : "
},
{
"code": null,
"e": 26475,
"s": 26298,
"text": "Input : A[] = {100, 200, 400, 100, 600}\n B[] = {45, 90, 48, 1000, 3000}\nOutput : 45, 90, 48 \nThe output elements are those that are \nnot divisible by any element of A[]."
},
{
"code": null,
"e": 26511,
"s": 26477,
"text": "Method I (Naive Implementation) "
},
{
"code": null,
"e": 26556,
"s": 26511,
"text": "Iterate through every single element of B[]."
},
{
"code": null,
"e": 26658,
"s": 26556,
"text": "Check if it is divisible by at least 1 element of A[] or not. If not divisible by any, then print it."
},
{
"code": null,
"e": 26664,
"s": 26660,
"text": "C++"
},
{
"code": null,
"e": 26669,
"s": 26664,
"text": "Java"
},
{
"code": null,
"e": 26677,
"s": 26669,
"text": "Python3"
},
{
"code": null,
"e": 26680,
"s": 26677,
"text": "C#"
},
{
"code": null,
"e": 26684,
"s": 26680,
"text": "PHP"
},
{
"code": null,
"e": 26695,
"s": 26684,
"text": "Javascript"
},
{
"code": "// C++ code for naive implementation#include<iostream>using namespace std; // Function for checking the condition// with 2 loopsvoid printNonDivisible(int A[], int B[], int n, int m){ for (int i = 0; i < m; i++) { int j = 0; for (j = 0; j < n; j++) if( B[i] % A[j] == 0 ) break; // If none of the elements in A[] // divided B[i] if (j == n) cout << B[i] << endl; }} // Driver codeint main(){ int A[] = {100, 200, 400, 100}; int n = sizeof(A)/sizeof(A[0]); int B[] = {190, 200, 87, 600, 800}; int m = sizeof(B)/sizeof(B[0]); printNonDivisible(A, B, n, m); return 0;}",
"e": 27386,
"s": 26695,
"text": null
},
{
"code": "// Java code for naive implementationimport java.io.*; public class GFG { // Function for checking the condition// with 2 loopsstatic void printNonDivisible(int []A, int []B, int n, int m){ for (int i = 0; i < m; i++) { int j = 0; for (j = 0; j < n; j++) if( B[i] % A[j] == 0 ) break; // If none of the elements // in A[] divided B[i] if (j == n) System.out.println(B[i]); }} // Driver code static public void main (String[] args) { int []A = {100, 200, 400, 100}; int n = A.length; int []B = {190, 200, 87, 600, 800}; int m = B.length; printNonDivisible(A, B, n, m); }} // This code is contributed by vt_m .",
"e": 28181,
"s": 27386,
"text": null
},
{
"code": "# Python3 code for naive implementationimport math as mt # Function for checking the condition# with 2 loopsdef printNonDivisible(A, B, n, m): for i in range(m): j = 0 for j in range(n): if(B[i] % A[j] == 0): break # If none of the elements in A[] # divided B[i] if (j == n - 1): print(B[i]) # Driver codeA = [100, 200, 400, 100]n = len(A)B = [190, 200, 87, 600, 800]m = len(B)printNonDivisible(A, B, n, m) # This code is contributed by## mohit kumar 29",
"e": 28712,
"s": 28181,
"text": null
},
{
"code": "// C# code for naive implementationusing System; public class GFG { // Function for checking the// condition with 2 loopsstatic void printNonDivisible(int []A, int []B, int n, int m){ for (int i = 0; i < m; i++) { int j = 0; for (j = 0; j < n; j++) if( B[i] % A[j] == 0 ) break; // If none of the elements // in A[] divided B[i] if (j == n) Console.WriteLine(B[i]); }} // Driver code static public void Main () { int []A = {100, 200, 400, 100}; int n = A.Length; int []B = {190, 200, 87, 600, 800}; int m = B.Length; printNonDivisible(A, B, n, m); }} // This code is contributed by vt_m .",
"e": 29469,
"s": 28712,
"text": null
},
{
"code": "<?php// PHP code for naive implementation // Function for checking// the condition with 2 loopsfunction printNonDivisible($A, $B, $n, $m){ for ($i = 0; $i < $m; $i++) { $j = 0; for ($j = 0; $j < $n; $j++) if( $B[$i] % $A[$j] == 0 ) break; // If none of the elements // in A[] divided B[i] if ($j == $n) echo $B[$i], \"\\n\"; }} // Driver code$A= array (100, 200, 400, 100);$n = sizeof($A);$B = array (190, 200, 87, 600, 800);$m = sizeof($B); printNonDivisible($A, $B, $n, $m); // This code is contributed by ajit?>",
"e": 30089,
"s": 29469,
"text": null
},
{
"code": "<script> // Javascript code for naive implementation // Function for checking the // condition with 2 loops function printNonDivisible(A, B, n, m) { for (let i = 0; i < m; i++) { let j = 0; for (j = 0; j < n; j++) if( B[i] % A[j] == 0 ) break; // If none of the elements // in A[] divided B[i] if (j == n) document.write(B[i] + \"</br>\"); } } let A = [100, 200, 400, 100]; let n = A.length; let B = [190, 200, 87, 600, 800]; let m = B.length; printNonDivisible(A, B, n, m); </script>",
"e": 30743,
"s": 30089,
"text": null
},
{
"code": null,
"e": 30753,
"s": 30743,
"text": "Output : "
},
{
"code": null,
"e": 30760,
"s": 30753,
"text": "190\n87"
},
{
"code": null,
"e": 30860,
"s": 30760,
"text": "Time Complexity :- O(n*m) Auxiliary Space :- O(1) Method 2 (Efficient when elements in are small) "
},
{
"code": null,
"e": 30930,
"s": 30860,
"text": "Maintain an array mark[] to mark the multiples of the numbers in A[]."
},
{
"code": null,
"e": 31000,
"s": 30930,
"text": "Mark all the multiples of all the elements in A[], till a max of B[]."
},
{
"code": null,
"e": 31087,
"s": 31000,
"text": "Check if mark[B[i]] value for every element n in B[] is not 0 and print if not marked."
},
{
"code": null,
"e": 31093,
"s": 31089,
"text": "C++"
},
{
"code": null,
"e": 31098,
"s": 31093,
"text": "Java"
},
{
"code": null,
"e": 31106,
"s": 31098,
"text": "Python3"
},
{
"code": null,
"e": 31109,
"s": 31106,
"text": "C#"
},
{
"code": null,
"e": 31113,
"s": 31109,
"text": "PHP"
},
{
"code": null,
"e": 31124,
"s": 31113,
"text": "Javascript"
},
{
"code": "// CPP code for improved implementation#include<bits/stdc++.h>using namespace std; // Function for printing all elements of B[]// that are not divisible by any element of A[]void printNonDivisible(int A[], int B[], int n, int m){ // Find maximum element in B[] int maxB = 0; for (int i = 0; i < m; i++) if (B[i] > maxB) maxB = B[i]; // Initialize all multiples as marked int mark[maxB]; memset(mark, 0, sizeof(mark)); // Marking the multiples of all the // elements of the array. for (int i = 0; i < n; i++) for (int x = A[i]; x <= maxB; x += A[i]) mark[x]++; // Print not marked elements for (int i = 0; i < m; i++) if (! mark[B[i]]) cout << B[i] << endl;} // Driver functionint main(){ int A[] = {100, 200, 400, 100}; int n = sizeof(A)/sizeof(A[0]); int B[] = {190, 200, 87, 600, 800}; int m = sizeof(B)/sizeof(B[0]); printNonDivisible(A, B, n, m); return 0;}",
"e": 32134,
"s": 31124,
"text": null
},
{
"code": "// Java code for improved implementationimport java.io.*; class GFG{ // Function for printing all elements of B[]// that are not divisible by any element of A[]static void printNonDivisible(int []A, int []B, int n,int m){ // Find maximum element in B[] int maxB = 0; for (int i = 0; i < m; i++) if (B[i] > maxB) maxB = B[i]; // Initialize all multiples as marked int [] mark = new int[maxB + 1]; for(int i = 0; i < maxB; i++) mark[i]=0; // Marking the multiples of all the // elements of the array. for (int i = 0; i < n; i++) for (int x = A[i]; x <= maxB; x += A[i]) mark[x]++; // Print not marked elements for (int i = 0; i < m; i++) if (mark[B[i]] == 0) System.out.println(B[i]);} // Driver codestatic public void main(String[] args){ int []A= {100, 200, 400, 100}; int n = A.length; int []B= {190, 200, 87, 600, 800}; int m = B.length; printNonDivisible(A, B, n, m);}} // This code is contributed by Mohit Kumar.",
"e": 33203,
"s": 32134,
"text": null
},
{
"code": "# Python 3 code for improved implementation # Function for printing all elements of B[]# that are not divisible by any element of A[]def printNonDivisible(A, B, n, m): # Find maximum element in B[] maxB = 0 for i in range(0, m, 1): if (B[i] > maxB): maxB = B[i] # Initialize all multiples as marked mark = [0 for i in range(maxB)] # Marking the multiples of all # the elements of the array. for i in range(0, n, 1): for x in range(A[i], maxB, A[i]): mark[x] += 1 # Print not marked elements for i in range(0, m - 1, 1): if (mark[B[i]] == 0): print(B[i]) # Driver Codeif __name__ == '__main__': A = [100, 200, 400, 100] n = len(A) B = [190, 200, 87, 600, 800] m = len(B) printNonDivisible(A, B, n, m) # This code is contributed by# Shashank_Sharma",
"e": 34057,
"s": 33203,
"text": null
},
{
"code": "// C# code for improved implementationusing System; class GFG{ // Function for printing all elements of []B// that are not divisible by any element of []Astatic void printNonDivisible(int []A, int []B, int n, int m){ // Find maximum element in []B int maxB = 0; for (int i = 0; i < m; i++) if (B[i] > maxB) maxB = B[i]; // Initialize all multiples as marked int [] mark = new int[maxB + 1]; for(int i = 0; i < maxB; i++) mark[i] = 0; // Marking the multiples of all the // elements of the array. for (int i = 0; i < n; i++) for (int x = A[i]; x <= maxB; x += A[i]) mark[x]++; // Print not marked elements for (int i = 0; i < m; i++) if (mark[B[i]] == 0) Console.WriteLine(B[i]);} // Driver codestatic public void Main(String[] args){ int []A= {100, 200, 400, 100}; int n = A.Length; int []B= {190, 200, 87, 600, 800}; int m = B.Length; printNonDivisible(A, B, n, m);}} // This code is contributed by Rajput-Ji",
"e": 35118,
"s": 34057,
"text": null
},
{
"code": "<?php// PHP code for improved implementation // Function for printing all elements of B[]// that are not divisible by any element of A[]function printNonDivisible($A, $B, $n, $m){ // Find maximum element in B[] $maxB = 0; for ($i = 0; $i < $m; $i++) { if ($B[$i] > $maxB) $maxB = $B[$i]; } // Initialize all multiples as marked $mark = array(); for ($i = 0; $i < $maxB; $i++) { $mark[] = \"0\"; } // Marking the multiples of all // the elements of the array. for ($i = 0; $i < $n; $i++) { for ($x = $A[$i]; $x < $maxB; $x += $A[$i]) { $mark[$x] += 1; } } // Print not marked elements for ($i = 0; $i < $m - 1; $i++) { if ($mark[$B[$i]] == 0) echo \"$B[$i]\\n\"; }} // Driver Code$A = array(100, 200, 400, 100);$n = count($A);$B = array(190, 200, 87, 600, 800);$m = count($B);printNonDivisible($A, $B, $n, $m); // This code is contributed by// Srathore?>",
"e": 36140,
"s": 35118,
"text": null
},
{
"code": "<script> // Javascript code for improved implementation // Function for printing all elements of []B // that are not divisible by any element of []A function printNonDivisible(A, B, n, m) { // Find maximum element in []B let maxB = 0; for (let i = 0; i < m; i++) if (B[i] > maxB) maxB = B[i]; // Initialize all multiples as marked let mark = new Array(maxB + 1); for(let i = 0; i < maxB; i++) mark[i] = 0; // Marking the multiples of all the // elements of the array. for (let i = 0; i < n; i++) for (let x = A[i]; x <= maxB; x += A[i]) mark[x]++; // Print not marked elements for (let i = 0; i < m; i++) if (mark[B[i]] == 0) document.write(B[i] + \"</br>\"); } let A= [100, 200, 400, 100]; let n = A.length; let B= [190, 200, 87, 600, 800]; let m = B.length; printNonDivisible(A, B, n, m); </script>",
"e": 37156,
"s": 36140,
"text": null
},
{
"code": null,
"e": 37166,
"s": 37156,
"text": "Output : "
},
{
"code": null,
"e": 37173,
"s": 37166,
"text": "190\n87"
},
{
"code": null,
"e": 37686,
"s": 37173,
"text": "Time Complexity :- O(m + n*(max(B[]/min(A[]))) Auxiliary Space :- O(n) + O(m) + O(max(B[])) This article is contributed by Sakshi Tiwari .If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 37691,
"s": 37686,
"text": "vt_m"
},
{
"code": null,
"e": 37697,
"s": 37691,
"text": "jit_t"
},
{
"code": null,
"e": 37713,
"s": 37697,
"text": "Shashank_Sharma"
},
{
"code": null,
"e": 37728,
"s": 37713,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 37743,
"s": 37728,
"text": "sapnasingh4991"
},
{
"code": null,
"e": 37754,
"s": 37743,
"text": "nidhi_biet"
},
{
"code": null,
"e": 37764,
"s": 37754,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 37775,
"s": 37764,
"text": "decode2207"
},
{
"code": null,
"e": 37789,
"s": 37775,
"text": "divyesh072019"
},
{
"code": null,
"e": 37802,
"s": 37789,
"text": "divisibility"
},
{
"code": null,
"e": 37809,
"s": 37802,
"text": "Arrays"
},
{
"code": null,
"e": 37816,
"s": 37809,
"text": "Arrays"
},
{
"code": null,
"e": 37914,
"s": 37816,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37941,
"s": 37914,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 37972,
"s": 37941,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 37997,
"s": 37972,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 38035,
"s": 37997,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 38056,
"s": 38035,
"text": "Next Greater Element"
},
{
"code": null,
"e": 38114,
"s": 38056,
"text": "Find duplicates in O(n) time and O(1) extra space | Set 1"
},
{
"code": null,
"e": 38173,
"s": 38114,
"text": "Find subarray with given sum | Set 1 (Nonnegative Numbers)"
},
{
"code": null,
"e": 38209,
"s": 38173,
"text": "Remove duplicates from sorted array"
},
{
"code": null,
"e": 38294,
"s": 38209,
"text": "Move all negative numbers to beginning and positive to end with constant extra space"
}
] |
Find pair with greatest product in array - GeeksforGeeks
|
28 Aug, 2021
Given an array of n elements, the task is to find the greatest number such that it is product of two elements of given array. If no such element exists, print -1. Elements are within the range of 1 to 10^5.Examples :
Input : arr[] = {10, 3, 5, 30, 35}
Output: 30
Explanation: 30 is the product of 10 and 3.
Input : arr[] = {2, 5, 7, 8}
Output: -1
Explanation: Since, no such element exists.
Input : arr[] = {10, 2, 4, 30, 35}
Output: -1
Input : arr[] = {10, 2, 2, 4, 30, 35}
Output: 4
Input : arr[] = {17, 2, 1, 35, 30}
Output : 35
A naive approach is to pick an element and then check for each pair product if equal to that number and update the max if the number is maximum,repeat until whole array gets traversed takes O(n^3) time.
C++
Java
Python 3
C#
PHP
Javascript
// C++ program to find a pair with product// in given array.#include<bits/stdc++.h>using namespace std; // Function to find greatest number that usint findGreatest( int arr[] , int n){ int result = -1; for (int i = 0; i < n ; i++) for (int j = 0; j < n-1; j++) for (int k = j+1 ; k < n ; k++) if (arr[j] * arr[k] == arr[i]) result = max(result, arr[i]); return result;} // Driver codeint main(){ // Your C++ Code int arr[] = {30, 10, 9, 3, 35}; int n = sizeof(arr)/sizeof(arr[0]); cout << findGreatest(arr, n); return 0;}
// Java program to find a pair// with product in given array.import java.io.*; class GFG{ static int findGreatest( int []arr , int n){ int result = -1; for (int i = 0; i < n ; i++) for (int j = 0; j < n-1; j++) for (int k = j+1 ; k < n ; k++) if (arr[j] * arr[k] == arr[i]) result = Math.max(result, arr[i]); return result;} // Driver code static public void main (String[] args) { int []arr = {30, 10, 9, 3, 35}; int n = arr.length; System.out.println(findGreatest(arr, n)); }} //This code is contributed by vt_m.
# Python 3 program to find a pair# with product in given array. # Function to find greatest numberdef findGreatest( arr , n): result = -1 for i in range(n): for j in range(n - 1): for k in range(j + 1, n): if (arr[j] * arr[k] == arr[i]): result = max(result, arr[i]) return result # Driver codeif __name__ == "__main__": arr = [ 30, 10, 9, 3, 35] n = len(arr) print(findGreatest(arr, n)) # This code is contributed by ita_c
// C# program to find a pair with product// in given array.using System; class GFG{ static int findGreatest( int []arr , int n){ int result = -1; for (int i = 0; i < n ; i++) for (int j = 0; j < n-1; j++) for (int k = j+1 ; k < n ; k++) if (arr[j] * arr[k] == arr[i]) result = Math.Max(result, arr[i]); return result;} // Driver code static public void Main () { int []arr = {30, 10, 9, 3, 35}; int n = arr.Length; Console.WriteLine(findGreatest(arr, n)); }} //This code is contributed by vt_m.
<?php// PHP program to find a pair// with product in given array. // Function to find// greatest numberfunction findGreatest($arr , $n){ $result = -1; for ($i = 0; $i < $n ; $i++) for ($j = 0; $j < $n - 1; $j++) for ($k = $j + 1 ; $k < $n ; $k++) if ($arr[$j] * $arr[$k] == $arr[$i]) $result = max($result, $arr[$i]); return $result;} // Driver code$arr = array(30, 10, 9, 3, 35);$n = count($arr); echo findGreatest($arr, $n); // This code is contributed by anuj_67.?>
<script> // Javascript program to find a pair// with product in given array. function findGreatest(arr , n){ let result = -1; for (let i = 0; i < n ; i++) for (let j = 0; j < n-1; j++) for (let k = j+1 ; k < n ; k++) if (arr[j] * arr[k] == arr[i]) result = Math.max(result, arr[i]); return result;} // Driver code let arr = [30, 10, 9, 3, 35]; let n = arr.length; document.write(findGreatest(arr, n)); // This code is contributed by splevel62. </script>
Output :
30
An efficient method follows below implementation:-
Create an empty hash table and store all array elements in it.Sort the array in ascending order.Pick elements one by one from end of the array.And check if there exists a pair whose product is equal to that number. In this efficiency can be achieved. The idea is to reach till sqrt of that number. If we don’t get the pair till sqrt that means no such pair exists. We use hash table to make sure that we can find other element of pair in O(1) time.Repeat steps 2 to 3 until we get the element or whole array gets traversed.
Create an empty hash table and store all array elements in it.
Sort the array in ascending order.
Pick elements one by one from end of the array.
And check if there exists a pair whose product is equal to that number. In this efficiency can be achieved. The idea is to reach till sqrt of that number. If we don’t get the pair till sqrt that means no such pair exists. We use hash table to make sure that we can find other element of pair in O(1) time.
Repeat steps 2 to 3 until we get the element or whole array gets traversed.
Below is the implementation.
C++
Java
Python
C#
Javascript
// C++ program to find the largest product number#include <bits/stdc++.h>using namespace std; // Function to find greatest numberint findGreatest(int arr[], int n){ // Store occurrences of all elements in hash // array unordered_map<int, int> m; for (int i = 0; i < n; i++) m[arr[i]]++; // Sort the array and traverse all elements from // end. sort(arr, arr + n); for (int i = n - 1; i > 1; i--) { // For every element, check if there is another // element which divides it. for (int j = 0; j < i && arr[j] <= sqrt(arr[i]); j++) { if (arr[i] % arr[j] == 0) { int result = arr[i] / arr[j]; // Check if the result value exists in array // or not if yes the return arr[i] if (result != arr[j] && result!=arr[i] && m[result] > 0) return arr[i]; // To handle the case like arr[i] = 4 and // arr[j] = 2 else if (result == arr[j] && m[result] > 1) return arr[i]; } } } return -1;} // Drivers codeint main(){ int arr[] = { 17, 2, 1, 15, 30 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findGreatest(arr, n); return 0;}
// Java program to find the largest product numberimport java.util.*; class GFG{ // Function to find greatest number static int findGreatest(int arr[], int n) { // Store occurrences of all // elements in hash array Map<Integer, Integer> m = new HashMap<>(); for (int i = 0; i < n; i++) { if (m.containsKey(arr[i])) { m.put(arr[i], m.get(arr[i]) + 1); } else { m.put(arr[i], m.get(arr[i])); } } // m[arr[i]]++; // Sort the array and traverse // all elements from end. Arrays.sort(arr); for (int i = n - 1; i > 1; i--) { // For every element, check if there is another // element which divides it. for (int j = 0; j < i && arr[j] <= Math.sqrt(arr[i]); j++) { if (arr[i] % arr[j] == 0) { int result = arr[i] / arr[j]; // Check if the result value exists in array // or not if yes the return arr[i] if (result != arr[j] && m.get(result) == null|| m.get(result) > 0) { return arr[i]; } // To handle the case like arr[i] = 4 // and arr[j] = 2 else if (result == arr[j] && m.get(result) > 1) { return arr[i]; } } } } return -1; } // Driver code public static void main(String[] args) { int arr[] = {17, 2, 1, 15, 30}; int n = arr.length; System.out.println(findGreatest(arr, n)); }} // This code is contributed by PrinciRaj1992
# Python3 program to find the largest product numberfrom math import sqrt # Function to find greatest numberdef findGreatest(arr, n): # Store occurrences of all elements in hash # array m = dict() for i in arr: m[i] = m.get(i, 0) + 1 # Sort the array and traverse all elements from # end. arr=sorted(arr) for i in range(n - 1, 0, -1): # For every element, check if there is another # element which divides it. j = 0 while(j < i and arr[j] <= sqrt(arr[i])): if (arr[i] % arr[j] == 0): result = arr[i]//arr[j] # Check if the result value exists in array # or not if yes the return arr[i] if (result != arr[j] and (result in m.keys() )and m[result] > 0): return arr[i] # To handle the case like arr[i] = 4 and # arr[j] = 2 elif (result == arr[j] and (result in m.keys()) and m[result] > 1): return arr[i] j += 1 return -1 # Drivers codearr= [17, 2, 1, 15, 30]n = len(arr)print(findGreatest(arr, n)) # This code is contributed by mohit kumar
// C# program to find the largest product numberusing System;using System.Collections.Generic; class GFG{ // Function to find greatest number static int findGreatest(int []arr, int n) { // Store occurrences of all // elements in hash array Dictionary<int,int> m = new Dictionary<int,int> (); for (int i = 0; i < n; i++) { if (m.ContainsKey(arr[i])) { var a = m[arr[i]] + 1; // m.Remove(arr[i]); m.Add(arr[i], a); } else { m.Add(arr[i], arr[i]); } } // m[arr[i]]++; // Sort the array and traverse // all elements from end. Array.Sort(arr); for (int i = n - 1; i > 1; i--) { // For every element, check if there is another // element which divides it. for (int j = 0; j < i && arr[j] <= Math.Sqrt(arr[i]); j++) { if (arr[i] % arr[j] == 0) { int result = arr[i] / arr[j]; // Check if the result value exists in array // or not if yes the return arr[i] if (result != arr[j] && m[result] == null|| m[result] > 0) { return arr[i]; } // To handle the case like arr[i] = 4 // and arr[j] = 2 else if (result == arr[j] && m[result] > 1) { return arr[i]; } } } } return -1; } // Driver code public static void Main(String[] args) { int []arr = {17, 2, 1, 15, 30}; int n = arr.Length; Console.WriteLine(findGreatest(arr, n)); }} // This code contributed by Rajput-Ji
<script> // Javascript program to find the largest product number // Function to find greatest number function findGreatest(arr,n) { // Store occurrences of all // elements in hash array let m = new Map(); for (let i = 0; i < n; i++) { if (m.has(arr[i])) { m.set(arr[i], m[arr[i]] + 1); } else { m.set(arr[i], m.get(arr[i])); } } // m[arr[i]]++; // Sort the array and traverse // all elements from end. arr.sort(function(a,b){return a-b;}); for (let i = n - 1; i > 1; i--) { // For every element, check if there is another // element which divides it. for (let j = 0; j < i && arr[j] <= Math.sqrt(arr[i]); j++) { if (arr[i] % arr[j] == 0) { let result = Math.floor(arr[i] / arr[j]); // Check if the result value exists in array // or not if yes the return arr[i] if (result != arr[j] && m[result] == null|| m[result] > 0) { return arr[i]; } // To handle the case like arr[i] = 4 // and arr[j] = 2 else if (result == arr[j] && m[result] > 1) { return arr[i]; } } } } return -1; } // Driver code let arr=[17, 2, 1, 15, 30]; let n = arr.length; document.write(findGreatest(arr, n)); // This code is contributed by avanitrachhadiya2155 </script>
Output :
30
Time Complexity : O(nlogn)This article is contributed by Sahil Chhabra (akku). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
vt_m
ukasp
princiraj1992
Rajput-Ji
VishalBachchas
mohit kumar 29
splevel62
avanitrachhadiya2155
raiastha18042001
Linkedin
Arrays
Hash
Sorting
Linkedin
Arrays
Hash
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Arrays
Multidimensional Arrays in Java
Linked List vs Array
Python | Using 2D arrays/lists the right way
Search an element in a sorted and rotated array
Internal Working of HashMap in Java
Count pairs with given sum
Hashing | Set 1 (Introduction)
Hashing | Set 3 (Open Addressing)
Hashing | Set 2 (Separate Chaining)
|
[
{
"code": null,
"e": 26643,
"s": 26615,
"text": "\n28 Aug, 2021"
},
{
"code": null,
"e": 26862,
"s": 26643,
"text": "Given an array of n elements, the task is to find the greatest number such that it is product of two elements of given array. If no such element exists, print -1. Elements are within the range of 1 to 10^5.Examples : "
},
{
"code": null,
"e": 27190,
"s": 26862,
"text": "Input : arr[] = {10, 3, 5, 30, 35}\nOutput: 30\nExplanation: 30 is the product of 10 and 3.\n\nInput : arr[] = {2, 5, 7, 8}\nOutput: -1\nExplanation: Since, no such element exists.\n\nInput : arr[] = {10, 2, 4, 30, 35}\nOutput: -1\n\nInput : arr[] = {10, 2, 2, 4, 30, 35}\nOutput: 4\n\nInput : arr[] = {17, 2, 1, 35, 30}\nOutput : 35"
},
{
"code": null,
"e": 27397,
"s": 27192,
"text": "A naive approach is to pick an element and then check for each pair product if equal to that number and update the max if the number is maximum,repeat until whole array gets traversed takes O(n^3) time. "
},
{
"code": null,
"e": 27401,
"s": 27397,
"text": "C++"
},
{
"code": null,
"e": 27406,
"s": 27401,
"text": "Java"
},
{
"code": null,
"e": 27415,
"s": 27406,
"text": "Python 3"
},
{
"code": null,
"e": 27418,
"s": 27415,
"text": "C#"
},
{
"code": null,
"e": 27422,
"s": 27418,
"text": "PHP"
},
{
"code": null,
"e": 27433,
"s": 27422,
"text": "Javascript"
},
{
"code": "// C++ program to find a pair with product// in given array.#include<bits/stdc++.h>using namespace std; // Function to find greatest number that usint findGreatest( int arr[] , int n){ int result = -1; for (int i = 0; i < n ; i++) for (int j = 0; j < n-1; j++) for (int k = j+1 ; k < n ; k++) if (arr[j] * arr[k] == arr[i]) result = max(result, arr[i]); return result;} // Driver codeint main(){ // Your C++ Code int arr[] = {30, 10, 9, 3, 35}; int n = sizeof(arr)/sizeof(arr[0]); cout << findGreatest(arr, n); return 0;}",
"e": 28034,
"s": 27433,
"text": null
},
{
"code": "// Java program to find a pair// with product in given array.import java.io.*; class GFG{ static int findGreatest( int []arr , int n){ int result = -1; for (int i = 0; i < n ; i++) for (int j = 0; j < n-1; j++) for (int k = j+1 ; k < n ; k++) if (arr[j] * arr[k] == arr[i]) result = Math.max(result, arr[i]); return result;} // Driver code static public void main (String[] args) { int []arr = {30, 10, 9, 3, 35}; int n = arr.length; System.out.println(findGreatest(arr, n)); }} //This code is contributed by vt_m.",
"e": 28645,
"s": 28034,
"text": null
},
{
"code": "# Python 3 program to find a pair# with product in given array. # Function to find greatest numberdef findGreatest( arr , n): result = -1 for i in range(n): for j in range(n - 1): for k in range(j + 1, n): if (arr[j] * arr[k] == arr[i]): result = max(result, arr[i]) return result # Driver codeif __name__ == \"__main__\": arr = [ 30, 10, 9, 3, 35] n = len(arr) print(findGreatest(arr, n)) # This code is contributed by ita_c",
"e": 29146,
"s": 28645,
"text": null
},
{
"code": "// C# program to find a pair with product// in given array.using System; class GFG{ static int findGreatest( int []arr , int n){ int result = -1; for (int i = 0; i < n ; i++) for (int j = 0; j < n-1; j++) for (int k = j+1 ; k < n ; k++) if (arr[j] * arr[k] == arr[i]) result = Math.Max(result, arr[i]); return result;} // Driver code static public void Main () { int []arr = {30, 10, 9, 3, 35}; int n = arr.Length; Console.WriteLine(findGreatest(arr, n)); }} //This code is contributed by vt_m.",
"e": 29734,
"s": 29146,
"text": null
},
{
"code": "<?php// PHP program to find a pair// with product in given array. // Function to find// greatest numberfunction findGreatest($arr , $n){ $result = -1; for ($i = 0; $i < $n ; $i++) for ($j = 0; $j < $n - 1; $j++) for ($k = $j + 1 ; $k < $n ; $k++) if ($arr[$j] * $arr[$k] == $arr[$i]) $result = max($result, $arr[$i]); return $result;} // Driver code$arr = array(30, 10, 9, 3, 35);$n = count($arr); echo findGreatest($arr, $n); // This code is contributed by anuj_67.?>",
"e": 30264,
"s": 29734,
"text": null
},
{
"code": "<script> // Javascript program to find a pair// with product in given array. function findGreatest(arr , n){ let result = -1; for (let i = 0; i < n ; i++) for (let j = 0; j < n-1; j++) for (let k = j+1 ; k < n ; k++) if (arr[j] * arr[k] == arr[i]) result = Math.max(result, arr[i]); return result;} // Driver code let arr = [30, 10, 9, 3, 35]; let n = arr.length; document.write(findGreatest(arr, n)); // This code is contributed by splevel62. </script>",
"e": 30818,
"s": 30264,
"text": null
},
{
"code": null,
"e": 30829,
"s": 30818,
"text": "Output : "
},
{
"code": null,
"e": 30832,
"s": 30829,
"text": "30"
},
{
"code": null,
"e": 30885,
"s": 30832,
"text": "An efficient method follows below implementation:- "
},
{
"code": null,
"e": 31409,
"s": 30885,
"text": "Create an empty hash table and store all array elements in it.Sort the array in ascending order.Pick elements one by one from end of the array.And check if there exists a pair whose product is equal to that number. In this efficiency can be achieved. The idea is to reach till sqrt of that number. If we don’t get the pair till sqrt that means no such pair exists. We use hash table to make sure that we can find other element of pair in O(1) time.Repeat steps 2 to 3 until we get the element or whole array gets traversed."
},
{
"code": null,
"e": 31472,
"s": 31409,
"text": "Create an empty hash table and store all array elements in it."
},
{
"code": null,
"e": 31507,
"s": 31472,
"text": "Sort the array in ascending order."
},
{
"code": null,
"e": 31555,
"s": 31507,
"text": "Pick elements one by one from end of the array."
},
{
"code": null,
"e": 31861,
"s": 31555,
"text": "And check if there exists a pair whose product is equal to that number. In this efficiency can be achieved. The idea is to reach till sqrt of that number. If we don’t get the pair till sqrt that means no such pair exists. We use hash table to make sure that we can find other element of pair in O(1) time."
},
{
"code": null,
"e": 31937,
"s": 31861,
"text": "Repeat steps 2 to 3 until we get the element or whole array gets traversed."
},
{
"code": null,
"e": 31967,
"s": 31937,
"text": "Below is the implementation. "
},
{
"code": null,
"e": 31971,
"s": 31967,
"text": "C++"
},
{
"code": null,
"e": 31976,
"s": 31971,
"text": "Java"
},
{
"code": null,
"e": 31983,
"s": 31976,
"text": "Python"
},
{
"code": null,
"e": 31986,
"s": 31983,
"text": "C#"
},
{
"code": null,
"e": 31997,
"s": 31986,
"text": "Javascript"
},
{
"code": "// C++ program to find the largest product number#include <bits/stdc++.h>using namespace std; // Function to find greatest numberint findGreatest(int arr[], int n){ // Store occurrences of all elements in hash // array unordered_map<int, int> m; for (int i = 0; i < n; i++) m[arr[i]]++; // Sort the array and traverse all elements from // end. sort(arr, arr + n); for (int i = n - 1; i > 1; i--) { // For every element, check if there is another // element which divides it. for (int j = 0; j < i && arr[j] <= sqrt(arr[i]); j++) { if (arr[i] % arr[j] == 0) { int result = arr[i] / arr[j]; // Check if the result value exists in array // or not if yes the return arr[i] if (result != arr[j] && result!=arr[i] && m[result] > 0) return arr[i]; // To handle the case like arr[i] = 4 and // arr[j] = 2 else if (result == arr[j] && m[result] > 1) return arr[i]; } } } return -1;} // Drivers codeint main(){ int arr[] = { 17, 2, 1, 15, 30 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findGreatest(arr, n); return 0;}",
"e": 33269,
"s": 31997,
"text": null
},
{
"code": "// Java program to find the largest product numberimport java.util.*; class GFG{ // Function to find greatest number static int findGreatest(int arr[], int n) { // Store occurrences of all // elements in hash array Map<Integer, Integer> m = new HashMap<>(); for (int i = 0; i < n; i++) { if (m.containsKey(arr[i])) { m.put(arr[i], m.get(arr[i]) + 1); } else { m.put(arr[i], m.get(arr[i])); } } // m[arr[i]]++; // Sort the array and traverse // all elements from end. Arrays.sort(arr); for (int i = n - 1; i > 1; i--) { // For every element, check if there is another // element which divides it. for (int j = 0; j < i && arr[j] <= Math.sqrt(arr[i]); j++) { if (arr[i] % arr[j] == 0) { int result = arr[i] / arr[j]; // Check if the result value exists in array // or not if yes the return arr[i] if (result != arr[j] && m.get(result) == null|| m.get(result) > 0) { return arr[i]; } // To handle the case like arr[i] = 4 // and arr[j] = 2 else if (result == arr[j] && m.get(result) > 1) { return arr[i]; } } } } return -1; } // Driver code public static void main(String[] args) { int arr[] = {17, 2, 1, 15, 30}; int n = arr.length; System.out.println(findGreatest(arr, n)); }} // This code is contributed by PrinciRaj1992",
"e": 35148,
"s": 33269,
"text": null
},
{
"code": "# Python3 program to find the largest product numberfrom math import sqrt # Function to find greatest numberdef findGreatest(arr, n): # Store occurrences of all elements in hash # array m = dict() for i in arr: m[i] = m.get(i, 0) + 1 # Sort the array and traverse all elements from # end. arr=sorted(arr) for i in range(n - 1, 0, -1): # For every element, check if there is another # element which divides it. j = 0 while(j < i and arr[j] <= sqrt(arr[i])): if (arr[i] % arr[j] == 0): result = arr[i]//arr[j] # Check if the result value exists in array # or not if yes the return arr[i] if (result != arr[j] and (result in m.keys() )and m[result] > 0): return arr[i] # To handle the case like arr[i] = 4 and # arr[j] = 2 elif (result == arr[j] and (result in m.keys()) and m[result] > 1): return arr[i] j += 1 return -1 # Drivers codearr= [17, 2, 1, 15, 30]n = len(arr)print(findGreatest(arr, n)) # This code is contributed by mohit kumar",
"e": 36333,
"s": 35148,
"text": null
},
{
"code": "// C# program to find the largest product numberusing System;using System.Collections.Generic; class GFG{ // Function to find greatest number static int findGreatest(int []arr, int n) { // Store occurrences of all // elements in hash array Dictionary<int,int> m = new Dictionary<int,int> (); for (int i = 0; i < n; i++) { if (m.ContainsKey(arr[i])) { var a = m[arr[i]] + 1; // m.Remove(arr[i]); m.Add(arr[i], a); } else { m.Add(arr[i], arr[i]); } } // m[arr[i]]++; // Sort the array and traverse // all elements from end. Array.Sort(arr); for (int i = n - 1; i > 1; i--) { // For every element, check if there is another // element which divides it. for (int j = 0; j < i && arr[j] <= Math.Sqrt(arr[i]); j++) { if (arr[i] % arr[j] == 0) { int result = arr[i] / arr[j]; // Check if the result value exists in array // or not if yes the return arr[i] if (result != arr[j] && m[result] == null|| m[result] > 0) { return arr[i]; } // To handle the case like arr[i] = 4 // and arr[j] = 2 else if (result == arr[j] && m[result] > 1) { return arr[i]; } } } } return -1; } // Driver code public static void Main(String[] args) { int []arr = {17, 2, 1, 15, 30}; int n = arr.Length; Console.WriteLine(findGreatest(arr, n)); }} // This code contributed by Rajput-Ji",
"e": 38293,
"s": 36333,
"text": null
},
{
"code": "<script> // Javascript program to find the largest product number // Function to find greatest number function findGreatest(arr,n) { // Store occurrences of all // elements in hash array let m = new Map(); for (let i = 0; i < n; i++) { if (m.has(arr[i])) { m.set(arr[i], m[arr[i]] + 1); } else { m.set(arr[i], m.get(arr[i])); } } // m[arr[i]]++; // Sort the array and traverse // all elements from end. arr.sort(function(a,b){return a-b;}); for (let i = n - 1; i > 1; i--) { // For every element, check if there is another // element which divides it. for (let j = 0; j < i && arr[j] <= Math.sqrt(arr[i]); j++) { if (arr[i] % arr[j] == 0) { let result = Math.floor(arr[i] / arr[j]); // Check if the result value exists in array // or not if yes the return arr[i] if (result != arr[j] && m[result] == null|| m[result] > 0) { return arr[i]; } // To handle the case like arr[i] = 4 // and arr[j] = 2 else if (result == arr[j] && m[result] > 1) { return arr[i]; } } } } return -1; } // Driver code let arr=[17, 2, 1, 15, 30]; let n = arr.length; document.write(findGreatest(arr, n)); // This code is contributed by avanitrachhadiya2155 </script>",
"e": 40110,
"s": 38293,
"text": null
},
{
"code": null,
"e": 40120,
"s": 40110,
"text": "Output : "
},
{
"code": null,
"e": 40123,
"s": 40120,
"text": "30"
},
{
"code": null,
"e": 40578,
"s": 40123,
"text": "Time Complexity : O(nlogn)This article is contributed by Sahil Chhabra (akku). 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": 40583,
"s": 40578,
"text": "vt_m"
},
{
"code": null,
"e": 40589,
"s": 40583,
"text": "ukasp"
},
{
"code": null,
"e": 40603,
"s": 40589,
"text": "princiraj1992"
},
{
"code": null,
"e": 40613,
"s": 40603,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 40628,
"s": 40613,
"text": "VishalBachchas"
},
{
"code": null,
"e": 40643,
"s": 40628,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 40653,
"s": 40643,
"text": "splevel62"
},
{
"code": null,
"e": 40674,
"s": 40653,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 40691,
"s": 40674,
"text": "raiastha18042001"
},
{
"code": null,
"e": 40700,
"s": 40691,
"text": "Linkedin"
},
{
"code": null,
"e": 40707,
"s": 40700,
"text": "Arrays"
},
{
"code": null,
"e": 40712,
"s": 40707,
"text": "Hash"
},
{
"code": null,
"e": 40720,
"s": 40712,
"text": "Sorting"
},
{
"code": null,
"e": 40729,
"s": 40720,
"text": "Linkedin"
},
{
"code": null,
"e": 40736,
"s": 40729,
"text": "Arrays"
},
{
"code": null,
"e": 40741,
"s": 40736,
"text": "Hash"
},
{
"code": null,
"e": 40749,
"s": 40741,
"text": "Sorting"
},
{
"code": null,
"e": 40847,
"s": 40749,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40870,
"s": 40847,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 40902,
"s": 40870,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 40923,
"s": 40902,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 40968,
"s": 40923,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 41016,
"s": 40968,
"text": "Search an element in a sorted and rotated array"
},
{
"code": null,
"e": 41052,
"s": 41016,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 41079,
"s": 41052,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 41110,
"s": 41079,
"text": "Hashing | Set 1 (Introduction)"
},
{
"code": null,
"e": 41144,
"s": 41110,
"text": "Hashing | Set 3 (Open Addressing)"
}
] |
numpy.info() function in Python - GeeksforGeeks
|
25 Oct, 2020
In Numpy we can get all the information about the function, class, or module like what will the parameter and what will be the type of the return value with the help of numpy.info() function. This function returns the help information for a function, class, or module.
Syntax: numpy.info(numpy.info(object=None, maxwidth=76, output=<_io.TextIOWrapper name='<stdout>’ mode=’w’ encoding=’utf-8′>, toplevel=’numpy’))
Parameters:
objectobject or str, optional: This is object or name for input to get information about.
maxwidthint, optional: For Width.
outputfile like object, optional: Object opening mode.
toplevelstr, optional: Start search at this level.
Return: All the information about add function in the numpy.
Example :
Python
import numpy as np print(np.info(np.add))
Output :
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n25 Oct, 2020"
},
{
"code": null,
"e": 25806,
"s": 25537,
"text": "In Numpy we can get all the information about the function, class, or module like what will the parameter and what will be the type of the return value with the help of numpy.info() function. This function returns the help information for a function, class, or module."
},
{
"code": null,
"e": 25951,
"s": 25806,
"text": "Syntax: numpy.info(numpy.info(object=None, maxwidth=76, output=<_io.TextIOWrapper name='<stdout>’ mode=’w’ encoding=’utf-8′>, toplevel=’numpy’))"
},
{
"code": null,
"e": 25963,
"s": 25951,
"text": "Parameters:"
},
{
"code": null,
"e": 26053,
"s": 25963,
"text": "objectobject or str, optional: This is object or name for input to get information about."
},
{
"code": null,
"e": 26087,
"s": 26053,
"text": "maxwidthint, optional: For Width."
},
{
"code": null,
"e": 26142,
"s": 26087,
"text": "outputfile like object, optional: Object opening mode."
},
{
"code": null,
"e": 26193,
"s": 26142,
"text": "toplevelstr, optional: Start search at this level."
},
{
"code": null,
"e": 26254,
"s": 26193,
"text": "Return: All the information about add function in the numpy."
},
{
"code": null,
"e": 26264,
"s": 26254,
"text": "Example :"
},
{
"code": null,
"e": 26271,
"s": 26264,
"text": "Python"
},
{
"code": "import numpy as np print(np.info(np.add))",
"e": 26316,
"s": 26271,
"text": null
},
{
"code": null,
"e": 26325,
"s": 26316,
"text": "Output :"
},
{
"code": null,
"e": 26338,
"s": 26325,
"text": "Python-numpy"
},
{
"code": null,
"e": 26345,
"s": 26338,
"text": "Python"
},
{
"code": null,
"e": 26443,
"s": 26345,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26475,
"s": 26443,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26517,
"s": 26475,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26559,
"s": 26517,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26586,
"s": 26559,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 26642,
"s": 26586,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26664,
"s": 26642,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26703,
"s": 26664,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26734,
"s": 26703,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26763,
"s": 26734,
"text": "Create a directory in Python"
}
] |
Count greater elements on the left side of every array element - GeeksforGeeks
|
31 May, 2021
Given an array arr[] of distinct integers of size N, the task is to print the count of greater elements on the left side of each array element.
Examples :
Input: arr[] = {12, 1, 2, 3, 0, }Output: 0 1 1 1 4Explanation:For index 0, no greater element exists on the left side.For index 1, {12} is greater element on the left side.For index 2, {12} is greater element on the left side.For index 3, {12} is greater element on the left side.For index 4, {12, 1, 2, 3} are greater elements on the left side.Therefore, the output is 0 1 1 1 4.
Input: arr[] = {5, 4, 3, 2, 1}Output: 0 1 2 3 4
Naive Approach: The simplest approach to solve the problem is to traverse the array and for every array element, traverse towards its left and compare every element with the current element. Finally, print the count of greater elements on its left for every array element.
Time Complexity: O(N2) Auxiliary Space: O(1)
Efficient Approach: The problem can be solved using Set containers which are implemented by Self Balancing Binary Search Tree. Follow the steps below solve the problem.
Create an empty Set, St.Traverse the array and insert every element in St one by one.Find the previous greater element of arr[i] using upper_bound function.Find the distance between the previous greater element and the last element of the set using the distance function.Store the distance in the array, countLeftGreater[].Print the array.
Create an empty Set, St.
Traverse the array and insert every element in St one by one.
Find the previous greater element of arr[i] using upper_bound function.
Find the distance between the previous greater element and the last element of the set using the distance function.
Store the distance in the array, countLeftGreater[].
Print the array.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to print the count of greater// elements on left of each array elementvoid display(int countLeftGreater[], int N){ for (int i = 0; i < N; i++) { cout << countLeftGreater[i] << " "; }} // Function to get the count of greater// elements on left of each array elementvoid countGreater(int arr[], int N){ // Store distinct array // elements in sorted order set<int> St; // Stores the count of greater // elements on the left side int countLeftGreater[N]; // Traverse the array for (int i = 0; i < N; i++) { // Insert array elements // into the set St.insert(arr[i]); // Find previous greater element auto it = St.upper_bound(arr[i]); // Find the distance between the // previous greater element of arr[i] // and last element of the set countLeftGreater[i] = distance(it, St.end()); } display(countLeftGreater, N);} // Driver Codeint main(){ int arr[] = { 12, 1, 2, 3, 0, 11, 4 }; int N = sizeof(arr) / sizeof(arr[0]); countGreater(arr, N);}
// Java program to implement// the above approachimport java.util.*;import java.lang.*; class GFG{ // Function to print the count of greater// elements on left of each array elementstatic void display(int countLeftGreater[], int N){ for(int i = 0; i < N; i++) { System.out.print(countLeftGreater[i] + " "); }} // Function to get the count of greater// elements on left of each array elementstatic void countGreater(int arr[], int N){ // Store distinct array // elements in sorted order Set<Integer> St = new TreeSet<>(); // Stores the count of greater // elements on the left side int[] countLeftGreater = new int[N]; // Traverse the array for(int i = 0; i < N; i++) { // Insert array elements // into the set St.add(arr[i]); int it = 0; // Find previous greater element Iterator<Integer> iterator = St.iterator(); while (iterator.hasNext()) { if (arr[i] < iterator.next()) { break; } it++; } // Find the distance between the // previous greater element of arr[i] // and last element of the set countLeftGreater[i] = Math.abs(it - St.size()); } display(countLeftGreater, N); } // Driver codepublic static void main (String[] args){ int arr[] = { 12, 1, 2, 3, 0, 11, 4 }; int N = arr.length; countGreater(arr, N);}} // This code is contributed by offbeat
# Python3 program to implement# the above approach # Function to print the count of greater# elements on left of each array elementdef display(countLeftGreater, N): for i in range(N): print(countLeftGreater[i], end = " ") # Function to get the count of greater# elements on left of each array elementdef countGreater(arr, N): # Store distinct array # elements in sorted order St = set() # Stores the count of greater # elements on the left side countLeftGreater = [0] * (N) # Traverse the array for i in range(N): # Insert array elements # into the set St.add(arr[i]) it = 0 # Find previous greater element for st in St: if (arr[i] < st): break it += 1 # Find the distance between the # previous greater element of arr[i] # and last element of the set countLeftGreater[i] = abs(it - len(St)) display(countLeftGreater, N) # Driver codeif __name__ == '__main__': arr = [ 12, 1, 2, 3, 0, 11, 4 ] N = len(arr) countGreater(arr, N) # This code is contributed by Rajput-Ji
// C# program to implement// the above approachusing System;using System.Collections.Generic; class GFG{ // Function to print the count of greater// elements on left of each array elementstatic void display(int []countLeftGreater, int N){ for(int i = 0; i < N; i++) { Console.Write(countLeftGreater[i] + " "); }} // Function to get the count of greater// elements on left of each array elementstatic void countGreater(int []arr, int N){ // Store distinct array // elements in sorted order List<int> St = new List<int>(); // Stores the count of greater // elements on the left side int[] countLeftGreater = new int[N]; // Traverse the array for(int i = 0; i < N; i++) { // Insert array elements // into the set St.Add(arr[i]); int it = 0; St.Sort(); // Find previous greater element foreach(int itr in St) { if (arr[i] < itr) { break; } it++; } // Find the distance between the // previous greater element of arr[i] // and last element of the set countLeftGreater[i] = Math.Abs(it - St.Count); } display(countLeftGreater, N); } // Driver codepublic static void Main(String[] args){ int []arr = { 12, 1, 2, 3, 0, 11, 4 }; int N = arr.Length; countGreater(arr, N);}} // This code is contributed by gauravrajput1
<script>// Js program to implement// the above approach // Function to print the count of greater// elements on left of each array elementfunction display( countLeftGreater, N){ for (let i = 0; i < N; i++) { document.write(countLeftGreater[i] ," "); }} // Function to get the count of greater// elements on left of each array elementfunction countGreater(arr, N){ // Store distinct array // elements in sorted order let St = new Set(); // Stores the count of greater // elements on the left side let countLeftGreater = []; // Traverse the array for (let i = 0; i < N; i++) { // Insert array elements // into the set St.add(arr[i]); // Find previous greater element let it = 0; // Find previous greater element //let a = Array.from(St); //a.sort(function(a,b){return a-b}); for (let st of St){ if (arr[i] < st) it += 1; } // Find the distance between the // previous greater element of arr[i] // and last element of the set countLeftGreater[i] = Math.abs(it); } display(countLeftGreater, N);} // Driver Codelet arr = [ 12, 1, 2, 3, 0, 11, 4 ];let N = arr.length;countGreater(arr, N);</script>
0 1 1 1 4 1 2
Time Complexity: O(N2) because distance function takes O(N) but the above implementation is very simple and works better than the naive algorithm in the average case. Auxiliary Space: O(N)
Note: Above approach works for unique elements but for duplicate elements just replace Set with Multiset.
offbeat
GauravRajput1
Rajput-Ji
rohan07
nidhi_biet
cpp-set
Arrays
Hash
Mathematical
Searching
Arrays
Searching
Hash
Mathematical
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
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Internal Working of HashMap in Java
Count pairs with given sum
Hashing | Set 1 (Introduction)
Hashing | Set 3 (Open Addressing)
|
[
{
"code": null,
"e": 26189,
"s": 26161,
"text": "\n31 May, 2021"
},
{
"code": null,
"e": 26333,
"s": 26189,
"text": "Given an array arr[] of distinct integers of size N, the task is to print the count of greater elements on the left side of each array element."
},
{
"code": null,
"e": 26344,
"s": 26333,
"text": "Examples :"
},
{
"code": null,
"e": 26725,
"s": 26344,
"text": "Input: arr[] = {12, 1, 2, 3, 0, }Output: 0 1 1 1 4Explanation:For index 0, no greater element exists on the left side.For index 1, {12} is greater element on the left side.For index 2, {12} is greater element on the left side.For index 3, {12} is greater element on the left side.For index 4, {12, 1, 2, 3} are greater elements on the left side.Therefore, the output is 0 1 1 1 4."
},
{
"code": null,
"e": 26773,
"s": 26725,
"text": "Input: arr[] = {5, 4, 3, 2, 1}Output: 0 1 2 3 4"
},
{
"code": null,
"e": 27047,
"s": 26773,
"text": "Naive Approach: The simplest approach to solve the problem is to traverse the array and for every array element, traverse towards its left and compare every element with the current element. Finally, print the count of greater elements on its left for every array element. "
},
{
"code": null,
"e": 27092,
"s": 27047,
"text": "Time Complexity: O(N2) Auxiliary Space: O(1)"
},
{
"code": null,
"e": 27261,
"s": 27092,
"text": "Efficient Approach: The problem can be solved using Set containers which are implemented by Self Balancing Binary Search Tree. Follow the steps below solve the problem."
},
{
"code": null,
"e": 27601,
"s": 27261,
"text": "Create an empty Set, St.Traverse the array and insert every element in St one by one.Find the previous greater element of arr[i] using upper_bound function.Find the distance between the previous greater element and the last element of the set using the distance function.Store the distance in the array, countLeftGreater[].Print the array."
},
{
"code": null,
"e": 27626,
"s": 27601,
"text": "Create an empty Set, St."
},
{
"code": null,
"e": 27688,
"s": 27626,
"text": "Traverse the array and insert every element in St one by one."
},
{
"code": null,
"e": 27760,
"s": 27688,
"text": "Find the previous greater element of arr[i] using upper_bound function."
},
{
"code": null,
"e": 27876,
"s": 27760,
"text": "Find the distance between the previous greater element and the last element of the set using the distance function."
},
{
"code": null,
"e": 27929,
"s": 27876,
"text": "Store the distance in the array, countLeftGreater[]."
},
{
"code": null,
"e": 27946,
"s": 27929,
"text": "Print the array."
},
{
"code": null,
"e": 27997,
"s": 27946,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 28001,
"s": 27997,
"text": "C++"
},
{
"code": null,
"e": 28006,
"s": 28001,
"text": "Java"
},
{
"code": null,
"e": 28014,
"s": 28006,
"text": "Python3"
},
{
"code": null,
"e": 28017,
"s": 28014,
"text": "C#"
},
{
"code": null,
"e": 28028,
"s": 28017,
"text": "Javascript"
},
{
"code": "// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to print the count of greater// elements on left of each array elementvoid display(int countLeftGreater[], int N){ for (int i = 0; i < N; i++) { cout << countLeftGreater[i] << \" \"; }} // Function to get the count of greater// elements on left of each array elementvoid countGreater(int arr[], int N){ // Store distinct array // elements in sorted order set<int> St; // Stores the count of greater // elements on the left side int countLeftGreater[N]; // Traverse the array for (int i = 0; i < N; i++) { // Insert array elements // into the set St.insert(arr[i]); // Find previous greater element auto it = St.upper_bound(arr[i]); // Find the distance between the // previous greater element of arr[i] // and last element of the set countLeftGreater[i] = distance(it, St.end()); } display(countLeftGreater, N);} // Driver Codeint main(){ int arr[] = { 12, 1, 2, 3, 0, 11, 4 }; int N = sizeof(arr) / sizeof(arr[0]); countGreater(arr, N);}",
"e": 29214,
"s": 28028,
"text": null
},
{
"code": "// Java program to implement// the above approachimport java.util.*;import java.lang.*; class GFG{ // Function to print the count of greater// elements on left of each array elementstatic void display(int countLeftGreater[], int N){ for(int i = 0; i < N; i++) { System.out.print(countLeftGreater[i] + \" \"); }} // Function to get the count of greater// elements on left of each array elementstatic void countGreater(int arr[], int N){ // Store distinct array // elements in sorted order Set<Integer> St = new TreeSet<>(); // Stores the count of greater // elements on the left side int[] countLeftGreater = new int[N]; // Traverse the array for(int i = 0; i < N; i++) { // Insert array elements // into the set St.add(arr[i]); int it = 0; // Find previous greater element Iterator<Integer> iterator = St.iterator(); while (iterator.hasNext()) { if (arr[i] < iterator.next()) { break; } it++; } // Find the distance between the // previous greater element of arr[i] // and last element of the set countLeftGreater[i] = Math.abs(it - St.size()); } display(countLeftGreater, N); } // Driver codepublic static void main (String[] args){ int arr[] = { 12, 1, 2, 3, 0, 11, 4 }; int N = arr.length; countGreater(arr, N);}} // This code is contributed by offbeat",
"e": 30716,
"s": 29214,
"text": null
},
{
"code": "# Python3 program to implement# the above approach # Function to print the count of greater# elements on left of each array elementdef display(countLeftGreater, N): for i in range(N): print(countLeftGreater[i], end = \" \") # Function to get the count of greater# elements on left of each array elementdef countGreater(arr, N): # Store distinct array # elements in sorted order St = set() # Stores the count of greater # elements on the left side countLeftGreater = [0] * (N) # Traverse the array for i in range(N): # Insert array elements # into the set St.add(arr[i]) it = 0 # Find previous greater element for st in St: if (arr[i] < st): break it += 1 # Find the distance between the # previous greater element of arr[i] # and last element of the set countLeftGreater[i] = abs(it - len(St)) display(countLeftGreater, N) # Driver codeif __name__ == '__main__': arr = [ 12, 1, 2, 3, 0, 11, 4 ] N = len(arr) countGreater(arr, N) # This code is contributed by Rajput-Ji",
"e": 31871,
"s": 30716,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System;using System.Collections.Generic; class GFG{ // Function to print the count of greater// elements on left of each array elementstatic void display(int []countLeftGreater, int N){ for(int i = 0; i < N; i++) { Console.Write(countLeftGreater[i] + \" \"); }} // Function to get the count of greater// elements on left of each array elementstatic void countGreater(int []arr, int N){ // Store distinct array // elements in sorted order List<int> St = new List<int>(); // Stores the count of greater // elements on the left side int[] countLeftGreater = new int[N]; // Traverse the array for(int i = 0; i < N; i++) { // Insert array elements // into the set St.Add(arr[i]); int it = 0; St.Sort(); // Find previous greater element foreach(int itr in St) { if (arr[i] < itr) { break; } it++; } // Find the distance between the // previous greater element of arr[i] // and last element of the set countLeftGreater[i] = Math.Abs(it - St.Count); } display(countLeftGreater, N); } // Driver codepublic static void Main(String[] args){ int []arr = { 12, 1, 2, 3, 0, 11, 4 }; int N = arr.Length; countGreater(arr, N);}} // This code is contributed by gauravrajput1",
"e": 33340,
"s": 31871,
"text": null
},
{
"code": "<script>// Js program to implement// the above approach // Function to print the count of greater// elements on left of each array elementfunction display( countLeftGreater, N){ for (let i = 0; i < N; i++) { document.write(countLeftGreater[i] ,\" \"); }} // Function to get the count of greater// elements on left of each array elementfunction countGreater(arr, N){ // Store distinct array // elements in sorted order let St = new Set(); // Stores the count of greater // elements on the left side let countLeftGreater = []; // Traverse the array for (let i = 0; i < N; i++) { // Insert array elements // into the set St.add(arr[i]); // Find previous greater element let it = 0; // Find previous greater element //let a = Array.from(St); //a.sort(function(a,b){return a-b}); for (let st of St){ if (arr[i] < st) it += 1; } // Find the distance between the // previous greater element of arr[i] // and last element of the set countLeftGreater[i] = Math.abs(it); } display(countLeftGreater, N);} // Driver Codelet arr = [ 12, 1, 2, 3, 0, 11, 4 ];let N = arr.length;countGreater(arr, N);</script>",
"e": 34620,
"s": 33340,
"text": null
},
{
"code": null,
"e": 34634,
"s": 34620,
"text": "0 1 1 1 4 1 2"
},
{
"code": null,
"e": 34826,
"s": 34636,
"text": "Time Complexity: O(N2) because distance function takes O(N) but the above implementation is very simple and works better than the naive algorithm in the average case. Auxiliary Space: O(N) "
},
{
"code": null,
"e": 34932,
"s": 34826,
"text": "Note: Above approach works for unique elements but for duplicate elements just replace Set with Multiset."
},
{
"code": null,
"e": 34944,
"s": 34936,
"text": "offbeat"
},
{
"code": null,
"e": 34958,
"s": 34944,
"text": "GauravRajput1"
},
{
"code": null,
"e": 34968,
"s": 34958,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 34976,
"s": 34968,
"text": "rohan07"
},
{
"code": null,
"e": 34987,
"s": 34976,
"text": "nidhi_biet"
},
{
"code": null,
"e": 34995,
"s": 34987,
"text": "cpp-set"
},
{
"code": null,
"e": 35002,
"s": 34995,
"text": "Arrays"
},
{
"code": null,
"e": 35007,
"s": 35002,
"text": "Hash"
},
{
"code": null,
"e": 35020,
"s": 35007,
"text": "Mathematical"
},
{
"code": null,
"e": 35030,
"s": 35020,
"text": "Searching"
},
{
"code": null,
"e": 35037,
"s": 35030,
"text": "Arrays"
},
{
"code": null,
"e": 35047,
"s": 35037,
"text": "Searching"
},
{
"code": null,
"e": 35052,
"s": 35047,
"text": "Hash"
},
{
"code": null,
"e": 35065,
"s": 35052,
"text": "Mathematical"
},
{
"code": null,
"e": 35163,
"s": 35065,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35231,
"s": 35163,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 35275,
"s": 35231,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 35298,
"s": 35275,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 35330,
"s": 35298,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 35344,
"s": 35330,
"text": "Linear Search"
},
{
"code": null,
"e": 35429,
"s": 35344,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 35465,
"s": 35429,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 35492,
"s": 35465,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 35523,
"s": 35492,
"text": "Hashing | Set 1 (Introduction)"
}
] |
T-Test Approach in R Programming - GeeksforGeeks
|
16 Dec, 2021
We will be trying to understand the T-Test in R Programming with the help of an example. Suppose a businessman with two sweet shops in a town wants to check if the average number of sweets sold in a day in both the stores is the same or not.
So, the businessman takes the average number of sweets sold to 15 random people in the respective shops. He found out that the first shop sold 30 sweets on average whereas the second shop sold 40. So, from the owner’s point of view, the second shop was doing better business than the former. But the thing to notice is that the data-set is based on a mere number of random people and they cannot represent all the customers. This is where T-testing comes into play it helps us to understand that the difference between the two means is real or simply by chance.
Mathematically, what the t-test does is, take a sample from both sets and establish the problem assuming a null hypothesis that the two means are the same.
Classification of T-tests
One Sample T-test
Two sample T-test
Paired sample T-test
The One-Sample T-Test is used to test the statistical difference between a sample mean and a known or assumed/hypothesized value of the mean in the population.
So, for performing a one-sample t-test in R, we would use the syntax t.test(y, mu = 0) where x is the name of the variable of interest and mu is set equal to the mean specified by the null hypothesis.
For Example:
R
set.seed(0)sweetSold <- c(rnorm(50, mean = 140, sd = 5))t.test(sweetSold, mu = 150) # Ho: mu = 150
Output:
It is used to help us to understand that the difference between the two means is real or simply by chance. The general form of the test is t.test(y1, y2, paired=FALSE). By default, R assumes that the variances of y1 and y2 are unequal, thus defaulting to Welch’s test. To toggle this, we use the flag var.equal=TRUE.
For Example:
R
set.seed(0) shopOne <- rnorm(50, mean = 140, sd = 4.5)shopTwo <- rnorm(50, mean = 150, sd = 4) t.test(shopOne, shopTwo, var.equal = TRUE)
Output:
This is a statistical procedure that is used to determine whether the mean difference between two sets of observations is zero. In a paired sample t-test, each subject is measured two times, resulting in pairs of observations.
The test is run using the syntax t.test(y1, y2, paired=TRUE)
For Example:
R
set.seed(2820) sweetOne <- c(rnorm(100, mean = 14, sd = 0.3))sweetTwo <- c(rnorm(100, mean = 13, sd = 0.2)) t.test(sweetOne, sweetTwo, paired = TRUE)
Output:
kumar_satyam
Picked
R-Mathematics
R-Statistics
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
Time Series Analysis in R
R - if statement
How to filter R dataframe by multiple conditions?
|
[
{
"code": null,
"e": 26487,
"s": 26459,
"text": "\n16 Dec, 2021"
},
{
"code": null,
"e": 26730,
"s": 26487,
"text": "We will be trying to understand the T-Test in R Programming with the help of an example. Suppose a businessman with two sweet shops in a town wants to check if the average number of sweets sold in a day in both the stores is the same or not. "
},
{
"code": null,
"e": 27292,
"s": 26730,
"text": "So, the businessman takes the average number of sweets sold to 15 random people in the respective shops. He found out that the first shop sold 30 sweets on average whereas the second shop sold 40. So, from the owner’s point of view, the second shop was doing better business than the former. But the thing to notice is that the data-set is based on a mere number of random people and they cannot represent all the customers. This is where T-testing comes into play it helps us to understand that the difference between the two means is real or simply by chance."
},
{
"code": null,
"e": 27448,
"s": 27292,
"text": "Mathematically, what the t-test does is, take a sample from both sets and establish the problem assuming a null hypothesis that the two means are the same."
},
{
"code": null,
"e": 27474,
"s": 27448,
"text": "Classification of T-tests"
},
{
"code": null,
"e": 27492,
"s": 27474,
"text": "One Sample T-test"
},
{
"code": null,
"e": 27510,
"s": 27492,
"text": "Two sample T-test"
},
{
"code": null,
"e": 27531,
"s": 27510,
"text": "Paired sample T-test"
},
{
"code": null,
"e": 27692,
"s": 27531,
"text": "The One-Sample T-Test is used to test the statistical difference between a sample mean and a known or assumed/hypothesized value of the mean in the population. "
},
{
"code": null,
"e": 27894,
"s": 27692,
"text": "So, for performing a one-sample t-test in R, we would use the syntax t.test(y, mu = 0) where x is the name of the variable of interest and mu is set equal to the mean specified by the null hypothesis. "
},
{
"code": null,
"e": 27908,
"s": 27894,
"text": "For Example: "
},
{
"code": null,
"e": 27910,
"s": 27908,
"text": "R"
},
{
"code": "set.seed(0)sweetSold <- c(rnorm(50, mean = 140, sd = 5))t.test(sweetSold, mu = 150) # Ho: mu = 150",
"e": 28009,
"s": 27910,
"text": null
},
{
"code": null,
"e": 28017,
"s": 28009,
"text": "Output:"
},
{
"code": null,
"e": 28334,
"s": 28017,
"text": "It is used to help us to understand that the difference between the two means is real or simply by chance. The general form of the test is t.test(y1, y2, paired=FALSE). By default, R assumes that the variances of y1 and y2 are unequal, thus defaulting to Welch’s test. To toggle this, we use the flag var.equal=TRUE."
},
{
"code": null,
"e": 28348,
"s": 28334,
"text": "For Example: "
},
{
"code": null,
"e": 28350,
"s": 28348,
"text": "R"
},
{
"code": "set.seed(0) shopOne <- rnorm(50, mean = 140, sd = 4.5)shopTwo <- rnorm(50, mean = 150, sd = 4) t.test(shopOne, shopTwo, var.equal = TRUE)",
"e": 28488,
"s": 28350,
"text": null
},
{
"code": null,
"e": 28496,
"s": 28488,
"text": "Output:"
},
{
"code": null,
"e": 28723,
"s": 28496,
"text": "This is a statistical procedure that is used to determine whether the mean difference between two sets of observations is zero. In a paired sample t-test, each subject is measured two times, resulting in pairs of observations."
},
{
"code": null,
"e": 28784,
"s": 28723,
"text": "The test is run using the syntax t.test(y1, y2, paired=TRUE)"
},
{
"code": null,
"e": 28797,
"s": 28784,
"text": "For Example:"
},
{
"code": null,
"e": 28799,
"s": 28797,
"text": "R"
},
{
"code": "set.seed(2820) sweetOne <- c(rnorm(100, mean = 14, sd = 0.3))sweetTwo <- c(rnorm(100, mean = 13, sd = 0.2)) t.test(sweetOne, sweetTwo, paired = TRUE)",
"e": 28949,
"s": 28799,
"text": null
},
{
"code": null,
"e": 28957,
"s": 28949,
"text": "Output:"
},
{
"code": null,
"e": 28970,
"s": 28957,
"text": "kumar_satyam"
},
{
"code": null,
"e": 28977,
"s": 28970,
"text": "Picked"
},
{
"code": null,
"e": 28991,
"s": 28977,
"text": "R-Mathematics"
},
{
"code": null,
"e": 29004,
"s": 28991,
"text": "R-Statistics"
},
{
"code": null,
"e": 29015,
"s": 29004,
"text": "R Language"
},
{
"code": null,
"e": 29113,
"s": 29015,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29165,
"s": 29113,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 29200,
"s": 29165,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 29238,
"s": 29200,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 29296,
"s": 29238,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 29339,
"s": 29296,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 29388,
"s": 29339,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 29425,
"s": 29388,
"text": "How to import an Excel File into R ?"
},
{
"code": null,
"e": 29451,
"s": 29425,
"text": "Time Series Analysis in R"
},
{
"code": null,
"e": 29468,
"s": 29451,
"text": "R - if statement"
}
] |
Scala Set size() method with example - GeeksforGeeks
|
18 Oct, 2019
The size() method is utilized to find the number of elements in the set.
Method Definition: def size: Int
Return Type: It returns the number of elements in the set.
Example #1:
// Scala program of size() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a set val s1 = Set(1, 2, 3, 4, 5) // Applying size method val result = s1.size // Display output println(result) } }
5
Example #2:
// Scala program of size() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a set val s1 = Set(1, 0) // Applying size method val result = s1.size // Display output println(result) } }
2
Scala
scala-collection
Scala-Method
Scala-Set
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Class and Object in Scala
Scala Lists
Scala Tutorial – Learn Scala with Step By Step Guide
Operators in Scala
Scala Constructors
Scala | Arrays
How to get the first element of List in Scala
Inheritance in Scala
Scala String replace() method with example
Scala Map get() method with example
|
[
{
"code": null,
"e": 25127,
"s": 25099,
"text": "\n18 Oct, 2019"
},
{
"code": null,
"e": 25200,
"s": 25127,
"text": "The size() method is utilized to find the number of elements in the set."
},
{
"code": null,
"e": 25233,
"s": 25200,
"text": "Method Definition: def size: Int"
},
{
"code": null,
"e": 25292,
"s": 25233,
"text": "Return Type: It returns the number of elements in the set."
},
{
"code": null,
"e": 25304,
"s": 25292,
"text": "Example #1:"
},
{
"code": "// Scala program of size() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a set val s1 = Set(1, 2, 3, 4, 5) // Applying size method val result = s1.size // Display output println(result) } } ",
"e": 25634,
"s": 25304,
"text": null
},
{
"code": null,
"e": 25637,
"s": 25634,
"text": "5\n"
},
{
"code": null,
"e": 25649,
"s": 25637,
"text": "Example #2:"
},
{
"code": "// Scala program of size() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a set val s1 = Set(1, 0) // Applying size method val result = s1.size // Display output println(result) } } ",
"e": 25970,
"s": 25649,
"text": null
},
{
"code": null,
"e": 25973,
"s": 25970,
"text": "2\n"
},
{
"code": null,
"e": 25979,
"s": 25973,
"text": "Scala"
},
{
"code": null,
"e": 25996,
"s": 25979,
"text": "scala-collection"
},
{
"code": null,
"e": 26009,
"s": 25996,
"text": "Scala-Method"
},
{
"code": null,
"e": 26019,
"s": 26009,
"text": "Scala-Set"
},
{
"code": null,
"e": 26025,
"s": 26019,
"text": "Scala"
},
{
"code": null,
"e": 26123,
"s": 26025,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26149,
"s": 26123,
"text": "Class and Object in Scala"
},
{
"code": null,
"e": 26161,
"s": 26149,
"text": "Scala Lists"
},
{
"code": null,
"e": 26214,
"s": 26161,
"text": "Scala Tutorial – Learn Scala with Step By Step Guide"
},
{
"code": null,
"e": 26233,
"s": 26214,
"text": "Operators in Scala"
},
{
"code": null,
"e": 26252,
"s": 26233,
"text": "Scala Constructors"
},
{
"code": null,
"e": 26267,
"s": 26252,
"text": "Scala | Arrays"
},
{
"code": null,
"e": 26313,
"s": 26267,
"text": "How to get the first element of List in Scala"
},
{
"code": null,
"e": 26334,
"s": 26313,
"text": "Inheritance in Scala"
},
{
"code": null,
"e": 26377,
"s": 26334,
"text": "Scala String replace() method with example"
}
] |
Determine whether a universal sink exists in a directed graph - GeeksforGeeks
|
10 May, 2022
Determine whether a universal sink exists in a directed graph. A universal sink is a vertex which has no edge emanating from it, and all other vertices have an edge towards the sink.
Input :
v1 -> v2 (implies vertex 1 is connected to vertex 2)
v3 -> v2
v4 -> v2
v5 -> v2
v6 -> v2
Output :
Sink found at vertex 2
Input :
v1 -> v6
v2 -> v3
v2 -> v4
v4 -> v3
v5 -> v3
Output :
No Sink
We try to eliminate n – 1 non-sink vertices in O(n) time and check the remaining vertex for the sink property. To eliminate vertices, we check whether a particular index (A[i][j]) in the adjacency matrix is a 1 or a 0. If it is a 0, it means that the vertex corresponding to index j cannot be a sink. If the index is a 1, it means the vertex corresponding to i cannot be a sink. We keep increasing i and j in this fashion until either i or j exceeds the number of vertices. Using this method allows us to carry out the universal sink test for only one vertex instead of all n vertices. Suppose we are left with only vertex i. We now check for whether row i has only 0s and whether row j as only 1s except for A[i][i], which will be 0.Illustration :
v1 -> v2
v3 -> v2
v4 -> v2
v5 -> v2
v6 -> v2
We can visualize the adjacency matrix for
the above as follows:
0 1 0 0 0 0
0 0 0 0 0 0
0 1 0 0 0 0
0 1 0 0 0 0
0 1 0 0 0 0
We observe that vertex 2 does not have any emanating edge, and that every other vertex has an edge in vertex 2. At A[0][0] (A[i][j]), we encounter a 0, so we increment j and next look at A[0][1]. Here we encounter a 1. So we have to increment i by 1. A[1][1] is 0, so we keep increasing j. We notice that A[1][2], A[1][3].. etc are all 0, so j will exceed the number of vertices (6 in this example). We now check row i and column i for the sink property. Row i must be completely 0, and column i must be completely 1 except for the index A[i][i]
Adjacency Matrix
Second Example:
v1 -> v6
v2 -> v3
v2 -> v4
v4 -> v3
v5 -> v3
We can visualize the adjacency matrix
for the above as follows:
0 0 0 0 0 1
0 0 1 1 0 0
0 0 0 0 0 0
0 0 1 0 0 0
0 0 1 0 0 0
0 0 0 0 0 0
In this example, we observer that in row 1, every element is 0 except for the last column. So we will increment j until we reach the 1. When we reach 1, we increment i as long as the value of A[i][j] is 0. If i exceeds the number of vertices, it is not possible to have a sink, and in this case, i will exceed the number of vertices.
Adjacency Matrix
Java
Python3
C#
Javascript
// Java program to find whether a universal sink// exists in a directed graphimport java.io.*;import java.util.*; class graph{ int vertices; int[][] adjacency_matrix; // constructor to initialize number of vertices and // size of adjacency matrix public graph(int vertices) { this.vertices = vertices; adjacency_matrix = new int[vertices][vertices]; } public void insert(int source, int destination) { // make adjacency_matrix[i][j] = 1 if there is // an edge from i to j adjacency_matrix[destination-1] = 1; } public boolean issink(int i) { for (int j = 0 ; j < vertices ; j++) { // if any element in the row i is 1, it means // that there is an edge emanating from the // vertex, which means it cannot be a sink if (adjacency_matrix[i][j] == 1) return false; // if any element other than i in the column // i is 0, it means that there is no edge from // that vertex to the vertex we are testing // and hence it cannot be a sink if (adjacency_matrix[j][i] == 0 && j != i) return false; } //if none of the checks fails, return true return true; } // we will eliminate n-1 non sink vertices so that // we have to check for only one vertex instead of // all n vertices public int eliminate() { int i = 0, j = 0; while (i < vertices && j < vertices) { // If the index is 1, increment the row we are // checking by 1 // else increment the column if (adjacency_matrix[i][j] == 1) i = i + 1; else j = j + 1; } // If i exceeds the number of vertices, it // means that there is no valid vertex in // the given vertices that can be a sink if (i > vertices) return -1; else if (!issink(i)) return -1; else return i; }} public class Sink{ public static void main(String[] args)throws IOException { int number_of_vertices = 6; int number_of_edges = 5; graph g = new graph(number_of_vertices); /* //input set 1 g.insert(1, 6); g.insert(2, 6); g.insert(3, 6); g.insert(4, 6); g.insert(5, 6); */ //input set 2 g.insert(1, 6); g.insert(2, 3); g.insert(2, 4); g.insert(4, 3); g.insert(5, 3); int vertex = g.eliminate(); // returns 0 based indexing of vertex. returns // -1 if no sink exits. // returns the vertex number-1 if sink is found if (vertex >= 0) System.out.println("Sink found at vertex " + (vertex + 1)); else System.out.println("No Sink"); }}
# Python3 program to find whether a# universal sink exists in a directed graphclass Graph: # constructor to initialize number of # vertices and size of adjacency matrix def __init__(self, vertices): self.vertices = vertices self.adjacency_matrix = [[0 for i in range(vertices)] for j in range(vertices)] def insert(self, s, destination): # make adjacency_matrix[i][j] = 1 # if there is an edge from i to j self.adjacency_matrix[s - 1][destination - 1] = 1 def issink(self, i): for j in range(self.vertices): # if any element in the row i is 1, it means # that there is an edge emanating from the # vertex, which means it cannot be a sink if self.adjacency_matrix[i][j] == 1: return False # if any element other than i in the column # i is 0, it means that there is no edge from # that vertex to the vertex we are testing # and hence it cannot be a sink if self.adjacency_matrix[j][i] == 0 and j != i: return False # if none of the checks fails, return true return True # we will eliminate n-1 non sink vertices so that # we have to check for only one vertex instead of # all n vertices def eliminate(self): i = 0 j = 0 while i < self.vertices and j < self.vertices: # If the index is 1, increment the row # we are checking by 1 # else increment the column if self.adjacency_matrix[i][j] == 1: i += 1 else: j += 1 # If i exceeds the number of vertices, it # means that there is no valid vertex in # the given vertices that can be a sink if i > self.vertices: return -1 else if self.issink(i) is False: return -1 else: return i # Driver Codeif __name__ == "__main__": number_of_vertices = 6 number_of_edges = 5 g = Graph(number_of_vertices) # input set 1 # g.insert(1, 6) # g.insert(2, 6) # g.insert(3, 6) # g.insert(4, 6) # g.insert(5, 6) # input set 2 g.insert(1, 6) g.insert(2, 3) g.insert(2, 4) g.insert(4, 3) g.insert(5, 3) vertex = g.eliminate() # returns 0 based indexing of vertex. # returns -1 if no sink exits. # returns the vertex number-1 if sink is found if vertex >= 0: print("Sink found at vertex %d" % (vertex + 1)) else: print("No Sink") # This code is contributed by# sanjeev2552
// C# program to find whether a universal sink// exists in a directed graphusing System;using System.Collections.Generic; class graph{ int vertices, itr; int[,] adjacency_matrix; // constructor to initialize number of vertices and // size of adjacency matrix public graph(int vertices) { this.vertices = vertices; adjacency_matrix = new int[vertices, vertices]; } public void insert(int source, int destination) { // make adjacency_matrix[i,j] = 1 if there is // an edge from i to j adjacency_matrix = 1; } public bool issink(int i) { for (int j = 0 ; j < vertices ; j++) { // if any element in the row i is 1, it means // that there is an edge emanating from the // vertex, which means it cannot be a sink if (adjacency_matrix[i, j] == 1) return false; // if any element other than i in the column // i is 0, it means that there is no edge from // that vertex to the vertex we are testing // and hence it cannot be a sink if (adjacency_matrix[j, i] == 0 && j != i) return false; } //if none of the checks fails, return true return true; } // we will eliminate n-1 non sink vertices so that // we have to check for only one vertex instead of // all n vertices public int eliminate() { int i = 0, j = 0; while (i < vertices && j < vertices) { // If the index is 1, increment the row we are // checking by 1 // else increment the column if (adjacency_matrix[i, j] == 1) i = i + 1; else j = j + 1; } // If i exceeds the number of vertices, it // means that there is no valid vertex in // the given vertices that can be a sink if (i > vertices) return -1; else if (!issink(i)) return -1; else return i; }} public class Sink{ public static void Main(String[] args) { int number_of_vertices = 6; graph g = new graph(number_of_vertices); /* //input set 1 g.insert(1, 6); g.insert(2, 6); g.insert(3, 6); g.insert(4, 6); g.insert(5, 6); */ //input set 2 g.insert(1, 6); g.insert(2, 3); g.insert(2, 4); g.insert(4, 3); g.insert(5, 3); int vertex = g.eliminate(); // returns 0 based indexing of vertex. returns // -1 if no sink exits. // returns the vertex number-1 if sink is found if (vertex >= 0) Console.WriteLine("Sink found at vertex " + (vertex + 1)); else Console.WriteLine("No Sink"); }} // This code is contributed by Rajput-Ji
<script> // JavaScript program to find whether a// universal sink exists in a directed graphclass Graph{ // constructor to initialize number of // vertices and size of adjacency matrix constructor(vertices){ this.vertices = vertices this.adjacency_matrix = new Array(this.vertices).fill(0).map(()=>new Array(this.vertices).fill(0)) } insert(s, destination){ // make adjacency_matrix[i][j] = 1 // if there is an edge from i to j this.adjacency_matrix[s - 1][destination - 1] = 1 } issink(i){ for(let j=0;j<this.vertices;j++){ // if any element in the row i is 1, it means // that there is an edge emanating from the // vertex, which means it cannot be a sink if(this.adjacency_matrix[i][j] == 1) return false // if any element other than i in the column // i is 0, it means that there is no edge from // that vertex to the vertex we are testing // and hence it cannot be a sink if(this.adjacency_matrix[j][i] == 0 && j != i) return false } // if none of the checks fails, return true return true } // we will eliminate n-1 non sink vertices so that // we have to check for only one vertex instead of // all n vertices eliminate(){ let i = 0 let j = 0 while(i < this.vertices && j < this.vertices){ // If the index is 1, increment the row // we are checking by 1 // else increment the column if(this.adjacency_matrix[i][j] == 1) i += 1 else j += 1 } // If i exceeds the number of vertices, it // means that there is no valid vertex in // the given vertices that can be a sink if(i > this.vertices) return -1 else if(this.issink(i) == false) return -1 else return i }} // Driver Code let number_of_vertices = 6let number_of_edges = 5let g = new Graph(number_of_vertices) // input set 1// g.insert(1, 6)// g.insert(2, 6)// g.insert(3, 6)// g.insert(4, 6)// g.insert(5, 6) // input set 2g.insert(1, 6)g.insert(2, 3)g.insert(2, 4)g.insert(4, 3)g.insert(5, 3) let vertex = g.eliminate() // returns 0 based indexing of vertex.// returns -1 if no sink exits.// returns the vertex number-1 if sink is foundif(vertex >= 0) document.write(`Sink found at vertex ${(vertex + 1)}`,"</br>")else document.write("No Sink","</br>") // This code is contributed by shinjanpatra </script>
Output:
input set 1:
Sink found at vertex 6
input set 2:
No Sink
This program eliminates non-sink vertices in O(n) complexity and checks for the sink property in O(n) complexity.You may also try The Celebrity Problem, which is an application of this conceptThis article is contributed by Deepak Srivatsav. 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.
sanjeev2552
Rajput-Ji
anas20023
simmytarika5
shinjanpatra
Graph
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Topological Sorting
Detect Cycle in a Directed Graph
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Ford-Fulkerson Algorithm for Maximum Flow Problem
Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)
Detect cycle in an undirected graph
Traveling Salesman Problem (TSP) Implementation
Find the number of islands | Set 1 (Using DFS)
m Coloring Problem | Backtracking-5
Hamiltonian Cycle | Backtracking-6
|
[
{
"code": null,
"e": 26419,
"s": 26391,
"text": "\n10 May, 2022"
},
{
"code": null,
"e": 26604,
"s": 26419,
"text": "Determine whether a universal sink exists in a directed graph. A universal sink is a vertex which has no edge emanating from it, and all other vertices have an edge towards the sink. "
},
{
"code": null,
"e": 26830,
"s": 26604,
"text": "Input : \nv1 -> v2 (implies vertex 1 is connected to vertex 2)\nv3 -> v2\nv4 -> v2\nv5 -> v2\nv6 -> v2 \nOutput :\nSink found at vertex 2\n\nInput : \nv1 -> v6\nv2 -> v3\nv2 -> v4\nv4 -> v3\nv5 -> v3\nOutput :\nNo Sink"
},
{
"code": null,
"e": 27583,
"s": 26832,
"text": "We try to eliminate n – 1 non-sink vertices in O(n) time and check the remaining vertex for the sink property. To eliminate vertices, we check whether a particular index (A[i][j]) in the adjacency matrix is a 1 or a 0. If it is a 0, it means that the vertex corresponding to index j cannot be a sink. If the index is a 1, it means the vertex corresponding to i cannot be a sink. We keep increasing i and j in this fashion until either i or j exceeds the number of vertices. Using this method allows us to carry out the universal sink test for only one vertex instead of all n vertices. Suppose we are left with only vertex i. We now check for whether row i has only 0s and whether row j as only 1s except for A[i][i], which will be 0.Illustration : "
},
{
"code": null,
"e": 27776,
"s": 27583,
"text": "v1 -> v2 \nv3 -> v2\nv4 -> v2\nv5 -> v2\nv6 -> v2 \nWe can visualize the adjacency matrix for \nthe above as follows:\n0 1 0 0 0 0\n0 0 0 0 0 0\n0 1 0 0 0 0\n0 1 0 0 0 0\n0 1 0 0 0 0 "
},
{
"code": null,
"e": 28324,
"s": 27776,
"text": "We observe that vertex 2 does not have any emanating edge, and that every other vertex has an edge in vertex 2. At A[0][0] (A[i][j]), we encounter a 0, so we increment j and next look at A[0][1]. Here we encounter a 1. So we have to increment i by 1. A[1][1] is 0, so we keep increasing j. We notice that A[1][2], A[1][3].. etc are all 0, so j will exceed the number of vertices (6 in this example). We now check row i and column i for the sink property. Row i must be completely 0, and column i must be completely 1 except for the index A[i][i] "
},
{
"code": null,
"e": 28341,
"s": 28324,
"text": "Adjacency Matrix"
},
{
"code": null,
"e": 28359,
"s": 28341,
"text": "Second Example: "
},
{
"code": null,
"e": 28540,
"s": 28359,
"text": "v1 -> v6\nv2 -> v3\nv2 -> v4\nv4 -> v3\nv5 -> v3\nWe can visualize the adjacency matrix\nfor the above as follows:\n0 0 0 0 0 1\n0 0 1 1 0 0\n0 0 0 0 0 0\n0 0 1 0 0 0\n0 0 1 0 0 0\n0 0 0 0 0 0"
},
{
"code": null,
"e": 28875,
"s": 28540,
"text": "In this example, we observer that in row 1, every element is 0 except for the last column. So we will increment j until we reach the 1. When we reach 1, we increment i as long as the value of A[i][j] is 0. If i exceeds the number of vertices, it is not possible to have a sink, and in this case, i will exceed the number of vertices. "
},
{
"code": null,
"e": 28892,
"s": 28875,
"text": "Adjacency Matrix"
},
{
"code": null,
"e": 28899,
"s": 28894,
"text": "Java"
},
{
"code": null,
"e": 28907,
"s": 28899,
"text": "Python3"
},
{
"code": null,
"e": 28910,
"s": 28907,
"text": "C#"
},
{
"code": null,
"e": 28921,
"s": 28910,
"text": "Javascript"
},
{
"code": "// Java program to find whether a universal sink// exists in a directed graphimport java.io.*;import java.util.*; class graph{ int vertices; int[][] adjacency_matrix; // constructor to initialize number of vertices and // size of adjacency matrix public graph(int vertices) { this.vertices = vertices; adjacency_matrix = new int[vertices][vertices]; } public void insert(int source, int destination) { // make adjacency_matrix[i][j] = 1 if there is // an edge from i to j adjacency_matrix[destination-1] = 1; } public boolean issink(int i) { for (int j = 0 ; j < vertices ; j++) { // if any element in the row i is 1, it means // that there is an edge emanating from the // vertex, which means it cannot be a sink if (adjacency_matrix[i][j] == 1) return false; // if any element other than i in the column // i is 0, it means that there is no edge from // that vertex to the vertex we are testing // and hence it cannot be a sink if (adjacency_matrix[j][i] == 0 && j != i) return false; } //if none of the checks fails, return true return true; } // we will eliminate n-1 non sink vertices so that // we have to check for only one vertex instead of // all n vertices public int eliminate() { int i = 0, j = 0; while (i < vertices && j < vertices) { // If the index is 1, increment the row we are // checking by 1 // else increment the column if (adjacency_matrix[i][j] == 1) i = i + 1; else j = j + 1; } // If i exceeds the number of vertices, it // means that there is no valid vertex in // the given vertices that can be a sink if (i > vertices) return -1; else if (!issink(i)) return -1; else return i; }} public class Sink{ public static void main(String[] args)throws IOException { int number_of_vertices = 6; int number_of_edges = 5; graph g = new graph(number_of_vertices); /* //input set 1 g.insert(1, 6); g.insert(2, 6); g.insert(3, 6); g.insert(4, 6); g.insert(5, 6); */ //input set 2 g.insert(1, 6); g.insert(2, 3); g.insert(2, 4); g.insert(4, 3); g.insert(5, 3); int vertex = g.eliminate(); // returns 0 based indexing of vertex. returns // -1 if no sink exits. // returns the vertex number-1 if sink is found if (vertex >= 0) System.out.println(\"Sink found at vertex \" + (vertex + 1)); else System.out.println(\"No Sink\"); }}",
"e": 31829,
"s": 28921,
"text": null
},
{
"code": "# Python3 program to find whether a# universal sink exists in a directed graphclass Graph: # constructor to initialize number of # vertices and size of adjacency matrix def __init__(self, vertices): self.vertices = vertices self.adjacency_matrix = [[0 for i in range(vertices)] for j in range(vertices)] def insert(self, s, destination): # make adjacency_matrix[i][j] = 1 # if there is an edge from i to j self.adjacency_matrix[s - 1][destination - 1] = 1 def issink(self, i): for j in range(self.vertices): # if any element in the row i is 1, it means # that there is an edge emanating from the # vertex, which means it cannot be a sink if self.adjacency_matrix[i][j] == 1: return False # if any element other than i in the column # i is 0, it means that there is no edge from # that vertex to the vertex we are testing # and hence it cannot be a sink if self.adjacency_matrix[j][i] == 0 and j != i: return False # if none of the checks fails, return true return True # we will eliminate n-1 non sink vertices so that # we have to check for only one vertex instead of # all n vertices def eliminate(self): i = 0 j = 0 while i < self.vertices and j < self.vertices: # If the index is 1, increment the row # we are checking by 1 # else increment the column if self.adjacency_matrix[i][j] == 1: i += 1 else: j += 1 # If i exceeds the number of vertices, it # means that there is no valid vertex in # the given vertices that can be a sink if i > self.vertices: return -1 else if self.issink(i) is False: return -1 else: return i # Driver Codeif __name__ == \"__main__\": number_of_vertices = 6 number_of_edges = 5 g = Graph(number_of_vertices) # input set 1 # g.insert(1, 6) # g.insert(2, 6) # g.insert(3, 6) # g.insert(4, 6) # g.insert(5, 6) # input set 2 g.insert(1, 6) g.insert(2, 3) g.insert(2, 4) g.insert(4, 3) g.insert(5, 3) vertex = g.eliminate() # returns 0 based indexing of vertex. # returns -1 if no sink exits. # returns the vertex number-1 if sink is found if vertex >= 0: print(\"Sink found at vertex %d\" % (vertex + 1)) else: print(\"No Sink\") # This code is contributed by# sanjeev2552",
"e": 34449,
"s": 31829,
"text": null
},
{
"code": "// C# program to find whether a universal sink// exists in a directed graphusing System;using System.Collections.Generic; class graph{ int vertices, itr; int[,] adjacency_matrix; // constructor to initialize number of vertices and // size of adjacency matrix public graph(int vertices) { this.vertices = vertices; adjacency_matrix = new int[vertices, vertices]; } public void insert(int source, int destination) { // make adjacency_matrix[i,j] = 1 if there is // an edge from i to j adjacency_matrix = 1; } public bool issink(int i) { for (int j = 0 ; j < vertices ; j++) { // if any element in the row i is 1, it means // that there is an edge emanating from the // vertex, which means it cannot be a sink if (adjacency_matrix[i, j] == 1) return false; // if any element other than i in the column // i is 0, it means that there is no edge from // that vertex to the vertex we are testing // and hence it cannot be a sink if (adjacency_matrix[j, i] == 0 && j != i) return false; } //if none of the checks fails, return true return true; } // we will eliminate n-1 non sink vertices so that // we have to check for only one vertex instead of // all n vertices public int eliminate() { int i = 0, j = 0; while (i < vertices && j < vertices) { // If the index is 1, increment the row we are // checking by 1 // else increment the column if (adjacency_matrix[i, j] == 1) i = i + 1; else j = j + 1; } // If i exceeds the number of vertices, it // means that there is no valid vertex in // the given vertices that can be a sink if (i > vertices) return -1; else if (!issink(i)) return -1; else return i; }} public class Sink{ public static void Main(String[] args) { int number_of_vertices = 6; graph g = new graph(number_of_vertices); /* //input set 1 g.insert(1, 6); g.insert(2, 6); g.insert(3, 6); g.insert(4, 6); g.insert(5, 6); */ //input set 2 g.insert(1, 6); g.insert(2, 3); g.insert(2, 4); g.insert(4, 3); g.insert(5, 3); int vertex = g.eliminate(); // returns 0 based indexing of vertex. returns // -1 if no sink exits. // returns the vertex number-1 if sink is found if (vertex >= 0) Console.WriteLine(\"Sink found at vertex \" + (vertex + 1)); else Console.WriteLine(\"No Sink\"); }} // This code is contributed by Rajput-Ji",
"e": 37338,
"s": 34449,
"text": null
},
{
"code": "<script> // JavaScript program to find whether a// universal sink exists in a directed graphclass Graph{ // constructor to initialize number of // vertices and size of adjacency matrix constructor(vertices){ this.vertices = vertices this.adjacency_matrix = new Array(this.vertices).fill(0).map(()=>new Array(this.vertices).fill(0)) } insert(s, destination){ // make adjacency_matrix[i][j] = 1 // if there is an edge from i to j this.adjacency_matrix[s - 1][destination - 1] = 1 } issink(i){ for(let j=0;j<this.vertices;j++){ // if any element in the row i is 1, it means // that there is an edge emanating from the // vertex, which means it cannot be a sink if(this.adjacency_matrix[i][j] == 1) return false // if any element other than i in the column // i is 0, it means that there is no edge from // that vertex to the vertex we are testing // and hence it cannot be a sink if(this.adjacency_matrix[j][i] == 0 && j != i) return false } // if none of the checks fails, return true return true } // we will eliminate n-1 non sink vertices so that // we have to check for only one vertex instead of // all n vertices eliminate(){ let i = 0 let j = 0 while(i < this.vertices && j < this.vertices){ // If the index is 1, increment the row // we are checking by 1 // else increment the column if(this.adjacency_matrix[i][j] == 1) i += 1 else j += 1 } // If i exceeds the number of vertices, it // means that there is no valid vertex in // the given vertices that can be a sink if(i > this.vertices) return -1 else if(this.issink(i) == false) return -1 else return i }} // Driver Code let number_of_vertices = 6let number_of_edges = 5let g = new Graph(number_of_vertices) // input set 1// g.insert(1, 6)// g.insert(2, 6)// g.insert(3, 6)// g.insert(4, 6)// g.insert(5, 6) // input set 2g.insert(1, 6)g.insert(2, 3)g.insert(2, 4)g.insert(4, 3)g.insert(5, 3) let vertex = g.eliminate() // returns 0 based indexing of vertex.// returns -1 if no sink exits.// returns the vertex number-1 if sink is foundif(vertex >= 0) document.write(`Sink found at vertex ${(vertex + 1)}`,\"</br>\")else document.write(\"No Sink\",\"</br>\") // This code is contributed by shinjanpatra </script>",
"e": 39940,
"s": 37338,
"text": null
},
{
"code": null,
"e": 39950,
"s": 39940,
"text": "Output: "
},
{
"code": null,
"e": 40008,
"s": 39950,
"text": "input set 1: \nSink found at vertex 6\ninput set 2:\nNo Sink"
},
{
"code": null,
"e": 40625,
"s": 40008,
"text": "This program eliminates non-sink vertices in O(n) complexity and checks for the sink property in O(n) complexity.You may also try The Celebrity Problem, which is an application of this conceptThis article is contributed by Deepak Srivatsav. 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": 40637,
"s": 40625,
"text": "sanjeev2552"
},
{
"code": null,
"e": 40647,
"s": 40637,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 40657,
"s": 40647,
"text": "anas20023"
},
{
"code": null,
"e": 40670,
"s": 40657,
"text": "simmytarika5"
},
{
"code": null,
"e": 40683,
"s": 40670,
"text": "shinjanpatra"
},
{
"code": null,
"e": 40689,
"s": 40683,
"text": "Graph"
},
{
"code": null,
"e": 40695,
"s": 40689,
"text": "Graph"
},
{
"code": null,
"e": 40793,
"s": 40695,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40813,
"s": 40793,
"text": "Topological Sorting"
},
{
"code": null,
"e": 40846,
"s": 40813,
"text": "Detect Cycle in a Directed Graph"
},
{
"code": null,
"e": 40914,
"s": 40846,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 40964,
"s": 40914,
"text": "Ford-Fulkerson Algorithm for Maximum Flow Problem"
},
{
"code": null,
"e": 41039,
"s": 40964,
"text": "Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)"
},
{
"code": null,
"e": 41075,
"s": 41039,
"text": "Detect cycle in an undirected graph"
},
{
"code": null,
"e": 41123,
"s": 41075,
"text": "Traveling Salesman Problem (TSP) Implementation"
},
{
"code": null,
"e": 41170,
"s": 41123,
"text": "Find the number of islands | Set 1 (Using DFS)"
},
{
"code": null,
"e": 41206,
"s": 41170,
"text": "m Coloring Problem | Backtracking-5"
}
] |
K-th Greatest Element in a Max-Heap - GeeksforGeeks
|
26 Nov, 2018
Given a max-heap of size n, find the kth greatest element in the max-heap.
Examples:
Input : maxHeap = {20, 15, 18, 8, 10, 5, 17}k = 4Output : 15
Input : maxHeap = {100, 50, 80, 10, 25, 20, 75}k = 2Output : 80
Naive approach: We can extract the maximum element from the max-heap k times and the last element extracted will be the kth greatest element. Each deletion operations takes O(log n) time, so the total time complexity of this approach comes out to be O(k * log n).
Below is the implementation of this approach:
// C++ program for the// above approach#include <bits/stdc++.h>using namespace std; // Structure for the heapstruct Heap { vector<int> v; int n; // Size of the heap Heap(int i = 0) : n(i) { v = vector<int>(n); }}; // Generic function to// swap two integersvoid swap(int& a, int& b){ int temp = a; a = b; b = temp;} // Returns the index of// the parent nodeinline int parent(int i){ return (i - 1) / 2;} // Returns the index of// the left child nodeinline int left(int i){ return 2 * i + 1;} // Returns the index of// the right child nodeinline int right(int i){ return 2 * i + 2;} // Maintains the heap propertyvoid heapify(Heap& h, int i){ int l = left(i), r = right(i), m = i; if (l < h.n && h.v[i] < h.v[l]) m = l; if (r < h.n && h.v[m] < h.v[r]) m = r; if (m != i) { swap(h.v[m], h.v[i]); heapify(h, m); }} // Extracts the maximum elementint extractMax(Heap& h){ if (!h.n) return -1; int m = h.v[0]; h.v[0] = h.v[h.n-- - 1]; heapify(h, 0); return m;} int kThGreatest(Heap &h, int k){ for (int i = 1; i < k; ++i) extractMax(h); return extractMax(h);} // Driver Codeint main(){ Heap h(7); h.v = vector<int>{ 20, 15, 18, 8, 10, 5, 17 }; int k = 4; cout << kThGreatest(h, k); return 0;}
15
Time Complexity: O(k * log n)
Efficient approach: We can note an interesting observation about max-heap. An element x at ith level has i – 1 ancestors. By the property of max-heaps, these i – 1 ancestors are guaranteed to be greater than x. This implies that x cannot be among the greatest i – 1 elements of the heap. Using this property, we can conclude that the kth greatest element can have a level of at most k.
We can reduce the size of the max-heap such that it has only k levels. We can then obtain the kth greatest element by our previous strategy of extracting the maximum element k times. Note that the size of the heap is reduced to a maximum of 2k – 1, therefore each heapify operation will take O(log 2k) = O(k) time. The total time complexity will be O(k2). If n >> k, then this approach performs better than the previous one.
Below is the implementation of this approach:
// C++ program for the// above approach#include <bits/stdc++.h>using namespace std; // Structure for the heapstruct Heap { vector<int> v; int n; // Size of the heap Heap(int i = 0) : n(i) { v = vector<int>(n); }}; // Generic function to// swap two integersvoid swap(int& a, int& b){ int temp = a; a = b; b = temp;} // Returns the index of// the parent nodeinline int parent(int i){ return (i - 1) / 2;} // Returns the index of// the left child nodeinline int left(int i){ return 2 * i + 1;} // Returns the index of// the right child nodeinline int right(int i){ return 2 * i + 2;} // Maintains the heap propertyvoid heapify(Heap& h, int i){ int l = left(i), r = right(i), m = i; if (l < h.n && h.v[i] < h.v[l]) m = l; if (r < h.n && h.v[m] < h.v[r]) m = r; if (m != i) { swap(h.v[m], h.v[i]); heapify(h, m); }} // Extracts the maximum elementint extractMax(Heap& h){ if (!h.n) return -1; int m = h.v[0]; h.v[0] = h.v[h.n-- - 1]; heapify(h, 0); return m;} int kThGreatest(Heap &h, int k){ // Change size of heap h.n = min(h.n, int(pow(2, k) - 1)); for (int i = 1; i < k; ++i) extractMax(h); return extractMax(h);} // Driver Codeint main(){ Heap h(7); h.v = vector<int>{ 20, 15, 18, 8, 10, 5, 17 }; int k = 2; cout << kThGreatest(h, k); return 0;}
18
Time Complexity: O(k2)
More efficient approach: We can further improve the time complexity of this problem by the following algorithm:
Create a priority queue P and insert the root node of the max-heap into P.Repeat these steps k – 1 times:Pop the greatest element from P.Insert left and right child elements of the popped element. (if they exist).The greatest element in P is the kth greatest element of the max-heap.
Create a priority queue P and insert the root node of the max-heap into P.
Repeat these steps k – 1 times:Pop the greatest element from P.Insert left and right child elements of the popped element. (if they exist).
Pop the greatest element from P.Insert left and right child elements of the popped element. (if they exist).
Pop the greatest element from P.
Insert left and right child elements of the popped element. (if they exist).
The greatest element in P is the kth greatest element of the max-heap.
The initial size of the priority queue is one, and it increases by at most one at each of the k – 1 steps. Therefore, there are maximum k elements in the priority queue and the time complexity of the pop and insert operations is O(log k). Thus the total time complexity is O(k * log k).
Below is the implementation of the above approach:
// C++ program for the// above approach#include <bits/stdc++.h>using namespace std; // Structure for the heapstruct Heap { vector<int> v; int n; // Size of the heap Heap(int i = 0) : n(i) { v = vector<int>(n); }}; // Returns the index of// the left child nodeinline int left(int i){ return 2 * i + 1;} // Returns the index of// the right child nodeinline int right(int i){ return 2 * i + 2;} int kThGreatest(Heap &h, int k){ priority_queue<pair<int, int> > p; p.push(make_pair(h.v[0], 0)); for (int i = 0; i < k - 1; ++i) { int j = p.top().second; p.pop(); int l = left(j), r = right(j); if (l < h.n) p.push(make_pair(h.v[l], l)); if (r < h.n) p.push(make_pair(h.v[r], r)); } return p.top().first;} // Driver Codeint main(){ Heap h(7); h.v = vector<int>{ 20, 15, 18, 8, 10, 5, 17 }; int k = 2; cout << kThGreatest(h, k); return 0;}
18
Time Complexity: O(k * log k)
priority-queue
Technical Scripter 2018
Heap
Queue
Technical Scripter
Queue
Heap
priority-queue
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Insertion and Deletion in Heaps
Priority Queue in Python
Priority Queue using Binary Heap
Median in a stream of integers (running integers)
Real-time application of Data Structures
Breadth First Search or BFS for a Graph
Level Order Binary Tree Traversal
Queue Interface In Java
Queue in Python
Queue | Set 1 (Introduction and Array Implementation)
|
[
{
"code": null,
"e": 25765,
"s": 25737,
"text": "\n26 Nov, 2018"
},
{
"code": null,
"e": 25840,
"s": 25765,
"text": "Given a max-heap of size n, find the kth greatest element in the max-heap."
},
{
"code": null,
"e": 25850,
"s": 25840,
"text": "Examples:"
},
{
"code": null,
"e": 25911,
"s": 25850,
"text": "Input : maxHeap = {20, 15, 18, 8, 10, 5, 17}k = 4Output : 15"
},
{
"code": null,
"e": 25975,
"s": 25911,
"text": "Input : maxHeap = {100, 50, 80, 10, 25, 20, 75}k = 2Output : 80"
},
{
"code": null,
"e": 26239,
"s": 25975,
"text": "Naive approach: We can extract the maximum element from the max-heap k times and the last element extracted will be the kth greatest element. Each deletion operations takes O(log n) time, so the total time complexity of this approach comes out to be O(k * log n)."
},
{
"code": null,
"e": 26285,
"s": 26239,
"text": "Below is the implementation of this approach:"
},
{
"code": "// C++ program for the// above approach#include <bits/stdc++.h>using namespace std; // Structure for the heapstruct Heap { vector<int> v; int n; // Size of the heap Heap(int i = 0) : n(i) { v = vector<int>(n); }}; // Generic function to// swap two integersvoid swap(int& a, int& b){ int temp = a; a = b; b = temp;} // Returns the index of// the parent nodeinline int parent(int i){ return (i - 1) / 2;} // Returns the index of// the left child nodeinline int left(int i){ return 2 * i + 1;} // Returns the index of// the right child nodeinline int right(int i){ return 2 * i + 2;} // Maintains the heap propertyvoid heapify(Heap& h, int i){ int l = left(i), r = right(i), m = i; if (l < h.n && h.v[i] < h.v[l]) m = l; if (r < h.n && h.v[m] < h.v[r]) m = r; if (m != i) { swap(h.v[m], h.v[i]); heapify(h, m); }} // Extracts the maximum elementint extractMax(Heap& h){ if (!h.n) return -1; int m = h.v[0]; h.v[0] = h.v[h.n-- - 1]; heapify(h, 0); return m;} int kThGreatest(Heap &h, int k){ for (int i = 1; i < k; ++i) extractMax(h); return extractMax(h);} // Driver Codeint main(){ Heap h(7); h.v = vector<int>{ 20, 15, 18, 8, 10, 5, 17 }; int k = 4; cout << kThGreatest(h, k); return 0;}",
"e": 27625,
"s": 26285,
"text": null
},
{
"code": null,
"e": 27629,
"s": 27625,
"text": "15\n"
},
{
"code": null,
"e": 27659,
"s": 27629,
"text": "Time Complexity: O(k * log n)"
},
{
"code": null,
"e": 28045,
"s": 27659,
"text": "Efficient approach: We can note an interesting observation about max-heap. An element x at ith level has i – 1 ancestors. By the property of max-heaps, these i – 1 ancestors are guaranteed to be greater than x. This implies that x cannot be among the greatest i – 1 elements of the heap. Using this property, we can conclude that the kth greatest element can have a level of at most k."
},
{
"code": null,
"e": 28470,
"s": 28045,
"text": "We can reduce the size of the max-heap such that it has only k levels. We can then obtain the kth greatest element by our previous strategy of extracting the maximum element k times. Note that the size of the heap is reduced to a maximum of 2k – 1, therefore each heapify operation will take O(log 2k) = O(k) time. The total time complexity will be O(k2). If n >> k, then this approach performs better than the previous one."
},
{
"code": null,
"e": 28516,
"s": 28470,
"text": "Below is the implementation of this approach:"
},
{
"code": "// C++ program for the// above approach#include <bits/stdc++.h>using namespace std; // Structure for the heapstruct Heap { vector<int> v; int n; // Size of the heap Heap(int i = 0) : n(i) { v = vector<int>(n); }}; // Generic function to// swap two integersvoid swap(int& a, int& b){ int temp = a; a = b; b = temp;} // Returns the index of// the parent nodeinline int parent(int i){ return (i - 1) / 2;} // Returns the index of// the left child nodeinline int left(int i){ return 2 * i + 1;} // Returns the index of// the right child nodeinline int right(int i){ return 2 * i + 2;} // Maintains the heap propertyvoid heapify(Heap& h, int i){ int l = left(i), r = right(i), m = i; if (l < h.n && h.v[i] < h.v[l]) m = l; if (r < h.n && h.v[m] < h.v[r]) m = r; if (m != i) { swap(h.v[m], h.v[i]); heapify(h, m); }} // Extracts the maximum elementint extractMax(Heap& h){ if (!h.n) return -1; int m = h.v[0]; h.v[0] = h.v[h.n-- - 1]; heapify(h, 0); return m;} int kThGreatest(Heap &h, int k){ // Change size of heap h.n = min(h.n, int(pow(2, k) - 1)); for (int i = 1; i < k; ++i) extractMax(h); return extractMax(h);} // Driver Codeint main(){ Heap h(7); h.v = vector<int>{ 20, 15, 18, 8, 10, 5, 17 }; int k = 2; cout << kThGreatest(h, k); return 0;}",
"e": 29925,
"s": 28516,
"text": null
},
{
"code": null,
"e": 29929,
"s": 29925,
"text": "18\n"
},
{
"code": null,
"e": 29952,
"s": 29929,
"text": "Time Complexity: O(k2)"
},
{
"code": null,
"e": 30064,
"s": 29952,
"text": "More efficient approach: We can further improve the time complexity of this problem by the following algorithm:"
},
{
"code": null,
"e": 30348,
"s": 30064,
"text": "Create a priority queue P and insert the root node of the max-heap into P.Repeat these steps k – 1 times:Pop the greatest element from P.Insert left and right child elements of the popped element. (if they exist).The greatest element in P is the kth greatest element of the max-heap."
},
{
"code": null,
"e": 30423,
"s": 30348,
"text": "Create a priority queue P and insert the root node of the max-heap into P."
},
{
"code": null,
"e": 30563,
"s": 30423,
"text": "Repeat these steps k – 1 times:Pop the greatest element from P.Insert left and right child elements of the popped element. (if they exist)."
},
{
"code": null,
"e": 30672,
"s": 30563,
"text": "Pop the greatest element from P.Insert left and right child elements of the popped element. (if they exist)."
},
{
"code": null,
"e": 30705,
"s": 30672,
"text": "Pop the greatest element from P."
},
{
"code": null,
"e": 30782,
"s": 30705,
"text": "Insert left and right child elements of the popped element. (if they exist)."
},
{
"code": null,
"e": 30853,
"s": 30782,
"text": "The greatest element in P is the kth greatest element of the max-heap."
},
{
"code": null,
"e": 31140,
"s": 30853,
"text": "The initial size of the priority queue is one, and it increases by at most one at each of the k – 1 steps. Therefore, there are maximum k elements in the priority queue and the time complexity of the pop and insert operations is O(log k). Thus the total time complexity is O(k * log k)."
},
{
"code": null,
"e": 31191,
"s": 31140,
"text": "Below is the implementation of the above approach:"
},
{
"code": "// C++ program for the// above approach#include <bits/stdc++.h>using namespace std; // Structure for the heapstruct Heap { vector<int> v; int n; // Size of the heap Heap(int i = 0) : n(i) { v = vector<int>(n); }}; // Returns the index of// the left child nodeinline int left(int i){ return 2 * i + 1;} // Returns the index of// the right child nodeinline int right(int i){ return 2 * i + 2;} int kThGreatest(Heap &h, int k){ priority_queue<pair<int, int> > p; p.push(make_pair(h.v[0], 0)); for (int i = 0; i < k - 1; ++i) { int j = p.top().second; p.pop(); int l = left(j), r = right(j); if (l < h.n) p.push(make_pair(h.v[l], l)); if (r < h.n) p.push(make_pair(h.v[r], r)); } return p.top().first;} // Driver Codeint main(){ Heap h(7); h.v = vector<int>{ 20, 15, 18, 8, 10, 5, 17 }; int k = 2; cout << kThGreatest(h, k); return 0;}",
"e": 32156,
"s": 31191,
"text": null
},
{
"code": null,
"e": 32160,
"s": 32156,
"text": "18\n"
},
{
"code": null,
"e": 32190,
"s": 32160,
"text": "Time Complexity: O(k * log k)"
},
{
"code": null,
"e": 32205,
"s": 32190,
"text": "priority-queue"
},
{
"code": null,
"e": 32229,
"s": 32205,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 32234,
"s": 32229,
"text": "Heap"
},
{
"code": null,
"e": 32240,
"s": 32234,
"text": "Queue"
},
{
"code": null,
"e": 32259,
"s": 32240,
"text": "Technical Scripter"
},
{
"code": null,
"e": 32265,
"s": 32259,
"text": "Queue"
},
{
"code": null,
"e": 32270,
"s": 32265,
"text": "Heap"
},
{
"code": null,
"e": 32285,
"s": 32270,
"text": "priority-queue"
},
{
"code": null,
"e": 32383,
"s": 32285,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32415,
"s": 32383,
"text": "Insertion and Deletion in Heaps"
},
{
"code": null,
"e": 32440,
"s": 32415,
"text": "Priority Queue in Python"
},
{
"code": null,
"e": 32473,
"s": 32440,
"text": "Priority Queue using Binary Heap"
},
{
"code": null,
"e": 32523,
"s": 32473,
"text": "Median in a stream of integers (running integers)"
},
{
"code": null,
"e": 32564,
"s": 32523,
"text": "Real-time application of Data Structures"
},
{
"code": null,
"e": 32604,
"s": 32564,
"text": "Breadth First Search or BFS for a Graph"
},
{
"code": null,
"e": 32638,
"s": 32604,
"text": "Level Order Binary Tree Traversal"
},
{
"code": null,
"e": 32662,
"s": 32638,
"text": "Queue Interface In Java"
},
{
"code": null,
"e": 32678,
"s": 32662,
"text": "Queue in Python"
}
] |
JavaFX | Alert with examples - GeeksforGeeks
|
19 Apr, 2021
Alert is a part of JavaFX and it is a subclass of Dialog class. Alerts are some predefined dialogs that are used to show some information to the user. Alerts are basically of specific alert types:
CONFIRMATION alert :The CONFIRMATION alert type configures the Alert dialog to appear in a way that suggests the content of the dialog is seeking confirmation from the user.
WARNING alert :The WARNING alert type configures the Alert dialog to appear in a way that suggests the content of the dialog is warning the user about some fact or action.
NONE alert :The NONE alert type has the effect of not setting any default properties in the Alert.
INFORMATION alert :The INFORMATION alert type configures the Alert dialog to appear in a way that suggests the content of the dialog is informing the user of a piece of information.
ERROR alert :The ERROR alert type configures the Alert dialog to appear in a way that suggests that something has gone wrong.
An Alert contains 3 parts:
The header
The content text
The confirmation buttons
Constructors of the class are:
Alert(Alert.AlertType a): Creates a new alert with a specified alert type.Alert(Alert.AlertType a, String c, ButtonType... b): Creates a new alert with a specified alert type, content and button type.
Alert(Alert.AlertType a): Creates a new alert with a specified alert type.
Alert(Alert.AlertType a, String c, ButtonType... b): Creates a new alert with a specified alert type, content and button type.
Commonly used methods:
Below programs illustrate the Alert class:
Program to create alert of different types and display them: This program creates an alert which is of default type. The alert would be changed to different alert types when required. This program creates a Buttons indicated by the name b, b1, b2, b3. The buttons will be created inside a scene, which in turn will be hosted inside a stage. We would create a label to show if the button is pressed or not. The function setTitle() is used to provide title to the stage. Then a tile pane is created, on which addChildren() method is called to attach the button and label inside the scene. Finally, the show() method is called to display the final results.we would create an event handler to handle the button events. The event handler would be added to the button using setOnAction() function. When the buttons are pressed they will display the respective alerts associated with them and will set the respective alertType using the function setAlertType() function.
Program to create alert of different types and display them: This program creates an alert which is of default type. The alert would be changed to different alert types when required. This program creates a Buttons indicated by the name b, b1, b2, b3. The buttons will be created inside a scene, which in turn will be hosted inside a stage. We would create a label to show if the button is pressed or not. The function setTitle() is used to provide title to the stage. Then a tile pane is created, on which addChildren() method is called to attach the button and label inside the scene. Finally, the show() method is called to display the final results.we would create an event handler to handle the button events. The event handler would be added to the button using setOnAction() function. When the buttons are pressed they will display the respective alerts associated with them and will set the respective alertType using the function setAlertType() function.
Java
// Java Program to create alert of different// types and display them import javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.*;import javafx.stage.Stage;import javafx.scene.control.Alert.AlertType;public class Alert_1 extends Application { // launch the application public void start(Stage s) { // set title for the stage s.setTitle("creating alerts"); // create a button Button b = new Button("Confirmation alert"); Button b1 = new Button("error alert"); Button b2 = new Button("Information alert"); Button b3 = new Button("Warning alert"); // create a tile pane TilePane r = new TilePane(); // create a alert Alert a = new Alert(AlertType.NONE); // action event EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { // set alert type a.setAlertType(AlertType.CONFIRMATION); // show the dialog a.show(); } }; // action event EventHandler<ActionEvent> event1 = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { // set alert type a.setAlertType(AlertType.ERROR); // show the dialog a.show(); } }; // action event EventHandler<ActionEvent> event2 = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { // set alert type a.setAlertType(AlertType.INFORMATION); // show the dialog a.show(); } }; // action event EventHandler<ActionEvent> event3 = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { // set alert type a.setAlertType(AlertType.WARNING); // show the dialog a.show(); } }; // when button is pressed b.setOnAction(event); b1.setOnAction(event1); b2.setOnAction(event2); b3.setOnAction(event3); // add button r.getChildren().add(b); r.getChildren().add(b1); r.getChildren().add(b2); r.getChildren().add(b3); // create a scene Scene sc = new Scene(r, 200, 200); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }}
Output:
Output:
Program to create alert and set different alert types and button type and also set different content text: This program creates an alert which is of default type. the alert would be changed to different alert types when required. This program creates a Buttons indicated by the name b, b1, b2, b3, b4. The buttons will be created inside a scene, which in turn will be hosted inside a stage. We would create a label to show if the button is pressed or not. The function setTitle() is used to provide title to the stage. Then a tile pane is created, on which addChildren() method is called to attach the button and label inside the scene. Finally, the show() method is called to display the final results.we would create an event handler to handle the button events. The event handler would be added to the button using setOnAction() function. When the buttons are pressed they will display the respective alerts associated with them and will set the respective alertType using the function setAlertType() function. The content text would also be changed using the setContentText() method .we would create a new alert for the 4th button which is of default type, and also set a button type using the constructor of alert.
Program to create alert and set different alert types and button type and also set different content text: This program creates an alert which is of default type. the alert would be changed to different alert types when required. This program creates a Buttons indicated by the name b, b1, b2, b3, b4. The buttons will be created inside a scene, which in turn will be hosted inside a stage. We would create a label to show if the button is pressed or not. The function setTitle() is used to provide title to the stage. Then a tile pane is created, on which addChildren() method is called to attach the button and label inside the scene. Finally, the show() method is called to display the final results.we would create an event handler to handle the button events. The event handler would be added to the button using setOnAction() function. When the buttons are pressed they will display the respective alerts associated with them and will set the respective alertType using the function setAlertType() function. The content text would also be changed using the setContentText() method .we would create a new alert for the 4th button which is of default type, and also set a button type using the constructor of alert.
Java
// Java Program to create alert and set// different alert types and button type// and also set different content text import javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.*;import javafx.stage.Stage;import javafx.scene.control.Alert.AlertType; public class Alert_2 extends Application { // launch the application public void start(Stage s) { // set title for the stage s.setTitle("creating alerts"); // create a button Button b = new Button("Confirmation alert"); Button b1 = new Button("error alert"); Button b2 = new Button("Information alert"); Button b3 = new Button("Warning alert"); Button b4 = new Button("none alert"); // create a tile pane TilePane r = new TilePane(); // create a alert Alert a = new Alert(AlertType.NONE); // action event EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { // set alert type a.setAlertType(AlertType.CONFIRMATION); // set content text a.setContentText("ConfirmationDialog"); // show the dialog a.show(); } }; // action event EventHandler<ActionEvent> event1 = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { // set alert type a.setAlertType(AlertType.ERROR); // set content text a.setContentText("error Dialog"); // show the dialog a.show(); } }; // action event EventHandler<ActionEvent> event2 = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { // set alert type a.setAlertType(AlertType.INFORMATION); // set content text a.setContentText("Information Dialog"); // show the dialog a.show(); } }; // action event EventHandler<ActionEvent> event3 = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { // set alert type a.setAlertType(AlertType.WARNING); // set content text a.setContentText("Warning Dialog"); // show the dialog a.show(); } }; // action event EventHandler<ActionEvent> event4 = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { Alert a1 = new Alert(AlertType.NONE, "default Dialog",ButtonType.APPLY); // show the dialog a1.show(); } }; // when button is pressed b.setOnAction(event); b1.setOnAction(event1); b2.setOnAction(event2); b3.setOnAction(event3); b4.setOnAction(event4); // add button r.getChildren().add(b); r.getChildren().add(b1); r.getChildren().add(b2); r.getChildren().add(b3); r.getChildren().add(b4); // create a scene Scene sc = new Scene(r, 200, 200); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }}
Output:
Output:
https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/Alert.html
https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/Alert.AlertType.html
ManasChhabra2
sweetyty
JavaFX
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HashMap in Java with Examples
Interfaces in Java
Stream In Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java
Multithreading in Java
Collections in Java
|
[
{
"code": null,
"e": 25315,
"s": 25287,
"text": "\n19 Apr, 2021"
},
{
"code": null,
"e": 25514,
"s": 25315,
"text": "Alert is a part of JavaFX and it is a subclass of Dialog class. Alerts are some predefined dialogs that are used to show some information to the user. Alerts are basically of specific alert types: "
},
{
"code": null,
"e": 25688,
"s": 25514,
"text": "CONFIRMATION alert :The CONFIRMATION alert type configures the Alert dialog to appear in a way that suggests the content of the dialog is seeking confirmation from the user."
},
{
"code": null,
"e": 25860,
"s": 25688,
"text": "WARNING alert :The WARNING alert type configures the Alert dialog to appear in a way that suggests the content of the dialog is warning the user about some fact or action."
},
{
"code": null,
"e": 25959,
"s": 25860,
"text": "NONE alert :The NONE alert type has the effect of not setting any default properties in the Alert."
},
{
"code": null,
"e": 26141,
"s": 25959,
"text": "INFORMATION alert :The INFORMATION alert type configures the Alert dialog to appear in a way that suggests the content of the dialog is informing the user of a piece of information."
},
{
"code": null,
"e": 26267,
"s": 26141,
"text": "ERROR alert :The ERROR alert type configures the Alert dialog to appear in a way that suggests that something has gone wrong."
},
{
"code": null,
"e": 26296,
"s": 26267,
"text": "An Alert contains 3 parts: "
},
{
"code": null,
"e": 26307,
"s": 26296,
"text": "The header"
},
{
"code": null,
"e": 26324,
"s": 26307,
"text": "The content text"
},
{
"code": null,
"e": 26349,
"s": 26324,
"text": "The confirmation buttons"
},
{
"code": null,
"e": 26382,
"s": 26349,
"text": "Constructors of the class are: "
},
{
"code": null,
"e": 26583,
"s": 26382,
"text": "Alert(Alert.AlertType a): Creates a new alert with a specified alert type.Alert(Alert.AlertType a, String c, ButtonType... b): Creates a new alert with a specified alert type, content and button type."
},
{
"code": null,
"e": 26658,
"s": 26583,
"text": "Alert(Alert.AlertType a): Creates a new alert with a specified alert type."
},
{
"code": null,
"e": 26785,
"s": 26658,
"text": "Alert(Alert.AlertType a, String c, ButtonType... b): Creates a new alert with a specified alert type, content and button type."
},
{
"code": null,
"e": 26809,
"s": 26785,
"text": "Commonly used methods: "
},
{
"code": null,
"e": 26856,
"s": 26811,
"text": "Below programs illustrate the Alert class: "
},
{
"code": null,
"e": 27821,
"s": 26856,
"text": "Program to create alert of different types and display them: This program creates an alert which is of default type. The alert would be changed to different alert types when required. This program creates a Buttons indicated by the name b, b1, b2, b3. The buttons will be created inside a scene, which in turn will be hosted inside a stage. We would create a label to show if the button is pressed or not. The function setTitle() is used to provide title to the stage. Then a tile pane is created, on which addChildren() method is called to attach the button and label inside the scene. Finally, the show() method is called to display the final results.we would create an event handler to handle the button events. The event handler would be added to the button using setOnAction() function. When the buttons are pressed they will display the respective alerts associated with them and will set the respective alertType using the function setAlertType() function. "
},
{
"code": null,
"e": 28786,
"s": 27821,
"text": "Program to create alert of different types and display them: This program creates an alert which is of default type. The alert would be changed to different alert types when required. This program creates a Buttons indicated by the name b, b1, b2, b3. The buttons will be created inside a scene, which in turn will be hosted inside a stage. We would create a label to show if the button is pressed or not. The function setTitle() is used to provide title to the stage. Then a tile pane is created, on which addChildren() method is called to attach the button and label inside the scene. Finally, the show() method is called to display the final results.we would create an event handler to handle the button events. The event handler would be added to the button using setOnAction() function. When the buttons are pressed they will display the respective alerts associated with them and will set the respective alertType using the function setAlertType() function. "
},
{
"code": null,
"e": 28791,
"s": 28786,
"text": "Java"
},
{
"code": "// Java Program to create alert of different// types and display them import javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.*;import javafx.stage.Stage;import javafx.scene.control.Alert.AlertType;public class Alert_1 extends Application { // launch the application public void start(Stage s) { // set title for the stage s.setTitle(\"creating alerts\"); // create a button Button b = new Button(\"Confirmation alert\"); Button b1 = new Button(\"error alert\"); Button b2 = new Button(\"Information alert\"); Button b3 = new Button(\"Warning alert\"); // create a tile pane TilePane r = new TilePane(); // create a alert Alert a = new Alert(AlertType.NONE); // action event EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { // set alert type a.setAlertType(AlertType.CONFIRMATION); // show the dialog a.show(); } }; // action event EventHandler<ActionEvent> event1 = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { // set alert type a.setAlertType(AlertType.ERROR); // show the dialog a.show(); } }; // action event EventHandler<ActionEvent> event2 = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { // set alert type a.setAlertType(AlertType.INFORMATION); // show the dialog a.show(); } }; // action event EventHandler<ActionEvent> event3 = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { // set alert type a.setAlertType(AlertType.WARNING); // show the dialog a.show(); } }; // when button is pressed b.setOnAction(event); b1.setOnAction(event1); b2.setOnAction(event2); b3.setOnAction(event3); // add button r.getChildren().add(b); r.getChildren().add(b1); r.getChildren().add(b2); r.getChildren().add(b3); // create a scene Scene sc = new Scene(r, 200, 200); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }}",
"e": 31646,
"s": 28791,
"text": null
},
{
"code": null,
"e": 31656,
"s": 31646,
"text": "Output: "
},
{
"code": null,
"e": 31666,
"s": 31656,
"text": "Output: "
},
{
"code": null,
"e": 32899,
"s": 31678,
"text": "Program to create alert and set different alert types and button type and also set different content text: This program creates an alert which is of default type. the alert would be changed to different alert types when required. This program creates a Buttons indicated by the name b, b1, b2, b3, b4. The buttons will be created inside a scene, which in turn will be hosted inside a stage. We would create a label to show if the button is pressed or not. The function setTitle() is used to provide title to the stage. Then a tile pane is created, on which addChildren() method is called to attach the button and label inside the scene. Finally, the show() method is called to display the final results.we would create an event handler to handle the button events. The event handler would be added to the button using setOnAction() function. When the buttons are pressed they will display the respective alerts associated with them and will set the respective alertType using the function setAlertType() function. The content text would also be changed using the setContentText() method .we would create a new alert for the 4th button which is of default type, and also set a button type using the constructor of alert. "
},
{
"code": null,
"e": 34120,
"s": 32899,
"text": "Program to create alert and set different alert types and button type and also set different content text: This program creates an alert which is of default type. the alert would be changed to different alert types when required. This program creates a Buttons indicated by the name b, b1, b2, b3, b4. The buttons will be created inside a scene, which in turn will be hosted inside a stage. We would create a label to show if the button is pressed or not. The function setTitle() is used to provide title to the stage. Then a tile pane is created, on which addChildren() method is called to attach the button and label inside the scene. Finally, the show() method is called to display the final results.we would create an event handler to handle the button events. The event handler would be added to the button using setOnAction() function. When the buttons are pressed they will display the respective alerts associated with them and will set the respective alertType using the function setAlertType() function. The content text would also be changed using the setContentText() method .we would create a new alert for the 4th button which is of default type, and also set a button type using the constructor of alert. "
},
{
"code": null,
"e": 34125,
"s": 34120,
"text": "Java"
},
{
"code": "// Java Program to create alert and set// different alert types and button type// and also set different content text import javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.*;import javafx.stage.Stage;import javafx.scene.control.Alert.AlertType; public class Alert_2 extends Application { // launch the application public void start(Stage s) { // set title for the stage s.setTitle(\"creating alerts\"); // create a button Button b = new Button(\"Confirmation alert\"); Button b1 = new Button(\"error alert\"); Button b2 = new Button(\"Information alert\"); Button b3 = new Button(\"Warning alert\"); Button b4 = new Button(\"none alert\"); // create a tile pane TilePane r = new TilePane(); // create a alert Alert a = new Alert(AlertType.NONE); // action event EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { // set alert type a.setAlertType(AlertType.CONFIRMATION); // set content text a.setContentText(\"ConfirmationDialog\"); // show the dialog a.show(); } }; // action event EventHandler<ActionEvent> event1 = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { // set alert type a.setAlertType(AlertType.ERROR); // set content text a.setContentText(\"error Dialog\"); // show the dialog a.show(); } }; // action event EventHandler<ActionEvent> event2 = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { // set alert type a.setAlertType(AlertType.INFORMATION); // set content text a.setContentText(\"Information Dialog\"); // show the dialog a.show(); } }; // action event EventHandler<ActionEvent> event3 = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { // set alert type a.setAlertType(AlertType.WARNING); // set content text a.setContentText(\"Warning Dialog\"); // show the dialog a.show(); } }; // action event EventHandler<ActionEvent> event4 = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { Alert a1 = new Alert(AlertType.NONE, \"default Dialog\",ButtonType.APPLY); // show the dialog a1.show(); } }; // when button is pressed b.setOnAction(event); b1.setOnAction(event1); b2.setOnAction(event2); b3.setOnAction(event3); b4.setOnAction(event4); // add button r.getChildren().add(b); r.getChildren().add(b1); r.getChildren().add(b2); r.getChildren().add(b3); r.getChildren().add(b4); // create a scene Scene sc = new Scene(r, 200, 200); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }}",
"e": 37885,
"s": 34125,
"text": null
},
{
"code": null,
"e": 37895,
"s": 37885,
"text": "Output: "
},
{
"code": null,
"e": 37905,
"s": 37895,
"text": "Output: "
},
{
"code": null,
"e": 37997,
"s": 37921,
"text": "https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/Alert.html"
},
{
"code": null,
"e": 38083,
"s": 37997,
"text": "https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/Alert.AlertType.html"
},
{
"code": null,
"e": 38097,
"s": 38083,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 38106,
"s": 38097,
"text": "sweetyty"
},
{
"code": null,
"e": 38113,
"s": 38106,
"text": "JavaFX"
},
{
"code": null,
"e": 38118,
"s": 38113,
"text": "Java"
},
{
"code": null,
"e": 38123,
"s": 38118,
"text": "Java"
},
{
"code": null,
"e": 38221,
"s": 38123,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38251,
"s": 38221,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 38270,
"s": 38251,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 38285,
"s": 38270,
"text": "Stream In Java"
},
{
"code": null,
"e": 38317,
"s": 38285,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 38337,
"s": 38317,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 38369,
"s": 38337,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 38393,
"s": 38369,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 38405,
"s": 38393,
"text": "Set in Java"
},
{
"code": null,
"e": 38428,
"s": 38405,
"text": "Multithreading in Java"
}
] |
RequireJS - jQuery Using Shim Config
|
jQuery uses shim configuration to define the dependencies for jQuery plugins and set a module value by declaring dependencies.
require(['jquery','jquery.myjsfile1','jquery.myjsfile2'], function($) {
$(function() {
//code here
});
});
The following example uses shim configuration to define the dependencies for jQuery plugins. Create a html file with the name index.html and place the following code in it −
<!DOCTYPE html>
<html>
<head>
<title>jQuery Shim Config</title>
<script data-main = "app" src = "lib/require.js"></script>
</head>
<body>
<h2>jQuery Shim Config</h2>
<p>Welcome to Tutorialspoint!!!</p>
</body>
</html>
Create a js file with the name app.js and add the following code in it −
//You can configure loading modules from the lib directory
requirejs.config ({
"baseUrl": "lib",
"paths": {
"app": "../app"
},
"shim": {
"jquery.shim1": ["jquery"],
"jquery.shim2": ["jquery"]
}
});
//To start the application, load the main module from app folder
requirejs(["app/main"]);
Create a folder called app and load the main.js module from this folder −
define(["jquery", "jquery.shim1", "jquery.shim2"], function($) {
//loading the jquery.shim1.js and jquery.shim2.js plugins
$(function() {
$('body').shim1().shim2();
});
});
Create one more folder called lib to store the require.js file and other js files as shown below −
$.fn.shim1 = function() {
return this.append('<p>This is shim1 config...!</p>');
};
$.fn.shim2 = function() {
return this.append('<p>This is shim2 config...!</p>');
};
Open the HTML file in a browser; you will receive the following output −
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1969,
"s": 1842,
"text": "jQuery uses shim configuration to define the dependencies for jQuery plugins and set a module value by declaring dependencies."
},
{
"code": null,
"e": 2088,
"s": 1969,
"text": "require(['jquery','jquery.myjsfile1','jquery.myjsfile2'], function($) {\n $(function() {\n //code here\n });\n});"
},
{
"code": null,
"e": 2262,
"s": 2088,
"text": "The following example uses shim configuration to define the dependencies for jQuery plugins. Create a html file with the name index.html and place the following code in it −"
},
{
"code": null,
"e": 2520,
"s": 2262,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>jQuery Shim Config</title>\n <script data-main = \"app\" src = \"lib/require.js\"></script>\n </head>\n \n <body>\n <h2>jQuery Shim Config</h2>\n <p>Welcome to Tutorialspoint!!!</p>\n </body>\n</html>"
},
{
"code": null,
"e": 2593,
"s": 2520,
"text": "Create a js file with the name app.js and add the following code in it −"
},
{
"code": null,
"e": 2923,
"s": 2593,
"text": "//You can configure loading modules from the lib directory\nrequirejs.config ({\n \"baseUrl\": \"lib\",\n \n \"paths\": {\n \"app\": \"../app\"\n },\n \n \"shim\": {\n \"jquery.shim1\": [\"jquery\"],\n \"jquery.shim2\": [\"jquery\"]\n }\n});\n\n//To start the application, load the main module from app folder\nrequirejs([\"app/main\"]);"
},
{
"code": null,
"e": 2997,
"s": 2923,
"text": "Create a folder called app and load the main.js module from this folder −"
},
{
"code": null,
"e": 3186,
"s": 2997,
"text": "define([\"jquery\", \"jquery.shim1\", \"jquery.shim2\"], function($) {\n //loading the jquery.shim1.js and jquery.shim2.js plugins \n $(function() {\n $('body').shim1().shim2();\n });\n});"
},
{
"code": null,
"e": 3285,
"s": 3186,
"text": "Create one more folder called lib to store the require.js file and other js files as shown below −"
},
{
"code": null,
"e": 3372,
"s": 3285,
"text": "$.fn.shim1 = function() {\n return this.append('<p>This is shim1 config...!</p>');\n};"
},
{
"code": null,
"e": 3459,
"s": 3372,
"text": "$.fn.shim2 = function() {\n return this.append('<p>This is shim2 config...!</p>');\n};"
},
{
"code": null,
"e": 3532,
"s": 3459,
"text": "Open the HTML file in a browser; you will receive the following output −"
},
{
"code": null,
"e": 3539,
"s": 3532,
"text": " Print"
},
{
"code": null,
"e": 3550,
"s": 3539,
"text": " Add Notes"
}
] |
Python - Word Replacement
|
Replacing the complete string or a part of string is a very frequent requirement in text processing. The replace() method returns a copy of the string in which the occurrences of old have been replaced with new, optionally restricting the number of replacements to max.
Following is the syntax for replace() method −
str.replace(old, new[, max])
old − This is old substring to be replaced.
old − This is old substring to be replaced.
new − This is new substring, which would replace old substring.
new − This is new substring, which would replace old substring.
max − If this optional argument max is given, only the first count occurrences are replaced.
max − If this optional argument max is given, only the first count occurrences are replaced.
This method returns a copy of the string with all occurrences of substring old replaced by new. If the optional argument max is given, only the first count occurrences are replaced.
The following example shows the usage of replace() method.
str = "this is string example....wow!!! this is really string"
print (str.replace("is", "was"))
print (str.replace("is", "was", 3))
When we run above program, it produces the following result −
thwas was string example....wow!!! thwas was really string
thwas was string example....wow!!! thwas is really string
import re
sourceline = re.compile("Tutor", re.IGNORECASE)
Replacedline = sourceline.sub("Tutor","Tutorialspoint has the best tutorials for learning.")
print (Replacedline)
When we run the above program, we get the following output −
Tutorialspoint has the best Tutorials for learning.
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2857,
"s": 2587,
"text": "Replacing the complete string or a part of string is a very frequent requirement in text processing. The replace() method returns a copy of the string in which the occurrences of old have been replaced with new, optionally restricting the number of replacements to max."
},
{
"code": null,
"e": 2904,
"s": 2857,
"text": "Following is the syntax for replace() method −"
},
{
"code": null,
"e": 2933,
"s": 2904,
"text": "str.replace(old, new[, max])"
},
{
"code": null,
"e": 2977,
"s": 2933,
"text": "old − This is old substring to be replaced."
},
{
"code": null,
"e": 3021,
"s": 2977,
"text": "old − This is old substring to be replaced."
},
{
"code": null,
"e": 3085,
"s": 3021,
"text": "new − This is new substring, which would replace old substring."
},
{
"code": null,
"e": 3149,
"s": 3085,
"text": "new − This is new substring, which would replace old substring."
},
{
"code": null,
"e": 3242,
"s": 3149,
"text": "max − If this optional argument max is given, only the first count occurrences are replaced."
},
{
"code": null,
"e": 3335,
"s": 3242,
"text": "max − If this optional argument max is given, only the first count occurrences are replaced."
},
{
"code": null,
"e": 3517,
"s": 3335,
"text": "This method returns a copy of the string with all occurrences of substring old replaced by new. If the optional argument max is given, only the first count occurrences are replaced."
},
{
"code": null,
"e": 3576,
"s": 3517,
"text": "The following example shows the usage of replace() method."
},
{
"code": null,
"e": 3708,
"s": 3576,
"text": "str = \"this is string example....wow!!! this is really string\"\nprint (str.replace(\"is\", \"was\"))\nprint (str.replace(\"is\", \"was\", 3))"
},
{
"code": null,
"e": 3770,
"s": 3708,
"text": "When we run above program, it produces the following result −"
},
{
"code": null,
"e": 3888,
"s": 3770,
"text": "thwas was string example....wow!!! thwas was really string\nthwas was string example....wow!!! thwas is really string\n"
},
{
"code": null,
"e": 4067,
"s": 3890,
"text": "import re\nsourceline = re.compile(\"Tutor\", re.IGNORECASE)\n \nReplacedline = sourceline.sub(\"Tutor\",\"Tutorialspoint has the best tutorials for learning.\")\nprint (Replacedline)\n"
},
{
"code": null,
"e": 4128,
"s": 4067,
"text": "When we run the above program, we get the following output −"
},
{
"code": null,
"e": 4181,
"s": 4128,
"text": "Tutorialspoint has the best Tutorials for learning.\n"
},
{
"code": null,
"e": 4218,
"s": 4181,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 4234,
"s": 4218,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4267,
"s": 4234,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 4286,
"s": 4267,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4321,
"s": 4286,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 4343,
"s": 4321,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 4377,
"s": 4343,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 4405,
"s": 4377,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4440,
"s": 4405,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 4454,
"s": 4440,
"text": " Lets Kode It"
},
{
"code": null,
"e": 4487,
"s": 4454,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4504,
"s": 4487,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 4511,
"s": 4504,
"text": " Print"
},
{
"code": null,
"e": 4522,
"s": 4511,
"text": " Add Notes"
}
] |
BERT: Sentiment Analysis of App Store Review | by Ng Wai Foong | Towards Data Science
|
Utilizing state-of-the-art model to analyze users’ sentiments from app store
This article provides you with the necessary steps to perform sentiment analysis on the reviews made by the public user at app store. In this tutorial, I will be using Bert-Base Chinese model instead to test out the performance of BERT when being applied to languages other than English. The steps for sentiment analysis are still the same regardless of which model that you are using. If you are unsure of which model to use, check out the following link for more information on the pre-trained model provided by the BERT team. If you are new to BERT, kindly check out my previous tutorial on Multi-Classifications Task using BERT. There are 5 sections in this tutorial:
Dataset PreparationTrainingPredictionResultsConclusion
Dataset Preparation
Training
Prediction
Results
Conclusion
I will be using the reviews from Taptap, which is a games app store catered for the Chinese market. Feel free to use your own dataset. You can even test it out on the reviews from Google Play Store and iOS Apple Store. If that is the case, make sure that you are using the English model for BERT. Let’s have a look at the details that we can obtain from the review in Taptap.
There are quite a lot of useful data here:
Comment posted by the user
Rating from 1 to 5
Count for thumbs up
Count for thumbs down
Replies from the other users to this comment
We can easily use the data available to do labeling for the sentiments. Labeling manually by hand is strongly recommended if you have the time. In this case, I am going to use the rating to determine the label.
Negative: 1–3 ⭐Neutral: 4 ⭐Positive: 5 ⭐
Negative: 1–3 ⭐
Neutral: 4 ⭐
Positive: 5 ⭐
I managed to collect quite a lot of dataset based on the users’ reviews from several games. I have loaded the dataset into three dataframes.
Train datasetEvaluation datasetTest dataset
Train dataset
Evaluation dataset
Test dataset
Let’s have a look at the content of the data for train and evaluation. Both of them share the same structure.
Guid: Id for comment.
Label: Sentiments for the comment. Labeling is based on the rating from user.
Alpha: Throwaway column. I just filled it with a.
Text: The actual comment from user.
If you have trouble in creating the dataframe above, feel free to use the following code (modify it accordingly):
df_bert = pd.DataFrame({'guid': id_list, 'label': label_list, 'alpha': ['a']*len(count), 'text': text_list})
The test data will be slightly different as it should only contains the guid and text.
Once you are done, let’s save it as tsv file using the following code (modify the name of the dataframe accordingly):
df_bert_train.to_csv('data/train.tsv', sep='\t', index=False, header=False)df_bert_dev.to_csv('data/dev.tsv', sep='\t', index=False, header=False)df_bert_test.to_csv('data/test.tsv', sep='\t', index=False, header=True)
Please be noted that the files are stored in the data folder. Feel free to modify it based on your use case but the name of the files must be as follow:
train.tsv
dev.tsv
test.tsv
Besides, the test.tsv data must have a header unlike the train.tsv and dev.tsv. Set the header to True for test.tsv.
Let’s move on to the next section once you are done with the data preparation.
We will now start to train and fine-tune the model. Make sure that you have cloned the repository from the official site. Moreover, you should have the following files and folders located somewhere inside the repository:
Data directory: The directory where you stored train.tsv, dev.tsv and test.tsv
Vocab file: The vocab.txt file. It comes together with the model that you have downloaded. I created a new model folder and put the file inside it.
Config file: The config.json file. It is also included together with the model. Likewise, I put it inside the model folder.
Initial model: The model to be used for training. You can use the pre-trained based model or resume from an existing model that you have fine-tuned. I am storing it inside the model folder
Output directory: The folder in which the model will be written to. You can simply create an empty folder for it.
The next part is to determine the following variables:
Max sequence length: The maximum total input sequence length after WordPiece tokenization. Sequences longer than this will be truncated, and sequences shorter will be padded. Default is 128 but I will be using 256 in this tutorial.
Train batch size: Total batch size for training. Default is 32. I will be using 8 in this tutorial since I am training on just one GeForce RTX 2080.
Learning rate: Initial learning rate for Adam. Default is 5e-5. I have set the value to 2e-5.
Num train epoch: Total number of training epochs to perform. I will just use the default value of 3.0
If you are unsure about which GPU to use, kindly run the following command to find it out:
nvidia-smi
We need to modify the code in the run_classifier.py since we have 3 classes for this use case. Open up the python file and search for the get_labels() function inside the ColaProcessor(DataProcessor) class. Change it to the following and save it:
def get_labels(self): """See base class.""" return ["0", "1", "2"]
Once you are done, activate the virtual environment and change the directory to the root of the repository. Type the following command in the terminal.
CUDA_VISIBLE_DEVICES=0 python run_classifier.py --task_name=cola --do_train=true --do_eval=true --data_dir=./data/ --vocab_file=./model/vocab.txt --bert_config_file=./model/bert_config.json --init_checkpoint=./model/bert_model.ckpt --max_seq_length=256 --train_batch_size=8 --learning_rate=2e-5 --num_train_epochs=3.0 --output_dir=./output/ --do_lower_case=False
Run it and you should see the following output:
It may take quite some time for it to train depends on the size of dataset that you used. The terminal will output the following once the training has been completed.
Let’s move on to the next step.
A model will be generated at the output folder. Kindly check the highest number of steps to identify the latest model that you have. If you are unsure of which model is the latest, open the checkpoint file to find out. In my case, I have 37125 as the last step for the model.
In the same terminal, run the following code (make sure that the max sequence length is the same as what you have used during the training):
CUDA_VISIBLE_DEVICES=0 python run_classifier.py --task_name=cola --do_predict=true --data_dir=./data/ --vocab_file=./model/vocab.txt --bert_config_file=./model/bert_config.json --init_checkpoint=./output/model.ckpt-37125 --max_seq_length=256 --output_dir=./output/
The code will generate a test_results.tsv file at the output folder. In my case, I got the following results.
Each columns represents the probabilities or confidence level of class predicted with the highest being the class predicted by the model.
It is time for us to analyze the results. The first task is to load the test_results.tsv and convert it into dataframe based on the highest predicted probabilities. Read the file with the following code:
df_result = pd.read_csv('output/test_results.tsv', sep='\t', header=None)df_result.head()
You should have a dataframe for the test data with three columns (I named it df_test_with_label):
guid
label
text
Create a new dataframe and map the result using idxmax.
df_predict = pd.DataFrame({'guid':df_test_with_label['guid'], 'label':df_result.idxmax(axis=1), 'text':df_test_with_label['text'],})df_predict.head()
Once you are done, let’s import the following metrics function from sklearn to calculate the performance of our model.
from sklearn.metrics import accuracy_score, precision_score, recall_score, confusion_matrix
You can calculate the accuracy of the model as follow.
accuracy_score(df_test_with_label['label'], df_predict['label'])
I got 0.7033952594490711 as the result.
Based on the sklearn documentation. The recall is the ratio tp / (tp + fn) where tp is the number of true positives and fn the number of false negatives. The recall is intuitively the ability of the classifier to find all the positive samples. The best value is 1 and the worst value is 0. It also requires a parameter called average. I am setting it to macro.
recall_score(df_test_with_label['label'], df_predict['label'], average='macro')
Running the code resulted in 0.6312777479889565 as the output.
The precision is the ratio tp / (tp + fp) where tp is the number of true positives and fp the number of false positives. The precision is intuitively the ability of the classifier not to label as positive a sample that is negative. The best value is 1 and the worst value is 0. Likewise, the average parameter is set to macro.
precision_score(df_test_with_label['label'], df_predict['label'], average='macro')
The precision is a little lower than recall at just 0.6303571005505256.
Having just recall and precision is not good enough as we don’t know which class has the best prediction and which class got the worst results. We can use the confusion matrix method to provide us with more insight on this.
confusion_matrix(df_test_with_label['label'], df_predict['label'])
I got the following output.
We can see that the model have some difficulties in predicting the second label (Neutral). In this case, we might need to make some modification to our dataset and try to re-train it again.
Congratulations for completing this tutorial. Let’s recap on what we have learned today.
First, we started with preparing the dataset for our sentiment analysis project. This includes obtaining the data and labeling it automatically based on the details provided. In our case, we use the app review rating as the label for the sentiment. We finalized it into three classes, namely Negative, Neutral and Positive. We generated three tsv files from the dataset.
Next, we configured the required parameters such as max sequence length and batch size. We trained the model and used it to do prediction on the test data.
Finally, we loaded the results into a dataframe and analyzed it using the metrics functions from sklearn. The insights provided allows us to determine the performance of our model.
Thanks for reading and hope you enjoyed this tutorial. See you again in the next article. Have a great day ahead! ❤️
|
[
{
"code": null,
"e": 124,
"s": 47,
"text": "Utilizing state-of-the-art model to analyze users’ sentiments from app store"
},
{
"code": null,
"e": 796,
"s": 124,
"text": "This article provides you with the necessary steps to perform sentiment analysis on the reviews made by the public user at app store. In this tutorial, I will be using Bert-Base Chinese model instead to test out the performance of BERT when being applied to languages other than English. The steps for sentiment analysis are still the same regardless of which model that you are using. If you are unsure of which model to use, check out the following link for more information on the pre-trained model provided by the BERT team. If you are new to BERT, kindly check out my previous tutorial on Multi-Classifications Task using BERT. There are 5 sections in this tutorial:"
},
{
"code": null,
"e": 851,
"s": 796,
"text": "Dataset PreparationTrainingPredictionResultsConclusion"
},
{
"code": null,
"e": 871,
"s": 851,
"text": "Dataset Preparation"
},
{
"code": null,
"e": 880,
"s": 871,
"text": "Training"
},
{
"code": null,
"e": 891,
"s": 880,
"text": "Prediction"
},
{
"code": null,
"e": 899,
"s": 891,
"text": "Results"
},
{
"code": null,
"e": 910,
"s": 899,
"text": "Conclusion"
},
{
"code": null,
"e": 1286,
"s": 910,
"text": "I will be using the reviews from Taptap, which is a games app store catered for the Chinese market. Feel free to use your own dataset. You can even test it out on the reviews from Google Play Store and iOS Apple Store. If that is the case, make sure that you are using the English model for BERT. Let’s have a look at the details that we can obtain from the review in Taptap."
},
{
"code": null,
"e": 1329,
"s": 1286,
"text": "There are quite a lot of useful data here:"
},
{
"code": null,
"e": 1356,
"s": 1329,
"text": "Comment posted by the user"
},
{
"code": null,
"e": 1375,
"s": 1356,
"text": "Rating from 1 to 5"
},
{
"code": null,
"e": 1395,
"s": 1375,
"text": "Count for thumbs up"
},
{
"code": null,
"e": 1417,
"s": 1395,
"text": "Count for thumbs down"
},
{
"code": null,
"e": 1462,
"s": 1417,
"text": "Replies from the other users to this comment"
},
{
"code": null,
"e": 1673,
"s": 1462,
"text": "We can easily use the data available to do labeling for the sentiments. Labeling manually by hand is strongly recommended if you have the time. In this case, I am going to use the rating to determine the label."
},
{
"code": null,
"e": 1714,
"s": 1673,
"text": "Negative: 1–3 ⭐Neutral: 4 ⭐Positive: 5 ⭐"
},
{
"code": null,
"e": 1730,
"s": 1714,
"text": "Negative: 1–3 ⭐"
},
{
"code": null,
"e": 1743,
"s": 1730,
"text": "Neutral: 4 ⭐"
},
{
"code": null,
"e": 1757,
"s": 1743,
"text": "Positive: 5 ⭐"
},
{
"code": null,
"e": 1898,
"s": 1757,
"text": "I managed to collect quite a lot of dataset based on the users’ reviews from several games. I have loaded the dataset into three dataframes."
},
{
"code": null,
"e": 1942,
"s": 1898,
"text": "Train datasetEvaluation datasetTest dataset"
},
{
"code": null,
"e": 1956,
"s": 1942,
"text": "Train dataset"
},
{
"code": null,
"e": 1975,
"s": 1956,
"text": "Evaluation dataset"
},
{
"code": null,
"e": 1988,
"s": 1975,
"text": "Test dataset"
},
{
"code": null,
"e": 2098,
"s": 1988,
"text": "Let’s have a look at the content of the data for train and evaluation. Both of them share the same structure."
},
{
"code": null,
"e": 2120,
"s": 2098,
"text": "Guid: Id for comment."
},
{
"code": null,
"e": 2198,
"s": 2120,
"text": "Label: Sentiments for the comment. Labeling is based on the rating from user."
},
{
"code": null,
"e": 2248,
"s": 2198,
"text": "Alpha: Throwaway column. I just filled it with a."
},
{
"code": null,
"e": 2284,
"s": 2248,
"text": "Text: The actual comment from user."
},
{
"code": null,
"e": 2398,
"s": 2284,
"text": "If you have trouble in creating the dataframe above, feel free to use the following code (modify it accordingly):"
},
{
"code": null,
"e": 2516,
"s": 2398,
"text": "df_bert = pd.DataFrame({'guid': id_list, 'label': label_list, 'alpha': ['a']*len(count), 'text': text_list})"
},
{
"code": null,
"e": 2603,
"s": 2516,
"text": "The test data will be slightly different as it should only contains the guid and text."
},
{
"code": null,
"e": 2721,
"s": 2603,
"text": "Once you are done, let’s save it as tsv file using the following code (modify the name of the dataframe accordingly):"
},
{
"code": null,
"e": 2940,
"s": 2721,
"text": "df_bert_train.to_csv('data/train.tsv', sep='\\t', index=False, header=False)df_bert_dev.to_csv('data/dev.tsv', sep='\\t', index=False, header=False)df_bert_test.to_csv('data/test.tsv', sep='\\t', index=False, header=True)"
},
{
"code": null,
"e": 3093,
"s": 2940,
"text": "Please be noted that the files are stored in the data folder. Feel free to modify it based on your use case but the name of the files must be as follow:"
},
{
"code": null,
"e": 3103,
"s": 3093,
"text": "train.tsv"
},
{
"code": null,
"e": 3111,
"s": 3103,
"text": "dev.tsv"
},
{
"code": null,
"e": 3120,
"s": 3111,
"text": "test.tsv"
},
{
"code": null,
"e": 3237,
"s": 3120,
"text": "Besides, the test.tsv data must have a header unlike the train.tsv and dev.tsv. Set the header to True for test.tsv."
},
{
"code": null,
"e": 3316,
"s": 3237,
"text": "Let’s move on to the next section once you are done with the data preparation."
},
{
"code": null,
"e": 3537,
"s": 3316,
"text": "We will now start to train and fine-tune the model. Make sure that you have cloned the repository from the official site. Moreover, you should have the following files and folders located somewhere inside the repository:"
},
{
"code": null,
"e": 3616,
"s": 3537,
"text": "Data directory: The directory where you stored train.tsv, dev.tsv and test.tsv"
},
{
"code": null,
"e": 3764,
"s": 3616,
"text": "Vocab file: The vocab.txt file. It comes together with the model that you have downloaded. I created a new model folder and put the file inside it."
},
{
"code": null,
"e": 3888,
"s": 3764,
"text": "Config file: The config.json file. It is also included together with the model. Likewise, I put it inside the model folder."
},
{
"code": null,
"e": 4077,
"s": 3888,
"text": "Initial model: The model to be used for training. You can use the pre-trained based model or resume from an existing model that you have fine-tuned. I am storing it inside the model folder"
},
{
"code": null,
"e": 4191,
"s": 4077,
"text": "Output directory: The folder in which the model will be written to. You can simply create an empty folder for it."
},
{
"code": null,
"e": 4246,
"s": 4191,
"text": "The next part is to determine the following variables:"
},
{
"code": null,
"e": 4478,
"s": 4246,
"text": "Max sequence length: The maximum total input sequence length after WordPiece tokenization. Sequences longer than this will be truncated, and sequences shorter will be padded. Default is 128 but I will be using 256 in this tutorial."
},
{
"code": null,
"e": 4627,
"s": 4478,
"text": "Train batch size: Total batch size for training. Default is 32. I will be using 8 in this tutorial since I am training on just one GeForce RTX 2080."
},
{
"code": null,
"e": 4721,
"s": 4627,
"text": "Learning rate: Initial learning rate for Adam. Default is 5e-5. I have set the value to 2e-5."
},
{
"code": null,
"e": 4823,
"s": 4721,
"text": "Num train epoch: Total number of training epochs to perform. I will just use the default value of 3.0"
},
{
"code": null,
"e": 4914,
"s": 4823,
"text": "If you are unsure about which GPU to use, kindly run the following command to find it out:"
},
{
"code": null,
"e": 4925,
"s": 4914,
"text": "nvidia-smi"
},
{
"code": null,
"e": 5172,
"s": 4925,
"text": "We need to modify the code in the run_classifier.py since we have 3 classes for this use case. Open up the python file and search for the get_labels() function inside the ColaProcessor(DataProcessor) class. Change it to the following and save it:"
},
{
"code": null,
"e": 5245,
"s": 5172,
"text": "def get_labels(self): \"\"\"See base class.\"\"\" return [\"0\", \"1\", \"2\"]"
},
{
"code": null,
"e": 5397,
"s": 5245,
"text": "Once you are done, activate the virtual environment and change the directory to the root of the repository. Type the following command in the terminal."
},
{
"code": null,
"e": 5760,
"s": 5397,
"text": "CUDA_VISIBLE_DEVICES=0 python run_classifier.py --task_name=cola --do_train=true --do_eval=true --data_dir=./data/ --vocab_file=./model/vocab.txt --bert_config_file=./model/bert_config.json --init_checkpoint=./model/bert_model.ckpt --max_seq_length=256 --train_batch_size=8 --learning_rate=2e-5 --num_train_epochs=3.0 --output_dir=./output/ --do_lower_case=False"
},
{
"code": null,
"e": 5808,
"s": 5760,
"text": "Run it and you should see the following output:"
},
{
"code": null,
"e": 5975,
"s": 5808,
"text": "It may take quite some time for it to train depends on the size of dataset that you used. The terminal will output the following once the training has been completed."
},
{
"code": null,
"e": 6007,
"s": 5975,
"text": "Let’s move on to the next step."
},
{
"code": null,
"e": 6283,
"s": 6007,
"text": "A model will be generated at the output folder. Kindly check the highest number of steps to identify the latest model that you have. If you are unsure of which model is the latest, open the checkpoint file to find out. In my case, I have 37125 as the last step for the model."
},
{
"code": null,
"e": 6424,
"s": 6283,
"text": "In the same terminal, run the following code (make sure that the max sequence length is the same as what you have used during the training):"
},
{
"code": null,
"e": 6689,
"s": 6424,
"text": "CUDA_VISIBLE_DEVICES=0 python run_classifier.py --task_name=cola --do_predict=true --data_dir=./data/ --vocab_file=./model/vocab.txt --bert_config_file=./model/bert_config.json --init_checkpoint=./output/model.ckpt-37125 --max_seq_length=256 --output_dir=./output/"
},
{
"code": null,
"e": 6799,
"s": 6689,
"text": "The code will generate a test_results.tsv file at the output folder. In my case, I got the following results."
},
{
"code": null,
"e": 6937,
"s": 6799,
"text": "Each columns represents the probabilities or confidence level of class predicted with the highest being the class predicted by the model."
},
{
"code": null,
"e": 7141,
"s": 6937,
"text": "It is time for us to analyze the results. The first task is to load the test_results.tsv and convert it into dataframe based on the highest predicted probabilities. Read the file with the following code:"
},
{
"code": null,
"e": 7231,
"s": 7141,
"text": "df_result = pd.read_csv('output/test_results.tsv', sep='\\t', header=None)df_result.head()"
},
{
"code": null,
"e": 7329,
"s": 7231,
"text": "You should have a dataframe for the test data with three columns (I named it df_test_with_label):"
},
{
"code": null,
"e": 7334,
"s": 7329,
"text": "guid"
},
{
"code": null,
"e": 7340,
"s": 7334,
"text": "label"
},
{
"code": null,
"e": 7345,
"s": 7340,
"text": "text"
},
{
"code": null,
"e": 7401,
"s": 7345,
"text": "Create a new dataframe and map the result using idxmax."
},
{
"code": null,
"e": 7605,
"s": 7401,
"text": "df_predict = pd.DataFrame({'guid':df_test_with_label['guid'], 'label':df_result.idxmax(axis=1), 'text':df_test_with_label['text'],})df_predict.head()"
},
{
"code": null,
"e": 7724,
"s": 7605,
"text": "Once you are done, let’s import the following metrics function from sklearn to calculate the performance of our model."
},
{
"code": null,
"e": 7816,
"s": 7724,
"text": "from sklearn.metrics import accuracy_score, precision_score, recall_score, confusion_matrix"
},
{
"code": null,
"e": 7871,
"s": 7816,
"text": "You can calculate the accuracy of the model as follow."
},
{
"code": null,
"e": 7936,
"s": 7871,
"text": "accuracy_score(df_test_with_label['label'], df_predict['label'])"
},
{
"code": null,
"e": 7976,
"s": 7936,
"text": "I got 0.7033952594490711 as the result."
},
{
"code": null,
"e": 8337,
"s": 7976,
"text": "Based on the sklearn documentation. The recall is the ratio tp / (tp + fn) where tp is the number of true positives and fn the number of false negatives. The recall is intuitively the ability of the classifier to find all the positive samples. The best value is 1 and the worst value is 0. It also requires a parameter called average. I am setting it to macro."
},
{
"code": null,
"e": 8417,
"s": 8337,
"text": "recall_score(df_test_with_label['label'], df_predict['label'], average='macro')"
},
{
"code": null,
"e": 8480,
"s": 8417,
"text": "Running the code resulted in 0.6312777479889565 as the output."
},
{
"code": null,
"e": 8807,
"s": 8480,
"text": "The precision is the ratio tp / (tp + fp) where tp is the number of true positives and fp the number of false positives. The precision is intuitively the ability of the classifier not to label as positive a sample that is negative. The best value is 1 and the worst value is 0. Likewise, the average parameter is set to macro."
},
{
"code": null,
"e": 8890,
"s": 8807,
"text": "precision_score(df_test_with_label['label'], df_predict['label'], average='macro')"
},
{
"code": null,
"e": 8962,
"s": 8890,
"text": "The precision is a little lower than recall at just 0.6303571005505256."
},
{
"code": null,
"e": 9186,
"s": 8962,
"text": "Having just recall and precision is not good enough as we don’t know which class has the best prediction and which class got the worst results. We can use the confusion matrix method to provide us with more insight on this."
},
{
"code": null,
"e": 9253,
"s": 9186,
"text": "confusion_matrix(df_test_with_label['label'], df_predict['label'])"
},
{
"code": null,
"e": 9281,
"s": 9253,
"text": "I got the following output."
},
{
"code": null,
"e": 9471,
"s": 9281,
"text": "We can see that the model have some difficulties in predicting the second label (Neutral). In this case, we might need to make some modification to our dataset and try to re-train it again."
},
{
"code": null,
"e": 9560,
"s": 9471,
"text": "Congratulations for completing this tutorial. Let’s recap on what we have learned today."
},
{
"code": null,
"e": 9931,
"s": 9560,
"text": "First, we started with preparing the dataset for our sentiment analysis project. This includes obtaining the data and labeling it automatically based on the details provided. In our case, we use the app review rating as the label for the sentiment. We finalized it into three classes, namely Negative, Neutral and Positive. We generated three tsv files from the dataset."
},
{
"code": null,
"e": 10087,
"s": 9931,
"text": "Next, we configured the required parameters such as max sequence length and batch size. We trained the model and used it to do prediction on the test data."
},
{
"code": null,
"e": 10268,
"s": 10087,
"text": "Finally, we loaded the results into a dataframe and analyzed it using the metrics functions from sklearn. The insights provided allows us to determine the performance of our model."
}
] |
C Program For Making Middle Node Head In A Linked List - GeeksforGeeks
|
13 Jan, 2022
Given a singly linked list, find middle of the linked list and set middle node of the linked list at beginning of the linked list. Examples:
Input: 1 2 3 4 5
Output: 3 1 2 4 5
Input: 1 2 3 4 5 6
Output: 4 1 2 3 5 6
The idea is to first find middle of a linked list using two pointers, first one moves one at a time and second one moves two at a time. When second pointer reaches end, first reaches middle. We also keep track of previous of first pointer so that we can remove middle node from its current position and can make it head.
C
// C program to make middle node as // head of linked list.#include <stdio.h>#include <stdlib.h> // Link list node struct Node { int data; struct Node* next;}; /* Function to get the middle and set at beginning of the linked list*/void setMiddleHead(struct Node** head){ if (*head == NULL) return; // To traverse list nodes one by one struct Node* one_node = (*head); // To traverse list nodes by skipping // one. struct Node* two_node = (*head); // To keep track of previous of middle struct Node* prev = NULL; while (two_node != NULL && two_node->next != NULL) { // For previous node of middle node prev = one_node; // Move one node each time two_node = two_node->next->next; // Move two node each time one_node = one_node->next; } // Set middle node at head prev->next = prev->next->next; one_node->next = (*head); (*head) = one_node;} // To insert a node at the beginning // of linked list.void push(struct Node** head_ref, int new_data){ // Allocate node struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); 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;} // A function to print a given linked listvoid printList(struct Node* ptr){ while (ptr != NULL) { printf("%d ", ptr->data); ptr = ptr->next; } printf("");} // Driver codeint main(){ // Create a list of 5 nodes struct Node* head = NULL; int i; for (i = 5; i > 0; i--) push(&head, i); printf(" list before: "); printList(head); setMiddleHead(&head); printf(" list After: "); printList(head); return 0;}
Output:
list before: 1 2 3 4 5
list After : 3 1 2 4 5
Please refer complete article on Make middle node head in a linked list for more details!
Tortoise-Hare-Approach
C Programs
Linked List
Misc
Misc
Linked List
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C Program to read contents of Whole File
Producer Consumer Problem in C
C program to find the length of a string
Exit codes in C/C++ with Examples
Difference between break and continue statement in C
Linked List | Set 1 (Introduction)
Linked List | Set 2 (Inserting a node)
Reverse a linked list
Stack Data Structure (Introduction and Program)
Linked List | Set 3 (Deleting a node)
|
[
{
"code": null,
"e": 24617,
"s": 24589,
"text": "\n13 Jan, 2022"
},
{
"code": null,
"e": 24758,
"s": 24617,
"text": "Given a singly linked list, find middle of the linked list and set middle node of the linked list at beginning of the linked list. Examples:"
},
{
"code": null,
"e": 24835,
"s": 24758,
"text": "Input: 1 2 3 4 5 \nOutput: 3 1 2 4 5\n\nInput: 1 2 3 4 5 6\nOutput: 4 1 2 3 5 6 "
},
{
"code": null,
"e": 25157,
"s": 24835,
"text": "The idea is to first find middle of a linked list using two pointers, first one moves one at a time and second one moves two at a time. When second pointer reaches end, first reaches middle. We also keep track of previous of first pointer so that we can remove middle node from its current position and can make it head. "
},
{
"code": null,
"e": 25159,
"s": 25157,
"text": "C"
},
{
"code": "// C program to make middle node as // head of linked list.#include <stdio.h>#include <stdlib.h> // Link list node struct Node { int data; struct Node* next;}; /* Function to get the middle and set at beginning of the linked list*/void setMiddleHead(struct Node** head){ if (*head == NULL) return; // To traverse list nodes one by one struct Node* one_node = (*head); // To traverse list nodes by skipping // one. struct Node* two_node = (*head); // To keep track of previous of middle struct Node* prev = NULL; while (two_node != NULL && two_node->next != NULL) { // For previous node of middle node prev = one_node; // Move one node each time two_node = two_node->next->next; // Move two node each time one_node = one_node->next; } // Set middle node at head prev->next = prev->next->next; one_node->next = (*head); (*head) = one_node;} // To insert a node at the beginning // of linked list.void push(struct Node** head_ref, int new_data){ // Allocate node struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); 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;} // A function to print a given linked listvoid printList(struct Node* ptr){ while (ptr != NULL) { printf(\"%d \", ptr->data); ptr = ptr->next; } printf(\"\");} // Driver codeint main(){ // Create a list of 5 nodes struct Node* head = NULL; int i; for (i = 5; i > 0; i--) push(&head, i); printf(\" list before: \"); printList(head); setMiddleHead(&head); printf(\" list After: \"); printList(head); return 0;}",
"e": 27012,
"s": 25159,
"text": null
},
{
"code": null,
"e": 27020,
"s": 27012,
"text": "Output:"
},
{
"code": null,
"e": 27067,
"s": 27020,
"text": "list before: 1 2 3 4 5\nlist After : 3 1 2 4 5 "
},
{
"code": null,
"e": 27157,
"s": 27067,
"text": "Please refer complete article on Make middle node head in a linked list for more details!"
},
{
"code": null,
"e": 27180,
"s": 27157,
"text": "Tortoise-Hare-Approach"
},
{
"code": null,
"e": 27191,
"s": 27180,
"text": "C Programs"
},
{
"code": null,
"e": 27203,
"s": 27191,
"text": "Linked List"
},
{
"code": null,
"e": 27208,
"s": 27203,
"text": "Misc"
},
{
"code": null,
"e": 27213,
"s": 27208,
"text": "Misc"
},
{
"code": null,
"e": 27225,
"s": 27213,
"text": "Linked List"
},
{
"code": null,
"e": 27230,
"s": 27225,
"text": "Misc"
},
{
"code": null,
"e": 27328,
"s": 27230,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27337,
"s": 27328,
"text": "Comments"
},
{
"code": null,
"e": 27350,
"s": 27337,
"text": "Old Comments"
},
{
"code": null,
"e": 27391,
"s": 27350,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 27422,
"s": 27391,
"text": "Producer Consumer Problem in C"
},
{
"code": null,
"e": 27463,
"s": 27422,
"text": "C program to find the length of a string"
},
{
"code": null,
"e": 27497,
"s": 27463,
"text": "Exit codes in C/C++ with Examples"
},
{
"code": null,
"e": 27550,
"s": 27497,
"text": "Difference between break and continue statement in C"
},
{
"code": null,
"e": 27585,
"s": 27550,
"text": "Linked List | Set 1 (Introduction)"
},
{
"code": null,
"e": 27624,
"s": 27585,
"text": "Linked List | Set 2 (Inserting a node)"
},
{
"code": null,
"e": 27646,
"s": 27624,
"text": "Reverse a linked list"
},
{
"code": null,
"e": 27694,
"s": 27646,
"text": "Stack Data Structure (Introduction and Program)"
}
] |
Ascii() in python
|
ASCII is abbreviated from of American Standard Code for Information Interchange. It is a character encoding standard. For example the ASCII value of English alphabet A is 65. Python provides this function to get the printable representation of an object. It takes one parameter which is an object that can be a list, strings, tuple etc. The output of the function is the hex representation. The non-ascii characters can be escaped using \x, \u or \U escapes.
The syntax is −
Syntax:
ascii(object)
Printing strings with individual characters and multiple characters.
# Individual Characters
print(ascii("Ω"))
print(ascii("θ"))
# A string int multiple characters
print(ascii("TΨtΦrial"))
Running the above code gives us the following result −
'\u03a9'
'\u03b8'
'T\u03a8t\u03a6rial'
|
[
{
"code": null,
"e": 1521,
"s": 1062,
"text": "ASCII is abbreviated from of American Standard Code for Information Interchange. It is a character encoding standard. For example the ASCII value of English alphabet A is 65. Python provides this function to get the printable representation of an object. It takes one parameter which is an object that can be a list, strings, tuple etc. The output of the function is the hex representation. The non-ascii characters can be escaped using \\x, \\u or \\U escapes."
},
{
"code": null,
"e": 1537,
"s": 1521,
"text": "The syntax is −"
},
{
"code": null,
"e": 1559,
"s": 1537,
"text": "Syntax:\nascii(object)"
},
{
"code": null,
"e": 1628,
"s": 1559,
"text": "Printing strings with individual characters and multiple characters."
},
{
"code": null,
"e": 1748,
"s": 1628,
"text": "# Individual Characters\nprint(ascii(\"Ω\"))\nprint(ascii(\"θ\"))\n# A string int multiple characters\nprint(ascii(\"TΨtΦrial\"))"
},
{
"code": null,
"e": 1803,
"s": 1748,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 1842,
"s": 1803,
"text": "'\\u03a9'\n'\\u03b8'\n'T\\u03a8t\\u03a6rial'"
}
] |
PHP date_interval_format() Function
|
The date_interval_format() function is an alias of DateInterval::format(). This function accepts an interval and a format string as parameters and, formats the given interval in the specified format.
date_interval_format($interval, $format)
interval (Mandatory)
This is an object of the DateInterval you need to format.
format (Mandatory)
This is a string value, specifying the format.
This function returns the formatted interval
This function was first introduced in PHP Version 5.3 and, works with all the later versions.
Following example demonstrates the usage of the date_interval_create_from_date_string() function −
<?php
$interval = new DateInterval('P25DP8MP9Y');
$format = "%d days;
$res = date_interval_format($interval, $format);
print($res);
?>
This will produce following result −
25 days
Unlike other date/time functions date_interval_format() doesn't recalculate carry over points in date and time strings. Therefore if you pass date/time values beyond their boundaries, they will be formatted as it is −
<?php
$interval = new DateInterval('P45M');
$format = "%m months";
$res1 = date_interval_format($interval, $format);
print($res1);
$res2 = date_interval_format(new DateInterval('PT30H'), "%h hours");
print("\n".$res2);
?>
This will produce following result −
45 months
30 hours
Following example calculates the difference between a given date and the current date and formats the result using the date_interval_format function −
<?php
$date1 = date_create("25-09-1989");
$date2 = date_create("1-09-2012");
$interval = date_diff($date1, $date2);
$res = date_interval_format($interval, '%Y years %d days');
print($res);
?>
<?php
print(date_interval_format(new DateInterval('P12D'), "%d days")."\n");
print(date_interval_format(new DateInterval('P7M'), "%m months")."\n");
print(date_interval_format(new DateInterval('P12Y'), "%y years")."\n");
print(date_interval_format(new DateInterval('PT9H'), "%h hours")."\n");
print(date_interval_format(new DateInterval('PT45S'), "%s seconds")."\n");
?>
This will produce following result −
22 years 7 days
12 days
7 months
12 years
9 hours
45 seconds
45 Lectures
9 hours
Malhar Lathkar
34 Lectures
4 hours
Syed Raza
84 Lectures
5.5 hours
Frahaan Hussain
17 Lectures
1 hours
Nivedita Jain
100 Lectures
34 hours
Azaz Patel
43 Lectures
5.5 hours
Vijay Kumar Parvatha Reddy
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2957,
"s": 2757,
"text": "The date_interval_format() function is an alias of DateInterval::format(). This function accepts an interval and a format string as parameters and, formats the given interval in the specified format."
},
{
"code": null,
"e": 2999,
"s": 2957,
"text": "date_interval_format($interval, $format)\n"
},
{
"code": null,
"e": 3020,
"s": 2999,
"text": "interval (Mandatory)"
},
{
"code": null,
"e": 3078,
"s": 3020,
"text": "This is an object of the DateInterval you need to format."
},
{
"code": null,
"e": 3097,
"s": 3078,
"text": "format (Mandatory)"
},
{
"code": null,
"e": 3144,
"s": 3097,
"text": "This is a string value, specifying the format."
},
{
"code": null,
"e": 3189,
"s": 3144,
"text": "This function returns the formatted interval"
},
{
"code": null,
"e": 3283,
"s": 3189,
"text": "This function was first introduced in PHP Version 5.3 and, works with all the later versions."
},
{
"code": null,
"e": 3382,
"s": 3283,
"text": "Following example demonstrates the usage of the date_interval_create_from_date_string() function −"
},
{
"code": null,
"e": 3527,
"s": 3382,
"text": "<?php\n $interval = new DateInterval('P25DP8MP9Y');\n $format = \"%d days;\n $res = date_interval_format($interval, $format);\n print($res); \n?>"
},
{
"code": null,
"e": 3564,
"s": 3527,
"text": "This will produce following result −"
},
{
"code": null,
"e": 3573,
"s": 3564,
"text": "25 days\n"
},
{
"code": null,
"e": 3792,
"s": 3573,
"text": "Unlike other date/time functions date_interval_format() doesn't recalculate carry over points in date and time strings. Therefore if you pass date/time values beyond their boundaries, they will be formatted as it is −"
},
{
"code": null,
"e": 4036,
"s": 3792,
"text": "<?php\n $interval = new DateInterval('P45M');\n $format = \"%m months\";\n $res1 = date_interval_format($interval, $format);\n print($res1); \n \n $res2 = date_interval_format(new DateInterval('PT30H'), \"%h hours\");\n print(\"\\n\".$res2);\n?>"
},
{
"code": null,
"e": 4073,
"s": 4036,
"text": "This will produce following result −"
},
{
"code": null,
"e": 4093,
"s": 4073,
"text": "45 months\n30 hours\n"
},
{
"code": null,
"e": 4244,
"s": 4093,
"text": "Following example calculates the difference between a given date and the current date and formats the result using the date_interval_format function −"
},
{
"code": null,
"e": 4454,
"s": 4244,
"text": "<?php\n $date1 = date_create(\"25-09-1989\");\n $date2 = date_create(\"1-09-2012\");\n $interval = date_diff($date1, $date2);\n $res = date_interval_format($interval, '%Y years %d days');\n print($res); \n\n?>"
},
{
"code": null,
"e": 4825,
"s": 4454,
"text": "<?php\nprint(date_interval_format(new DateInterval('P12D'), \"%d days\").\"\\n\");\nprint(date_interval_format(new DateInterval('P7M'), \"%m months\").\"\\n\");\nprint(date_interval_format(new DateInterval('P12Y'), \"%y years\").\"\\n\");\nprint(date_interval_format(new DateInterval('PT9H'), \"%h hours\").\"\\n\");\nprint(date_interval_format(new DateInterval('PT45S'), \"%s seconds\").\"\\n\");\n?>"
},
{
"code": null,
"e": 4862,
"s": 4825,
"text": "This will produce following result −"
},
{
"code": null,
"e": 4924,
"s": 4862,
"text": "22 years 7 days\n12 days\n7 months\n12 years\n9 hours\n45 seconds\n"
},
{
"code": null,
"e": 4957,
"s": 4924,
"text": "\n 45 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 4973,
"s": 4957,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 5006,
"s": 4973,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5017,
"s": 5006,
"text": " Syed Raza"
},
{
"code": null,
"e": 5052,
"s": 5017,
"text": "\n 84 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 5069,
"s": 5052,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5102,
"s": 5069,
"text": "\n 17 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5117,
"s": 5102,
"text": " Nivedita Jain"
},
{
"code": null,
"e": 5152,
"s": 5117,
"text": "\n 100 Lectures \n 34 hours \n"
},
{
"code": null,
"e": 5164,
"s": 5152,
"text": " Azaz Patel"
},
{
"code": null,
"e": 5199,
"s": 5164,
"text": "\n 43 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 5227,
"s": 5199,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 5234,
"s": 5227,
"text": " Print"
},
{
"code": null,
"e": 5245,
"s": 5234,
"text": " Add Notes"
}
] |
Spelling Correction: How to make an accurate and fast corrector | by Filipp Bakanov | Towards Data Science
|
Dirty data leads to bad model quality. In real-world NLP problems we often meet texts with a lot of typos. As the result, we are unable to reach the best score. As painful as it may be, data should be cleaned before fitting.
We need an automatic spelling corrector which can fix words with typos and, at the same time not break correct spellings.
But how can we achieve this?
Let start with a Norvig’s spelling corrector and iteratively increase its capabilities.
Peter Norvig (director of research at Google) described the following approach to spelling correction.
Let’s take a word and brute force all possible edits, such as delete, insert, transpose, replace and split. Eg. for word abc possible candidates will be: ab ac bc bac cba acb a_bc ab_c aabc abbc acbc adbc aebc etc.
Every word is added to a candidate list. We repeat this procedure for every word for a second time to get candidates with bigger edit distance (for cases with two errors).
Each candidate is estimated with unigram language model. For each vocabulary word frequencies are pre-calculated, based on some big text collections. The candidate word with highest frequency is taken as an answer.
First improvement — adding n-gram language model (3-grams). Let’s pre-calculate not only single words, but word and a small context (3 nearest words). Let’s estimate probability of some fragment as a product of all n-grams of n-size:
To make everything simple let’s calculate probability of n-gram of size n as a product of probabilities of all lower order grams (actually there are some smoothing technics, like Kneser–Ney — they improve model’s accuracy, but let’s talk about it later, see “Improve Accuracy” paragraph below):
To get a probability of n-gram from appearance frequencies we need to normalize frequencies (eg. divide number of 3-grams by number of 2-grams, etc.):
Now we can use our extended language model to estimate candidates with context.
Sentence probability can be calculated like this:
def predict(self, sentence): result = 0 for i in range(0, len(sentence) - 2): p2 = self.getGram3Prob(sentence[i], sentence[i + 1], sentence[i + 2]) p3 = self.getGram2Prob(sentence[i], sentence[i + 1]) p4 = self.getGram1Prob(sentence[i]) result += math.log(p2) + math.log(p3) + math.log(p4) return result
And n-gram probabilities like this:
def getGram1Prob(self, wordID): wordCounts = self.gram1.get(wordID, 0) + SimpleLangModel.K vocabSize = len(self.gram1) return float(wordCounts) / (self.totalWords + vocabSize)def getGram2Prob(self, wordID1, wordID2): countsWord1 = self.gram1.get(wordID1, 0) + self.totalWords countsBigram = self.gram2.get((wordID1, wordID2), 0) + SimpleLangModel.K return float(countsBigram) / countsWord1def getGram3Prob(self, wordID1, wordID2, wordID3): countsGram2 = self.gram2.get((wordID1, wordID2), 0) + self.totalWords countsGram3 = self.gram3.get((wordID1, wordID2, wordID3), 0) + SimpleLangModel.K return float(countsGram3) / countsGram2
Now we got a much better accuracy. However, model become really huge, and everything works so slow. For 600 Mb train text we got:
To improve speed — let’s use an idea from SymSpell. Idea is quite elegant. Instead of generating all possible edits each time we met incorrect word — we can pre-calculate all delete typos (and other typos derived from deletes). You can read more details in the original article.
Obviously, we wouldn’t be able to achieve as high speed as the original (because we use a language model and look at the context, and not only single word), but we can improve performance significantly. The cost is additional memory consumption:
To get the best possible accuracy we need a big dataset (at least few gigabytes). Training n-gram model on 600 mb file leads to significant memory consumption (25 Gb). Half of that size is used by language model, and another half by the symspell index.
One reason of such a high memory usage is that we don’t store a plain text, instead we store frequencies. For example, for following text of 5 words: “a b c a b” we store following frequencies:
a => 2b => 2c => 1a b => 2b c => 1c a => 1a b c => 1b c a => 1c a b => 1
Another reason — high memory overhead of the hash table data structure (hash table is used inside python dict or c++ unordered_map).
To compress our n-gram model let’s use an approach described in Efficient Minimal Perfect Hash Language Models paper. Let’s use a perfect hash (Compress, Hash and Displace) to store n-gram counts. Perfect hash is a hash which guarantees no collisions. Without collisions it’s possible to store only values (count frequencies) and not the original n-grams. To ensure that unknown words hash wouldn’t match the existing one we will use a bloom filter with known words. Also we can use a nonlinear quantization to pack a 32 bit long count frequencies into a 16 bit values. This does not affect the final metrics but reduces memory usage.
Quantization:
static const uint32_t MAX_REAL_NUM = 268435456;static const uint32_t MAX_AVAILABLE_NUM = 65536;uint16_t PackInt32(uint32_t num) { double r = double(num) / double(MAX_REAL_NUM); assert(r >= 0.0 && r <= 1.0); r = pow(r, 0.2); r *= MAX_AVAILABLE_NUM; return uint16_t(r);}uint32_t UnpackInt32(uint16_t num) { double r = double(num) / double(MAX_AVAILABLE_NUM); r = pow(r, 5.0); r *= MAX_REAL_NUM; return uint32_t(ceil(r));}
Count frequencies extraction:
template<typename T>TCount GetGramHashCount(T key, const TPerfectHash& ph, const std::vector<uint16_t>& buckets, TBloomFilter& filter){ constexpr int TMP_BUF_SIZE = 128; static char tmpBuff[TMP_BUF_SIZE]; static MemStream tmpBuffStream(tmpBuff, TMP_BUF_SIZE - 1); static std::ostream out(&tmpBuffStream); tmpBuffStream.Reset(); NHandyPack::Dump(out, key); if (!filter.Contains(tmpBuff, tmpBuffStream.Size())) { return TCount(); } uint32_t bucket = ph.Hash(tmpBuff, tmpBuffStream.Size()); assert(bucket < ph.BucketsNumber()); return UnpackInt32(buckets[bucket]);}
First we check if key exists in bloom filter. And then we get counts based on perfect hash bucket number.
To compress a symspell index let’s use a Bloom filter. A Bloom filter is a space-efficient probabilistic data structure that is used to test whether an element is a member of a set. Let’s put all delete hashes into a bloom filter and use this index to skip non-existing candidates.
Here is a modified second step of the symspell algorithm. Here we take candidate words, that were previously generated by removing a single or multiple letters from original word, and check each word if it contains in index or not. Deletes1 and Deletes2 are the bloom filters.
TWords CheckCandidate(const std::wstring& s){ TWords results; if (Deletes1->Contains(w)) { Inserts(w, results); } if (Deletes2->Contains(w)) { Inserts2(w, results); }}void TSpellCorrector::Inserts(const std::wstring& w, TWords& result) const { for (size_t i = 0; i < w.size() + 1; ++i) { for (auto&& ch: LangModel.GetAlphabet()) { std::wstring s = w.substr(0, i) + ch + w.substr(i); TWord c = LangModel.GetWord(s); if (!c.Empty()) { result.push_back(c); } } }}void TSpellCorrector::Inserts2(const std::wstring& w, TWords& result) const { for (size_t i = 0; i < w.size() + 1; ++i) { for (auto&& ch: LangModel.GetAlphabet()) { std::wstring s = w.substr(0, i) + ch + w.substr(i); if (Deletes1->Contains(WideToUTF8(s))) { Inserts(s, result); } } }}
After this optimization model size was reduced significantly, down to 800 Mb:
To improve accuracy let’s add a several machine learning classifiers. First one will be used to make the decision whether the word has error or not. Second one, regressor, will be used for candidates ranking. This classifier partly plays a role of language model smoothing (it gets all grams as a separate input and a classifier makes a decision how much impact each gram has).
For candidates ranking we will train a catboost (gradient boosted decision trees) ranking model with following features:
word frequency
n-grams frequencies, separate for each gram (2, 3)
frequencies of nearby words with distance 3, 4
n-gram model prediction
edit distance between candidate and a source word
number of candidates with better edit distance
words length
word existence in a clean static dictionary
from catboost import CatBoostparams = { 'loss_function': 'PairLogit', 'iterations': 400, 'learning_rate': 0.1, 'depth': 8, 'verbose': False, 'random_seed': 42, 'early_stopping_rounds': 50, 'border_count': 64, 'leaf_estimation_backtracking': 'AnyImprovement', 'leaf_estimation_iterations': 2, 'leaf_estimation_method': 'Newton', 'task_type': 'CPU' }model = CatBoost(params, ) model.fit(trainX, trainY, pairs=trainPairs, group_id=groupIDs, eval_set=evalPool, verbose=1)
For error prediction we will train a binary classifier. Let’s use the same features calculated for each word of the original word, and let the classifier decide if the word has error or not. That will gives an ability to detect an error depends on context, even for dictionary words.
from catboost import CatBoostClassifiermodel = CatBoostClassifier( iterations=400, learning_rate=0.3, depth=8)model.fit(trainX, trainY, sample_weight=trainWeight, verbose=False)
This improves accuracy even more, however, it’s not free, we get reduced performance. Still, for most applications this performance is more than enough, and accuracy usually more important.
To evaluate a model we need some datasets. We can generate an artificial errors based on a clean text. Also we can use public datasets — one of them is a SpellRuEval dataset. Let’s check accuracy both on a couple of artificial datasets and a real one. We will use some alternative spell checkers from giant IT companies to compare with. Here jamspell is our spell checker and we got the following metrics:
errRate — number of errors left in text after performing automatic correction
fixRate — number of fixed errors
broken — number of correct words that were broken
pr, re, f1 — precision, recall, f1 score
Next steps to improve accuracy — gathering a large parallel corpus of texts (separate for mobile and desktop platforms) with errors and corrected texts and training a dedicated error models.
Another possible way to improve accuracy is to add dynamic learning option. We can learn on flight while making corrections, or we can make a two-passes correction. At the first pass model will learn some statistics and at the second pass make an actual correction.
Also a neural-network language models (bidirectional LSTM or BERT) may give some additional accuracy boost. They didn’t work well with a straight forward approach (LSTM errors classifier, seq-2-seq LSTM model, using BERT outputs as a candidates ranking weights) but may be their predictions will be useful as features in a rank model / error detector.
Here is some details about approaches that we were unable to make working (doesn’t mean that they can’t work — it just our experience).
We trained BERT and tried to use it for predicting the best candidate.
from transformers import RobertaConfig, RobertaTokenizerFast, RobertaForMaskedLM, LineByLineTextDataset, DataCollatorForLanguageModelingconfig = RobertaConfig( vocab_size=52_000, max_position_embeddings=514, num_attention_heads=12, num_hidden_layers=6, type_vocab_size=1,)dataset = LineByLineTextDataset( tokenizer=tokenizer, file_path=TRAIN_TEXT_FILE, block_size=128,)from transformers importdata_collator = DataCollatorForLanguageModeling( tokenizer=tokenizer, mlm=True, mlm_probability=0.15)from transformers import Trainer, TrainingArgumentstraining_args = TrainingArguments( output_dir="~/transformers", overwrite_output_dir=True, num_train_epochs=3, per_gpu_train_batch_size=32, save_steps=10_000, save_total_limit=2,)trainer = Trainer( model=model, args=training_args, data_collator=data_collator, train_dataset=dataset, prediction_loss_only=False,)trainer.train()
It worked superior to n-gram language model for masked word prediction task (30% accuracy for BERT model, and 20% accuracy for n-gram model), but it performed worse while selecting best word from a list of candidate words. Our hypothesis that it’s due to the fact that BERT knows nothing about edit distance or matching with original word. We believe that adding BERT prediction as a feature for catboost ranking model can give accuracy boost.
We tried to use LSTM as an error detector (to predict if word has error or not), but our best possible result was ~same as a regular n-gram language model errors predictor + manual heuristics. And training time was much bigger, so we decided not to use it for now. Here is a model that gave the best score. Input is word level GloVe embeddings, trained on the same file.
Model: "functional_1"_________________________________________________________________Layer (type) Output Shape Param # =================================================================input_1 (InputLayer) [(None, 9, 200)] 0 _________________________________________________________________bidirectional (Bidirectional (None, 9, 1800) 7927200 _________________________________________________________________dropout (Dropout) (None, 9, 1800) 0 _________________________________________________________________attention (Attention) (None, 1800) 1809 _________________________________________________________________dense (Dense) (None, 724) 1303924 _________________________________________________________________dropout_1 (Dropout) (None, 724) 0 _________________________________________________________________batch_normalization (BatchNo (None, 724) 2896 _________________________________________________________________dense_1 (Dense) (None, 2) 1450 =================================================================Total params: 9,237,279Trainable params: 9,235,831Non-trainable params: 1,448_________________________________________________________________None
We started from very simple model and iteratively increase it’s capabilities, and finally we get a strong, production level spell checker. Still, it’s not the end, there is a lot of steps on the long road to our goal — making the best possible spell checker in the world.
|
[
{
"code": null,
"e": 272,
"s": 47,
"text": "Dirty data leads to bad model quality. In real-world NLP problems we often meet texts with a lot of typos. As the result, we are unable to reach the best score. As painful as it may be, data should be cleaned before fitting."
},
{
"code": null,
"e": 394,
"s": 272,
"text": "We need an automatic spelling corrector which can fix words with typos and, at the same time not break correct spellings."
},
{
"code": null,
"e": 423,
"s": 394,
"text": "But how can we achieve this?"
},
{
"code": null,
"e": 511,
"s": 423,
"text": "Let start with a Norvig’s spelling corrector and iteratively increase its capabilities."
},
{
"code": null,
"e": 614,
"s": 511,
"text": "Peter Norvig (director of research at Google) described the following approach to spelling correction."
},
{
"code": null,
"e": 829,
"s": 614,
"text": "Let’s take a word and brute force all possible edits, such as delete, insert, transpose, replace and split. Eg. for word abc possible candidates will be: ab ac bc bac cba acb a_bc ab_c aabc abbc acbc adbc aebc etc."
},
{
"code": null,
"e": 1001,
"s": 829,
"text": "Every word is added to a candidate list. We repeat this procedure for every word for a second time to get candidates with bigger edit distance (for cases with two errors)."
},
{
"code": null,
"e": 1216,
"s": 1001,
"text": "Each candidate is estimated with unigram language model. For each vocabulary word frequencies are pre-calculated, based on some big text collections. The candidate word with highest frequency is taken as an answer."
},
{
"code": null,
"e": 1450,
"s": 1216,
"text": "First improvement — adding n-gram language model (3-grams). Let’s pre-calculate not only single words, but word and a small context (3 nearest words). Let’s estimate probability of some fragment as a product of all n-grams of n-size:"
},
{
"code": null,
"e": 1745,
"s": 1450,
"text": "To make everything simple let’s calculate probability of n-gram of size n as a product of probabilities of all lower order grams (actually there are some smoothing technics, like Kneser–Ney — they improve model’s accuracy, but let’s talk about it later, see “Improve Accuracy” paragraph below):"
},
{
"code": null,
"e": 1896,
"s": 1745,
"text": "To get a probability of n-gram from appearance frequencies we need to normalize frequencies (eg. divide number of 3-grams by number of 2-grams, etc.):"
},
{
"code": null,
"e": 1976,
"s": 1896,
"text": "Now we can use our extended language model to estimate candidates with context."
},
{
"code": null,
"e": 2026,
"s": 1976,
"text": "Sentence probability can be calculated like this:"
},
{
"code": null,
"e": 2367,
"s": 2026,
"text": "def predict(self, sentence): result = 0 for i in range(0, len(sentence) - 2): p2 = self.getGram3Prob(sentence[i], sentence[i + 1], sentence[i + 2]) p3 = self.getGram2Prob(sentence[i], sentence[i + 1]) p4 = self.getGram1Prob(sentence[i]) result += math.log(p2) + math.log(p3) + math.log(p4) return result"
},
{
"code": null,
"e": 2403,
"s": 2367,
"text": "And n-gram probabilities like this:"
},
{
"code": null,
"e": 3061,
"s": 2403,
"text": "def getGram1Prob(self, wordID): wordCounts = self.gram1.get(wordID, 0) + SimpleLangModel.K vocabSize = len(self.gram1) return float(wordCounts) / (self.totalWords + vocabSize)def getGram2Prob(self, wordID1, wordID2): countsWord1 = self.gram1.get(wordID1, 0) + self.totalWords countsBigram = self.gram2.get((wordID1, wordID2), 0) + SimpleLangModel.K return float(countsBigram) / countsWord1def getGram3Prob(self, wordID1, wordID2, wordID3): countsGram2 = self.gram2.get((wordID1, wordID2), 0) + self.totalWords countsGram3 = self.gram3.get((wordID1, wordID2, wordID3), 0) + SimpleLangModel.K return float(countsGram3) / countsGram2"
},
{
"code": null,
"e": 3191,
"s": 3061,
"text": "Now we got a much better accuracy. However, model become really huge, and everything works so slow. For 600 Mb train text we got:"
},
{
"code": null,
"e": 3470,
"s": 3191,
"text": "To improve speed — let’s use an idea from SymSpell. Idea is quite elegant. Instead of generating all possible edits each time we met incorrect word — we can pre-calculate all delete typos (and other typos derived from deletes). You can read more details in the original article."
},
{
"code": null,
"e": 3716,
"s": 3470,
"text": "Obviously, we wouldn’t be able to achieve as high speed as the original (because we use a language model and look at the context, and not only single word), but we can improve performance significantly. The cost is additional memory consumption:"
},
{
"code": null,
"e": 3969,
"s": 3716,
"text": "To get the best possible accuracy we need a big dataset (at least few gigabytes). Training n-gram model on 600 mb file leads to significant memory consumption (25 Gb). Half of that size is used by language model, and another half by the symspell index."
},
{
"code": null,
"e": 4163,
"s": 3969,
"text": "One reason of such a high memory usage is that we don’t store a plain text, instead we store frequencies. For example, for following text of 5 words: “a b c a b” we store following frequencies:"
},
{
"code": null,
"e": 4236,
"s": 4163,
"text": "a => 2b => 2c => 1a b => 2b c => 1c a => 1a b c => 1b c a => 1c a b => 1"
},
{
"code": null,
"e": 4369,
"s": 4236,
"text": "Another reason — high memory overhead of the hash table data structure (hash table is used inside python dict or c++ unordered_map)."
},
{
"code": null,
"e": 5004,
"s": 4369,
"text": "To compress our n-gram model let’s use an approach described in Efficient Minimal Perfect Hash Language Models paper. Let’s use a perfect hash (Compress, Hash and Displace) to store n-gram counts. Perfect hash is a hash which guarantees no collisions. Without collisions it’s possible to store only values (count frequencies) and not the original n-grams. To ensure that unknown words hash wouldn’t match the existing one we will use a bloom filter with known words. Also we can use a nonlinear quantization to pack a 32 bit long count frequencies into a 16 bit values. This does not affect the final metrics but reduces memory usage."
},
{
"code": null,
"e": 5018,
"s": 5004,
"text": "Quantization:"
},
{
"code": null,
"e": 5465,
"s": 5018,
"text": "static const uint32_t MAX_REAL_NUM = 268435456;static const uint32_t MAX_AVAILABLE_NUM = 65536;uint16_t PackInt32(uint32_t num) { double r = double(num) / double(MAX_REAL_NUM); assert(r >= 0.0 && r <= 1.0); r = pow(r, 0.2); r *= MAX_AVAILABLE_NUM; return uint16_t(r);}uint32_t UnpackInt32(uint16_t num) { double r = double(num) / double(MAX_AVAILABLE_NUM); r = pow(r, 5.0); r *= MAX_REAL_NUM; return uint32_t(ceil(r));}"
},
{
"code": null,
"e": 5495,
"s": 5465,
"text": "Count frequencies extraction:"
},
{
"code": null,
"e": 6167,
"s": 5495,
"text": "template<typename T>TCount GetGramHashCount(T key, const TPerfectHash& ph, const std::vector<uint16_t>& buckets, TBloomFilter& filter){ constexpr int TMP_BUF_SIZE = 128; static char tmpBuff[TMP_BUF_SIZE]; static MemStream tmpBuffStream(tmpBuff, TMP_BUF_SIZE - 1); static std::ostream out(&tmpBuffStream); tmpBuffStream.Reset(); NHandyPack::Dump(out, key); if (!filter.Contains(tmpBuff, tmpBuffStream.Size())) { return TCount(); } uint32_t bucket = ph.Hash(tmpBuff, tmpBuffStream.Size()); assert(bucket < ph.BucketsNumber()); return UnpackInt32(buckets[bucket]);}"
},
{
"code": null,
"e": 6273,
"s": 6167,
"text": "First we check if key exists in bloom filter. And then we get counts based on perfect hash bucket number."
},
{
"code": null,
"e": 6555,
"s": 6273,
"text": "To compress a symspell index let’s use a Bloom filter. A Bloom filter is a space-efficient probabilistic data structure that is used to test whether an element is a member of a set. Let’s put all delete hashes into a bloom filter and use this index to skip non-existing candidates."
},
{
"code": null,
"e": 6832,
"s": 6555,
"text": "Here is a modified second step of the symspell algorithm. Here we take candidate words, that were previously generated by removing a single or multiple letters from original word, and check each word if it contains in index or not. Deletes1 and Deletes2 are the bloom filters."
},
{
"code": null,
"e": 7753,
"s": 6832,
"text": "TWords CheckCandidate(const std::wstring& s){ TWords results; if (Deletes1->Contains(w)) { Inserts(w, results); } if (Deletes2->Contains(w)) { Inserts2(w, results); }}void TSpellCorrector::Inserts(const std::wstring& w, TWords& result) const { for (size_t i = 0; i < w.size() + 1; ++i) { for (auto&& ch: LangModel.GetAlphabet()) { std::wstring s = w.substr(0, i) + ch + w.substr(i); TWord c = LangModel.GetWord(s); if (!c.Empty()) { result.push_back(c); } } }}void TSpellCorrector::Inserts2(const std::wstring& w, TWords& result) const { for (size_t i = 0; i < w.size() + 1; ++i) { for (auto&& ch: LangModel.GetAlphabet()) { std::wstring s = w.substr(0, i) + ch + w.substr(i); if (Deletes1->Contains(WideToUTF8(s))) { Inserts(s, result); } } }}"
},
{
"code": null,
"e": 7831,
"s": 7753,
"text": "After this optimization model size was reduced significantly, down to 800 Mb:"
},
{
"code": null,
"e": 8209,
"s": 7831,
"text": "To improve accuracy let’s add a several machine learning classifiers. First one will be used to make the decision whether the word has error or not. Second one, regressor, will be used for candidates ranking. This classifier partly plays a role of language model smoothing (it gets all grams as a separate input and a classifier makes a decision how much impact each gram has)."
},
{
"code": null,
"e": 8330,
"s": 8209,
"text": "For candidates ranking we will train a catboost (gradient boosted decision trees) ranking model with following features:"
},
{
"code": null,
"e": 8345,
"s": 8330,
"text": "word frequency"
},
{
"code": null,
"e": 8396,
"s": 8345,
"text": "n-grams frequencies, separate for each gram (2, 3)"
},
{
"code": null,
"e": 8443,
"s": 8396,
"text": "frequencies of nearby words with distance 3, 4"
},
{
"code": null,
"e": 8467,
"s": 8443,
"text": "n-gram model prediction"
},
{
"code": null,
"e": 8517,
"s": 8467,
"text": "edit distance between candidate and a source word"
},
{
"code": null,
"e": 8564,
"s": 8517,
"text": "number of candidates with better edit distance"
},
{
"code": null,
"e": 8577,
"s": 8564,
"text": "words length"
},
{
"code": null,
"e": 8621,
"s": 8577,
"text": "word existence in a clean static dictionary"
},
{
"code": null,
"e": 9179,
"s": 8621,
"text": "from catboost import CatBoostparams = { 'loss_function': 'PairLogit', 'iterations': 400, 'learning_rate': 0.1, 'depth': 8, 'verbose': False, 'random_seed': 42, 'early_stopping_rounds': 50, 'border_count': 64, 'leaf_estimation_backtracking': 'AnyImprovement', 'leaf_estimation_iterations': 2, 'leaf_estimation_method': 'Newton', 'task_type': 'CPU' }model = CatBoost(params, ) model.fit(trainX, trainY, pairs=trainPairs, group_id=groupIDs, eval_set=evalPool, verbose=1)"
},
{
"code": null,
"e": 9463,
"s": 9179,
"text": "For error prediction we will train a binary classifier. Let’s use the same features calculated for each word of the original word, and let the classifier decide if the word has error or not. That will gives an ability to detect an error depends on context, even for dictionary words."
},
{
"code": null,
"e": 9650,
"s": 9463,
"text": "from catboost import CatBoostClassifiermodel = CatBoostClassifier( iterations=400, learning_rate=0.3, depth=8)model.fit(trainX, trainY, sample_weight=trainWeight, verbose=False)"
},
{
"code": null,
"e": 9840,
"s": 9650,
"text": "This improves accuracy even more, however, it’s not free, we get reduced performance. Still, for most applications this performance is more than enough, and accuracy usually more important."
},
{
"code": null,
"e": 10246,
"s": 9840,
"text": "To evaluate a model we need some datasets. We can generate an artificial errors based on a clean text. Also we can use public datasets — one of them is a SpellRuEval dataset. Let’s check accuracy both on a couple of artificial datasets and a real one. We will use some alternative spell checkers from giant IT companies to compare with. Here jamspell is our spell checker and we got the following metrics:"
},
{
"code": null,
"e": 10324,
"s": 10246,
"text": "errRate — number of errors left in text after performing automatic correction"
},
{
"code": null,
"e": 10357,
"s": 10324,
"text": "fixRate — number of fixed errors"
},
{
"code": null,
"e": 10407,
"s": 10357,
"text": "broken — number of correct words that were broken"
},
{
"code": null,
"e": 10448,
"s": 10407,
"text": "pr, re, f1 — precision, recall, f1 score"
},
{
"code": null,
"e": 10639,
"s": 10448,
"text": "Next steps to improve accuracy — gathering a large parallel corpus of texts (separate for mobile and desktop platforms) with errors and corrected texts and training a dedicated error models."
},
{
"code": null,
"e": 10905,
"s": 10639,
"text": "Another possible way to improve accuracy is to add dynamic learning option. We can learn on flight while making corrections, or we can make a two-passes correction. At the first pass model will learn some statistics and at the second pass make an actual correction."
},
{
"code": null,
"e": 11257,
"s": 10905,
"text": "Also a neural-network language models (bidirectional LSTM or BERT) may give some additional accuracy boost. They didn’t work well with a straight forward approach (LSTM errors classifier, seq-2-seq LSTM model, using BERT outputs as a candidates ranking weights) but may be their predictions will be useful as features in a rank model / error detector."
},
{
"code": null,
"e": 11393,
"s": 11257,
"text": "Here is some details about approaches that we were unable to make working (doesn’t mean that they can’t work — it just our experience)."
},
{
"code": null,
"e": 11464,
"s": 11393,
"text": "We trained BERT and tried to use it for predicting the best candidate."
},
{
"code": null,
"e": 12396,
"s": 11464,
"text": "from transformers import RobertaConfig, RobertaTokenizerFast, RobertaForMaskedLM, LineByLineTextDataset, DataCollatorForLanguageModelingconfig = RobertaConfig( vocab_size=52_000, max_position_embeddings=514, num_attention_heads=12, num_hidden_layers=6, type_vocab_size=1,)dataset = LineByLineTextDataset( tokenizer=tokenizer, file_path=TRAIN_TEXT_FILE, block_size=128,)from transformers importdata_collator = DataCollatorForLanguageModeling( tokenizer=tokenizer, mlm=True, mlm_probability=0.15)from transformers import Trainer, TrainingArgumentstraining_args = TrainingArguments( output_dir=\"~/transformers\", overwrite_output_dir=True, num_train_epochs=3, per_gpu_train_batch_size=32, save_steps=10_000, save_total_limit=2,)trainer = Trainer( model=model, args=training_args, data_collator=data_collator, train_dataset=dataset, prediction_loss_only=False,)trainer.train()"
},
{
"code": null,
"e": 12840,
"s": 12396,
"text": "It worked superior to n-gram language model for masked word prediction task (30% accuracy for BERT model, and 20% accuracy for n-gram model), but it performed worse while selecting best word from a list of candidate words. Our hypothesis that it’s due to the fact that BERT knows nothing about edit distance or matching with original word. We believe that adding BERT prediction as a feature for catboost ranking model can give accuracy boost."
},
{
"code": null,
"e": 13211,
"s": 12840,
"text": "We tried to use LSTM as an error detector (to predict if word has error or not), but our best possible result was ~same as a regular n-gram language model errors predictor + manual heuristics. And training time was much bigger, so we decided not to use it for now. Here is a model that gave the best score. Input is word level GloVe embeddings, trained on the same file."
},
{
"code": null,
"e": 14614,
"s": 13211,
"text": "Model: \"functional_1\"_________________________________________________________________Layer (type) Output Shape Param # =================================================================input_1 (InputLayer) [(None, 9, 200)] 0 _________________________________________________________________bidirectional (Bidirectional (None, 9, 1800) 7927200 _________________________________________________________________dropout (Dropout) (None, 9, 1800) 0 _________________________________________________________________attention (Attention) (None, 1800) 1809 _________________________________________________________________dense (Dense) (None, 724) 1303924 _________________________________________________________________dropout_1 (Dropout) (None, 724) 0 _________________________________________________________________batch_normalization (BatchNo (None, 724) 2896 _________________________________________________________________dense_1 (Dense) (None, 2) 1450 =================================================================Total params: 9,237,279Trainable params: 9,235,831Non-trainable params: 1,448_________________________________________________________________None"
}
] |
Assessing Annotator Disagreements in Python to Build a Robust Dataset for Machine Learning | by Oliver Price | Towards Data Science
|
As Matthew Honnibal pointed out at his 2018 PyData Berlin talk [1], developing a solid annotation schema and having attentive annotators is one of the building blocks of a successful machine learning model, and an integral part of the workflow. The pyramid below — taken from his slides — shows these as being essential stages prior to model development.
Having recently completed an MSc in Data Analytics and then working closely with a charity in machine learning, what is only now striking me as troubling about the state of formal education is the distinct under-focus on the bottom three building blocks, and an over-focus on the top two blocks. Despite it being troubling, the reason is clear: students aren’t attracted to the gritty pre-machine learning phase. But the fact remains that without an understanding of how to work on what might be less exciting, it simply won’t be possible to build a robust, strong, and reliable machine learning product.
I’ve noticed that explanations of annotation disagreement assessment methods are not confined to a single post on the web, and methods for doing this in Python are not confined to a single library. So in this post we will cover a number of important topics in the annotator agreements space:
Definitions of well-known statistical scores for assessing agreement quality. (The maths can also be found on the relevant Wikipedia pages.)Python implementations of these statistical scores using a new library I wrote, called disagree.How to assess which labels warrant further attention using the same library, introducing the concept of bidisagreements.
Definitions of well-known statistical scores for assessing agreement quality. (The maths can also be found on the relevant Wikipedia pages.)
Python implementations of these statistical scores using a new library I wrote, called disagree.
How to assess which labels warrant further attention using the same library, introducing the concept of bidisagreements.
What is an annotation schema?
Before we can start doing any form of computational learning, we need a data set. In supervised learning, in order for the computer to learn, each instance of our data must have some label. To obtain the labels, we might need a group of people to sit down and manually label each instance of data — these people are annotators. In order to allow people to do this, we must develop and write an annotation schema, advising them on how to correctly label the instances of data.
When multiple annotators label the same instance of data (as is always the case), there might be disagreements about what the label should be. Disagreements amongst annotators are not good, because it means that we cannot effectively allocate instances with labels. If we begin allocating instances of data with labels for which there was significant disagreement, then our machine learning model is in serious danger. This is because the data cannot be relied on, and neither can any model we develop.
Thus, once the data has all been labelled, it is imperative to investigate these cases of disagreement, so that we can gain knowledge and understanding about where disagreements come from.
Remove data with significant disagreements: This leaves us with only data that has been confidently labelled and is reliable.Modify the annotation schema for future use: It could be that it wasn’t written clearly, and we can improve future agreement.Change or merge the label types: Perhaps we were fundamentally wrong about the types of labels that would be useful. Sometimes we need to modify labels to fit annotator capabilities.
Remove data with significant disagreements: This leaves us with only data that has been confidently labelled and is reliable.
Modify the annotation schema for future use: It could be that it wasn’t written clearly, and we can improve future agreement.
Change or merge the label types: Perhaps we were fundamentally wrong about the types of labels that would be useful. Sometimes we need to modify labels to fit annotator capabilities.
In order to run through a number of the most useful (and not-so-useful) methods for quantitatively evaluating the inter-annotator disagreements, I will first show you how to set up the Python ‘disagree’ library. Then I will go through a variety of statistics, combining both mathematical theory and Python implementations.
The ‘disagree’ library
It aims to do a few things:
Provide statistical capabilities for quantitatively assessing annotator disagreements.
Provide statistical capabilities for quantitatively assessing annotator disagreements.
2. Provide visualisations between different annotators.
3. Provide visualisations to see which labels experience the most disagreement.
After observing each of these three points, the three solutions mentioned above can be considered if necessary. First, you need to import the library. Below is every module available, all of which I will demonstrate here:
from disagree import BiDisagreementsfrom disagree import Metrics, Krippendorff
There are two nuances fundamental to disagree. The first is that you need the annotations to be stored in a pandas DataFrame in a specific way. The rows are indexed by the instance of data, and the columns are each annotator’s label for that instance of data. The column headings are the annotator’s names as strings. Labels must be either None, or between 0 and the maximum label. (You have to convert your labels to this format.) So let’s set up an example DataFrame so that this is clear:
example_annotations = {"a": [None, None, None, None, None, 1, 3, 0, 1, 0, 0, 2, 2, None, 2], "b": [0, None, 1, 0, 2, 2, 3, 2, None, None, None, None, None, None, None], "c": [None, None, 1, 0, 2, 3, 3, None, 1, 0, 0, 2, 2, None, 3]}labels = [0, 1, 2, 3]
So in our example we have 3 annotators named “a”, “b”, and “c”, who have collectively labelled 15 instances of data. (The first instance of data is not labelled by “a” and “c”, and is labelled as 0 by “b”.) The dataframe will look like this:
Furthermore, for each instance they had the choice of labels [0, 1, 2, 3]. (In reality, they could have had the choice of [1, 2, 3, 4] or [“cat”, “dog”, “horse”, “cow”], but the labels had to be indexed from zero for use in the library.)
Now we are ready to explore the possible metrics used to assess annotator agreements. Start by setting up the Metrics instance from the metrics module:
mets = metrics.Metrics(df, labels)
Joint Probability
The joint probability is the most simple, and most naïve, method for assessing annotator agreements. It can be used to look at how much one annotator agrees with another.
Essentially, it adds up the number of times annotators 1 and 2 agree, and divides it by the total number of data points that they both labelled.
For our example dataset, we can compute this between two annotators of our choice:
joint_prob = mets.joint_probability("a", "b")print("Joint probability between annotator a and b: {:.3f}".format(joint_prob))Out: Joint probability between annotator a and b: 0.333
Cohen’s kappa
This is a more statistically advanced method than joint probability because it considers the probability of agreeing by chance. It also compares two annotators.
Using the Python library:
cohens = mets.cohens_kappa("a", "b")print("Cohens kappa between annotator a and b: {:.3f}".format(cohens))Out: Cohens kappa between annotator a and b: 0.330
Correlation
Correlation is also an obvious choice! If annotator 1 and annotator 2 have a high correlation, then they are likely to agree on labels. Conversely, a low correlation means that they are unlikely to agree.
spearman = mets.correlation("a", "b", measure="spearman")pearson = mets.correlation("a", "b", measure="pearson")kendall = mets.correlation("a", "b", measure="kendall")print("Spearman's correlation between a and b: {:.3f}".format(spearman[0]))print("Pearson's correlation between a and b: {:.3f}".format(pearson[0]))print("Kendall's correlation between a and b: {:.3f}".format(kendall[0]))Out: Spearman's correlation between a and b: 0.866Out: Pearson's correlation between a and b: 0.945Out: Kendall's correlation between a and b: 0.816
Note that with the correlation measures, a tuple of the correlation and p-value is returned, hence the zero-indexing when printing the result. (This uses the scipy library.)
At this point, you might be thinking the following: “But what if we have more than two annotators? Aren’t these methods pretty useless?” The answer can be both “Yes” and “No”. Yes, they would be useless for assessing global annotator disagreements with respect to making your dataset more robust. However, there are a number of cases when you might want to do this:
Imagine you have 10 annotators, 2 of which sit in a room together, whilst the other 8 sit separately. (Perhaps due to office space.) Following the annotations, you might want to see if there is greater agreement between the two who sat in a room together, since they might have been discussing the labels.
Perhaps you want to see the agreement amongst annotators with the same educational background, relative to groups from another educational background.
Now I will go through a number of more advanced — and arguably the most popular — methods for assessing annotator agreement statistics across any number of annotators. These are more commonly seen in modern machine learning literature.
Fleiss’ kappa
Fleiss’ kappa is an extension of Cohen’s kappa. It extends it by considering the consistency of annotator agreements, as opposed to absolute agreements that Cohen’s kappa looks at. This is a statistically reliable method, and is commonly used in the literature to demonstrate data quality.
In Python:
fleiss = mets.fleiss_kappa()
Krippendorff’s alpha
The final, most computationally expensive, and mathematically messy, is Krippendorff’s alpha. This, along with Fleiss’ kappa, is considered one of the most useful statistics (if not the most useful). (There’s a great example on the Wikipedia page if you want to see manual computation of Krippendorph’s alpha.)
In Python, this is as simple as any of the other statistics:
kripp = Krippendorff(df, labels)alpha = kripp.alpha(data_type="nominal")print("Krippendorff's alpha: {:.3f}".format(alpha))Out: Krippendorff's alpha: 0.647
The reason I reserve Krippendorff’s alpha for a separate class is because there are a few very computationally expensive processes in the initialisation. If there are a large number of annotations (say, 50,000 to 100,000) it would be frustrating to have to initialise Krippendorff alpha data structures when one is not interested in using it. Having said this, it has been implemented in such a way that it doesn’t take long to run anyway.
And there it is — computing an array of useful annotation disagreement statistics in one easy-to-use, compact Python library.
Bidisagreements
Another useful thing to consider is something I like to call bidisagreements. These are the number of times that an instance of data is labelled differently by two different annotators. The reason these are useful is because they allow you to examine where there might be flaws in the labelling system used, or the annotation schema provided to the annotators.
For example, on a given instance of the dataset, the labels [0, 0, 1], or [1, 1, 1, 2], or [1, 3, 1, 3] would each be considered a single bidisagreement. (Rows 8 and 15 are examples of bidisagreements in the dataframe above.) This can be extended to tridisagreements, 4-disagreements, 5-disagreements, and so on.
Using the disagree library, we can examine these cases with the BiDisagreements module, which was imported above.
First, set up the instance:
bidis = BiDisagreements(df, labels)
A useful attribute is the following:
bidis.agreements_summary()Number of instances with:=========================No disagreement: 9Bidisagreement: 2Tridisagreement: 1More disagreements: 0Out[14]: (9, 2, 1, 0)
The output shows that from our example annotations, there are 9 instances of data for which there are no disagreements; 2 instances of data for which there is a bidisagreement; and 1 instance of data for which there is a tridisagreement. (Note that this returns the tuple as the output.) The reason these add up to 12 and not 15 is because in our example dataset, there are 3 instances where at most 1 annotator labelled the instance. These are not included in the computations because any instance of data labelled by 1 annotator should be considered void anyway.
We can also visualise which labels are causing the bidisagreements:
mat = bidis.agreements_matrix(normalise=False)print(mat)[[0. 0. 1. 0.] [0. 0. 0. 0.] [1. 0. 0. 1.] [0. 0. 1. 0.]]
From this matrix, we can see that one bidisagreement stems from label 0 vs label 2, and the other stems from label 2 vs label 3. Using this matrix, you can create a visualisation of your choice — such as something in the form of a confusion matrix using matplotlib: https://www.kaggle.com/grfiv4/plot-a-confusion-matrix.
This final capability is particularly useful when you have very large datasets. Recently, using this on 25,000 annotations across 6,000 data instances, I was able to very quickly identify that almost 650 bidisagreements were coming from just two labels. This allowed me to address these two labels and how they were to be used in the machine learning model, as well as when modifying the annotation schema for future use by annotators.
Future consideration
With bidisagreements, you will have noticed that the library is only capable of showing the the frequency. This has a somewhat significant floor. Imagine the following two sets of labels for two instances of data:
[0, 0, 0, 0, 1][2, 1, 1, 2, 2]
[0, 0, 0, 0, 1]
[2, 1, 1, 2, 2]
Clearly, the first one has much better agreement than the second one, yet disagree considers them equally. It will be interesting to work towards a bidisagreement method that statistically weights the second one as a more significant bidisagreement than the first, and then normalises the bidisagreements matrix accordingly.
Final notes about ‘disagree’
This library is very recent, and is my first implementation of one. (For this reason, I ask you to please excuse the messy version and commit histories.) The full GitHub repo can be found here: https://github.com/o-P-o/disagree.
The repo includes all of the code, as well as Jupyter notebooks with the examples illustrated above. There is also a full documentation in the README file.
Please feel free to raise issues and make suggestions for additional capabilities as well. I will address any of these promptly.
|
[
{
"code": null,
"e": 527,
"s": 172,
"text": "As Matthew Honnibal pointed out at his 2018 PyData Berlin talk [1], developing a solid annotation schema and having attentive annotators is one of the building blocks of a successful machine learning model, and an integral part of the workflow. The pyramid below — taken from his slides — shows these as being essential stages prior to model development."
},
{
"code": null,
"e": 1132,
"s": 527,
"text": "Having recently completed an MSc in Data Analytics and then working closely with a charity in machine learning, what is only now striking me as troubling about the state of formal education is the distinct under-focus on the bottom three building blocks, and an over-focus on the top two blocks. Despite it being troubling, the reason is clear: students aren’t attracted to the gritty pre-machine learning phase. But the fact remains that without an understanding of how to work on what might be less exciting, it simply won’t be possible to build a robust, strong, and reliable machine learning product."
},
{
"code": null,
"e": 1424,
"s": 1132,
"text": "I’ve noticed that explanations of annotation disagreement assessment methods are not confined to a single post on the web, and methods for doing this in Python are not confined to a single library. So in this post we will cover a number of important topics in the annotator agreements space:"
},
{
"code": null,
"e": 1781,
"s": 1424,
"text": "Definitions of well-known statistical scores for assessing agreement quality. (The maths can also be found on the relevant Wikipedia pages.)Python implementations of these statistical scores using a new library I wrote, called disagree.How to assess which labels warrant further attention using the same library, introducing the concept of bidisagreements."
},
{
"code": null,
"e": 1922,
"s": 1781,
"text": "Definitions of well-known statistical scores for assessing agreement quality. (The maths can also be found on the relevant Wikipedia pages.)"
},
{
"code": null,
"e": 2019,
"s": 1922,
"text": "Python implementations of these statistical scores using a new library I wrote, called disagree."
},
{
"code": null,
"e": 2140,
"s": 2019,
"text": "How to assess which labels warrant further attention using the same library, introducing the concept of bidisagreements."
},
{
"code": null,
"e": 2170,
"s": 2140,
"text": "What is an annotation schema?"
},
{
"code": null,
"e": 2646,
"s": 2170,
"text": "Before we can start doing any form of computational learning, we need a data set. In supervised learning, in order for the computer to learn, each instance of our data must have some label. To obtain the labels, we might need a group of people to sit down and manually label each instance of data — these people are annotators. In order to allow people to do this, we must develop and write an annotation schema, advising them on how to correctly label the instances of data."
},
{
"code": null,
"e": 3149,
"s": 2646,
"text": "When multiple annotators label the same instance of data (as is always the case), there might be disagreements about what the label should be. Disagreements amongst annotators are not good, because it means that we cannot effectively allocate instances with labels. If we begin allocating instances of data with labels for which there was significant disagreement, then our machine learning model is in serious danger. This is because the data cannot be relied on, and neither can any model we develop."
},
{
"code": null,
"e": 3338,
"s": 3149,
"text": "Thus, once the data has all been labelled, it is imperative to investigate these cases of disagreement, so that we can gain knowledge and understanding about where disagreements come from."
},
{
"code": null,
"e": 3771,
"s": 3338,
"text": "Remove data with significant disagreements: This leaves us with only data that has been confidently labelled and is reliable.Modify the annotation schema for future use: It could be that it wasn’t written clearly, and we can improve future agreement.Change or merge the label types: Perhaps we were fundamentally wrong about the types of labels that would be useful. Sometimes we need to modify labels to fit annotator capabilities."
},
{
"code": null,
"e": 3897,
"s": 3771,
"text": "Remove data with significant disagreements: This leaves us with only data that has been confidently labelled and is reliable."
},
{
"code": null,
"e": 4023,
"s": 3897,
"text": "Modify the annotation schema for future use: It could be that it wasn’t written clearly, and we can improve future agreement."
},
{
"code": null,
"e": 4206,
"s": 4023,
"text": "Change or merge the label types: Perhaps we were fundamentally wrong about the types of labels that would be useful. Sometimes we need to modify labels to fit annotator capabilities."
},
{
"code": null,
"e": 4529,
"s": 4206,
"text": "In order to run through a number of the most useful (and not-so-useful) methods for quantitatively evaluating the inter-annotator disagreements, I will first show you how to set up the Python ‘disagree’ library. Then I will go through a variety of statistics, combining both mathematical theory and Python implementations."
},
{
"code": null,
"e": 4552,
"s": 4529,
"text": "The ‘disagree’ library"
},
{
"code": null,
"e": 4580,
"s": 4552,
"text": "It aims to do a few things:"
},
{
"code": null,
"e": 4667,
"s": 4580,
"text": "Provide statistical capabilities for quantitatively assessing annotator disagreements."
},
{
"code": null,
"e": 4754,
"s": 4667,
"text": "Provide statistical capabilities for quantitatively assessing annotator disagreements."
},
{
"code": null,
"e": 4810,
"s": 4754,
"text": "2. Provide visualisations between different annotators."
},
{
"code": null,
"e": 4890,
"s": 4810,
"text": "3. Provide visualisations to see which labels experience the most disagreement."
},
{
"code": null,
"e": 5112,
"s": 4890,
"text": "After observing each of these three points, the three solutions mentioned above can be considered if necessary. First, you need to import the library. Below is every module available, all of which I will demonstrate here:"
},
{
"code": null,
"e": 5191,
"s": 5112,
"text": "from disagree import BiDisagreementsfrom disagree import Metrics, Krippendorff"
},
{
"code": null,
"e": 5683,
"s": 5191,
"text": "There are two nuances fundamental to disagree. The first is that you need the annotations to be stored in a pandas DataFrame in a specific way. The rows are indexed by the instance of data, and the columns are each annotator’s label for that instance of data. The column headings are the annotator’s names as strings. Labels must be either None, or between 0 and the maximum label. (You have to convert your labels to this format.) So let’s set up an example DataFrame so that this is clear:"
},
{
"code": null,
"e": 5937,
"s": 5683,
"text": "example_annotations = {\"a\": [None, None, None, None, None, 1, 3, 0, 1, 0, 0, 2, 2, None, 2], \"b\": [0, None, 1, 0, 2, 2, 3, 2, None, None, None, None, None, None, None], \"c\": [None, None, 1, 0, 2, 3, 3, None, 1, 0, 0, 2, 2, None, 3]}labels = [0, 1, 2, 3]"
},
{
"code": null,
"e": 6179,
"s": 5937,
"text": "So in our example we have 3 annotators named “a”, “b”, and “c”, who have collectively labelled 15 instances of data. (The first instance of data is not labelled by “a” and “c”, and is labelled as 0 by “b”.) The dataframe will look like this:"
},
{
"code": null,
"e": 6417,
"s": 6179,
"text": "Furthermore, for each instance they had the choice of labels [0, 1, 2, 3]. (In reality, they could have had the choice of [1, 2, 3, 4] or [“cat”, “dog”, “horse”, “cow”], but the labels had to be indexed from zero for use in the library.)"
},
{
"code": null,
"e": 6569,
"s": 6417,
"text": "Now we are ready to explore the possible metrics used to assess annotator agreements. Start by setting up the Metrics instance from the metrics module:"
},
{
"code": null,
"e": 6604,
"s": 6569,
"text": "mets = metrics.Metrics(df, labels)"
},
{
"code": null,
"e": 6622,
"s": 6604,
"text": "Joint Probability"
},
{
"code": null,
"e": 6794,
"s": 6622,
"text": "The joint probability is the most simple, and most naïve, method for assessing annotator agreements. It can be used to look at how much one annotator agrees with another."
},
{
"code": null,
"e": 6939,
"s": 6794,
"text": "Essentially, it adds up the number of times annotators 1 and 2 agree, and divides it by the total number of data points that they both labelled."
},
{
"code": null,
"e": 7022,
"s": 6939,
"text": "For our example dataset, we can compute this between two annotators of our choice:"
},
{
"code": null,
"e": 7202,
"s": 7022,
"text": "joint_prob = mets.joint_probability(\"a\", \"b\")print(\"Joint probability between annotator a and b: {:.3f}\".format(joint_prob))Out: Joint probability between annotator a and b: 0.333"
},
{
"code": null,
"e": 7216,
"s": 7202,
"text": "Cohen’s kappa"
},
{
"code": null,
"e": 7377,
"s": 7216,
"text": "This is a more statistically advanced method than joint probability because it considers the probability of agreeing by chance. It also compares two annotators."
},
{
"code": null,
"e": 7403,
"s": 7377,
"text": "Using the Python library:"
},
{
"code": null,
"e": 7560,
"s": 7403,
"text": "cohens = mets.cohens_kappa(\"a\", \"b\")print(\"Cohens kappa between annotator a and b: {:.3f}\".format(cohens))Out: Cohens kappa between annotator a and b: 0.330"
},
{
"code": null,
"e": 7572,
"s": 7560,
"text": "Correlation"
},
{
"code": null,
"e": 7777,
"s": 7572,
"text": "Correlation is also an obvious choice! If annotator 1 and annotator 2 have a high correlation, then they are likely to agree on labels. Conversely, a low correlation means that they are unlikely to agree."
},
{
"code": null,
"e": 8314,
"s": 7777,
"text": "spearman = mets.correlation(\"a\", \"b\", measure=\"spearman\")pearson = mets.correlation(\"a\", \"b\", measure=\"pearson\")kendall = mets.correlation(\"a\", \"b\", measure=\"kendall\")print(\"Spearman's correlation between a and b: {:.3f}\".format(spearman[0]))print(\"Pearson's correlation between a and b: {:.3f}\".format(pearson[0]))print(\"Kendall's correlation between a and b: {:.3f}\".format(kendall[0]))Out: Spearman's correlation between a and b: 0.866Out: Pearson's correlation between a and b: 0.945Out: Kendall's correlation between a and b: 0.816"
},
{
"code": null,
"e": 8488,
"s": 8314,
"text": "Note that with the correlation measures, a tuple of the correlation and p-value is returned, hence the zero-indexing when printing the result. (This uses the scipy library.)"
},
{
"code": null,
"e": 8854,
"s": 8488,
"text": "At this point, you might be thinking the following: “But what if we have more than two annotators? Aren’t these methods pretty useless?” The answer can be both “Yes” and “No”. Yes, they would be useless for assessing global annotator disagreements with respect to making your dataset more robust. However, there are a number of cases when you might want to do this:"
},
{
"code": null,
"e": 9160,
"s": 8854,
"text": "Imagine you have 10 annotators, 2 of which sit in a room together, whilst the other 8 sit separately. (Perhaps due to office space.) Following the annotations, you might want to see if there is greater agreement between the two who sat in a room together, since they might have been discussing the labels."
},
{
"code": null,
"e": 9311,
"s": 9160,
"text": "Perhaps you want to see the agreement amongst annotators with the same educational background, relative to groups from another educational background."
},
{
"code": null,
"e": 9547,
"s": 9311,
"text": "Now I will go through a number of more advanced — and arguably the most popular — methods for assessing annotator agreement statistics across any number of annotators. These are more commonly seen in modern machine learning literature."
},
{
"code": null,
"e": 9561,
"s": 9547,
"text": "Fleiss’ kappa"
},
{
"code": null,
"e": 9851,
"s": 9561,
"text": "Fleiss’ kappa is an extension of Cohen’s kappa. It extends it by considering the consistency of annotator agreements, as opposed to absolute agreements that Cohen’s kappa looks at. This is a statistically reliable method, and is commonly used in the literature to demonstrate data quality."
},
{
"code": null,
"e": 9862,
"s": 9851,
"text": "In Python:"
},
{
"code": null,
"e": 9891,
"s": 9862,
"text": "fleiss = mets.fleiss_kappa()"
},
{
"code": null,
"e": 9912,
"s": 9891,
"text": "Krippendorff’s alpha"
},
{
"code": null,
"e": 10223,
"s": 9912,
"text": "The final, most computationally expensive, and mathematically messy, is Krippendorff’s alpha. This, along with Fleiss’ kappa, is considered one of the most useful statistics (if not the most useful). (There’s a great example on the Wikipedia page if you want to see manual computation of Krippendorph’s alpha.)"
},
{
"code": null,
"e": 10284,
"s": 10223,
"text": "In Python, this is as simple as any of the other statistics:"
},
{
"code": null,
"e": 10440,
"s": 10284,
"text": "kripp = Krippendorff(df, labels)alpha = kripp.alpha(data_type=\"nominal\")print(\"Krippendorff's alpha: {:.3f}\".format(alpha))Out: Krippendorff's alpha: 0.647"
},
{
"code": null,
"e": 10880,
"s": 10440,
"text": "The reason I reserve Krippendorff’s alpha for a separate class is because there are a few very computationally expensive processes in the initialisation. If there are a large number of annotations (say, 50,000 to 100,000) it would be frustrating to have to initialise Krippendorff alpha data structures when one is not interested in using it. Having said this, it has been implemented in such a way that it doesn’t take long to run anyway."
},
{
"code": null,
"e": 11006,
"s": 10880,
"text": "And there it is — computing an array of useful annotation disagreement statistics in one easy-to-use, compact Python library."
},
{
"code": null,
"e": 11022,
"s": 11006,
"text": "Bidisagreements"
},
{
"code": null,
"e": 11383,
"s": 11022,
"text": "Another useful thing to consider is something I like to call bidisagreements. These are the number of times that an instance of data is labelled differently by two different annotators. The reason these are useful is because they allow you to examine where there might be flaws in the labelling system used, or the annotation schema provided to the annotators."
},
{
"code": null,
"e": 11696,
"s": 11383,
"text": "For example, on a given instance of the dataset, the labels [0, 0, 1], or [1, 1, 1, 2], or [1, 3, 1, 3] would each be considered a single bidisagreement. (Rows 8 and 15 are examples of bidisagreements in the dataframe above.) This can be extended to tridisagreements, 4-disagreements, 5-disagreements, and so on."
},
{
"code": null,
"e": 11810,
"s": 11696,
"text": "Using the disagree library, we can examine these cases with the BiDisagreements module, which was imported above."
},
{
"code": null,
"e": 11838,
"s": 11810,
"text": "First, set up the instance:"
},
{
"code": null,
"e": 11874,
"s": 11838,
"text": "bidis = BiDisagreements(df, labels)"
},
{
"code": null,
"e": 11911,
"s": 11874,
"text": "A useful attribute is the following:"
},
{
"code": null,
"e": 12083,
"s": 11911,
"text": "bidis.agreements_summary()Number of instances with:=========================No disagreement: 9Bidisagreement: 2Tridisagreement: 1More disagreements: 0Out[14]: (9, 2, 1, 0)"
},
{
"code": null,
"e": 12648,
"s": 12083,
"text": "The output shows that from our example annotations, there are 9 instances of data for which there are no disagreements; 2 instances of data for which there is a bidisagreement; and 1 instance of data for which there is a tridisagreement. (Note that this returns the tuple as the output.) The reason these add up to 12 and not 15 is because in our example dataset, there are 3 instances where at most 1 annotator labelled the instance. These are not included in the computations because any instance of data labelled by 1 annotator should be considered void anyway."
},
{
"code": null,
"e": 12716,
"s": 12648,
"text": "We can also visualise which labels are causing the bidisagreements:"
},
{
"code": null,
"e": 12831,
"s": 12716,
"text": "mat = bidis.agreements_matrix(normalise=False)print(mat)[[0. 0. 1. 0.] [0. 0. 0. 0.] [1. 0. 0. 1.] [0. 0. 1. 0.]]"
},
{
"code": null,
"e": 13152,
"s": 12831,
"text": "From this matrix, we can see that one bidisagreement stems from label 0 vs label 2, and the other stems from label 2 vs label 3. Using this matrix, you can create a visualisation of your choice — such as something in the form of a confusion matrix using matplotlib: https://www.kaggle.com/grfiv4/plot-a-confusion-matrix."
},
{
"code": null,
"e": 13588,
"s": 13152,
"text": "This final capability is particularly useful when you have very large datasets. Recently, using this on 25,000 annotations across 6,000 data instances, I was able to very quickly identify that almost 650 bidisagreements were coming from just two labels. This allowed me to address these two labels and how they were to be used in the machine learning model, as well as when modifying the annotation schema for future use by annotators."
},
{
"code": null,
"e": 13609,
"s": 13588,
"text": "Future consideration"
},
{
"code": null,
"e": 13823,
"s": 13609,
"text": "With bidisagreements, you will have noticed that the library is only capable of showing the the frequency. This has a somewhat significant floor. Imagine the following two sets of labels for two instances of data:"
},
{
"code": null,
"e": 13854,
"s": 13823,
"text": "[0, 0, 0, 0, 1][2, 1, 1, 2, 2]"
},
{
"code": null,
"e": 13870,
"s": 13854,
"text": "[0, 0, 0, 0, 1]"
},
{
"code": null,
"e": 13886,
"s": 13870,
"text": "[2, 1, 1, 2, 2]"
},
{
"code": null,
"e": 14211,
"s": 13886,
"text": "Clearly, the first one has much better agreement than the second one, yet disagree considers them equally. It will be interesting to work towards a bidisagreement method that statistically weights the second one as a more significant bidisagreement than the first, and then normalises the bidisagreements matrix accordingly."
},
{
"code": null,
"e": 14240,
"s": 14211,
"text": "Final notes about ‘disagree’"
},
{
"code": null,
"e": 14469,
"s": 14240,
"text": "This library is very recent, and is my first implementation of one. (For this reason, I ask you to please excuse the messy version and commit histories.) The full GitHub repo can be found here: https://github.com/o-P-o/disagree."
},
{
"code": null,
"e": 14625,
"s": 14469,
"text": "The repo includes all of the code, as well as Jupyter notebooks with the examples illustrated above. There is also a full documentation in the README file."
}
] |
Update View – Function based Views Django
|
17 May, 2021
Update View refers to a view (logic) to update a particular instance of a table from the database with some extra details. It is used to update entries in the database for example, updating an article at geeksforgeeks. So Update view must display the old data in the form and let user update the data from there only. Django provides extra-ordinary support for Update Views but let’s check how it is done manually through a function-based view. This article revolves around Update View which involves concepts such as Django Forms, Django Models.
For Update View, we need a project with some models and multiple instances which will be displayed. Basically, Update view is a combination of Detail view and Create view.
Illustration of How to create and use Update view using an Example. Consider a project named geeksforgeeks having an app named geeks.
Refer to the following articles to check how to create a project and an app in Django.
How to Create a Basic Project using MVT in Django?
How to Create an App in Django ?
After you have a project and an app, let’s create a model of which we will be creating instances through our view. In geeks/models.py,
Python3
# import the standard Django Model# from built-in libraryfrom django.db import models # declare a new model with a name "GeeksModel"class GeeksModel(models.Model): # fields of the model title = models.CharField(max_length = 200) description = models.TextField() # renames the instances of the model # with their title name def __str__(self): return self.title
After creating this model, we need to run two commands in order to create Database for the same.
Python manage.py makemigrations
Python manage.py migrate
Now let’s create some instances of this model using shell, run form bash,
Python manage.py shell
Enter following commands
>>> from geeks.models import GeeksModel
>>> GeeksModel.objects.create(
title="title1",
description="description1").save()
>>> GeeksModel.objects.create(
title="title2",
description="description2").save()
>>> GeeksModel.objects.create(
title="title2",
description="description2").save()
Now we have everything ready for back end. Verify that instances have been created from http://localhost:8000/admin/geeks/geeksmodel/
Now we will create a Django ModelForm for this model. Refer this article for more on modelform – Django ModelForm – Create form from Models. create a file forms.py in geeks folder,
Python3
from django import formsfrom .models import GeeksModel # creating a formclass GeeksForm(forms.ModelForm): # create meta class class Meta: # specify model to be used model = GeeksModel # specify fields to be used fields = [ "title", "description"]
For Update_view one would need some identification to get a particular instance of the model. Usually it is unique primary key such as id. To specify this identification we need to define it in urls.py. Go to geeks/urls.py,
Python3
from django.urls import path # importing views from views..pyfrom .views import update_view, detail_view urlpatterns = [ path('<id>/', detail_view ), path('<id>/update', update_view ),]
Let’s create these views with explanations. In geeks/views.py,
Python3
from django.shortcuts import (get_object_or_404, render, HttpResponseRedirect) # relative import of formsfrom .models import GeeksModelfrom .forms import GeeksForm # after updating it will redirect to detail_Viewdef detail_view(request, id): # dictionary for initial data with # field names as keys context ={} # add the dictionary during initialization context["data"] = GeeksModel.objects.get(id = id) return render(request, "detail_view.html", context) # update view for detailsdef update_view(request, id): # dictionary for initial data with # field names as keys context ={} # fetch the object related to passed id obj = get_object_or_404(GeeksModel, id = id) # pass the object as instance in form form = GeeksForm(request.POST or None, instance = obj) # save the data from the form and # redirect to detail_view if form.is_valid(): form.save() return HttpResponseRedirect("/"+id) # add form dictionary to context context["form"] = form return render(request, "update_view.html", context)
Now create following templates in templates folder, In geeks/templates/update_view.html,
HTML
<div class="main"> <!-- Create a Form --> <form method="POST"> <!-- Security token by Django --> {% csrf_token %} <!-- form as paragraph --> {{ form.as_p }} <input type="submit" value="Update"> </form> </div>
In geeks/templates/detail_view.html,
HTML
<div class="main"> <!-- Display attributes of instance --> {{ data.title }} <br/> {{ data.description }}</div>
Let’s check if everything is working, visithttp://localhost:8000/1/update.
Here you can see the form with data already filled from the instance, Now one can edit this data and update it easily, let’s check it out
Hit update and done.
saurabh1990aror
Django-views
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n17 May, 2021"
},
{
"code": null,
"e": 601,
"s": 53,
"text": "Update View refers to a view (logic) to update a particular instance of a table from the database with some extra details. It is used to update entries in the database for example, updating an article at geeksforgeeks. So Update view must display the old data in the form and let user update the data from there only. Django provides extra-ordinary support for Update Views but let’s check how it is done manually through a function-based view. This article revolves around Update View which involves concepts such as Django Forms, Django Models. "
},
{
"code": null,
"e": 774,
"s": 601,
"text": "For Update View, we need a project with some models and multiple instances which will be displayed. Basically, Update view is a combination of Detail view and Create view. "
},
{
"code": null,
"e": 910,
"s": 774,
"text": "Illustration of How to create and use Update view using an Example. Consider a project named geeksforgeeks having an app named geeks. "
},
{
"code": null,
"e": 999,
"s": 910,
"text": "Refer to the following articles to check how to create a project and an app in Django. "
},
{
"code": null,
"e": 1050,
"s": 999,
"text": "How to Create a Basic Project using MVT in Django?"
},
{
"code": null,
"e": 1083,
"s": 1050,
"text": "How to Create an App in Django ?"
},
{
"code": null,
"e": 1220,
"s": 1083,
"text": "After you have a project and an app, let’s create a model of which we will be creating instances through our view. In geeks/models.py, "
},
{
"code": null,
"e": 1228,
"s": 1220,
"text": "Python3"
},
{
"code": "# import the standard Django Model# from built-in libraryfrom django.db import models # declare a new model with a name \"GeeksModel\"class GeeksModel(models.Model): # fields of the model title = models.CharField(max_length = 200) description = models.TextField() # renames the instances of the model # with their title name def __str__(self): return self.title",
"e": 1616,
"s": 1228,
"text": null
},
{
"code": null,
"e": 1714,
"s": 1616,
"text": "After creating this model, we need to run two commands in order to create Database for the same. "
},
{
"code": null,
"e": 1771,
"s": 1714,
"text": "Python manage.py makemigrations\nPython manage.py migrate"
},
{
"code": null,
"e": 1846,
"s": 1771,
"text": "Now let’s create some instances of this model using shell, run form bash, "
},
{
"code": null,
"e": 1869,
"s": 1846,
"text": "Python manage.py shell"
},
{
"code": null,
"e": 1895,
"s": 1869,
"text": "Enter following commands "
},
{
"code": null,
"e": 2319,
"s": 1895,
"text": ">>> from geeks.models import GeeksModel\n>>> GeeksModel.objects.create(\n title=\"title1\",\n description=\"description1\").save()\n>>> GeeksModel.objects.create(\n title=\"title2\",\n description=\"description2\").save()\n>>> GeeksModel.objects.create(\n title=\"title2\",\n description=\"description2\").save()"
},
{
"code": null,
"e": 2454,
"s": 2319,
"text": "Now we have everything ready for back end. Verify that instances have been created from http://localhost:8000/admin/geeks/geeksmodel/ "
},
{
"code": null,
"e": 2636,
"s": 2454,
"text": "Now we will create a Django ModelForm for this model. Refer this article for more on modelform – Django ModelForm – Create form from Models. create a file forms.py in geeks folder, "
},
{
"code": null,
"e": 2644,
"s": 2636,
"text": "Python3"
},
{
"code": "from django import formsfrom .models import GeeksModel # creating a formclass GeeksForm(forms.ModelForm): # create meta class class Meta: # specify model to be used model = GeeksModel # specify fields to be used fields = [ \"title\", \"description\"]",
"e": 2950,
"s": 2644,
"text": null
},
{
"code": null,
"e": 3175,
"s": 2950,
"text": "For Update_view one would need some identification to get a particular instance of the model. Usually it is unique primary key such as id. To specify this identification we need to define it in urls.py. Go to geeks/urls.py, "
},
{
"code": null,
"e": 3183,
"s": 3175,
"text": "Python3"
},
{
"code": "from django.urls import path # importing views from views..pyfrom .views import update_view, detail_view urlpatterns = [ path('<id>/', detail_view ), path('<id>/update', update_view ),]",
"e": 3375,
"s": 3183,
"text": null
},
{
"code": null,
"e": 3438,
"s": 3375,
"text": "Let’s create these views with explanations. In geeks/views.py,"
},
{
"code": null,
"e": 3446,
"s": 3438,
"text": "Python3"
},
{
"code": "from django.shortcuts import (get_object_or_404, render, HttpResponseRedirect) # relative import of formsfrom .models import GeeksModelfrom .forms import GeeksForm # after updating it will redirect to detail_Viewdef detail_view(request, id): # dictionary for initial data with # field names as keys context ={} # add the dictionary during initialization context[\"data\"] = GeeksModel.objects.get(id = id) return render(request, \"detail_view.html\", context) # update view for detailsdef update_view(request, id): # dictionary for initial data with # field names as keys context ={} # fetch the object related to passed id obj = get_object_or_404(GeeksModel, id = id) # pass the object as instance in form form = GeeksForm(request.POST or None, instance = obj) # save the data from the form and # redirect to detail_view if form.is_valid(): form.save() return HttpResponseRedirect(\"/\"+id) # add form dictionary to context context[\"form\"] = form return render(request, \"update_view.html\", context)",
"e": 4586,
"s": 3446,
"text": null
},
{
"code": null,
"e": 4675,
"s": 4586,
"text": "Now create following templates in templates folder, In geeks/templates/update_view.html,"
},
{
"code": null,
"e": 4680,
"s": 4675,
"text": "HTML"
},
{
"code": "<div class=\"main\"> <!-- Create a Form --> <form method=\"POST\"> <!-- Security token by Django --> {% csrf_token %} <!-- form as paragraph --> {{ form.as_p }} <input type=\"submit\" value=\"Update\"> </form> </div>",
"e": 4935,
"s": 4680,
"text": null
},
{
"code": null,
"e": 4973,
"s": 4935,
"text": "In geeks/templates/detail_view.html, "
},
{
"code": null,
"e": 4978,
"s": 4973,
"text": "HTML"
},
{
"code": "<div class=\"main\"> <!-- Display attributes of instance --> {{ data.title }} <br/> {{ data.description }}</div>",
"e": 5098,
"s": 4978,
"text": null
},
{
"code": null,
"e": 5174,
"s": 5098,
"text": "Let’s check if everything is working, visithttp://localhost:8000/1/update. "
},
{
"code": null,
"e": 5314,
"s": 5174,
"text": "Here you can see the form with data already filled from the instance, Now one can edit this data and update it easily, let’s check it out "
},
{
"code": null,
"e": 5337,
"s": 5314,
"text": "Hit update and done. "
},
{
"code": null,
"e": 5355,
"s": 5339,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 5368,
"s": 5355,
"text": "Django-views"
},
{
"code": null,
"e": 5382,
"s": 5368,
"text": "Python Django"
},
{
"code": null,
"e": 5389,
"s": 5382,
"text": "Python"
}
] |
PostgreSQL – Copy Database
|
22 Feb, 2021
In this article, we will discuss the process of copying a PostgreSQL database on the same server or from a server to another.
If a situation arises where one needs to copy a PostgreSQL database within a database server for testing purposes. PostgreSQL makes it simple to do so using the CREATE DATABASE statement as follows:
Syntax:
CREATE DATABASE target_database
WITH TEMPLATE source_database;
This statement copies the source_database to the target_database. For instance, to copy the dvdrental sample database which is described here and can be downloaded from here, to the dvdrental_test database, you use the following statement:
CREATE DATABASE dvdrental_test
WITH TEMPLATE dvdrental;
It may take a while to complete copying depending upon the size of the original database.
There are many ways to copy a database between various PostgreSQL database servers. The connection between servers grows slower as the database gets larger. One way of doing so is to create a database dump and restore the same dump to another server. To do so the following commands need to be followed:
Step 1: Create a Dump file of the source database.
pg_dump -U postgres -d source_database -f source_database.sql
Step 2: Copy the dump file to the remote server.
Step 3: Create a new database in the remote server where you want to restore the database dump:
CREATE DATABASE target_database;
Step 4: Restore the dump file on the remote server:
psql -U postgres -d target_database -f source_database.sql
Example: Here we will copy the dvdrental database from the local server to the remote server. First, we will dump the dvdrental database into a dump file e.g., dvdrental.sql:
pg_dump -U postgres -O dvdrental dvdrental.sql
Then we will copy the dump file to a remote server and we will create the dvdrental database on the remote server:
CREATE DATABASE dvdrental;
Now, we will restore the dump file that we just created into the remote server:
psql -U postgres -d dvdrental -f dvdrental.sql
For high-speed connections between servers or for smaller databases, you can also use the following command:
pg_dump -C -h local -U localuser source_database | psql -h remote -U remoteuser target_database
For instance, if one desires to copy the dvdrental database from the localhost to the remote server, you do it as follows:
pg_dump -C -h localhost -U postgres dvdrental | psql -h remote -U postgres dvdrental
RajuKumar19
postgreSQL-managing-database
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL - REPLACE Function
PostgreSQL - DROP INDEX
PostgreSQL - INSERT
PostgreSQL - TIME Data Type
PostgreSQL - ROW_NUMBER Function
PostgreSQL - CREATE SCHEMA
PostgreSQL - SELECT
PostgreSQL - EXISTS Operator
PostgreSQL - SELECT DISTINCT clause
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Feb, 2021"
},
{
"code": null,
"e": 179,
"s": 52,
"text": "In this article, we will discuss the process of copying a PostgreSQL database on the same server or from a server to another. "
},
{
"code": null,
"e": 379,
"s": 179,
"text": "If a situation arises where one needs to copy a PostgreSQL database within a database server for testing purposes. PostgreSQL makes it simple to do so using the CREATE DATABASE statement as follows: "
},
{
"code": null,
"e": 451,
"s": 379,
"text": "Syntax:\nCREATE DATABASE target_database \nWITH TEMPLATE source_database;"
},
{
"code": null,
"e": 692,
"s": 451,
"text": "This statement copies the source_database to the target_database. For instance, to copy the dvdrental sample database which is described here and can be downloaded from here, to the dvdrental_test database, you use the following statement: "
},
{
"code": null,
"e": 749,
"s": 692,
"text": "CREATE DATABASE dvdrental_test \nWITH TEMPLATE dvdrental;"
},
{
"code": null,
"e": 840,
"s": 749,
"text": "It may take a while to complete copying depending upon the size of the original database. "
},
{
"code": null,
"e": 1145,
"s": 840,
"text": "There are many ways to copy a database between various PostgreSQL database servers. The connection between servers grows slower as the database gets larger. One way of doing so is to create a database dump and restore the same dump to another server. To do so the following commands need to be followed: "
},
{
"code": null,
"e": 1196,
"s": 1145,
"text": "Step 1: Create a Dump file of the source database."
},
{
"code": null,
"e": 1258,
"s": 1196,
"text": "pg_dump -U postgres -d source_database -f source_database.sql"
},
{
"code": null,
"e": 1308,
"s": 1258,
"text": "Step 2: Copy the dump file to the remote server. "
},
{
"code": null,
"e": 1404,
"s": 1308,
"text": "Step 3: Create a new database in the remote server where you want to restore the database dump:"
},
{
"code": null,
"e": 1437,
"s": 1404,
"text": "CREATE DATABASE target_database;"
},
{
"code": null,
"e": 1490,
"s": 1437,
"text": "Step 4: Restore the dump file on the remote server: "
},
{
"code": null,
"e": 1549,
"s": 1490,
"text": "psql -U postgres -d target_database -f source_database.sql"
},
{
"code": null,
"e": 1725,
"s": 1549,
"text": "Example: Here we will copy the dvdrental database from the local server to the remote server. First, we will dump the dvdrental database into a dump file e.g., dvdrental.sql: "
},
{
"code": null,
"e": 1772,
"s": 1725,
"text": "pg_dump -U postgres -O dvdrental dvdrental.sql"
},
{
"code": null,
"e": 1888,
"s": 1772,
"text": "Then we will copy the dump file to a remote server and we will create the dvdrental database on the remote server: "
},
{
"code": null,
"e": 1915,
"s": 1888,
"text": "CREATE DATABASE dvdrental;"
},
{
"code": null,
"e": 1996,
"s": 1915,
"text": "Now, we will restore the dump file that we just created into the remote server: "
},
{
"code": null,
"e": 2043,
"s": 1996,
"text": "psql -U postgres -d dvdrental -f dvdrental.sql"
},
{
"code": null,
"e": 2153,
"s": 2043,
"text": "For high-speed connections between servers or for smaller databases, you can also use the following command: "
},
{
"code": null,
"e": 2249,
"s": 2153,
"text": "pg_dump -C -h local -U localuser source_database | psql -h remote -U remoteuser target_database"
},
{
"code": null,
"e": 2373,
"s": 2249,
"text": "For instance, if one desires to copy the dvdrental database from the localhost to the remote server, you do it as follows: "
},
{
"code": null,
"e": 2458,
"s": 2373,
"text": "pg_dump -C -h localhost -U postgres dvdrental | psql -h remote -U postgres dvdrental"
},
{
"code": null,
"e": 2470,
"s": 2458,
"text": "RajuKumar19"
},
{
"code": null,
"e": 2499,
"s": 2470,
"text": "postgreSQL-managing-database"
},
{
"code": null,
"e": 2510,
"s": 2499,
"text": "PostgreSQL"
},
{
"code": null,
"e": 2608,
"s": 2510,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2646,
"s": 2608,
"text": "PostgreSQL - LIMIT with OFFSET clause"
},
{
"code": null,
"e": 2676,
"s": 2646,
"text": "PostgreSQL - REPLACE Function"
},
{
"code": null,
"e": 2700,
"s": 2676,
"text": "PostgreSQL - DROP INDEX"
},
{
"code": null,
"e": 2720,
"s": 2700,
"text": "PostgreSQL - INSERT"
},
{
"code": null,
"e": 2748,
"s": 2720,
"text": "PostgreSQL - TIME Data Type"
},
{
"code": null,
"e": 2781,
"s": 2748,
"text": "PostgreSQL - ROW_NUMBER Function"
},
{
"code": null,
"e": 2808,
"s": 2781,
"text": "PostgreSQL - CREATE SCHEMA"
},
{
"code": null,
"e": 2828,
"s": 2808,
"text": "PostgreSQL - SELECT"
},
{
"code": null,
"e": 2857,
"s": 2828,
"text": "PostgreSQL - EXISTS Operator"
}
] |
How to build a Random Story Generator using Python?
|
26 Mar, 2021
In this section, we are going to make a very interesting beginner-level project of Python. It is a random story generator. The random story generator project aims to generate random stories every time user executes the code. A story is made up of a collection of sentences. We will choose random phrases to build sentences, and hence stories.
Now, the pertinent question is – How we will do so? Its answer is very simple :
We will first put the elements of the story in different lists.
Then we will use the random module to select random parts of the story collected in different lists.
And then concatenate them to make a story.
We will make use of random.choice() function. Before starting, let’s see an example of how random.choice() works.
Python3
import random # list of books is stored in the list -'books'books = ['Mother', 'Midnight Children', 'My experiments with truth'] # An item from the list 'books' is selected# by random.choice()print(random.choice(books))
Midnight Children
As we can see, random.choice() function basically selects an item from a list of items.
Following are the steps involved in this Random story generator project.
1. Import the random module, as it is a built-in module of python. So, there’s no need to install it manually.
Python3
# Importing random moduleimport random
2. Define several lists of phrases. Here, we have defined eight lists. We can define more also, it depends totally on our choice.
Sentence_starter – This list gives an idea about the time of the event.
character – This list tells about the main character of this story.
time – This list defines the exact day on which some incident has occurred.
story_plot – This list defines the plot of the story.
place – This list defines the place at which the incident occurred.
second_character – This list defines the second character of the story.
age – This list defines the age of the second character.
work – This list tells about the work the second character was doing.
Python3
# Defining list of phrases which will help to build a storySentence_starter = ['About 100 years ago', ' In the 20 BC', 'Once upon a time'] character = [' there lived a king.',' there was a man named Jack.', ' there lived a farmer.'] time = [' One day', ' One full-moon night'] story_plot = [' he was passing by', ' he was going for a picnic to '] place = [' the mountains', ' the garden'] second_character = [' he saw a man', ' he saw a young lady'] age = [' who seemed to be in late 20s', ' who seemed very old and feeble'] work = [' searching something.', ' digging a well on roadside.']
3. With the help of random.choice() select an item from each list and concatenate the selected items to generate sentences for the story.
Python3
# Selecting an item from each list and concatenating them.print(random.choice(Sentence_starter)+random.choice(character)+ random.choice(time)+random.choice(story_plot)+ random.choice(place)+random.choice(second_character)+ random.choice(age)+random.choice(work))
Implementation:
Let’s try the full implementation with the help of an example.
Python3
# Importing random moduleimport random # Defining list of phrases which will help to build a story Sentence_starter = ['About 100 years ago', ' In the 20 BC', 'Once upon a time']character = [' there lived a king.',' there was a man named Jack.', ' there lived a farmer.']time = [' One day', ' One full-moon night']story_plot = [' he was passing by',' he was going for a picnic to ']place = [' the mountains', ' the garden']second_character = [' he saw a man', ' he saw a young lady']age = [' who seemed to be in late 20s', ' who seemed very old and feeble']work = [' searching something.', ' digging a well on roadside.'] # Selecting an item from each list and concatenating them.print(random.choice(Sentence_starter)+random.choice(character)+ random.choice(time)+random.choice(story_plot) + random.choice(place)+random.choice(second_character)+ random.choice(age)+random.choice(work))
Output:
In the 20 BC there lived a king. One day he was going for a picnic to the mountains he saw a man who seemed to be in late 20s digging a well on roadside.
In this way, we can compile and run this code as many times as we want. And different short stories will be generated.
Python-random
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n26 Mar, 2021"
},
{
"code": null,
"e": 398,
"s": 54,
"text": "In this section, we are going to make a very interesting beginner-level project of Python. It is a random story generator. The random story generator project aims to generate random stories every time user executes the code. A story is made up of a collection of sentences. We will choose random phrases to build sentences, and hence stories. "
},
{
"code": null,
"e": 478,
"s": 398,
"text": "Now, the pertinent question is – How we will do so? Its answer is very simple :"
},
{
"code": null,
"e": 542,
"s": 478,
"text": "We will first put the elements of the story in different lists."
},
{
"code": null,
"e": 643,
"s": 542,
"text": "Then we will use the random module to select random parts of the story collected in different lists."
},
{
"code": null,
"e": 686,
"s": 643,
"text": "And then concatenate them to make a story."
},
{
"code": null,
"e": 800,
"s": 686,
"text": "We will make use of random.choice() function. Before starting, let’s see an example of how random.choice() works."
},
{
"code": null,
"e": 808,
"s": 800,
"text": "Python3"
},
{
"code": "import random # list of books is stored in the list -'books'books = ['Mother', 'Midnight Children', 'My experiments with truth'] # An item from the list 'books' is selected# by random.choice()print(random.choice(books))",
"e": 1030,
"s": 808,
"text": null
},
{
"code": null,
"e": 1048,
"s": 1030,
"text": "Midnight Children"
},
{
"code": null,
"e": 1137,
"s": 1048,
"text": "As we can see, random.choice() function basically selects an item from a list of items. "
},
{
"code": null,
"e": 1210,
"s": 1137,
"text": "Following are the steps involved in this Random story generator project."
},
{
"code": null,
"e": 1322,
"s": 1210,
"text": "1. Import the random module, as it is a built-in module of python. So, there’s no need to install it manually."
},
{
"code": null,
"e": 1330,
"s": 1322,
"text": "Python3"
},
{
"code": "# Importing random moduleimport random",
"e": 1369,
"s": 1330,
"text": null
},
{
"code": null,
"e": 1500,
"s": 1369,
"text": "2. Define several lists of phrases. Here, we have defined eight lists. We can define more also, it depends totally on our choice."
},
{
"code": null,
"e": 1572,
"s": 1500,
"text": "Sentence_starter – This list gives an idea about the time of the event."
},
{
"code": null,
"e": 1640,
"s": 1572,
"text": "character – This list tells about the main character of this story."
},
{
"code": null,
"e": 1716,
"s": 1640,
"text": "time – This list defines the exact day on which some incident has occurred."
},
{
"code": null,
"e": 1770,
"s": 1716,
"text": "story_plot – This list defines the plot of the story."
},
{
"code": null,
"e": 1838,
"s": 1770,
"text": "place – This list defines the place at which the incident occurred."
},
{
"code": null,
"e": 1910,
"s": 1838,
"text": "second_character – This list defines the second character of the story."
},
{
"code": null,
"e": 1967,
"s": 1910,
"text": "age – This list defines the age of the second character."
},
{
"code": null,
"e": 2037,
"s": 1967,
"text": "work – This list tells about the work the second character was doing."
},
{
"code": null,
"e": 2045,
"s": 2037,
"text": "Python3"
},
{
"code": "# Defining list of phrases which will help to build a storySentence_starter = ['About 100 years ago', ' In the 20 BC', 'Once upon a time'] character = [' there lived a king.',' there was a man named Jack.', ' there lived a farmer.'] time = [' One day', ' One full-moon night'] story_plot = [' he was passing by', ' he was going for a picnic to '] place = [' the mountains', ' the garden'] second_character = [' he saw a man', ' he saw a young lady'] age = [' who seemed to be in late 20s', ' who seemed very old and feeble'] work = [' searching something.', ' digging a well on roadside.']",
"e": 2654,
"s": 2045,
"text": null
},
{
"code": null,
"e": 2792,
"s": 2654,
"text": "3. With the help of random.choice() select an item from each list and concatenate the selected items to generate sentences for the story."
},
{
"code": null,
"e": 2800,
"s": 2792,
"text": "Python3"
},
{
"code": "# Selecting an item from each list and concatenating them.print(random.choice(Sentence_starter)+random.choice(character)+ random.choice(time)+random.choice(story_plot)+ random.choice(place)+random.choice(second_character)+ random.choice(age)+random.choice(work))",
"e": 3078,
"s": 2800,
"text": null
},
{
"code": null,
"e": 3094,
"s": 3078,
"text": "Implementation:"
},
{
"code": null,
"e": 3157,
"s": 3094,
"text": "Let’s try the full implementation with the help of an example."
},
{
"code": null,
"e": 3165,
"s": 3157,
"text": "Python3"
},
{
"code": "# Importing random moduleimport random # Defining list of phrases which will help to build a story Sentence_starter = ['About 100 years ago', ' In the 20 BC', 'Once upon a time']character = [' there lived a king.',' there was a man named Jack.', ' there lived a farmer.']time = [' One day', ' One full-moon night']story_plot = [' he was passing by',' he was going for a picnic to ']place = [' the mountains', ' the garden']second_character = [' he saw a man', ' he saw a young lady']age = [' who seemed to be in late 20s', ' who seemed very old and feeble']work = [' searching something.', ' digging a well on roadside.'] # Selecting an item from each list and concatenating them.print(random.choice(Sentence_starter)+random.choice(character)+ random.choice(time)+random.choice(story_plot) + random.choice(place)+random.choice(second_character)+ random.choice(age)+random.choice(work))",
"e": 4081,
"s": 3165,
"text": null
},
{
"code": null,
"e": 4089,
"s": 4081,
"text": "Output:"
},
{
"code": null,
"e": 4244,
"s": 4089,
"text": "In the 20 BC there lived a king. One day he was going for a picnic to the mountains he saw a man who seemed to be in late 20s digging a well on roadside."
},
{
"code": null,
"e": 4363,
"s": 4244,
"text": "In this way, we can compile and run this code as many times as we want. And different short stories will be generated."
},
{
"code": null,
"e": 4377,
"s": 4363,
"text": "Python-random"
},
{
"code": null,
"e": 4384,
"s": 4377,
"text": "Python"
}
] |
Python 3 - Number atan2() Method
|
The atan2() method returns atan(y / x), in radians.
Following is the syntax for atan2() method −
atan2(y, x)
Note − This function is not accessible directly, so we need to import math module and then we need to call this function using math static object.
y − This must be a numeric value.
y − This must be a numeric value.
x − This must be a numeric value.
x − This must be a numeric value.
This method returns atan(y / x), in radians.
The following example shows the usage of atan2() method.
#!/usr/bin/python3
import math
print ("atan2(-0.50,-0.50) : ", math.atan2(-0.50,-0.50))
print ("atan2(0.50,0.50) : ", math.atan2(0.50,0.50))
print ("atan2(5,5) : ", math.atan2(5,5))
print ("atan2(-10,10) : ", math.atan2(-10,10))
print ("atan2(10,20) : ", math.atan2(10,20))
When we run the above program, it produces the following result −
atan2(-0.50,-0.50) : -2.35619449019
atan2(0.50,0.50) : 0.785398163397
atan2(5,5) : 0.785398163397
atan2(-10,10) : -0.785398163397
atan2(10,20) : 0.463647609001
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2392,
"s": 2340,
"text": "The atan2() method returns atan(y / x), in radians."
},
{
"code": null,
"e": 2437,
"s": 2392,
"text": "Following is the syntax for atan2() method −"
},
{
"code": null,
"e": 2450,
"s": 2437,
"text": "atan2(y, x)\n"
},
{
"code": null,
"e": 2597,
"s": 2450,
"text": "Note − This function is not accessible directly, so we need to import math module and then we need to call this function using math static object."
},
{
"code": null,
"e": 2631,
"s": 2597,
"text": "y − This must be a numeric value."
},
{
"code": null,
"e": 2665,
"s": 2631,
"text": "y − This must be a numeric value."
},
{
"code": null,
"e": 2699,
"s": 2665,
"text": "x − This must be a numeric value."
},
{
"code": null,
"e": 2733,
"s": 2699,
"text": "x − This must be a numeric value."
},
{
"code": null,
"e": 2778,
"s": 2733,
"text": "This method returns atan(y / x), in radians."
},
{
"code": null,
"e": 2835,
"s": 2778,
"text": "The following example shows the usage of atan2() method."
},
{
"code": null,
"e": 3115,
"s": 2835,
"text": "#!/usr/bin/python3\nimport math\n\nprint (\"atan2(-0.50,-0.50) : \", math.atan2(-0.50,-0.50))\nprint (\"atan2(0.50,0.50) : \", math.atan2(0.50,0.50))\nprint (\"atan2(5,5) : \", math.atan2(5,5))\nprint (\"atan2(-10,10) : \", math.atan2(-10,10))\nprint (\"atan2(10,20) : \", math.atan2(10,20))"
},
{
"code": null,
"e": 3181,
"s": 3115,
"text": "When we run the above program, it produces the following result −"
},
{
"code": null,
"e": 3347,
"s": 3181,
"text": "atan2(-0.50,-0.50) : -2.35619449019\natan2(0.50,0.50) : 0.785398163397\natan2(5,5) : 0.785398163397\natan2(-10,10) : -0.785398163397\natan2(10,20) : 0.463647609001\n"
},
{
"code": null,
"e": 3384,
"s": 3347,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3400,
"s": 3384,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3433,
"s": 3400,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3452,
"s": 3433,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3487,
"s": 3452,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3509,
"s": 3487,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3543,
"s": 3509,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3571,
"s": 3543,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3606,
"s": 3571,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3620,
"s": 3606,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3653,
"s": 3620,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3670,
"s": 3653,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3677,
"s": 3670,
"text": " Print"
},
{
"code": null,
"e": 3688,
"s": 3677,
"text": " Add Notes"
}
] |
Basic Properties of a Graph - GeeksforGeeks
|
25 Oct, 2018
A Graph is a non-linear data structure consisting of nodes and edges. The nodes are sometimes also referred to as vertices and the edges are lines or arcs that connect any two nodes in the graph.
Properties of Graphs are basically used for characterization of graphs depending on their structures. We defined these properties in specific terms that pertain to the domain of graph theory. In this article, we are going to discuss some properties of Graphs these are as follows:
Distance between two VerticesIt is basically the number of edges that are available in the shortest path between vertex A and vertex B.If there is more than one edge which is used two connect two vertices then we basically considered the shortest path as the distance between these two vertices.Notation used :
d(A, B)
here function d is basically showing the distance between vertex A and vertex B.
Let us understand this using an example:In the above diagram, let’s try to find the distance between vertices b and d.d(b, c)
We can go from vertex b to vertex d in different ways such as
1.ba, af, fe, ed here the d(b, c) will be 4.
2.ba, af, fc, cd here the d(b, c) will be 4.
3.bc, cf, fe, ed here the d(b, c) will be 4.
4.bc, cd here the d(b, c) will be 2.
hence the minimum distance between vertex b and vertex d is 2.
Eccentricity of a VertexMaximum distance from a vertex to all other vertices is considered as the Eccentricity of that vertex.Notation used:
e(V)
here e(v) determines the eccentricity of vertex V.
Let us try to understand this using following example.From the above diagram lets try to find the eccentricity of vertex b.
e(b)
d(b, a)=1
d(b, c)=1
d(b, d)=2
d(b, e)=3
d(b, f)=2
d(b, g)=2
Hence the eccentricity of vertex b is 3
Radius of a Connected GraphThe minimum value of eccentricity from all vertices is basically considered as the radius of connected graph.Notation used:
r(G)
here G is the connected graph.
Let us try to understand this using following example.From the above diagram:
r(G) is 2.
Because the minimum value of eccentricity from all vertices is 2.
Diameter of A Connected GraphUnlike the radius of the connected graph here we basically used the maximum value of eccentricity from all vertices to determine the diameter of the graph.Notation used:
d(G)
where G is the connected graph.
Let us try to understand this using following example.From the above diagram:
d(G) is 3.
Because the maximum value of eccentricity from all vertices is 3.
Central Point and CentreThe vertex having minimum eccentricity is considered as the central point of the graph.And the sets of all central point is considered as the centre of Graph.if
e(V)=r(G)
then v is the central point.
Let us try to understand this using following example.In the above diagram the central point will be f.
because
e(f)=r(G)=2
hence f is considered as the central point of graph.
Hence f is also the centre of the graph.
Distance between two VerticesIt is basically the number of edges that are available in the shortest path between vertex A and vertex B.If there is more than one edge which is used two connect two vertices then we basically considered the shortest path as the distance between these two vertices.Notation used :
d(A, B)
here function d is basically showing the distance between vertex A and vertex B.
Let us understand this using an example:In the above diagram, let’s try to find the distance between vertices b and d.d(b, c)
We can go from vertex b to vertex d in different ways such as
1.ba, af, fe, ed here the d(b, c) will be 4.
2.ba, af, fc, cd here the d(b, c) will be 4.
3.bc, cf, fe, ed here the d(b, c) will be 4.
4.bc, cd here the d(b, c) will be 2.
hence the minimum distance between vertex b and vertex d is 2.
Notation used :
d(A, B)
here function d is basically showing the distance between vertex A and vertex B.
Let us understand this using an example:In the above diagram, let’s try to find the distance between vertices b and d.
d(b, c)
We can go from vertex b to vertex d in different ways such as
1.ba, af, fe, ed here the d(b, c) will be 4.
2.ba, af, fc, cd here the d(b, c) will be 4.
3.bc, cf, fe, ed here the d(b, c) will be 4.
4.bc, cd here the d(b, c) will be 2.
hence the minimum distance between vertex b and vertex d is 2.
Eccentricity of a VertexMaximum distance from a vertex to all other vertices is considered as the Eccentricity of that vertex.Notation used:
e(V)
here e(v) determines the eccentricity of vertex V.
Let us try to understand this using following example.From the above diagram lets try to find the eccentricity of vertex b.
e(b)
d(b, a)=1
d(b, c)=1
d(b, d)=2
d(b, e)=3
d(b, f)=2
d(b, g)=2
Hence the eccentricity of vertex b is 3
Notation used:
e(V)
here e(v) determines the eccentricity of vertex V.
Let us try to understand this using following example.
From the above diagram lets try to find the eccentricity of vertex b.
e(b)
d(b, a)=1
d(b, c)=1
d(b, d)=2
d(b, e)=3
d(b, f)=2
d(b, g)=2
Hence the eccentricity of vertex b is 3
Radius of a Connected GraphThe minimum value of eccentricity from all vertices is basically considered as the radius of connected graph.Notation used:
r(G)
here G is the connected graph.
Let us try to understand this using following example.From the above diagram:
r(G) is 2.
Because the minimum value of eccentricity from all vertices is 2.
Notation used:
r(G)
here G is the connected graph.
Let us try to understand this using following example.
From the above diagram:
r(G) is 2.
Because the minimum value of eccentricity from all vertices is 2.
Diameter of A Connected GraphUnlike the radius of the connected graph here we basically used the maximum value of eccentricity from all vertices to determine the diameter of the graph.Notation used:
d(G)
where G is the connected graph.
Let us try to understand this using following example.From the above diagram:
d(G) is 3.
Because the maximum value of eccentricity from all vertices is 3.
Notation used:
d(G)
where G is the connected graph.
Let us try to understand this using following example.
From the above diagram:
d(G) is 3.
Because the maximum value of eccentricity from all vertices is 3.
Central Point and CentreThe vertex having minimum eccentricity is considered as the central point of the graph.And the sets of all central point is considered as the centre of Graph.if
e(V)=r(G)
then v is the central point.
Let us try to understand this using following example.In the above diagram the central point will be f.
because
e(f)=r(G)=2
hence f is considered as the central point of graph.
Hence f is also the centre of the graph.
if
e(V)=r(G)
then v is the central point.
Let us try to understand this using following example.
In the above diagram the central point will be f.
because
e(f)=r(G)=2
hence f is considered as the central point of graph.
Hence f is also the centre of the graph.
Data Structures-Graph
graph-basics
Graph
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Best First Search (Informed Search)
Find if there is a path between two vertices in a directed graph
Graph Coloring | Set 2 (Greedy Algorithm)
Vertex Cover Problem | Set 1 (Introduction and Approximate Algorithm)
Iterative Deepening Search(IDS) or Iterative Deepening Depth First Search(IDDFS)
Maximum Bipartite Matching
Eulerian path and circuit for undirected graph
Longest Path in a Directed Acyclic Graph
Comparison between Adjacency List and Adjacency Matrix representation of Graph
Printing Paths in Dijkstra's Shortest Path Algorithm
|
[
{
"code": null,
"e": 25066,
"s": 25038,
"text": "\n25 Oct, 2018"
},
{
"code": null,
"e": 25262,
"s": 25066,
"text": "A Graph is a non-linear data structure consisting of nodes and edges. The nodes are sometimes also referred to as vertices and the edges are lines or arcs that connect any two nodes in the graph."
},
{
"code": null,
"e": 25543,
"s": 25262,
"text": "Properties of Graphs are basically used for characterization of graphs depending on their structures. We defined these properties in specific terms that pertain to the domain of graph theory. In this article, we are going to discuss some properties of Graphs these are as follows:"
},
{
"code": null,
"e": 27969,
"s": 25543,
"text": "Distance between two VerticesIt is basically the number of edges that are available in the shortest path between vertex A and vertex B.If there is more than one edge which is used two connect two vertices then we basically considered the shortest path as the distance between these two vertices.Notation used :\nd(A, B)\nhere function d is basically showing the distance between vertex A and vertex B.\nLet us understand this using an example:In the above diagram, let’s try to find the distance between vertices b and d.d(b, c)\nWe can go from vertex b to vertex d in different ways such as\n1.ba, af, fe, ed here the d(b, c) will be 4.\n2.ba, af, fc, cd here the d(b, c) will be 4.\n3.bc, cf, fe, ed here the d(b, c) will be 4.\n4.bc, cd here the d(b, c) will be 2.\nhence the minimum distance between vertex b and vertex d is 2.\nEccentricity of a VertexMaximum distance from a vertex to all other vertices is considered as the Eccentricity of that vertex.Notation used:\ne(V)\nhere e(v) determines the eccentricity of vertex V.\nLet us try to understand this using following example.From the above diagram lets try to find the eccentricity of vertex b.\ne(b)\nd(b, a)=1\nd(b, c)=1\nd(b, d)=2\nd(b, e)=3\nd(b, f)=2\nd(b, g)=2\nHence the eccentricity of vertex b is 3\nRadius of a Connected GraphThe minimum value of eccentricity from all vertices is basically considered as the radius of connected graph.Notation used:\nr(G)\nhere G is the connected graph.\nLet us try to understand this using following example.From the above diagram:\nr(G) is 2.\nBecause the minimum value of eccentricity from all vertices is 2.\nDiameter of A Connected GraphUnlike the radius of the connected graph here we basically used the maximum value of eccentricity from all vertices to determine the diameter of the graph.Notation used:\nd(G)\nwhere G is the connected graph.\nLet us try to understand this using following example.From the above diagram:\nd(G) is 3.\nBecause the maximum value of eccentricity from all vertices is 3.\nCentral Point and CentreThe vertex having minimum eccentricity is considered as the central point of the graph.And the sets of all central point is considered as the centre of Graph.if\ne(V)=r(G)\nthen v is the central point.\nLet us try to understand this using following example.In the above diagram the central point will be f.\nbecause \ne(f)=r(G)=2\nhence f is considered as the central point of graph.\nHence f is also the centre of the graph.\n"
},
{
"code": null,
"e": 28793,
"s": 27969,
"text": "Distance between two VerticesIt is basically the number of edges that are available in the shortest path between vertex A and vertex B.If there is more than one edge which is used two connect two vertices then we basically considered the shortest path as the distance between these two vertices.Notation used :\nd(A, B)\nhere function d is basically showing the distance between vertex A and vertex B.\nLet us understand this using an example:In the above diagram, let’s try to find the distance between vertices b and d.d(b, c)\nWe can go from vertex b to vertex d in different ways such as\n1.ba, af, fe, ed here the d(b, c) will be 4.\n2.ba, af, fc, cd here the d(b, c) will be 4.\n3.bc, cf, fe, ed here the d(b, c) will be 4.\n4.bc, cd here the d(b, c) will be 2.\nhence the minimum distance between vertex b and vertex d is 2.\n"
},
{
"code": null,
"e": 28899,
"s": 28793,
"text": "Notation used :\nd(A, B)\nhere function d is basically showing the distance between vertex A and vertex B.\n"
},
{
"code": null,
"e": 29018,
"s": 28899,
"text": "Let us understand this using an example:In the above diagram, let’s try to find the distance between vertices b and d."
},
{
"code": null,
"e": 29324,
"s": 29018,
"text": "d(b, c)\nWe can go from vertex b to vertex d in different ways such as\n1.ba, af, fe, ed here the d(b, c) will be 4.\n2.ba, af, fc, cd here the d(b, c) will be 4.\n3.bc, cf, fe, ed here the d(b, c) will be 4.\n4.bc, cd here the d(b, c) will be 2.\nhence the minimum distance between vertex b and vertex d is 2.\n"
},
{
"code": null,
"e": 29751,
"s": 29324,
"text": "Eccentricity of a VertexMaximum distance from a vertex to all other vertices is considered as the Eccentricity of that vertex.Notation used:\ne(V)\nhere e(v) determines the eccentricity of vertex V.\nLet us try to understand this using following example.From the above diagram lets try to find the eccentricity of vertex b.\ne(b)\nd(b, a)=1\nd(b, c)=1\nd(b, d)=2\nd(b, e)=3\nd(b, f)=2\nd(b, g)=2\nHence the eccentricity of vertex b is 3\n"
},
{
"code": null,
"e": 29823,
"s": 29751,
"text": "Notation used:\ne(V)\nhere e(v) determines the eccentricity of vertex V.\n"
},
{
"code": null,
"e": 29878,
"s": 29823,
"text": "Let us try to understand this using following example."
},
{
"code": null,
"e": 30054,
"s": 29878,
"text": "From the above diagram lets try to find the eccentricity of vertex b.\ne(b)\nd(b, a)=1\nd(b, c)=1\nd(b, d)=2\nd(b, e)=3\nd(b, f)=2\nd(b, g)=2\nHence the eccentricity of vertex b is 3\n"
},
{
"code": null,
"e": 30397,
"s": 30054,
"text": "Radius of a Connected GraphThe minimum value of eccentricity from all vertices is basically considered as the radius of connected graph.Notation used:\nr(G)\nhere G is the connected graph.\nLet us try to understand this using following example.From the above diagram:\nr(G) is 2.\nBecause the minimum value of eccentricity from all vertices is 2.\n"
},
{
"code": null,
"e": 30449,
"s": 30397,
"text": "Notation used:\nr(G)\nhere G is the connected graph.\n"
},
{
"code": null,
"e": 30504,
"s": 30449,
"text": "Let us try to understand this using following example."
},
{
"code": null,
"e": 30606,
"s": 30504,
"text": "From the above diagram:\nr(G) is 2.\nBecause the minimum value of eccentricity from all vertices is 2.\n"
},
{
"code": null,
"e": 30998,
"s": 30606,
"text": "Diameter of A Connected GraphUnlike the radius of the connected graph here we basically used the maximum value of eccentricity from all vertices to determine the diameter of the graph.Notation used:\nd(G)\nwhere G is the connected graph.\nLet us try to understand this using following example.From the above diagram:\nd(G) is 3.\nBecause the maximum value of eccentricity from all vertices is 3.\n"
},
{
"code": null,
"e": 31051,
"s": 30998,
"text": "Notation used:\nd(G)\nwhere G is the connected graph.\n"
},
{
"code": null,
"e": 31106,
"s": 31051,
"text": "Let us try to understand this using following example."
},
{
"code": null,
"e": 31208,
"s": 31106,
"text": "From the above diagram:\nd(G) is 3.\nBecause the maximum value of eccentricity from all vertices is 3.\n"
},
{
"code": null,
"e": 31652,
"s": 31208,
"text": "Central Point and CentreThe vertex having minimum eccentricity is considered as the central point of the graph.And the sets of all central point is considered as the centre of Graph.if\ne(V)=r(G)\nthen v is the central point.\nLet us try to understand this using following example.In the above diagram the central point will be f.\nbecause \ne(f)=r(G)=2\nhence f is considered as the central point of graph.\nHence f is also the centre of the graph.\n"
},
{
"code": null,
"e": 31695,
"s": 31652,
"text": "if\ne(V)=r(G)\nthen v is the central point.\n"
},
{
"code": null,
"e": 31750,
"s": 31695,
"text": "Let us try to understand this using following example."
},
{
"code": null,
"e": 31916,
"s": 31750,
"text": "In the above diagram the central point will be f.\nbecause \ne(f)=r(G)=2\nhence f is considered as the central point of graph.\nHence f is also the centre of the graph.\n"
},
{
"code": null,
"e": 31938,
"s": 31916,
"text": "Data Structures-Graph"
},
{
"code": null,
"e": 31951,
"s": 31938,
"text": "graph-basics"
},
{
"code": null,
"e": 31957,
"s": 31951,
"text": "Graph"
},
{
"code": null,
"e": 31963,
"s": 31957,
"text": "Graph"
},
{
"code": null,
"e": 32061,
"s": 31963,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32097,
"s": 32061,
"text": "Best First Search (Informed Search)"
},
{
"code": null,
"e": 32162,
"s": 32097,
"text": "Find if there is a path between two vertices in a directed graph"
},
{
"code": null,
"e": 32204,
"s": 32162,
"text": "Graph Coloring | Set 2 (Greedy Algorithm)"
},
{
"code": null,
"e": 32274,
"s": 32204,
"text": "Vertex Cover Problem | Set 1 (Introduction and Approximate Algorithm)"
},
{
"code": null,
"e": 32355,
"s": 32274,
"text": "Iterative Deepening Search(IDS) or Iterative Deepening Depth First Search(IDDFS)"
},
{
"code": null,
"e": 32382,
"s": 32355,
"text": "Maximum Bipartite Matching"
},
{
"code": null,
"e": 32429,
"s": 32382,
"text": "Eulerian path and circuit for undirected graph"
},
{
"code": null,
"e": 32470,
"s": 32429,
"text": "Longest Path in a Directed Acyclic Graph"
},
{
"code": null,
"e": 32549,
"s": 32470,
"text": "Comparison between Adjacency List and Adjacency Matrix representation of Graph"
}
] |
Check for Palindrome after every character replacement Query - GeeksforGeeks
|
10 Jul, 2021
Given a string str and Q queries. Each query contains a pair of integers (i1, i2) and a character ‘ch’. We need to replace characters at indexes i1 and i2 with new character ‘ch’ and then tell if string str is palindrome or not. (0 <= i1, i2 < string_length)Examples:
Input : str = "geeks" Q = 2
query 1: i1 = 3 ,i2 = 0, ch = 'e'
query 2: i1 = 0 ,i2 = 2, ch = 's'
Output : query 1: "NO"
query 2: "NO"
Explanation :
In query 1 : i1 = 3 , i2 = 0 ch = 'e'
After replacing char at index i1, i2
str[3] = 'e', str[0] = 'e'
string become "eeees" which is not
palindrome so output "NO"
In query 2 : i1 = 0 i2 = 2 ch = 's'
After replacing char at index i1 , i2
str[0] = 's', str[2] = 's'
string become "sesks" which is
palindrome so output "NO"
Input : str = "jasonamat" Q = 3
query 1: i1 = 3, i2 = 8 ch = 'j'
query 2: i1 = 2, i2 = 6 ch = 'n'
query 3: i1 = 3, i2 = 7 ch = 'a'
Output :
query 1: "NO"
query 2: "NO"
query 3: "YES"
A Simple solution is that for each query , we replace character at indexes (i1 & i2) with a new character ‘ch’ and then check if string is palindrome or not.Below is implementation of above idea
C++
Python3
// C++ program to find if string becomes palindrome// after every query.#include<bits/stdc++.h>using namespace std; // Function to check if string is Palindrome or Notbool IsPalindrome(string &str){ int n = strlen(str); for (int i = 0; i < n/2 ; i++) if (str[i] != str[n-1-i]) return false; return true;} // Takes two inputs for Q queries. For every query, it// prints Yes if string becomes palindrome and No if not.void Query(string &str, int Q){ int i1, i2; char ch; // Process all queries one by one for (int q = 1 ; q <= Q ; q++ ) { cin >> i1 >> i2 >> ch; // query 1: i1 = 3 ,i2 = 0, ch = 'e' // query 2: i1 = 0 ,i2 = 2 , ch = 's' // replace character at index i1 & i2 with new 'ch' str[i1] = str[i2] = ch; // check string is palindrome or not (isPalindrome(str)== true) ? cout << "YES" << endl : cout << "NO" << endl; }} // Driver programint main(){ char str[] = "geeks"; int Q = 2; Query(str, Q); return 0;}
# Python3 program to find if# string becomes palindrome# after every query. # Function to check if string# is Palindrome or Notdef isPalindrome(string: list) -> bool: n = len(string) for i in range(n // 2): if string[i] != string[n - 1 - i]: return False return True # Takes two inputs for Q queries.# For every query, it prints Yes# if string becomes palindrome# and No if not.def Query(string: list, Q: int) -> None: # Process all queries one by one for i in range(Q): # To get space separated # input from user inp = list(input().split()) # parsing user inputs as integers # and strings/char i1 = int(inp[0]) i2 = int(inp[1]) ch = inp[2] # query 1: i1 = 3 ,i2 = 0, ch = 'e' # query 2: i1 = 0 ,i2 = 2 , ch = 's' # replace character at index # i1 & i2 with new 'ch' string[i1] = string[i2] = ch # check string is palindrome or not if isPalindrome(string): print("Yes") else: print("No") # Driver Codeif __name__ == "__main__": string = list("geeks") Q = 2 Query(string, Q) # This code is contributed by# sanjeev2552
Input:
3 0 e
0 2 s
Output:
"NO"
"YES"
Time complexity O(Q*n) (n is length of string )An efficient solution is to use hashing. We create an empty hash set that stores indexes that are unequal in palindrome (Note: ” we have to store indexes only first half of string that are unequal “).
Given string "str" and length 'n'.
Create an empty set S and store unequal indexes in first half.
Do following for each query :
1. First replace character at indexes i1 & i2 with
new char "ch"
2. If i1 and/or i2 are/is greater than n/2 then convert
into first half index(es)
3. In this step we make sure that S contains maintains
unequal indexes of first half.
a) If str[i1] == str [n - 1 - i1] means i1 becomes
equal after replacement, remove it from S (if present)
Else add i1 to S
b) Repeat step a) for i2 (replace i1 with i2)
4. If S is empty then string is palindrome else NOT
Below is C++ implementation of above idea
CPP
// C++/c program check if given string is palindrome// or not after every query#include<bits/stdc++.h>using namespace std; // This function makes sure that set S contains// unequal characters from first half. This is called// for every character.void addRemoveUnequal(string &str, int index, int n, unordered_set<int> &S){ // If character becomes equal after query if (str[index] == str[n-1-index]) { // Remove the current index from set if it // is present auto it = S.find(index); if (it != S.end()) S.erase(it) ; } // If not equal after query, insert it into set else S.insert(index);} // Takes two inputs for Q queries. For every query, it// prints Yes if string becomes palindrome and No if not.void Query(string &str, int Q){ int n = str.length(); // create an empty set that store indexes of // unequal location in palindrome unordered_set<int> S; // we store indexes that are unequal in palindrome // traverse only first half of string for (int i=0; i<n/2; i++) if (str[i] != str[n-1-i]) S.insert(i); // traversal the query for (int q=1; q<=Q; q++) { // query 1: i1 = 3, i2 = 0, ch = 'e' // query 2: i1 = 0, i2 = 2, ch = 's' int i1, i2; char ch; cin >> i1 >> i2 >> ch; // Replace characters at indexes i1 & i2 with // new char 'ch' str[i1] = str [i2] = ch; // If i1 and/or i2 greater than n/2 // then convert into first half index if (i1 > n/2) i1 = n- 1 -i1; if (i2 > n/2) i2 = n -1 - i2; // call addRemoveUnequal function to insert and remove // unequal indexes addRemoveUnequal(str, i1 , n, S ); addRemoveUnequal(str, i2 , n, S ); // if set is not empty then string is not palindrome S.empty()? cout << "YES\n" : cout << "NO\n"; }} // Driver programint main(){ string str = "geeks"; int Q = 2 ; Query(str, Q); return 0;}
Input:
3 0 e
0 2 s
Output:
"NO"
"YES"
Time Complexity : O(Q + n) under the assumption that set insert, delete and find operations take O(1) time.This article is contributed by Nishant_Singh(Pintu). 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.
sanjeev2552
vnkarthik7
Hash
Strings
Hash
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Quadratic Probing in Hashing
Load Factor and Rehashing
Implementing own Hash Table with Open Addressing Linear Probing
Practice Problems on Hashing
Advantages of BST over Hash Table
Longest Common Subsequence | DP-4
Reverse a string in Java
Write a program to print all permutations of a given string
KMP Algorithm for Pattern Searching
C++ Data Types
|
[
{
"code": null,
"e": 24765,
"s": 24737,
"text": "\n10 Jul, 2021"
},
{
"code": null,
"e": 25035,
"s": 24765,
"text": "Given a string str and Q queries. Each query contains a pair of integers (i1, i2) and a character ‘ch’. We need to replace characters at indexes i1 and i2 with new character ‘ch’ and then tell if string str is palindrome or not. (0 <= i1, i2 < string_length)Examples: "
},
{
"code": null,
"e": 25937,
"s": 25035,
"text": "Input : str = \"geeks\" Q = 2\n query 1: i1 = 3 ,i2 = 0, ch = 'e'\n query 2: i1 = 0 ,i2 = 2, ch = 's'\nOutput : query 1: \"NO\"\n query 2: \"NO\"\nExplanation :\n In query 1 : i1 = 3 , i2 = 0 ch = 'e'\n After replacing char at index i1, i2\n str[3] = 'e', str[0] = 'e'\n string become \"eeees\" which is not\n palindrome so output \"NO\"\n In query 2 : i1 = 0 i2 = 2 ch = 's'\n After replacing char at index i1 , i2\n str[0] = 's', str[2] = 's'\n string become \"sesks\" which is\n palindrome so output \"NO\"\n\nInput : str = \"jasonamat\" Q = 3\n query 1: i1 = 3, i2 = 8 ch = 'j'\n query 2: i1 = 2, i2 = 6 ch = 'n'\n query 3: i1 = 3, i2 = 7 ch = 'a'\nOutput :\n query 1: \"NO\"\n query 2: \"NO\"\n query 3: \"YES\""
},
{
"code": null,
"e": 26136,
"s": 25939,
"text": "A Simple solution is that for each query , we replace character at indexes (i1 & i2) with a new character ‘ch’ and then check if string is palindrome or not.Below is implementation of above idea "
},
{
"code": null,
"e": 26140,
"s": 26136,
"text": "C++"
},
{
"code": null,
"e": 26148,
"s": 26140,
"text": "Python3"
},
{
"code": "// C++ program to find if string becomes palindrome// after every query.#include<bits/stdc++.h>using namespace std; // Function to check if string is Palindrome or Notbool IsPalindrome(string &str){ int n = strlen(str); for (int i = 0; i < n/2 ; i++) if (str[i] != str[n-1-i]) return false; return true;} // Takes two inputs for Q queries. For every query, it// prints Yes if string becomes palindrome and No if not.void Query(string &str, int Q){ int i1, i2; char ch; // Process all queries one by one for (int q = 1 ; q <= Q ; q++ ) { cin >> i1 >> i2 >> ch; // query 1: i1 = 3 ,i2 = 0, ch = 'e' // query 2: i1 = 0 ,i2 = 2 , ch = 's' // replace character at index i1 & i2 with new 'ch' str[i1] = str[i2] = ch; // check string is palindrome or not (isPalindrome(str)== true) ? cout << \"YES\" << endl : cout << \"NO\" << endl; }} // Driver programint main(){ char str[] = \"geeks\"; int Q = 2; Query(str, Q); return 0;}",
"e": 27207,
"s": 26148,
"text": null
},
{
"code": "# Python3 program to find if# string becomes palindrome# after every query. # Function to check if string# is Palindrome or Notdef isPalindrome(string: list) -> bool: n = len(string) for i in range(n // 2): if string[i] != string[n - 1 - i]: return False return True # Takes two inputs for Q queries.# For every query, it prints Yes# if string becomes palindrome# and No if not.def Query(string: list, Q: int) -> None: # Process all queries one by one for i in range(Q): # To get space separated # input from user inp = list(input().split()) # parsing user inputs as integers # and strings/char i1 = int(inp[0]) i2 = int(inp[1]) ch = inp[2] # query 1: i1 = 3 ,i2 = 0, ch = 'e' # query 2: i1 = 0 ,i2 = 2 , ch = 's' # replace character at index # i1 & i2 with new 'ch' string[i1] = string[i2] = ch # check string is palindrome or not if isPalindrome(string): print(\"Yes\") else: print(\"No\") # Driver Codeif __name__ == \"__main__\": string = list(\"geeks\") Q = 2 Query(string, Q) # This code is contributed by# sanjeev2552",
"e": 28405,
"s": 27207,
"text": null
},
{
"code": null,
"e": 28414,
"s": 28405,
"text": "Input: "
},
{
"code": null,
"e": 28426,
"s": 28414,
"text": "3 0 e\n0 2 s"
},
{
"code": null,
"e": 28436,
"s": 28426,
"text": "Output: "
},
{
"code": null,
"e": 28447,
"s": 28436,
"text": "\"NO\"\n\"YES\""
},
{
"code": null,
"e": 28697,
"s": 28447,
"text": "Time complexity O(Q*n) (n is length of string )An efficient solution is to use hashing. We create an empty hash set that stores indexes that are unequal in palindrome (Note: ” we have to store indexes only first half of string that are unequal “). "
},
{
"code": null,
"e": 29349,
"s": 28697,
"text": "Given string \"str\" and length 'n'.\nCreate an empty set S and store unequal indexes in first half.\nDo following for each query :\n 1. First replace character at indexes i1 & i2 with \n new char \"ch\"\n\n 2. If i1 and/or i2 are/is greater than n/2 then convert \n into first half index(es)\n\n 3. In this step we make sure that S contains maintains \n unequal indexes of first half.\n a) If str[i1] == str [n - 1 - i1] means i1 becomes \n equal after replacement, remove it from S (if present)\n Else add i1 to S \n b) Repeat step a) for i2 (replace i1 with i2) \n\n 4. If S is empty then string is palindrome else NOT"
},
{
"code": null,
"e": 29393,
"s": 29349,
"text": "Below is C++ implementation of above idea "
},
{
"code": null,
"e": 29397,
"s": 29393,
"text": "CPP"
},
{
"code": "// C++/c program check if given string is palindrome// or not after every query#include<bits/stdc++.h>using namespace std; // This function makes sure that set S contains// unequal characters from first half. This is called// for every character.void addRemoveUnequal(string &str, int index, int n, unordered_set<int> &S){ // If character becomes equal after query if (str[index] == str[n-1-index]) { // Remove the current index from set if it // is present auto it = S.find(index); if (it != S.end()) S.erase(it) ; } // If not equal after query, insert it into set else S.insert(index);} // Takes two inputs for Q queries. For every query, it// prints Yes if string becomes palindrome and No if not.void Query(string &str, int Q){ int n = str.length(); // create an empty set that store indexes of // unequal location in palindrome unordered_set<int> S; // we store indexes that are unequal in palindrome // traverse only first half of string for (int i=0; i<n/2; i++) if (str[i] != str[n-1-i]) S.insert(i); // traversal the query for (int q=1; q<=Q; q++) { // query 1: i1 = 3, i2 = 0, ch = 'e' // query 2: i1 = 0, i2 = 2, ch = 's' int i1, i2; char ch; cin >> i1 >> i2 >> ch; // Replace characters at indexes i1 & i2 with // new char 'ch' str[i1] = str [i2] = ch; // If i1 and/or i2 greater than n/2 // then convert into first half index if (i1 > n/2) i1 = n- 1 -i1; if (i2 > n/2) i2 = n -1 - i2; // call addRemoveUnequal function to insert and remove // unequal indexes addRemoveUnequal(str, i1 , n, S ); addRemoveUnequal(str, i2 , n, S ); // if set is not empty then string is not palindrome S.empty()? cout << \"YES\\n\" : cout << \"NO\\n\"; }} // Driver programint main(){ string str = \"geeks\"; int Q = 2 ; Query(str, Q); return 0;}",
"e": 31441,
"s": 29397,
"text": null
},
{
"code": null,
"e": 31448,
"s": 31441,
"text": "Input:"
},
{
"code": null,
"e": 31460,
"s": 31448,
"text": "3 0 e\n0 2 s"
},
{
"code": null,
"e": 31470,
"s": 31460,
"text": "Output: "
},
{
"code": null,
"e": 31481,
"s": 31470,
"text": "\"NO\"\n\"YES\""
},
{
"code": null,
"e": 32017,
"s": 31481,
"text": "Time Complexity : O(Q + n) under the assumption that set insert, delete and find operations take O(1) time.This article is contributed by Nishant_Singh(Pintu). 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": 32029,
"s": 32017,
"text": "sanjeev2552"
},
{
"code": null,
"e": 32040,
"s": 32029,
"text": "vnkarthik7"
},
{
"code": null,
"e": 32045,
"s": 32040,
"text": "Hash"
},
{
"code": null,
"e": 32053,
"s": 32045,
"text": "Strings"
},
{
"code": null,
"e": 32058,
"s": 32053,
"text": "Hash"
},
{
"code": null,
"e": 32066,
"s": 32058,
"text": "Strings"
},
{
"code": null,
"e": 32164,
"s": 32066,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32173,
"s": 32164,
"text": "Comments"
},
{
"code": null,
"e": 32186,
"s": 32173,
"text": "Old Comments"
},
{
"code": null,
"e": 32215,
"s": 32186,
"text": "Quadratic Probing in Hashing"
},
{
"code": null,
"e": 32241,
"s": 32215,
"text": "Load Factor and Rehashing"
},
{
"code": null,
"e": 32305,
"s": 32241,
"text": "Implementing own Hash Table with Open Addressing Linear Probing"
},
{
"code": null,
"e": 32334,
"s": 32305,
"text": "Practice Problems on Hashing"
},
{
"code": null,
"e": 32368,
"s": 32334,
"text": "Advantages of BST over Hash Table"
},
{
"code": null,
"e": 32402,
"s": 32368,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 32427,
"s": 32402,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 32487,
"s": 32427,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 32523,
"s": 32487,
"text": "KMP Algorithm for Pattern Searching"
}
] |
Animated Floating Action Button in kivy - Python - GeeksforGeeks
|
19 Oct, 2021
Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications.In this article we will learn about how can we Add the Animation to a Floating Action button. To learn How to create it you must know about the Animation and Clock.
Animation : Animation and AnimationTransition are used to animate Widget properties. You must specify at least a property name and target value. To use an Animation, follow these steps:
Setup an Animation object
Use the Animation object on a Widget
To animate a Widget’s x or y position, simply specify the target x/y values where you want the widget positioned at the end of the animation:
anim = Animation(x=100, y=100)
anim.start(widget)
Clock: The Clock object allows you to schedule a function call in the future; once or repeatedly at specified intervals.It is must to use kivy inbuilt module while working with Animation and clock –
from kivy.animation import Animation
from kivy.clock import Clock
Basic Approach:
1) import kivy
2) import kivyApp
3) import Boxlayout
4) import Animation
5) Import Clock
6) Set minimum version(optional)
7) create Layout class and Add(create) animation in it
8) create App class
9) Set up .kv file :
1) Add Floating Button Properties
2) Create Main Window
3) Add Float Button(don't forget to give id)
10) return Layout/widget/Class(according to requirement)
11) Run an instance of the class
Kivy Tutorial – Learn Kivy with Examples.
Implementation of the Approach:main.py file
Python3
## Sample Python application demonstrating that## How to create a button like floating Action Button## in Kivy using .kv file #################################################### import modules import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # BoxLayout arranges widgets in either# in a vertical fashion that# is one on top of another or in a horizontal# fashion that is one after another.from kivy.uix.boxlayout import BoxLayout # To change the kivy default settings # we use this module config from kivy.config import Config # 0 being off 1 being on as in true / false # you can use 0 or 1 && True or False Config.set('graphics', 'resizable', True) # The Clock object allows you to# schedule a function call in the futurefrom kivy.clock import Clock # To work with Animation you must have to import itfrom kivy.animation import Animation # creating the root widget used in .kv fileclass MainWindow(BoxLayout): def __init__(self, **kwargs): super().__init__(**kwargs) # Schedule the interval for the animation Clock.schedule_interval(self.breath, 1) # Creating Animation function name breath def breath(self, dtx): # create an animation object. This object could be stored # and reused each call or reused across different widgets. # += is a sequential step anim = (Animation(btn_size =(60, 60), t ='in_quad', duration =.5)+ Animation(btn_size =(70, 70), t ='in_quad', duration =.5)) # Call the button id tgt = self.ids.cta # Start the Animation anim.start(tgt) # creating the App class in which name#.kv file is to be named main.kvclass MainApp(App): # defining build() def build(self): # returning the instance of root class return MainWindow() # run the appif __name__ == '__main__': MainApp().run()
.kv file
Python3
#.kv file implementation of BoxLayout # using Float Layout for the creation of Floatbutton# Here we are creating the properties of button# Button will be created in Main window Box Layout <FloatButton@FloatLayout> id: float_root # Giving id to button size_hint: (None, None) text: '' btn_size: (70, 70) size: (70, 70) bg_color: (0.404, 0.227, 0.718, 1.0) pos_hint: {'x': .6} # Adding shape and all, size, position to button Button: text: float_root.text markup: True font_size: 40 size_hint: (None, None) size: float_root.btn_size pos_hint: {'x': 5.5, 'y': 3.8} background_normal: '' background_color: (0, 0, 0, 0) canvas.before: Color: rgba: (0.404, 0.227, 0.718, 1.0) Ellipse: size: self.size pos: self.pos # Creation of main window<MainWindow>: BoxLayout: # Creating the Float button FloatButton: # Giving id to the button # So that we can Apply the Animation id: cta text: '+' markup: True background_color: 1, 0, 1, 0
Output:
Video Output:
saurabh1990aror
Python-gui
Python-kivy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
Read a file line by line in Python
Defaultdict in Python
Different ways to create Pandas Dataframe
sum() function in Python
Iterate over a list in Python
How to Install PIP on Windows ?
Deque in Python
Python String | replace()
|
[
{
"code": null,
"e": 23975,
"s": 23947,
"text": "\n19 Oct, 2021"
},
{
"code": null,
"e": 24376,
"s": 23975,
"text": "Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications.In this article we will learn about how can we Add the Animation to a Floating Action button. To learn How to create it you must know about the Animation and Clock. "
},
{
"code": null,
"e": 24563,
"s": 24376,
"text": "Animation : Animation and AnimationTransition are used to animate Widget properties. You must specify at least a property name and target value. To use an Animation, follow these steps: "
},
{
"code": null,
"e": 24589,
"s": 24563,
"text": "Setup an Animation object"
},
{
"code": null,
"e": 24626,
"s": 24589,
"text": "Use the Animation object on a Widget"
},
{
"code": null,
"e": 24770,
"s": 24626,
"text": "To animate a Widget’s x or y position, simply specify the target x/y values where you want the widget positioned at the end of the animation: "
},
{
"code": null,
"e": 24820,
"s": 24770,
"text": "anim = Animation(x=100, y=100)\nanim.start(widget)"
},
{
"code": null,
"e": 25021,
"s": 24820,
"text": "Clock: The Clock object allows you to schedule a function call in the future; once or repeatedly at specified intervals.It is must to use kivy inbuilt module while working with Animation and clock – "
},
{
"code": null,
"e": 25087,
"s": 25021,
"text": "from kivy.animation import Animation\nfrom kivy.clock import Clock"
},
{
"code": null,
"e": 25536,
"s": 25089,
"text": "Basic Approach:\n\n1) import kivy\n2) import kivyApp\n3) import Boxlayout\n4) import Animation\n5) Import Clock\n6) Set minimum version(optional)\n7) create Layout class and Add(create) animation in it\n8) create App class\n9) Set up .kv file :\n 1) Add Floating Button Properties\n 2) Create Main Window\n 3) Add Float Button(don't forget to give id)\n10) return Layout/widget/Class(according to requirement)\n11) Run an instance of the class"
},
{
"code": null,
"e": 25580,
"s": 25538,
"text": "Kivy Tutorial – Learn Kivy with Examples."
},
{
"code": null,
"e": 25626,
"s": 25580,
"text": "Implementation of the Approach:main.py file "
},
{
"code": null,
"e": 25634,
"s": 25626,
"text": "Python3"
},
{
"code": "## Sample Python application demonstrating that## How to create a button like floating Action Button## in Kivy using .kv file #################################################### import modules import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # BoxLayout arranges widgets in either# in a vertical fashion that# is one on top of another or in a horizontal# fashion that is one after another.from kivy.uix.boxlayout import BoxLayout # To change the kivy default settings # we use this module config from kivy.config import Config # 0 being off 1 being on as in true / false # you can use 0 or 1 && True or False Config.set('graphics', 'resizable', True) # The Clock object allows you to# schedule a function call in the futurefrom kivy.clock import Clock # To work with Animation you must have to import itfrom kivy.animation import Animation # creating the root widget used in .kv fileclass MainWindow(BoxLayout): def __init__(self, **kwargs): super().__init__(**kwargs) # Schedule the interval for the animation Clock.schedule_interval(self.breath, 1) # Creating Animation function name breath def breath(self, dtx): # create an animation object. This object could be stored # and reused each call or reused across different widgets. # += is a sequential step anim = (Animation(btn_size =(60, 60), t ='in_quad', duration =.5)+ Animation(btn_size =(70, 70), t ='in_quad', duration =.5)) # Call the button id tgt = self.ids.cta # Start the Animation anim.start(tgt) # creating the App class in which name#.kv file is to be named main.kvclass MainApp(App): # defining build() def build(self): # returning the instance of root class return MainWindow() # run the appif __name__ == '__main__': MainApp().run()",
"e": 27583,
"s": 25634,
"text": null
},
{
"code": null,
"e": 27594,
"s": 27583,
"text": ".kv file "
},
{
"code": null,
"e": 27602,
"s": 27594,
"text": "Python3"
},
{
"code": "#.kv file implementation of BoxLayout # using Float Layout for the creation of Floatbutton# Here we are creating the properties of button# Button will be created in Main window Box Layout <FloatButton@FloatLayout> id: float_root # Giving id to button size_hint: (None, None) text: '' btn_size: (70, 70) size: (70, 70) bg_color: (0.404, 0.227, 0.718, 1.0) pos_hint: {'x': .6} # Adding shape and all, size, position to button Button: text: float_root.text markup: True font_size: 40 size_hint: (None, None) size: float_root.btn_size pos_hint: {'x': 5.5, 'y': 3.8} background_normal: '' background_color: (0, 0, 0, 0) canvas.before: Color: rgba: (0.404, 0.227, 0.718, 1.0) Ellipse: size: self.size pos: self.pos # Creation of main window<MainWindow>: BoxLayout: # Creating the Float button FloatButton: # Giving id to the button # So that we can Apply the Animation id: cta text: '+' markup: True background_color: 1, 0, 1, 0",
"e": 28777,
"s": 27602,
"text": null
},
{
"code": null,
"e": 28786,
"s": 28777,
"text": "Output: "
},
{
"code": null,
"e": 28804,
"s": 28788,
"text": "Video Output: "
},
{
"code": null,
"e": 28822,
"s": 28806,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 28833,
"s": 28822,
"text": "Python-gui"
},
{
"code": null,
"e": 28845,
"s": 28833,
"text": "Python-kivy"
},
{
"code": null,
"e": 28852,
"s": 28845,
"text": "Python"
},
{
"code": null,
"e": 28950,
"s": 28852,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28959,
"s": 28950,
"text": "Comments"
},
{
"code": null,
"e": 28972,
"s": 28959,
"text": "Old Comments"
},
{
"code": null,
"e": 28990,
"s": 28972,
"text": "Python Dictionary"
},
{
"code": null,
"e": 29012,
"s": 28990,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 29047,
"s": 29012,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 29069,
"s": 29047,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 29111,
"s": 29069,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 29136,
"s": 29111,
"text": "sum() function in Python"
},
{
"code": null,
"e": 29166,
"s": 29136,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 29198,
"s": 29166,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29214,
"s": 29198,
"text": "Deque in Python"
}
] |
Count number of pairs in array having sum divisible by K | SET 2 - GeeksforGeeks
|
23 Apr, 2021
Given an array A[] and positive integer K, the task is to count the total number of pairs in the array whose sum is divisible by K.Examples:
Input : A[] = {2, 2, 1, 7, 5, 3}, K = 4 Output : 5 There are five pairs possible whose sum Is divisible by ‘4’ i.e., (2, 2), (1, 7), (7, 5), (1, 3) and (5, 3)Input : A[] = {5, 9, 36, 74, 52, 31, 42}, K = 3 Output : 7
Approach: In the previous post, an approach using hashing is discussed. In this article, another approach using hashing is discussed.
Analyzing the statement we can say we need to make pairs of (a, b) such that:
(a + b) % K = 0
=> a%K + b%K = 0
=> a%K + b%K = K%K
=> b%K = K%K - a%K
=> b%K = (K - a%K) % K. {Range of a%K => [0,K-1]}
The idea is a can be paired with (K — a%K) % K. Now we have to find the same for each a present in the given array.
The algorithm would create a hash-map:Keys: possible remainders for value%K i.e 0 to K-1 Values: count of values with value%K = key
The stepwise algorithm is:
Find x = arr[i]%k.This array element can be paired with array elements having mod value k-x. This frequency count of array elements is stored in hash. So add that count to answer.Increment count for x in hash.In case the value of x is zero, then it can be paired only with elements having 0 mod value.
Find x = arr[i]%k.
This array element can be paired with array elements having mod value k-x. This frequency count of array elements is stored in hash. So add that count to answer.
Increment count for x in hash.
In case the value of x is zero, then it can be paired only with elements having 0 mod value.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ Program to count pairs// whose sum divisible by 'K'#include <bits/stdc++.h>using namespace std; // Program to count pairs whose sum divisible// by 'K'int countKdivPairs(int A[], int n, int K){ // Create a frequency array to count // occurrences of all remainders when // divided by K int freq[K] = { 0 }; // To store count of pairs. int ans = 0; // Traverse the array, compute the remainder // and add k-remainder value hash count to ans for (int i = 0; i < n; i++) { int rem = A[i] % K; // Count number of ( A[i], (K - rem)%K ) pairs ans += freq[(K - rem) % K]; // Increment count of remainder in hash map freq[rem]++; } return ans;} // Driver codeint main(){ int A[] = { 2, 2, 1, 7, 5, 3 }; int n = sizeof(A) / sizeof(A[0]); int K = 4; cout << countKdivPairs(A, n, K); return 0;}
// JAVA Program to count pairs whose sum divisible// by 'K'class GFG{ static int countKdivPairs(int A[], int n, int K) { // Create a frequency array to count // occurrences of all remainders when // divided by K int []freq = new int[K]; // To store count of pairs. int ans = 0; // Traverse the array, compute the remainder // and add k-remainder value hash count to ans for (int i = 0; i < n; i++) { int rem = A[i] % K; // Count number of ( A[i], (K - rem)%K ) pairs ans += freq[(K - rem) % K]; // Increment count of remainder in hash map freq[rem]++; } return ans; } // Driver code public static void main(String[] args) { int A[] = { 2, 2, 1, 7, 5, 3 }; int n = A.length; int K = 4; System.out.println(countKdivPairs(A, n, K)); }} // This code is contributed by Princi Singh, Yadvendra Naveen
# Python Program to count pairs whose sum divisible# by 'K'def countKdivPairs(A, n, K): # Create a frequency array to count # occurrences of all remainders when # divided by K freq = [0 for i in range(K)] # To store count of pairs. ans = 0 # Traverse the array, compute the remainder # and add k-remainder value hash count to ans for i in range(n): rem = A[i] % K # Count number of ( A[i], (K - rem)%K ) pairs ans += freq[(K - rem) % K] # Increment count of remainder in hash map freq[rem] += 1 return ans # Driver codeif __name__ == '__main__': A = [2, 2, 1, 7, 5, 3] n = len(A) K = 4 print(countKdivPairs(A, n, K)) # This code is contributed by# Surendra_Gangwar, Yadvendra Naveen
// C# Program to count pairs// whose sum divisible by 'K'using System; class GFG{ // Program to count pairs whose sum divisible// by 'K'static int countKdivPairs(int []A, int n, int K){ // Create a frequency array to count // occurrences of all remainders when // divided by K int []freq = new int[K]; // To store count of pairs. int ans = 0; // Traverse the array, compute the remainder // and add k-remainder value hash count to ans for (int i = 0; i < n; i++) { int rem = A[i] % K; // Count number of ( A[i], (K - rem)%K ) pairs ans += freq[(K - rem) % K]; // Increment count of remainder in hash map freq[rem]++; } return ans;} // Driver codepublic static void Main(String[] args){ int []A = { 2, 2, 1, 7, 5, 3 }; int n = A.Length; int K = 4; Console.WriteLine(countKdivPairs(A, n, K));}} // This code contributed by Rajput-Ji, Yadvendra Naveen
<script> // Javascript Program to count pairs// whose sum divisible by 'K' // Program to count pairs whose sum divisible// by 'K'function countKdivPairs( A, n, K){ // Create a frequency array to count // occurrences of all remainders when // divided by K var freq = Array(K).fill(0); // To store count of pairs. var ans = 0; // Traverse the array, compute the remainder // and add k-remainder value hash count to ans for (var i = 0; i < n; i++) { var rem = A[i] % K; // Count number of ( A[i], (K - rem)%K ) pairs ans += freq[(K - rem) % K]; // Increment count of remainder in hash map freq[rem]++; } return ans;} // Driver codevar A = [ 2, 2, 1, 7, 5, 3 ];var n = A.length;var K = 4;document.write( countKdivPairs(A, n, K)); // This code is contributed by itsok.</script>
5
Time Complexity: O(N) Auxiliary Space: O(K)
princi singh
Rajput-Ji
SURENDRA_GANGWAR
Yadvendra Naveen
itsok
Hash
Arrays
Hash
Mathematical
Arrays
Hash
Mathematical
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
Introduction to Arrays
Linear Search
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Hashing | Set 3 (Open Addressing)
Count pairs with given sum
|
[
{
"code": null,
"e": 25156,
"s": 25128,
"text": "\n23 Apr, 2021"
},
{
"code": null,
"e": 25298,
"s": 25156,
"text": "Given an array A[] and positive integer K, the task is to count the total number of pairs in the array whose sum is divisible by K.Examples: "
},
{
"code": null,
"e": 25517,
"s": 25298,
"text": "Input : A[] = {2, 2, 1, 7, 5, 3}, K = 4 Output : 5 There are five pairs possible whose sum Is divisible by ‘4’ i.e., (2, 2), (1, 7), (7, 5), (1, 3) and (5, 3)Input : A[] = {5, 9, 36, 74, 52, 31, 42}, K = 3 Output : 7 "
},
{
"code": null,
"e": 25651,
"s": 25517,
"text": "Approach: In the previous post, an approach using hashing is discussed. In this article, another approach using hashing is discussed."
},
{
"code": null,
"e": 25729,
"s": 25651,
"text": "Analyzing the statement we can say we need to make pairs of (a, b) such that:"
},
{
"code": null,
"e": 25876,
"s": 25729,
"text": " (a + b) % K = 0\n => a%K + b%K = 0\n => a%K + b%K = K%K\n => b%K = K%K - a%K\n => b%K = (K - a%K) % K. {Range of a%K => [0,K-1]}"
},
{
"code": null,
"e": 25992,
"s": 25876,
"text": "The idea is a can be paired with (K — a%K) % K. Now we have to find the same for each a present in the given array."
},
{
"code": null,
"e": 26124,
"s": 25992,
"text": "The algorithm would create a hash-map:Keys: possible remainders for value%K i.e 0 to K-1 Values: count of values with value%K = key"
},
{
"code": null,
"e": 26152,
"s": 26124,
"text": "The stepwise algorithm is: "
},
{
"code": null,
"e": 26454,
"s": 26152,
"text": "Find x = arr[i]%k.This array element can be paired with array elements having mod value k-x. This frequency count of array elements is stored in hash. So add that count to answer.Increment count for x in hash.In case the value of x is zero, then it can be paired only with elements having 0 mod value."
},
{
"code": null,
"e": 26473,
"s": 26454,
"text": "Find x = arr[i]%k."
},
{
"code": null,
"e": 26635,
"s": 26473,
"text": "This array element can be paired with array elements having mod value k-x. This frequency count of array elements is stored in hash. So add that count to answer."
},
{
"code": null,
"e": 26666,
"s": 26635,
"text": "Increment count for x in hash."
},
{
"code": null,
"e": 26759,
"s": 26666,
"text": "In case the value of x is zero, then it can be paired only with elements having 0 mod value."
},
{
"code": null,
"e": 26812,
"s": 26759,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26816,
"s": 26812,
"text": "C++"
},
{
"code": null,
"e": 26821,
"s": 26816,
"text": "Java"
},
{
"code": null,
"e": 26829,
"s": 26821,
"text": "Python3"
},
{
"code": null,
"e": 26832,
"s": 26829,
"text": "C#"
},
{
"code": null,
"e": 26843,
"s": 26832,
"text": "Javascript"
},
{
"code": "// C++ Program to count pairs// whose sum divisible by 'K'#include <bits/stdc++.h>using namespace std; // Program to count pairs whose sum divisible// by 'K'int countKdivPairs(int A[], int n, int K){ // Create a frequency array to count // occurrences of all remainders when // divided by K int freq[K] = { 0 }; // To store count of pairs. int ans = 0; // Traverse the array, compute the remainder // and add k-remainder value hash count to ans for (int i = 0; i < n; i++) { int rem = A[i] % K; // Count number of ( A[i], (K - rem)%K ) pairs ans += freq[(K - rem) % K]; // Increment count of remainder in hash map freq[rem]++; } return ans;} // Driver codeint main(){ int A[] = { 2, 2, 1, 7, 5, 3 }; int n = sizeof(A) / sizeof(A[0]); int K = 4; cout << countKdivPairs(A, n, K); return 0;}",
"e": 27730,
"s": 26843,
"text": null
},
{
"code": "// JAVA Program to count pairs whose sum divisible// by 'K'class GFG{ static int countKdivPairs(int A[], int n, int K) { // Create a frequency array to count // occurrences of all remainders when // divided by K int []freq = new int[K]; // To store count of pairs. int ans = 0; // Traverse the array, compute the remainder // and add k-remainder value hash count to ans for (int i = 0; i < n; i++) { int rem = A[i] % K; // Count number of ( A[i], (K - rem)%K ) pairs ans += freq[(K - rem) % K]; // Increment count of remainder in hash map freq[rem]++; } return ans; } // Driver code public static void main(String[] args) { int A[] = { 2, 2, 1, 7, 5, 3 }; int n = A.length; int K = 4; System.out.println(countKdivPairs(A, n, K)); }} // This code is contributed by Princi Singh, Yadvendra Naveen",
"e": 28662,
"s": 27730,
"text": null
},
{
"code": "# Python Program to count pairs whose sum divisible# by 'K'def countKdivPairs(A, n, K): # Create a frequency array to count # occurrences of all remainders when # divided by K freq = [0 for i in range(K)] # To store count of pairs. ans = 0 # Traverse the array, compute the remainder # and add k-remainder value hash count to ans for i in range(n): rem = A[i] % K # Count number of ( A[i], (K - rem)%K ) pairs ans += freq[(K - rem) % K] # Increment count of remainder in hash map freq[rem] += 1 return ans # Driver codeif __name__ == '__main__': A = [2, 2, 1, 7, 5, 3] n = len(A) K = 4 print(countKdivPairs(A, n, K)) # This code is contributed by# Surendra_Gangwar, Yadvendra Naveen",
"e": 29448,
"s": 28662,
"text": null
},
{
"code": "// C# Program to count pairs// whose sum divisible by 'K'using System; class GFG{ // Program to count pairs whose sum divisible// by 'K'static int countKdivPairs(int []A, int n, int K){ // Create a frequency array to count // occurrences of all remainders when // divided by K int []freq = new int[K]; // To store count of pairs. int ans = 0; // Traverse the array, compute the remainder // and add k-remainder value hash count to ans for (int i = 0; i < n; i++) { int rem = A[i] % K; // Count number of ( A[i], (K - rem)%K ) pairs ans += freq[(K - rem) % K]; // Increment count of remainder in hash map freq[rem]++; } return ans;} // Driver codepublic static void Main(String[] args){ int []A = { 2, 2, 1, 7, 5, 3 }; int n = A.Length; int K = 4; Console.WriteLine(countKdivPairs(A, n, K));}} // This code contributed by Rajput-Ji, Yadvendra Naveen",
"e": 30387,
"s": 29448,
"text": null
},
{
"code": "<script> // Javascript Program to count pairs// whose sum divisible by 'K' // Program to count pairs whose sum divisible// by 'K'function countKdivPairs( A, n, K){ // Create a frequency array to count // occurrences of all remainders when // divided by K var freq = Array(K).fill(0); // To store count of pairs. var ans = 0; // Traverse the array, compute the remainder // and add k-remainder value hash count to ans for (var i = 0; i < n; i++) { var rem = A[i] % K; // Count number of ( A[i], (K - rem)%K ) pairs ans += freq[(K - rem) % K]; // Increment count of remainder in hash map freq[rem]++; } return ans;} // Driver codevar A = [ 2, 2, 1, 7, 5, 3 ];var n = A.length;var K = 4;document.write( countKdivPairs(A, n, K)); // This code is contributed by itsok.</script>",
"e": 31241,
"s": 30387,
"text": null
},
{
"code": null,
"e": 31243,
"s": 31241,
"text": "5"
},
{
"code": null,
"e": 31290,
"s": 31245,
"text": "Time Complexity: O(N) Auxiliary Space: O(K) "
},
{
"code": null,
"e": 31303,
"s": 31290,
"text": "princi singh"
},
{
"code": null,
"e": 31313,
"s": 31303,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 31330,
"s": 31313,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 31347,
"s": 31330,
"text": "Yadvendra Naveen"
},
{
"code": null,
"e": 31353,
"s": 31347,
"text": "itsok"
},
{
"code": null,
"e": 31358,
"s": 31353,
"text": "Hash"
},
{
"code": null,
"e": 31365,
"s": 31358,
"text": "Arrays"
},
{
"code": null,
"e": 31370,
"s": 31365,
"text": "Hash"
},
{
"code": null,
"e": 31383,
"s": 31370,
"text": "Mathematical"
},
{
"code": null,
"e": 31390,
"s": 31383,
"text": "Arrays"
},
{
"code": null,
"e": 31395,
"s": 31390,
"text": "Hash"
},
{
"code": null,
"e": 31408,
"s": 31395,
"text": "Mathematical"
},
{
"code": null,
"e": 31506,
"s": 31408,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31574,
"s": 31506,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 31618,
"s": 31574,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 31650,
"s": 31618,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 31673,
"s": 31650,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 31687,
"s": 31673,
"text": "Linear Search"
},
{
"code": null,
"e": 31772,
"s": 31687,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 31808,
"s": 31772,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 31839,
"s": 31808,
"text": "Hashing | Set 1 (Introduction)"
},
{
"code": null,
"e": 31873,
"s": 31839,
"text": "Hashing | Set 3 (Open Addressing)"
}
] |
Replacing every nth instance of characters in a string - JavaScript
|
We are required to write a JavaScript function that takes in a string as the first argument, a number, say n, as the second argument and a character, say c, as the third argument. The function should replace the nth appearance of any character with the character provided as the third argument and return the new string.
Following is the code −
const str = 'This is a sample string';
const num = 2;
const char = '*';
const replaceNthAppearance = (str, num, char) => {
const creds = str.split('').reduce((acc, val, ind, arr) => {
let { res, map } = acc;
if(!map.has(val)){
map.set(val, 1);
if(num === 0){
res += char;
}else{
res += val;
}
}else{
const freq = map.get(val);
if(num - freq === 1){
res += char;
}else{
res += val;
};
map.set(val, freq+1);
};
return { res, map };
}, {
res: '',
map: new Map()
});
return creds.res;
}
console.log(replaceNthAppearance(str, num, char));
Following is the output in the console −
This ***a s*mple string
|
[
{
"code": null,
"e": 1383,
"s": 1062,
"text": "We are required to write a JavaScript function that takes in a string as the first argument, a number, say n, as the second argument and a character, say c, as the third argument. The function should replace the nth appearance of any character with the character provided as the third argument and return the new string."
},
{
"code": null,
"e": 1407,
"s": 1383,
"text": "Following is the code −"
},
{
"code": null,
"e": 2112,
"s": 1407,
"text": "const str = 'This is a sample string';\nconst num = 2;\nconst char = '*';\nconst replaceNthAppearance = (str, num, char) => {\n const creds = str.split('').reduce((acc, val, ind, arr) => {\n let { res, map } = acc;\n if(!map.has(val)){\n map.set(val, 1);\n if(num === 0){\n res += char;\n }else{\n res += val;\n }\n }else{\n const freq = map.get(val);\n if(num - freq === 1){\n res += char;\n }else{\n res += val;\n };\n map.set(val, freq+1);\n };\n return { res, map };\n }, {\n res: '',\n map: new Map()\n });\n return creds.res;\n}\nconsole.log(replaceNthAppearance(str, num, char));"
},
{
"code": null,
"e": 2153,
"s": 2112,
"text": "Following is the output in the console −"
},
{
"code": null,
"e": 2177,
"s": 2153,
"text": "This ***a s*mple string"
}
] |
C Program to find IP Address, Subnet Mask & Default Gateway - GeeksforGeeks
|
09 Nov, 2021
Terminology
IP Address : An IP address, short for Internet Protocol address, is an identifying number for a piece of network hardware. Having an IP address allows a device to communicate with other devices over an IP-based network like the internet.
Subnet mask: A subnet mask is a 32-bit number used to differentiate the network component of an IP address by dividing the IP address into a network address and host address. Subnet masks are used to design subnetworks, or subnets, that connect local networks and determine what subnet an IP address belongs to.
Default Gateway: A default gateway serves as an access point or IP router that a networked computer uses to send information to a computer in another network or the Internet. The default simply means that this gateway is used by default, unless an application specifies another gateway. A default gateway allows computers on a network to communicate with computers on another network. Without it, the network is isolated from the outside.
Using system command
To get the IP Address, Subnet Mask and Default Gateway, we execute ipconfig command in the cmd.Here, we will make use of system() from < stdlib.h > to perform a system operation with the help of a C program:
#include <stdio.h>#include <stdlib.h> int main(){ system("c:\\windows\\system32\\ipconfig"); return 0;}
Using execl command
This displays the IPv4 address, Subnet Mask and the Default Gateway.The same operation can also be performed with the execl() function.To execute the later, we code:
#include <stdio.h>#include <stdlib.h>#include <unistd.h> int main(){ execl("c:\\windows\\system32\\ipconfig", "ipconfig", 0); return 0;}
Output:
This article is contributed by Amaryta Ranjan Saikia. 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.
vaibhavsinghtanwar3
C Language
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
Arrays in C/C++
std::sort() in C++ STL
Bitwise Operators in C/C++
Multidimensional Arrays in C / C++
Caesar Cipher in Cryptography
Socket Programming in Python
UDP Server-Client implementation in C
Differences between IPv4 and IPv6
Socket Programming in Java
|
[
{
"code": null,
"e": 36593,
"s": 36565,
"text": "\n09 Nov, 2021"
},
{
"code": null,
"e": 36605,
"s": 36593,
"text": "Terminology"
},
{
"code": null,
"e": 36843,
"s": 36605,
"text": "IP Address : An IP address, short for Internet Protocol address, is an identifying number for a piece of network hardware. Having an IP address allows a device to communicate with other devices over an IP-based network like the internet."
},
{
"code": null,
"e": 37155,
"s": 36843,
"text": "Subnet mask: A subnet mask is a 32-bit number used to differentiate the network component of an IP address by dividing the IP address into a network address and host address. Subnet masks are used to design subnetworks, or subnets, that connect local networks and determine what subnet an IP address belongs to."
},
{
"code": null,
"e": 37594,
"s": 37155,
"text": "Default Gateway: A default gateway serves as an access point or IP router that a networked computer uses to send information to a computer in another network or the Internet. The default simply means that this gateway is used by default, unless an application specifies another gateway. A default gateway allows computers on a network to communicate with computers on another network. Without it, the network is isolated from the outside."
},
{
"code": null,
"e": 37615,
"s": 37594,
"text": "Using system command"
},
{
"code": null,
"e": 37823,
"s": 37615,
"text": "To get the IP Address, Subnet Mask and Default Gateway, we execute ipconfig command in the cmd.Here, we will make use of system() from < stdlib.h > to perform a system operation with the help of a C program:"
},
{
"code": "#include <stdio.h>#include <stdlib.h> int main(){ system(\"c:\\\\windows\\\\system32\\\\ipconfig\"); return 0;}",
"e": 37930,
"s": 37823,
"text": null
},
{
"code": null,
"e": 37950,
"s": 37930,
"text": "Using execl command"
},
{
"code": null,
"e": 38116,
"s": 37950,
"text": "This displays the IPv4 address, Subnet Mask and the Default Gateway.The same operation can also be performed with the execl() function.To execute the later, we code:"
},
{
"code": "#include <stdio.h>#include <stdlib.h>#include <unistd.h> int main(){ execl(\"c:\\\\windows\\\\system32\\\\ipconfig\", \"ipconfig\", 0); return 0;}",
"e": 38256,
"s": 38116,
"text": null
},
{
"code": null,
"e": 38264,
"s": 38256,
"text": "Output:"
},
{
"code": null,
"e": 38569,
"s": 38264,
"text": "This article is contributed by Amaryta Ranjan Saikia. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 38694,
"s": 38569,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 38714,
"s": 38694,
"text": "vaibhavsinghtanwar3"
},
{
"code": null,
"e": 38725,
"s": 38714,
"text": "C Language"
},
{
"code": null,
"e": 38743,
"s": 38725,
"text": "Computer Networks"
},
{
"code": null,
"e": 38761,
"s": 38743,
"text": "Computer Networks"
},
{
"code": null,
"e": 38859,
"s": 38761,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38937,
"s": 38859,
"text": "Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()"
},
{
"code": null,
"e": 38953,
"s": 38937,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 38976,
"s": 38953,
"text": "std::sort() in C++ STL"
},
{
"code": null,
"e": 39003,
"s": 38976,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 39038,
"s": 39003,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 39068,
"s": 39038,
"text": "Caesar Cipher in Cryptography"
},
{
"code": null,
"e": 39097,
"s": 39068,
"text": "Socket Programming in Python"
},
{
"code": null,
"e": 39135,
"s": 39097,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 39169,
"s": 39135,
"text": "Differences between IPv4 and IPv6"
}
] |
Typecasting in C
|
Typecasting is a method in C language of converting one data type to another.
There are two types of typecasting.
1.Implicit Type casting − This conversion is done by the compiler. When more than one data type of variables are used in an expression, the compiler converts data types to avoid loss of data.
Here is an example of implicit type casting in C language,
Live Demo
#include <stdio.h>
int main() {
int a = 10;
char b = 'S';
float c = 2.88;
a = a+b;
printf("Implicit conversion from character to integer : %d\n",a);
c = c+a;
printf("Implicit conversion from integer to float : %f\n",c);
return 0;
}
Implicit conversion from character to integer : 93
Implicit conversion from integer to float : 95.879997
2.Explicit Type casting − This conversion is done by user. This is also known as typecasting. Data type is converted into another data type forcefully by the user.
Here is the syntax of explicit type casting in C language,
(type) expression
Here is an example of explicit type casting in C language,
Live Demo
#include <stdio.h>
int main() {
float c = 5.55;
int s = (int)c+1;
printf("Explicit Conversion : %d\n",s);
return 0;
}
Explicit Conversion : 6
|
[
{
"code": null,
"e": 1140,
"s": 1062,
"text": "Typecasting is a method in C language of converting one data type to another."
},
{
"code": null,
"e": 1176,
"s": 1140,
"text": "There are two types of typecasting."
},
{
"code": null,
"e": 1368,
"s": 1176,
"text": "1.Implicit Type casting − This conversion is done by the compiler. When more than one data type of variables are used in an expression, the compiler converts data types to avoid loss of data."
},
{
"code": null,
"e": 1427,
"s": 1368,
"text": "Here is an example of implicit type casting in C language,"
},
{
"code": null,
"e": 1438,
"s": 1427,
"text": " Live Demo"
},
{
"code": null,
"e": 1694,
"s": 1438,
"text": "#include <stdio.h>\nint main() {\n int a = 10;\n char b = 'S';\n float c = 2.88;\n a = a+b;\n printf(\"Implicit conversion from character to integer : %d\\n\",a);\n c = c+a;\n printf(\"Implicit conversion from integer to float : %f\\n\",c);\n return 0;\n}"
},
{
"code": null,
"e": 1799,
"s": 1694,
"text": "Implicit conversion from character to integer : 93\nImplicit conversion from integer to float : 95.879997"
},
{
"code": null,
"e": 1963,
"s": 1799,
"text": "2.Explicit Type casting − This conversion is done by user. This is also known as typecasting. Data type is converted into another data type forcefully by the user."
},
{
"code": null,
"e": 2022,
"s": 1963,
"text": "Here is the syntax of explicit type casting in C language,"
},
{
"code": null,
"e": 2040,
"s": 2022,
"text": "(type) expression"
},
{
"code": null,
"e": 2099,
"s": 2040,
"text": "Here is an example of explicit type casting in C language,"
},
{
"code": null,
"e": 2110,
"s": 2099,
"text": " Live Demo"
},
{
"code": null,
"e": 2240,
"s": 2110,
"text": "#include <stdio.h>\nint main() {\n float c = 5.55;\n int s = (int)c+1;\n printf(\"Explicit Conversion : %d\\n\",s);\n return 0;\n}"
},
{
"code": null,
"e": 2264,
"s": 2240,
"text": "Explicit Conversion : 6"
}
] |
XQuery - FLWOR
|
FLWOR is an acronym that stands for "For, Let, Where, Order by, Return". The following list shows what they account for in a FLWOR expression −
F - For - Selects a collection of all nodes.
F - For - Selects a collection of all nodes.
L - Let - Puts the result in an XQuery variable.
L - Let - Puts the result in an XQuery variable.
W - Where - Selects the nodes specified by the condition.
W - Where - Selects the nodes specified by the condition.
O - Order by - Orders the nodes specified as per criteria.
O - Order by - Orders the nodes specified as per criteria.
R - Return - Returns the final result.
R - Return - Returns the final result.
Following is a sample XML document that contains information on a collection of books. We will use a FLWOR expression to retrieve the titles of those books with a price greater than 30.
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book category="JAVA">
<title lang="en">Learn Java in 24 Hours</title>
<author>Robert</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="DOTNET">
<title lang="en">Learn .Net in 24 hours</title>
<author>Peter</author>
<year>2011</year>
<price>70.50</price>
</book>
<book category="XML">
<title lang="en">Learn XQuery in 24 hours</title>
<author>Robert</author>
<author>Peter</author>
<year>2013</year>
<price>50.00</price>
</book>
<book category="XML">
<title lang="en">Learn XPath in 24 hours</title>
<author>Jay Ban</author>
<year>2010</year>
<price>16.50</price>
</book>
</books>
The following Xquery document contains the query expression to be executed on the above XML document.
let $books := (doc("books.xml")/books/book)
return <results>
{
for $x in $books
where $x/price>30
order by $x/price
return $x/title
}
</results>
<title lang="en">Learn XQuery in 24 hours</title>
<title lang="en">Learn .Net in 24 hours</title>
To verify the result, replace the contents of books.xqy (given in theEnvironment Setup chapter) with the above XQuery expression and execute the XQueryTester java program.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2016,
"s": 1872,
"text": "FLWOR is an acronym that stands for \"For, Let, Where, Order by, Return\". The following list shows what they account for in a FLWOR expression −"
},
{
"code": null,
"e": 2061,
"s": 2016,
"text": "F - For - Selects a collection of all nodes."
},
{
"code": null,
"e": 2106,
"s": 2061,
"text": "F - For - Selects a collection of all nodes."
},
{
"code": null,
"e": 2155,
"s": 2106,
"text": "L - Let - Puts the result in an XQuery variable."
},
{
"code": null,
"e": 2204,
"s": 2155,
"text": "L - Let - Puts the result in an XQuery variable."
},
{
"code": null,
"e": 2262,
"s": 2204,
"text": "W - Where - Selects the nodes specified by the condition."
},
{
"code": null,
"e": 2320,
"s": 2262,
"text": "W - Where - Selects the nodes specified by the condition."
},
{
"code": null,
"e": 2379,
"s": 2320,
"text": "O - Order by - Orders the nodes specified as per criteria."
},
{
"code": null,
"e": 2438,
"s": 2379,
"text": "O - Order by - Orders the nodes specified as per criteria."
},
{
"code": null,
"e": 2477,
"s": 2438,
"text": "R - Return - Returns the final result."
},
{
"code": null,
"e": 2516,
"s": 2477,
"text": "R - Return - Returns the final result."
},
{
"code": null,
"e": 2702,
"s": 2516,
"text": "Following is a sample XML document that contains information on a collection of books. We will use a FLWOR expression to retrieve the titles of those books with a price greater than 30."
},
{
"code": null,
"e": 3499,
"s": 2702,
"text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<books>\n \n <book category=\"JAVA\">\n <title lang=\"en\">Learn Java in 24 Hours</title>\n <author>Robert</author>\n <year>2005</year>\n <price>30.00</price>\n </book>\n \n <book category=\"DOTNET\">\n <title lang=\"en\">Learn .Net in 24 hours</title>\n <author>Peter</author>\n <year>2011</year>\n <price>70.50</price>\n </book>\n \n <book category=\"XML\">\n <title lang=\"en\">Learn XQuery in 24 hours</title>\n <author>Robert</author>\n <author>Peter</author> \n <year>2013</year>\n <price>50.00</price>\n </book>\n \n <book category=\"XML\">\n <title lang=\"en\">Learn XPath in 24 hours</title>\n <author>Jay Ban</author>\n <year>2010</year>\n <price>16.50</price>\n </book>\n \n</books>"
},
{
"code": null,
"e": 3601,
"s": 3499,
"text": "The following Xquery document contains the query expression to be executed on the above XML document."
},
{
"code": null,
"e": 3758,
"s": 3601,
"text": "let $books := (doc(\"books.xml\")/books/book)\nreturn <results>\n{\n for $x in $books\n where $x/price>30\n order by $x/price\n return $x/title\n}\n</results>"
},
{
"code": null,
"e": 3857,
"s": 3758,
"text": "<title lang=\"en\">Learn XQuery in 24 hours</title>\n<title lang=\"en\">Learn .Net in 24 hours</title>\n"
},
{
"code": null,
"e": 4029,
"s": 3857,
"text": "To verify the result, replace the contents of books.xqy (given in theEnvironment Setup chapter) with the above XQuery expression and execute the XQueryTester java program."
},
{
"code": null,
"e": 4036,
"s": 4029,
"text": " Print"
},
{
"code": null,
"e": 4047,
"s": 4036,
"text": " Add Notes"
}
] |
How to clear the content of the recycle bin in PowerShell?
|
Recycle bin in Windows operating system is to store the soft-deleted data. Soft deleted data means, data that is not deleted with (SHIFT + DEL) button but simply deleted with DEL button. Each local disk has its own configured recycle bin space.
To delete the recycle bin data using GUI, you can simply right click and delete the content.
It is also possible to delete the recycle bin content with the PowerShell command with the Clear-Recyclebin cmdlet. This command is introduced in PowerShell 5 and available in newer versions as well.
Clear-RecycleBin
PS C:\WINDOWS\system32> Clear-RecycleBin
Confirm
Are you sure you want to perform this action?
Performing the operation "Clear-RecycleBin" on target "All of the contents of the Recycle Bin".
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"):
User needs to confirm how the contents should be deleted as per the above output.
To delete the content of the specific drive, you need to specify –DriveLetter parameter.
Clear-RecycleBin -DriveLetter D
You can also delete the content without the user consent with the –Force parameter.
Clear-RecycleBin -Force
Clear-RecycleBin doesn’t generate any output on the successful deletion of contents.
To delete the recycle bin content of the remote computers, you need to use the remote commands.
For example,
Invoke-Command -ComputerName Test-PC -ScriptBlock{Clear-RecycleBin -Force}
You need to make sure that the remote PowerShell version is also 5.0 or higher while running these commands.
|
[
{
"code": null,
"e": 1307,
"s": 1062,
"text": "Recycle bin in Windows operating system is to store the soft-deleted data. Soft deleted data means, data that is not deleted with (SHIFT + DEL) button but simply deleted with DEL button. Each local disk has its own configured recycle bin space."
},
{
"code": null,
"e": 1400,
"s": 1307,
"text": "To delete the recycle bin data using GUI, you can simply right click and delete the content."
},
{
"code": null,
"e": 1600,
"s": 1400,
"text": "It is also possible to delete the recycle bin content with the PowerShell command with the Clear-Recyclebin cmdlet. This command is introduced in PowerShell 5 and available in newer versions as well."
},
{
"code": null,
"e": 1617,
"s": 1600,
"text": "Clear-RecycleBin"
},
{
"code": null,
"e": 1896,
"s": 1617,
"text": "PS C:\\WINDOWS\\system32> Clear-RecycleBin\nConfirm\nAre you sure you want to perform this action?\nPerforming the operation \"Clear-RecycleBin\" on target \"All of the contents of the Recycle Bin\".\n[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is \"Y\"):"
},
{
"code": null,
"e": 1978,
"s": 1896,
"text": "User needs to confirm how the contents should be deleted as per the above output."
},
{
"code": null,
"e": 2067,
"s": 1978,
"text": "To delete the content of the specific drive, you need to specify –DriveLetter parameter."
},
{
"code": null,
"e": 2099,
"s": 2067,
"text": "Clear-RecycleBin -DriveLetter D"
},
{
"code": null,
"e": 2183,
"s": 2099,
"text": "You can also delete the content without the user consent with the –Force parameter."
},
{
"code": null,
"e": 2207,
"s": 2183,
"text": "Clear-RecycleBin -Force"
},
{
"code": null,
"e": 2292,
"s": 2207,
"text": "Clear-RecycleBin doesn’t generate any output on the successful deletion of contents."
},
{
"code": null,
"e": 2388,
"s": 2292,
"text": "To delete the recycle bin content of the remote computers, you need to use the remote commands."
},
{
"code": null,
"e": 2401,
"s": 2388,
"text": "For example,"
},
{
"code": null,
"e": 2477,
"s": 2401,
"text": "Invoke-Command -ComputerName Test-PC -ScriptBlock{Clear-RecycleBin -Force}\n"
},
{
"code": null,
"e": 2586,
"s": 2477,
"text": "You need to make sure that the remote PowerShell version is also 5.0 or higher while running these commands."
}
] |
Remove All Adjacent Duplicates in String II in C++
|
Suppose a string s is given, a k duplicate removal consists of choosing k adjacent and equal letters from string s and removing them causing the left and the right side of the deleted substring to concatenate together. We will repeatedly make k duplicate removals on the given string s until we cannot change any remaining. We have to find the final string after all such duplicate removals have been made. So if the input is like s = “deeedbbcccbdaa”, and k = 3, then the output will be “aa”, at first delete the “eee” and “ccc” and we will get “ddbbbaa”, then delete “bbb”, the string will be “dddaa”, then delete “ddd”, and the output will be “aa”
To solve this, we will follow these steps −
ans := empty string
create one stack for char-int pair, n := size of the string
for i in range 0 to nx := s[i]if stack is not empty and integer of the stack top element = k, then delete top element from stackif i = n, then breakif stack is empty or character of stack top is not x, then insert pair (x, 1) into stack, and increase i by 1otherwise increase the integer part of the stack top element, and increase i by 1
x := s[i]
if stack is not empty and integer of the stack top element = k, then delete top element from stack
if i = n, then break
if stack is empty or character of stack top is not x, then insert pair (x, 1) into stack, and increase i by 1
otherwise increase the integer part of the stack top element, and increase i by 1
while stack is not emptytemp := stack top elementwhile integer part of temp is not 0,ans := ans + character part of tempdecrease integer part of temp by 1delete the top element from stack
temp := stack top element
while integer part of temp is not 0,ans := ans + character part of tempdecrease integer part of temp by 1
ans := ans + character part of temp
decrease integer part of temp by 1
delete the top element from stack
reverse the ans string and return.
Let us see the following implementation to get better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
string removeDuplicates(string s, int k) {
string ans = "";
stack < pair<char, int> > st;
int n = s.size();
for(int i = 0; i <= n;){
char x = s[i];
if(!st.empty() && st.top().second == k)st.pop();
if(i == n)break;
if(st.empty() || st.top().first != x){
st.push({x, 1});
i++;
} else {
st.top().second++;
i++;
}
}
while(!st.empty()){
pair <char, int> temp = st.top();
while(temp.second--) ans += temp.first;
st.pop();
}
reverse(ans.begin(), ans.end());
return ans;
}
};
main(){
Solution ob;
cout <<(ob.removeDuplicates("deeedbbcccbdaa", 3));
}
"deeedbbcccbdaa"
3
aa
|
[
{
"code": null,
"e": 1713,
"s": 1062,
"text": "Suppose a string s is given, a k duplicate removal consists of choosing k adjacent and equal letters from string s and removing them causing the left and the right side of the deleted substring to concatenate together. We will repeatedly make k duplicate removals on the given string s until we cannot change any remaining. We have to find the final string after all such duplicate removals have been made. So if the input is like s = “deeedbbcccbdaa”, and k = 3, then the output will be “aa”, at first delete the “eee” and “ccc” and we will get “ddbbbaa”, then delete “bbb”, the string will be “dddaa”, then delete “ddd”, and the output will be “aa”"
},
{
"code": null,
"e": 1757,
"s": 1713,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1777,
"s": 1757,
"text": "ans := empty string"
},
{
"code": null,
"e": 1837,
"s": 1777,
"text": "create one stack for char-int pair, n := size of the string"
},
{
"code": null,
"e": 2176,
"s": 1837,
"text": "for i in range 0 to nx := s[i]if stack is not empty and integer of the stack top element = k, then delete top element from stackif i = n, then breakif stack is empty or character of stack top is not x, then insert pair (x, 1) into stack, and increase i by 1otherwise increase the integer part of the stack top element, and increase i by 1"
},
{
"code": null,
"e": 2186,
"s": 2176,
"text": "x := s[i]"
},
{
"code": null,
"e": 2285,
"s": 2186,
"text": "if stack is not empty and integer of the stack top element = k, then delete top element from stack"
},
{
"code": null,
"e": 2306,
"s": 2285,
"text": "if i = n, then break"
},
{
"code": null,
"e": 2416,
"s": 2306,
"text": "if stack is empty or character of stack top is not x, then insert pair (x, 1) into stack, and increase i by 1"
},
{
"code": null,
"e": 2498,
"s": 2416,
"text": "otherwise increase the integer part of the stack top element, and increase i by 1"
},
{
"code": null,
"e": 2686,
"s": 2498,
"text": "while stack is not emptytemp := stack top elementwhile integer part of temp is not 0,ans := ans + character part of tempdecrease integer part of temp by 1delete the top element from stack"
},
{
"code": null,
"e": 2712,
"s": 2686,
"text": "temp := stack top element"
},
{
"code": null,
"e": 2818,
"s": 2712,
"text": "while integer part of temp is not 0,ans := ans + character part of tempdecrease integer part of temp by 1"
},
{
"code": null,
"e": 2854,
"s": 2818,
"text": "ans := ans + character part of temp"
},
{
"code": null,
"e": 2889,
"s": 2854,
"text": "decrease integer part of temp by 1"
},
{
"code": null,
"e": 2923,
"s": 2889,
"text": "delete the top element from stack"
},
{
"code": null,
"e": 2958,
"s": 2923,
"text": "reverse the ans string and return."
},
{
"code": null,
"e": 3028,
"s": 2958,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 3039,
"s": 3028,
"text": " Live Demo"
},
{
"code": null,
"e": 3850,
"s": 3039,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\n public:\n string removeDuplicates(string s, int k) {\n string ans = \"\";\n stack < pair<char, int> > st;\n int n = s.size();\n for(int i = 0; i <= n;){\n char x = s[i];\n if(!st.empty() && st.top().second == k)st.pop();\n if(i == n)break;\n if(st.empty() || st.top().first != x){\n st.push({x, 1});\n i++;\n } else {\n st.top().second++;\n i++;\n }\n }\n while(!st.empty()){\n pair <char, int> temp = st.top();\n while(temp.second--) ans += temp.first;\n st.pop();\n }\n reverse(ans.begin(), ans.end());\n return ans;\n }\n};\nmain(){\n Solution ob;\n cout <<(ob.removeDuplicates(\"deeedbbcccbdaa\", 3));\n}"
},
{
"code": null,
"e": 3869,
"s": 3850,
"text": "\"deeedbbcccbdaa\"\n3"
},
{
"code": null,
"e": 3872,
"s": 3869,
"text": "aa"
}
] |
Java Program to Add Characters to a String - GeeksforGeeks
|
16 Jul, 2021
We will be discussing out how to add character to a string at particular position in a string in java. It can be interpreted as follows as depicted in the illustration what we are trying to do which is as follows:
Illustration:
Input:
Input custom string = Hello
Output:
--> String to be added 'Geeks'
--> If end position, Output: HelloGeeks
--> If in beginning, Output: GeeksHello
--> If at sat 3rd index, Output: HelGeekslo
Methods: This can be done using multiple methods of which frequently used methods are listed below as follows:
Using + operatorAt the endAt the beginningUsing insert() method of StringBuffer classUsing substring() method
Using + operatorAt the endAt the beginning
At the end
At the beginning
Using insert() method of StringBuffer class
Using substring() method
Let us discuss all three methods above listed in detail to get a fair understanding of the same
Method 1: Using + operator
1.1 At the end
Example: One can add character at the start of String using the ‘+’ operator.
Java
// Java Program to Add Characters to a String// At the End // Importing input output classesimport java.io.*; // Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Input character and string char a = 's'; String str = "GeeksforGeek"; // Inserting at the end String str2 = str + a; // Print and display the above string System.out.println(str2); }}
GeeksforGeeks
1.2 At the beginning
Example: One can add character at the start of String using the ‘+’ operator.
Java
// Java Program to Add Characters to a String// At the Beginning // Importing input output classesimport java.io.*; // Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Input character and string char a = 'G'; String str = "eeksforGeeks"; // Inserting at the beginning String str2 = a + str; // Print and display the above string System.out.println(str2); }}
GeeksforGeeks
Method 2: Using insert() method of StringBuffer class
StringBuffer is a peer class of String that provides much of the functionality of strings. The string represents fixed-length, immutable character sequences while StringBuffer represents grow able and writable character sequences. StringBuffer may have characters and sub-strings inserted in the middle or appended to the end. It will automatically grow to make room for such additions and often has more characters pre-allocated than are actually needed, to allow room for growth. One can use the StringBuffer class method namely the insert() method to add character to String at the given position. This method inserts the string representation of given data type at given position in StringBuffer.
Syntax:
str.insert(int position, char x);
str.insert(int position, boolean x);
str.insert(int position, char[] x);
str.insert(int position, float x);
str.insert(int position, double x);
str.insert(int position, long x);
str.insert(int position, int x);
position is the index in string where
we need to insert.
Return type: A reference to this object.
Example
Java
// Java Program to Add Characters to a String// Using StringBuffer class insert() method // Main class// AddCharacterToStringAnyPositionpublic class GFG { // Method 1 // To add character to string public static String addCharToString(String str, char c, int pos) { // Creating an object of StringBuffer class StringBuffer stringBuffer = new StringBuffer(str); // insert() method where position of character to be // inserted is specified as in arguments stringBuffer.insert(pos, c); // Return the updated string // Concatenated string return stringBuffer.toString(); } // Method 2 // Main driver method public static void main(String[] args) { // Input string and character String blogName = "GeeksorGeeks"; char two = 'f'; // Calling the method 1 to // add character to a string // Custom string, character and position passed String cblogName = addCharToString(blogName, two, 5); // Print and display th above string System.out.println(cblogName); }}
GeeksforGeeks
Method 3: Using substring() method
One can also use String’s substring method to add character to String at given position. This method has two variants, and it returns a new string hat is substring of a string where the substring begins with a character at the specified index and extends to the end of the string.
Syntax:
public String substring(int begIndex)
Parameters: The beginning index, inclusive.
Return Value: The specified substring.
Example
Java
// Java Program to Add Characters to a String// Using substring() method // Main class// AddCharacterToStringAnyPositionpublic class GFG { // Method 1 // To add character to a string public static String addCharToStringUsingSubString(String str, char c, int pos) { return str.substring(0, pos) + c + str.substring(pos); } // Method 2 // Main driver method public static void main(String[] args) { // Custom input character and string String blogName = "GeeksorGeeks"; char two = 'f'; // Calling the Method 1 to // To add character to a string // Custom arguments String cblogName = addCharToStringUsingSubString( blogName, two, 5); // Print and display the above string on console System.out.println(cblogName); }}
GeeksforGeeks
akshaysingh98088
sagar0719kumar
surindertarika1234
Java-String-Programs
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Interfaces in Java
Initialize an ArrayList in Java
ArrayList in Java
Multidimensional Arrays in Java
Overriding in Java
Initializing a List in Java
Convert a String to Character array in Java
Java Programming Examples
Implementing a Linked List in Java using Class
Convert Double to Integer in Java
|
[
{
"code": null,
"e": 24730,
"s": 24702,
"text": "\n16 Jul, 2021"
},
{
"code": null,
"e": 24944,
"s": 24730,
"text": "We will be discussing out how to add character to a string at particular position in a string in java. It can be interpreted as follows as depicted in the illustration what we are trying to do which is as follows:"
},
{
"code": null,
"e": 24958,
"s": 24944,
"text": "Illustration:"
},
{
"code": null,
"e": 25171,
"s": 24958,
"text": "Input: \nInput custom string = Hello\nOutput: \n--> String to be added 'Geeks'\n --> If end position, Output: HelloGeeks\n --> If in beginning, Output: GeeksHello\n --> If at sat 3rd index, Output: HelGeekslo "
},
{
"code": null,
"e": 25282,
"s": 25171,
"text": "Methods: This can be done using multiple methods of which frequently used methods are listed below as follows:"
},
{
"code": null,
"e": 25392,
"s": 25282,
"text": "Using + operatorAt the endAt the beginningUsing insert() method of StringBuffer classUsing substring() method"
},
{
"code": null,
"e": 25435,
"s": 25392,
"text": "Using + operatorAt the endAt the beginning"
},
{
"code": null,
"e": 25446,
"s": 25435,
"text": "At the end"
},
{
"code": null,
"e": 25463,
"s": 25446,
"text": "At the beginning"
},
{
"code": null,
"e": 25507,
"s": 25463,
"text": "Using insert() method of StringBuffer class"
},
{
"code": null,
"e": 25532,
"s": 25507,
"text": "Using substring() method"
},
{
"code": null,
"e": 25628,
"s": 25532,
"text": "Let us discuss all three methods above listed in detail to get a fair understanding of the same"
},
{
"code": null,
"e": 25655,
"s": 25628,
"text": "Method 1: Using + operator"
},
{
"code": null,
"e": 25670,
"s": 25655,
"text": "1.1 At the end"
},
{
"code": null,
"e": 25748,
"s": 25670,
"text": "Example: One can add character at the start of String using the ‘+’ operator."
},
{
"code": null,
"e": 25753,
"s": 25748,
"text": "Java"
},
{
"code": "// Java Program to Add Characters to a String// At the End // Importing input output classesimport java.io.*; // Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Input character and string char a = 's'; String str = \"GeeksforGeek\"; // Inserting at the end String str2 = str + a; // Print and display the above string System.out.println(str2); }}",
"e": 26210,
"s": 25753,
"text": null
},
{
"code": null,
"e": 26224,
"s": 26210,
"text": "GeeksforGeeks"
},
{
"code": null,
"e": 26245,
"s": 26224,
"text": "1.2 At the beginning"
},
{
"code": null,
"e": 26324,
"s": 26245,
"text": "Example: One can add character at the start of String using the ‘+’ operator. "
},
{
"code": null,
"e": 26329,
"s": 26324,
"text": "Java"
},
{
"code": "// Java Program to Add Characters to a String// At the Beginning // Importing input output classesimport java.io.*; // Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Input character and string char a = 'G'; String str = \"eeksforGeeks\"; // Inserting at the beginning String str2 = a + str; // Print and display the above string System.out.println(str2); }}",
"e": 26797,
"s": 26329,
"text": null
},
{
"code": null,
"e": 26811,
"s": 26797,
"text": "GeeksforGeeks"
},
{
"code": null,
"e": 26866,
"s": 26811,
"text": "Method 2: Using insert() method of StringBuffer class "
},
{
"code": null,
"e": 27567,
"s": 26866,
"text": "StringBuffer is a peer class of String that provides much of the functionality of strings. The string represents fixed-length, immutable character sequences while StringBuffer represents grow able and writable character sequences. StringBuffer may have characters and sub-strings inserted in the middle or appended to the end. It will automatically grow to make room for such additions and often has more characters pre-allocated than are actually needed, to allow room for growth. One can use the StringBuffer class method namely the insert() method to add character to String at the given position. This method inserts the string representation of given data type at given position in StringBuffer."
},
{
"code": null,
"e": 27576,
"s": 27567,
"text": "Syntax: "
},
{
"code": null,
"e": 27889,
"s": 27576,
"text": " str.insert(int position, char x);\n str.insert(int position, boolean x);\n str.insert(int position, char[] x);\n str.insert(int position, float x);\n str.insert(int position, double x);\n str.insert(int position, long x);\n str.insert(int position, int x);\n\nposition is the index in string where\nwe need to insert."
},
{
"code": null,
"e": 27930,
"s": 27889,
"text": "Return type: A reference to this object."
},
{
"code": null,
"e": 27940,
"s": 27930,
"text": "Example "
},
{
"code": null,
"e": 27945,
"s": 27940,
"text": "Java"
},
{
"code": "// Java Program to Add Characters to a String// Using StringBuffer class insert() method // Main class// AddCharacterToStringAnyPositionpublic class GFG { // Method 1 // To add character to string public static String addCharToString(String str, char c, int pos) { // Creating an object of StringBuffer class StringBuffer stringBuffer = new StringBuffer(str); // insert() method where position of character to be // inserted is specified as in arguments stringBuffer.insert(pos, c); // Return the updated string // Concatenated string return stringBuffer.toString(); } // Method 2 // Main driver method public static void main(String[] args) { // Input string and character String blogName = \"GeeksorGeeks\"; char two = 'f'; // Calling the method 1 to // add character to a string // Custom string, character and position passed String cblogName = addCharToString(blogName, two, 5); // Print and display th above string System.out.println(cblogName); }}",
"e": 29107,
"s": 27945,
"text": null
},
{
"code": null,
"e": 29121,
"s": 29107,
"text": "GeeksforGeeks"
},
{
"code": null,
"e": 29156,
"s": 29121,
"text": "Method 3: Using substring() method"
},
{
"code": null,
"e": 29439,
"s": 29156,
"text": "One can also use String’s substring method to add character to String at given position. This method has two variants, and it returns a new string hat is substring of a string where the substring begins with a character at the specified index and extends to the end of the string. "
},
{
"code": null,
"e": 29449,
"s": 29439,
"text": "Syntax: "
},
{
"code": null,
"e": 29487,
"s": 29449,
"text": "public String substring(int begIndex)"
},
{
"code": null,
"e": 29531,
"s": 29487,
"text": "Parameters: The beginning index, inclusive."
},
{
"code": null,
"e": 29570,
"s": 29531,
"text": "Return Value: The specified substring."
},
{
"code": null,
"e": 29580,
"s": 29570,
"text": "Example "
},
{
"code": null,
"e": 29585,
"s": 29580,
"text": "Java"
},
{
"code": "// Java Program to Add Characters to a String// Using substring() method // Main class// AddCharacterToStringAnyPositionpublic class GFG { // Method 1 // To add character to a string public static String addCharToStringUsingSubString(String str, char c, int pos) { return str.substring(0, pos) + c + str.substring(pos); } // Method 2 // Main driver method public static void main(String[] args) { // Custom input character and string String blogName = \"GeeksorGeeks\"; char two = 'f'; // Calling the Method 1 to // To add character to a string // Custom arguments String cblogName = addCharToStringUsingSubString( blogName, two, 5); // Print and display the above string on console System.out.println(cblogName); }}",
"e": 30463,
"s": 29585,
"text": null
},
{
"code": null,
"e": 30477,
"s": 30463,
"text": "GeeksforGeeks"
},
{
"code": null,
"e": 30496,
"s": 30479,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 30511,
"s": 30496,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 30530,
"s": 30511,
"text": "surindertarika1234"
},
{
"code": null,
"e": 30551,
"s": 30530,
"text": "Java-String-Programs"
},
{
"code": null,
"e": 30558,
"s": 30551,
"text": "Picked"
},
{
"code": null,
"e": 30563,
"s": 30558,
"text": "Java"
},
{
"code": null,
"e": 30577,
"s": 30563,
"text": "Java Programs"
},
{
"code": null,
"e": 30582,
"s": 30577,
"text": "Java"
},
{
"code": null,
"e": 30680,
"s": 30582,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30689,
"s": 30680,
"text": "Comments"
},
{
"code": null,
"e": 30702,
"s": 30689,
"text": "Old Comments"
},
{
"code": null,
"e": 30721,
"s": 30702,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 30753,
"s": 30721,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 30771,
"s": 30753,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 30803,
"s": 30771,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 30822,
"s": 30803,
"text": "Overriding in Java"
},
{
"code": null,
"e": 30850,
"s": 30822,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 30894,
"s": 30850,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 30920,
"s": 30894,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 30967,
"s": 30920,
"text": "Implementing a Linked List in Java using Class"
}
] |
2D Line Plot in MATLAB - GeeksforGeeks
|
29 May, 2021
‘2D’ stands for 2-dimensional and a 2D line is a line that is moved in 2-dimensions. A line in 2D means that we could move in forward and backward direction but also in any direction like left, right, up, down.
In MATLAB we have a function named plot() which allows us to plot a line in 2 directions.
Syntax:
plot(X,Y)
where X and Y represent the x and the y axis of the plane. The X and Y both are can be vectors or matrices but there are some conditions to plot the graph and these conditions are mentioned below:
Condition 1: If X and Y both are vectors then they must be of equal length.
Condition 2: If X and Y both are Matrices then they must be of equal size.
Condition 3: If one of X or Y is a vector and the other is a matrix, then the matrix must have dimensions such that one of its dimensions equals the vector length.
Condition 4: If one is a scalar and the other is either a scalar or a vector, then discrete points must be plotted.
Now let’s move to some examples.
Example 1: Draw a simple line:
MATLAB
% coordinates of the x-axisx=[10,20,30,40,50] % coordinates of the y-axisy=[100,200,300,400,500] % plot function is used to plot the% line according to the coordinatesplot(x,y) % to put grid on the graphgrid on
Output :
Example 2: Draw a line with only 1 axis coordinates as input:
Note: If you give only 1 axis then the plot() function takes it as coordinates of the y-axis and by default gives values to the x-axis starting from 1, 2, 3, up to y coordinates.
MATLAB
% coordinates of axisy=[100,200,300,400,500] % plot function is used to plot the% line according to the coordinatesplot(x,y) % to put grid on the graphgrid on
Output :
Example 3: Draw more than 1 line on the same graph with axis names:
MATLAB
% coordinates of x-axisx=[10,20,30,40,50] % coordinates of y-axis of line 1% represented by blue colory1=[100,500,200,100,0] % coordinates of y-axis of line 2% represented by red colory2=[400,100,0,200,300] % coordinates of y-axis of line 3% represented by yellow colory3=[200,300,400,100,500] % plot function to plot the lines on graphplot(x,y1,x,y2,x,y3) % to add grid on graphgrid on % name of x axisxlabel('x') % name of y axisylabel('y')
Output :
Example 4: Now the value of the y-axis is given as matrix instead of vector:
MATLAB
% coordinates of x-axisx=[1,2,3,4,5] % coordinates of y-axis in form of matrix% magic(n) matrix is a n*n matrix% in which value scattered from 1 to n^2% with equal row and columns sumy=magic(5) % plot functionplot(x,y) % to add gridgrid on % add name on axisxlabel('x')ylabel('y')
Output:
Example 5: Now we plot the graph by using 2 y-axis one is on the left side another is on the right side.
MATLAB
% coordinates of x-axisx=[1,2,3,4,5] % coordinates of y-axisy=[50,40,30,20,10] % assigning left side to the above% coordinatesyyaxis left % plot graph of left y-axisplot(x,y) % coordinates of y-axisy=[10,20,30,40,50] % assigning right side to the above% coordinatesyyaxis right % plot graph of right y-axisplot(x,y) % put grid on graphgrid on % name of x-axisxlabel('x') % name of left side y coordinatesyyaxis leftylabel('Left Side') % name of right side y coordinatesyyaxis rightylabel('Right Side')
Output:
clintra
MATLAB
Picked
MATLAB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Remove Noise from Digital Image in Frequency Domain Using MATLAB?
MRI Image Segmentation in MATLAB
How to Solve Histogram Equalization Numerical Problem in MATLAB?
How to Normalize a Histogram in MATLAB?
Laplace Transform in MATLAB
Laplacian of Gaussian Filter in MATLAB
Adaptive Histogram Equalization in Image Processing Using MATLAB
Forward and Inverse Fourier Transform of an Image in MATLAB
How to Remove Salt and Pepper Noise from Image Using MATLAB?
Boundary Extraction of image using MATLAB
|
[
{
"code": null,
"e": 24255,
"s": 24227,
"text": "\n29 May, 2021"
},
{
"code": null,
"e": 24466,
"s": 24255,
"text": "‘2D’ stands for 2-dimensional and a 2D line is a line that is moved in 2-dimensions. A line in 2D means that we could move in forward and backward direction but also in any direction like left, right, up, down."
},
{
"code": null,
"e": 24557,
"s": 24466,
"text": "In MATLAB we have a function named plot() which allows us to plot a line in 2 directions. "
},
{
"code": null,
"e": 24565,
"s": 24557,
"text": "Syntax:"
},
{
"code": null,
"e": 24575,
"s": 24565,
"text": "plot(X,Y)"
},
{
"code": null,
"e": 24772,
"s": 24575,
"text": "where X and Y represent the x and the y axis of the plane. The X and Y both are can be vectors or matrices but there are some conditions to plot the graph and these conditions are mentioned below:"
},
{
"code": null,
"e": 24848,
"s": 24772,
"text": "Condition 1: If X and Y both are vectors then they must be of equal length."
},
{
"code": null,
"e": 24923,
"s": 24848,
"text": "Condition 2: If X and Y both are Matrices then they must be of equal size."
},
{
"code": null,
"e": 25088,
"s": 24923,
"text": "Condition 3: If one of X or Y is a vector and the other is a matrix, then the matrix must have dimensions such that one of its dimensions equals the vector length. "
},
{
"code": null,
"e": 25204,
"s": 25088,
"text": "Condition 4: If one is a scalar and the other is either a scalar or a vector, then discrete points must be plotted."
},
{
"code": null,
"e": 25237,
"s": 25204,
"text": "Now let’s move to some examples."
},
{
"code": null,
"e": 25268,
"s": 25237,
"text": "Example 1: Draw a simple line:"
},
{
"code": null,
"e": 25275,
"s": 25268,
"text": "MATLAB"
},
{
"code": "% coordinates of the x-axisx=[10,20,30,40,50] % coordinates of the y-axisy=[100,200,300,400,500] % plot function is used to plot the% line according to the coordinatesplot(x,y) % to put grid on the graphgrid on",
"e": 25488,
"s": 25275,
"text": null
},
{
"code": null,
"e": 25502,
"s": 25492,
"text": "Output : "
},
{
"code": null,
"e": 25568,
"s": 25506,
"text": "Example 2: Draw a line with only 1 axis coordinates as input:"
},
{
"code": null,
"e": 25749,
"s": 25570,
"text": "Note: If you give only 1 axis then the plot() function takes it as coordinates of the y-axis and by default gives values to the x-axis starting from 1, 2, 3, up to y coordinates."
},
{
"code": null,
"e": 25758,
"s": 25751,
"text": "MATLAB"
},
{
"code": "% coordinates of axisy=[100,200,300,400,500] % plot function is used to plot the% line according to the coordinatesplot(x,y) % to put grid on the graphgrid on",
"e": 25917,
"s": 25758,
"text": null
},
{
"code": null,
"e": 25931,
"s": 25921,
"text": "Output : "
},
{
"code": null,
"e": 26003,
"s": 25935,
"text": "Example 3: Draw more than 1 line on the same graph with axis names:"
},
{
"code": null,
"e": 26012,
"s": 26005,
"text": "MATLAB"
},
{
"code": "% coordinates of x-axisx=[10,20,30,40,50] % coordinates of y-axis of line 1% represented by blue colory1=[100,500,200,100,0] % coordinates of y-axis of line 2% represented by red colory2=[400,100,0,200,300] % coordinates of y-axis of line 3% represented by yellow colory3=[200,300,400,100,500] % plot function to plot the lines on graphplot(x,y1,x,y2,x,y3) % to add grid on graphgrid on % name of x axisxlabel('x') % name of y axisylabel('y')",
"e": 26457,
"s": 26012,
"text": null
},
{
"code": null,
"e": 26470,
"s": 26461,
"text": "Output :"
},
{
"code": null,
"e": 26551,
"s": 26474,
"text": "Example 4: Now the value of the y-axis is given as matrix instead of vector:"
},
{
"code": null,
"e": 26560,
"s": 26553,
"text": "MATLAB"
},
{
"code": "% coordinates of x-axisx=[1,2,3,4,5] % coordinates of y-axis in form of matrix% magic(n) matrix is a n*n matrix% in which value scattered from 1 to n^2% with equal row and columns sumy=magic(5) % plot functionplot(x,y) % to add gridgrid on % add name on axisxlabel('x')ylabel('y')",
"e": 26841,
"s": 26560,
"text": null
},
{
"code": null,
"e": 26854,
"s": 26845,
"text": "Output: "
},
{
"code": null,
"e": 26963,
"s": 26858,
"text": "Example 5: Now we plot the graph by using 2 y-axis one is on the left side another is on the right side."
},
{
"code": null,
"e": 26972,
"s": 26965,
"text": "MATLAB"
},
{
"code": "% coordinates of x-axisx=[1,2,3,4,5] % coordinates of y-axisy=[50,40,30,20,10] % assigning left side to the above% coordinatesyyaxis left % plot graph of left y-axisplot(x,y) % coordinates of y-axisy=[10,20,30,40,50] % assigning right side to the above% coordinatesyyaxis right % plot graph of right y-axisplot(x,y) % put grid on graphgrid on % name of x-axisxlabel('x') % name of left side y coordinatesyyaxis leftylabel('Left Side') % name of right side y coordinatesyyaxis rightylabel('Right Side')",
"e": 27480,
"s": 26972,
"text": null
},
{
"code": null,
"e": 27492,
"s": 27484,
"text": "Output:"
},
{
"code": null,
"e": 27504,
"s": 27496,
"text": "clintra"
},
{
"code": null,
"e": 27511,
"s": 27504,
"text": "MATLAB"
},
{
"code": null,
"e": 27518,
"s": 27511,
"text": "Picked"
},
{
"code": null,
"e": 27525,
"s": 27518,
"text": "MATLAB"
},
{
"code": null,
"e": 27623,
"s": 27525,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27632,
"s": 27623,
"text": "Comments"
},
{
"code": null,
"e": 27645,
"s": 27632,
"text": "Old Comments"
},
{
"code": null,
"e": 27718,
"s": 27645,
"text": "How to Remove Noise from Digital Image in Frequency Domain Using MATLAB?"
},
{
"code": null,
"e": 27751,
"s": 27718,
"text": "MRI Image Segmentation in MATLAB"
},
{
"code": null,
"e": 27816,
"s": 27751,
"text": "How to Solve Histogram Equalization Numerical Problem in MATLAB?"
},
{
"code": null,
"e": 27856,
"s": 27816,
"text": "How to Normalize a Histogram in MATLAB?"
},
{
"code": null,
"e": 27884,
"s": 27856,
"text": "Laplace Transform in MATLAB"
},
{
"code": null,
"e": 27923,
"s": 27884,
"text": "Laplacian of Gaussian Filter in MATLAB"
},
{
"code": null,
"e": 27988,
"s": 27923,
"text": "Adaptive Histogram Equalization in Image Processing Using MATLAB"
},
{
"code": null,
"e": 28048,
"s": 27988,
"text": "Forward and Inverse Fourier Transform of an Image in MATLAB"
},
{
"code": null,
"e": 28109,
"s": 28048,
"text": "How to Remove Salt and Pepper Noise from Image Using MATLAB?"
}
] |
Printing the numbers in reverse order using Division and modulo operators using C
|
How to print the given two-digit number in reverse order with the help of division and Modulo operator using C programming language?
So far, we had seen how to reverse the string using string function and without string function. Now let’s see how to reverse the two-digit number without using the predefined function.
The logic we use to reverse the number with the help of operators is −
int firstno=number%10; //stores remainder
int secondno=number/10;// stores quotient
Then print the first number followed by the second number then you will get the reverse number for the given number.
In this example, we will take a 2-digit number and apply division and modulo operator to reverse the number −
#include<stdio.h>
int main(){
int number;
printf("enter a number:");
scanf("%4d",&number);
int firstno=number%10; //stores remainder
int secondno=number/10;// stores quotient
printf("After reversing =%d%d\n",firstno,secondno);
return 0;
}
enter a number:45
After reversing =54
In this example, we will take a 3-digit number and apply division and modulo operator to reverse the number −
Live Demo
#include<stdio.h>
int main(){
int number,num1,num2,num3,result;
printf("enter a number:");
scanf("%4d",&number);
num1 = number / 100;
num2 = (number % 100) / 10;
num3 = number%10 ;
result = 100*num3 + 10*num2 + num1;
printf("After reversing =%d\n",result);
return 0;
}
enter a number:479
After reversing =974
|
[
{
"code": null,
"e": 1195,
"s": 1062,
"text": "How to print the given two-digit number in reverse order with the help of division and Modulo operator using C programming language?"
},
{
"code": null,
"e": 1381,
"s": 1195,
"text": "So far, we had seen how to reverse the string using string function and without string function. Now let’s see how to reverse the two-digit number without using the predefined function."
},
{
"code": null,
"e": 1452,
"s": 1381,
"text": "The logic we use to reverse the number with the help of operators is −"
},
{
"code": null,
"e": 1536,
"s": 1452,
"text": "int firstno=number%10; //stores remainder\nint secondno=number/10;// stores quotient"
},
{
"code": null,
"e": 1653,
"s": 1536,
"text": "Then print the first number followed by the second number then you will get the reverse number for the given number."
},
{
"code": null,
"e": 1763,
"s": 1653,
"text": "In this example, we will take a 2-digit number and apply division and modulo operator to reverse the number −"
},
{
"code": null,
"e": 2023,
"s": 1763,
"text": "#include<stdio.h>\nint main(){\n int number;\n printf(\"enter a number:\");\n scanf(\"%4d\",&number);\n int firstno=number%10; //stores remainder\n int secondno=number/10;// stores quotient\n printf(\"After reversing =%d%d\\n\",firstno,secondno);\n return 0;\n}"
},
{
"code": null,
"e": 2061,
"s": 2023,
"text": "enter a number:45\nAfter reversing =54"
},
{
"code": null,
"e": 2171,
"s": 2061,
"text": "In this example, we will take a 3-digit number and apply division and modulo operator to reverse the number −"
},
{
"code": null,
"e": 2182,
"s": 2171,
"text": " Live Demo"
},
{
"code": null,
"e": 2478,
"s": 2182,
"text": "#include<stdio.h>\nint main(){\n int number,num1,num2,num3,result;\n printf(\"enter a number:\");\n scanf(\"%4d\",&number);\n num1 = number / 100;\n num2 = (number % 100) / 10;\n num3 = number%10 ;\n result = 100*num3 + 10*num2 + num1;\n printf(\"After reversing =%d\\n\",result);\n return 0;\n}"
},
{
"code": null,
"e": 2518,
"s": 2478,
"text": "enter a number:479\nAfter reversing =974"
}
] |
Airflow in Docker Metrics Reporting | by Sarah Krasnik | Towards Data Science
|
An unsettling yet likely familiar situation: you deployed Airflow successfully, but find yourself constantly refreshing the webserver UI to make sure everything is running smoothly.
You rely on certain alerting tasks to execute upon upstream failures, but if the queue is full and tasks are stalling, how will you be notified?
One solution: deploying Grafana, an open source reporting service, on top of Airflow.
To start, I’ll assume basic understanding of Airflow functionality and containerization using Docker and Docker Compose. More resources can be found here for Airflow, here for Docker, and here for Docker Compose.
Reference the code to follow along: https://github.com/sarahmk125/airflow-docker-metrics
Now, the fun stuff.
To get Airflow metrics into a visually appealing dashboard that supports alerting, the following services are spun up in Docker containers declared in the docker-compose.yml file:
Airflow: Airflow runs tasks within DAGs, defined in Python files stored in the ./dags/ folder. One sample DAG declaration file is already there. Multiple containers are run, with particular nuances accounting for using the official apache/airflow image. More on that later.
StatsD-Exporter: The StatsD-Exporter container converts Airflow’s metrics in StatsD format to Prometheus format, the datasource for the reporting layer (Grafana). More information on StatsD-Exporter found here. The container definition includes the command to be executed upon startup, defining how to use the ports exposed.
statsd-exporter: image: prom/statsd-exporter container_name: airflow-statsd-exporter command: "--statsd.listen-udp=:8125 --web.listen-address=:9102" ports: - 9123:9102 - 8125:8125/udp
Prometheus: Prometheus is a service commonly used for time-series data reporting. It is particularly convenient when using Grafana as a reporting UI since Prometheus is a supported datasource. More information on Prometheus found here. The volumes mounted in the container definition indicate how the data flows to/from Prometheus.
prometheus: image: prom/prometheus container_name: airflow-prometheus user: "0" ports: - 9090:9090 volumes: - ./prometheus/prometheus.yml:/etc/prometheus/prometheus.yml - ./prometheus/volume:/prometheus
Grafana: Grafana is a reporting UI service that is often used to connect to non-relational databases. In the code described, Grafana uses Prometheus as a datasource for dashboards. The container definition includes an admin user for the portal, as well as the volumes defining datasources and dashboards that are already pre-configured.
grafana: image: grafana/grafana:7.1.5 container_name: airflow-grafana environment: GF_SECURITY_ADMIN_USER: admin GF_SECURITY_ADMIN_PASSWORD: password GF_PATHS_PROVISIONING: /grafana/provisioning ports: - 3000:3000 volumes: - ./grafana/volume/data:/grafana - ./grafana/volume/datasources:/grafana/datasources - ./grafana/volume/dashboards:/grafana/dashboards - ./grafana/volume/provisioning:/grafana/provisioning
To start everything up, the following tools are required: Docker, docker-compose, Python3, Git.
Steps (to be run in a terminal):
Clone the repository: git clone https://github.com/sarahmk125/airflow-docker-metrics.git
Navigate to the cloned folder: cd airflow-docker-metrics
Startup the containers: docker-compose -f docker-compose.yml up -d (Note: they can be stopped or removed by running the same command except with stop or down at the end, respectively)
The result:
Airflow webserver UI: http://localhost:8080
StatsD metrics list: http://localhost:9123/metrics
Prometheus: http://localhost:9090
Grafana: http://localhost:3000 (login: username=admin, password=password)The repository includes an Airflow Metrics dashboard, that can be setup with alerts, showing the number of running and queued tasks over time:
Prometheus is configured upon startup in the ./prometheus/prometheus.yml file which is mounted as a volume:
global: scrape_interval: 30s evaluation_interval: 30s scrape_timeout: 10s external_labels: monitor: 'codelab-monitor'scrape_configs: - job_name: 'prometheus' static_configs: - targets: ['airflow-prometheus:9090'] - job_name: 'statsd-exporter' static_configs: - targets: ['airflow-statsd-exporter:9102'] tls_config: insecure_skip_verify: true
In particular, the scrape_configs section declares a destination (the airflow-prometheus container) and a source (the airflow-statsd-exporter container) to scrape.
Provisioning is your friend!
Provisioning in Grafana means using code to define datasources, dashboards, and alerts to exist upon startup. When starting the containers, there is a Prometheus datasource already configured in localhost:3000/datasources and an Airflow Metrics dashboard listed in localhost:3000/dashboards.
How to provision:
All the relevant data is mounted as volumes onto the grafana container defined in the docker-compose.yml file (described above)
The ./grafana/volume/provisioning/datasources/default.yaml file contains a definition of all data sources:
apiVersion: 1datasources: - name: Prometheus type: prometheus access: proxy url: http://prometheus:9090
The ./grafana/volume/provisioning/dashboards/default.yaml file contains information on where to mount dashboards in the container:
apiVersion: 1providers: - name: dashboards folder: General type: file editable: true updateIntervalSeconds: 10 allowUiUpdates: true options: path: /grafana/dashboards foldersFromFilesStructure: true
The ./grafana/volume/dashboards/ folder contains .json files, each representing a dashboard. The airflow_metrics.json file results in the dashboard shown above.
The JSON can be retrieved from the Grafana UI by following these instructions.
Alerts in the UI can be setup as described here; there is also an excellent Medium article here on setting up Grafana alerting with Slack. Alerts can be provisioned in the same way as dashboards and datasources.
Before there was an official Docker image, Matthieu “Puckel_” Roisil released Docker support for Airflow. Starting with Airflow version 1.10.10, the Apache Software Foundation released an official image on DockerHub which is the only current and continuously updated image. However, many still rely on the legacy and unofficial docker-airflow repository.
Why is this a problem? Well, relying on the legacy repository means capping Airflow at version 1.10.9. Airflow 1.10.10 began supporting some cool features such as running tasks on Kubernetes. The official repository will also be where the the upcoming (and highly anticipated) Airflow 2.0 will be released.
The new docker-compose declaration found in the described repository for the webserver looks something like this:
webserver: container_name: airflow-webserver image: apache/airflow:1.10.12-python3.7 restart: always depends_on: - postgres - redis - statsd-exporter environment: - LOAD_EX=n - EXECUTOR=Local - POSTGRES_USER=airflow - POSTGRES_PASSWORD=airflow - POSTGRES_DB=airflow - AIRFLOW__SCHEDULER__STATSD_ON=True - AIRFLOW__SCHEDULER__STATSD_HOST=statsd-exporter - AIRFLOW__SCHEDULER__STATSD_PORT=8125 - AIRFLOW__SCHEDULER__STATSD_PREFIX=airflow -AIRFLOW__CORE__SQL_ALCHEMY_CONN= postgresql+psycopg2://airflow:airflow@postgres:5432/airflow -AIRFLOW__CORE__FERNET_KEY= pMrhjIcqUNHMYRk_ZOBmMptWR6o1DahCXCKn5lEMpzM= - AIRFLOW__CORE__EXECUTOR=LocalExecutor - AIRFLOW__CORE__AIRFLOW_HOME=/opt/airflow/ - AIRFLOW__CORE__LOAD_EXAMPLES=False - AIRFLOW__CORE__LOAD_DEFAULT_CONNECTIONS=False - AIRFLOW__WEBSERVER__WORKERS=2 - AIRFLOW__WEBSERVER__WORKER_REFRESH_INTERVAL=1800 volumes: - ./dags:/opt/airflow/dags ports: - "8080:8080" command: bash -c "airflow initdb && airflow webserver" healthcheck: test: ["CMD-SHELL", "[ -f /opt/airflow/airflow-webserver.pid ]"] interval: 30s timeout: 30s retries: 3
A few changes from the puckel/docker-airflow configuration to highlight:
Custom parameters such as the AIRFLOW__CORE__SQL_ALCHEMY_CONN that were previously found in the airflow.cfg file are now declared as environment variables in the docker-compose file.
The airflow initdb command to initialize the backend database is now declared as a command in the docker-compose file, as opposed to an entrypoint script.
There you have it. No more worrying if your tasks are infinitely queued and not running. Airflow running in Docker, with dashboards and alerting available in Grafana at your fingertips. The same architecture can be run on an instance deployed in GCP or AWS for 24/7 monitoring just like it was run locally.
The finished product can be found here: https://github.com/sarahmk125/airflow-docker-metrics
It’s important to note, there’s always room for improvement:
This monitoring setup does not capture container or instance failures; a separate or extended solution is needed to monitor at the container or instance level.
The current code runs using the LocalExecutor, which is less than ideal for large workloads. Further testing with the CeleryExecutor can be done.
There are many more metrics available in StatsD that were not highlighted (such as DAG or task duration, counts of task failures, etc.). More dashboards can be built and provisioned in Grafana to leverage all the relevant metrics.
Lastly, this article focuses on a self-hosted (or highly configurable cloud) deployment for Airflow, but this is not the only option for deploying Airflow.
Thanks for reading! I love talking data stacks. Shoot me a message.
|
[
{
"code": null,
"e": 354,
"s": 172,
"text": "An unsettling yet likely familiar situation: you deployed Airflow successfully, but find yourself constantly refreshing the webserver UI to make sure everything is running smoothly."
},
{
"code": null,
"e": 499,
"s": 354,
"text": "You rely on certain alerting tasks to execute upon upstream failures, but if the queue is full and tasks are stalling, how will you be notified?"
},
{
"code": null,
"e": 585,
"s": 499,
"text": "One solution: deploying Grafana, an open source reporting service, on top of Airflow."
},
{
"code": null,
"e": 798,
"s": 585,
"text": "To start, I’ll assume basic understanding of Airflow functionality and containerization using Docker and Docker Compose. More resources can be found here for Airflow, here for Docker, and here for Docker Compose."
},
{
"code": null,
"e": 887,
"s": 798,
"text": "Reference the code to follow along: https://github.com/sarahmk125/airflow-docker-metrics"
},
{
"code": null,
"e": 907,
"s": 887,
"text": "Now, the fun stuff."
},
{
"code": null,
"e": 1087,
"s": 907,
"text": "To get Airflow metrics into a visually appealing dashboard that supports alerting, the following services are spun up in Docker containers declared in the docker-compose.yml file:"
},
{
"code": null,
"e": 1361,
"s": 1087,
"text": "Airflow: Airflow runs tasks within DAGs, defined in Python files stored in the ./dags/ folder. One sample DAG declaration file is already there. Multiple containers are run, with particular nuances accounting for using the official apache/airflow image. More on that later."
},
{
"code": null,
"e": 1686,
"s": 1361,
"text": "StatsD-Exporter: The StatsD-Exporter container converts Airflow’s metrics in StatsD format to Prometheus format, the datasource for the reporting layer (Grafana). More information on StatsD-Exporter found here. The container definition includes the command to be executed upon startup, defining how to use the ports exposed."
},
{
"code": null,
"e": 1880,
"s": 1686,
"text": "statsd-exporter: image: prom/statsd-exporter container_name: airflow-statsd-exporter command: \"--statsd.listen-udp=:8125 --web.listen-address=:9102\" ports: - 9123:9102 - 8125:8125/udp"
},
{
"code": null,
"e": 2212,
"s": 1880,
"text": "Prometheus: Prometheus is a service commonly used for time-series data reporting. It is particularly convenient when using Grafana as a reporting UI since Prometheus is a supported datasource. More information on Prometheus found here. The volumes mounted in the container definition indicate how the data flows to/from Prometheus."
},
{
"code": null,
"e": 2429,
"s": 2212,
"text": "prometheus: image: prom/prometheus container_name: airflow-prometheus user: \"0\" ports: - 9090:9090 volumes: - ./prometheus/prometheus.yml:/etc/prometheus/prometheus.yml - ./prometheus/volume:/prometheus"
},
{
"code": null,
"e": 2766,
"s": 2429,
"text": "Grafana: Grafana is a reporting UI service that is often used to connect to non-relational databases. In the code described, Grafana uses Prometheus as a datasource for dashboards. The container definition includes an admin user for the portal, as well as the volumes defining datasources and dashboards that are already pre-configured."
},
{
"code": null,
"e": 3207,
"s": 2766,
"text": "grafana: image: grafana/grafana:7.1.5 container_name: airflow-grafana environment: GF_SECURITY_ADMIN_USER: admin GF_SECURITY_ADMIN_PASSWORD: password GF_PATHS_PROVISIONING: /grafana/provisioning ports: - 3000:3000 volumes: - ./grafana/volume/data:/grafana - ./grafana/volume/datasources:/grafana/datasources - ./grafana/volume/dashboards:/grafana/dashboards - ./grafana/volume/provisioning:/grafana/provisioning"
},
{
"code": null,
"e": 3303,
"s": 3207,
"text": "To start everything up, the following tools are required: Docker, docker-compose, Python3, Git."
},
{
"code": null,
"e": 3336,
"s": 3303,
"text": "Steps (to be run in a terminal):"
},
{
"code": null,
"e": 3425,
"s": 3336,
"text": "Clone the repository: git clone https://github.com/sarahmk125/airflow-docker-metrics.git"
},
{
"code": null,
"e": 3482,
"s": 3425,
"text": "Navigate to the cloned folder: cd airflow-docker-metrics"
},
{
"code": null,
"e": 3666,
"s": 3482,
"text": "Startup the containers: docker-compose -f docker-compose.yml up -d (Note: they can be stopped or removed by running the same command except with stop or down at the end, respectively)"
},
{
"code": null,
"e": 3678,
"s": 3666,
"text": "The result:"
},
{
"code": null,
"e": 3722,
"s": 3678,
"text": "Airflow webserver UI: http://localhost:8080"
},
{
"code": null,
"e": 3773,
"s": 3722,
"text": "StatsD metrics list: http://localhost:9123/metrics"
},
{
"code": null,
"e": 3807,
"s": 3773,
"text": "Prometheus: http://localhost:9090"
},
{
"code": null,
"e": 4023,
"s": 3807,
"text": "Grafana: http://localhost:3000 (login: username=admin, password=password)The repository includes an Airflow Metrics dashboard, that can be setup with alerts, showing the number of running and queued tasks over time:"
},
{
"code": null,
"e": 4131,
"s": 4023,
"text": "Prometheus is configured upon startup in the ./prometheus/prometheus.yml file which is mounted as a volume:"
},
{
"code": null,
"e": 4512,
"s": 4131,
"text": "global: scrape_interval: 30s evaluation_interval: 30s scrape_timeout: 10s external_labels: monitor: 'codelab-monitor'scrape_configs: - job_name: 'prometheus' static_configs: - targets: ['airflow-prometheus:9090'] - job_name: 'statsd-exporter' static_configs: - targets: ['airflow-statsd-exporter:9102'] tls_config: insecure_skip_verify: true"
},
{
"code": null,
"e": 4676,
"s": 4512,
"text": "In particular, the scrape_configs section declares a destination (the airflow-prometheus container) and a source (the airflow-statsd-exporter container) to scrape."
},
{
"code": null,
"e": 4705,
"s": 4676,
"text": "Provisioning is your friend!"
},
{
"code": null,
"e": 4997,
"s": 4705,
"text": "Provisioning in Grafana means using code to define datasources, dashboards, and alerts to exist upon startup. When starting the containers, there is a Prometheus datasource already configured in localhost:3000/datasources and an Airflow Metrics dashboard listed in localhost:3000/dashboards."
},
{
"code": null,
"e": 5015,
"s": 4997,
"text": "How to provision:"
},
{
"code": null,
"e": 5143,
"s": 5015,
"text": "All the relevant data is mounted as volumes onto the grafana container defined in the docker-compose.yml file (described above)"
},
{
"code": null,
"e": 5250,
"s": 5143,
"text": "The ./grafana/volume/provisioning/datasources/default.yaml file contains a definition of all data sources:"
},
{
"code": null,
"e": 5364,
"s": 5250,
"text": "apiVersion: 1datasources: - name: Prometheus type: prometheus access: proxy url: http://prometheus:9090"
},
{
"code": null,
"e": 5495,
"s": 5364,
"text": "The ./grafana/volume/provisioning/dashboards/default.yaml file contains information on where to mount dashboards in the container:"
},
{
"code": null,
"e": 5723,
"s": 5495,
"text": "apiVersion: 1providers: - name: dashboards folder: General type: file editable: true updateIntervalSeconds: 10 allowUiUpdates: true options: path: /grafana/dashboards foldersFromFilesStructure: true"
},
{
"code": null,
"e": 5884,
"s": 5723,
"text": "The ./grafana/volume/dashboards/ folder contains .json files, each representing a dashboard. The airflow_metrics.json file results in the dashboard shown above."
},
{
"code": null,
"e": 5963,
"s": 5884,
"text": "The JSON can be retrieved from the Grafana UI by following these instructions."
},
{
"code": null,
"e": 6175,
"s": 5963,
"text": "Alerts in the UI can be setup as described here; there is also an excellent Medium article here on setting up Grafana alerting with Slack. Alerts can be provisioned in the same way as dashboards and datasources."
},
{
"code": null,
"e": 6530,
"s": 6175,
"text": "Before there was an official Docker image, Matthieu “Puckel_” Roisil released Docker support for Airflow. Starting with Airflow version 1.10.10, the Apache Software Foundation released an official image on DockerHub which is the only current and continuously updated image. However, many still rely on the legacy and unofficial docker-airflow repository."
},
{
"code": null,
"e": 6837,
"s": 6530,
"text": "Why is this a problem? Well, relying on the legacy repository means capping Airflow at version 1.10.9. Airflow 1.10.10 began supporting some cool features such as running tasks on Kubernetes. The official repository will also be where the the upcoming (and highly anticipated) Airflow 2.0 will be released."
},
{
"code": null,
"e": 6951,
"s": 6837,
"text": "The new docker-compose declaration found in the described repository for the webserver looks something like this:"
},
{
"code": null,
"e": 8121,
"s": 6951,
"text": "webserver: container_name: airflow-webserver image: apache/airflow:1.10.12-python3.7 restart: always depends_on: - postgres - redis - statsd-exporter environment: - LOAD_EX=n - EXECUTOR=Local - POSTGRES_USER=airflow - POSTGRES_PASSWORD=airflow - POSTGRES_DB=airflow - AIRFLOW__SCHEDULER__STATSD_ON=True - AIRFLOW__SCHEDULER__STATSD_HOST=statsd-exporter - AIRFLOW__SCHEDULER__STATSD_PORT=8125 - AIRFLOW__SCHEDULER__STATSD_PREFIX=airflow -AIRFLOW__CORE__SQL_ALCHEMY_CONN= postgresql+psycopg2://airflow:airflow@postgres:5432/airflow -AIRFLOW__CORE__FERNET_KEY= pMrhjIcqUNHMYRk_ZOBmMptWR6o1DahCXCKn5lEMpzM= - AIRFLOW__CORE__EXECUTOR=LocalExecutor - AIRFLOW__CORE__AIRFLOW_HOME=/opt/airflow/ - AIRFLOW__CORE__LOAD_EXAMPLES=False - AIRFLOW__CORE__LOAD_DEFAULT_CONNECTIONS=False - AIRFLOW__WEBSERVER__WORKERS=2 - AIRFLOW__WEBSERVER__WORKER_REFRESH_INTERVAL=1800 volumes: - ./dags:/opt/airflow/dags ports: - \"8080:8080\" command: bash -c \"airflow initdb && airflow webserver\" healthcheck: test: [\"CMD-SHELL\", \"[ -f /opt/airflow/airflow-webserver.pid ]\"] interval: 30s timeout: 30s retries: 3"
},
{
"code": null,
"e": 8194,
"s": 8121,
"text": "A few changes from the puckel/docker-airflow configuration to highlight:"
},
{
"code": null,
"e": 8377,
"s": 8194,
"text": "Custom parameters such as the AIRFLOW__CORE__SQL_ALCHEMY_CONN that were previously found in the airflow.cfg file are now declared as environment variables in the docker-compose file."
},
{
"code": null,
"e": 8532,
"s": 8377,
"text": "The airflow initdb command to initialize the backend database is now declared as a command in the docker-compose file, as opposed to an entrypoint script."
},
{
"code": null,
"e": 8839,
"s": 8532,
"text": "There you have it. No more worrying if your tasks are infinitely queued and not running. Airflow running in Docker, with dashboards and alerting available in Grafana at your fingertips. The same architecture can be run on an instance deployed in GCP or AWS for 24/7 monitoring just like it was run locally."
},
{
"code": null,
"e": 8932,
"s": 8839,
"text": "The finished product can be found here: https://github.com/sarahmk125/airflow-docker-metrics"
},
{
"code": null,
"e": 8993,
"s": 8932,
"text": "It’s important to note, there’s always room for improvement:"
},
{
"code": null,
"e": 9153,
"s": 8993,
"text": "This monitoring setup does not capture container or instance failures; a separate or extended solution is needed to monitor at the container or instance level."
},
{
"code": null,
"e": 9299,
"s": 9153,
"text": "The current code runs using the LocalExecutor, which is less than ideal for large workloads. Further testing with the CeleryExecutor can be done."
},
{
"code": null,
"e": 9530,
"s": 9299,
"text": "There are many more metrics available in StatsD that were not highlighted (such as DAG or task duration, counts of task failures, etc.). More dashboards can be built and provisioned in Grafana to leverage all the relevant metrics."
},
{
"code": null,
"e": 9686,
"s": 9530,
"text": "Lastly, this article focuses on a self-hosted (or highly configurable cloud) deployment for Airflow, but this is not the only option for deploying Airflow."
}
] |
Can we explicitly define datatype in a Python Function?
|
In Python, variables are never explicitly typed. Python figures out what type a variable is and keeps track of it internally. In Java, C++, and other statically-typed languages, you must specify the datatype of the function return value and each function argument.
If we explicitly define datatype in a python function, it still works like a normal program where data type is not declared explicitly.
We get the following output for the given code
C:/Users/TutorialsPoint1/~.py
The required Sum is: 13.0
Consider this function
def addSum(x,y):
return x+y
print addSum(2.2, 5.6)
print addSum(float(2.2), float(5.6))
7.8
7.8
So the declaration of the datatype of a variable explicitly has no impact on the output.
|
[
{
"code": null,
"e": 1327,
"s": 1062,
"text": "In Python, variables are never explicitly typed. Python figures out what type a variable is and keeps track of it internally. In Java, C++, and other statically-typed languages, you must specify the datatype of the function return value and each function argument."
},
{
"code": null,
"e": 1463,
"s": 1327,
"text": "If we explicitly define datatype in a python function, it still works like a normal program where data type is not declared explicitly."
},
{
"code": null,
"e": 1510,
"s": 1463,
"text": "We get the following output for the given code"
},
{
"code": null,
"e": 1567,
"s": 1510,
"text": "C:/Users/TutorialsPoint1/~.py\nThe required Sum is: 13.0"
},
{
"code": null,
"e": 1590,
"s": 1567,
"text": "Consider this function"
},
{
"code": null,
"e": 1685,
"s": 1590,
"text": "def addSum(x,y):\n return x+y\nprint addSum(2.2, 5.6)\nprint addSum(float(2.2), float(5.6))"
},
{
"code": null,
"e": 1693,
"s": 1685,
"text": "7.8\n7.8"
},
{
"code": null,
"e": 1782,
"s": 1693,
"text": "So the declaration of the datatype of a variable explicitly has no impact on the output."
}
] |
How to bring Tkinter window in front of other windows?
|
Tkinter window are created and executed by mainloop() function. The mainloop() function gets executed until the application is not closed by the user abruptly.
To keep the Tkinter window above all the other windows, we can use win.after(duration, function()) function in a loop. This function inside the loop gets executed and forces the main window to appear above all the other windows.
# Import the required libraries
from tkinter import *
from tkinter import ttk
# Create an instance of tkinter frame or window
win = Tk()
# Set the size of the window
win.geometry("700x350")
# Define a function to make the window above
def lift_window():
win.lift()
win.after(1000, lift_window)
# Add A label widget
Label(win, text="Hey Folks, Welcome to TutorialsPoint✨", font=('Aerial 18 italic')).place(x=130, y=150)
lift_window()
win.mainloop()
Run the above code to display a window that will appear above all the other windows.
|
[
{
"code": null,
"e": 1222,
"s": 1062,
"text": "Tkinter window are created and executed by mainloop() function. The mainloop() function gets executed until the application is not closed by the user abruptly."
},
{
"code": null,
"e": 1451,
"s": 1222,
"text": "To keep the Tkinter window above all the other windows, we can use win.after(duration, function()) function in a loop. This function inside the loop gets executed and forces the main window to appear above all the other windows."
},
{
"code": null,
"e": 1911,
"s": 1451,
"text": "# Import the required libraries\nfrom tkinter import *\nfrom tkinter import ttk\n\n# Create an instance of tkinter frame or window\nwin = Tk()\n\n# Set the size of the window\nwin.geometry(\"700x350\")\n\n# Define a function to make the window above\ndef lift_window():\n win.lift()\n win.after(1000, lift_window)\n\n# Add A label widget\nLabel(win, text=\"Hey Folks, Welcome to TutorialsPoint✨\", font=('Aerial 18 italic')).place(x=130, y=150)\n\nlift_window()\n\nwin.mainloop()"
},
{
"code": null,
"e": 1996,
"s": 1911,
"text": "Run the above code to display a window that will appear above all the other windows."
}
] |
Switch case in Arduino
|
Switch case in Arduino is just like the switch case in C language. For those who are unaware of switch case, it is a more compact way of writing multiple if statements, when they concern the value of a variable.
switch (var) {
case value1:
// statements for value1
break;
case value2:
// statements for value2
break;
.
.
.
default:
// statements for default value
break;
}
var is the variable whose different values we are checking. If its value is equal to value1, then the statements for value1 will be executed. If its value is equal to value2, then the statements for value2 will be executed, and so on. If the value is not equal to any values listed, then the statements corresponding to the default value will be executed. If you don’t add the break statement after each case, then all the cases following it will be executed, till the first break is encountered.
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Serial.println();
while(!Serial.available()){
Serial.print('.');
delay(500);
}
int a = Serial.parseInt();
Serial.print("Serial value received is "); Serial.println(a);
switch(a){
case 1:
Serial.println("Value 1 received");
break;
case 2:
Serial.println("Value 2 received");
break;
case 3:
Serial.println("Value 3 received");
break;
default:
Serial.println("Value outside 1,2,3 received");
break;
}
}
void loop() {
// put your main code here, to run repeatedly:
}
As you can see, we take one integer from the user (Serial.parseInt()), and print different values depending on the value of the input.
The Serial Monitor Output is shown below −
|
[
{
"code": null,
"e": 1274,
"s": 1062,
"text": "Switch case in Arduino is just like the switch case in C language. For those who are unaware of switch case, it is a more compact way of writing multiple if statements, when they concern the value of a variable."
},
{
"code": null,
"e": 1480,
"s": 1274,
"text": "switch (var) {\n case value1:\n // statements for value1\n break;\n case value2:\n // statements for value2\n break;\n.\n.\n.\n default:\n // statements for default value\n break;\n}"
},
{
"code": null,
"e": 1977,
"s": 1480,
"text": "var is the variable whose different values we are checking. If its value is equal to value1, then the statements for value1 will be executed. If its value is equal to value2, then the statements for value2 will be executed, and so on. If the value is not equal to any values listed, then the statements corresponding to the default value will be executed. If you don’t add the break statement after each case, then all the cases following it will be executed, till the first break is encountered."
},
{
"code": null,
"e": 2661,
"s": 1977,
"text": "void setup() {\n // put your setup code here, to run once:\n Serial.begin(9600);\n Serial.println();\n\n while(!Serial.available()){\n Serial.print('.');\n delay(500);\n }\n\n int a = Serial.parseInt();\n Serial.print(\"Serial value received is \"); Serial.println(a);\n switch(a){\n case 1:\n Serial.println(\"Value 1 received\");\n break;\n\n case 2:\n Serial.println(\"Value 2 received\");\n break;\n\n case 3:\n Serial.println(\"Value 3 received\");\n break;\n\n default:\n Serial.println(\"Value outside 1,2,3 received\");\n break;\n }\n}\n\nvoid loop() {\n // put your main code here, to run repeatedly:\n}"
},
{
"code": null,
"e": 2796,
"s": 2661,
"text": "As you can see, we take one integer from the user (Serial.parseInt()), and print different values depending on the value of the input."
},
{
"code": null,
"e": 2839,
"s": 2796,
"text": "The Serial Monitor Output is shown below −"
}
] |
Average of each n-length consecutive segment in a Python list
|
We have a list containing only numbers. We plan to get the average of a set of sequential numbers from the list which keeps rolling from the first number to next number and then to next number and so on.
The below example simplifies the requirement of finding the average of each 4-length consecutive elements of the list.
Given list:
[10,12,14,16,18,20,22,24,26]
Average of every segment of 4 consecutive numbers:
[13.0, 15.0, 17.0, 19.0, 21.0, 23.0]
We use the list comprehension approach to take the sum of the consecutive numbers by applying range to keep track of how many numbers we gathered. Then we keep dividing the sum with the segment length with the help of a loop. Finally the result is gathered into a new list.
Live Demo
listA = [10,12,14,16,18,20,22,24,26]
print("Given list:\n",listA)
seg = 4
# List comprehension
res = [sum(listA[m:m + seg])/seg
for m in range(len(listA) - seg + 1)]
print("new list with averages:\n ",res)
Running the above code gives us the following result −
Given list:
[10, 12, 14, 16, 18, 20, 22, 24, 26]
new list with averages:
[13.0, 15.0, 17.0, 19.0, 21.0, 23.0]
In this approach we take help of python modules which can calculate these values in a more direct way. We keep slicing the elements of the list in the given range using the isslice function and then apply the mean function directly on the new list to get the final result.
Live Demo
from statistics import mean
from itertools import islice
listA = [10,12,14,16,18,20,22,24,26]
print("Given list:\n",listA)
# With islice and mean
listB = zip(*(islice(listA, i, None) for i in range(4)))
res = list(map(mean, listB))
print("new list with averages:\n ",res)
Running the above code gives us the following result −
Given list:
[10, 12, 14, 16, 18, 20, 22, 24, 26]
new list with averages:
[13, 15, 17, 19, 21, 23]
|
[
{
"code": null,
"e": 1266,
"s": 1062,
"text": "We have a list containing only numbers. We plan to get the average of a set of sequential numbers from the list which keeps rolling from the first number to next number and then to next number and so on."
},
{
"code": null,
"e": 1385,
"s": 1266,
"text": "The below example simplifies the requirement of finding the average of each 4-length consecutive elements of the list."
},
{
"code": null,
"e": 1516,
"s": 1385,
"text": "Given list:\n[10,12,14,16,18,20,22,24,26]\n\nAverage of every segment of 4 consecutive numbers:\n\n[13.0, 15.0, 17.0, 19.0, 21.0, 23.0]"
},
{
"code": null,
"e": 1790,
"s": 1516,
"text": "We use the list comprehension approach to take the sum of the consecutive numbers by applying range to keep track of how many numbers we gathered. Then we keep dividing the sum with the segment length with the help of a loop. Finally the result is gathered into a new list."
},
{
"code": null,
"e": 1801,
"s": 1790,
"text": " Live Demo"
},
{
"code": null,
"e": 2013,
"s": 1801,
"text": "listA = [10,12,14,16,18,20,22,24,26]\nprint(\"Given list:\\n\",listA)\nseg = 4\n# List comprehension\nres = [sum(listA[m:m + seg])/seg\n for m in range(len(listA) - seg + 1)]\nprint(\"new list with averages:\\n \",res)"
},
{
"code": null,
"e": 2068,
"s": 2013,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2184,
"s": 2068,
"text": "Given list:\n [10, 12, 14, 16, 18, 20, 22, 24, 26]\nnew list with averages:\n [13.0, 15.0, 17.0, 19.0, 21.0, 23.0]"
},
{
"code": null,
"e": 2457,
"s": 2184,
"text": "In this approach we take help of python modules which can calculate these values in a more direct way. We keep slicing the elements of the list in the given range using the isslice function and then apply the mean function directly on the new list to get the final result."
},
{
"code": null,
"e": 2468,
"s": 2457,
"text": " Live Demo"
},
{
"code": null,
"e": 2743,
"s": 2468,
"text": "from statistics import mean\nfrom itertools import islice\n\nlistA = [10,12,14,16,18,20,22,24,26]\nprint(\"Given list:\\n\",listA)\n\n# With islice and mean\nlistB = zip(*(islice(listA, i, None) for i in range(4)))\nres = list(map(mean, listB))\n\nprint(\"new list with averages:\\n \",res)"
},
{
"code": null,
"e": 2798,
"s": 2743,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2902,
"s": 2798,
"text": "Given list:\n [10, 12, 14, 16, 18, 20, 22, 24, 26]\nnew list with averages:\n [13, 15, 17, 19, 21, 23]"
}
] |
C# | BitConverter.ToInt32() Method - GeeksforGeeks
|
19 May, 2021
BitConverter.ToInt32(Byte[], Int32) Method is used to return a 32-bit signed integer converted from four bytes at a specified position in a byte array.Syntax:
public static int ToInt32 (byte[] value, int startIndex);
Parameters:
value: It is an array of bytes. startIndex: It is the starting position within the value.
Return Value: This method returns a 32-bit signed integer formed by two bytes beginning at startIndex.Exceptions:
ArgumentException: If the startIndex is greater than or equal to the length of value minus 3, and is less than or equal to the length of value minus 1.
ArgumentNullException: If the value is null.
ArgumentOutOfRangeException: If the startIndex is less than zero or greater than the length of value minus 1.
Below programs illustrate the use of BitConverter.ToInt32(Byte[], Int32) Method:Example 1:
CSHARP
// C# program to demonstrate// BitConverter.ToInt32(Byte[], Int32);// Methodusing System; class GFG { // Main Methodpublic static void Main(){ try { // Define an array // of byte values. byte[] bytes = {32, 0, 0, 42, 0, 65, 0, 125, 0, 197, 0, 168, 3, 41, 4, 125, 32 }; // Display the values of the myArr. Console.Write("Initial Array: "); // calling the PrintIndexAndValues() // method to print PrintIndexAndValues(bytes); // print char value Console.WriteLine("index byte Array int value"); for (int index = 0; index < bytes.Length - 3; index = index + 4) { int values = BitConverter.ToInt16(bytes, index); Console.WriteLine(" {0} {1} {2}", index, BitConverter.ToString(bytes, index, 4), values); } } catch (ArgumentNullException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } catch (ArgumentOutOfRangeException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } catch (ArgumentException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); }} // Defining the method// PrintIndexAndValuespublic static void PrintIndexAndValues(byte[] myArr){ for (int i = 0; i < myArr.Length; i++) { Console.Write("{0} ", myArr[i]); } Console.WriteLine(); Console.WriteLine();}}
Output:
Initial Array: 32 0 0 42 0 65 0 125 0 197 0 168 3 41 4 125 32
index byte Array int value
0 20-00-00-2A 32
4 00-41-00-7D 16640
8 00-C5-00-A8 -15104
12 03-29-04-7D 10499
Example 2: For ArgumentException
CSHARP
// C# program to demonstrate// BitConverter.ToInt32(Byte[], Int32);// Methodusing System; class GFG { // Main Methodpublic static void Main(){ try { // Define an array // of byte values. byte[] bytes = {32, 0, 0, 42, 0, 65, 0, 125, 0, 197, 0, 168, 3, 41, 4, 125}; // Display the values of the myArr. Console.Write("Initial Array: "); // calling the PrintIndexAndValues() // method to print PrintIndexAndValues(bytes); // print char value Console.WriteLine("index element int value"); for (int index = 1; index < bytes.Length - 2; index = index + 4) { if (index == bytes.Length - 3) { Console.WriteLine(); Console.WriteLine("startIndex equals the "+ "length of value minus 3."); int values = BitConverter.ToInt32(bytes, index); Console.WriteLine(" {0} {1} {2}", index, BitConverter.ToString(bytes, index, 4), values); } else { int values = BitConverter.ToInt32(bytes, index); Console.WriteLine(" {0} {1} {2}", index, BitConverter.ToString(bytes, index, 4), values); } } } catch (ArgumentNullException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } catch (ArgumentOutOfRangeException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } catch (ArgumentException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); }} // Defining the method// PrintIndexAndValuespublic static void PrintIndexAndValues(byte[] myArr){ for (int i = 0; i < myArr.Length; i++) { Console.Write("{0} ", myArr[i]); } Console.WriteLine(); Console.WriteLine(); Console.WriteLine("initial Array in string: {0} ", BitConverter.ToString(myArr)); Console.WriteLine();}}
Output:
Initial Array: 32 0 0 42 0 65 0 125 0 197 0 168 3 41 4 125
initial Array in string: 20-00-00-2A-00-41-00-7D-00-C5-00-A8-03-29-04-7D
index element int value
1 00-00-2A-00 2752512
5 41-00-7D-00 8192065
9 C5-00-A8-03 61341893
startIndex equals the length of value minus 3.
Exception Thrown: System.ArgumentException
Example 3: For ArgumentOutOfRangeException
CSHARP
// C# program to demonstrate// BitConverter.ToInt32(Byte[], Int32);// Methodusing System; class GFG { // Main Methodpublic static void Main(){ try { // Define an array // of byte values. byte[] bytes = {32, 0, 0, 42, 0, 65, 0, 125, 0, 197, 0, 168, 3, 41, 4, 125}; // Display the values of the myArr. Console.Write("Initial Array: "); // calling the PrintIndexAndValues() // method to print PrintIndexAndValues(bytes); // print char value Console.WriteLine("index element int value"); for (int index = 0; index < bytes.Length + 1; index = index + 4) { if (index == bytes.Length) { Console.WriteLine(); Console.WriteLine("startIndex is greater than "+ "the length of value minus 1"); int values = BitConverter.ToInt32(bytes, index); Console.WriteLine(" {0} {1} {2}", index, BitConverter.ToString(bytes, index, 4), values); } else { int values = BitConverter.ToInt32(bytes, index); Console.WriteLine(" {0} {1} {2}", index, BitConverter.ToString(bytes, index, 4), values); } } } catch (ArgumentNullException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } catch (ArgumentOutOfRangeException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } catch (ArgumentException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); }} // Defining the method// PrintIndexAndValuespublic static void PrintIndexAndValues(byte[] myArr){ for (int i = 0; i < myArr.Length; i++) { Console.Write("{0} ", myArr[i]); } Console.WriteLine(); Console.WriteLine(); Console.WriteLine("initial Array in string: {0} ", BitConverter.ToString(myArr)); Console.WriteLine();}}
Output:
Initial Array: 32 0 0 42 0 65 0 125 0 197 0 168 3 41 4 125
initial Array in string: 20-00-00-2A-00-41-00-7D-00-C5-00-A8-03-29-04-7D
index element int value
0 20-00-00-2A 704643104
4 00-41-00-7D 2097168640
8 00-C5-00-A8 -1476344576
12 03-29-04-7D 2097424643
startIndex is greater than the length of value minus 1
Exception Thrown: System.ArgumentOutOfRangeException
Example 4: For ArgumentNullException
CSHARP
// C# program to demonstrate// BitConverter.ToInt32(Byte[], Int32);// Methodusing System; class GFG { // Main Methodpublic static void Main(){ try { // Define an array of byte values. byte[] bytes = null; // get the int value int values = BitConverter.ToInt32(bytes, 0); Console.Write("{0}", values); } catch (ArgumentNullException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } catch (ArgumentOutOfRangeException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } catch (ArgumentException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); }}}
Output:
Exception Thrown: System.ArgumentNullException
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.bitconverter.toint32?view=netframework-4.7.2
simranarora5sos
CSharp-BitConverter-Class
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Abstract Class and Interface in C#
C# | How to check whether a List contains a specified element
C# | IsNullOrEmpty() Method
String.Split() Method in C# with Examples
C# | Method Overriding
C# Dictionary with examples
C# | Arrays of Strings
Difference between Ref and Out keywords in C#
C# | Delegates
Destructors in C#
|
[
{
"code": null,
"e": 23282,
"s": 23254,
"text": "\n19 May, 2021"
},
{
"code": null,
"e": 23443,
"s": 23282,
"text": "BitConverter.ToInt32(Byte[], Int32) Method is used to return a 32-bit signed integer converted from four bytes at a specified position in a byte array.Syntax: "
},
{
"code": null,
"e": 23501,
"s": 23443,
"text": "public static int ToInt32 (byte[] value, int startIndex);"
},
{
"code": null,
"e": 23514,
"s": 23501,
"text": "Parameters: "
},
{
"code": null,
"e": 23606,
"s": 23514,
"text": "value: It is an array of bytes. startIndex: It is the starting position within the value. "
},
{
"code": null,
"e": 23722,
"s": 23606,
"text": "Return Value: This method returns a 32-bit signed integer formed by two bytes beginning at startIndex.Exceptions: "
},
{
"code": null,
"e": 23874,
"s": 23722,
"text": "ArgumentException: If the startIndex is greater than or equal to the length of value minus 3, and is less than or equal to the length of value minus 1."
},
{
"code": null,
"e": 23919,
"s": 23874,
"text": "ArgumentNullException: If the value is null."
},
{
"code": null,
"e": 24029,
"s": 23919,
"text": "ArgumentOutOfRangeException: If the startIndex is less than zero or greater than the length of value minus 1."
},
{
"code": null,
"e": 24121,
"s": 24029,
"text": "Below programs illustrate the use of BitConverter.ToInt32(Byte[], Int32) Method:Example 1: "
},
{
"code": null,
"e": 24128,
"s": 24121,
"text": "CSHARP"
},
{
"code": "// C# program to demonstrate// BitConverter.ToInt32(Byte[], Int32);// Methodusing System; class GFG { // Main Methodpublic static void Main(){ try { // Define an array // of byte values. byte[] bytes = {32, 0, 0, 42, 0, 65, 0, 125, 0, 197, 0, 168, 3, 41, 4, 125, 32 }; // Display the values of the myArr. Console.Write(\"Initial Array: \"); // calling the PrintIndexAndValues() // method to print PrintIndexAndValues(bytes); // print char value Console.WriteLine(\"index byte Array int value\"); for (int index = 0; index < bytes.Length - 3; index = index + 4) { int values = BitConverter.ToInt16(bytes, index); Console.WriteLine(\" {0} {1} {2}\", index, BitConverter.ToString(bytes, index, 4), values); } } catch (ArgumentNullException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } catch (ArgumentOutOfRangeException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } catch (ArgumentException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); }} // Defining the method// PrintIndexAndValuespublic static void PrintIndexAndValues(byte[] myArr){ for (int i = 0; i < myArr.Length; i++) { Console.Write(\"{0} \", myArr[i]); } Console.WriteLine(); Console.WriteLine();}}",
"e": 25796,
"s": 24128,
"text": null
},
{
"code": null,
"e": 25806,
"s": 25796,
"text": "Output: "
},
{
"code": null,
"e": 26055,
"s": 25806,
"text": "Initial Array: 32 0 0 42 0 65 0 125 0 197 0 168 3 41 4 125 32 \n\nindex byte Array int value\n 0 20-00-00-2A 32\n 4 00-41-00-7D 16640\n 8 00-C5-00-A8 -15104\n 12 03-29-04-7D 10499"
},
{
"code": null,
"e": 26089,
"s": 26055,
"text": "Example 2: For ArgumentException "
},
{
"code": null,
"e": 26096,
"s": 26089,
"text": "CSHARP"
},
{
"code": "// C# program to demonstrate// BitConverter.ToInt32(Byte[], Int32);// Methodusing System; class GFG { // Main Methodpublic static void Main(){ try { // Define an array // of byte values. byte[] bytes = {32, 0, 0, 42, 0, 65, 0, 125, 0, 197, 0, 168, 3, 41, 4, 125}; // Display the values of the myArr. Console.Write(\"Initial Array: \"); // calling the PrintIndexAndValues() // method to print PrintIndexAndValues(bytes); // print char value Console.WriteLine(\"index element int value\"); for (int index = 1; index < bytes.Length - 2; index = index + 4) { if (index == bytes.Length - 3) { Console.WriteLine(); Console.WriteLine(\"startIndex equals the \"+ \"length of value minus 3.\"); int values = BitConverter.ToInt32(bytes, index); Console.WriteLine(\" {0} {1} {2}\", index, BitConverter.ToString(bytes, index, 4), values); } else { int values = BitConverter.ToInt32(bytes, index); Console.WriteLine(\" {0} {1} {2}\", index, BitConverter.ToString(bytes, index, 4), values); } } } catch (ArgumentNullException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } catch (ArgumentOutOfRangeException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } catch (ArgumentException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); }} // Defining the method// PrintIndexAndValuespublic static void PrintIndexAndValues(byte[] myArr){ for (int i = 0; i < myArr.Length; i++) { Console.Write(\"{0} \", myArr[i]); } Console.WriteLine(); Console.WriteLine(); Console.WriteLine(\"initial Array in string: {0} \", BitConverter.ToString(myArr)); Console.WriteLine();}}",
"e": 28272,
"s": 26096,
"text": null
},
{
"code": null,
"e": 28282,
"s": 28272,
"text": "Output: "
},
{
"code": null,
"e": 28659,
"s": 28282,
"text": "Initial Array: 32 0 0 42 0 65 0 125 0 197 0 168 3 41 4 125 \n\ninitial Array in string: 20-00-00-2A-00-41-00-7D-00-C5-00-A8-03-29-04-7D \n\nindex element int value\n 1 00-00-2A-00 2752512\n 5 41-00-7D-00 8192065\n 9 C5-00-A8-03 61341893\n\nstartIndex equals the length of value minus 3.\nException Thrown: System.ArgumentException"
},
{
"code": null,
"e": 28703,
"s": 28659,
"text": "Example 3: For ArgumentOutOfRangeException "
},
{
"code": null,
"e": 28710,
"s": 28703,
"text": "CSHARP"
},
{
"code": "// C# program to demonstrate// BitConverter.ToInt32(Byte[], Int32);// Methodusing System; class GFG { // Main Methodpublic static void Main(){ try { // Define an array // of byte values. byte[] bytes = {32, 0, 0, 42, 0, 65, 0, 125, 0, 197, 0, 168, 3, 41, 4, 125}; // Display the values of the myArr. Console.Write(\"Initial Array: \"); // calling the PrintIndexAndValues() // method to print PrintIndexAndValues(bytes); // print char value Console.WriteLine(\"index element int value\"); for (int index = 0; index < bytes.Length + 1; index = index + 4) { if (index == bytes.Length) { Console.WriteLine(); Console.WriteLine(\"startIndex is greater than \"+ \"the length of value minus 1\"); int values = BitConverter.ToInt32(bytes, index); Console.WriteLine(\" {0} {1} {2}\", index, BitConverter.ToString(bytes, index, 4), values); } else { int values = BitConverter.ToInt32(bytes, index); Console.WriteLine(\" {0} {1} {2}\", index, BitConverter.ToString(bytes, index, 4), values); } } } catch (ArgumentNullException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } catch (ArgumentOutOfRangeException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } catch (ArgumentException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); }} // Defining the method// PrintIndexAndValuespublic static void PrintIndexAndValues(byte[] myArr){ for (int i = 0; i < myArr.Length; i++) { Console.Write(\"{0} \", myArr[i]); } Console.WriteLine(); Console.WriteLine(); Console.WriteLine(\"initial Array in string: {0} \", BitConverter.ToString(myArr)); Console.WriteLine();}}",
"e": 30900,
"s": 28710,
"text": null
},
{
"code": null,
"e": 30909,
"s": 30900,
"text": "Output: "
},
{
"code": null,
"e": 31353,
"s": 30909,
"text": "Initial Array: 32 0 0 42 0 65 0 125 0 197 0 168 3 41 4 125 \n\ninitial Array in string: 20-00-00-2A-00-41-00-7D-00-C5-00-A8-03-29-04-7D \n\nindex element int value\n 0 20-00-00-2A 704643104\n 4 00-41-00-7D 2097168640\n 8 00-C5-00-A8 -1476344576\n 12 03-29-04-7D 2097424643\n\nstartIndex is greater than the length of value minus 1\nException Thrown: System.ArgumentOutOfRangeException"
},
{
"code": null,
"e": 31391,
"s": 31353,
"text": "Example 4: For ArgumentNullException "
},
{
"code": null,
"e": 31398,
"s": 31391,
"text": "CSHARP"
},
{
"code": "// C# program to demonstrate// BitConverter.ToInt32(Byte[], Int32);// Methodusing System; class GFG { // Main Methodpublic static void Main(){ try { // Define an array of byte values. byte[] bytes = null; // get the int value int values = BitConverter.ToInt32(bytes, 0); Console.Write(\"{0}\", values); } catch (ArgumentNullException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } catch (ArgumentOutOfRangeException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } catch (ArgumentException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); }}}",
"e": 32170,
"s": 31398,
"text": null
},
{
"code": null,
"e": 32180,
"s": 32170,
"text": "Output: "
},
{
"code": null,
"e": 32227,
"s": 32180,
"text": "Exception Thrown: System.ArgumentNullException"
},
{
"code": null,
"e": 32240,
"s": 32227,
"text": "Reference: "
},
{
"code": null,
"e": 32336,
"s": 32240,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.bitconverter.toint32?view=netframework-4.7.2"
},
{
"code": null,
"e": 32354,
"s": 32338,
"text": "simranarora5sos"
},
{
"code": null,
"e": 32380,
"s": 32354,
"text": "CSharp-BitConverter-Class"
},
{
"code": null,
"e": 32394,
"s": 32380,
"text": "CSharp-method"
},
{
"code": null,
"e": 32397,
"s": 32394,
"text": "C#"
},
{
"code": null,
"e": 32495,
"s": 32397,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32549,
"s": 32495,
"text": "Difference between Abstract Class and Interface in C#"
},
{
"code": null,
"e": 32611,
"s": 32549,
"text": "C# | How to check whether a List contains a specified element"
},
{
"code": null,
"e": 32639,
"s": 32611,
"text": "C# | IsNullOrEmpty() Method"
},
{
"code": null,
"e": 32681,
"s": 32639,
"text": "String.Split() Method in C# with Examples"
},
{
"code": null,
"e": 32704,
"s": 32681,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 32732,
"s": 32704,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 32755,
"s": 32732,
"text": "C# | Arrays of Strings"
},
{
"code": null,
"e": 32801,
"s": 32755,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 32816,
"s": 32801,
"text": "C# | Delegates"
}
] |
jQuery | closest() with Examples - GeeksforGeeks
|
03 Aug, 2021
The closest() is an inbuilt method in jQuery that returns the first ancestor of the selected element in the DOM tree. This method traverse upwards from the current element in the search of first ancestor of the element. Document Object Model (DOM) is a World Wide Web Consortium standard. This defines for accessing elements in the DOM tree.Syntax:
$(selector).closest(para1, para2);
Parameter: It accepts two parameters which are specified below-
para1: This specifies the element to narrate the ancestor search in the DOM tree.
para2: This is an optional parameter DOM element within which a matching element being found.
Return Value: It returns the first ancestor for the selected element.
<html> <head> <style> .main * { display: block; border: 2px solid lightgrey; color: grey; padding: 5px; margin: 15px; } </style> <script src="https://ajax.googleapis.com/ajax/libs/ jquery/3.3.1/jquery.min.js"></script> <script> <!-- here is the script code for performing the method --> $(document).ready(function() { $("span").closest("ul").css({ "color": "green", "border": "2px solid green" }); }); </script></head> <body class="main"> This is great-great grand parent element ! <div style="width:600px;"> This is great grand parent element ! <ul> This is the second ancestor element ! <ul> <!-- This element will be selected --> This is first ancestor element ! <li>This is direct parent ! <span>This is span the child element !</span> </li> </ul> </ul> </div></body> </html>
Output:Code #2:In the below code, optional parameter is passed to the method.
<html> <head> <style> .main * { display: block; border: 2px solid lightgrey; color: grey; padding: 5px; margin: 15px; } </style> <script src="https://ajax.googleapis.com/ajax/libs/ jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function() { <!--Here among dom id first ancestor will select --> var item = document.getElementById("dom"); $("li").closest("ul", item).css({ "color": "green", "border": "2px solid green" }); }); </script></head> <body class="main"> This is great-great-grandparent ! <div style="width:500px;"> div (great-grandparent) <ul id="dom"> This is second ancestor ! <ul id="dom"> This is first ancestor ! <li>This is direct parent ! <span>This is span the child one !</span> </li> </ul> </ul> </div></body> </html>
Output:
jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.
jQuery-Traversing
JavaScript
JQuery
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
How to calculate the number of days between two dates in javascript?
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
JQuery | Set the value of an input text field
How to change selected value of a drop-down list using jQuery?
Form validation using jQuery
How to change the background color after clicking the button in JavaScript ?
How to Dynamically Add/Remove Table Rows using jQuery ?
|
[
{
"code": null,
"e": 40723,
"s": 40695,
"text": "\n03 Aug, 2021"
},
{
"code": null,
"e": 41072,
"s": 40723,
"text": "The closest() is an inbuilt method in jQuery that returns the first ancestor of the selected element in the DOM tree. This method traverse upwards from the current element in the search of first ancestor of the element. Document Object Model (DOM) is a World Wide Web Consortium standard. This defines for accessing elements in the DOM tree.Syntax:"
},
{
"code": null,
"e": 41108,
"s": 41072,
"text": "$(selector).closest(para1, para2);\n"
},
{
"code": null,
"e": 41172,
"s": 41108,
"text": "Parameter: It accepts two parameters which are specified below-"
},
{
"code": null,
"e": 41254,
"s": 41172,
"text": "para1: This specifies the element to narrate the ancestor search in the DOM tree."
},
{
"code": null,
"e": 41348,
"s": 41254,
"text": "para2: This is an optional parameter DOM element within which a matching element being found."
},
{
"code": null,
"e": 41418,
"s": 41348,
"text": "Return Value: It returns the first ancestor for the selected element."
},
{
"code": "<html> <head> <style> .main * { display: block; border: 2px solid lightgrey; color: grey; padding: 5px; margin: 15px; } </style> <script src=\"https://ajax.googleapis.com/ajax/libs/ jquery/3.3.1/jquery.min.js\"></script> <script> <!-- here is the script code for performing the method --> $(document).ready(function() { $(\"span\").closest(\"ul\").css({ \"color\": \"green\", \"border\": \"2px solid green\" }); }); </script></head> <body class=\"main\"> This is great-great grand parent element ! <div style=\"width:600px;\"> This is great grand parent element ! <ul> This is the second ancestor element ! <ul> <!-- This element will be selected --> This is first ancestor element ! <li>This is direct parent ! <span>This is span the child element !</span> </li> </ul> </ul> </div></body> </html>",
"e": 42506,
"s": 41418,
"text": null
},
{
"code": null,
"e": 42584,
"s": 42506,
"text": "Output:Code #2:In the below code, optional parameter is passed to the method."
},
{
"code": "<html> <head> <style> .main * { display: block; border: 2px solid lightgrey; color: grey; padding: 5px; margin: 15px; } </style> <script src=\"https://ajax.googleapis.com/ajax/libs/ jquery/3.3.1/jquery.min.js\"></script> <script> $(document).ready(function() { <!--Here among dom id first ancestor will select --> var item = document.getElementById(\"dom\"); $(\"li\").closest(\"ul\", item).css({ \"color\": \"green\", \"border\": \"2px solid green\" }); }); </script></head> <body class=\"main\"> This is great-great-grandparent ! <div style=\"width:500px;\"> div (great-grandparent) <ul id=\"dom\"> This is second ancestor ! <ul id=\"dom\"> This is first ancestor ! <li>This is direct parent ! <span>This is span the child one !</span> </li> </ul> </ul> </div></body> </html>",
"e": 43644,
"s": 42584,
"text": null
},
{
"code": null,
"e": 43652,
"s": 43644,
"text": "Output:"
},
{
"code": null,
"e": 43920,
"s": 43652,
"text": "jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples."
},
{
"code": null,
"e": 43938,
"s": 43920,
"text": "jQuery-Traversing"
},
{
"code": null,
"e": 43949,
"s": 43938,
"text": "JavaScript"
},
{
"code": null,
"e": 43956,
"s": 43949,
"text": "JQuery"
},
{
"code": null,
"e": 44054,
"s": 43956,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 44099,
"s": 44054,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 44160,
"s": 44099,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 44229,
"s": 44160,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 44301,
"s": 44229,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 44353,
"s": 44301,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 44399,
"s": 44353,
"text": "JQuery | Set the value of an input text field"
},
{
"code": null,
"e": 44462,
"s": 44399,
"text": "How to change selected value of a drop-down list using jQuery?"
},
{
"code": null,
"e": 44491,
"s": 44462,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 44568,
"s": 44491,
"text": "How to change the background color after clicking the button in JavaScript ?"
}
] |
Knapsack with Duplicate Items | Practice | GeeksforGeeks
|
Given a set of N items, each with a weight and a value, represented by the array w[] and val[] respectively. Also, a knapsack with weight limit W.
The task is to fill the knapsack in such a way that we can get the maximum profit. Return the maximum profit.
Note: Each item can be taken any number of times.
Example 1:
Input: N = 2, W = 3
val[] = {1, 1}
wt[] = {2, 1}
Output: 3
Explanation:
1.Pick the 2nd element thrice.
2.Total profit = 1 + 1 + 1 = 3. Also the total
weight = 1 + 1 + 1 = 3 which is <= W.
Example 2:
Input: N = 4, W = 8
val[] = {1, 4, 5, 7}
wt[] = {1, 3, 4, 5}
Output: 11
Explanation: The optimal choice is to
pick the 2nd and 4th element.
Your Task:
You do not need to read input or print anything. Your task is to complete the function knapSack() which takes the values N, W and the arrays val[] and wt[] as input parameters and returns the maximum possible value.
Expected Time Complexity: O(N*W)
Expected Auxiliary Space: O(W)
Constraints:
1 ≤ N, W ≤ 1000
1 ≤ val[i], wt[i] ≤ 100
+1
adarshgupta4013 days ago
DP Java Code-
class Solution{
static int knapSack(int N, int W, int val[], int wt[])
{
//multiple occurences of an item allowed in sum
int [][] dp = new int[N+1][W+1];
for(int i = 0 ; i<W+1 ; i++) dp[0][i] = 0;
for(int i = 0 ; i<N+1 ; i++) dp[i][0] = 0;
for(int i=1 ; i<N+1 ; i++){
for(int j= 1; j<W+1 ; j++){
if(wt[i-1] <= j ){
dp[i][j] = Math.max(val[i-1]+dp[i][j-wt[i-1]] , // if it is taken in bag then can be taken again
dp[i-1][j] ); //if it is not taken then its processed , do not need to take it again.
} else{
dp[i][j] = dp[i-1][j];
}
}
}
return dp[N][W];
}
}
0
arghya2k011 week ago
int knapSack(int n, int w, int val[], int wt[])
{
vector<int>prev(w+1,0);
for(int i=0;i<=w;i++)prev[i]=(i/wt[0])*val[0];
for(int i=1;i<n;i++){
for(int j=1;j<=w;j++){
int notpick=prev[j];
int pick=0;
if(j>=wt[i])pick=val[i]+prev[j-wt[i]];
prev[j]=max(pick,notpick);
}
}
return prev[w];
}
0
annanyamathur1 week ago
int memo[1002][1002];
int knap(int n, int w, int val[], int wt[])
{
if(memo[n][w]==-1)
{
if(n==0 ||w==0)
memo[n][w]= 0;
else if(wt[n-1]<=w)
{
memo[n][w]= max(knap(n-1,w,val,wt),max(val[n-1]+knap(n,w-wt[n-1],val,wt),val[n-1]+
knap(n-1,w-wt[n-1],val,wt)));
}
else
{
memo[n][w]= knap(n-1,w,val,wt);
}
}
return memo[n][w];
}
int knapSack(int n, int w, int val[], int wt[])
{
memset(memo,-1,sizeof(memo));
return knap(n,w,val,wt);
}
+1
jainmuskan5652 weeks ago
int dp[1002][1002]; int solve(int N, int W, int val[], int wt[]){ // initialize for(int i=0;i<=N;i++){ for(int j=0;j<=W;j++){ if(i==0||j==0){ dp[i][j]=0; } } } for(int i=1;i<=N;i++){ for(int j=0;j<=W;j++){ if(wt[i-1]<=j){ dp[i][j]=max(val[i-1]+dp[i][j-wt[i-1]],dp[i-1][j]); } else{ dp[i][j]=dp[i-1][j]; } } } return dp[N][W]; } int knapSack(int N, int W, int val[], int wt[]) { memset(dp,-1,sizeof(dp)); return solve(N,W,val,wt); }
0
devashishbakare2 weeks ago
Java DP Tabulation
static int knapSack(int n, int cap, int val[], int wt[])
{
if(n == 0)
return 0;
//we have to solve smaller problem first
//so there ans should be stored one place hence this array created(Tabulation)
int dp[] = new int[cap+1];
dp[0] = 0;
//travers through capsity
for(int i = 1; i < cap+1; i++)
{
//max for getting maximum outcome from all weights
int max = 0;
//taking one weight at a time and geting the profit
for(int j = 0; j < wt.length; j++)
{
//cap should be greater than the weight
if(i >= wt[j])
{
//previosly possible max weight
int prevMax = dp[i-wt[j]];
//adding current weight
int currMax = val[j] + prevMax;
//if maximum then update
if(currMax > max)
max = currMax;
//as we are exploring all the weight hence declaring max above the for loop
}
}
dp[i] = max;
}//return final capacity
return dp[cap];
}
0
onlyprofessionalmails1 month ago
int knapSack(int N, int W, int val[], int wt[]) { int dp[N + 1][W + 1]; for(int i = 0 ;i < W + 1; i++){ dp[0][i] = 0; } for(int j = 0; j < N + 1; j++){ dp[j][0] = 0; } for(int i = 1; i < N + 1; i++){ for(int j = 1; j < W + 1; j++){ if(wt[i - 1] <= j){ dp[i][j] = max(val[i - 1] + dp[i][j - wt[i - 1]], dp[i - 1][j]); }else{ dp[i][j] = dp[i - 1][j]; } } } return dp[N][W]; }
0
ayushkumar54511 month ago
int knapSack(int N, int W, int val[], int wt[]) { for(int i=1;i<=N;i++){ for(int j=0;j<=W;j++){ if(i==0 or j==0) dp[i][j]=0; } } for(int i=1;i<N+1;i++){ for(int j=1;j<W+1;j++){ if(wt[i-1]<=j){ dp[i][j]=max(val[i-1]+dp[i][j-wt[i-1]],dp[i-1][j]); } else{ dp[i][j]=dp[i-1][j]; } } } return dp[N][W]; }
+4
debajyoti dev1 month ago
Question is common. But DP cant be consider as EASY ! no beginner can undestand DP funda. Thats why LeetCode level is reliable. not GFG.
0
sangamchoudhary72 months ago
class Solution{
public:
int dp[1001][1001];
int solve(int n,int w,int val[],int wt[]){
if(w >= 0 and n < 0) return 0;
else if(w < 0) return INT_MIN;
else if(dp[n][w] != -1) return dp[n][w];
int op1 = val[n] + solve(n-1,w-wt[n],val,wt);
int op2 = val[n] + solve(n,w-wt[n],val,wt);
int op3 = solve(n-1,w,val,wt);
int ans = max({op1,op2,op3});
return dp[n][w] = ans;
}
int knapSack(int N, int W, int val[], int wt[]){
memset(dp,-1,sizeof dp);
return solve(N-1,W,val,wt);
}
};
+2
mithileshkumarsingh2 months ago
int solve(int wt[], int val[], int w, int n)
{
//using top down approach
int dp[n + 1][w + 1];
for (int i = 0; i <= n; i++)
{
for (int j = 0; j <= w; j++)
{
if (i == 0 || j == 0)
dp[i][j] = 0;
else if (wt[i - 1] <= j)
dp[i][j] = max(val[i - 1] + dp[i][j - wt[i - 1]], dp[i - 1][j]);
else
dp[i][j] = dp[i - 1][j];
}
}
return dp[n][w];
}
int knapSack(int N, int W, int val[], int wt[]){
int ans=solve(wt,val,W,N);
return ans;
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 545,
"s": 238,
"text": "Given a set of N items, each with a weight and a value, represented by the array w[] and val[] respectively. Also, a knapsack with weight limit W.\nThe task is to fill the knapsack in such a way that we can get the maximum profit. Return the maximum profit.\nNote: Each item can be taken any number of times."
},
{
"code": null,
"e": 558,
"s": 547,
"text": "Example 1:"
},
{
"code": null,
"e": 752,
"s": 558,
"text": "Input: N = 2, W = 3\nval[] = {1, 1}\nwt[] = {2, 1}\nOutput: 3\nExplanation: \n1.Pick the 2nd element thrice.\n2.Total profit = 1 + 1 + 1 = 3. Also the total \n weight = 1 + 1 + 1 = 3 which is <= W.\n"
},
{
"code": null,
"e": 765,
"s": 754,
"text": "Example 2:"
},
{
"code": null,
"e": 906,
"s": 765,
"text": "Input: N = 4, W = 8\nval[] = {1, 4, 5, 7}\nwt[] = {1, 3, 4, 5}\nOutput: 11\nExplanation: The optimal choice is to \npick the 2nd and 4th element."
},
{
"code": null,
"e": 1135,
"s": 908,
"text": "Your Task:\nYou do not need to read input or print anything. Your task is to complete the function knapSack() which takes the values N, W and the arrays val[] and wt[] as input parameters and returns the maximum possible value."
},
{
"code": null,
"e": 1201,
"s": 1137,
"text": "Expected Time Complexity: O(N*W)\nExpected Auxiliary Space: O(W)"
},
{
"code": null,
"e": 1256,
"s": 1203,
"text": "Constraints:\n1 ≤ N, W ≤ 1000\n1 ≤ val[i], wt[i] ≤ 100"
},
{
"code": null,
"e": 1259,
"s": 1256,
"text": "+1"
},
{
"code": null,
"e": 1284,
"s": 1259,
"text": "adarshgupta4013 days ago"
},
{
"code": null,
"e": 1298,
"s": 1284,
"text": "DP Java Code-"
},
{
"code": null,
"e": 2086,
"s": 1298,
"text": "class Solution{\n static int knapSack(int N, int W, int val[], int wt[])\n {\n //multiple occurences of an item allowed in sum\n int [][] dp = new int[N+1][W+1];\n for(int i = 0 ; i<W+1 ; i++) dp[0][i] = 0;\n for(int i = 0 ; i<N+1 ; i++) dp[i][0] = 0;\n \n for(int i=1 ; i<N+1 ; i++){\n for(int j= 1; j<W+1 ; j++){\n if(wt[i-1] <= j ){\n dp[i][j] = Math.max(val[i-1]+dp[i][j-wt[i-1]] , // if it is taken in bag then can be taken again \n dp[i-1][j] ); //if it is not taken then its processed , do not need to take it again.\n } else{\n dp[i][j] = dp[i-1][j]; \n }\n }\n }\n return dp[N][W];\n \n }\n}"
},
{
"code": null,
"e": 2088,
"s": 2086,
"text": "0"
},
{
"code": null,
"e": 2109,
"s": 2088,
"text": "arghya2k011 week ago"
},
{
"code": null,
"e": 2434,
"s": 2109,
"text": "int knapSack(int n, int w, int val[], int wt[])\n {\n vector<int>prev(w+1,0);\n\tfor(int i=0;i<=w;i++)prev[i]=(i/wt[0])*val[0];\n\t\n\tfor(int i=1;i<n;i++){\n\t\tfor(int j=1;j<=w;j++){\n\t\t\tint notpick=prev[j];\n\t\t\tint pick=0;\n\t\t\tif(j>=wt[i])pick=val[i]+prev[j-wt[i]];\n\t\t\tprev[j]=max(pick,notpick);\n\t\t}\n\t}\n\treturn prev[w];\n }"
},
{
"code": null,
"e": 2436,
"s": 2434,
"text": "0"
},
{
"code": null,
"e": 2460,
"s": 2436,
"text": "annanyamathur1 week ago"
},
{
"code": null,
"e": 3075,
"s": 2460,
"text": "int memo[1002][1002];\n int knap(int n, int w, int val[], int wt[])\n {\n if(memo[n][w]==-1)\n {\n if(n==0 ||w==0)\n memo[n][w]= 0;\n else if(wt[n-1]<=w)\n {\n memo[n][w]= max(knap(n-1,w,val,wt),max(val[n-1]+knap(n,w-wt[n-1],val,wt),val[n-1]+\n knap(n-1,w-wt[n-1],val,wt)));\n }\n else\n {\n memo[n][w]= knap(n-1,w,val,wt);\n }\n \n }\n return memo[n][w];\n }\n int knapSack(int n, int w, int val[], int wt[])\n {\n memset(memo,-1,sizeof(memo));\n return knap(n,w,val,wt);\n \n }"
},
{
"code": null,
"e": 3078,
"s": 3075,
"text": "+1"
},
{
"code": null,
"e": 3103,
"s": 3078,
"text": "jainmuskan5652 weeks ago"
},
{
"code": null,
"e": 3786,
"s": 3103,
"text": "int dp[1002][1002]; int solve(int N, int W, int val[], int wt[]){ // initialize for(int i=0;i<=N;i++){ for(int j=0;j<=W;j++){ if(i==0||j==0){ dp[i][j]=0; } } } for(int i=1;i<=N;i++){ for(int j=0;j<=W;j++){ if(wt[i-1]<=j){ dp[i][j]=max(val[i-1]+dp[i][j-wt[i-1]],dp[i-1][j]); } else{ dp[i][j]=dp[i-1][j]; } } } return dp[N][W]; } int knapSack(int N, int W, int val[], int wt[]) { memset(dp,-1,sizeof(dp)); return solve(N,W,val,wt); }"
},
{
"code": null,
"e": 3788,
"s": 3786,
"text": "0"
},
{
"code": null,
"e": 3815,
"s": 3788,
"text": "devashishbakare2 weeks ago"
},
{
"code": null,
"e": 3834,
"s": 3815,
"text": "Java DP Tabulation"
},
{
"code": null,
"e": 5130,
"s": 3836,
"text": "static int knapSack(int n, int cap, int val[], int wt[])\n {\n if(n == 0)\n return 0;\n //we have to solve smaller problem first\n //so there ans should be stored one place hence this array created(Tabulation)\n int dp[] = new int[cap+1];\n \n dp[0] = 0;\n \n //travers through capsity\n for(int i = 1; i < cap+1; i++)\n {\n //max for getting maximum outcome from all weights\n int max = 0;\n //taking one weight at a time and geting the profit\n for(int j = 0; j < wt.length; j++)\n {\n //cap should be greater than the weight\n if(i >= wt[j])\n {\n //previosly possible max weight\n int prevMax = dp[i-wt[j]];\n //adding current weight\n int currMax = val[j] + prevMax;\n //if maximum then update\n if(currMax > max)\n max = currMax;\n \n //as we are exploring all the weight hence declaring max above the for loop\n }\n \n \n }\n dp[i] = max; \n }//return final capacity\n return dp[cap];\n }"
},
{
"code": null,
"e": 5132,
"s": 5130,
"text": "0"
},
{
"code": null,
"e": 5165,
"s": 5132,
"text": "onlyprofessionalmails1 month ago"
},
{
"code": null,
"e": 5709,
"s": 5165,
"text": "int knapSack(int N, int W, int val[], int wt[]) { int dp[N + 1][W + 1]; for(int i = 0 ;i < W + 1; i++){ dp[0][i] = 0; } for(int j = 0; j < N + 1; j++){ dp[j][0] = 0; } for(int i = 1; i < N + 1; i++){ for(int j = 1; j < W + 1; j++){ if(wt[i - 1] <= j){ dp[i][j] = max(val[i - 1] + dp[i][j - wt[i - 1]], dp[i - 1][j]); }else{ dp[i][j] = dp[i - 1][j]; } } } return dp[N][W]; }"
},
{
"code": null,
"e": 5711,
"s": 5709,
"text": "0"
},
{
"code": null,
"e": 5737,
"s": 5711,
"text": "ayushkumar54511 month ago"
},
{
"code": null,
"e": 6232,
"s": 5737,
"text": " int knapSack(int N, int W, int val[], int wt[]) { for(int i=1;i<=N;i++){ for(int j=0;j<=W;j++){ if(i==0 or j==0) dp[i][j]=0; } } for(int i=1;i<N+1;i++){ for(int j=1;j<W+1;j++){ if(wt[i-1]<=j){ dp[i][j]=max(val[i-1]+dp[i][j-wt[i-1]],dp[i-1][j]); } else{ dp[i][j]=dp[i-1][j]; } } } return dp[N][W]; }"
},
{
"code": null,
"e": 6235,
"s": 6232,
"text": "+4"
},
{
"code": null,
"e": 6260,
"s": 6235,
"text": "debajyoti dev1 month ago"
},
{
"code": null,
"e": 6398,
"s": 6260,
"text": "Question is common. But DP cant be consider as EASY ! no beginner can undestand DP funda. Thats why LeetCode level is reliable. not GFG."
},
{
"code": null,
"e": 6400,
"s": 6398,
"text": "0"
},
{
"code": null,
"e": 6429,
"s": 6400,
"text": "sangamchoudhary72 months ago"
},
{
"code": null,
"e": 7030,
"s": 6429,
"text": "class Solution{\npublic:\n int dp[1001][1001];\n int solve(int n,int w,int val[],int wt[]){\n if(w >= 0 and n < 0) return 0;\n else if(w < 0) return INT_MIN;\n else if(dp[n][w] != -1) return dp[n][w];\n \n int op1 = val[n] + solve(n-1,w-wt[n],val,wt);\n int op2 = val[n] + solve(n,w-wt[n],val,wt);\n int op3 = solve(n-1,w,val,wt);\n \n int ans = max({op1,op2,op3});\n \n return dp[n][w] = ans;\n }\n\n int knapSack(int N, int W, int val[], int wt[]){\n memset(dp,-1,sizeof dp);\n return solve(N-1,W,val,wt);\n }\n};"
},
{
"code": null,
"e": 7033,
"s": 7030,
"text": "+2"
},
{
"code": null,
"e": 7065,
"s": 7033,
"text": "mithileshkumarsingh2 months ago"
},
{
"code": null,
"e": 7650,
"s": 7065,
"text": "int solve(int wt[], int val[], int w, int n)\n{\n //using top down approach\n int dp[n + 1][w + 1];\n for (int i = 0; i <= n; i++)\n {\n for (int j = 0; j <= w; j++)\n {\n if (i == 0 || j == 0)\n dp[i][j] = 0;\n else if (wt[i - 1] <= j)\n dp[i][j] = max(val[i - 1] + dp[i][j - wt[i - 1]], dp[i - 1][j]);\n else\n dp[i][j] = dp[i - 1][j];\n }\n }\n return dp[n][w];\n}\n int knapSack(int N, int W, int val[], int wt[]){\n int ans=solve(wt,val,W,N);\n return ans;\n }"
},
{
"code": null,
"e": 7796,
"s": 7650,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 7832,
"s": 7796,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 7842,
"s": 7832,
"text": "\nProblem\n"
},
{
"code": null,
"e": 7852,
"s": 7842,
"text": "\nContest\n"
},
{
"code": null,
"e": 7915,
"s": 7852,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 8063,
"s": 7915,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 8271,
"s": 8063,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 8377,
"s": 8271,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Maximize length of subarray of equal elements by performing at most K increment operations - GeeksforGeeks
|
20 May, 2021
Given an array A[] consisting of N integers and an integer K, the task is to maximize the length of the subarray having equal elements after performing at most K increments by 1 on array elements.
Note: Same array element can be incremented more than once.
Examples:
Input: A[] = {2, 4, 8, 5, 9, 6}, K = 6Output: 3Explanation:Subarray [8, 5, 9] can be modified to [9, 9, 9].Total number of increments required is 5 which is less than K(= 6).
Input: A[] = {2, 2, 4}, K = 10Output: 3
Naive Approach: The simplest approach to solve the problem is to generate all possible subarrays and for each subarray, check if all its elements can be made equal in at most K increments. Print the maximum length of such subarrays obtained.
Time Complexity: O(N3) Auxiliary Space: O(1)
Approach: The above approach can be optimized using the Sliding Window technique. Follow the steps below to solve the problem:
Keep a track of the maximum element of the window.
The total operations required for a particular window is obtained by the following equation:
Count of operations = (Length of the window calculated so far + 1) * (Maximum element from the window) – Sum of the window
Now, check if the above-calculated value exceeds K or not. If so, then slide the starting pointer of the window towards the right, otherwise increment the length of the window calculated so far.
Repeat the above steps to obtain the longest window satisfying the required condition.
Below is the implementation of the above approach:
C++14
Java
Python3
C#
Javascript
// C++14 program for above approach#include <bits/stdc++.h>using namespace std;#define newl "\n" // Function to find the maximum length// of subarray of equal elements after// performing at most K incrementsint maxSubarray(int a[], int k, int n){ // Stores the size // of required subarray int answer = 0; // Starting point of a window int start = 0; // Stores the sum of window long int s = 0; deque<int> dq; // Iterate over array for(int i = 0; i < n; i++) { // Current element int x = a[i]; // Remove index of minimum elements // from deque which are less than // the current element while (!dq.empty() && a[dq.front()] <= x) dq.pop_front(); // Insert current index in deque dq.push_back(i); // Update current window sum s += x; // Calculate required operation to // make current window elements equal long int cost = (long int)a[dq.front()] * (answer + 1) - s; // If cost is less than k if (cost <= (long int)k) answer++; // Shift window start pointer towards // right and update current window sum else { if (dq.front() == start) dq.pop_front(); s -= a[start++]; } } // Return answer return answer;} // Driver Codeint main(){ int a[] = { 2, 2, 4 }; int k = 10; // Length of array int n = sizeof(a) / sizeof(a[0]); cout << (maxSubarray(a, k, n)); return 0;} // This code is contributed by jojo9911
// Java Program for above approachimport java.util.*; class GFG { // Function to find the maximum length // of subarray of equal elements after // performing at most K increments static int maxSubarray(int[] a, int k) { // Length of array int n = a.length; // Stores the size // of required subarray int answer = 0; // Starting point of a window int start = 0; // Stores the sum of window long s = 0; Deque<Integer> dq = new LinkedList<>(); // Iterate over array for (int i = 0; i < n; i++) { // Current element int x = a[i]; // Remove index of minimum elements // from deque which are less than // the current element while (!dq.isEmpty() && a[dq.peek()] <= x) dq.poll(); // Insert current index in deque dq.add(i); // Update current window sum s += x; // Calculate required operation to // make current window elements equal long cost = (long)a[dq.peekFirst()] * (answer + 1) - s; // If cost is less than k if (cost <= (long)k) answer++; // Shift window start pointer towards // right and update current window sum else { if (dq.peekFirst() == start) dq.pollFirst(); s -= a[start++]; } } // Return answer return answer; } // Driver Code public static void main(String[] args) { int[] a = { 2, 2, 4 }; int k = 10; // Function call System.out.println(maxSubarray(a, k)); }}
# Python3 program for above approachfrom collections import deque # Function to find the maximum length# of subarray of equal elements after# performing at most K incrementsdef maxSubarray(a, k): # Length of array n = len(a) # Stores the size # of required subarray answer = 0 # Starting po of a window start = 0 # Stores the sum of window s = 0 dq = deque() # Iterate over array for i in range(n): # Current element x = a[i] # Remove index of minimum elements # from deque which are less than # the current element while (len(dq) > 0 and a[dq[-1]] <= x): dq.popleft() # Insert current index in deque dq.append(i) # Update current window sum s += x # Calculate required operation to # make current window elements equal cost = a[dq[0]] * (answer + 1) - s # If cost is less than k if (cost <= k): answer += 1 # Shift window start pointer towards # right and update current window sum else: if (dq[0] == start): dq.popleft() s -= a[start] start += 1 # Return answer return answer # Driver Codeif __name__ == '__main__': a = [ 2, 2, 4 ] k = 10 # Function call print(maxSubarray(a, k)) # This code is contributed by mohit kumar 29
// C# Program for// the above approachusing System;using System.Collections.Generic;class GFG{ // Function to find the maximum length// of subarray of equal elements after// performing at most K incrementsstatic int maxSubarray(int[] a, int k){ // Length of array int n = a.Length; // Stores the size // of required subarray int answer = 0; // Starting point of a window int start = 0; // Stores the sum of window long s = 0; Queue<int> dq = new Queue<int>(); // Iterate over array for (int i = 0; i < n; i++) { // Current element int x = a[i]; // Remove index of minimum // elements from deque // which are less than // the current element while (dq.Count!=0 && a[dq.Peek()] <= x) dq.Dequeue(); // Insert current // index in deque dq.Enqueue(i); // Update current window sum s += x; // Calculate required operation to // make current window elements equal long cost = (long)a[dq.Peek()] * (answer + 1) - s; // If cost is less than k if (cost <= (long)k) answer++; // Shift window start pointer towards // right and update current window sum else { if (dq.Peek() == start) dq.Dequeue(); s -= a[start++]; } } // Return answer return answer;} // Driver Codepublic static void Main(String[] args){ int[] a = {2, 2, 4}; int k = 10; // Function call Console.WriteLine(maxSubarray(a, k));}} // This code is contributed by gauravrajput1
<script> // Javascript program for above approach // Function to find the maximum length// of subarray of equal elements after// performing at most K incrementsfunction maxSubarray(a, k, n){ // Stores the size // of required subarray var answer = 0; // Starting point of a window var start = 0; // Stores the sum of window var s = 0; var dq = []; // Iterate over array for(var i = 0; i < n; i++) { // Current element var x = a[i]; // Remove index of minimum elements // from deque which are less than // the current element while (dq.length!=0 && a[dq[0]] <= x) dq.shift(); // Insert current index in deque dq.push(i); // Update current window sum s += x; // Calculate required operation to // make current window elements equal var cost = a[dq[0]] * (answer + 1) - s; // If cost is less than k if (cost <= k) answer++; // Shift window start pointer towards // right and update current window sum else { if (dq[0] == start) dq.shift(); s -= a[start++]; } } // Return answer return answer;} // Driver Codevar a = [2, 2, 4];var k = 10; // Length of arrayvar n = a.length; document.write(maxSubarray(a, k, n)); </script>
3
Time Complexity: O(N)Auxiliary Space: O(N)
mohit kumar 29
jojo9911
GauravRajput1
surinderdawra388
importantly
deque
Google
sliding-window
subarray
Arrays
Mathematical
Queue
Searching
Google
sliding-window
Arrays
Searching
Mathematical
Queue
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Introduction to Arrays
Linear Search
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
|
[
{
"code": null,
"e": 25246,
"s": 25218,
"text": "\n20 May, 2021"
},
{
"code": null,
"e": 25443,
"s": 25246,
"text": "Given an array A[] consisting of N integers and an integer K, the task is to maximize the length of the subarray having equal elements after performing at most K increments by 1 on array elements."
},
{
"code": null,
"e": 25503,
"s": 25443,
"text": "Note: Same array element can be incremented more than once."
},
{
"code": null,
"e": 25513,
"s": 25503,
"text": "Examples:"
},
{
"code": null,
"e": 25688,
"s": 25513,
"text": "Input: A[] = {2, 4, 8, 5, 9, 6}, K = 6Output: 3Explanation:Subarray [8, 5, 9] can be modified to [9, 9, 9].Total number of increments required is 5 which is less than K(= 6)."
},
{
"code": null,
"e": 25728,
"s": 25688,
"text": "Input: A[] = {2, 2, 4}, K = 10Output: 3"
},
{
"code": null,
"e": 25971,
"s": 25728,
"text": "Naive Approach: The simplest approach to solve the problem is to generate all possible subarrays and for each subarray, check if all its elements can be made equal in at most K increments. Print the maximum length of such subarrays obtained. "
},
{
"code": null,
"e": 26016,
"s": 25971,
"text": "Time Complexity: O(N3) Auxiliary Space: O(1)"
},
{
"code": null,
"e": 26143,
"s": 26016,
"text": "Approach: The above approach can be optimized using the Sliding Window technique. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 26194,
"s": 26143,
"text": "Keep a track of the maximum element of the window."
},
{
"code": null,
"e": 26287,
"s": 26194,
"text": "The total operations required for a particular window is obtained by the following equation:"
},
{
"code": null,
"e": 26410,
"s": 26287,
"text": "Count of operations = (Length of the window calculated so far + 1) * (Maximum element from the window) – Sum of the window"
},
{
"code": null,
"e": 26605,
"s": 26410,
"text": "Now, check if the above-calculated value exceeds K or not. If so, then slide the starting pointer of the window towards the right, otherwise increment the length of the window calculated so far."
},
{
"code": null,
"e": 26692,
"s": 26605,
"text": "Repeat the above steps to obtain the longest window satisfying the required condition."
},
{
"code": null,
"e": 26743,
"s": 26692,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26749,
"s": 26743,
"text": "C++14"
},
{
"code": null,
"e": 26754,
"s": 26749,
"text": "Java"
},
{
"code": null,
"e": 26762,
"s": 26754,
"text": "Python3"
},
{
"code": null,
"e": 26765,
"s": 26762,
"text": "C#"
},
{
"code": null,
"e": 26776,
"s": 26765,
"text": "Javascript"
},
{
"code": "// C++14 program for above approach#include <bits/stdc++.h>using namespace std;#define newl \"\\n\" // Function to find the maximum length// of subarray of equal elements after// performing at most K incrementsint maxSubarray(int a[], int k, int n){ // Stores the size // of required subarray int answer = 0; // Starting point of a window int start = 0; // Stores the sum of window long int s = 0; deque<int> dq; // Iterate over array for(int i = 0; i < n; i++) { // Current element int x = a[i]; // Remove index of minimum elements // from deque which are less than // the current element while (!dq.empty() && a[dq.front()] <= x) dq.pop_front(); // Insert current index in deque dq.push_back(i); // Update current window sum s += x; // Calculate required operation to // make current window elements equal long int cost = (long int)a[dq.front()] * (answer + 1) - s; // If cost is less than k if (cost <= (long int)k) answer++; // Shift window start pointer towards // right and update current window sum else { if (dq.front() == start) dq.pop_front(); s -= a[start++]; } } // Return answer return answer;} // Driver Codeint main(){ int a[] = { 2, 2, 4 }; int k = 10; // Length of array int n = sizeof(a) / sizeof(a[0]); cout << (maxSubarray(a, k, n)); return 0;} // This code is contributed by jojo9911",
"e": 28431,
"s": 26776,
"text": null
},
{
"code": "// Java Program for above approachimport java.util.*; class GFG { // Function to find the maximum length // of subarray of equal elements after // performing at most K increments static int maxSubarray(int[] a, int k) { // Length of array int n = a.length; // Stores the size // of required subarray int answer = 0; // Starting point of a window int start = 0; // Stores the sum of window long s = 0; Deque<Integer> dq = new LinkedList<>(); // Iterate over array for (int i = 0; i < n; i++) { // Current element int x = a[i]; // Remove index of minimum elements // from deque which are less than // the current element while (!dq.isEmpty() && a[dq.peek()] <= x) dq.poll(); // Insert current index in deque dq.add(i); // Update current window sum s += x; // Calculate required operation to // make current window elements equal long cost = (long)a[dq.peekFirst()] * (answer + 1) - s; // If cost is less than k if (cost <= (long)k) answer++; // Shift window start pointer towards // right and update current window sum else { if (dq.peekFirst() == start) dq.pollFirst(); s -= a[start++]; } } // Return answer return answer; } // Driver Code public static void main(String[] args) { int[] a = { 2, 2, 4 }; int k = 10; // Function call System.out.println(maxSubarray(a, k)); }}",
"e": 30205,
"s": 28431,
"text": null
},
{
"code": "# Python3 program for above approachfrom collections import deque # Function to find the maximum length# of subarray of equal elements after# performing at most K incrementsdef maxSubarray(a, k): # Length of array n = len(a) # Stores the size # of required subarray answer = 0 # Starting po of a window start = 0 # Stores the sum of window s = 0 dq = deque() # Iterate over array for i in range(n): # Current element x = a[i] # Remove index of minimum elements # from deque which are less than # the current element while (len(dq) > 0 and a[dq[-1]] <= x): dq.popleft() # Insert current index in deque dq.append(i) # Update current window sum s += x # Calculate required operation to # make current window elements equal cost = a[dq[0]] * (answer + 1) - s # If cost is less than k if (cost <= k): answer += 1 # Shift window start pointer towards # right and update current window sum else: if (dq[0] == start): dq.popleft() s -= a[start] start += 1 # Return answer return answer # Driver Codeif __name__ == '__main__': a = [ 2, 2, 4 ] k = 10 # Function call print(maxSubarray(a, k)) # This code is contributed by mohit kumar 29",
"e": 31623,
"s": 30205,
"text": null
},
{
"code": "// C# Program for// the above approachusing System;using System.Collections.Generic;class GFG{ // Function to find the maximum length// of subarray of equal elements after// performing at most K incrementsstatic int maxSubarray(int[] a, int k){ // Length of array int n = a.Length; // Stores the size // of required subarray int answer = 0; // Starting point of a window int start = 0; // Stores the sum of window long s = 0; Queue<int> dq = new Queue<int>(); // Iterate over array for (int i = 0; i < n; i++) { // Current element int x = a[i]; // Remove index of minimum // elements from deque // which are less than // the current element while (dq.Count!=0 && a[dq.Peek()] <= x) dq.Dequeue(); // Insert current // index in deque dq.Enqueue(i); // Update current window sum s += x; // Calculate required operation to // make current window elements equal long cost = (long)a[dq.Peek()] * (answer + 1) - s; // If cost is less than k if (cost <= (long)k) answer++; // Shift window start pointer towards // right and update current window sum else { if (dq.Peek() == start) dq.Dequeue(); s -= a[start++]; } } // Return answer return answer;} // Driver Codepublic static void Main(String[] args){ int[] a = {2, 2, 4}; int k = 10; // Function call Console.WriteLine(maxSubarray(a, k));}} // This code is contributed by gauravrajput1",
"e": 33104,
"s": 31623,
"text": null
},
{
"code": "<script> // Javascript program for above approach // Function to find the maximum length// of subarray of equal elements after// performing at most K incrementsfunction maxSubarray(a, k, n){ // Stores the size // of required subarray var answer = 0; // Starting point of a window var start = 0; // Stores the sum of window var s = 0; var dq = []; // Iterate over array for(var i = 0; i < n; i++) { // Current element var x = a[i]; // Remove index of minimum elements // from deque which are less than // the current element while (dq.length!=0 && a[dq[0]] <= x) dq.shift(); // Insert current index in deque dq.push(i); // Update current window sum s += x; // Calculate required operation to // make current window elements equal var cost = a[dq[0]] * (answer + 1) - s; // If cost is less than k if (cost <= k) answer++; // Shift window start pointer towards // right and update current window sum else { if (dq[0] == start) dq.shift(); s -= a[start++]; } } // Return answer return answer;} // Driver Codevar a = [2, 2, 4];var k = 10; // Length of arrayvar n = a.length; document.write(maxSubarray(a, k, n)); </script>",
"e": 34543,
"s": 33104,
"text": null
},
{
"code": null,
"e": 34545,
"s": 34543,
"text": "3"
},
{
"code": null,
"e": 34588,
"s": 34545,
"text": "Time Complexity: O(N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 34603,
"s": 34588,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 34612,
"s": 34603,
"text": "jojo9911"
},
{
"code": null,
"e": 34626,
"s": 34612,
"text": "GauravRajput1"
},
{
"code": null,
"e": 34643,
"s": 34626,
"text": "surinderdawra388"
},
{
"code": null,
"e": 34655,
"s": 34643,
"text": "importantly"
},
{
"code": null,
"e": 34661,
"s": 34655,
"text": "deque"
},
{
"code": null,
"e": 34668,
"s": 34661,
"text": "Google"
},
{
"code": null,
"e": 34683,
"s": 34668,
"text": "sliding-window"
},
{
"code": null,
"e": 34692,
"s": 34683,
"text": "subarray"
},
{
"code": null,
"e": 34699,
"s": 34692,
"text": "Arrays"
},
{
"code": null,
"e": 34712,
"s": 34699,
"text": "Mathematical"
},
{
"code": null,
"e": 34718,
"s": 34712,
"text": "Queue"
},
{
"code": null,
"e": 34728,
"s": 34718,
"text": "Searching"
},
{
"code": null,
"e": 34735,
"s": 34728,
"text": "Google"
},
{
"code": null,
"e": 34750,
"s": 34735,
"text": "sliding-window"
},
{
"code": null,
"e": 34757,
"s": 34750,
"text": "Arrays"
},
{
"code": null,
"e": 34767,
"s": 34757,
"text": "Searching"
},
{
"code": null,
"e": 34780,
"s": 34767,
"text": "Mathematical"
},
{
"code": null,
"e": 34786,
"s": 34780,
"text": "Queue"
},
{
"code": null,
"e": 34884,
"s": 34786,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34932,
"s": 34884,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 34976,
"s": 34932,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 35008,
"s": 34976,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 35031,
"s": 35008,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 35045,
"s": 35031,
"text": "Linear Search"
},
{
"code": null,
"e": 35075,
"s": 35045,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 35135,
"s": 35075,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 35150,
"s": 35135,
"text": "C++ Data Types"
},
{
"code": null,
"e": 35193,
"s": 35150,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
comm command in Linux with examples - GeeksforGeeks
|
19 Feb, 2021
comm compare two sorted files line by line and write to standard output; the lines that are common and the lines that are unique.
Suppose you have two lists of people and you are asked to find out the names available in one and not in the other, or even those common to both. comm is the command that will help you to achieve this. It requires two sorted files which it compares line by line.Before discussing anything further first let’s check out the syntax of comm command:Syntax :
$comm [OPTION]... FILE1 FILE2
As using comm, we are trying to compare two files therefore the syntax of comm command needs two filenames as arguments.
With no OPTION used, comm produces three-column output where first column contains lines unique to FILE1 ,second column contains lines unique to FILE2 and third and last column contains lines common to both the files.
comm command only works right if you are comparing two files which are already sorted.Example: Let us suppose there are two sorted files file1.txt and file2.txt and now we will use comm command to compare these two.// displaying contents of file1 //
$cat file1.txt
Apaar
Ayush Rajput
Deepak
Hemant
// displaying contents of file2 //
$cat file2.txt
Apaar
Hemant
Lucky
Pranjal Thakral
Now, run comm command as:// using comm command for
comparing two files //
$comm file1.txt file2.txt
Apaar
Ayush Rajput
Deepak
Hemant
Lucky
Pranjal ThakralThe above output contains of three columns where first column is separated by zero tab and contains names only present in file1.txt ,second column contains names only present in file2.txt and separated by one tab and the third column contains names common to both the files and is separated by two tabs from the beginning of the line.This is the default pattern of the output produced by comm command when no option is used .Options for comm command:1. -1 :suppress first column(lines unique to first file).2. -2 :suppress second column(lines unique to second file).3. -3 :suppress third column(lines common to both files).4. – -check-order :check that the input is correctly sorted, even if all input lines are pairable.5. – -nocheck-order :do not check that the input is correctly sorted.6. – -output-delimiter=STR :separate columns with string STR7. – -help :display a help message, and exit.8. – -version :output version information, and exit.Note : The options 4 to 8 are rarely used but options 1 to 3 are very useful in terms of the desired output user wants.Using comm with options1. Using -1 ,-2 and -3 options : The use of these three options can be easily explained with the help of example ://suppress first column using -1//
$comm -1 file1.txt file2.txt
Apaar
Hemant
Lucky
Pranjal Thakral
//suppress second column using -2//
$comm -2 file1.txt file2.txt
Apaar
Ayush Rajput
Deepak
Hemant
//suppress third column using -3//
$comm -3 file1.txt file2.txt
Ayush Rajput
Deepak
Lucky
Pranjal Thakral
Note that you can also suppress multiple columns using these options together as://...suppressing multiple columns...//
$comm -12 file1.txt file2.txt
Apaar
Hemant
/* using -12 together suppressed both first
and second columns */
2. Using – -check-order option : This option is used to check whether the input files are sorted or not and in case if either of the two files are wrongly ordered then comm command will fail with an error message.$comm - -check-order f1.txt f2.txt
The above command produces the normal output if both f1.txt and f2.txt are sorted and it just gives an error message if either of the two files are not sorted.3. Using – -nocheck-order option : In case if you don’t want to check whether the input files are sorted or not, use this option. This can be explained with the help of an example.//displaying contents of unsorted f1.txt//
$cat f1.txt
Parnjal
Kartik
//displaying contents of sorted file f2.txt//
$cat f2.txt
Apaar
Kartik
//now use - -nocheck-order option with comm//
$comm - -nocheck-order f1.txt f2.txt
Pranjal
Apaar
Kartik
/*as this option forced comm not to check
the sorted order that's why the output
comm produced is also
not in sorted order*/4 . – -output-delimiter=STR option : By default, the columns in the comm command output are separated by spaces as explained above. However, if you want, you can change that, and have a string of your choice as separator. This can be done using the –output-delimiter option. This option requires you to specify the string that you want to use as the separator.Syntax:$comm - -output-delimiter=STR FILE1 FILE2EXAMPLE://...comm command with - -output-delimiter=STR option...//
$comm - -output-delimiter=+file1.txt file2.txt
++Apaar
Ayush Rajput
Deepak
++Hemant
+Lucky
+Pranjal Thakral
/*+ before content indicates content of
second column and ++ before content
indicates content of third column*/
So,that’s all about comm command and its options.YouTubeGeeksforGeeks502K subscribersLinux Tutorials | cmp, diff and comm commands | GeeksforGeeksInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch laterShareCopy linkWatch on0:000:001:22 / 5:36•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=0k6obEKGTyk" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>My Personal Notes
arrow_drop_upSave
Example: Let us suppose there are two sorted files file1.txt and file2.txt and now we will use comm command to compare these two.
// displaying contents of file1 //
$cat file1.txt
Apaar
Ayush Rajput
Deepak
Hemant
// displaying contents of file2 //
$cat file2.txt
Apaar
Hemant
Lucky
Pranjal Thakral
Now, run comm command as:
// using comm command for
comparing two files //
$comm file1.txt file2.txt
Apaar
Ayush Rajput
Deepak
Hemant
Lucky
Pranjal Thakral
The above output contains of three columns where first column is separated by zero tab and contains names only present in file1.txt ,second column contains names only present in file2.txt and separated by one tab and the third column contains names common to both the files and is separated by two tabs from the beginning of the line.This is the default pattern of the output produced by comm command when no option is used .
Options for comm command:
1. -1 :suppress first column(lines unique to first file).2. -2 :suppress second column(lines unique to second file).3. -3 :suppress third column(lines common to both files).4. – -check-order :check that the input is correctly sorted, even if all input lines are pairable.5. – -nocheck-order :do not check that the input is correctly sorted.6. – -output-delimiter=STR :separate columns with string STR7. – -help :display a help message, and exit.8. – -version :output version information, and exit.Note : The options 4 to 8 are rarely used but options 1 to 3 are very useful in terms of the desired output user wants.
Using comm with options
1. Using -1 ,-2 and -3 options : The use of these three options can be easily explained with the help of example :
//suppress first column using -1//
$comm -1 file1.txt file2.txt
Apaar
Hemant
Lucky
Pranjal Thakral
//suppress second column using -2//
$comm -2 file1.txt file2.txt
Apaar
Ayush Rajput
Deepak
Hemant
//suppress third column using -3//
$comm -3 file1.txt file2.txt
Ayush Rajput
Deepak
Lucky
Pranjal Thakral
Note that you can also suppress multiple columns using these options together as:
//...suppressing multiple columns...//
$comm -12 file1.txt file2.txt
Apaar
Hemant
/* using -12 together suppressed both first
and second columns */
2. Using – -check-order option : This option is used to check whether the input files are sorted or not and in case if either of the two files are wrongly ordered then comm command will fail with an error message.
$comm - -check-order f1.txt f2.txt
The above command produces the normal output if both f1.txt and f2.txt are sorted and it just gives an error message if either of the two files are not sorted.
3. Using – -nocheck-order option : In case if you don’t want to check whether the input files are sorted or not, use this option. This can be explained with the help of an example.
//displaying contents of unsorted f1.txt//
$cat f1.txt
Parnjal
Kartik
//displaying contents of sorted file f2.txt//
$cat f2.txt
Apaar
Kartik
//now use - -nocheck-order option with comm//
$comm - -nocheck-order f1.txt f2.txt
Pranjal
Apaar
Kartik
/*as this option forced comm not to check
the sorted order that's why the output
comm produced is also
not in sorted order*/
4 . – -output-delimiter=STR option : By default, the columns in the comm command output are separated by spaces as explained above. However, if you want, you can change that, and have a string of your choice as separator. This can be done using the –output-delimiter option. This option requires you to specify the string that you want to use as the separator.Syntax:
$comm - -output-delimiter=STR FILE1 FILE2
EXAMPLE:
//...comm command with - -output-delimiter=STR option...//
$comm - -output-delimiter=+file1.txt file2.txt
++Apaar
Ayush Rajput
Deepak
++Hemant
+Lucky
+Pranjal Thakral
/*+ before content indicates content of
second column and ++ before content
indicates content of third column*/
So,that’s all about comm command and its options.
YouTubeGeeksforGeeks502K subscribersLinux Tutorials | cmp, diff and comm commands | GeeksforGeeksInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch laterShareCopy linkWatch on0:000:001:22 / 5:36•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=0k6obEKGTyk" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
linux-command
Linux-text-processing-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
UDP Server-Client implementation in C
Conditional Statements | Shell Script
Cat command in Linux with examples
Tail command in Linux with examples
touch command in Linux with Examples
Mutex lock for Linux Thread Synchronization
echo command in Linux with Examples
tee command in Linux with examples
Compiling with g++
|
[
{
"code": null,
"e": 23958,
"s": 23930,
"text": "\n19 Feb, 2021"
},
{
"code": null,
"e": 24088,
"s": 23958,
"text": "comm compare two sorted files line by line and write to standard output; the lines that are common and the lines that are unique."
},
{
"code": null,
"e": 24443,
"s": 24088,
"text": "Suppose you have two lists of people and you are asked to find out the names available in one and not in the other, or even those common to both. comm is the command that will help you to achieve this. It requires two sorted files which it compares line by line.Before discussing anything further first let’s check out the syntax of comm command:Syntax :"
},
{
"code": null,
"e": 24474,
"s": 24443,
"text": "$comm [OPTION]... FILE1 FILE2\n"
},
{
"code": null,
"e": 24595,
"s": 24474,
"text": "As using comm, we are trying to compare two files therefore the syntax of comm command needs two filenames as arguments."
},
{
"code": null,
"e": 24813,
"s": 24595,
"text": "With no OPTION used, comm produces three-column output where first column contains lines unique to FILE1 ,second column contains lines unique to FILE2 and third and last column contains lines common to both the files."
},
{
"code": null,
"e": 29831,
"s": 24813,
"text": "comm command only works right if you are comparing two files which are already sorted.Example: Let us suppose there are two sorted files file1.txt and file2.txt and now we will use comm command to compare these two.// displaying contents of file1 //\n$cat file1.txt\nApaar \nAyush Rajput\nDeepak\nHemant\n\n// displaying contents of file2 //\n$cat file2.txt\nApaar\nHemant\nLucky\nPranjal Thakral\nNow, run comm command as:// using comm command for \ncomparing two files //\n$comm file1.txt file2.txt\n Apaar\nAyush Rajput\nDeepak\n Hemant\n Lucky\n Pranjal ThakralThe above output contains of three columns where first column is separated by zero tab and contains names only present in file1.txt ,second column contains names only present in file2.txt and separated by one tab and the third column contains names common to both the files and is separated by two tabs from the beginning of the line.This is the default pattern of the output produced by comm command when no option is used .Options for comm command:1. -1 :suppress first column(lines unique to first file).2. -2 :suppress second column(lines unique to second file).3. -3 :suppress third column(lines common to both files).4. – -check-order :check that the input is correctly sorted, even if all input lines are pairable.5. – -nocheck-order :do not check that the input is correctly sorted.6. – -output-delimiter=STR :separate columns with string STR7. – -help :display a help message, and exit.8. – -version :output version information, and exit.Note : The options 4 to 8 are rarely used but options 1 to 3 are very useful in terms of the desired output user wants.Using comm with options1. Using -1 ,-2 and -3 options : The use of these three options can be easily explained with the help of example ://suppress first column using -1//\n$comm -1 file1.txt file2.txt\n Apaar\n Hemant\n Lucky\n Pranjal Thakral\n\n//suppress second column using -2//\n$comm -2 file1.txt file2.txt\n Apaar\nAyush Rajput\nDeepak\n Hemant\n\n//suppress third column using -3//\n$comm -3 file1.txt file2.txt \nAyush Rajput\nDeepak \n Lucky\n Pranjal Thakral\nNote that you can also suppress multiple columns using these options together as://...suppressing multiple columns...//\n\n$comm -12 file1.txt file2.txt\nApaar\nHemant\n\n/* using -12 together suppressed both first\nand second columns */\n2. Using – -check-order option : This option is used to check whether the input files are sorted or not and in case if either of the two files are wrongly ordered then comm command will fail with an error message.$comm - -check-order f1.txt f2.txt\nThe above command produces the normal output if both f1.txt and f2.txt are sorted and it just gives an error message if either of the two files are not sorted.3. Using – -nocheck-order option : In case if you don’t want to check whether the input files are sorted or not, use this option. This can be explained with the help of an example.//displaying contents of unsorted f1.txt//\n\n$cat f1.txt\nParnjal \nKartik \n\n//displaying contents of sorted file f2.txt//\n\n$cat f2.txt\nApaar\nKartik\n\n//now use - -nocheck-order option with comm//\n\n$comm - -nocheck-order f1.txt f2.txt\nPranjal\n Apaar\n Kartik\n\n/*as this option forced comm not to check\n the sorted order that's why the output \ncomm produced is also \nnot in sorted order*/4 . – -output-delimiter=STR option : By default, the columns in the comm command output are separated by spaces as explained above. However, if you want, you can change that, and have a string of your choice as separator. This can be done using the –output-delimiter option. This option requires you to specify the string that you want to use as the separator.Syntax:$comm - -output-delimiter=STR FILE1 FILE2EXAMPLE://...comm command with - -output-delimiter=STR option...//\n\n$comm - -output-delimiter=+file1.txt file2.txt\n++Apaar\nAyush Rajput\nDeepak\n++Hemant\n+Lucky\n+Pranjal Thakral\n\n/*+ before content indicates content of \nsecond column and ++ before content \nindicates content of third column*/ \nSo,that’s all about comm command and its options.YouTubeGeeksforGeeks502K subscribersLinux Tutorials | cmp, diff and comm commands | GeeksforGeeksInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch laterShareCopy linkWatch on0:000:001:22 / 5:36•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=0k6obEKGTyk\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 29961,
"s": 29831,
"text": "Example: Let us suppose there are two sorted files file1.txt and file2.txt and now we will use comm command to compare these two."
},
{
"code": null,
"e": 30132,
"s": 29961,
"text": "// displaying contents of file1 //\n$cat file1.txt\nApaar \nAyush Rajput\nDeepak\nHemant\n\n// displaying contents of file2 //\n$cat file2.txt\nApaar\nHemant\nLucky\nPranjal Thakral\n"
},
{
"code": null,
"e": 30158,
"s": 30132,
"text": "Now, run comm command as:"
},
{
"code": null,
"e": 30337,
"s": 30158,
"text": "// using comm command for \ncomparing two files //\n$comm file1.txt file2.txt\n Apaar\nAyush Rajput\nDeepak\n Hemant\n Lucky\n Pranjal Thakral"
},
{
"code": null,
"e": 30763,
"s": 30337,
"text": "The above output contains of three columns where first column is separated by zero tab and contains names only present in file1.txt ,second column contains names only present in file2.txt and separated by one tab and the third column contains names common to both the files and is separated by two tabs from the beginning of the line.This is the default pattern of the output produced by comm command when no option is used ."
},
{
"code": null,
"e": 30789,
"s": 30763,
"text": "Options for comm command:"
},
{
"code": null,
"e": 31406,
"s": 30789,
"text": "1. -1 :suppress first column(lines unique to first file).2. -2 :suppress second column(lines unique to second file).3. -3 :suppress third column(lines common to both files).4. – -check-order :check that the input is correctly sorted, even if all input lines are pairable.5. – -nocheck-order :do not check that the input is correctly sorted.6. – -output-delimiter=STR :separate columns with string STR7. – -help :display a help message, and exit.8. – -version :output version information, and exit.Note : The options 4 to 8 are rarely used but options 1 to 3 are very useful in terms of the desired output user wants."
},
{
"code": null,
"e": 31430,
"s": 31406,
"text": "Using comm with options"
},
{
"code": null,
"e": 31545,
"s": 31430,
"text": "1. Using -1 ,-2 and -3 options : The use of these three options can be easily explained with the help of example :"
},
{
"code": null,
"e": 31923,
"s": 31545,
"text": "//suppress first column using -1//\n$comm -1 file1.txt file2.txt\n Apaar\n Hemant\n Lucky\n Pranjal Thakral\n\n//suppress second column using -2//\n$comm -2 file1.txt file2.txt\n Apaar\nAyush Rajput\nDeepak\n Hemant\n\n//suppress third column using -3//\n$comm -3 file1.txt file2.txt \nAyush Rajput\nDeepak \n Lucky\n Pranjal Thakral\n"
},
{
"code": null,
"e": 32005,
"s": 31923,
"text": "Note that you can also suppress multiple columns using these options together as:"
},
{
"code": null,
"e": 32156,
"s": 32005,
"text": "//...suppressing multiple columns...//\n\n$comm -12 file1.txt file2.txt\nApaar\nHemant\n\n/* using -12 together suppressed both first\nand second columns */\n"
},
{
"code": null,
"e": 32370,
"s": 32156,
"text": "2. Using – -check-order option : This option is used to check whether the input files are sorted or not and in case if either of the two files are wrongly ordered then comm command will fail with an error message."
},
{
"code": null,
"e": 32406,
"s": 32370,
"text": "$comm - -check-order f1.txt f2.txt\n"
},
{
"code": null,
"e": 32566,
"s": 32406,
"text": "The above command produces the normal output if both f1.txt and f2.txt are sorted and it just gives an error message if either of the two files are not sorted."
},
{
"code": null,
"e": 32747,
"s": 32566,
"text": "3. Using – -nocheck-order option : In case if you don’t want to check whether the input files are sorted or not, use this option. This can be explained with the help of an example."
},
{
"code": null,
"e": 33152,
"s": 32747,
"text": "//displaying contents of unsorted f1.txt//\n\n$cat f1.txt\nParnjal \nKartik \n\n//displaying contents of sorted file f2.txt//\n\n$cat f2.txt\nApaar\nKartik\n\n//now use - -nocheck-order option with comm//\n\n$comm - -nocheck-order f1.txt f2.txt\nPranjal\n Apaar\n Kartik\n\n/*as this option forced comm not to check\n the sorted order that's why the output \ncomm produced is also \nnot in sorted order*/"
},
{
"code": null,
"e": 33520,
"s": 33152,
"text": "4 . – -output-delimiter=STR option : By default, the columns in the comm command output are separated by spaces as explained above. However, if you want, you can change that, and have a string of your choice as separator. This can be done using the –output-delimiter option. This option requires you to specify the string that you want to use as the separator.Syntax:"
},
{
"code": null,
"e": 33562,
"s": 33520,
"text": "$comm - -output-delimiter=STR FILE1 FILE2"
},
{
"code": null,
"e": 33571,
"s": 33562,
"text": "EXAMPLE:"
},
{
"code": null,
"e": 33856,
"s": 33571,
"text": "//...comm command with - -output-delimiter=STR option...//\n\n$comm - -output-delimiter=+file1.txt file2.txt\n++Apaar\nAyush Rajput\nDeepak\n++Hemant\n+Lucky\n+Pranjal Thakral\n\n/*+ before content indicates content of \nsecond column and ++ before content \nindicates content of third column*/ \n"
},
{
"code": null,
"e": 33906,
"s": 33856,
"text": "So,that’s all about comm command and its options."
},
{
"code": null,
"e": 34750,
"s": 33906,
"text": "YouTubeGeeksforGeeks502K subscribersLinux Tutorials | cmp, diff and comm commands | GeeksforGeeksInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch laterShareCopy linkWatch on0:000:001:22 / 5:36•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=0k6obEKGTyk\" 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": 34764,
"s": 34750,
"text": "linux-command"
},
{
"code": null,
"e": 34795,
"s": 34764,
"text": "Linux-text-processing-commands"
},
{
"code": null,
"e": 34806,
"s": 34795,
"text": "Linux-Unix"
},
{
"code": null,
"e": 34904,
"s": 34806,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34939,
"s": 34904,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 34977,
"s": 34939,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 35015,
"s": 34977,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 35050,
"s": 35015,
"text": "Cat command in Linux with examples"
},
{
"code": null,
"e": 35086,
"s": 35050,
"text": "Tail command in Linux with examples"
},
{
"code": null,
"e": 35123,
"s": 35086,
"text": "touch command in Linux with Examples"
},
{
"code": null,
"e": 35167,
"s": 35123,
"text": "Mutex lock for Linux Thread Synchronization"
},
{
"code": null,
"e": 35203,
"s": 35167,
"text": "echo command in Linux with Examples"
},
{
"code": null,
"e": 35238,
"s": 35203,
"text": "tee command in Linux with examples"
}
] |
Inventory Management for Retail — Deterministic Demand | by Samir Saci | Towards Data Science
|
For most retailers, inventory management systems take a fixed, rule-based approach to forecast and replenishment orders management.
Considering the distribution of the demand, the objective is to build a replenishment policy that will minimize your ordering, holding and shortage costs.
Ordering Costs: fixed cost to place an order due to administrative costs, system maintenance or manufacturing costs in (Euros/Order)
Holding Costs: all the costs required to hold your inventory (storage, insurance, and capital costs) in (Euros/unit x time)
Shortage/Stock-out Costs: the costs of not having enough inventory to meet the customer demand (Lost Sales, Penalty) in (Euros/Unit)
In this article, we will present a simple methodology using a discrete simulation model built with Python to test several inventory management rules based assuming:
Deterministic Constant Demand: D (Units/Year)
Lead Time between ordering and replenishment (Days)
Cost of shortage and storage (Euros/Unit)
SUMMARYI. ScenarioProblem StatementAs an Inventory Manager of a mid-size retail chain, you are in charge of setting the replenishment quantity in the ERP.ObjectiveII. Build your ModelEconomic Order Quantity (EOQ)What is the best compromise between ordering and holding costs?1. Visualize the current rule2. Economic Order Quantity: Q = Q*3. Include replenishment lead time4. Real-Time visualization of Cost of Goods Sold (COGS)III. Conclusion & Next Steps
As an Inventory Manager of a mid-size retail chain, you are in charge of setting the replenishment quantity in the ERP.
Based on the feedback of the store manager, you start to doubt that the replenishment rules of the ERP are the most optimal especially for the fast runners because your stores are facing lost sales due to stock-outs.
For each SKU, you would like to build a simple simulation model to test several inventory rules and estimate the impact on:
Total Costs: how much does it cost to receive, store and sells this product?
Shortages: what is the % of lost sales due to stock-out?
In this article, we will build this model for,
# Total Demand (units/year)D = 2000# Number of days of sales per year (days)T_total = 365# Customer demand per day (unit/day)D_day = D/T_total# Purchase cost of the product (Euros/unit)c = 50# Cost of placing an order (/order)c_t = 500# Holding Cost (% unit cost per year)h = .25c_e = h * c# Selling Price (Euros/unit)p = 75# Lead Time between ordering and receivingLD# Cost of shortage (Euros/unit)c_s = 12
To simplify the comprehension, let’s introduce some notations
In this article, we will
Visualize the current rule used by the store's managerCalculate the Economic Order Quantity and simulate the impactVisualize the impact of lead time between ordering and receivingReal-Time Visualization of COGS for each rule
Visualize the current rule used by the store's manager
Calculate the Economic Order Quantity and simulate the impact
Visualize the impact of lead time between ordering and receiving
Real-Time Visualization of COGS for each rule
You can find the full code in this Github repository: Link.My portfolio with other projects: Samir Saci
The theory behind the Economic Order Quantity (EOQ) that is used by many Inventory Optimization models is to find the optimal order quantity Q* that will be the best compromise between ordering costs and holding costs.
A low order quantity will give you high ordering costs (increase the number of replenishment orders: D/Q) but will reduce your holding cost (reduce the average inventory level: (Q/2))
The inverse for a high order quantity
Comments
In the chart above we can see that the Total Relevant Cost (TRC) (total cost without the purchase cost cD) is minimum for Q*=400 units/order.
TRC(Q*) = 5,000 Euros
The current rule is to order every 10 days the exact quantity needed to absorb the demand for 10 days.
This quantity is way lower than Q*, we can easily understand that the TRC will be way higher than its optimal value:
TRC(10) = 100,062 Euros
To understand why let’s simulate the rule for a range of 365 days:
CommentsVery short replenishment cycles that multiply the number of replenishment orders.
For each replenishment cycle, you order Q* = 400 orders and you reorder when the inventory level is zero.
CommentsLonger replenishment cycles that reduce the number of orders by 7 times => lower TRC
samirsaci.com
What would be the stock-out level if we have a replenishment lead time LD = N Days?
CommentsWith 25 days lead time between ordering and receiving we reach 140 units of stock-out quantity per replenishment cycle.
If you want to convince your commercial team and the store managers; you need to speak their languages.
You can prepare a simple visualization of the potential turnover with the COGS (here we’ll exclude purchase costs COGS = TRC) to understand the impacts along the year.
Initial Rule
CommentsCOGS is mainly driven by the ordering costs because of the high frequency of reordering due to the low replenishment quantity.
EOQ Rule
CommentsWe see here that the Economic Order Quantity is providing a compromise between ordering costs and holding costs that drastically reduce the total COGS.
This simple modelisation was the occasion to design a basic simulation model that shows the impact of customer demand and inventory rules on key performance metrics.
It gives you visibility on your ordering frequency, inventory level and the impacts of lead times in your supply chain.
The initial assumption of constant deterministic demand is very optimistic. In the next article, we’ll study the impact of the variability of the demand on the total relevant costs and the lost sales.
www.samirsaci.com
Have a look at my blog: https://samirsaci.com
[1] Supply Chain Science, Wallace J. Hopp
|
[
{
"code": null,
"e": 303,
"s": 171,
"text": "For most retailers, inventory management systems take a fixed, rule-based approach to forecast and replenishment orders management."
},
{
"code": null,
"e": 458,
"s": 303,
"text": "Considering the distribution of the demand, the objective is to build a replenishment policy that will minimize your ordering, holding and shortage costs."
},
{
"code": null,
"e": 591,
"s": 458,
"text": "Ordering Costs: fixed cost to place an order due to administrative costs, system maintenance or manufacturing costs in (Euros/Order)"
},
{
"code": null,
"e": 715,
"s": 591,
"text": "Holding Costs: all the costs required to hold your inventory (storage, insurance, and capital costs) in (Euros/unit x time)"
},
{
"code": null,
"e": 848,
"s": 715,
"text": "Shortage/Stock-out Costs: the costs of not having enough inventory to meet the customer demand (Lost Sales, Penalty) in (Euros/Unit)"
},
{
"code": null,
"e": 1013,
"s": 848,
"text": "In this article, we will present a simple methodology using a discrete simulation model built with Python to test several inventory management rules based assuming:"
},
{
"code": null,
"e": 1059,
"s": 1013,
"text": "Deterministic Constant Demand: D (Units/Year)"
},
{
"code": null,
"e": 1111,
"s": 1059,
"text": "Lead Time between ordering and replenishment (Days)"
},
{
"code": null,
"e": 1153,
"s": 1111,
"text": "Cost of shortage and storage (Euros/Unit)"
},
{
"code": null,
"e": 1609,
"s": 1153,
"text": "SUMMARYI. ScenarioProblem StatementAs an Inventory Manager of a mid-size retail chain, you are in charge of setting the replenishment quantity in the ERP.ObjectiveII. Build your ModelEconomic Order Quantity (EOQ)What is the best compromise between ordering and holding costs?1. Visualize the current rule2. Economic Order Quantity: Q = Q*3. Include replenishment lead time4. Real-Time visualization of Cost of Goods Sold (COGS)III. Conclusion & Next Steps"
},
{
"code": null,
"e": 1729,
"s": 1609,
"text": "As an Inventory Manager of a mid-size retail chain, you are in charge of setting the replenishment quantity in the ERP."
},
{
"code": null,
"e": 1946,
"s": 1729,
"text": "Based on the feedback of the store manager, you start to doubt that the replenishment rules of the ERP are the most optimal especially for the fast runners because your stores are facing lost sales due to stock-outs."
},
{
"code": null,
"e": 2070,
"s": 1946,
"text": "For each SKU, you would like to build a simple simulation model to test several inventory rules and estimate the impact on:"
},
{
"code": null,
"e": 2147,
"s": 2070,
"text": "Total Costs: how much does it cost to receive, store and sells this product?"
},
{
"code": null,
"e": 2204,
"s": 2147,
"text": "Shortages: what is the % of lost sales due to stock-out?"
},
{
"code": null,
"e": 2251,
"s": 2204,
"text": "In this article, we will build this model for,"
},
{
"code": null,
"e": 2659,
"s": 2251,
"text": "# Total Demand (units/year)D = 2000# Number of days of sales per year (days)T_total = 365# Customer demand per day (unit/day)D_day = D/T_total# Purchase cost of the product (Euros/unit)c = 50# Cost of placing an order (/order)c_t = 500# Holding Cost (% unit cost per year)h = .25c_e = h * c# Selling Price (Euros/unit)p = 75# Lead Time between ordering and receivingLD# Cost of shortage (Euros/unit)c_s = 12"
},
{
"code": null,
"e": 2721,
"s": 2659,
"text": "To simplify the comprehension, let’s introduce some notations"
},
{
"code": null,
"e": 2746,
"s": 2721,
"text": "In this article, we will"
},
{
"code": null,
"e": 2971,
"s": 2746,
"text": "Visualize the current rule used by the store's managerCalculate the Economic Order Quantity and simulate the impactVisualize the impact of lead time between ordering and receivingReal-Time Visualization of COGS for each rule"
},
{
"code": null,
"e": 3026,
"s": 2971,
"text": "Visualize the current rule used by the store's manager"
},
{
"code": null,
"e": 3088,
"s": 3026,
"text": "Calculate the Economic Order Quantity and simulate the impact"
},
{
"code": null,
"e": 3153,
"s": 3088,
"text": "Visualize the impact of lead time between ordering and receiving"
},
{
"code": null,
"e": 3199,
"s": 3153,
"text": "Real-Time Visualization of COGS for each rule"
},
{
"code": null,
"e": 3303,
"s": 3199,
"text": "You can find the full code in this Github repository: Link.My portfolio with other projects: Samir Saci"
},
{
"code": null,
"e": 3522,
"s": 3303,
"text": "The theory behind the Economic Order Quantity (EOQ) that is used by many Inventory Optimization models is to find the optimal order quantity Q* that will be the best compromise between ordering costs and holding costs."
},
{
"code": null,
"e": 3706,
"s": 3522,
"text": "A low order quantity will give you high ordering costs (increase the number of replenishment orders: D/Q) but will reduce your holding cost (reduce the average inventory level: (Q/2))"
},
{
"code": null,
"e": 3744,
"s": 3706,
"text": "The inverse for a high order quantity"
},
{
"code": null,
"e": 3753,
"s": 3744,
"text": "Comments"
},
{
"code": null,
"e": 3895,
"s": 3753,
"text": "In the chart above we can see that the Total Relevant Cost (TRC) (total cost without the purchase cost cD) is minimum for Q*=400 units/order."
},
{
"code": null,
"e": 3917,
"s": 3895,
"text": "TRC(Q*) = 5,000 Euros"
},
{
"code": null,
"e": 4020,
"s": 3917,
"text": "The current rule is to order every 10 days the exact quantity needed to absorb the demand for 10 days."
},
{
"code": null,
"e": 4137,
"s": 4020,
"text": "This quantity is way lower than Q*, we can easily understand that the TRC will be way higher than its optimal value:"
},
{
"code": null,
"e": 4161,
"s": 4137,
"text": "TRC(10) = 100,062 Euros"
},
{
"code": null,
"e": 4228,
"s": 4161,
"text": "To understand why let’s simulate the rule for a range of 365 days:"
},
{
"code": null,
"e": 4318,
"s": 4228,
"text": "CommentsVery short replenishment cycles that multiply the number of replenishment orders."
},
{
"code": null,
"e": 4424,
"s": 4318,
"text": "For each replenishment cycle, you order Q* = 400 orders and you reorder when the inventory level is zero."
},
{
"code": null,
"e": 4517,
"s": 4424,
"text": "CommentsLonger replenishment cycles that reduce the number of orders by 7 times => lower TRC"
},
{
"code": null,
"e": 4531,
"s": 4517,
"text": "samirsaci.com"
},
{
"code": null,
"e": 4615,
"s": 4531,
"text": "What would be the stock-out level if we have a replenishment lead time LD = N Days?"
},
{
"code": null,
"e": 4743,
"s": 4615,
"text": "CommentsWith 25 days lead time between ordering and receiving we reach 140 units of stock-out quantity per replenishment cycle."
},
{
"code": null,
"e": 4847,
"s": 4743,
"text": "If you want to convince your commercial team and the store managers; you need to speak their languages."
},
{
"code": null,
"e": 5015,
"s": 4847,
"text": "You can prepare a simple visualization of the potential turnover with the COGS (here we’ll exclude purchase costs COGS = TRC) to understand the impacts along the year."
},
{
"code": null,
"e": 5028,
"s": 5015,
"text": "Initial Rule"
},
{
"code": null,
"e": 5163,
"s": 5028,
"text": "CommentsCOGS is mainly driven by the ordering costs because of the high frequency of reordering due to the low replenishment quantity."
},
{
"code": null,
"e": 5172,
"s": 5163,
"text": "EOQ Rule"
},
{
"code": null,
"e": 5332,
"s": 5172,
"text": "CommentsWe see here that the Economic Order Quantity is providing a compromise between ordering costs and holding costs that drastically reduce the total COGS."
},
{
"code": null,
"e": 5498,
"s": 5332,
"text": "This simple modelisation was the occasion to design a basic simulation model that shows the impact of customer demand and inventory rules on key performance metrics."
},
{
"code": null,
"e": 5618,
"s": 5498,
"text": "It gives you visibility on your ordering frequency, inventory level and the impacts of lead times in your supply chain."
},
{
"code": null,
"e": 5819,
"s": 5618,
"text": "The initial assumption of constant deterministic demand is very optimistic. In the next article, we’ll study the impact of the variability of the demand on the total relevant costs and the lost sales."
},
{
"code": null,
"e": 5837,
"s": 5819,
"text": "www.samirsaci.com"
},
{
"code": null,
"e": 5883,
"s": 5837,
"text": "Have a look at my blog: https://samirsaci.com"
}
] |
Spring Boot DataRest Example @RepositoryRestResource
|
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In this tutorial, we are going to see an essential crud operation on Spring Boot DataRest Example.
Spring Boot DataRest build on top of the Spring Data, and it’s taking the advantages of Spring HATEOAS. We can say that Spring Boot Data Rest combines the Spring Data and Spring HATEOS to provide the hypermedia-based Restful front end.
Spring Boot 2.1.4 RELEASE
Spring Boot Data JPA
Spring Boot DataRest
Lombok
MySQL connector
Java 8
Maven
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
As part of this example, we are going to implement a simple crud operation using spring datarest – here the data persisted in MySQL database.
We are configuring MySQL properties.
spring.datasource.driver-class-name:com.mysql.jdbc.Driver
spring.datasource.url:jdbc:mysql://localhost:3306/otp
spring.datasource.username:root
spring.datasource.password:1234
spring.jpa.show-sql=true
spring.jpa.generate-ddl=false
spring.jooq.sql-dialect=org.hibernate.dialect.MySQL5Dialect
We are preparing Item domain object – representing an item table in the database.
package com.onlinetutorialspoint.domain;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
@Data
@NoArgsConstructor
public class Item {
@Id
@GeneratedValue
private long id;
private String name;
private String category;
}
On the above Item class, we have used @Data and @NoArgsConstructor annotations to eliminate the boilerplate code like getters and setters, for more details on Lombok you can see this document.
The ItemRepository interface allows you to perform various CRUD operations on Item object. This repository gets CRUD operations from the PagingAndSortingRepository – it internally uses Spring Data Commons.
Apart from the basic CRUD operations, if we wanted to expose any domain related operations, you can always free to define your custom JPA operations or even use any JPQL operations inside the ItemRepository like below findByCategory().
package com.onlinetutorialspoint.repo;
import com.onlinetutorialspoint.domain.Item;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import java.util.List;
@RepositoryRestResource(path="items",collectionResourceRel = "items")
public interface ItemRepository extends PagingAndSortingRepository<Item,Long> {
List<Item> findByCategory(@Param("category") String category);
}
@RepositoryRestResource creates HATEOAS service with Spring JPA and the operations will be exposed in HATEOAS format.
package com.onlinetutorialspoint;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootDataRestExampleApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootDataRestExampleApplication.class, args);
}
}
$ mvn clean install
$ mvn spring-boot:run
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.4.RELEASE)
2019-05-05 13:44:12.317 INFO 556 --- [ restartedMain] c.o.SpringBootDataRestExampleApplication : Starting SpringBootDataRestExampleApplication on DESKTOP-RN4SMHT with PID 556 (D:\work\SpringBoot-DataRest-Example\target\classes started by Lenovo in D:\work\SpringBoot-DataRest-Example)
2019-05-05 13:44:12.323 INFO 556 --- [ restartedMain] c.o.SpringBootDataRestExampleApplication : No active profile set, falling back to default profiles: default
2019-05-05 13:44:12.491 INFO 556 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2019-05-05 13:44:12.491 INFO 556 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2019-05-05 13:44:16.069 INFO 556 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-05-05 13:44:16.218 INFO 556 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 126ms. Found 1 repository interfaces.
2019-05-05 13:44:17.287 INFO 556 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$3afa984d] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-05-05 13:44:17.346 INFO 556 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.hateoas.config.HateoasConfiguration' of type [org.springframework.hateoas.config.HateoasConfiguration$$EnhancerBySpringCGLIB$$ba7ae57f] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-05-05 13:44:18.873 INFO 556 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2019-05-05 13:44:18.968 INFO 556 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2019-05-05 13:44:18.968 INFO 556 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.17]
2019-05-05 13:44:19.275 INFO 556 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2019-05-05 13:44:19.276 INFO 556 --- [ restartedMain] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 6784 ms
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
2019-05-05 13:44:19.969 INFO 556 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2019-05-05 13:44:19.976 WARN 556 --- [ restartedMain] com.zaxxer.hikari.util.DriverDataSource : Registered driver with driverClassName=com.mysql.jdbc.Driver was not found, trying direct instantiation.
2019-05-05 13:44:20.766 INFO 556 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2019-05-05 13:44:21.126 INFO 556 --- [ restartedMain] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
......
......
After running the application, go to http://localhost:8080/ then you would see the following JSON structure.
You can observe, there were two endpoints available /items with three different options (page, size, sort) and /profile which provides the application metadata.
Currently, there are no items in our database, let’s create some of them.
Now you can access all the available items using the http://localhost:8080/items/ endpoint.
{
"_embedded": {
"items": [
{
"name": "Thinking in Java",
"category": "Books",
"_links": {
"self": {
"href": "http://localhost:8080/items/1"
},
"item": {
"href": "http://localhost:8080/items/1"
}
}
},
{
"name": "Hibernate in Action",
"category": "Books",
"_links": {
"self": {
"href": "http://localhost:8080/items/2"
},
"item": {
"href": "http://localhost:8080/items/2"
}
}
}
]
},
"_links": {
"self": {
"href": "http://localhost:8080/items{?page,size,sort}",
"templated": true
},
"profile": {
"href": "http://localhost:8080/profile/items"
},
"search": {
"href": "http://localhost:8080/items/search"
}
},
"page": {
"size": 20,
"totalElements": 2,
"totalPages": 1,
"number": 0
}
}
On the above output, we can observe that, along with the items list, there is one more /search endpoint available. It is used to call the custom endpoints. Let’s try to access our custom endpoint getItemByCategory();
http://localhost:8080/items/search/findByCategory?category=Books
Done!
Spring Data Rest Document
Spring Boot Data JPA
Happy Learning 🙂
Spring Boot How to change the Tomcat to Jetty Server
Spring Boot Kafka Producer Example
Spring Boot RabbitMQ Message Publishing Example
Spring Boot JdbcTemplate CRUD Operations Mysql
Spring Boot RabbitMQ Consumer Messages Example
Sending Spring Boot Kafka JSON Message to Kafka Topic
How to set Spring Boot SetTimeZone
How to enable Swagger in Spring Boot Application
Spring Boot Hazelcast Cache Example
Step By Step Spring Boot Docker Deployment Example
Spring Boot MongoDB + Spring Data Example
Spring Boot Redis Data Example CRUD Operations
How to change Spring Boot Tomcat Port Number
How To Change Spring Boot Context Path
Spring Boot Validation Login Form Example
Spring Boot How to change the Tomcat to Jetty Server
Spring Boot Kafka Producer Example
Spring Boot RabbitMQ Message Publishing Example
Spring Boot JdbcTemplate CRUD Operations Mysql
Spring Boot RabbitMQ Consumer Messages Example
Sending Spring Boot Kafka JSON Message to Kafka Topic
How to set Spring Boot SetTimeZone
How to enable Swagger in Spring Boot Application
Spring Boot Hazelcast Cache Example
Step By Step Spring Boot Docker Deployment Example
Spring Boot MongoDB + Spring Data Example
Spring Boot Redis Data Example CRUD Operations
How to change Spring Boot Tomcat Port Number
How To Change Spring Boot Context Path
Spring Boot Validation Login Form Example
Δ
Spring Boot – Hello World
Spring Boot – MVC Example
Spring Boot- Change Context Path
Spring Boot – Change Tomcat Port Number
Spring Boot – Change Tomcat to Jetty Server
Spring Boot – Tomcat session timeout
Spring Boot – Enable Random Port
Spring Boot – Properties File
Spring Boot – Beans Lazy Loading
Spring Boot – Set Favicon image
Spring Boot – Set Custom Banner
Spring Boot – Set Application TimeZone
Spring Boot – Send Mail
Spring Boot – FileUpload Ajax
Spring Boot – Actuator
Spring Boot – Actuator Database Health Check
Spring Boot – Swagger
Spring Boot – Enable CORS
Spring Boot – External Apache ActiveMQ Setup
Spring Boot – Inmemory Apache ActiveMq
Spring Boot – Scheduler Job
Spring Boot – Exception Handling
Spring Boot – Hibernate CRUD
Spring Boot – JPA Integration CRUD
Spring Boot – JPA DataRest CRUD
Spring Boot – JdbcTemplate CRUD
Spring Boot – Multiple Data Sources Config
Spring Boot – JNDI Configuration
Spring Boot – H2 Database CRUD
Spring Boot – MongoDB CRUD
Spring Boot – Redis Data CRUD
Spring Boot – MVC Login Form Validation
Spring Boot – Custom Error Pages
Spring Boot – iText PDF
Spring Boot – Enable SSL (HTTPs)
Spring Boot – Basic Authentication
Spring Boot – In Memory Basic Authentication
Spring Boot – Security MySQL Database Integration
Spring Boot – Redis Cache – Redis Server
Spring Boot – Hazelcast Cache
Spring Boot – EhCache
Spring Boot – Kafka Producer
Spring Boot – Kafka Consumer
Spring Boot – Kafka JSON Message to Kafka Topic
Spring Boot – RabbitMQ Publisher
Spring Boot – RabbitMQ Consumer
Spring Boot – SOAP Consumer
Spring Boot – Soap WebServices
Spring Boot – Batch Csv to Database
Spring Boot – Eureka Server
Spring Boot – MockMvc JUnit
Spring Boot – Docker Deployment
|
[
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
"text": "C Tutorials"
},
{
"code": null,
"e": 199,
"s": 195,
"text": "aws"
},
{
"code": null,
"e": 234,
"s": 199,
"text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "EXCEPTIONS"
},
{
"code": null,
"e": 257,
"s": 245,
"text": "COLLECTIONS"
},
{
"code": null,
"e": 263,
"s": 257,
"text": "SWING"
},
{
"code": null,
"e": 268,
"s": 263,
"text": "JDBC"
},
{
"code": null,
"e": 275,
"s": 268,
"text": "JAVA 8"
},
{
"code": null,
"e": 282,
"s": 275,
"text": "SPRING"
},
{
"code": null,
"e": 294,
"s": 282,
"text": "SPRING BOOT"
},
{
"code": null,
"e": 304,
"s": 294,
"text": "HIBERNATE"
},
{
"code": null,
"e": 311,
"s": 304,
"text": "PYTHON"
},
{
"code": null,
"e": 315,
"s": 311,
"text": "PHP"
},
{
"code": null,
"e": 322,
"s": 315,
"text": "JQUERY"
},
{
"code": null,
"e": 357,
"s": 322,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 371,
"s": 357,
"text": "Java Examples"
},
{
"code": null,
"e": 382,
"s": 371,
"text": "C Examples"
},
{
"code": null,
"e": 394,
"s": 382,
"text": "C Tutorials"
},
{
"code": null,
"e": 398,
"s": 394,
"text": "aws"
},
{
"code": null,
"e": 497,
"s": 398,
"text": "In this tutorial, we are going to see an essential crud operation on Spring Boot DataRest Example."
},
{
"code": null,
"e": 733,
"s": 497,
"text": "Spring Boot DataRest build on top of the Spring Data, and it’s taking the advantages of Spring HATEOAS. We can say that Spring Boot Data Rest combines the Spring Data and Spring HATEOS to provide the hypermedia-based Restful front end."
},
{
"code": null,
"e": 759,
"s": 733,
"text": "Spring Boot 2.1.4 RELEASE"
},
{
"code": null,
"e": 780,
"s": 759,
"text": "Spring Boot Data JPA"
},
{
"code": null,
"e": 801,
"s": 780,
"text": "Spring Boot DataRest"
},
{
"code": null,
"e": 808,
"s": 801,
"text": "Lombok"
},
{
"code": null,
"e": 824,
"s": 808,
"text": "MySQL connector"
},
{
"code": null,
"e": 831,
"s": 824,
"text": "Java 8"
},
{
"code": null,
"e": 837,
"s": 831,
"text": "Maven"
},
{
"code": null,
"e": 1789,
"s": 837,
"text": "<dependencies>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-data-jpa</artifactId>\n </dependency>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-data-rest</artifactId>\n </dependency>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-devtools</artifactId>\n <scope>runtime</scope>\n </dependency>\n <dependency>\n <groupId>mysql</groupId>\n <artifactId>mysql-connector-java</artifactId>\n <scope>runtime</scope>\n </dependency>\n <dependency>\n <groupId>org.projectlombok</groupId>\n <artifactId>lombok</artifactId>\n <optional>true</optional>\n </dependency>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-test</artifactId>\n <scope>test</scope>\n </dependency>\n </dependencies>"
},
{
"code": null,
"e": 1931,
"s": 1789,
"text": "As part of this example, we are going to implement a simple crud operation using spring datarest – here the data persisted in MySQL database."
},
{
"code": null,
"e": 1968,
"s": 1931,
"text": "We are configuring MySQL properties."
},
{
"code": null,
"e": 2261,
"s": 1968,
"text": "spring.datasource.driver-class-name:com.mysql.jdbc.Driver\nspring.datasource.url:jdbc:mysql://localhost:3306/otp\nspring.datasource.username:root\nspring.datasource.password:1234\n\nspring.jpa.show-sql=true\nspring.jpa.generate-ddl=false\nspring.jooq.sql-dialect=org.hibernate.dialect.MySQL5Dialect\n"
},
{
"code": null,
"e": 2343,
"s": 2261,
"text": "We are preparing Item domain object – representing an item table in the database."
},
{
"code": null,
"e": 2701,
"s": 2343,
"text": "package com.onlinetutorialspoint.domain;\n\nimport lombok.Data;\nimport lombok.NoArgsConstructor;\n\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.Id;\n\n@Entity\n@Data\n@NoArgsConstructor\npublic class Item {\n @Id\n @GeneratedValue\n private long id;\n private String name;\n private String category;\n}"
},
{
"code": null,
"e": 2894,
"s": 2701,
"text": "On the above Item class, we have used @Data and @NoArgsConstructor annotations to eliminate the boilerplate code like getters and setters, for more details on Lombok you can see this document."
},
{
"code": null,
"e": 3100,
"s": 2894,
"text": "The ItemRepository interface allows you to perform various CRUD operations on Item object. This repository gets CRUD operations from the PagingAndSortingRepository – it internally uses Spring Data Commons."
},
{
"code": null,
"e": 3336,
"s": 3100,
"text": "Apart from the basic CRUD operations, if we wanted to expose any domain related operations, you can always free to define your custom JPA operations or even use any JPQL operations inside the ItemRepository like below findByCategory()."
},
{
"code": null,
"e": 3870,
"s": 3336,
"text": "package com.onlinetutorialspoint.repo;\n\nimport com.onlinetutorialspoint.domain.Item;\nimport org.springframework.data.repository.PagingAndSortingRepository;\nimport org.springframework.data.repository.query.Param;\nimport org.springframework.data.rest.core.annotation.RepositoryRestResource;\n\nimport java.util.List;\n\n@RepositoryRestResource(path=\"items\",collectionResourceRel = \"items\")\npublic interface ItemRepository extends PagingAndSortingRepository<Item,Long> {\n List<Item> findByCategory(@Param(\"category\") String category);\n}\n"
},
{
"code": null,
"e": 3988,
"s": 3870,
"text": "@RepositoryRestResource creates HATEOAS service with Spring JPA and the operations will be exposed in HATEOAS format."
},
{
"code": null,
"e": 4348,
"s": 3988,
"text": "package com.onlinetutorialspoint;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\n@SpringBootApplication\npublic class SpringBootDataRestExampleApplication {\n\n public static void main(String[] args) {\n SpringApplication.run(SpringBootDataRestExampleApplication.class, args);\n }\n\n}\n"
},
{
"code": null,
"e": 8229,
"s": 4348,
"text": "$ mvn clean install\n$ mvn spring-boot:run\n . ____ _ __ _ _\n /\\\\ / ___'_ __ _ _(_)_ __ __ _ \\ \\ \\ \\\n( ( )\\___ | '_ | '_| | '_ \\/ _` | \\ \\ \\ \\\n \\\\/ ___)| |_)| | | | | || (_| | ) ) ) )\n ' |____| .__|_| |_|_| |_\\__, | / / / /\n =========|_|==============|___/=/_/_/_/\n :: Spring Boot :: (v2.1.4.RELEASE)\n\n2019-05-05 13:44:12.317 INFO 556 --- [ restartedMain] c.o.SpringBootDataRestExampleApplication : Starting SpringBootDataRestExampleApplication on DESKTOP-RN4SMHT with PID 556 (D:\\work\\SpringBoot-DataRest-Example\\target\\classes started by Lenovo in D:\\work\\SpringBoot-DataRest-Example)\n2019-05-05 13:44:12.323 INFO 556 --- [ restartedMain] c.o.SpringBootDataRestExampleApplication : No active profile set, falling back to default profiles: default\n2019-05-05 13:44:12.491 INFO 556 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable\n2019-05-05 13:44:12.491 INFO 556 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'\n2019-05-05 13:44:16.069 INFO 556 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.\n2019-05-05 13:44:16.218 INFO 556 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 126ms. Found 1 repository interfaces.\n2019-05-05 13:44:17.287 INFO 556 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$3afa984d] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)\n2019-05-05 13:44:17.346 INFO 556 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.hateoas.config.HateoasConfiguration' of type [org.springframework.hateoas.config.HateoasConfiguration$$EnhancerBySpringCGLIB$$ba7ae57f] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)\n2019-05-05 13:44:18.873 INFO 556 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)\n2019-05-05 13:44:18.968 INFO 556 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]\n2019-05-05 13:44:18.968 INFO 556 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.17]\n2019-05-05 13:44:19.275 INFO 556 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext\n2019-05-05 13:44:19.276 INFO 556 --- [ restartedMain] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 6784 ms\nLoading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.\n2019-05-05 13:44:19.969 INFO 556 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...\n2019-05-05 13:44:19.976 WARN 556 --- [ restartedMain] com.zaxxer.hikari.util.DriverDataSource : Registered driver with driverClassName=com.mysql.jdbc.Driver was not found, trying direct instantiation.\n2019-05-05 13:44:20.766 INFO 556 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.\n2019-05-05 13:44:21.126 INFO 556 --- [ restartedMain] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [\n......\n......\n"
},
{
"code": null,
"e": 8338,
"s": 8229,
"text": "After running the application, go to http://localhost:8080/ then you would see the following JSON structure."
},
{
"code": null,
"e": 8499,
"s": 8338,
"text": "You can observe, there were two endpoints available /items with three different options (page, size, sort) and /profile which provides the application metadata."
},
{
"code": null,
"e": 8573,
"s": 8499,
"text": "Currently, there are no items in our database, let’s create some of them."
},
{
"code": null,
"e": 8665,
"s": 8573,
"text": "Now you can access all the available items using the http://localhost:8080/items/ endpoint."
},
{
"code": null,
"e": 9944,
"s": 8665,
"text": "{\n \"_embedded\": {\n \"items\": [\n {\n \"name\": \"Thinking in Java\",\n \"category\": \"Books\",\n \"_links\": {\n \"self\": {\n \"href\": \"http://localhost:8080/items/1\"\n },\n \"item\": {\n \"href\": \"http://localhost:8080/items/1\"\n }\n }\n },\n {\n \"name\": \"Hibernate in Action\",\n \"category\": \"Books\",\n \"_links\": {\n \"self\": {\n \"href\": \"http://localhost:8080/items/2\"\n },\n \"item\": {\n \"href\": \"http://localhost:8080/items/2\"\n }\n }\n }\n ]\n },\n \"_links\": {\n \"self\": {\n \"href\": \"http://localhost:8080/items{?page,size,sort}\",\n \"templated\": true\n },\n \"profile\": {\n \"href\": \"http://localhost:8080/profile/items\"\n },\n \"search\": {\n \"href\": \"http://localhost:8080/items/search\"\n }\n },\n \"page\": {\n \"size\": 20,\n \"totalElements\": 2,\n \"totalPages\": 1,\n \"number\": 0\n }\n}"
},
{
"code": null,
"e": 10161,
"s": 9944,
"text": "On the above output, we can observe that, along with the items list, there is one more /search endpoint available. It is used to call the custom endpoints. Let’s try to access our custom endpoint getItemByCategory();"
},
{
"code": null,
"e": 10226,
"s": 10161,
"text": "http://localhost:8080/items/search/findByCategory?category=Books"
},
{
"code": null,
"e": 10232,
"s": 10226,
"text": "Done!"
},
{
"code": null,
"e": 10258,
"s": 10232,
"text": "Spring Data Rest Document"
},
{
"code": null,
"e": 10279,
"s": 10258,
"text": "Spring Boot Data JPA"
},
{
"code": null,
"e": 10296,
"s": 10279,
"text": "Happy Learning 🙂"
},
{
"code": null,
"e": 10968,
"s": 10296,
"text": "\nSpring Boot How to change the Tomcat to Jetty Server\nSpring Boot Kafka Producer Example\nSpring Boot RabbitMQ Message Publishing Example\nSpring Boot JdbcTemplate CRUD Operations Mysql\nSpring Boot RabbitMQ Consumer Messages Example\nSending Spring Boot Kafka JSON Message to Kafka Topic\nHow to set Spring Boot SetTimeZone\nHow to enable Swagger in Spring Boot Application\nSpring Boot Hazelcast Cache Example\nStep By Step Spring Boot Docker Deployment Example\nSpring Boot MongoDB + Spring Data Example\nSpring Boot Redis Data Example CRUD Operations\nHow to change Spring Boot Tomcat Port Number\nHow To Change Spring Boot Context Path\nSpring Boot Validation Login Form Example\n"
},
{
"code": null,
"e": 11021,
"s": 10968,
"text": "Spring Boot How to change the Tomcat to Jetty Server"
},
{
"code": null,
"e": 11056,
"s": 11021,
"text": "Spring Boot Kafka Producer Example"
},
{
"code": null,
"e": 11104,
"s": 11056,
"text": "Spring Boot RabbitMQ Message Publishing Example"
},
{
"code": null,
"e": 11151,
"s": 11104,
"text": "Spring Boot JdbcTemplate CRUD Operations Mysql"
},
{
"code": null,
"e": 11198,
"s": 11151,
"text": "Spring Boot RabbitMQ Consumer Messages Example"
},
{
"code": null,
"e": 11252,
"s": 11198,
"text": "Sending Spring Boot Kafka JSON Message to Kafka Topic"
},
{
"code": null,
"e": 11287,
"s": 11252,
"text": "How to set Spring Boot SetTimeZone"
},
{
"code": null,
"e": 11336,
"s": 11287,
"text": "How to enable Swagger in Spring Boot Application"
},
{
"code": null,
"e": 11372,
"s": 11336,
"text": "Spring Boot Hazelcast Cache Example"
},
{
"code": null,
"e": 11423,
"s": 11372,
"text": "Step By Step Spring Boot Docker Deployment Example"
},
{
"code": null,
"e": 11465,
"s": 11423,
"text": "Spring Boot MongoDB + Spring Data Example"
},
{
"code": null,
"e": 11512,
"s": 11465,
"text": "Spring Boot Redis Data Example CRUD Operations"
},
{
"code": null,
"e": 11557,
"s": 11512,
"text": "How to change Spring Boot Tomcat Port Number"
},
{
"code": null,
"e": 11596,
"s": 11557,
"text": "How To Change Spring Boot Context Path"
},
{
"code": null,
"e": 11638,
"s": 11596,
"text": "Spring Boot Validation Login Form Example"
},
{
"code": null,
"e": 11644,
"s": 11642,
"text": "Δ"
},
{
"code": null,
"e": 11671,
"s": 11644,
"text": " Spring Boot – Hello World"
},
{
"code": null,
"e": 11698,
"s": 11671,
"text": " Spring Boot – MVC Example"
},
{
"code": null,
"e": 11732,
"s": 11698,
"text": " Spring Boot- Change Context Path"
},
{
"code": null,
"e": 11773,
"s": 11732,
"text": " Spring Boot – Change Tomcat Port Number"
},
{
"code": null,
"e": 11818,
"s": 11773,
"text": " Spring Boot – Change Tomcat to Jetty Server"
},
{
"code": null,
"e": 11856,
"s": 11818,
"text": " Spring Boot – Tomcat session timeout"
},
{
"code": null,
"e": 11890,
"s": 11856,
"text": " Spring Boot – Enable Random Port"
},
{
"code": null,
"e": 11921,
"s": 11890,
"text": " Spring Boot – Properties File"
},
{
"code": null,
"e": 11955,
"s": 11921,
"text": " Spring Boot – Beans Lazy Loading"
},
{
"code": null,
"e": 11988,
"s": 11955,
"text": " Spring Boot – Set Favicon image"
},
{
"code": null,
"e": 12021,
"s": 11988,
"text": " Spring Boot – Set Custom Banner"
},
{
"code": null,
"e": 12061,
"s": 12021,
"text": " Spring Boot – Set Application TimeZone"
},
{
"code": null,
"e": 12086,
"s": 12061,
"text": " Spring Boot – Send Mail"
},
{
"code": null,
"e": 12117,
"s": 12086,
"text": " Spring Boot – FileUpload Ajax"
},
{
"code": null,
"e": 12141,
"s": 12117,
"text": " Spring Boot – Actuator"
},
{
"code": null,
"e": 12187,
"s": 12141,
"text": " Spring Boot – Actuator Database Health Check"
},
{
"code": null,
"e": 12210,
"s": 12187,
"text": " Spring Boot – Swagger"
},
{
"code": null,
"e": 12237,
"s": 12210,
"text": " Spring Boot – Enable CORS"
},
{
"code": null,
"e": 12283,
"s": 12237,
"text": " Spring Boot – External Apache ActiveMQ Setup"
},
{
"code": null,
"e": 12323,
"s": 12283,
"text": " Spring Boot – Inmemory Apache ActiveMq"
},
{
"code": null,
"e": 12352,
"s": 12323,
"text": " Spring Boot – Scheduler Job"
},
{
"code": null,
"e": 12386,
"s": 12352,
"text": " Spring Boot – Exception Handling"
},
{
"code": null,
"e": 12416,
"s": 12386,
"text": " Spring Boot – Hibernate CRUD"
},
{
"code": null,
"e": 12452,
"s": 12416,
"text": " Spring Boot – JPA Integration CRUD"
},
{
"code": null,
"e": 12485,
"s": 12452,
"text": " Spring Boot – JPA DataRest CRUD"
},
{
"code": null,
"e": 12518,
"s": 12485,
"text": " Spring Boot – JdbcTemplate CRUD"
},
{
"code": null,
"e": 12562,
"s": 12518,
"text": " Spring Boot – Multiple Data Sources Config"
},
{
"code": null,
"e": 12596,
"s": 12562,
"text": " Spring Boot – JNDI Configuration"
},
{
"code": null,
"e": 12628,
"s": 12596,
"text": " Spring Boot – H2 Database CRUD"
},
{
"code": null,
"e": 12656,
"s": 12628,
"text": " Spring Boot – MongoDB CRUD"
},
{
"code": null,
"e": 12687,
"s": 12656,
"text": " Spring Boot – Redis Data CRUD"
},
{
"code": null,
"e": 12728,
"s": 12687,
"text": " Spring Boot – MVC Login Form Validation"
},
{
"code": null,
"e": 12762,
"s": 12728,
"text": " Spring Boot – Custom Error Pages"
},
{
"code": null,
"e": 12787,
"s": 12762,
"text": " Spring Boot – iText PDF"
},
{
"code": null,
"e": 12821,
"s": 12787,
"text": " Spring Boot – Enable SSL (HTTPs)"
},
{
"code": null,
"e": 12857,
"s": 12821,
"text": " Spring Boot – Basic Authentication"
},
{
"code": null,
"e": 12903,
"s": 12857,
"text": " Spring Boot – In Memory Basic Authentication"
},
{
"code": null,
"e": 12954,
"s": 12903,
"text": " Spring Boot – Security MySQL Database Integration"
},
{
"code": null,
"e": 12996,
"s": 12954,
"text": " Spring Boot – Redis Cache – Redis Server"
},
{
"code": null,
"e": 13027,
"s": 12996,
"text": " Spring Boot – Hazelcast Cache"
},
{
"code": null,
"e": 13050,
"s": 13027,
"text": " Spring Boot – EhCache"
},
{
"code": null,
"e": 13080,
"s": 13050,
"text": " Spring Boot – Kafka Producer"
},
{
"code": null,
"e": 13110,
"s": 13080,
"text": " Spring Boot – Kafka Consumer"
},
{
"code": null,
"e": 13159,
"s": 13110,
"text": " Spring Boot – Kafka JSON Message to Kafka Topic"
},
{
"code": null,
"e": 13193,
"s": 13159,
"text": " Spring Boot – RabbitMQ Publisher"
},
{
"code": null,
"e": 13226,
"s": 13193,
"text": " Spring Boot – RabbitMQ Consumer"
},
{
"code": null,
"e": 13255,
"s": 13226,
"text": " Spring Boot – SOAP Consumer"
},
{
"code": null,
"e": 13287,
"s": 13255,
"text": " Spring Boot – Soap WebServices"
},
{
"code": null,
"e": 13324,
"s": 13287,
"text": " Spring Boot – Batch Csv to Database"
},
{
"code": null,
"e": 13353,
"s": 13324,
"text": " Spring Boot – Eureka Server"
},
{
"code": null,
"e": 13382,
"s": 13353,
"text": " Spring Boot – MockMvc JUnit"
}
] |
How to remove the key-value pairs corresponding to the given keys from an object using JavaScript ?
|
22 Jul, 2021
In JavaScript objects store data in the form of key-value pairs where the key may be any property of the object. In this article let us see how to remove key-value pairs corresponding to a given key in the object.
Using delete operator. When only a single key is to be removed we can directly use the delete operator specifying the key in an object.
Syntax:
delete(object_name.key_name);
/* or */
delete(object_name[key_name]);
Example:
HTML
<script> var myObj = { Name: "Raghav", Age: 30, Sex: "Male", Work: "Web Developer", YearsOfExperience: 6, Organisation: "GeeksforGeeks", Address: "address--address some value" }; console.log("After removal: "); // Deleting address key delete (myObj.Address); // Or delete(myObj[Address]); console.log(myObj);</script>
Output:
"After removal: "
[object Object] {
Age: 30,
Name: "Raghav",
Organisation: "GeeksforGeeks",
Sex: "Male",
Work: "Web Developer",
YearsOfExperience: 6
}
When multiple keys are to be removed then the keys can be stored in an array and can be passed to a function that uses a loop to delete the required keys in the array.
Syntax:
function function_name(object_name, array_of_keys) {
{ Iterate through the array using loop. }
return object_name;
}
Example 2:
HTML
<script> // Function to delete the keys given in the array function DeleteKeys(myObj, array) { for (let index = 0; index < array.length; index++) { delete myObj[array[index]]; } return myObj; } // Declaring the object var myObj = { Name: "Raghav", Age: 30, Sex: "Male", Work: "Web Developer", YearsOfExperience: 6, Organisation: "Geeks For Geeks", Address: "address--address some value" }; // Adding the keys to be deleted in the array var array = ["Work", "Address", "Organisation", "YearsOfExperience"]; var finalobj = DeleteKeys(myObj, array); console.log("After removal: "); console.log(finalobj);</script>
Output:
"After removal: "
[object Object] {
Age: 30,
Name: "Raghav",
Sex: "Male"
}
saurabh1990aror
javascript-functions
JavaScript-Questions
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n22 Jul, 2021"
},
{
"code": null,
"e": 268,
"s": 54,
"text": "In JavaScript objects store data in the form of key-value pairs where the key may be any property of the object. In this article let us see how to remove key-value pairs corresponding to a given key in the object."
},
{
"code": null,
"e": 405,
"s": 268,
"text": "Using delete operator. When only a single key is to be removed we can directly use the delete operator specifying the key in an object. "
},
{
"code": null,
"e": 413,
"s": 405,
"text": "Syntax:"
},
{
"code": null,
"e": 485,
"s": 415,
"text": "delete(object_name.key_name);\n/* or */\ndelete(object_name[key_name]);"
},
{
"code": null,
"e": 496,
"s": 487,
"text": "Example:"
},
{
"code": null,
"e": 503,
"s": 498,
"text": "HTML"
},
{
"code": "<script> var myObj = { Name: \"Raghav\", Age: 30, Sex: \"Male\", Work: \"Web Developer\", YearsOfExperience: 6, Organisation: \"GeeksforGeeks\", Address: \"address--address some value\" }; console.log(\"After removal: \"); // Deleting address key delete (myObj.Address); // Or delete(myObj[Address]); console.log(myObj);</script> ",
"e": 906,
"s": 503,
"text": null
},
{
"code": null,
"e": 914,
"s": 906,
"text": "Output:"
},
{
"code": null,
"e": 1077,
"s": 914,
"text": "\"After removal: \"\n[object Object] {\n Age: 30,\n Name: \"Raghav\",\n Organisation: \"GeeksforGeeks\",\n Sex: \"Male\",\n Work: \"Web Developer\",\n YearsOfExperience: 6\n}"
},
{
"code": null,
"e": 1246,
"s": 1077,
"text": "When multiple keys are to be removed then the keys can be stored in an array and can be passed to a function that uses a loop to delete the required keys in the array. "
},
{
"code": null,
"e": 1254,
"s": 1246,
"text": "Syntax:"
},
{
"code": null,
"e": 1381,
"s": 1256,
"text": "function function_name(object_name, array_of_keys) {\n { Iterate through the array using loop. }\n return object_name;\n}"
},
{
"code": null,
"e": 1394,
"s": 1383,
"text": "Example 2:"
},
{
"code": null,
"e": 1401,
"s": 1396,
"text": "HTML"
},
{
"code": "<script> // Function to delete the keys given in the array function DeleteKeys(myObj, array) { for (let index = 0; index < array.length; index++) { delete myObj[array[index]]; } return myObj; } // Declaring the object var myObj = { Name: \"Raghav\", Age: 30, Sex: \"Male\", Work: \"Web Developer\", YearsOfExperience: 6, Organisation: \"Geeks For Geeks\", Address: \"address--address some value\" }; // Adding the keys to be deleted in the array var array = [\"Work\", \"Address\", \"Organisation\", \"YearsOfExperience\"]; var finalobj = DeleteKeys(myObj, array); console.log(\"After removal: \"); console.log(finalobj);</script>",
"e": 2112,
"s": 1401,
"text": null
},
{
"code": null,
"e": 2120,
"s": 2112,
"text": "Output:"
},
{
"code": null,
"e": 2201,
"s": 2120,
"text": "\"After removal: \"\n[object Object] {\n Age: 30,\n Name: \"Raghav\",\n Sex: \"Male\"\n}"
},
{
"code": null,
"e": 2217,
"s": 2201,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 2238,
"s": 2217,
"text": "javascript-functions"
},
{
"code": null,
"e": 2259,
"s": 2238,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 2266,
"s": 2259,
"text": "Picked"
},
{
"code": null,
"e": 2277,
"s": 2266,
"text": "JavaScript"
},
{
"code": null,
"e": 2294,
"s": 2277,
"text": "Web Technologies"
}
] |
Flexible Array Members in a structure in C
|
22 Oct, 2019
Flexible Array Member(FAM) is a feature introduced in the C99 standard of the C programming language.
For the structures in C programming language from C99 standard onwards, we can declare an array without a dimension and whose size is flexible in nature.
Such an array inside the structure should preferably be declared as the last member of structure and its size is variable(can be changed be at runtime).
The structure must contain at least one more named member in addition to the flexible array member.
What must be the size of the structure below?
struct student{ int stud_id; int name_len; int struct_size; char stud_name[];};
The size of structure is = 4 + 4 + 4 + 0 = 12
In the above code snippet, the size i.e length of array “stud_name” isn’t fixed and is an FAM.
The memory allocation using flexible array members(as per C99 standards) for the above example can be done as:
struct student *s = malloc( sizeof(*s) + sizeof(char [strlen(stud_name)]) );
Note: While using flexible array members in structures some convention regarding actual size of the member is defined.In the above example the convention is that the member “stud_name” has character size.
For Example, Consider the following structure:
Input : id = 15, name = "Kartik"
Output : Student_id : 15
Stud_Name : Kartik
Name_Length: 6
Allocated_Struct_size: 18
Memory allocation of above structure:
struct student *s =
malloc( sizeof(*s) + sizeof(char [strlen("Kartik")]));
Its structure representation is equal to:
struct student{ int stud_id; int name_len; int struct_size; char stud_name[6]; //character array of length 6};
Implementation
// C program for variable length members in// structures in GCC#include<string.h>#include<stdio.h>#include<stdlib.h> // A structure of type studentstruct student{ int stud_id; int name_len; // This is used to store size of flexible // character array stud_name[] int struct_size; // Flexible Array Member(FAM) // variable length array must be last // member of structure char stud_name[];}; // Memory allocation and initialisation of structurestruct student *createStudent(struct student *s, int id, char a[]){ // Allocating memory according to user provided // array of characters s = malloc( sizeof(*s) + sizeof(char) * strlen(a)); s->stud_id = id; s->name_len = strlen(a); strcpy(s->stud_name, a); // Assigning size according to size of stud_name // which is a copy of user provided array a[]. s->struct_size = (sizeof(*s) + sizeof(char) * strlen(s->stud_name)); return s;} // Print student detailsvoid printStudent(struct student *s){ printf("Student_id : %d\n" "Stud_Name : %s\n" "Name_Length: %d\n" "Allocated_Struct_size: %d\n\n", s->stud_id, s->stud_name, s->name_len, s->struct_size); // Value of Allocated_Struct_size is in bytes here} // Driver Codeint main(){ struct student *s1 = createStudent(s1, 523, "Cherry"); struct student *s2 = createStudent(s2, 535, "Sanjayulsha"); printStudent(s1); printStudent(s2); // Size in struct student printf("Size of Struct student: %lu\n", sizeof(struct student)); // Size in struct pointer printf("Size of Struct pointer: %lu", sizeof(s1)); return 0;}
Output:
Student_id : 523
Stud_Name : SanjayKanna
Name_Length: 11
Allocated_Struct_size: 23
Student_id : 535
Stud_Name : Cherry
Name_Length: 6
Allocated_Struct_size: 18
Size of Struct student: 12
Size of Struct pointer: 8
Important Points:
Adjacent memory locations are used to store structure members in memory.In previous standards of the C programming language, we were able to declare a zero size array member in place of a flexible array member. The GCC compiler with C89 standard considers it as zero size array.
Adjacent memory locations are used to store structure members in memory.
In previous standards of the C programming language, we were able to declare a zero size array member in place of a flexible array member. The GCC compiler with C89 standard considers it as zero size array.
This article is contributed by Sanjay Kumar Ulsha from JNTUH College Of Engineering, Hyderabad. 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.
Akanksha_Rai
C-Struct-Union-Enum
C-Structure & Union
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n22 Oct, 2019"
},
{
"code": null,
"e": 156,
"s": 54,
"text": "Flexible Array Member(FAM) is a feature introduced in the C99 standard of the C programming language."
},
{
"code": null,
"e": 310,
"s": 156,
"text": "For the structures in C programming language from C99 standard onwards, we can declare an array without a dimension and whose size is flexible in nature."
},
{
"code": null,
"e": 463,
"s": 310,
"text": "Such an array inside the structure should preferably be declared as the last member of structure and its size is variable(can be changed be at runtime)."
},
{
"code": null,
"e": 563,
"s": 463,
"text": "The structure must contain at least one more named member in addition to the flexible array member."
},
{
"code": null,
"e": 609,
"s": 563,
"text": "What must be the size of the structure below?"
},
{
"code": "struct student{ int stud_id; int name_len; int struct_size; char stud_name[];};",
"e": 697,
"s": 609,
"text": null
},
{
"code": null,
"e": 743,
"s": 697,
"text": "The size of structure is = 4 + 4 + 4 + 0 = 12"
},
{
"code": null,
"e": 838,
"s": 743,
"text": "In the above code snippet, the size i.e length of array “stud_name” isn’t fixed and is an FAM."
},
{
"code": null,
"e": 949,
"s": 838,
"text": "The memory allocation using flexible array members(as per C99 standards) for the above example can be done as:"
},
{
"code": null,
"e": 1029,
"s": 949,
"text": " struct student *s = malloc( sizeof(*s) + sizeof(char [strlen(stud_name)]) );\n"
},
{
"code": null,
"e": 1234,
"s": 1029,
"text": "Note: While using flexible array members in structures some convention regarding actual size of the member is defined.In the above example the convention is that the member “stud_name” has character size."
},
{
"code": null,
"e": 1281,
"s": 1234,
"text": "For Example, Consider the following structure:"
},
{
"code": null,
"e": 1429,
"s": 1281,
"text": "Input : id = 15, name = \"Kartik\" \nOutput : Student_id : 15\n Stud_Name : Kartik\n Name_Length: 6\n Allocated_Struct_size: 18\n"
},
{
"code": null,
"e": 1467,
"s": 1429,
"text": "Memory allocation of above structure:"
},
{
"code": null,
"e": 1552,
"s": 1467,
"text": "struct student *s = \n malloc( sizeof(*s) + sizeof(char [strlen(\"Kartik\")]));\n"
},
{
"code": null,
"e": 1594,
"s": 1552,
"text": "Its structure representation is equal to:"
},
{
"code": "struct student{ int stud_id; int name_len; int struct_size; char stud_name[6]; //character array of length 6};",
"e": 1713,
"s": 1594,
"text": null
},
{
"code": null,
"e": 1728,
"s": 1713,
"text": "Implementation"
},
{
"code": "// C program for variable length members in// structures in GCC#include<string.h>#include<stdio.h>#include<stdlib.h> // A structure of type studentstruct student{ int stud_id; int name_len; // This is used to store size of flexible // character array stud_name[] int struct_size; // Flexible Array Member(FAM) // variable length array must be last // member of structure char stud_name[];}; // Memory allocation and initialisation of structurestruct student *createStudent(struct student *s, int id, char a[]){ // Allocating memory according to user provided // array of characters s = malloc( sizeof(*s) + sizeof(char) * strlen(a)); s->stud_id = id; s->name_len = strlen(a); strcpy(s->stud_name, a); // Assigning size according to size of stud_name // which is a copy of user provided array a[]. s->struct_size = (sizeof(*s) + sizeof(char) * strlen(s->stud_name)); return s;} // Print student detailsvoid printStudent(struct student *s){ printf(\"Student_id : %d\\n\" \"Stud_Name : %s\\n\" \"Name_Length: %d\\n\" \"Allocated_Struct_size: %d\\n\\n\", s->stud_id, s->stud_name, s->name_len, s->struct_size); // Value of Allocated_Struct_size is in bytes here} // Driver Codeint main(){ struct student *s1 = createStudent(s1, 523, \"Cherry\"); struct student *s2 = createStudent(s2, 535, \"Sanjayulsha\"); printStudent(s1); printStudent(s2); // Size in struct student printf(\"Size of Struct student: %lu\\n\", sizeof(struct student)); // Size in struct pointer printf(\"Size of Struct pointer: %lu\", sizeof(s1)); return 0;}",
"e": 3485,
"s": 1728,
"text": null
},
{
"code": null,
"e": 3493,
"s": 3485,
"text": "Output:"
},
{
"code": null,
"e": 3709,
"s": 3493,
"text": "Student_id : 523\nStud_Name : SanjayKanna\nName_Length: 11\nAllocated_Struct_size: 23\n\nStudent_id : 535\nStud_Name : Cherry\nName_Length: 6\nAllocated_Struct_size: 18\n\nSize of Struct student: 12\nSize of Struct pointer: 8\n"
},
{
"code": null,
"e": 3727,
"s": 3709,
"text": "Important Points:"
},
{
"code": null,
"e": 4006,
"s": 3727,
"text": "Adjacent memory locations are used to store structure members in memory.In previous standards of the C programming language, we were able to declare a zero size array member in place of a flexible array member. The GCC compiler with C89 standard considers it as zero size array."
},
{
"code": null,
"e": 4079,
"s": 4006,
"text": "Adjacent memory locations are used to store structure members in memory."
},
{
"code": null,
"e": 4286,
"s": 4079,
"text": "In previous standards of the C programming language, we were able to declare a zero size array member in place of a flexible array member. The GCC compiler with C89 standard considers it as zero size array."
},
{
"code": null,
"e": 4637,
"s": 4286,
"text": "This article is contributed by Sanjay Kumar Ulsha from JNTUH College Of Engineering, Hyderabad. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 4762,
"s": 4637,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 4775,
"s": 4762,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 4795,
"s": 4775,
"text": "C-Struct-Union-Enum"
},
{
"code": null,
"e": 4815,
"s": 4795,
"text": "C-Structure & Union"
},
{
"code": null,
"e": 4826,
"s": 4815,
"text": "C Language"
}
] |
Matplotlib.figure.Figure.ginput() in Python
|
30 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements.
The ginput() method figure module of matplotlib library is used to block call to interact with a figure.
Syntax: ginput(self, n=1, timeout=30, show_clicks=True, mouse_add=1, mouse_pop=3, mouse_stop=2)
Parameters: This method accept the following parameters that are described below:
n : This parameter is the number of mouse clicks to accumulate.
timeout : This parameter is the number of seconds to wait before timing out.
show_clicks : This parameter is used to show a red cross at the location of each click.
mouse_add : This parameter is the Mouse button used to add points.
mouse_pop : This parameter is the Mouse button used to remove the most recently added point.
mouse_stop : This parameter is the Mouse button used to stop input.
Returns: This method return the list of the clicked (x, y) coordinates.
Below examples illustrate the matplotlib.figure.Figure.ginput() function in matplotlib.figure:
Example 1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np t = np.arange(10) fig = plt.figure()ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) ax.plot(t, np.sin(t)) fig.suptitle('matplotlib.figure.Figure.ginput() \function Example', fontweight ="bold") print("After 3 clicks :")x = fig.ginput(3)print(x) plt.show()
Output:
After 3 clicks :
[(5.370117187499999, 0.12683733876216197),
(5.370117187499999, 0.12683733876216197),
(5.370117187499999, 0.12683733876216197)]
Example 2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np np.random.seed(10**7) x1 = np.random.rand(103, 53) fig = plt.figure(dpi = 100)axes = fig.add_subplot(111) fig.suptitle('matplotlib.figure.Figure.ginput() \function Example', fontweight ="bold") print("After 2 clicks :")axes.imshow(x1)x = fig.ginput(2) print(x) plt.show()
Output:
After 2 clicks :
[(29.90151515151514, 65.65854978354977),
(29.90151515151514, 65.65854978354977)]
Matplotlib figure-class
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": "\n30 Apr, 2020"
},
{
"code": null,
"e": 339,
"s": 28,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements."
},
{
"code": null,
"e": 444,
"s": 339,
"text": "The ginput() method figure module of matplotlib library is used to block call to interact with a figure."
},
{
"code": null,
"e": 540,
"s": 444,
"text": "Syntax: ginput(self, n=1, timeout=30, show_clicks=True, mouse_add=1, mouse_pop=3, mouse_stop=2)"
},
{
"code": null,
"e": 622,
"s": 540,
"text": "Parameters: This method accept the following parameters that are described below:"
},
{
"code": null,
"e": 686,
"s": 622,
"text": "n : This parameter is the number of mouse clicks to accumulate."
},
{
"code": null,
"e": 763,
"s": 686,
"text": "timeout : This parameter is the number of seconds to wait before timing out."
},
{
"code": null,
"e": 851,
"s": 763,
"text": "show_clicks : This parameter is used to show a red cross at the location of each click."
},
{
"code": null,
"e": 918,
"s": 851,
"text": "mouse_add : This parameter is the Mouse button used to add points."
},
{
"code": null,
"e": 1011,
"s": 918,
"text": "mouse_pop : This parameter is the Mouse button used to remove the most recently added point."
},
{
"code": null,
"e": 1079,
"s": 1011,
"text": "mouse_stop : This parameter is the Mouse button used to stop input."
},
{
"code": null,
"e": 1151,
"s": 1079,
"text": "Returns: This method return the list of the clicked (x, y) coordinates."
},
{
"code": null,
"e": 1246,
"s": 1151,
"text": "Below examples illustrate the matplotlib.figure.Figure.ginput() function in matplotlib.figure:"
},
{
"code": null,
"e": 1257,
"s": 1246,
"text": "Example 1:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np t = np.arange(10) fig = plt.figure()ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) ax.plot(t, np.sin(t)) fig.suptitle('matplotlib.figure.Figure.ginput() \\function Example', fontweight =\"bold\") print(\"After 3 clicks :\")x = fig.ginput(3)print(x) plt.show()",
"e": 1604,
"s": 1257,
"text": null
},
{
"code": null,
"e": 1612,
"s": 1604,
"text": "Output:"
},
{
"code": null,
"e": 1758,
"s": 1612,
"text": "After 3 clicks :\n[(5.370117187499999, 0.12683733876216197), \n(5.370117187499999, 0.12683733876216197),\n(5.370117187499999, 0.12683733876216197)]\n"
},
{
"code": null,
"e": 1769,
"s": 1758,
"text": "Example 2:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np np.random.seed(10**7) x1 = np.random.rand(103, 53) fig = plt.figure(dpi = 100)axes = fig.add_subplot(111) fig.suptitle('matplotlib.figure.Figure.ginput() \\function Example', fontweight =\"bold\") print(\"After 2 clicks :\")axes.imshow(x1)x = fig.ginput(2) print(x) plt.show()",
"e": 2141,
"s": 1769,
"text": null
},
{
"code": null,
"e": 2149,
"s": 2141,
"text": "Output:"
},
{
"code": null,
"e": 2248,
"s": 2149,
"text": "After 2 clicks :\n[(29.90151515151514, 65.65854978354977),\n(29.90151515151514, 65.65854978354977)]\n"
},
{
"code": null,
"e": 2272,
"s": 2248,
"text": "Matplotlib figure-class"
},
{
"code": null,
"e": 2290,
"s": 2272,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 2297,
"s": 2290,
"text": "Python"
}
] |
Stored Procedure for prime numbers in MYSQL
|
22 Sep, 2020
In this article, you will see how you can write the logic of stored procedure to generate prime numbers for any given input.
Title :Given a number N print all the prime number (<=N) separated by comma (, ) using Stored Procedure in MYSQL.
Example-1 :
Input : N = 10
Output : 2, 3, 5, 7
Example-2 :
Input : N = 20
Output : 2, 3, 5, 7, 11, 13, 17, 19
Program :A program to demonstrate that how you can generate the prime numbers for any given input.
delimiter $$
create procedure getPrime(IN n int, OUT result varchar(200))
Begin
declare j, i, flag int; /* Declare variables */
set j:=2;
set result:=' ';
while(j<n) do /* Loop from 2 to n */
set i:=2;
set flag:=0;
while(i<=j) do /* Loop from 2 to j */
if(j%i=0)then
set flag:=flag+1;
end if;
set i:=i+1; /* Increment i */
end while;
if (flag=1) then
set result:=concat(result, j, ', ');
/* Concat the prime number with ', ' */
end if ;
set j:=j+1; /* Increment j */
end while;
End
$$
How to call the procedure :To call the procedure used the following query given below.
call getPrime(20, @result);
select substr(@result, 1, length(@result)-1); /* To remove last character */
Output :
2, 3, 5, 7, 11, 13, 17, 19
mysql
Prime Number
DBMS
Prime Number
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n22 Sep, 2020"
},
{
"code": null,
"e": 179,
"s": 54,
"text": "In this article, you will see how you can write the logic of stored procedure to generate prime numbers for any given input."
},
{
"code": null,
"e": 293,
"s": 179,
"text": "Title :Given a number N print all the prime number (<=N) separated by comma (, ) using Stored Procedure in MYSQL."
},
{
"code": null,
"e": 305,
"s": 293,
"text": "Example-1 :"
},
{
"code": null,
"e": 341,
"s": 305,
"text": "Input : N = 10\nOutput : 2, 3, 5, 7\n"
},
{
"code": null,
"e": 353,
"s": 341,
"text": "Example-2 :"
},
{
"code": null,
"e": 405,
"s": 353,
"text": "Input : N = 20\nOutput : 2, 3, 5, 7, 11, 13, 17, 19\n"
},
{
"code": null,
"e": 504,
"s": 405,
"text": "Program :A program to demonstrate that how you can generate the prime numbers for any given input."
},
{
"code": null,
"e": 997,
"s": 504,
"text": "delimiter $$\ncreate procedure getPrime(IN n int, OUT result varchar(200))\nBegin\ndeclare j, i, flag int; /* Declare variables */\nset j:=2; \nset result:=' '; \nwhile(j<n) do /* Loop from 2 to n */\nset i:=2;\nset flag:=0;\n\nwhile(i<=j) do /* Loop from 2 to j */\nif(j%i=0)then\nset flag:=flag+1;\nend if;\nset i:=i+1; /* Increment i */\nend while;\n\nif (flag=1) then\nset result:=concat(result, j, ', '); \n/* Concat the prime number with ', ' */\nend if ;\nset j:=j+1; /* Increment j */\nend while;\n\nEnd\n$$\n"
},
{
"code": null,
"e": 1084,
"s": 997,
"text": "How to call the procedure :To call the procedure used the following query given below."
},
{
"code": null,
"e": 1190,
"s": 1084,
"text": "call getPrime(20, @result);\nselect substr(@result, 1, length(@result)-1); /* To remove last character */\n"
},
{
"code": null,
"e": 1199,
"s": 1190,
"text": "Output :"
},
{
"code": null,
"e": 1227,
"s": 1199,
"text": "2, 3, 5, 7, 11, 13, 17, 19\n"
},
{
"code": null,
"e": 1233,
"s": 1227,
"text": "mysql"
},
{
"code": null,
"e": 1246,
"s": 1233,
"text": "Prime Number"
},
{
"code": null,
"e": 1251,
"s": 1246,
"text": "DBMS"
},
{
"code": null,
"e": 1264,
"s": 1251,
"text": "Prime Number"
},
{
"code": null,
"e": 1269,
"s": 1264,
"text": "DBMS"
}
] |
Force Law for Simple Harmonic Motion
|
23 Feb, 2022
Have you ever wondered why, when we stretch an elastic band and then let it go, it returns to its previous state? It is compelled to revert to its original state by a force. But what exactly is this force? Let us investigate this force and develop the force law for simple harmonic motion.
Periodic Motion is something we’re already familiar with. Periodic motion is defined as motion that repeats itself at equal intervals of time. For example, the motion of a clock’s hands, the motion of a car’s wheels, and the motion of a merry-go-round. In nature, all of these motions are repeated. They repeat themselves after a certain period of time.
An Oscillatory Motion is a periodic movement in which an item oscillates about its equilibrium position. After a given amount of time, the item repeats the same sequence of moves. An Oscillation is one such series of motions. An oscillatory motion may be seen in the movement of a basic pendulum, the movement of leaves in a breeze, and the movement of a cradle.
Simple harmonic motion is the most basic type of oscillatory motion. When an object moves in a straight path, it exhibits simple harmonic motion. All oscillatory motion examples are instances of basic harmonic motion.
Swinging a basic pendulum causes it to move away from its mean equilibrium point. When it reaches its extreme position, where it has the greatest displacement, it comes to a halt, and its velocity becomes zero. It returns to its equilibrium position as a result of a force acting in the direction of the equilibrium position.
It now travels through its normal location but does not stop. It shifts to its other extreme position. After that, it returns to its original place. An Oscillation is a type of full motion. A basic pendulum’s swing is an excellent illustration of simple harmonic motion.
Thus, the motion of a body is said to be simply harmonic if the restoring force acting on it is directly proportional to the displacement from the mean position and always tends to oppose it. The direction of the restoring force is opposite to the direction of displacement.
The acceleration of a particle moving in a simple harmonic motion is given by,
a(t) = -ω2x(t)
where ω is the angular velocity of the particle.
Let’s now discuss some important terms related to a Simple Harmonic Motion of a particle as
Displacement (x): Displacement at any instant of time is defined as the net distance travelled by the body executing SHM from its mean or equilibrium position.Amplitude (A): The amplitude of oscillation is defined as the maximum displacement of the body executing SHM on either side of the mean position.Velocity (v): Velocity at any instant is defined as the rate of change of displacement with time. For a body executing SHM, its velocity is maximum at the mean position and minimum (zero) at the extremes. The Velocity of the body is inversely proportional to the displacement from the mean position.Acceleration (a): Acceleration is defined as the rate of change of velocity with time. Unlike velocity, acceleration is directly proportional to displacement. It is maximum at the extreme positions where the displacement is maximum and minimum at the mean position (displacement = 0).Restoring Force (FR): Restoring Force is the force that always acts in a direction opposite to that of displacement but is directly proportional to it. Restoring Force is maximum at the extreme positions and minimum at the mean position.Spring Constant (k): Spring Constant is a constant value for a particular spring that determines the amount of force required to compress or stretch the spring by 1 unit.Energy (E): The total energy of the body under SHM is called mechanical energy, mechanical energy of the body remains constant throughout the motion if the medium is frictionless. The Mechanical Energy of a body at any instant is the sum total of its kinetic and potential energy.Time Period (T): The Time Period of oscillation is defined as the time taken by the body to complete one oscillation. In other words, it is the time taken to cover 4 times the amplitude.Frequency (f): Frequency is defined as the number of oscillations made by the body in one second. It is reciprocal of the time period. f = (1/T)
Displacement (x): Displacement at any instant of time is defined as the net distance travelled by the body executing SHM from its mean or equilibrium position.
Amplitude (A): The amplitude of oscillation is defined as the maximum displacement of the body executing SHM on either side of the mean position.
Velocity (v): Velocity at any instant is defined as the rate of change of displacement with time. For a body executing SHM, its velocity is maximum at the mean position and minimum (zero) at the extremes. The Velocity of the body is inversely proportional to the displacement from the mean position.
Acceleration (a): Acceleration is defined as the rate of change of velocity with time. Unlike velocity, acceleration is directly proportional to displacement. It is maximum at the extreme positions where the displacement is maximum and minimum at the mean position (displacement = 0).
Restoring Force (FR): Restoring Force is the force that always acts in a direction opposite to that of displacement but is directly proportional to it. Restoring Force is maximum at the extreme positions and minimum at the mean position.
Spring Constant (k): Spring Constant is a constant value for a particular spring that determines the amount of force required to compress or stretch the spring by 1 unit.
Energy (E): The total energy of the body under SHM is called mechanical energy, mechanical energy of the body remains constant throughout the motion if the medium is frictionless. The Mechanical Energy of a body at any instant is the sum total of its kinetic and potential energy.
Time Period (T): The Time Period of oscillation is defined as the time taken by the body to complete one oscillation. In other words, it is the time taken to cover 4 times the amplitude.
Frequency (f): Frequency is defined as the number of oscillations made by the body in one second. It is reciprocal of the time period. f = (1/T)
Note: In periodic motion, the direction of restoring force may or may not be in the direction of displacement but in Simple Harmonic Motion (SHM) the direction of restoring force is always opposite to the direction of displacement. This leads to the fact that all Simple Harmonic Motions are periodic motions but vice versa is not true.
Let us use an example to develop the force law for simple harmonic motion. The most basic example of simple harmonic motion is a spring-block system. Consider a mass m block attached to a spring, which is then attached to a stiff wall. The block is supported by a frictionless surface.
The spring is at its equilibrium position when we do not pull it, that is when no force is exerted to it. The net force acting on it is zero in this condition. Let’s try two different things and see what happens.
When we move the block outwards, a force acts on it, attempting to draw it inwards, towards its equilibrium position.When we press the block inwards, a force operating on it tries to push it outwards, towards its equilibrium position.
When we move the block outwards, a force acts on it, attempting to draw it inwards, towards its equilibrium position.
When we press the block inwards, a force operating on it tries to push it outwards, towards its equilibrium position.
In both situations, we can observe that a force is operating on the block to try to return it to its equilibrium position. This force is the restoring force, and it is the foundation of the force law for simple harmonic motion. Let’s figure out how to apply this concept.
Variation in restoring force with change in displacement
Let F be the restoring force and x denote the displacement of the block from its equilibrium position. As a result of our observations, we may conclude that the restoring force is directly proportional to the displacement from the mean position.
This implies,
F = – kx ......(1)
where k is known as the force constant. It is measured in N/m in the SI system and in dynes/cm in the C.G.S. system. The negative symbol denotes that the restoring force and displacement are always pointing in opposing directions. For simple harmonic motion, equation (1) is the simplest version of the force law.
It demonstrates the fundamental law of simple harmonic motion, which states that force and displacement must be in opposing directions.
We also know that:
F = ma
As a result,
a = F/m
Substituting the value of F from equation (1) which yields,
a = – kx/m = – ω2x (where k/m = ω2) ......(2)
As a result, Equations I and II are the force laws of simple harmonic motion. It should be noted that the restoring force is always directed towards the mean position and in the opposite direction of displacement.
Example:
If the force required to stretch a spring by 50 cm is 150 N. How much force is
required to compress it by 35 cm?
Solution:
According to Hooke’s law: FR = -kx
In the first case: x= -50 cm = -0.5 m
[x is taken negative to indicate that it is opposite to FR]
FR = 150 N
k = (- 150/-0.5) N/m
k = 300 N/m
In the second case:
x= 35 cm = 0.35 m
FR= -300 * 0.35 N
= -105 N
Differential Equation
We know Force = mass * acceleration.
Acceleration (a) of a body in SHM is given by:
a = d2x/dt2 [Acceleration is the rate of change of velocity, a = (dv/dt) and v = (dx/dt)]
Force (F) = mass (m) * acceleration (a).
Now according to Hooke’s law,
FR = -kx, F = FR [F is the force applied and FR is the restoring force]
Therefore: -kx = m * a
-kx = m * d2x / dt2
d2x / dt2= (-k * x) / m
Note: Restoring Force is zero at the mean position because at mean position the value of x ix zero.
Work Done in SHM
Work done = Force * Displacement, you might be thinking that as the applied force is equal to the
restoring force which is kx (magnitude) and the displacement is x so the work done should be kx2,
but this is not the case here, we cannot use W = Force * Displacement because this definition or formula
of work done is applicable only when the force is constant but in SHM, force is a function of displacement
from the mean position.
The formula for work done in the case of SHM :
W = (1/2) ∗ k ∗ x2
Proof:
For variable force,
W = ∫ F dx
W = ∫ kx dx [F = kx]
W = (1/2) ∗ k ∗ x2
This is also the formula for the potential energy of the mass-spring system denoted by UX
Relationship between SHM and uniform circular motion.
The motion of the body is said to be circular if its distance from a fixed point (centre) remains constant throughout the motion.
The circular motion is said to be uniform if the speed of the body in motion remains constant.
Note: Speed remains constant but not the velocity because the direction of motion keeps on changing. Uniform circular motion is an
accelerated motion.
Uniform Circular Motion of a body
Considering the figure given above, the projection of the body under uniform circular motion on the diameter is said to be simple harmonic motion.
If we consider the motion of the body sideways it looks as if the body is moving in a straight-line path along the diameter with the centre
of the circle being the equilibrium position.
Displacement in SHM
In the figure, ‘θ’ is the angular displacement, ‘x’ is the linear displacement of the body under SHM.
cos θ = Base / Hypotenuse,
cos θ = OF / OT
cos θ = x / A, x is the displacement from the mean position and A is the amplitude
x = A cos θ — Equation of displacement of a body under SHM.
x = A cos(ωt), ω is the angular velocity or frequency, θ = ωt.
x = A cos (2πft), ω = 2πft
The maximum value of the cosine of any angle is +1 (positive direction) and -1 (negative direction), considering this the maximum value of x can be A (magnitude),
which is the amplitude of oscillation or vibration.
The equation can also be written in the form of sine of the angular displacement, y = A sin θ.
Velocity in SHM
As discussed, velocity is defined as the rate of change of displacement with time.
v = d(x) / dt
v = d(A cos (ωt)) / dt
v =(-A sin (ωt)) * ω
v = -V sin (ωt) — Equation of velocity, V= Aω.
‘V’ is the velocity with which the body is revolving in the circular path. Linear Velocity = Angular Velocity * Radius of the circle.
‘ω’ is the angular velocity, ‘A’ is the amplitude which in turn is the radius of the circle, hence we can write ‘V’ in place
of ‘Aω’.
In △ TOF, sin (ωt) = (TF) / (TO),
sin (ωt) = √(A2 – x2) / A [By Pythagoras Theorem, Hypotenuse2 = (Perpendicular)2 + (Base)2, TF = √(A2– x2)]
Replacing the value of sin (ωt) in the equation of velocity,
v =( -V * √(A2 – x2 )) / A — Another form of equation of velocity.
In the above equation, if the value of x is equal to A i.e. if the displacement is maximum then the value of v is zero and
if the value of x is zero i.e. if the body is at the mean position then the value of v is max.
‘V’ is the velocity of the body executing uniform circular motion and also the maximum velocity
of the body executing simple harmonic motion.
Acceleration in SHM
Acceleration (a) is defined as the rate of change of velocity with time.
v = -A sin (ωt)) * ω — Equation of velocity
a = d(v) / dt
a = d((-A sin (ωt)) * ω) / dt
a= -A cos (ωt) * ω2 — Equation of acceleration
In △ TOF, cos (ωt) = (OF) / (OT)
cos (ωt) = x / A
Replacing the value of cos (ωt) in the equation of acceleration,
a = (-A * x * ω2 ) / A
a = – xω2 — Another form of the equation of acceleration
Considering the above equation, if the value of x is zero then acceleration is also zero which proves the fact that acceleration is zero at the mean position.
On the other hand, if the value of x is maximum i.e. ‘A’ then the value of acceleration is also maximum.
amax = -Aω2 — Equation for maximum acceleration
Time Period in SHM
Time Period of Oscillation is given by,
T = (2πR) / V, 2πR is the circumference of the circle and V is the linear velocity,
T = (2π) / ω, V = ω * R.
T = (2π) / √(a / x), ω = √(a / x)
T = (2π) * √(x / a)
Hence the time period of oscillation is given by Time Period = (2π) * √(displacement / acceleration).
Frequency in SHM
Frequency is the total number of vibrations or oscillations made by the body in one second.
f = (1/ Time Period)
f = (1/2π) * √(acceleration / displacement)
Kinetic Energy
This energy of the body is due to the motion of the body.
K = (1/2) * m * v2
K = (1/2) * m * (ω * √(A2 – x2 ))2, v = ω * √(A2 – x2)
K = (1/2) * m * ω 2 * (A2 – x2 )
At x = 0, the value of K is maximum.
Kmax = (1/2) * m * ω 2* (A2)
At x= A, the value of K is zero.
Potential Energy
This energy of the body is due to the position of the body or the amount of work done by the body.
U = (1/2) * m * ω2 * x2
Potential Energy is maximum at the extreme positions where the value of displacement is equal to Amplitude and minimum at the equilibrium position
where the displacement is zero.
Umax = (1/2) * m * ω 2 * A2
Simple Pendulum
Another example of a body executing SHM is a simple pendulum, a simple pendulum
consists of a bob being suspended from a thread. If we neglect the mass of thread and friction around
the system then the motion is called SHM.
Forces acting on the bob executing SHM
Considering the figure given above:
The effect of mgcosA is cancelled by Force of Tension [F] as both are acting opposite
to each other. This is why the bob is having zero movement in the vertical direction.
The restoring force is being generated due to mgsinA which is in the direction opposite
to that of displacement.
FR = -mgsin(∠A), now if the angular displacement i.e. ∠A is very small then
∠A = sin(∠A) [Unit of angle is radian]
Therefore, FR = -mg∠A, now ∠A =x/l where x is the linear displacement of the bob
from the mean position and l is the length of the rope or thread used.
Substituting the value of ∠A, we get:
FR = -mg(x/l)
The expression states that the restoring force is directly proportional and opposite in direction
to the displacement from the mean position.
Problem 1: The amount of force required to stretch a spring by 10 cm is 150 N. How much force is required to stretch the spring by 100 cm? Calculate the spring constant of the spring.
Solution:
As long as the external force is applied on the body, the restoring and the applied force are the same, then
F = -kx
Since, it is given that, F = 150 N
x = -10 cm = – 0.1 m (Taking x negative because we have taken force as positive)
Therefore, k = (150 / 0.1) = 1500 N/m
Now, x = -100 cm = -1 m
F = -kx
F = -(1500) × -1
F = 1500 N
Thus, Spring Constant = 1500 N/m
Problem 2: Calculate the amount of work done to compress a spring having a spring constant of 1000 N/m by 30 m.
Solution:
Work done = (1/2) × k × x2
= (1/2) × 1000 × (30)2 Nm or Joule
= 500 × 900 Joule
= 450000 Joule
Problem 3: A body is moving in a circular motion having a Time Period equal to 10 seconds. Considering the motion of the body along the diameter of the circular path. If the force acting on the body at a displacement from the mean position is 200 N then find the acceleration at that point. (Consider the diameter to be made of spring having spring constant = 100 N/m)
Solution:
Given that, T = 10 seconds
According to Hooke’s law, F = -kx
200 = -(100) * x
x = -2 m [Negative sign indicates that the direction of displacement is opposite to that of force]
Acceleration = -ω2x
ω = 2πf,
where f is the frequency of oscillation given by,
f =1/T
f = (1/10) Hz,
And
ω = 2 × 3.14 × 0.1
= 0.628 radian/second
Acceleration = -(0.628)2 × (-2) m/s2
= 0.788768 m/s2
Problem 4: A body having a mass of 10 Kg has a velocity of 3 m/s after 2 seconds of its staring from the maximum displacement position. If the frequency is (1/8) Hz, find the potential energy and kinetic energy of the body at that point and even find the total energy.
Solution:
Since, K = (1/2) × m × v2
= (1/2) × 10 × 9 J
= 45 J
ω = 2πf
= (2 × 3.14) / 8
= 0.785 radians/second
Instantaneous velocity is given by,
v = A × ω × sin (ωt) (Neglecting the negative sign)
3 = A × (0.785) × sin((π/4) × 2)),
0.785 = (π/4) (approx)
or
A = 3 / 0.785 m
A = 3.8217 m
Total Energy(E) = (1/2) * m * ω2 * A2
= (1/2) * 10 * (0.785)2 * (3.8217)2
= 45 J
Potential Energy(U) = Total Energy(E) – Kinetic Energy(K)
= 45 – 45 J
= 0 J
This indicates that the body is at the mean position.
Problem 5: What is the significance of the Spring Constant? Write the dimension of the Spring Constant.
Solution:
Spring constant of a spring is the amount of force required to stretch or compress the given spring by unit displacement. It is used to compare the stiffness of two springs. The one with greater spring constant has more stiffness i.e. is more difficult to deform compared to the one having lower spring constant.
In other words, the amount of work done to stretch or compress a spring (mass-spring system) is directly proportional to its spring constant. Higher the spring constant, higher the amount of work done to stretch or compress it. Unit of Spring Constant is N/m. And the Dimension of Spring Constant is [M L0 T-2].
Problem 6: Derive the expression for the potential energy of the body under SHM.
Solution:
Derivation of Potential Energy
Force = mass * acceleration
F = m * a
F = m * -ω2 * x
We know that Work done = Force * Displacement, but we cannot use this formula directly in SHM because force is not constant.
dW = F . dx, where dW is the work done for a very small-displacement dx.
dW = (-m * ω2 * x) * dx * cos(180°) [ Cross product of F and dx, as both are opposite to each other hence the angle between them is 180°]
dW = m * ω2 * x * dx
To calculate the work done in moving the particle from O to D, we integrate the above equation between the limits 0 to z:
∫ dW = ∫ m * ω2 * x dx
W = (1/2) * m * ω2 * z2 [On putting the limits]
This in turn is the potential energy of the body.
Problem 7: The frequency of the body moving in Simple Harmonic Motion is 10 Hz. Calculate the force acting on the body at a displacement of 3 m
from the mean position. Mass of the body is 12 Kg.
Solution:
Given,
f = 10 Hz
ω = 2 * π * f
= 2 * 3.14 * 10 radian/second
= 62.8 radian/second
acceleration(a) = -ω 2* x
= -(62.8)2 * 3
= -11831.52 m/s2
Force = mass * acceleration
= 12 * 11831.52 N
Force = 141978.24 N
Problem 8: Force on a body moving in SHM at a displacement of 3 m from the mean position is 200 N. Mass of the body being 50 kg,
find the frequency of oscillation.
Solution:
Given,
F = 200 N
F = m * a
200 = 50 * a
a = 4 m/s2
We know,
a = -ω2 * x
4 = -ω2 * (-3) [Taken x as negative to state that its direction is opposite to that of acceleration or vice versa]
ω = 2 / √(3)
ω = 1.1547 radian/second (approx)
ω = 2 * π * f
f = (1.1547) / (2 * 3.14)
f = 0.1839 Hz (approx)
Problem 9: A body is undergoing SHM with Time Period equals 20 seconds. The mass of the body is 30 kg. Find the force acting on the body at
4 m from the mean position.
Solution:
Given,
T = 20 seconds
T = 2 * π * √(x / a)
20 = 2 * 3.14 * √(4 / a)
a = 0.394 m/s
F = m * a
F = 30 * 0.394 N [Mass = 30 kg]
F = 11.82 N
Problem 10: At what positions do the values of potential energy and kinetic energy are maximum in SHM ?
Solution:
Potential Energy is maximum at the extreme positions i.e. when the value of x is equal to A (amplitude) i.e
when the value of displacement is maximum.
Kinetic Energy is maximum at the equilibrium position because kinetic energy depends on the velocity and
since the velocity is maximum at the equilibrium position (x = 0), hence Kinetic Energy is also maximum.
Problem 11: A body executes SHM having a period of 20 seconds. Three seconds after it passes through its centre of oscillation, its velocity
is found to be 2 m/s. Find the amplitude.
Solution:
We know,
v = -A * ω * sin(ωt), v is the velocity, ω is the angular velocity and t is the time.
Given,
T = 20 seconds
ω = 2 * π * f
= 2 * π * (1 / 20) — f = 1 / T.
Note: We cannot take t = 3 because we have derived all the equations of simple harmonic motion
considering the motion to be starting from extreme position hence we need
to subtract the time from the (time period / 4) to get the actual time.
t = (20 / 4) – 3
= 2
Now,
v = -A * ω * sin(ωt)
2 = -A * (2 * π * (1 / 20)) * sin(2 * π * (1 / 20) * 2)
A = -10.84 m
[Neglecting the minus sign]
Amplitude = 10.84 m.
Problem12: Is the uniform circular motion of a body an example of Simple Harmonic Motion?
Solution:
No, the uniform circular motion of a body is not simple harmonic motion, it is not even an oscillatory motion.
It is a periodic motion.
All simple harmonic motions are periodic motions but all periodic motions are not simple harmonic motions.
If we consider the motion of the body along the diameter of the circle then it is a simple harmonic motion.
Problem 13: Does force acting on a body executing simple harmonic motion dependent on the displacement from the mean position?
Solution:
Yes, force is directly proportional to the displacement from the mean position.
It is zero at the equilibrium position (x = 0) and maximum at the extreme positions where the value of displacement is maximum.
According to Hooke’s law,
F = -kx, where k is the spring constant and x is the displacement from the equilibrium position.
Problem 14: The frequency of oscillation of a body is f. What is the frequency with which its kinetic energy oscillates?
Solution :
As the Kinetic Energy becomes zero and maximum twice in course of one full oscillation hence it oscillates at frequency 2 * f.
Question 15: What is the phase difference between the displacement and acceleration of the particle oscillating in SHM?
Solution:
Zero, there is no phase difference between displacement and acceleration.
priyanshusingh241202
Picked
Class 11
School Learning
School Physics
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n23 Feb, 2022"
},
{
"code": null,
"e": 345,
"s": 54,
"text": "Have you ever wondered why, when we stretch an elastic band and then let it go, it returns to its previous state? It is compelled to revert to its original state by a force. But what exactly is this force? Let us investigate this force and develop the force law for simple harmonic motion. "
},
{
"code": null,
"e": 699,
"s": 345,
"text": "Periodic Motion is something we’re already familiar with. Periodic motion is defined as motion that repeats itself at equal intervals of time. For example, the motion of a clock’s hands, the motion of a car’s wheels, and the motion of a merry-go-round. In nature, all of these motions are repeated. They repeat themselves after a certain period of time."
},
{
"code": null,
"e": 1062,
"s": 699,
"text": "An Oscillatory Motion is a periodic movement in which an item oscillates about its equilibrium position. After a given amount of time, the item repeats the same sequence of moves. An Oscillation is one such series of motions. An oscillatory motion may be seen in the movement of a basic pendulum, the movement of leaves in a breeze, and the movement of a cradle."
},
{
"code": null,
"e": 1281,
"s": 1062,
"text": "Simple harmonic motion is the most basic type of oscillatory motion. When an object moves in a straight path, it exhibits simple harmonic motion. All oscillatory motion examples are instances of basic harmonic motion. "
},
{
"code": null,
"e": 1607,
"s": 1281,
"text": "Swinging a basic pendulum causes it to move away from its mean equilibrium point. When it reaches its extreme position, where it has the greatest displacement, it comes to a halt, and its velocity becomes zero. It returns to its equilibrium position as a result of a force acting in the direction of the equilibrium position."
},
{
"code": null,
"e": 1878,
"s": 1607,
"text": "It now travels through its normal location but does not stop. It shifts to its other extreme position. After that, it returns to its original place. An Oscillation is a type of full motion. A basic pendulum’s swing is an excellent illustration of simple harmonic motion."
},
{
"code": null,
"e": 2153,
"s": 1878,
"text": "Thus, the motion of a body is said to be simply harmonic if the restoring force acting on it is directly proportional to the displacement from the mean position and always tends to oppose it. The direction of the restoring force is opposite to the direction of displacement."
},
{
"code": null,
"e": 2232,
"s": 2153,
"text": "The acceleration of a particle moving in a simple harmonic motion is given by,"
},
{
"code": null,
"e": 2247,
"s": 2232,
"text": "a(t) = -ω2x(t)"
},
{
"code": null,
"e": 2296,
"s": 2247,
"text": "where ω is the angular velocity of the particle."
},
{
"code": null,
"e": 2388,
"s": 2296,
"text": "Let’s now discuss some important terms related to a Simple Harmonic Motion of a particle as"
},
{
"code": null,
"e": 4293,
"s": 2388,
"text": "Displacement (x): Displacement at any instant of time is defined as the net distance travelled by the body executing SHM from its mean or equilibrium position.Amplitude (A): The amplitude of oscillation is defined as the maximum displacement of the body executing SHM on either side of the mean position.Velocity (v): Velocity at any instant is defined as the rate of change of displacement with time. For a body executing SHM, its velocity is maximum at the mean position and minimum (zero) at the extremes. The Velocity of the body is inversely proportional to the displacement from the mean position.Acceleration (a): Acceleration is defined as the rate of change of velocity with time. Unlike velocity, acceleration is directly proportional to displacement. It is maximum at the extreme positions where the displacement is maximum and minimum at the mean position (displacement = 0).Restoring Force (FR): Restoring Force is the force that always acts in a direction opposite to that of displacement but is directly proportional to it. Restoring Force is maximum at the extreme positions and minimum at the mean position.Spring Constant (k): Spring Constant is a constant value for a particular spring that determines the amount of force required to compress or stretch the spring by 1 unit.Energy (E): The total energy of the body under SHM is called mechanical energy, mechanical energy of the body remains constant throughout the motion if the medium is frictionless. The Mechanical Energy of a body at any instant is the sum total of its kinetic and potential energy.Time Period (T): The Time Period of oscillation is defined as the time taken by the body to complete one oscillation. In other words, it is the time taken to cover 4 times the amplitude.Frequency (f): Frequency is defined as the number of oscillations made by the body in one second. It is reciprocal of the time period. f = (1/T)"
},
{
"code": null,
"e": 4453,
"s": 4293,
"text": "Displacement (x): Displacement at any instant of time is defined as the net distance travelled by the body executing SHM from its mean or equilibrium position."
},
{
"code": null,
"e": 4599,
"s": 4453,
"text": "Amplitude (A): The amplitude of oscillation is defined as the maximum displacement of the body executing SHM on either side of the mean position."
},
{
"code": null,
"e": 4899,
"s": 4599,
"text": "Velocity (v): Velocity at any instant is defined as the rate of change of displacement with time. For a body executing SHM, its velocity is maximum at the mean position and minimum (zero) at the extremes. The Velocity of the body is inversely proportional to the displacement from the mean position."
},
{
"code": null,
"e": 5184,
"s": 4899,
"text": "Acceleration (a): Acceleration is defined as the rate of change of velocity with time. Unlike velocity, acceleration is directly proportional to displacement. It is maximum at the extreme positions where the displacement is maximum and minimum at the mean position (displacement = 0)."
},
{
"code": null,
"e": 5422,
"s": 5184,
"text": "Restoring Force (FR): Restoring Force is the force that always acts in a direction opposite to that of displacement but is directly proportional to it. Restoring Force is maximum at the extreme positions and minimum at the mean position."
},
{
"code": null,
"e": 5593,
"s": 5422,
"text": "Spring Constant (k): Spring Constant is a constant value for a particular spring that determines the amount of force required to compress or stretch the spring by 1 unit."
},
{
"code": null,
"e": 5874,
"s": 5593,
"text": "Energy (E): The total energy of the body under SHM is called mechanical energy, mechanical energy of the body remains constant throughout the motion if the medium is frictionless. The Mechanical Energy of a body at any instant is the sum total of its kinetic and potential energy."
},
{
"code": null,
"e": 6061,
"s": 5874,
"text": "Time Period (T): The Time Period of oscillation is defined as the time taken by the body to complete one oscillation. In other words, it is the time taken to cover 4 times the amplitude."
},
{
"code": null,
"e": 6206,
"s": 6061,
"text": "Frequency (f): Frequency is defined as the number of oscillations made by the body in one second. It is reciprocal of the time period. f = (1/T)"
},
{
"code": null,
"e": 6543,
"s": 6206,
"text": "Note: In periodic motion, the direction of restoring force may or may not be in the direction of displacement but in Simple Harmonic Motion (SHM) the direction of restoring force is always opposite to the direction of displacement. This leads to the fact that all Simple Harmonic Motions are periodic motions but vice versa is not true."
},
{
"code": null,
"e": 6829,
"s": 6543,
"text": "Let us use an example to develop the force law for simple harmonic motion. The most basic example of simple harmonic motion is a spring-block system. Consider a mass m block attached to a spring, which is then attached to a stiff wall. The block is supported by a frictionless surface."
},
{
"code": null,
"e": 7042,
"s": 6829,
"text": "The spring is at its equilibrium position when we do not pull it, that is when no force is exerted to it. The net force acting on it is zero in this condition. Let’s try two different things and see what happens."
},
{
"code": null,
"e": 7277,
"s": 7042,
"text": "When we move the block outwards, a force acts on it, attempting to draw it inwards, towards its equilibrium position.When we press the block inwards, a force operating on it tries to push it outwards, towards its equilibrium position."
},
{
"code": null,
"e": 7395,
"s": 7277,
"text": "When we move the block outwards, a force acts on it, attempting to draw it inwards, towards its equilibrium position."
},
{
"code": null,
"e": 7513,
"s": 7395,
"text": "When we press the block inwards, a force operating on it tries to push it outwards, towards its equilibrium position."
},
{
"code": null,
"e": 7786,
"s": 7513,
"text": "In both situations, we can observe that a force is operating on the block to try to return it to its equilibrium position. This force is the restoring force, and it is the foundation of the force law for simple harmonic motion. Let’s figure out how to apply this concept. "
},
{
"code": null,
"e": 7843,
"s": 7786,
"text": "Variation in restoring force with change in displacement"
},
{
"code": null,
"e": 8089,
"s": 7843,
"text": "Let F be the restoring force and x denote the displacement of the block from its equilibrium position. As a result of our observations, we may conclude that the restoring force is directly proportional to the displacement from the mean position."
},
{
"code": null,
"e": 8104,
"s": 8089,
"text": "This implies, "
},
{
"code": null,
"e": 8318,
"s": 8104,
"text": "F = – kx ......(1)"
},
{
"code": null,
"e": 8632,
"s": 8318,
"text": "where k is known as the force constant. It is measured in N/m in the SI system and in dynes/cm in the C.G.S. system. The negative symbol denotes that the restoring force and displacement are always pointing in opposing directions. For simple harmonic motion, equation (1) is the simplest version of the force law."
},
{
"code": null,
"e": 8768,
"s": 8632,
"text": "It demonstrates the fundamental law of simple harmonic motion, which states that force and displacement must be in opposing directions."
},
{
"code": null,
"e": 8788,
"s": 8768,
"text": "We also know that: "
},
{
"code": null,
"e": 8795,
"s": 8788,
"text": "F = ma"
},
{
"code": null,
"e": 8809,
"s": 8795,
"text": "As a result, "
},
{
"code": null,
"e": 8817,
"s": 8809,
"text": "a = F/m"
},
{
"code": null,
"e": 8877,
"s": 8817,
"text": "Substituting the value of F from equation (1) which yields,"
},
{
"code": null,
"e": 9068,
"s": 8877,
"text": "a = – kx/m = – ω2x (where k/m = ω2) ......(2)"
},
{
"code": null,
"e": 9282,
"s": 9068,
"text": "As a result, Equations I and II are the force laws of simple harmonic motion. It should be noted that the restoring force is always directed towards the mean position and in the opposite direction of displacement."
},
{
"code": null,
"e": 9291,
"s": 9282,
"text": "Example:"
},
{
"code": null,
"e": 9371,
"s": 9291,
"text": "If the force required to stretch a spring by 50 cm is 150 N. How much force is"
},
{
"code": null,
"e": 9405,
"s": 9371,
"text": "required to compress it by 35 cm?"
},
{
"code": null,
"e": 9415,
"s": 9405,
"text": "Solution:"
},
{
"code": null,
"e": 9450,
"s": 9415,
"text": "According to Hooke’s law: FR = -kx"
},
{
"code": null,
"e": 9490,
"s": 9450,
"text": " In the first case: x= -50 cm = -0.5 m"
},
{
"code": null,
"e": 9550,
"s": 9490,
"text": "[x is taken negative to indicate that it is opposite to FR]"
},
{
"code": null,
"e": 9586,
"s": 9566,
"text": " FR = 150 N"
},
{
"code": null,
"e": 9627,
"s": 9586,
"text": " k = (- 150/-0.5) N/m "
},
{
"code": null,
"e": 9649,
"s": 9627,
"text": " k = 300 N/m"
},
{
"code": null,
"e": 9671,
"s": 9649,
"text": " In the second case:"
},
{
"code": null,
"e": 9698,
"s": 9671,
"text": " x= 35 cm = 0.35 m"
},
{
"code": null,
"e": 9723,
"s": 9698,
"text": " FR= -300 * 0.35 N"
},
{
"code": null,
"e": 9741,
"s": 9723,
"text": " = -105 N"
},
{
"code": null,
"e": 9763,
"s": 9741,
"text": "Differential Equation"
},
{
"code": null,
"e": 9800,
"s": 9763,
"text": "We know Force = mass * acceleration."
},
{
"code": null,
"e": 9847,
"s": 9800,
"text": "Acceleration (a) of a body in SHM is given by:"
},
{
"code": null,
"e": 9937,
"s": 9847,
"text": "a = d2x/dt2 [Acceleration is the rate of change of velocity, a = (dv/dt) and v = (dx/dt)]"
},
{
"code": null,
"e": 9978,
"s": 9937,
"text": "Force (F) = mass (m) * acceleration (a)."
},
{
"code": null,
"e": 10008,
"s": 9978,
"text": "Now according to Hooke’s law,"
},
{
"code": null,
"e": 10081,
"s": 10008,
"text": "FR = -kx, F = FR [F is the force applied and FR is the restoring force]"
},
{
"code": null,
"e": 10104,
"s": 10081,
"text": "Therefore: -kx = m * a"
},
{
"code": null,
"e": 10141,
"s": 10104,
"text": " -kx = m * d2x / dt2"
},
{
"code": null,
"e": 10183,
"s": 10141,
"text": " d2x / dt2= (-k * x) / m"
},
{
"code": null,
"e": 10283,
"s": 10183,
"text": "Note: Restoring Force is zero at the mean position because at mean position the value of x ix zero."
},
{
"code": null,
"e": 10300,
"s": 10283,
"text": "Work Done in SHM"
},
{
"code": null,
"e": 10398,
"s": 10300,
"text": "Work done = Force * Displacement, you might be thinking that as the applied force is equal to the"
},
{
"code": null,
"e": 10498,
"s": 10398,
"text": "restoring force which is kx (magnitude) and the displacement is x so the work done should be kx2, "
},
{
"code": null,
"e": 10603,
"s": 10498,
"text": "but this is not the case here, we cannot use W = Force * Displacement because this definition or formula"
},
{
"code": null,
"e": 10710,
"s": 10603,
"text": "of work done is applicable only when the force is constant but in SHM, force is a function of displacement"
},
{
"code": null,
"e": 10734,
"s": 10710,
"text": "from the mean position."
},
{
"code": null,
"e": 10781,
"s": 10734,
"text": "The formula for work done in the case of SHM :"
},
{
"code": null,
"e": 10800,
"s": 10781,
"text": "W = (1/2) ∗ k ∗ x2"
},
{
"code": null,
"e": 10807,
"s": 10800,
"text": "Proof:"
},
{
"code": null,
"e": 10827,
"s": 10807,
"text": "For variable force,"
},
{
"code": null,
"e": 10838,
"s": 10827,
"text": "W = ∫ F dx"
},
{
"code": null,
"e": 10859,
"s": 10838,
"text": "W = ∫ kx dx [F = kx]"
},
{
"code": null,
"e": 10878,
"s": 10859,
"text": "W = (1/2) ∗ k ∗ x2"
},
{
"code": null,
"e": 10968,
"s": 10878,
"text": "This is also the formula for the potential energy of the mass-spring system denoted by UX"
},
{
"code": null,
"e": 11022,
"s": 10968,
"text": "Relationship between SHM and uniform circular motion."
},
{
"code": null,
"e": 11152,
"s": 11022,
"text": "The motion of the body is said to be circular if its distance from a fixed point (centre) remains constant throughout the motion."
},
{
"code": null,
"e": 11247,
"s": 11152,
"text": "The circular motion is said to be uniform if the speed of the body in motion remains constant."
},
{
"code": null,
"e": 11378,
"s": 11247,
"text": "Note: Speed remains constant but not the velocity because the direction of motion keeps on changing. Uniform circular motion is an"
},
{
"code": null,
"e": 11398,
"s": 11378,
"text": "accelerated motion."
},
{
"code": null,
"e": 11432,
"s": 11398,
"text": "Uniform Circular Motion of a body"
},
{
"code": null,
"e": 11579,
"s": 11432,
"text": "Considering the figure given above, the projection of the body under uniform circular motion on the diameter is said to be simple harmonic motion."
},
{
"code": null,
"e": 11719,
"s": 11579,
"text": "If we consider the motion of the body sideways it looks as if the body is moving in a straight-line path along the diameter with the centre"
},
{
"code": null,
"e": 11765,
"s": 11719,
"text": "of the circle being the equilibrium position."
},
{
"code": null,
"e": 11785,
"s": 11765,
"text": "Displacement in SHM"
},
{
"code": null,
"e": 11887,
"s": 11785,
"text": "In the figure, ‘θ’ is the angular displacement, ‘x’ is the linear displacement of the body under SHM."
},
{
"code": null,
"e": 11985,
"s": 11887,
"text": " cos θ = Base / Hypotenuse,"
},
{
"code": null,
"e": 12072,
"s": 11985,
"text": " cos θ = OF / OT"
},
{
"code": null,
"e": 12227,
"s": 12072,
"text": " cos θ = x / A, x is the displacement from the mean position and A is the amplitude"
},
{
"code": null,
"e": 12358,
"s": 12227,
"text": " x = A cos θ — Equation of displacement of a body under SHM."
},
{
"code": null,
"e": 12493,
"s": 12358,
"text": " x = A cos(ωt), ω is the angular velocity or frequency, θ = ωt."
},
{
"code": null,
"e": 12591,
"s": 12493,
"text": " x = A cos (2πft), ω = 2πft"
},
{
"code": null,
"e": 12754,
"s": 12591,
"text": "The maximum value of the cosine of any angle is +1 (positive direction) and -1 (negative direction), considering this the maximum value of x can be A (magnitude),"
},
{
"code": null,
"e": 12806,
"s": 12754,
"text": "which is the amplitude of oscillation or vibration."
},
{
"code": null,
"e": 12901,
"s": 12806,
"text": "The equation can also be written in the form of sine of the angular displacement, y = A sin θ."
},
{
"code": null,
"e": 12917,
"s": 12901,
"text": "Velocity in SHM"
},
{
"code": null,
"e": 13000,
"s": 12917,
"text": "As discussed, velocity is defined as the rate of change of displacement with time."
},
{
"code": null,
"e": 13136,
"s": 13000,
"text": " v = d(x) / dt"
},
{
"code": null,
"e": 13281,
"s": 13136,
"text": " v = d(A cos (ωt)) / dt"
},
{
"code": null,
"e": 13424,
"s": 13281,
"text": " v =(-A sin (ωt)) * ω"
},
{
"code": null,
"e": 13593,
"s": 13424,
"text": " v = -V sin (ωt) — Equation of velocity, V= Aω."
},
{
"code": null,
"e": 13727,
"s": 13593,
"text": "‘V’ is the velocity with which the body is revolving in the circular path. Linear Velocity = Angular Velocity * Radius of the circle."
},
{
"code": null,
"e": 13852,
"s": 13727,
"text": "‘ω’ is the angular velocity, ‘A’ is the amplitude which in turn is the radius of the circle, hence we can write ‘V’ in place"
},
{
"code": null,
"e": 13861,
"s": 13852,
"text": "of ‘Aω’."
},
{
"code": null,
"e": 13896,
"s": 13861,
"text": "In △ TOF, sin (ωt) = (TF) / (TO),"
},
{
"code": null,
"e": 14109,
"s": 13896,
"text": " sin (ωt) = √(A2 – x2) / A [By Pythagoras Theorem, Hypotenuse2 = (Perpendicular)2 + (Base)2, TF = √(A2– x2)] "
},
{
"code": null,
"e": 14170,
"s": 14109,
"text": "Replacing the value of sin (ωt) in the equation of velocity,"
},
{
"code": null,
"e": 14247,
"s": 14170,
"text": " v =( -V * √(A2 – x2 )) / A — Another form of equation of velocity."
},
{
"code": null,
"e": 14370,
"s": 14247,
"text": "In the above equation, if the value of x is equal to A i.e. if the displacement is maximum then the value of v is zero and"
},
{
"code": null,
"e": 14465,
"s": 14370,
"text": "if the value of x is zero i.e. if the body is at the mean position then the value of v is max."
},
{
"code": null,
"e": 14561,
"s": 14465,
"text": "‘V’ is the velocity of the body executing uniform circular motion and also the maximum velocity"
},
{
"code": null,
"e": 14607,
"s": 14561,
"text": "of the body executing simple harmonic motion."
},
{
"code": null,
"e": 14627,
"s": 14607,
"text": "Acceleration in SHM"
},
{
"code": null,
"e": 14701,
"s": 14627,
"text": "Acceleration (a) is defined as the rate of change of velocity with time."
},
{
"code": null,
"e": 14842,
"s": 14701,
"text": " v = -A sin (ωt)) * ω — Equation of velocity"
},
{
"code": null,
"e": 14953,
"s": 14842,
"text": " a = d(v) / dt"
},
{
"code": null,
"e": 15080,
"s": 14953,
"text": " a = d((-A sin (ωt)) * ω) / dt"
},
{
"code": null,
"e": 15225,
"s": 15080,
"text": " a= -A cos (ωt) * ω2 — Equation of acceleration"
},
{
"code": null,
"e": 15258,
"s": 15225,
"text": "In △ TOF, cos (ωt) = (OF) / (OT)"
},
{
"code": null,
"e": 15290,
"s": 15258,
"text": " cos (ωt) = x / A"
},
{
"code": null,
"e": 15355,
"s": 15290,
"text": "Replacing the value of cos (ωt) in the equation of acceleration,"
},
{
"code": null,
"e": 15476,
"s": 15355,
"text": " a = (-A * x * ω2 ) / A"
},
{
"code": null,
"e": 15631,
"s": 15476,
"text": " a = – xω2 — Another form of the equation of acceleration"
},
{
"code": null,
"e": 15790,
"s": 15631,
"text": "Considering the above equation, if the value of x is zero then acceleration is also zero which proves the fact that acceleration is zero at the mean position."
},
{
"code": null,
"e": 15895,
"s": 15790,
"text": "On the other hand, if the value of x is maximum i.e. ‘A’ then the value of acceleration is also maximum."
},
{
"code": null,
"e": 16000,
"s": 15895,
"text": " amax = -Aω2 — Equation for maximum acceleration"
},
{
"code": null,
"e": 16019,
"s": 16000,
"text": "Time Period in SHM"
},
{
"code": null,
"e": 16059,
"s": 16019,
"text": "Time Period of Oscillation is given by,"
},
{
"code": null,
"e": 16203,
"s": 16059,
"text": " T = (2πR) / V, 2πR is the circumference of the circle and V is the linear velocity,"
},
{
"code": null,
"e": 16292,
"s": 16203,
"text": " T = (2π) / ω, V = ω * R."
},
{
"code": null,
"e": 16390,
"s": 16292,
"text": " T = (2π) / √(a / x), ω = √(a / x)"
},
{
"code": null,
"e": 16471,
"s": 16390,
"text": " T = (2π) * √(x / a)"
},
{
"code": null,
"e": 16573,
"s": 16471,
"text": "Hence the time period of oscillation is given by Time Period = (2π) * √(displacement / acceleration)."
},
{
"code": null,
"e": 16590,
"s": 16573,
"text": "Frequency in SHM"
},
{
"code": null,
"e": 16682,
"s": 16590,
"text": "Frequency is the total number of vibrations or oscillations made by the body in one second."
},
{
"code": null,
"e": 16846,
"s": 16682,
"text": " f = (1/ Time Period)"
},
{
"code": null,
"e": 17034,
"s": 16846,
"text": " f = (1/2π) * √(acceleration / displacement)"
},
{
"code": null,
"e": 17193,
"s": 17178,
"text": "Kinetic Energy"
},
{
"code": null,
"e": 17251,
"s": 17193,
"text": "This energy of the body is due to the motion of the body."
},
{
"code": null,
"e": 17354,
"s": 17251,
"text": " K = (1/2) * m * v2"
},
{
"code": null,
"e": 17496,
"s": 17354,
"text": " K = (1/2) * m * (ω * √(A2 – x2 ))2, v = ω * √(A2 – x2)"
},
{
"code": null,
"e": 17613,
"s": 17496,
"text": " K = (1/2) * m * ω 2 * (A2 – x2 )"
},
{
"code": null,
"e": 17651,
"s": 17613,
"text": "At x = 0, the value of K is maximum."
},
{
"code": null,
"e": 17737,
"s": 17651,
"text": " Kmax = (1/2) * m * ω 2* (A2)"
},
{
"code": null,
"e": 17770,
"s": 17737,
"text": "At x= A, the value of K is zero."
},
{
"code": null,
"e": 17787,
"s": 17770,
"text": "Potential Energy"
},
{
"code": null,
"e": 17886,
"s": 17787,
"text": "This energy of the body is due to the position of the body or the amount of work done by the body."
},
{
"code": null,
"e": 18069,
"s": 17886,
"text": " U = (1/2) * m * ω2 * x2"
},
{
"code": null,
"e": 18216,
"s": 18069,
"text": "Potential Energy is maximum at the extreme positions where the value of displacement is equal to Amplitude and minimum at the equilibrium position"
},
{
"code": null,
"e": 18248,
"s": 18216,
"text": "where the displacement is zero."
},
{
"code": null,
"e": 18325,
"s": 18248,
"text": " Umax = (1/2) * m * ω 2 * A2"
},
{
"code": null,
"e": 18341,
"s": 18325,
"text": "Simple Pendulum"
},
{
"code": null,
"e": 18422,
"s": 18341,
"text": "Another example of a body executing SHM is a simple pendulum, a simple pendulum"
},
{
"code": null,
"e": 18524,
"s": 18422,
"text": "consists of a bob being suspended from a thread. If we neglect the mass of thread and friction around"
},
{
"code": null,
"e": 18566,
"s": 18524,
"text": "the system then the motion is called SHM."
},
{
"code": null,
"e": 18605,
"s": 18566,
"text": "Forces acting on the bob executing SHM"
},
{
"code": null,
"e": 18641,
"s": 18605,
"text": "Considering the figure given above:"
},
{
"code": null,
"e": 19409,
"s": 18641,
"text": "The effect of mgcosA is cancelled by Force of Tension [F] as both are acting opposite\nto each other. This is why the bob is having zero movement in the vertical direction.\nThe restoring force is being generated due to mgsinA which is in the direction opposite\nto that of displacement.\n\nFR = -mgsin(∠A), now if the angular displacement i.e. ∠A is very small then\n∠A = sin(∠A) [Unit of angle is radian]\nTherefore, FR = -mg∠A, now ∠A =x/l where x is the linear displacement of the bob\nfrom the mean position and l is the length of the rope or thread used.\nSubstituting the value of ∠A, we get:\n FR = -mg(x/l) \nThe expression states that the restoring force is directly proportional and opposite in direction\nto the displacement from the mean position."
},
{
"code": null,
"e": 19593,
"s": 19409,
"text": "Problem 1: The amount of force required to stretch a spring by 10 cm is 150 N. How much force is required to stretch the spring by 100 cm? Calculate the spring constant of the spring."
},
{
"code": null,
"e": 19603,
"s": 19593,
"text": "Solution:"
},
{
"code": null,
"e": 19712,
"s": 19603,
"text": "As long as the external force is applied on the body, the restoring and the applied force are the same, then"
},
{
"code": null,
"e": 19720,
"s": 19712,
"text": "F = -kx"
},
{
"code": null,
"e": 19755,
"s": 19720,
"text": "Since, it is given that, F = 150 N"
},
{
"code": null,
"e": 19836,
"s": 19755,
"text": "x = -10 cm = – 0.1 m (Taking x negative because we have taken force as positive)"
},
{
"code": null,
"e": 19874,
"s": 19836,
"text": "Therefore, k = (150 / 0.1) = 1500 N/m"
},
{
"code": null,
"e": 19898,
"s": 19874,
"text": "Now, x = -100 cm = -1 m"
},
{
"code": null,
"e": 19906,
"s": 19898,
"text": "F = -kx"
},
{
"code": null,
"e": 19923,
"s": 19906,
"text": "F = -(1500) × -1"
},
{
"code": null,
"e": 19934,
"s": 19923,
"text": "F = 1500 N"
},
{
"code": null,
"e": 19967,
"s": 19934,
"text": "Thus, Spring Constant = 1500 N/m"
},
{
"code": null,
"e": 20079,
"s": 19967,
"text": "Problem 2: Calculate the amount of work done to compress a spring having a spring constant of 1000 N/m by 30 m."
},
{
"code": null,
"e": 20089,
"s": 20079,
"text": "Solution:"
},
{
"code": null,
"e": 20116,
"s": 20089,
"text": "Work done = (1/2) × k × x2"
},
{
"code": null,
"e": 20170,
"s": 20116,
"text": " = (1/2) × 1000 × (30)2 Nm or Joule"
},
{
"code": null,
"e": 20207,
"s": 20170,
"text": " = 500 × 900 Joule"
},
{
"code": null,
"e": 20250,
"s": 20207,
"text": " = 450000 Joule "
},
{
"code": null,
"e": 20619,
"s": 20250,
"text": "Problem 3: A body is moving in a circular motion having a Time Period equal to 10 seconds. Considering the motion of the body along the diameter of the circular path. If the force acting on the body at a displacement from the mean position is 200 N then find the acceleration at that point. (Consider the diameter to be made of spring having spring constant = 100 N/m)"
},
{
"code": null,
"e": 20631,
"s": 20619,
"text": "Solution: "
},
{
"code": null,
"e": 20658,
"s": 20631,
"text": "Given that, T = 10 seconds"
},
{
"code": null,
"e": 20692,
"s": 20658,
"text": "According to Hooke’s law, F = -kx"
},
{
"code": null,
"e": 20709,
"s": 20692,
"text": "200 = -(100) * x"
},
{
"code": null,
"e": 20808,
"s": 20709,
"text": "x = -2 m [Negative sign indicates that the direction of displacement is opposite to that of force]"
},
{
"code": null,
"e": 20828,
"s": 20808,
"text": "Acceleration = -ω2x"
},
{
"code": null,
"e": 20838,
"s": 20828,
"text": "ω = 2πf, "
},
{
"code": null,
"e": 20889,
"s": 20838,
"text": "where f is the frequency of oscillation given by, "
},
{
"code": null,
"e": 20896,
"s": 20889,
"text": "f =1/T"
},
{
"code": null,
"e": 20912,
"s": 20896,
"text": "f = (1/10) Hz, "
},
{
"code": null,
"e": 20916,
"s": 20912,
"text": "And"
},
{
"code": null,
"e": 20935,
"s": 20916,
"text": "ω = 2 × 3.14 × 0.1"
},
{
"code": null,
"e": 20961,
"s": 20935,
"text": " = 0.628 radian/second"
},
{
"code": null,
"e": 20998,
"s": 20961,
"text": "Acceleration = -(0.628)2 × (-2) m/s2"
},
{
"code": null,
"e": 21040,
"s": 20998,
"text": " = 0.788768 m/s2"
},
{
"code": null,
"e": 21313,
"s": 21040,
"text": "Problem 4: A body having a mass of 10 Kg has a velocity of 3 m/s after 2 seconds of its staring from the maximum displacement position. If the frequency is (1/8) Hz, find the potential energy and kinetic energy of the body at that point and even find the total energy. "
},
{
"code": null,
"e": 21326,
"s": 21313,
"text": "Solution: "
},
{
"code": null,
"e": 21352,
"s": 21326,
"text": "Since, K = (1/2) × m × v2"
},
{
"code": null,
"e": 21391,
"s": 21352,
"text": " = (1/2) × 10 × 9 J"
},
{
"code": null,
"e": 21418,
"s": 21391,
"text": " = 45 J"
},
{
"code": null,
"e": 21428,
"s": 21418,
"text": " ω = 2πf"
},
{
"code": null,
"e": 21451,
"s": 21428,
"text": " = (2 × 3.14) / 8"
},
{
"code": null,
"e": 21480,
"s": 21451,
"text": " = 0.785 radians/second"
},
{
"code": null,
"e": 21516,
"s": 21480,
"text": "Instantaneous velocity is given by,"
},
{
"code": null,
"e": 21665,
"s": 21516,
"text": "v = A × ω × sin (ωt) (Neglecting the negative sign)"
},
{
"code": null,
"e": 21702,
"s": 21665,
"text": "3 = A × (0.785) × sin((π/4) × 2)), "
},
{
"code": null,
"e": 21725,
"s": 21702,
"text": "0.785 = (π/4) (approx)"
},
{
"code": null,
"e": 21728,
"s": 21725,
"text": "or"
},
{
"code": null,
"e": 21744,
"s": 21728,
"text": "A = 3 / 0.785 m"
},
{
"code": null,
"e": 21757,
"s": 21744,
"text": "A = 3.8217 m"
},
{
"code": null,
"e": 21796,
"s": 21757,
"text": "Total Energy(E) = (1/2) * m * ω2 * A2 "
},
{
"code": null,
"e": 21857,
"s": 21796,
"text": " = (1/2) * 10 * (0.785)2 * (3.8217)2"
},
{
"code": null,
"e": 21889,
"s": 21857,
"text": " = 45 J"
},
{
"code": null,
"e": 21947,
"s": 21889,
"text": "Potential Energy(U) = Total Energy(E) – Kinetic Energy(K)"
},
{
"code": null,
"e": 21991,
"s": 21947,
"text": " = 45 – 45 J"
},
{
"code": null,
"e": 22030,
"s": 21991,
"text": " = 0 J"
},
{
"code": null,
"e": 22084,
"s": 22030,
"text": "This indicates that the body is at the mean position."
},
{
"code": null,
"e": 22188,
"s": 22084,
"text": "Problem 5: What is the significance of the Spring Constant? Write the dimension of the Spring Constant."
},
{
"code": null,
"e": 22198,
"s": 22188,
"text": "Solution:"
},
{
"code": null,
"e": 22512,
"s": 22198,
"text": "Spring constant of a spring is the amount of force required to stretch or compress the given spring by unit displacement. It is used to compare the stiffness of two springs. The one with greater spring constant has more stiffness i.e. is more difficult to deform compared to the one having lower spring constant. "
},
{
"code": null,
"e": 22824,
"s": 22512,
"text": "In other words, the amount of work done to stretch or compress a spring (mass-spring system) is directly proportional to its spring constant. Higher the spring constant, higher the amount of work done to stretch or compress it. Unit of Spring Constant is N/m. And the Dimension of Spring Constant is [M L0 T-2]."
},
{
"code": null,
"e": 22905,
"s": 22824,
"text": "Problem 6: Derive the expression for the potential energy of the body under SHM."
},
{
"code": null,
"e": 22915,
"s": 22905,
"text": "Solution:"
},
{
"code": null,
"e": 22946,
"s": 22915,
"text": "Derivation of Potential Energy"
},
{
"code": null,
"e": 23666,
"s": 22946,
"text": " Force = mass * acceleration\n F = m * a\n F = m * -ω2 * x\nWe know that Work done = Force * Displacement, but we cannot use this formula directly in SHM because force is not constant.\n dW = F . dx, where dW is the work done for a very small-displacement dx.\n dW = (-m * ω2 * x) * dx * cos(180°) [ Cross product of F and dx, as both are opposite to each other hence the angle between them is 180°]\n dW = m * ω2 * x * dx\nTo calculate the work done in moving the particle from O to D, we integrate the above equation between the limits 0 to z:\n ∫ dW = ∫ m * ω2 * x dx\n W = (1/2) * m * ω2 * z2 [On putting the limits]\nThis in turn is the potential energy of the body."
},
{
"code": null,
"e": 23810,
"s": 23666,
"text": "Problem 7: The frequency of the body moving in Simple Harmonic Motion is 10 Hz. Calculate the force acting on the body at a displacement of 3 m"
},
{
"code": null,
"e": 23861,
"s": 23810,
"text": "from the mean position. Mass of the body is 12 Kg."
},
{
"code": null,
"e": 23871,
"s": 23861,
"text": "Solution:"
},
{
"code": null,
"e": 23891,
"s": 23871,
"text": " Given,"
},
{
"code": null,
"e": 23926,
"s": 23891,
"text": " f = 10 Hz"
},
{
"code": null,
"e": 23965,
"s": 23926,
"text": " ω = 2 * π * f"
},
{
"code": null,
"e": 24024,
"s": 23965,
"text": " = 2 * 3.14 * 10 radian/second"
},
{
"code": null,
"e": 24074,
"s": 24024,
"text": " = 62.8 radian/second"
},
{
"code": null,
"e": 24123,
"s": 24074,
"text": " acceleration(a) = -ω 2* x"
},
{
"code": null,
"e": 24177,
"s": 24123,
"text": " = -(62.8)2 * 3"
},
{
"code": null,
"e": 24233,
"s": 24177,
"text": " = -11831.52 m/s2"
},
{
"code": null,
"e": 24282,
"s": 24233,
"text": " Force = mass * acceleration"
},
{
"code": null,
"e": 24327,
"s": 24282,
"text": " = 12 * 11831.52 N"
},
{
"code": null,
"e": 24368,
"s": 24327,
"text": " Force = 141978.24 N"
},
{
"code": null,
"e": 24497,
"s": 24368,
"text": "Problem 8: Force on a body moving in SHM at a displacement of 3 m from the mean position is 200 N. Mass of the body being 50 kg,"
},
{
"code": null,
"e": 24532,
"s": 24497,
"text": "find the frequency of oscillation."
},
{
"code": null,
"e": 24542,
"s": 24532,
"text": "Solution:"
},
{
"code": null,
"e": 24563,
"s": 24542,
"text": " Given,"
},
{
"code": null,
"e": 24598,
"s": 24563,
"text": " F = 200 N"
},
{
"code": null,
"e": 24633,
"s": 24598,
"text": " F = m * a"
},
{
"code": null,
"e": 24670,
"s": 24633,
"text": " 200 = 50 * a"
},
{
"code": null,
"e": 24706,
"s": 24670,
"text": " a = 4 m/s2"
},
{
"code": null,
"e": 24731,
"s": 24706,
"text": " We know,"
},
{
"code": null,
"e": 24770,
"s": 24731,
"text": " a = -ω2 * x"
},
{
"code": null,
"e": 24912,
"s": 24770,
"text": " 4 = -ω2 * (-3) [Taken x as negative to state that its direction is opposite to that of acceleration or vice versa]"
},
{
"code": null,
"e": 24952,
"s": 24912,
"text": " ω = 2 / √(3)"
},
{
"code": null,
"e": 25013,
"s": 24952,
"text": " ω = 1.1547 radian/second (approx)"
},
{
"code": null,
"e": 25054,
"s": 25013,
"text": " ω = 2 * π * f"
},
{
"code": null,
"e": 25107,
"s": 25054,
"text": " f = (1.1547) / (2 * 3.14)"
},
{
"code": null,
"e": 25157,
"s": 25107,
"text": " f = 0.1839 Hz (approx)"
},
{
"code": null,
"e": 25297,
"s": 25157,
"text": "Problem 9: A body is undergoing SHM with Time Period equals 20 seconds. The mass of the body is 30 kg. Find the force acting on the body at"
},
{
"code": null,
"e": 25325,
"s": 25297,
"text": "4 m from the mean position."
},
{
"code": null,
"e": 25335,
"s": 25325,
"text": "Solution:"
},
{
"code": null,
"e": 25361,
"s": 25335,
"text": " Given,"
},
{
"code": null,
"e": 25403,
"s": 25361,
"text": " T = 20 seconds"
},
{
"code": null,
"e": 25451,
"s": 25403,
"text": " T = 2 * π * √(x / a)"
},
{
"code": null,
"e": 25503,
"s": 25451,
"text": " 20 = 2 * 3.14 * √(4 / a)"
},
{
"code": null,
"e": 25544,
"s": 25503,
"text": " a = 0.394 m/s"
},
{
"code": null,
"e": 25581,
"s": 25544,
"text": " F = m * a"
},
{
"code": null,
"e": 25640,
"s": 25581,
"text": " F = 30 * 0.394 N [Mass = 30 kg]"
},
{
"code": null,
"e": 25679,
"s": 25640,
"text": " F = 11.82 N"
},
{
"code": null,
"e": 25798,
"s": 25679,
"text": " Problem 10: At what positions do the values of potential energy and kinetic energy are maximum in SHM ? "
},
{
"code": null,
"e": 25808,
"s": 25798,
"text": "Solution:"
},
{
"code": null,
"e": 25928,
"s": 25808,
"text": " Potential Energy is maximum at the extreme positions i.e. when the value of x is equal to A (amplitude) i.e"
},
{
"code": null,
"e": 25983,
"s": 25928,
"text": " when the value of displacement is maximum."
},
{
"code": null,
"e": 26100,
"s": 25983,
"text": " Kinetic Energy is maximum at the equilibrium position because kinetic energy depends on the velocity and"
},
{
"code": null,
"e": 26219,
"s": 26100,
"text": " since the velocity is maximum at the equilibrium position (x = 0), hence Kinetic Energy is also maximum. "
},
{
"code": null,
"e": 26364,
"s": 26219,
"text": " Problem 11: A body executes SHM having a period of 20 seconds. Three seconds after it passes through its centre of oscillation, its velocity"
},
{
"code": null,
"e": 26406,
"s": 26364,
"text": "is found to be 2 m/s. Find the amplitude."
},
{
"code": null,
"e": 26420,
"s": 26406,
"text": "Solution: "
},
{
"code": null,
"e": 26438,
"s": 26420,
"text": " We know,"
},
{
"code": null,
"e": 26541,
"s": 26438,
"text": " v = -A * ω * sin(ωt), v is the velocity, ω is the angular velocity and t is the time."
},
{
"code": null,
"e": 26565,
"s": 26541,
"text": " Given,"
},
{
"code": null,
"e": 26604,
"s": 26565,
"text": " T = 20 seconds"
},
{
"code": null,
"e": 26642,
"s": 26604,
"text": " ω = 2 * π * f"
},
{
"code": null,
"e": 26701,
"s": 26642,
"text": " = 2 * π * (1 / 20) — f = 1 / T."
},
{
"code": null,
"e": 26812,
"s": 26701,
"text": " Note: We cannot take t = 3 because we have derived all the equations of simple harmonic motion"
},
{
"code": null,
"e": 26909,
"s": 26812,
"text": " considering the motion to be starting from extreme position hence we need"
},
{
"code": null,
"e": 27003,
"s": 26909,
"text": " to subtract the time from the (time period / 4) to get the actual time."
},
{
"code": null,
"e": 27043,
"s": 27003,
"text": " t = (20 / 4) – 3"
},
{
"code": null,
"e": 27073,
"s": 27043,
"text": " = 2"
},
{
"code": null,
"e": 27099,
"s": 27073,
"text": " Now,"
},
{
"code": null,
"e": 27145,
"s": 27099,
"text": " v = -A * ω * sin(ωt)"
},
{
"code": null,
"e": 27226,
"s": 27145,
"text": " 2 = -A * (2 * π * (1 / 20)) * sin(2 * π * (1 / 20) * 2)"
},
{
"code": null,
"e": 27265,
"s": 27226,
"text": " A = -10.84 m"
},
{
"code": null,
"e": 27318,
"s": 27265,
"text": " [Neglecting the minus sign]"
},
{
"code": null,
"e": 27364,
"s": 27318,
"text": " Amplitude = 10.84 m."
},
{
"code": null,
"e": 27454,
"s": 27364,
"text": "Problem12: Is the uniform circular motion of a body an example of Simple Harmonic Motion?"
},
{
"code": null,
"e": 27464,
"s": 27454,
"text": "Solution:"
},
{
"code": null,
"e": 27592,
"s": 27464,
"text": " No, the uniform circular motion of a body is not simple harmonic motion, it is not even an oscillatory motion."
},
{
"code": null,
"e": 27634,
"s": 27592,
"text": " It is a periodic motion."
},
{
"code": null,
"e": 27758,
"s": 27634,
"text": " All simple harmonic motions are periodic motions but all periodic motions are not simple harmonic motions."
},
{
"code": null,
"e": 27882,
"s": 27758,
"text": " If we consider the motion of the body along the diameter of the circle then it is a simple harmonic motion."
},
{
"code": null,
"e": 28011,
"s": 27882,
"text": "Problem 13: Does force acting on a body executing simple harmonic motion dependent on the displacement from the mean position?"
},
{
"code": null,
"e": 28021,
"s": 28011,
"text": "Solution:"
},
{
"code": null,
"e": 28111,
"s": 28021,
"text": " Yes, force is directly proportional to the displacement from the mean position."
},
{
"code": null,
"e": 28249,
"s": 28111,
"text": " It is zero at the equilibrium position (x = 0) and maximum at the extreme positions where the value of displacement is maximum."
},
{
"code": null,
"e": 28293,
"s": 28249,
"text": " According to Hooke’s law,"
},
{
"code": null,
"e": 28432,
"s": 28293,
"text": " F = -kx, where k is the spring constant and x is the displacement from the equilibrium position."
},
{
"code": null,
"e": 28554,
"s": 28432,
"text": "Problem 14: The frequency of oscillation of a body is f. What is the frequency with which its kinetic energy oscillates?"
},
{
"code": null,
"e": 28568,
"s": 28554,
"text": " Solution :"
},
{
"code": null,
"e": 28714,
"s": 28568,
"text": " As the Kinetic Energy becomes zero and maximum twice in course of one full oscillation hence it oscillates at frequency 2 * f."
},
{
"code": null,
"e": 28834,
"s": 28714,
"text": "Question 15: What is the phase difference between the displacement and acceleration of the particle oscillating in SHM?"
},
{
"code": null,
"e": 28844,
"s": 28834,
"text": "Solution:"
},
{
"code": null,
"e": 28935,
"s": 28844,
"text": " Zero, there is no phase difference between displacement and acceleration."
},
{
"code": null,
"e": 28956,
"s": 28935,
"text": "priyanshusingh241202"
},
{
"code": null,
"e": 28963,
"s": 28956,
"text": "Picked"
},
{
"code": null,
"e": 28972,
"s": 28963,
"text": "Class 11"
},
{
"code": null,
"e": 28988,
"s": 28972,
"text": "School Learning"
},
{
"code": null,
"e": 29003,
"s": 28988,
"text": "School Physics"
}
] |
Java.util.concurrent.RecursiveTask class in Java with Examples
|
28 Jun, 2019
RecursiveTask is an abstract class encapsulates a task that returns a result. It is a subclass of ForkJoinTask. The RecursiveTask class is extended to create a task that has a particular return type. The code that represents the computational portion of the task is kept within the compute() method of RecursiveTask.
RecursiveTask class is mostly used in the context of parallel programming. Tasks that can be divided into independent subtasks and the final outcome of the task can be obtained from the outcomes of the subtask, can be implemented more efficiently using RecursiveTask. For example, searching for an element in a large array.
Class Hierarchy
java.lang.Object
↳ java.util.concurrent.ForkJoinTask
↳ java.util.concurrent.RecursiveTask<V>
Constructor
RecursiveTask()– Creates an object of RecursiveTask with default settings.public RecursiveTask()
RecursiveTask()– Creates an object of RecursiveTask with default settings.public RecursiveTask()
public RecursiveTask()
Methods
compute()– The method that defines the task.protected abstract void compute()
exec()– This method implements the basic rules necessary for the execution of a task.protected final boolean exec()
getRawResult()– The function returns the value obtained after the completion of the task, even if the task is completed abnormally. It returns null, if the task is not yet completed.public final Void getRawResult()
setRawResult()– The function sets the return value of the task to the value passed in the argument.protected final void setRawResult(Void mustBeNull)
compute()– The method that defines the task.protected abstract void compute()
protected abstract void compute()
exec()– This method implements the basic rules necessary for the execution of a task.protected final boolean exec()
protected final boolean exec()
getRawResult()– The function returns the value obtained after the completion of the task, even if the task is completed abnormally. It returns null, if the task is not yet completed.public final Void getRawResult()
public final Void getRawResult()
setRawResult()– The function sets the return value of the task to the value passed in the argument.protected final void setRawResult(Void mustBeNull)
protected final void setRawResult(Void mustBeNull)
Example to demonstrate RecursiveTask
import java.util.concurrent.ForkJoinPool;import java.util.concurrent.RecursiveTask; public class RecursiveTaskDemo { public static void main(String[] args) { ForkJoinPool fjp = new ForkJoinPool(); double[] nums = new double[5000]; for (int i = 0; i < nums.length; i++) { nums[i] = (double)(((i % 2) == 0) ? i : -1); } Sum task = new Sum(nums, 0, nums.length); double summation = fjp.invoke(task); System.out.println("Summation " + summation); }} class Sum extends RecursiveTask<Double> { final int seqThreshold = 500; double[] data; int start, end; Sum(double[] data, int start, int end) { this.data = data; this.start = start; this.end = end; } @Override protected Double compute() { double sum = 0; if ((end - start) < seqThreshold) { for (int i = start; i < end; i++) sum += data[i]; } else { int middle = (start + end) / 2; Sum subtaskA = new Sum(data, start, middle); Sum subtaskB = new Sum(data, middle, end); subtaskA.fork(); subtaskB.fork(); sum += subtaskA.join() + subtaskB.join(); } return sum; }}
Summation 6245000.0
Reference: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/RecursiveTask.html
Java - util package
Java-concurrent-package
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": "\n28 Jun, 2019"
},
{
"code": null,
"e": 345,
"s": 28,
"text": "RecursiveTask is an abstract class encapsulates a task that returns a result. It is a subclass of ForkJoinTask. The RecursiveTask class is extended to create a task that has a particular return type. The code that represents the computational portion of the task is kept within the compute() method of RecursiveTask."
},
{
"code": null,
"e": 669,
"s": 345,
"text": "RecursiveTask class is mostly used in the context of parallel programming. Tasks that can be divided into independent subtasks and the final outcome of the task can be obtained from the outcomes of the subtask, can be implemented more efficiently using RecursiveTask. For example, searching for an element in a large array."
},
{
"code": null,
"e": 685,
"s": 669,
"text": "Class Hierarchy"
},
{
"code": null,
"e": 781,
"s": 685,
"text": "java.lang.Object\n↳ java.util.concurrent.ForkJoinTask\n ↳ java.util.concurrent.RecursiveTask<V>\n"
},
{
"code": null,
"e": 793,
"s": 781,
"text": "Constructor"
},
{
"code": null,
"e": 891,
"s": 793,
"text": "RecursiveTask()– Creates an object of RecursiveTask with default settings.public RecursiveTask()\n"
},
{
"code": null,
"e": 989,
"s": 891,
"text": "RecursiveTask()– Creates an object of RecursiveTask with default settings.public RecursiveTask()\n"
},
{
"code": null,
"e": 1013,
"s": 989,
"text": "public RecursiveTask()\n"
},
{
"code": null,
"e": 1021,
"s": 1013,
"text": "Methods"
},
{
"code": null,
"e": 1581,
"s": 1021,
"text": "compute()– The method that defines the task.protected abstract void compute()\nexec()– This method implements the basic rules necessary for the execution of a task.protected final boolean exec()\ngetRawResult()– The function returns the value obtained after the completion of the task, even if the task is completed abnormally. It returns null, if the task is not yet completed.public final Void getRawResult()\nsetRawResult()– The function sets the return value of the task to the value passed in the argument.protected final void setRawResult(Void mustBeNull)\n"
},
{
"code": null,
"e": 1660,
"s": 1581,
"text": "compute()– The method that defines the task.protected abstract void compute()\n"
},
{
"code": null,
"e": 1695,
"s": 1660,
"text": "protected abstract void compute()\n"
},
{
"code": null,
"e": 1812,
"s": 1695,
"text": "exec()– This method implements the basic rules necessary for the execution of a task.protected final boolean exec()\n"
},
{
"code": null,
"e": 1844,
"s": 1812,
"text": "protected final boolean exec()\n"
},
{
"code": null,
"e": 2060,
"s": 1844,
"text": "getRawResult()– The function returns the value obtained after the completion of the task, even if the task is completed abnormally. It returns null, if the task is not yet completed.public final Void getRawResult()\n"
},
{
"code": null,
"e": 2094,
"s": 2060,
"text": "public final Void getRawResult()\n"
},
{
"code": null,
"e": 2245,
"s": 2094,
"text": "setRawResult()– The function sets the return value of the task to the value passed in the argument.protected final void setRawResult(Void mustBeNull)\n"
},
{
"code": null,
"e": 2297,
"s": 2245,
"text": "protected final void setRawResult(Void mustBeNull)\n"
},
{
"code": null,
"e": 2334,
"s": 2297,
"text": "Example to demonstrate RecursiveTask"
},
{
"code": "import java.util.concurrent.ForkJoinPool;import java.util.concurrent.RecursiveTask; public class RecursiveTaskDemo { public static void main(String[] args) { ForkJoinPool fjp = new ForkJoinPool(); double[] nums = new double[5000]; for (int i = 0; i < nums.length; i++) { nums[i] = (double)(((i % 2) == 0) ? i : -1); } Sum task = new Sum(nums, 0, nums.length); double summation = fjp.invoke(task); System.out.println(\"Summation \" + summation); }} class Sum extends RecursiveTask<Double> { final int seqThreshold = 500; double[] data; int start, end; Sum(double[] data, int start, int end) { this.data = data; this.start = start; this.end = end; } @Override protected Double compute() { double sum = 0; if ((end - start) < seqThreshold) { for (int i = start; i < end; i++) sum += data[i]; } else { int middle = (start + end) / 2; Sum subtaskA = new Sum(data, start, middle); Sum subtaskB = new Sum(data, middle, end); subtaskA.fork(); subtaskB.fork(); sum += subtaskA.join() + subtaskB.join(); } return sum; }}",
"e": 3611,
"s": 2334,
"text": null
},
{
"code": null,
"e": 3632,
"s": 3611,
"text": "Summation 6245000.0\n"
},
{
"code": null,
"e": 3725,
"s": 3632,
"text": "Reference: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/RecursiveTask.html"
},
{
"code": null,
"e": 3745,
"s": 3725,
"text": "Java - util package"
},
{
"code": null,
"e": 3769,
"s": 3745,
"text": "Java-concurrent-package"
},
{
"code": null,
"e": 3774,
"s": 3769,
"text": "Java"
},
{
"code": null,
"e": 3779,
"s": 3774,
"text": "Java"
}
] |
Constructors in C++
|
11 Jul, 2022
Constructor in C++ is a special method that is invoked automatically at the time of object creation. It is used to initialize the data members of new objects generally. The constructor in C++ has the same name as the class or structure. Constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object which is why it is known as constructors.
Constructor does not have a return value, hence they do not have a return type.
The prototype of Constructors is as follows:
<class-name> (list-of-parameters);
Constructors can be defined inside or outside the class declaration:-
The syntax for defining the constructor within the class:
<class-name> (list-of-parameters) { // constructor definition }
The syntax for defining the constructor outside the class:
<class-name>: :<class-name> (list-of-parameters){ // constructor definition}
Example
C++
// defining the constructor within the class #include <iostream>using namespace std; class student { int rno; char name[10]; double fee; public: student() { cout << "Enter the RollNo:"; cin >> rno; cout << "Enter the Name:"; cin >> name; cout << "Enter the Fee:"; cin >> fee; } void display() { cout << endl << rno << "\t" << name << "\t" << fee; }}; int main(){ student s; // constructor gets called automatically when // we create the object of the class s.display(); return 0;}
Enter the RollNo:Enter the Name:Enter the Fee:
0 6.95303e-310
Example
C++
// defining the constructor outside the class #include <iostream>using namespace std;class student { int rno; char name[50]; double fee; public: student(); void display();}; student::student(){ cout << "Enter the RollNo:"; cin >> rno; cout << "Enter the Name:"; cin >> name; cout << "Enter the Fee:"; cin >> fee;} void student::display(){ cout << endl << rno << "\t" << name << "\t" << fee;} int main(){ student s; s.display(); return 0;}
Output:
Enter the RollNo: 30
Enter the Name: ram
Enter the Fee: 20000
30 ram 20000
How constructors are different from a normal member function?
C++
#include <iostream>using namespace std; class Line { public: void setLength( double len ); double getLength( void ); Line( double len ); //This is the constructor private: double length;};//Member function definition including constructorLine::Line( double len ) { cout<<"Object is being created , length ="<< len <<endl; length = len;}void Line::setLength( double len ) { length = len;}double Line::getLength( void ) { return length;}//Main function for the program int main() { Line line(10.0); //get initially set length cout<<"Length of line :" << line.getLength() << endl; //set line length again line.setLength(6.0); cout<<"Length of line :" << line.getLength() << endl; return 0;}
A constructor is different from normal functions in following ways:
Constructor has same name as the class itself
Default Constructors don’t have input argument however, Copy and Parameterized Constructors have input arguments
Constructors don’t have return type
A constructor is automatically called when an object is created.
It must be placed in public section of class.
If we do not specify a constructor, C++ compiler generates a default constructor for object (expects no parameters and has an empty body).
Let us understand the types of constructors in C++ by taking a real-world example. Suppose you went to a shop to buy a marker. When you want to buy a marker, what are the options. The first one you go to a shop and say give me a marker. So just saying give me a marker mean that you did not set which brand name and which color, you didn’t mention anything just say you want a marker. So when we said just I want a marker so whatever the frequently sold marker is there in the market or in his shop he will simply hand over that. And this is what a default constructor is! The second method is you go to a shop and say I want a marker a red in color and XYZ brand. So you are mentioning this and he will give you that marker. So in this case you have given the parameters. And this is what a parameterized constructor is! Then the third one you go to a shop and say I want a marker like this(a physical marker on your hand). So the shopkeeper will see that marker. Okay, and he will give a new marker for you. So copy of that marker. And that’s what a copy constructor is!
The name of the constructor is the same as its class name.
Constructors are mostly declared in the public section of the class though it can be declared in the private section of the class.
Constructors do not return values; hence they do not have a return type.
A constructor gets called automatically when we create the object of the class.
Constructors can be overloaded.
Constructor can not be declared virtual.
1. Default Constructors: Default constructor is the constructor which doesn’t take any argument. It has no parameters. It is also called a zero-argument constructor.
CPP
// Cpp program to illustrate the// concept of Constructors#include <iostream>using namespace std; class construct {public: int a, b; // Default Constructor construct() { a = 10; b = 20; }}; int main(){ // Default constructor called automatically // when the object is created construct c; cout << "a: " << c.a << endl << "b: " << c.b; return 1;}
a: 10
b: 20
Note: Even if we do not define any constructor explicitly, the compiler will automatically provide a default constructor implicitly.
C++
// Example #include<iostream>using namespace std;class student{ int rno; char name[50]; double fee; public: student() // Explicit Default constructor { cout<<"Enter the RollNo:"; cin>>rno; cout<<"Enter the Name:"; cin>>name; cout<<"Enter the Fee:"; cin>>fee; } void display() { cout<<endl<<rno<<"\t"<<name<<"\t"<<fee; }}; int main(){ student s; s.display(); return 0;}
2. Parameterized Constructors: It is possible to pass arguments to constructors. Typically, these arguments help initialize an object when it is created. To create a parameterized constructor, simply add parameters to it the way you would to any other function. When you define the constructor’s body, use the parameters to initialize the object.
Note: when the parameterized constructor is defined and no default constructor is defined explicitly, the compiler will not implicitly call the default constructor and hence creating a simple object as
Student s;
Will flash an error
CPP
// CPP program to illustrate// parameterized constructors#include <iostream>using namespace std; class Point {private: int x, y; public: // Parameterized Constructor Point(int x1, int y1) { x = x1; y = y1; } int getX() { return x; } int getY() { return y; }}; int main(){ // Constructor called Point p1(10, 15); // Access values assigned by constructor cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY(); return 0;}
p1.x = 10, p1.y = 15
C++
// Example #include<iostream>#include<string.h>using namespace std; class student{ int rno; char name[50]; double fee; public: student(int,char[],double); void display(); }; student::student(int no,char n[],double f){ rno=no; strcpy(name,n); fee=f;} void student::display(){ cout<<endl<<rno<<"\t"<<name<<"\t"<<fee;} int main(){ student s(1001,"Ram",10000); s.display(); return 0;}
When an object is declared in a parameterized constructor, the initial values have to be passed as arguments to the constructor function. The normal way of object declaration may not work. The constructors can be called explicitly or implicitly.
Example e = Example(0, 50); // Explicit call
Example e(0, 50); // Implicit call
Uses of Parameterized constructor: It is used to initialize the various data elements of different objects with different values when they are created.It is used to overload constructors.
It is used to initialize the various data elements of different objects with different values when they are created.It is used to overload constructors.
It is used to initialize the various data elements of different objects with different values when they are created.
It is used to overload constructors.
Can we have more than one constructor in a class? Yes, It is called Constructor Overloading.
A copy constructor is a member function that initializes an object using another object of the same class. A detailed article on Copy Constructor.
Whenever we define one or more non-default constructors( with parameters ) for a class, a default constructor( without parameters ) should also be explicitly defined as the compiler will not provide a default constructor in this case. However, it is not necessary but it’s considered to be the best practice to always define a default constructor.
Copy constructor takes a reference to an object of the same class as an argument.
Sample(Sample &t)
{
id=t.id;
}
CPP
// Illustration#include <iostream>using namespace std; class point {private: double x, y; public: // Non-default Constructor & // default Constructor point(double px, double py) { x = px, y = py; }}; int main(void){ // Define an array of size // 10 & of type point // This line will cause error point a[10]; // Remove above line and program // will compile without error point b = point(5, 6);}
Output:
Error: point (double px, double py): expects 2 arguments, 0 provided
C++
// Implicit copy constructor #include<iostream>using namespace std; class Sample{ int id; public: void init(int x) { id=x; } void display() { cout<<endl<<"ID="<<id; }}; int main(){ Sample obj1; obj1.init(10); obj1.display(); Sample obj2(obj1); //or obj2=obj1; obj2.display(); return 0;}
ID=10
ID=10
C++
// Example: Explicit copy constructor #include <iostream>using namespace std; class Sample{ int id; public: void init(int x) { id=x; } Sample(){} //default constructor with empty body Sample(Sample &t) //copy constructor { id=t.id; } void display() { cout<<endl<<"ID="<<id; }};int main(){ Sample obj1; obj1.init(10); obj1.display(); Sample obj2(obj1); //or obj2=obj1; copy constructor called obj2.display(); return 0;}
ID=10
ID=10
C++
#include<iostream>#include<string.h>using namespace std;class student{ int rno; char name[50]; double fee; public: student(int,char[],double); student(student &t) //copy constructor { rno=t.rno; strcpy(name,t.name); fee=t.fee; } void display(); }; student::student(int no,char n[],double f) { rno=no; strcpy(name,n); fee=f; } void student::display() { cout<<endl<<rno<<"\t"<<name<<"\t"<<fee; } int main(){ student s(1001,"Manjeet",10000); s.display(); student manjeet(s); //copy constructor called manjeet.display(); return 0;}
C++
#include<iostream>#include<string.h>using namespace std;class student{ int rno; char name[50]; double fee; public: student(int,char[],double); student(student &t) //copy constructor (member wise initialization) { rno=t.rno; strcpy(name,t.name); } void display(); void disp() { cout<<endl<<rno<<"\t"<<name; } }; student::student(int no, char n[],double f) { rno=no; strcpy(name,n); fee=f; } void student::display() { cout<<endl<<rno<<"\t"<<name<<"\t"<<fee; } int main(){ student s(1001,"Manjeet",10000); s.display(); student manjeet(s); //copy constructor called manjeet.disp(); return 0;}
A destructor is also a special member function as a constructor. Destructor destroys the class objects created by the constructor. Destructor has the same name as their class name preceded by a tiled (~) symbol. It is not possible to define more than one destructor. The destructor is only one way to destroy the object created by the constructor. Hence destructor can-not be overloaded. Destructor neither requires any argument nor returns any value. It is automatically called when the object goes out of scope. Destructors release memory space occupied by the objects created by the constructor. In destructor, objects are destroyed in the reverse of object creation.
The syntax for defining the destructor within the class
~ <class-name>()
{
}
The syntax for defining the destructor outside the class
<class-name>: : ~ <class-name>(){}
C++
#include <iostream>using namespace std; class Test {public: Test() { cout << "\n Constructor executed"; } ~Test() { cout << "\n Destructor executed"; }};main(){ Test t; return 0;}
Constructor executed
Destructor executed
C++
#include <iostream>using namespace std;class Test {public: Test() { cout << "\n Constructor executed"; } ~Test() { cout << "\n Destructor executed"; }}; main(){ Test t, t1, t2, t3; return 0;}
Constructor executed
Constructor executed
Constructor executed
Constructor executed
Destructor executed
Destructor executed
Destructor executed
Destructor executed
C++
#include <iostream>using namespace std;int count = 0;class Test {public: Test() { count++; cout << "\n No. of Object created:\t" << count; } ~Test() { cout << "\n No. of Object destroyed:\t" << count; --count; }}; main(){ Test t, t1, t2, t3; return 0;}
No. of Object created: 1
No. of Object created: 2
No. of Object created: 3
No. of Object created: 4
No. of Object destroyed: 4
No. of Object destroyed: 3
No. of Object destroyed: 2
No. of Object destroyed: 1
1. Destructor is invoked automatically by the compiler when its corresponding constructor goes out of scope and releases the memory space that is no longer required by the program.2. Destructor neither requires any argument nor returns any value therefore it cannot be overloaded.3. Destructor cannot be declared as static and const;4. Destructor should be declared in the public section of the program.5. Destructor is called in the reverse order of its constructor invocation.
Q: What are the functions that are generated by the compiler by default, if we do not provide them explicitly?Ans: he functions that are generated by the compiler by default if we do not provide them explicitly are:I. Default constructorII. Copy constructorIII. Assignment operatorIV. Destructor
Related Articles :
Destructors in C++
quiz on constructors in C++
Output of C++ programs | Set 26 (Constructors)
Output of C++ programs | Set 27(Constructors and Destructors)
Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above
ashish2021
AmiyaRanjanRout
prathamjainyt
utkarshgupta04092003
12chiranth
apredator409
niranjanhebli
aditiyadav20102001
thekingsld4o1
cpp-constructor
C++
School Programming
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n11 Jul, 2022"
},
{
"code": null,
"e": 445,
"s": 52,
"text": "Constructor in C++ is a special method that is invoked automatically at the time of object creation. It is used to initialize the data members of new objects generally. The constructor in C++ has the same name as the class or structure. Constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object which is why it is known as constructors."
},
{
"code": null,
"e": 525,
"s": 445,
"text": "Constructor does not have a return value, hence they do not have a return type."
},
{
"code": null,
"e": 570,
"s": 525,
"text": "The prototype of Constructors is as follows:"
},
{
"code": null,
"e": 605,
"s": 570,
"text": "<class-name> (list-of-parameters);"
},
{
"code": null,
"e": 675,
"s": 605,
"text": "Constructors can be defined inside or outside the class declaration:-"
},
{
"code": null,
"e": 733,
"s": 675,
"text": "The syntax for defining the constructor within the class:"
},
{
"code": null,
"e": 797,
"s": 733,
"text": "<class-name> (list-of-parameters) { // constructor definition }"
},
{
"code": null,
"e": 856,
"s": 797,
"text": "The syntax for defining the constructor outside the class:"
},
{
"code": null,
"e": 933,
"s": 856,
"text": "<class-name>: :<class-name> (list-of-parameters){ // constructor definition}"
},
{
"code": null,
"e": 941,
"s": 933,
"text": "Example"
},
{
"code": null,
"e": 945,
"s": 941,
"text": "C++"
},
{
"code": "// defining the constructor within the class #include <iostream>using namespace std; class student { int rno; char name[10]; double fee; public: student() { cout << \"Enter the RollNo:\"; cin >> rno; cout << \"Enter the Name:\"; cin >> name; cout << \"Enter the Fee:\"; cin >> fee; } void display() { cout << endl << rno << \"\\t\" << name << \"\\t\" << fee; }}; int main(){ student s; // constructor gets called automatically when // we create the object of the class s.display(); return 0;}",
"e": 1533,
"s": 945,
"text": null
},
{
"code": null,
"e": 1602,
"s": 1533,
"text": "Enter the RollNo:Enter the Name:Enter the Fee:\n0 6.95303e-310"
},
{
"code": null,
"e": 1611,
"s": 1602,
"text": "Example "
},
{
"code": null,
"e": 1615,
"s": 1611,
"text": "C++"
},
{
"code": "// defining the constructor outside the class #include <iostream>using namespace std;class student { int rno; char name[50]; double fee; public: student(); void display();}; student::student(){ cout << \"Enter the RollNo:\"; cin >> rno; cout << \"Enter the Name:\"; cin >> name; cout << \"Enter the Fee:\"; cin >> fee;} void student::display(){ cout << endl << rno << \"\\t\" << name << \"\\t\" << fee;} int main(){ student s; s.display(); return 0;}",
"e": 2110,
"s": 1615,
"text": null
},
{
"code": null,
"e": 2119,
"s": 2110,
"text": "Output: "
},
{
"code": null,
"e": 2194,
"s": 2119,
"text": "Enter the RollNo: 30\nEnter the Name: ram\nEnter the Fee: 20000\n30 ram 20000"
},
{
"code": null,
"e": 2256,
"s": 2194,
"text": "How constructors are different from a normal member function?"
},
{
"code": null,
"e": 2260,
"s": 2256,
"text": "C++"
},
{
"code": "#include <iostream>using namespace std; class Line { public: void setLength( double len ); double getLength( void ); Line( double len ); //This is the constructor private: double length;};//Member function definition including constructorLine::Line( double len ) { cout<<\"Object is being created , length =\"<< len <<endl; length = len;}void Line::setLength( double len ) { length = len;}double Line::getLength( void ) { return length;}//Main function for the program int main() { Line line(10.0); //get initially set length cout<<\"Length of line :\" << line.getLength() << endl; //set line length again line.setLength(6.0); cout<<\"Length of line :\" << line.getLength() << endl; return 0;} ",
"e": 3005,
"s": 2260,
"text": null
},
{
"code": null,
"e": 3074,
"s": 3005,
"text": "A constructor is different from normal functions in following ways: "
},
{
"code": null,
"e": 3120,
"s": 3074,
"text": "Constructor has same name as the class itself"
},
{
"code": null,
"e": 3233,
"s": 3120,
"text": "Default Constructors don’t have input argument however, Copy and Parameterized Constructors have input arguments"
},
{
"code": null,
"e": 3269,
"s": 3233,
"text": "Constructors don’t have return type"
},
{
"code": null,
"e": 3334,
"s": 3269,
"text": "A constructor is automatically called when an object is created."
},
{
"code": null,
"e": 3380,
"s": 3334,
"text": "It must be placed in public section of class."
},
{
"code": null,
"e": 3519,
"s": 3380,
"text": "If we do not specify a constructor, C++ compiler generates a default constructor for object (expects no parameters and has an empty body)."
},
{
"code": null,
"e": 4592,
"s": 3519,
"text": "Let us understand the types of constructors in C++ by taking a real-world example. Suppose you went to a shop to buy a marker. When you want to buy a marker, what are the options. The first one you go to a shop and say give me a marker. So just saying give me a marker mean that you did not set which brand name and which color, you didn’t mention anything just say you want a marker. So when we said just I want a marker so whatever the frequently sold marker is there in the market or in his shop he will simply hand over that. And this is what a default constructor is! The second method is you go to a shop and say I want a marker a red in color and XYZ brand. So you are mentioning this and he will give you that marker. So in this case you have given the parameters. And this is what a parameterized constructor is! Then the third one you go to a shop and say I want a marker like this(a physical marker on your hand). So the shopkeeper will see that marker. Okay, and he will give a new marker for you. So copy of that marker. And that’s what a copy constructor is!"
},
{
"code": null,
"e": 4651,
"s": 4592,
"text": "The name of the constructor is the same as its class name."
},
{
"code": null,
"e": 4782,
"s": 4651,
"text": "Constructors are mostly declared in the public section of the class though it can be declared in the private section of the class."
},
{
"code": null,
"e": 4855,
"s": 4782,
"text": "Constructors do not return values; hence they do not have a return type."
},
{
"code": null,
"e": 4935,
"s": 4855,
"text": "A constructor gets called automatically when we create the object of the class."
},
{
"code": null,
"e": 4967,
"s": 4935,
"text": "Constructors can be overloaded."
},
{
"code": null,
"e": 5008,
"s": 4967,
"text": "Constructor can not be declared virtual."
},
{
"code": null,
"e": 5174,
"s": 5008,
"text": "1. Default Constructors: Default constructor is the constructor which doesn’t take any argument. It has no parameters. It is also called a zero-argument constructor."
},
{
"code": null,
"e": 5178,
"s": 5174,
"text": "CPP"
},
{
"code": "// Cpp program to illustrate the// concept of Constructors#include <iostream>using namespace std; class construct {public: int a, b; // Default Constructor construct() { a = 10; b = 20; }}; int main(){ // Default constructor called automatically // when the object is created construct c; cout << \"a: \" << c.a << endl << \"b: \" << c.b; return 1;}",
"e": 5572,
"s": 5178,
"text": null
},
{
"code": null,
"e": 5584,
"s": 5572,
"text": "a: 10\nb: 20"
},
{
"code": null,
"e": 5717,
"s": 5584,
"text": "Note: Even if we do not define any constructor explicitly, the compiler will automatically provide a default constructor implicitly."
},
{
"code": null,
"e": 5721,
"s": 5717,
"text": "C++"
},
{
"code": "// Example #include<iostream>using namespace std;class student{ int rno; char name[50]; double fee; public: student() // Explicit Default constructor { cout<<\"Enter the RollNo:\"; cin>>rno; cout<<\"Enter the Name:\"; cin>>name; cout<<\"Enter the Fee:\"; cin>>fee; } void display() { cout<<endl<<rno<<\"\\t\"<<name<<\"\\t\"<<fee; }}; int main(){ student s; s.display(); return 0;}",
"e": 6214,
"s": 5721,
"text": null
},
{
"code": null,
"e": 6562,
"s": 6214,
"text": "2. Parameterized Constructors: It is possible to pass arguments to constructors. Typically, these arguments help initialize an object when it is created. To create a parameterized constructor, simply add parameters to it the way you would to any other function. When you define the constructor’s body, use the parameters to initialize the object. "
},
{
"code": null,
"e": 6764,
"s": 6562,
"text": "Note: when the parameterized constructor is defined and no default constructor is defined explicitly, the compiler will not implicitly call the default constructor and hence creating a simple object as"
},
{
"code": null,
"e": 6795,
"s": 6764,
"text": "Student s;\nWill flash an error"
},
{
"code": null,
"e": 6799,
"s": 6795,
"text": "CPP"
},
{
"code": "// CPP program to illustrate// parameterized constructors#include <iostream>using namespace std; class Point {private: int x, y; public: // Parameterized Constructor Point(int x1, int y1) { x = x1; y = y1; } int getX() { return x; } int getY() { return y; }}; int main(){ // Constructor called Point p1(10, 15); // Access values assigned by constructor cout << \"p1.x = \" << p1.getX() << \", p1.y = \" << p1.getY(); return 0;}",
"e": 7290,
"s": 6799,
"text": null
},
{
"code": null,
"e": 7311,
"s": 7290,
"text": "p1.x = 10, p1.y = 15"
},
{
"code": null,
"e": 7315,
"s": 7311,
"text": "C++"
},
{
"code": "// Example #include<iostream>#include<string.h>using namespace std; class student{ int rno; char name[50]; double fee; public: student(int,char[],double); void display(); }; student::student(int no,char n[],double f){ rno=no; strcpy(name,n); fee=f;} void student::display(){ cout<<endl<<rno<<\"\\t\"<<name<<\"\\t\"<<fee;} int main(){ student s(1001,\"Ram\",10000); s.display(); return 0;}",
"e": 7757,
"s": 7315,
"text": null
},
{
"code": null,
"e": 8003,
"s": 7757,
"text": "When an object is declared in a parameterized constructor, the initial values have to be passed as arguments to the constructor function. The normal way of object declaration may not work. The constructors can be called explicitly or implicitly."
},
{
"code": null,
"e": 8096,
"s": 8003,
"text": " Example e = Example(0, 50); // Explicit call\n\n Example e(0, 50); // Implicit call"
},
{
"code": null,
"e": 8284,
"s": 8096,
"text": "Uses of Parameterized constructor: It is used to initialize the various data elements of different objects with different values when they are created.It is used to overload constructors."
},
{
"code": null,
"e": 8437,
"s": 8284,
"text": "It is used to initialize the various data elements of different objects with different values when they are created.It is used to overload constructors."
},
{
"code": null,
"e": 8554,
"s": 8437,
"text": "It is used to initialize the various data elements of different objects with different values when they are created."
},
{
"code": null,
"e": 8591,
"s": 8554,
"text": "It is used to overload constructors."
},
{
"code": null,
"e": 8690,
"s": 8591,
"text": "Can we have more than one constructor in a class? Yes, It is called Constructor Overloading."
},
{
"code": null,
"e": 8837,
"s": 8690,
"text": "A copy constructor is a member function that initializes an object using another object of the same class. A detailed article on Copy Constructor."
},
{
"code": null,
"e": 9186,
"s": 8837,
"text": "Whenever we define one or more non-default constructors( with parameters ) for a class, a default constructor( without parameters ) should also be explicitly defined as the compiler will not provide a default constructor in this case. However, it is not necessary but it’s considered to be the best practice to always define a default constructor. "
},
{
"code": null,
"e": 9268,
"s": 9186,
"text": "Copy constructor takes a reference to an object of the same class as an argument."
},
{
"code": null,
"e": 9340,
"s": 9268,
"text": "Sample(Sample &t)\n {\n id=t.id;\n }"
},
{
"code": null,
"e": 9344,
"s": 9340,
"text": "CPP"
},
{
"code": "// Illustration#include <iostream>using namespace std; class point {private: double x, y; public: // Non-default Constructor & // default Constructor point(double px, double py) { x = px, y = py; }}; int main(void){ // Define an array of size // 10 & of type point // This line will cause error point a[10]; // Remove above line and program // will compile without error point b = point(5, 6);}",
"e": 9779,
"s": 9344,
"text": null
},
{
"code": null,
"e": 9788,
"s": 9779,
"text": "Output: "
},
{
"code": null,
"e": 9857,
"s": 9788,
"text": "Error: point (double px, double py): expects 2 arguments, 0 provided"
},
{
"code": null,
"e": 9861,
"s": 9857,
"text": "C++"
},
{
"code": "// Implicit copy constructor #include<iostream>using namespace std; class Sample{ int id; public: void init(int x) { id=x; } void display() { cout<<endl<<\"ID=\"<<id; }}; int main(){ Sample obj1; obj1.init(10); obj1.display(); Sample obj2(obj1); //or obj2=obj1; obj2.display(); return 0;}",
"e": 10228,
"s": 9861,
"text": null
},
{
"code": null,
"e": 10240,
"s": 10228,
"text": "ID=10\nID=10"
},
{
"code": null,
"e": 10244,
"s": 10240,
"text": "C++"
},
{
"code": "// Example: Explicit copy constructor #include <iostream>using namespace std; class Sample{ int id; public: void init(int x) { id=x; } Sample(){} //default constructor with empty body Sample(Sample &t) //copy constructor { id=t.id; } void display() { cout<<endl<<\"ID=\"<<id; }};int main(){ Sample obj1; obj1.init(10); obj1.display(); Sample obj2(obj1); //or obj2=obj1; copy constructor called obj2.display(); return 0;}",
"e": 10766,
"s": 10244,
"text": null
},
{
"code": null,
"e": 10778,
"s": 10766,
"text": "ID=10\nID=10"
},
{
"code": null,
"e": 10782,
"s": 10778,
"text": "C++"
},
{
"code": "#include<iostream>#include<string.h>using namespace std;class student{ int rno; char name[50]; double fee; public: student(int,char[],double); student(student &t) //copy constructor { rno=t.rno; strcpy(name,t.name); fee=t.fee; } void display(); }; student::student(int no,char n[],double f) { rno=no; strcpy(name,n); fee=f; } void student::display() { cout<<endl<<rno<<\"\\t\"<<name<<\"\\t\"<<fee; } int main(){ student s(1001,\"Manjeet\",10000); s.display(); student manjeet(s); //copy constructor called manjeet.display(); return 0;}",
"e": 11462,
"s": 10782,
"text": null
},
{
"code": null,
"e": 11466,
"s": 11462,
"text": "C++"
},
{
"code": "#include<iostream>#include<string.h>using namespace std;class student{ int rno; char name[50]; double fee; public: student(int,char[],double); student(student &t) //copy constructor (member wise initialization) { rno=t.rno; strcpy(name,t.name); } void display(); void disp() { cout<<endl<<rno<<\"\\t\"<<name; } }; student::student(int no, char n[],double f) { rno=no; strcpy(name,n); fee=f; } void student::display() { cout<<endl<<rno<<\"\\t\"<<name<<\"\\t\"<<fee; } int main(){ student s(1001,\"Manjeet\",10000); s.display(); student manjeet(s); //copy constructor called manjeet.disp(); return 0;}",
"e": 12222,
"s": 11466,
"text": null
},
{
"code": null,
"e": 12894,
"s": 12222,
"text": "A destructor is also a special member function as a constructor. Destructor destroys the class objects created by the constructor. Destructor has the same name as their class name preceded by a tiled (~) symbol. It is not possible to define more than one destructor. The destructor is only one way to destroy the object created by the constructor. Hence destructor can-not be overloaded. Destructor neither requires any argument nor returns any value. It is automatically called when the object goes out of scope. Destructors release memory space occupied by the objects created by the constructor. In destructor, objects are destroyed in the reverse of object creation."
},
{
"code": null,
"e": 12950,
"s": 12894,
"text": "The syntax for defining the destructor within the class"
},
{
"code": null,
"e": 13003,
"s": 12950,
"text": " ~ <class-name>()\n {\n }"
},
{
"code": null,
"e": 13060,
"s": 13003,
"text": "The syntax for defining the destructor outside the class"
},
{
"code": null,
"e": 13095,
"s": 13060,
"text": "<class-name>: : ~ <class-name>(){}"
},
{
"code": null,
"e": 13099,
"s": 13095,
"text": "C++"
},
{
"code": "#include <iostream>using namespace std; class Test {public: Test() { cout << \"\\n Constructor executed\"; } ~Test() { cout << \"\\n Destructor executed\"; }};main(){ Test t; return 0;}",
"e": 13296,
"s": 13099,
"text": null
},
{
"code": null,
"e": 13339,
"s": 13296,
"text": " Constructor executed\n Destructor executed"
},
{
"code": null,
"e": 13343,
"s": 13339,
"text": "C++"
},
{
"code": "#include <iostream>using namespace std;class Test {public: Test() { cout << \"\\n Constructor executed\"; } ~Test() { cout << \"\\n Destructor executed\"; }}; main(){ Test t, t1, t2, t3; return 0;}",
"e": 13550,
"s": 13343,
"text": null
},
{
"code": null,
"e": 13722,
"s": 13550,
"text": " Constructor executed\n Constructor executed\n Constructor executed\n Constructor executed\n Destructor executed\n Destructor executed\n Destructor executed\n Destructor executed"
},
{
"code": null,
"e": 13726,
"s": 13722,
"text": "C++"
},
{
"code": "#include <iostream>using namespace std;int count = 0;class Test {public: Test() { count++; cout << \"\\n No. of Object created:\\t\" << count; } ~Test() { cout << \"\\n No. of Object destroyed:\\t\" << count; --count; }}; main(){ Test t, t1, t2, t3; return 0;}",
"e": 14034,
"s": 13726,
"text": null
},
{
"code": null,
"e": 14274,
"s": 14034,
"text": " No. of Object created: 1\n No. of Object created: 2\n No. of Object created: 3\n No. of Object created: 4\n No. of Object destroyed: 4\n No. of Object destroyed: 3\n No. of Object destroyed: 2\n No. of Object destroyed: 1"
},
{
"code": null,
"e": 14754,
"s": 14274,
"text": "1. Destructor is invoked automatically by the compiler when its corresponding constructor goes out of scope and releases the memory space that is no longer required by the program.2. Destructor neither requires any argument nor returns any value therefore it cannot be overloaded.3. Destructor cannot be declared as static and const;4. Destructor should be declared in the public section of the program.5. Destructor is called in the reverse order of its constructor invocation."
},
{
"code": null,
"e": 15050,
"s": 14754,
"text": "Q: What are the functions that are generated by the compiler by default, if we do not provide them explicitly?Ans: he functions that are generated by the compiler by default if we do not provide them explicitly are:I. Default constructorII. Copy constructorIII. Assignment operatorIV. Destructor"
},
{
"code": null,
"e": 15070,
"s": 15050,
"text": "Related Articles : "
},
{
"code": null,
"e": 15089,
"s": 15070,
"text": "Destructors in C++"
},
{
"code": null,
"e": 15117,
"s": 15089,
"text": "quiz on constructors in C++"
},
{
"code": null,
"e": 15164,
"s": 15117,
"text": "Output of C++ programs | Set 26 (Constructors)"
},
{
"code": null,
"e": 15226,
"s": 15164,
"text": "Output of C++ programs | Set 27(Constructors and Destructors)"
},
{
"code": null,
"e": 15353,
"s": 15226,
"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": 15364,
"s": 15353,
"text": "ashish2021"
},
{
"code": null,
"e": 15380,
"s": 15364,
"text": "AmiyaRanjanRout"
},
{
"code": null,
"e": 15394,
"s": 15380,
"text": "prathamjainyt"
},
{
"code": null,
"e": 15415,
"s": 15394,
"text": "utkarshgupta04092003"
},
{
"code": null,
"e": 15426,
"s": 15415,
"text": "12chiranth"
},
{
"code": null,
"e": 15439,
"s": 15426,
"text": "apredator409"
},
{
"code": null,
"e": 15453,
"s": 15439,
"text": "niranjanhebli"
},
{
"code": null,
"e": 15472,
"s": 15453,
"text": "aditiyadav20102001"
},
{
"code": null,
"e": 15486,
"s": 15472,
"text": "thekingsld4o1"
},
{
"code": null,
"e": 15502,
"s": 15486,
"text": "cpp-constructor"
},
{
"code": null,
"e": 15506,
"s": 15502,
"text": "C++"
},
{
"code": null,
"e": 15525,
"s": 15506,
"text": "School Programming"
},
{
"code": null,
"e": 15529,
"s": 15525,
"text": "CPP"
}
] |
Streamlit – Introduction and Setup
|
23 Oct, 2020
Streamlit is an open source app framework in python language. It helps us create beautiful web-apps for data science and machine learning in a little time. It is compatible with major python libraries such as scikit-learn, keras, pytorch, latex, numpy, pandas, matplotlib, etc.. Syntax for installing this library is shown below.
Install StreamLit –In the command-prompt type
pip install streamlit
Creating a Simple application (Hello World) –
The 'hello, world!' script in Streamlit:
streamlit hello
# to run your python script
streamlit run myFirstStreamlitApp.py
You can stop running your app any time using Ctrl + C.
Advantages: 1. It embraces python-scripting. 2. Less code is needed to create amazing web-apps. 3. No callbacks are needed since widgets are treated as variables. 4. Data caching simplifies and speeds up computation pipelines.
Disadvantages: 1. Streamlit’s Data caching cannot keep track of changes to the data happening outside the function body.
Some of its basic functions are described here.
1. Adding a Title
# myFirstStreamlitApp.py #import the libraryimport streamlit as stl # add title to your appstl.title("Geeks for Geeks")
Output:
2. Adding some text
# myFirstStreamlitApp.py #import the libraryimport streamlit as stl # add title to your appstl.title("Geeks for Geeks") #adding text to your appstl.write("A Computer Science portal for Geeks")
Output:
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 | datetime.timedelta() function
Python | Get unique values from a list
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Oct, 2020"
},
{
"code": null,
"e": 359,
"s": 28,
"text": "Streamlit is an open source app framework in python language. It helps us create beautiful web-apps for data science and machine learning in a little time. It is compatible with major python libraries such as scikit-learn, keras, pytorch, latex, numpy, pandas, matplotlib, etc.. Syntax for installing this library is shown below. "
},
{
"code": null,
"e": 407,
"s": 361,
"text": "Install StreamLit –In the command-prompt type"
},
{
"code": null,
"e": 430,
"s": 407,
"text": "pip install streamlit\n"
},
{
"code": null,
"e": 476,
"s": 430,
"text": "Creating a Simple application (Hello World) –"
},
{
"code": null,
"e": 599,
"s": 476,
"text": "The 'hello, world!' script in Streamlit:\nstreamlit hello\n\n# to run your python script\nstreamlit run myFirstStreamlitApp.py"
},
{
"code": null,
"e": 655,
"s": 599,
"text": "You can stop running your app any time using Ctrl + C. "
},
{
"code": null,
"e": 883,
"s": 655,
"text": "Advantages: 1. It embraces python-scripting. 2. Less code is needed to create amazing web-apps. 3. No callbacks are needed since widgets are treated as variables. 4. Data caching simplifies and speeds up computation pipelines. "
},
{
"code": null,
"e": 1005,
"s": 883,
"text": "Disadvantages: 1. Streamlit’s Data caching cannot keep track of changes to the data happening outside the function body. "
},
{
"code": null,
"e": 1054,
"s": 1005,
"text": "Some of its basic functions are described here. "
},
{
"code": null,
"e": 1074,
"s": 1054,
"text": "1. Adding a Title "
},
{
"code": "# myFirstStreamlitApp.py #import the libraryimport streamlit as stl # add title to your appstl.title(\"Geeks for Geeks\")",
"e": 1196,
"s": 1074,
"text": null
},
{
"code": null,
"e": 1206,
"s": 1196,
"text": "Output: "
},
{
"code": null,
"e": 1228,
"s": 1206,
"text": "2. Adding some text "
},
{
"code": "# myFirstStreamlitApp.py #import the libraryimport streamlit as stl # add title to your appstl.title(\"Geeks for Geeks\") #adding text to your appstl.write(\"A Computer Science portal for Geeks\")",
"e": 1424,
"s": 1228,
"text": null
},
{
"code": null,
"e": 1434,
"s": 1424,
"text": "Output: "
},
{
"code": null,
"e": 1443,
"s": 1436,
"text": "Python"
},
{
"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": 1573,
"s": 1541,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1600,
"s": 1573,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1621,
"s": 1600,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1644,
"s": 1621,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1675,
"s": 1644,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1731,
"s": 1675,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1773,
"s": 1731,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1815,
"s": 1773,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1854,
"s": 1815,
"text": "Python | datetime.timedelta() function"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.