title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Reversing an Equation | 17 Jun, 2022
Given a mathematical equation using numbers/variables and +, -, *, /. Print the equation in reverse.
Examples:
Input : 20 - 3 + 5 * 2
Output : 2 * 5 + 3 - 20
Input : 25 + 3 - 2 * 11
Output : 11 * 2 - 3 + 25
Input : a + b * c - d / e
Output : e / d - c * b + a
Approach : The approach to this problem is simple. We iterate the string from left to right and as soon we strike a symbol we insert the number and the symbol in the beginning of the resultant string.
C++
Java
C#
Python3
// C++ program to reverse an equation#include <bits/stdc++.h>using namespace std; // Function to reverse order of wordsstring reverseEquation(string s){ // Resultant string string result; int j = 0; for (int i = 0; i < s.length(); i++) { // A space marks the end of the word if (s[i] == '+' || s[i] == '-' || s[i] == '/' || s[i] == '*') { // insert the word at the beginning // of the result string result.insert(result.begin(), s.begin() + j, s.begin() + i); j = i + 1; // insert the symbol result.insert(result.begin(), s[i]); } } // insert the last word in the string // to the result string result.insert(result.begin(), s.begin() + j, s.end()); return result;} // driver codeint main(){ string s = "a+b*c-d/e"; cout << reverseEquation(s) << endl; return 0;}
// Java program to reverse an equationimport java.util.*; class GFG{ // Function to reverse order of wordspublic static String reverseEquation(String s){ // Resultant string String result = "", str = ""; int j = 0; for(int i = 0; i < s.length(); i++) { // A space marks the end of the word if (s.charAt(i) == '+' || s.charAt(i) == '-' || s.charAt(i) == '/' || s.charAt(i) == '*') { // Insert the word at the beginning // of the result string result = s.charAt(i) + str + result; str = ""; } else { str += s.charAt(i); } } result = str + result; return result;} // Driver codepublic static void main(String args[]){ String s = "a+b*c-d/e"; System.out.println(reverseEquation(s));}} // This code is contributed by bolliranadheer
// C# program to reverse an equationusing System;using System.Text; public class GFG{ // Function to reverse order of words public static string reverseEquation(string s) { // Resultant string string result = "", str = ""; for(int i = 0; i < s.Length; i++) { // A space marks the end of the word if (s[i] == '+' || s[i] == '-' || s[i] == '/' || s[i] == '*') { // Insert the word at the beginning // of the result string result = s[i] + str + result; str = ""; } else { str += s[i]; } } result = str + result; return result; } // Driver Code static public void Main (){ string s = "a+b*c-d/e"; Console.Write(reverseEquation(s)); }} // This code is contributed by shruti456rawal
# Python3 Program to reverse an equation# Function to reverse order of wordsdef reverseEquation(s): # Reverse String result="" for i in range(len(s)): # A space marks the end of the word if(s[i]=='+' or s[i]=='-' or s[i]=='/' or s[i]=='*'): # insert the word at the beginning # of the result String result = s[i] + result # insert the symbol else: result = s[i] + result return result # Driver Codes = "a+b*c-d/e"print(reverseEquation(s)) # This code is contributed by simranjenny84
Output:
e/d-c*b+a
Time Complexity: O(N)
Auxiliary Space: O(1)
This article is contributed by Raghav Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Akanksha_Rai
simranjenny84
bolliranadheer
tarakki100
shruti456rawal
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n17 Jun, 2022"
},
{
"code": null,
"e": 154,
"s": 53,
"text": "Given a mathematical equation using numbers/variables and +, -, *, /. Print the equation in reverse."
},
{
"code": null,
"e": 166,
"s": 154,
"text": "Examples: "
},
{
"code": null,
"e": 317,
"s": 166,
"text": "Input : 20 - 3 + 5 * 2\nOutput : 2 * 5 + 3 - 20\n\nInput : 25 + 3 - 2 * 11\nOutput : 11 * 2 - 3 + 25\n\nInput : a + b * c - d / e\nOutput : e / d - c * b + a"
},
{
"code": null,
"e": 518,
"s": 317,
"text": "Approach : The approach to this problem is simple. We iterate the string from left to right and as soon we strike a symbol we insert the number and the symbol in the beginning of the resultant string."
},
{
"code": null,
"e": 522,
"s": 518,
"text": "C++"
},
{
"code": null,
"e": 527,
"s": 522,
"text": "Java"
},
{
"code": null,
"e": 530,
"s": 527,
"text": "C#"
},
{
"code": null,
"e": 538,
"s": 530,
"text": "Python3"
},
{
"code": "// C++ program to reverse an equation#include <bits/stdc++.h>using namespace std; // Function to reverse order of wordsstring reverseEquation(string s){ // Resultant string string result; int j = 0; for (int i = 0; i < s.length(); i++) { // A space marks the end of the word if (s[i] == '+' || s[i] == '-' || s[i] == '/' || s[i] == '*') { // insert the word at the beginning // of the result string result.insert(result.begin(), s.begin() + j, s.begin() + i); j = i + 1; // insert the symbol result.insert(result.begin(), s[i]); } } // insert the last word in the string // to the result string result.insert(result.begin(), s.begin() + j, s.end()); return result;} // driver codeint main(){ string s = \"a+b*c-d/e\"; cout << reverseEquation(s) << endl; return 0;}",
"e": 1526,
"s": 538,
"text": null
},
{
"code": "// Java program to reverse an equationimport java.util.*; class GFG{ // Function to reverse order of wordspublic static String reverseEquation(String s){ // Resultant string String result = \"\", str = \"\"; int j = 0; for(int i = 0; i < s.length(); i++) { // A space marks the end of the word if (s.charAt(i) == '+' || s.charAt(i) == '-' || s.charAt(i) == '/' || s.charAt(i) == '*') { // Insert the word at the beginning // of the result string result = s.charAt(i) + str + result; str = \"\"; } else { str += s.charAt(i); } } result = str + result; return result;} // Driver codepublic static void main(String args[]){ String s = \"a+b*c-d/e\"; System.out.println(reverseEquation(s));}} // This code is contributed by bolliranadheer",
"e": 2461,
"s": 1526,
"text": null
},
{
"code": "// C# program to reverse an equationusing System;using System.Text; public class GFG{ // Function to reverse order of words public static string reverseEquation(string s) { // Resultant string string result = \"\", str = \"\"; for(int i = 0; i < s.Length; i++) { // A space marks the end of the word if (s[i] == '+' || s[i] == '-' || s[i] == '/' || s[i] == '*') { // Insert the word at the beginning // of the result string result = s[i] + str + result; str = \"\"; } else { str += s[i]; } } result = str + result; return result; } // Driver Code static public void Main (){ string s = \"a+b*c-d/e\"; Console.Write(reverseEquation(s)); }} // This code is contributed by shruti456rawal",
"e": 3254,
"s": 2461,
"text": null
},
{
"code": "# Python3 Program to reverse an equation# Function to reverse order of wordsdef reverseEquation(s): # Reverse String result=\"\" for i in range(len(s)): # A space marks the end of the word if(s[i]=='+' or s[i]=='-' or s[i]=='/' or s[i]=='*'): # insert the word at the beginning # of the result String result = s[i] + result # insert the symbol else: result = s[i] + result return result # Driver Codes = \"a+b*c-d/e\"print(reverseEquation(s)) # This code is contributed by simranjenny84",
"e": 3857,
"s": 3254,
"text": null
},
{
"code": null,
"e": 3866,
"s": 3857,
"text": "Output: "
},
{
"code": null,
"e": 3876,
"s": 3866,
"text": "e/d-c*b+a"
},
{
"code": null,
"e": 3898,
"s": 3876,
"text": "Time Complexity: O(N)"
},
{
"code": null,
"e": 3920,
"s": 3898,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 4342,
"s": 3920,
"text": "This article is contributed by Raghav Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 4355,
"s": 4342,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 4369,
"s": 4355,
"text": "simranjenny84"
},
{
"code": null,
"e": 4384,
"s": 4369,
"text": "bolliranadheer"
},
{
"code": null,
"e": 4395,
"s": 4384,
"text": "tarakki100"
},
{
"code": null,
"e": 4410,
"s": 4395,
"text": "shruti456rawal"
},
{
"code": null,
"e": 4418,
"s": 4410,
"text": "Strings"
},
{
"code": null,
"e": 4426,
"s": 4418,
"text": "Strings"
}
]
|
Python | Django Admin Interface | 05 Jun, 2018
Prerequisites : django-introduction-and-installation | django-introduction-set-2-creating-a-project
Django provides a default admin interface which can be used to perform create, read, update and delete operations on the model directly. It reads set of data that explain and gives information about data from the model, to provide an instant interface where the user can adjust contents of the application . This is an in-built module and design to execute admin related work to the user.
Activating and Using the Admin InterfaceThe admin app(django.contrib.admin) is enabled by default and already added into the INSTALLED_APPS list present in the settings.py file.
To access this admin interface on browser write ‘/admin/’ at ‘localhost:8000/admin/’ and it shows the output as given below:
It prompts for login details, if no login id is created before, then a new superuser can be created by using the command given below:
python manage.py createsuperuser
Now, access the admin login page after starting the Development Server which can be done by using the command given below.
python manage.py runserver
Enter username and password, then hit login .
After logging in successfully, it shows the interface as shown below: .
This is what is called a Django Admin Dashboard where one can add, delete and update data belonging to any registered model.
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Iterate over a list in Python | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n05 Jun, 2018"
},
{
"code": null,
"e": 153,
"s": 53,
"text": "Prerequisites : django-introduction-and-installation | django-introduction-set-2-creating-a-project"
},
{
"code": null,
"e": 542,
"s": 153,
"text": "Django provides a default admin interface which can be used to perform create, read, update and delete operations on the model directly. It reads set of data that explain and gives information about data from the model, to provide an instant interface where the user can adjust contents of the application . This is an in-built module and design to execute admin related work to the user."
},
{
"code": null,
"e": 720,
"s": 542,
"text": "Activating and Using the Admin InterfaceThe admin app(django.contrib.admin) is enabled by default and already added into the INSTALLED_APPS list present in the settings.py file."
},
{
"code": null,
"e": 845,
"s": 720,
"text": "To access this admin interface on browser write ‘/admin/’ at ‘localhost:8000/admin/’ and it shows the output as given below:"
},
{
"code": null,
"e": 979,
"s": 845,
"text": "It prompts for login details, if no login id is created before, then a new superuser can be created by using the command given below:"
},
{
"code": null,
"e": 1013,
"s": 979,
"text": "python manage.py createsuperuser\n"
},
{
"code": null,
"e": 1136,
"s": 1013,
"text": "Now, access the admin login page after starting the Development Server which can be done by using the command given below."
},
{
"code": null,
"e": 1164,
"s": 1136,
"text": "python manage.py runserver\n"
},
{
"code": null,
"e": 1210,
"s": 1164,
"text": "Enter username and password, then hit login ."
},
{
"code": null,
"e": 1282,
"s": 1210,
"text": "After logging in successfully, it shows the interface as shown below: ."
},
{
"code": null,
"e": 1407,
"s": 1282,
"text": "This is what is called a Django Admin Dashboard where one can add, delete and update data belonging to any registered model."
},
{
"code": null,
"e": 1421,
"s": 1407,
"text": "Python Django"
},
{
"code": null,
"e": 1428,
"s": 1421,
"text": "Python"
},
{
"code": null,
"e": 1526,
"s": 1428,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1544,
"s": 1526,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1586,
"s": 1544,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1608,
"s": 1586,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1643,
"s": 1608,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1669,
"s": 1643,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1701,
"s": 1669,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1730,
"s": 1701,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1757,
"s": 1730,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1778,
"s": 1757,
"text": "Python OOPs Concepts"
}
]
|
numpy.logspace() in Python | 05 Apr, 2022
The numpy.logspace() function returns number spaces evenly w.r.t interval on a log scale. Syntax :
numpy.logspace(start,
stop,
num = 50,
endpoint = True,
base = 10.0,
dtype = None)
Parameters :
-> start : [float] start(base ** start) of interval range.
-> stop : [float] end(base ** stop) of interval range
-> endpoint : [boolean, optional]If True, stop is the last sample. By default, True
-> num : [int, optional] No. of samples to generate
-> base : [float, optional] Base of log scale. By default, equals 10.0
-> dtype : type of output array
Return :
-> ndarray
Code 1 : Explaining the use of logspace()
Python
# Python Programming illustrating# numpy.logspace method import numpy as geek # base = 11print("B\n", geek.logspace(2.0, 3.0, num=5, base = 11)) # base = 10print("B\n", geek.logspace(2.0, 3.0, num=5)) # base = 10, dtype = intprint("B\n", geek.logspace(2.0, 3.0, num=5, dtype = int))
Output :
B
[ 121. 220.36039471 401.31159963 730.8527479 1331. ]
B
[ 100. 177.827941 316.22776602 562.34132519 1000. ]
B
[ 100 177 316 562 1000]
Code 2 : Graphical Representation of numpy.logspace() using matplotlib module – pylab
Python
# Graphical Representation of numpy.logspace()import numpy as geekimport pylab as p # Start = 0# End = 2# Samples to generate = 10x1 = geek.logspace(0, 1, 10)y1 = geek.zeros(10) # Start = 0.1# End = 1.5# Samples to generate = 12x2 = geek.logspace(0.1, 1.5, 12)y2 = geek.zeros(12) p.plot(x1, y1+0.05, 'o')p.xlim(-0.2, 18)p.ylim(-0.5, 1)p.plot(x2, y2, 'x')
Output :
Note : These NumPy-Python programs won’t run on online IDE’s, so run them on your systems to explore themSimilar methods :
arange
linspace
saurabh1990aror
kothavvsaakash
surinderdawra388
Python numpy-arrayCreation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Apr, 2022"
},
{
"code": null,
"e": 129,
"s": 28,
"text": "The numpy.logspace() function returns number spaces evenly w.r.t interval on a log scale. Syntax : "
},
{
"code": null,
"e": 286,
"s": 129,
"text": "numpy.logspace(start,\n stop,\n num = 50,\n endpoint = True,\n base = 10.0,\n dtype = None)"
},
{
"code": null,
"e": 300,
"s": 286,
"text": "Parameters : "
},
{
"code": null,
"e": 671,
"s": 300,
"text": "-> start : [float] start(base ** start) of interval range.\n-> stop : [float] end(base ** stop) of interval range\n-> endpoint : [boolean, optional]If True, stop is the last sample. By default, True\n-> num : [int, optional] No. of samples to generate\n-> base : [float, optional] Base of log scale. By default, equals 10.0\n-> dtype : type of output array"
},
{
"code": null,
"e": 682,
"s": 671,
"text": "Return : "
},
{
"code": null,
"e": 693,
"s": 682,
"text": "-> ndarray"
},
{
"code": null,
"e": 737,
"s": 693,
"text": "Code 1 : Explaining the use of logspace() "
},
{
"code": null,
"e": 744,
"s": 737,
"text": "Python"
},
{
"code": "# Python Programming illustrating# numpy.logspace method import numpy as geek # base = 11print(\"B\\n\", geek.logspace(2.0, 3.0, num=5, base = 11)) # base = 10print(\"B\\n\", geek.logspace(2.0, 3.0, num=5)) # base = 10, dtype = intprint(\"B\\n\", geek.logspace(2.0, 3.0, num=5, dtype = int))",
"e": 1027,
"s": 744,
"text": null
},
{
"code": null,
"e": 1038,
"s": 1027,
"text": "Output : "
},
{
"code": null,
"e": 1228,
"s": 1038,
"text": "B\n [ 121. 220.36039471 401.31159963 730.8527479 1331. ]\nB\n [ 100. 177.827941 316.22776602 562.34132519 1000. ]\nB\n [ 100 177 316 562 1000]"
},
{
"code": null,
"e": 1316,
"s": 1228,
"text": "Code 2 : Graphical Representation of numpy.logspace() using matplotlib module – pylab "
},
{
"code": null,
"e": 1323,
"s": 1316,
"text": "Python"
},
{
"code": "# Graphical Representation of numpy.logspace()import numpy as geekimport pylab as p # Start = 0# End = 2# Samples to generate = 10x1 = geek.logspace(0, 1, 10)y1 = geek.zeros(10) # Start = 0.1# End = 1.5# Samples to generate = 12x2 = geek.logspace(0.1, 1.5, 12)y2 = geek.zeros(12) p.plot(x1, y1+0.05, 'o')p.xlim(-0.2, 18)p.ylim(-0.5, 1)p.plot(x2, y2, 'x')",
"e": 1678,
"s": 1323,
"text": null
},
{
"code": null,
"e": 1689,
"s": 1678,
"text": "Output : "
},
{
"code": null,
"e": 1814,
"s": 1689,
"text": "Note : These NumPy-Python programs won’t run on online IDE’s, so run them on your systems to explore themSimilar methods : "
},
{
"code": null,
"e": 1821,
"s": 1814,
"text": "arange"
},
{
"code": null,
"e": 1830,
"s": 1821,
"text": "linspace"
},
{
"code": null,
"e": 1846,
"s": 1830,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 1861,
"s": 1846,
"text": "kothavvsaakash"
},
{
"code": null,
"e": 1878,
"s": 1861,
"text": "surinderdawra388"
},
{
"code": null,
"e": 1905,
"s": 1878,
"text": "Python numpy-arrayCreation"
},
{
"code": null,
"e": 1918,
"s": 1905,
"text": "Python-numpy"
},
{
"code": null,
"e": 1925,
"s": 1918,
"text": "Python"
}
]
|
Program to find Smallest and Largest Word in a String | 23 Jun, 2022
Given a string, find the minimum and the maximum length words in it. Examples:
Input : "This is a test string"
Output : Minimum length word: a
Maximum length word: string
Input : "GeeksforGeeks A computer Science portal for Geeks"
Output : Minimum length word: A
Maximum length word: GeeksforGeeks
Approach
The idea is to keep a starting index si and an ending index ei.
si points to the starting of a new word and we traverse the string using ei.
Whenever a space or ‘\0’ character is encountered,we compute the length of the current word using (ei – si) and compare it with the minimum and the maximum length so far. If it is less, update the min_length and the min_start_index( which points to the starting of the minimum length word).If it is greater, update the max_length and the max_start_index( which points to the starting of the maximum length word).
If it is less, update the min_length and the min_start_index( which points to the starting of the minimum length word).
If it is greater, update the max_length and the max_start_index( which points to the starting of the maximum length word).
Finally update minWord and maxWord which are output strings that have been sent by reference with the substrings starting at min_start_index and max_start_index of length min_length and max_length respectively.
C++
Java
Python 3
C#
Javascript
// CPP Program to find Smallest and// Largest Word in a String#include<iostream>#include<cstring>using namespace std; void minMaxLengthWords(string input, string &minWord, string &maxWord){ // minWord and maxWord are received by reference // and not by value // will be used to store and return output int len = input.length(); int si = 0, ei = 0; int min_length = len, min_start_index = 0, max_length = 0, max_start_index = 0; // Loop while input string is not empty while (ei <= len) { if (ei < len && input[ei] != ' ') ei++; else { // end of a word // find curr word length int curr_length = ei - si; if (curr_length < min_length) { min_length = curr_length; min_start_index = si; } if (curr_length > max_length) { max_length = curr_length; max_start_index = si; } ei++; si = ei; } } // store minimum and maximum length words minWord = input.substr(min_start_index, min_length); maxWord = input.substr(max_start_index, max_length);} // Driver codeint main(){ string a = "GeeksforGeeks A Computer Science portal for Geeks"; string minWord, maxWord; minMaxLengthWords(a, minWord, maxWord); // to take input in string use getline(cin, a); cout << "Minimum length word: " << minWord << endl << "Maximum length word: " << maxWord << endl;}
// Java Program to find Smallest and// Largest Word in a Stringclass GFG{ static String minWord = "", maxWord = ""; static void minMaxLengthWords(String input) { input=input.trim();//Triming any space before the String else space at start would be consider as smallest word // minWord and maxWord are received by reference // and not by value // will be used to store and return output int len = input.length(); int si = 0, ei = 0; int min_length = len, min_start_index = 0, max_length = 0, max_start_index = 0; // Loop while input string is not empty while (ei <= len) { if (ei < len && input.charAt(ei) != ' ') { ei++; } else { // end of a word // find curr word length int curr_length = ei - si; if (curr_length < min_length) { min_length = curr_length; min_start_index = si; } if (curr_length > max_length) { max_length = curr_length; max_start_index = si; } ei++; si = ei; } } // store minimum and maximum length words minWord = input.substring(min_start_index, min_start_index + min_length); maxWord = input.substring(max_start_index, max_start_index+max_length);//Earlier code was not working if the largests word is inbetween String } // Driver code public static void main(String[] args) { String a = "GeeksforGeeks A Computer Science portal for Geeks"; minMaxLengthWords(a); // to take input in string use getline(cin, a); System.out.print("Minimum length word: " + minWord + "\nMaximum length word: " + maxWord); }} // This code contributed by Rajput-Ji
# Python3 program to find Smallest and# Largest Word in a String # defining the method to find the longest# word and the shortest worddef minMaxLengthWords(inp): length = len(inp) si = ei = 0 min_length = length min_start_index = max_length = max_start_index = 0 # loop to find the length and stating index # of both longest and shortest words while ei <= length: if (ei < length) and (inp[ei] != " "): ei += 1 else: curr_length = ei - si # condition checking for the shortest word if curr_length < min_length: min_length = curr_length min_start_index = si # condition for the longest word if curr_length > max_length: max_length = curr_length max_start_index = si ei += 1 si = ei # extracting the shortest word using # it's starting index and length minWord = inp[min_start_index : min_start_index + min_length] # extracting the longest word using # it's starting index and length maxWord = inp[max_start_index : max_length] # printing the final result print("Minimum length word: ", minWord) print ("Maximum length word: ", maxWord) # Driver Code # Using this string to test our codea = "GeeksforGeeks A Computer Science portal for Geeks"minMaxLengthWords(a) # This code is contributed by Animesh_Gupta
// C# Program to find Smallest and// Largest Word in a Stringusing System; class GFG{ static String minWord = "", maxWord = ""; static void minMaxLengthWords(String input) { // minWord and maxWord are received by reference // and not by value // will be used to store and return output int len = input.Length; int si = 0, ei = 0; int min_length = len, min_start_index = 0, max_length = 0, max_start_index = 0; // Loop while input string is not empty while (ei <= len) { if (ei < len && input[ei] != ' ') { ei++; } else { // end of a word // find curr word length int curr_length = ei - si; if (curr_length < min_length) { min_length = curr_length; min_start_index = si; } if (curr_length > max_length) { max_length = curr_length; max_start_index = si; } ei++; si = ei; } } // store minimum and maximum length words minWord = input.Substring(min_start_index, min_length); maxWord = input.Substring(max_start_index, max_length); } // Driver code public static void Main(String[] args) { String a = "GeeksforGeeks A Computer Science portal for Geeks"; minMaxLengthWords(a); // to take input in string use getline(cin, a); Console.Write("Minimum length word: " + minWord + "\nMaximum length word: " + maxWord); }} // This code has been contributed by 29AjayKumar
<script> // JavaScript Program to find Smallest and// Largest Word in a String let minWord = "";let maxWord = ""; function minMaxLengthWords(input){ // minWord and maxWord are received by reference // and not by value // will be used to store and return output let len = input.length; let si = 0, ei = 0; let min_length = len; let min_start_index = 0; let max_length = 0; let max_start_index = 0; // Loop while input string is not empty while (ei <= len) { if (ei < len && input[ei] != ' ') { ei++; } else { // end of a word // find curr word length let curr_length = ei - si; if (curr_length < min_length) { min_length = curr_length; min_start_index = si; } if (curr_length > max_length) { max_length = curr_length; max_start_index = si; } ei++; si = ei; } } // store minimum and maximum length words minWord = input.substring(min_start_index,min_start_index + min_length); maxWord = input.substring(max_start_index, max_length); } // Driver code let a = "GeeksforGeeks A Computer Science portal for Geeks"; minMaxLengthWords(a); // to take input in string use getline(cin, a);document.write("Minimum length word: " + minWord+"<br>" + "Maximum length word: " + maxWord); </script>
Minimum length word: A
Maximum length word: GeeksforGeeks
Time Complexity: O(n), where n is the length of string.
Auxiliary Space: O(n), where n is the length of string.
This is because when string is passed in the function it creates a copy of itself in stack.
Rajput-Ji
29AjayKumar
Animesh_Gupta
mohit kumar 29
nambiarjishnu1210
sagar0719kumar
sweetyty
anandkumarshivam2266
mysticunj5qe
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different Methods to Reverse a String in C++
KMP Algorithm for Pattern Searching
Python program to check if a string is palindrome or not
Length of the longest substring without repeating characters
Longest Palindromic Substring | Set 1
Convert string to char array in C++
stringstream in C++ and its Applications
Iterate over characters of a string in C++
Program to add two binary strings
Check for Balanced Brackets in an expression (well-formedness) using Stack | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 Jun, 2022"
},
{
"code": null,
"e": 133,
"s": 52,
"text": "Given a string, find the minimum and the maximum length words in it. Examples: "
},
{
"code": null,
"e": 371,
"s": 133,
"text": "Input : \"This is a test string\"\nOutput : Minimum length word: a\n Maximum length word: string\n\nInput : \"GeeksforGeeks A computer Science portal for Geeks\"\nOutput : Minimum length word: A\n Maximum length word: GeeksforGeeks"
},
{
"code": null,
"e": 382,
"s": 373,
"text": "Approach"
},
{
"code": null,
"e": 448,
"s": 382,
"text": "The idea is to keep a starting index si and an ending index ei. "
},
{
"code": null,
"e": 525,
"s": 448,
"text": "si points to the starting of a new word and we traverse the string using ei."
},
{
"code": null,
"e": 938,
"s": 525,
"text": "Whenever a space or ‘\\0’ character is encountered,we compute the length of the current word using (ei – si) and compare it with the minimum and the maximum length so far. If it is less, update the min_length and the min_start_index( which points to the starting of the minimum length word).If it is greater, update the max_length and the max_start_index( which points to the starting of the maximum length word)."
},
{
"code": null,
"e": 1058,
"s": 938,
"text": "If it is less, update the min_length and the min_start_index( which points to the starting of the minimum length word)."
},
{
"code": null,
"e": 1181,
"s": 1058,
"text": "If it is greater, update the max_length and the max_start_index( which points to the starting of the maximum length word)."
},
{
"code": null,
"e": 1392,
"s": 1181,
"text": "Finally update minWord and maxWord which are output strings that have been sent by reference with the substrings starting at min_start_index and max_start_index of length min_length and max_length respectively."
},
{
"code": null,
"e": 1398,
"s": 1394,
"text": "C++"
},
{
"code": null,
"e": 1403,
"s": 1398,
"text": "Java"
},
{
"code": null,
"e": 1412,
"s": 1403,
"text": "Python 3"
},
{
"code": null,
"e": 1415,
"s": 1412,
"text": "C#"
},
{
"code": null,
"e": 1426,
"s": 1415,
"text": "Javascript"
},
{
"code": "// CPP Program to find Smallest and// Largest Word in a String#include<iostream>#include<cstring>using namespace std; void minMaxLengthWords(string input, string &minWord, string &maxWord){ // minWord and maxWord are received by reference // and not by value // will be used to store and return output int len = input.length(); int si = 0, ei = 0; int min_length = len, min_start_index = 0, max_length = 0, max_start_index = 0; // Loop while input string is not empty while (ei <= len) { if (ei < len && input[ei] != ' ') ei++; else { // end of a word // find curr word length int curr_length = ei - si; if (curr_length < min_length) { min_length = curr_length; min_start_index = si; } if (curr_length > max_length) { max_length = curr_length; max_start_index = si; } ei++; si = ei; } } // store minimum and maximum length words minWord = input.substr(min_start_index, min_length); maxWord = input.substr(max_start_index, max_length);} // Driver codeint main(){ string a = \"GeeksforGeeks A Computer Science portal for Geeks\"; string minWord, maxWord; minMaxLengthWords(a, minWord, maxWord); // to take input in string use getline(cin, a); cout << \"Minimum length word: \" << minWord << endl << \"Maximum length word: \" << maxWord << endl;}",
"e": 3007,
"s": 1426,
"text": null
},
{
"code": "// Java Program to find Smallest and// Largest Word in a Stringclass GFG{ static String minWord = \"\", maxWord = \"\"; static void minMaxLengthWords(String input) { input=input.trim();//Triming any space before the String else space at start would be consider as smallest word // minWord and maxWord are received by reference // and not by value // will be used to store and return output int len = input.length(); int si = 0, ei = 0; int min_length = len, min_start_index = 0, max_length = 0, max_start_index = 0; // Loop while input string is not empty while (ei <= len) { if (ei < len && input.charAt(ei) != ' ') { ei++; } else { // end of a word // find curr word length int curr_length = ei - si; if (curr_length < min_length) { min_length = curr_length; min_start_index = si; } if (curr_length > max_length) { max_length = curr_length; max_start_index = si; } ei++; si = ei; } } // store minimum and maximum length words minWord = input.substring(min_start_index, min_start_index + min_length); maxWord = input.substring(max_start_index, max_start_index+max_length);//Earlier code was not working if the largests word is inbetween String } // Driver code public static void main(String[] args) { String a = \"GeeksforGeeks A Computer Science portal for Geeks\"; minMaxLengthWords(a); // to take input in string use getline(cin, a); System.out.print(\"Minimum length word: \" + minWord + \"\\nMaximum length word: \" + maxWord); }} // This code contributed by Rajput-Ji",
"e": 5028,
"s": 3007,
"text": null
},
{
"code": "# Python3 program to find Smallest and# Largest Word in a String # defining the method to find the longest# word and the shortest worddef minMaxLengthWords(inp): length = len(inp) si = ei = 0 min_length = length min_start_index = max_length = max_start_index = 0 # loop to find the length and stating index # of both longest and shortest words while ei <= length: if (ei < length) and (inp[ei] != \" \"): ei += 1 else: curr_length = ei - si # condition checking for the shortest word if curr_length < min_length: min_length = curr_length min_start_index = si # condition for the longest word if curr_length > max_length: max_length = curr_length max_start_index = si ei += 1 si = ei # extracting the shortest word using # it's starting index and length minWord = inp[min_start_index : min_start_index + min_length] # extracting the longest word using # it's starting index and length maxWord = inp[max_start_index : max_length] # printing the final result print(\"Minimum length word: \", minWord) print (\"Maximum length word: \", maxWord) # Driver Code # Using this string to test our codea = \"GeeksforGeeks A Computer Science portal for Geeks\"minMaxLengthWords(a) # This code is contributed by Animesh_Gupta",
"e": 6530,
"s": 5028,
"text": null
},
{
"code": "// C# Program to find Smallest and// Largest Word in a Stringusing System; class GFG{ static String minWord = \"\", maxWord = \"\"; static void minMaxLengthWords(String input) { // minWord and maxWord are received by reference // and not by value // will be used to store and return output int len = input.Length; int si = 0, ei = 0; int min_length = len, min_start_index = 0, max_length = 0, max_start_index = 0; // Loop while input string is not empty while (ei <= len) { if (ei < len && input[ei] != ' ') { ei++; } else { // end of a word // find curr word length int curr_length = ei - si; if (curr_length < min_length) { min_length = curr_length; min_start_index = si; } if (curr_length > max_length) { max_length = curr_length; max_start_index = si; } ei++; si = ei; } } // store minimum and maximum length words minWord = input.Substring(min_start_index, min_length); maxWord = input.Substring(max_start_index, max_length); } // Driver code public static void Main(String[] args) { String a = \"GeeksforGeeks A Computer Science portal for Geeks\"; minMaxLengthWords(a); // to take input in string use getline(cin, a); Console.Write(\"Minimum length word: \" + minWord + \"\\nMaximum length word: \" + maxWord); }} // This code has been contributed by 29AjayKumar",
"e": 8319,
"s": 6530,
"text": null
},
{
"code": "<script> // JavaScript Program to find Smallest and// Largest Word in a String let minWord = \"\";let maxWord = \"\"; function minMaxLengthWords(input){ // minWord and maxWord are received by reference // and not by value // will be used to store and return output let len = input.length; let si = 0, ei = 0; let min_length = len; let min_start_index = 0; let max_length = 0; let max_start_index = 0; // Loop while input string is not empty while (ei <= len) { if (ei < len && input[ei] != ' ') { ei++; } else { // end of a word // find curr word length let curr_length = ei - si; if (curr_length < min_length) { min_length = curr_length; min_start_index = si; } if (curr_length > max_length) { max_length = curr_length; max_start_index = si; } ei++; si = ei; } } // store minimum and maximum length words minWord = input.substring(min_start_index,min_start_index + min_length); maxWord = input.substring(max_start_index, max_length); } // Driver code let a = \"GeeksforGeeks A Computer Science portal for Geeks\"; minMaxLengthWords(a); // to take input in string use getline(cin, a);document.write(\"Minimum length word: \" + minWord+\"<br>\" + \"Maximum length word: \" + maxWord); </script>",
"e": 9824,
"s": 8319,
"text": null
},
{
"code": null,
"e": 9882,
"s": 9824,
"text": "Minimum length word: A\nMaximum length word: GeeksforGeeks"
},
{
"code": null,
"e": 9938,
"s": 9882,
"text": "Time Complexity: O(n), where n is the length of string."
},
{
"code": null,
"e": 9994,
"s": 9938,
"text": "Auxiliary Space: O(n), where n is the length of string."
},
{
"code": null,
"e": 10087,
"s": 9994,
"text": "This is because when string is passed in the function it creates a copy of itself in stack. "
},
{
"code": null,
"e": 10097,
"s": 10087,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 10109,
"s": 10097,
"text": "29AjayKumar"
},
{
"code": null,
"e": 10123,
"s": 10109,
"text": "Animesh_Gupta"
},
{
"code": null,
"e": 10138,
"s": 10123,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 10156,
"s": 10138,
"text": "nambiarjishnu1210"
},
{
"code": null,
"e": 10171,
"s": 10156,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 10180,
"s": 10171,
"text": "sweetyty"
},
{
"code": null,
"e": 10201,
"s": 10180,
"text": "anandkumarshivam2266"
},
{
"code": null,
"e": 10214,
"s": 10201,
"text": "mysticunj5qe"
},
{
"code": null,
"e": 10222,
"s": 10214,
"text": "Strings"
},
{
"code": null,
"e": 10230,
"s": 10222,
"text": "Strings"
},
{
"code": null,
"e": 10328,
"s": 10230,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10373,
"s": 10328,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 10409,
"s": 10373,
"text": "KMP Algorithm for Pattern Searching"
},
{
"code": null,
"e": 10466,
"s": 10409,
"text": "Python program to check if a string is palindrome or not"
},
{
"code": null,
"e": 10527,
"s": 10466,
"text": "Length of the longest substring without repeating characters"
},
{
"code": null,
"e": 10565,
"s": 10527,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 10601,
"s": 10565,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 10642,
"s": 10601,
"text": "stringstream in C++ and its Applications"
},
{
"code": null,
"e": 10685,
"s": 10642,
"text": "Iterate over characters of a string in C++"
},
{
"code": null,
"e": 10719,
"s": 10685,
"text": "Program to add two binary strings"
}
]
|
JavaScript | Date Formats | 17 Feb, 2022
JavaScript Date Input: There are many ways in which one can format the date in JavaScript.
Formats:
ISO Date"2019-03-06" (The International Standard)
"2019-03-06" (The International Standard)
Short Date"03/06/2019"
"03/06/2019"
Long Date"Mar 06 2019" or "06 Mar 2019"
"Mar 06 2019" or "06 Mar 2019"
Example 1: This example uses ISO date format to display the date.
<!DOCTYPE html><html> <head> <title>Date format</title> </head> <body> <center> <div style="background-color: white;"> <h1>Welcome to GeeksforGeeks!.</h1> <h3>JavaScript ISO Dates:</h3> <p id="name" style="background-color: green;"></p> </div> </center> <script> let dat = new Date("2015-03-25"); document.getElementById("name").innerHTML = dat; </script> </body></html>
Output:
JavaScript ISO Dates Format Output:
Complete date (Date(“2019-03-06”)):Wed Mar 06 2019 02:07:00 GMT+0530 (India Standard Time)
Wed Mar 06 2019 02:07:00 GMT+0530 (India Standard Time)
Year and Month (Date(“2019-03”)):Fri Mar 01 2019 02:07:00 GMT+0530 (India Standard Time)
Fri Mar 01 2019 02:07:00 GMT+0530 (India Standard Time)
Only Year (Date(“2019”)):Tue Jan 01 2019 02:07:00 GMT+0530 (India Standard Time)
Tue Jan 01 2019 02:07:00 GMT+0530 (India Standard Time)
Only Year (Date(“2019-03-06T12:00:00Z”)):Wed Mar 06 2019 02:07:00 GMT+0530 (India Standard Time)
Wed Mar 06 2019 02:07:00 GMT+0530 (India Standard Time)
JavaScript Short Dates: The JavaScript short dates are written in MM/DD/YYYY format.Syntax:
"MM/DD/YYYY"
JavaScript Long Dates: The JavaScript long dates are written in MMM DD YYYY format.Syntax:
"MMM DD YYYY"
Example 2: This example uses short date format.
<!DOCTYPE html><html> <head> <title>Date format</title> </head> <body> <center> <div style="background-color: green;"> <h1>Welcome to GeeksforGeeks!.</h1> <h3>JavaScript ISO Dates:</h3> <p id="name"></p> </div> </center> <script> var x = new Date("03/06/2019"); document.getElementById("name").innerHTML = x; </script> </body></html>
Output:
toTimeString() Method: It is used to return the time portion of the given date object in English. The date object is created by using date() constructor. This method converts the time portion of the date in to a string.
Syntax:
var string_name = date_variable.toTimeString
Example:
<!DOCTYPE html><html> <body onload="myFunction()"> <center> <div style="background-color: green;"> <h1>Geeksforgeeks !!</h1> <p id="geek"></p> </div> <script> function myFunction() { let dt = new Date(); let s = dt.toTimeString(); document.getElementById("geek").innerHTML = s; } </script> </body></html>
Output:
Date.parse() Method: The Date.parse() function is used to help the exact number of milliseconds that have passed since midnight, January 1, 1970, till the date we provide. It converts the valid date string given to it in milliseconds.
Syntax:
var var_name = Date.parse(valid_date_string)
Example:
<!DOCTYPE html><html> <body> <center> <div style="background-color: green;"> <h1>Geeksforgeeks !!</h1> <b>Date.parse() returns the number milliseconds</b> <p id="geek"></p> </div> <script> let msec = Date.parse("March 21, 2012"); document.getElementById("geek").innerHTML = msec; </script> </body></html>
Output:
Supported Browser:
Chrome
Edge
Internet Explorer
Opera
safari
ysachin2314
javascript-date
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Feb, 2022"
},
{
"code": null,
"e": 119,
"s": 28,
"text": "JavaScript Date Input: There are many ways in which one can format the date in JavaScript."
},
{
"code": null,
"e": 128,
"s": 119,
"text": "Formats:"
},
{
"code": null,
"e": 178,
"s": 128,
"text": "ISO Date\"2019-03-06\" (The International Standard)"
},
{
"code": null,
"e": 220,
"s": 178,
"text": "\"2019-03-06\" (The International Standard)"
},
{
"code": null,
"e": 243,
"s": 220,
"text": "Short Date\"03/06/2019\""
},
{
"code": null,
"e": 256,
"s": 243,
"text": "\"03/06/2019\""
},
{
"code": null,
"e": 296,
"s": 256,
"text": "Long Date\"Mar 06 2019\" or \"06 Mar 2019\""
},
{
"code": null,
"e": 327,
"s": 296,
"text": "\"Mar 06 2019\" or \"06 Mar 2019\""
},
{
"code": null,
"e": 393,
"s": 327,
"text": "Example 1: This example uses ISO date format to display the date."
},
{
"code": "<!DOCTYPE html><html> <head> <title>Date format</title> </head> <body> <center> <div style=\"background-color: white;\"> <h1>Welcome to GeeksforGeeks!.</h1> <h3>JavaScript ISO Dates:</h3> <p id=\"name\" style=\"background-color: green;\"></p> </div> </center> <script> let dat = new Date(\"2015-03-25\"); document.getElementById(\"name\").innerHTML = dat; </script> </body></html> ",
"e": 920,
"s": 393,
"text": null
},
{
"code": null,
"e": 928,
"s": 920,
"text": "Output:"
},
{
"code": null,
"e": 964,
"s": 928,
"text": "JavaScript ISO Dates Format Output:"
},
{
"code": null,
"e": 1055,
"s": 964,
"text": "Complete date (Date(“2019-03-06”)):Wed Mar 06 2019 02:07:00 GMT+0530 (India Standard Time)"
},
{
"code": null,
"e": 1111,
"s": 1055,
"text": "Wed Mar 06 2019 02:07:00 GMT+0530 (India Standard Time)"
},
{
"code": null,
"e": 1200,
"s": 1111,
"text": "Year and Month (Date(“2019-03”)):Fri Mar 01 2019 02:07:00 GMT+0530 (India Standard Time)"
},
{
"code": null,
"e": 1256,
"s": 1200,
"text": "Fri Mar 01 2019 02:07:00 GMT+0530 (India Standard Time)"
},
{
"code": null,
"e": 1337,
"s": 1256,
"text": "Only Year (Date(“2019”)):Tue Jan 01 2019 02:07:00 GMT+0530 (India Standard Time)"
},
{
"code": null,
"e": 1393,
"s": 1337,
"text": "Tue Jan 01 2019 02:07:00 GMT+0530 (India Standard Time)"
},
{
"code": null,
"e": 1490,
"s": 1393,
"text": "Only Year (Date(“2019-03-06T12:00:00Z”)):Wed Mar 06 2019 02:07:00 GMT+0530 (India Standard Time)"
},
{
"code": null,
"e": 1546,
"s": 1490,
"text": "Wed Mar 06 2019 02:07:00 GMT+0530 (India Standard Time)"
},
{
"code": null,
"e": 1638,
"s": 1546,
"text": "JavaScript Short Dates: The JavaScript short dates are written in MM/DD/YYYY format.Syntax:"
},
{
"code": null,
"e": 1651,
"s": 1638,
"text": "\"MM/DD/YYYY\""
},
{
"code": null,
"e": 1742,
"s": 1651,
"text": "JavaScript Long Dates: The JavaScript long dates are written in MMM DD YYYY format.Syntax:"
},
{
"code": null,
"e": 1756,
"s": 1742,
"text": "\"MMM DD YYYY\""
},
{
"code": null,
"e": 1804,
"s": 1756,
"text": "Example 2: This example uses short date format."
},
{
"code": "<!DOCTYPE html><html> <head> <title>Date format</title> </head> <body> <center> <div style=\"background-color: green;\"> <h1>Welcome to GeeksforGeeks!.</h1> <h3>JavaScript ISO Dates:</h3> <p id=\"name\"></p> </div> </center> <script> var x = new Date(\"03/06/2019\"); document.getElementById(\"name\").innerHTML = x; </script> </body></html>",
"e": 2274,
"s": 1804,
"text": null
},
{
"code": null,
"e": 2282,
"s": 2274,
"text": "Output:"
},
{
"code": null,
"e": 2502,
"s": 2282,
"text": "toTimeString() Method: It is used to return the time portion of the given date object in English. The date object is created by using date() constructor. This method converts the time portion of the date in to a string."
},
{
"code": null,
"e": 2510,
"s": 2502,
"text": "Syntax:"
},
{
"code": null,
"e": 2555,
"s": 2510,
"text": "var string_name = date_variable.toTimeString"
},
{
"code": null,
"e": 2564,
"s": 2555,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <body onload=\"myFunction()\"> <center> <div style=\"background-color: green;\"> <h1>Geeksforgeeks !!</h1> <p id=\"geek\"></p> </div> <script> function myFunction() { let dt = new Date(); let s = dt.toTimeString(); document.getElementById(\"geek\").innerHTML = s; } </script> </body></html>",
"e": 2993,
"s": 2564,
"text": null
},
{
"code": null,
"e": 3001,
"s": 2993,
"text": "Output:"
},
{
"code": null,
"e": 3236,
"s": 3001,
"text": "Date.parse() Method: The Date.parse() function is used to help the exact number of milliseconds that have passed since midnight, January 1, 1970, till the date we provide. It converts the valid date string given to it in milliseconds."
},
{
"code": null,
"e": 3244,
"s": 3236,
"text": "Syntax:"
},
{
"code": null,
"e": 3289,
"s": 3244,
"text": "var var_name = Date.parse(valid_date_string)"
},
{
"code": null,
"e": 3298,
"s": 3289,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <body> <center> <div style=\"background-color: green;\"> <h1>Geeksforgeeks !!</h1> <b>Date.parse() returns the number milliseconds</b> <p id=\"geek\"></p> </div> <script> let msec = Date.parse(\"March 21, 2012\"); document.getElementById(\"geek\").innerHTML = msec; </script> </body></html>",
"e": 3699,
"s": 3298,
"text": null
},
{
"code": null,
"e": 3707,
"s": 3699,
"text": "Output:"
},
{
"code": null,
"e": 3726,
"s": 3707,
"text": "Supported Browser:"
},
{
"code": null,
"e": 3733,
"s": 3726,
"text": "Chrome"
},
{
"code": null,
"e": 3738,
"s": 3733,
"text": "Edge"
},
{
"code": null,
"e": 3756,
"s": 3738,
"text": "Internet Explorer"
},
{
"code": null,
"e": 3762,
"s": 3756,
"text": "Opera"
},
{
"code": null,
"e": 3769,
"s": 3762,
"text": "safari"
},
{
"code": null,
"e": 3781,
"s": 3769,
"text": "ysachin2314"
},
{
"code": null,
"e": 3797,
"s": 3781,
"text": "javascript-date"
},
{
"code": null,
"e": 3804,
"s": 3797,
"text": "Picked"
},
{
"code": null,
"e": 3815,
"s": 3804,
"text": "JavaScript"
},
{
"code": null,
"e": 3832,
"s": 3815,
"text": "Web Technologies"
}
]
|
Runtime JAR File in Java | 26 May, 2021
JAR stands for Java Archive file. It is a platform–independent file format that allows bundling and packaging all files associated with java application, class files, audio, and image files as well. These files are needed when we run an applet program. It bundles JAR files use a Data compression algorithm. These jar files can be manipulated using zip programs like WINZIP or WINRAR.
It enables ease of distribution as all class files are packaged/bundled together and distributed to client applications. as one single jar file. These jar files can be signed by an author using digital certificate. These jar files can be authenticated using digital certificates and checking the author’s signature. The JRE (Java Runtime Environment) loads the classes from the JAR file without un-jarring it.
Methods: There are 2 ways of creating a JAR file.
Using IDEUsing the command line
Using IDE
Using the command line
Let us do discuss both of them in depth.
1. The creation of a JAR file through an IDE like Netbeans or Eclipse is pretty straightforward. In File, we have an export option that helps us to export the java application as a JAR file. After this go to
File -> Export->Java-> JAR file
2. Now in a JAR file specification dialog, specify the resources/files to be included in the JAR file. The export destination is the location where the jar file is to be created.
3. Click on the Finish button
4. We then provide the location where we wish to have the jar file created.
5. It is pictorially depicted below in two snapshots which are as follows:
Method 2: Using the command line
Using the jar tool, we can create a jar file as below
cmd>> jar cvf jarfile inputfileDir1 inputfileDir2
Here,
c – create a new jar file
v – verbose mode which displays the messages while the jar file is created.
f – bundles into a jar file specified by the parameter jarfile instead of standard output.
inputfileDir1, inputfileDir2 – indicates the input files which are to be bundled together in the jar file.
Now we will be manifesting the file as this is a special file that is bundled in your JAR file. It has special metadata like main class name, version control, the digital signature of the author, the java version used for bundling the jar file. The file name is “MANIFEST.MF” and it is a part of the META-INF subdirectory. If this file is not provided during bundling of the JAR file, it gets created automatically. When we extract and open the jar file, we can view this file. It has the following details
Manifest-Version: 1.0
The jar file can be run by the java application directly if has a manifest file with the header as Main-class. The Main-class header has the fully qualified name of the class which has the main(). This specifies the entry point of the application.
Illustration: Consider creating a JAR file with a manifest File called helloworld.MF
Manifest-Version : 1.0
Main-class : com.sample.test.HelloWorld
Example:
Java
// Importing the package package com.sample.test; // Main classpublic class HelloWorld { // Main driver method public static void main(String[] args) { // Print statements only System.out.println("Welcome to helloworld"); System.out.println("Jar file to be created"); }}
Keep a note here m indicates the manifest file to be included while bundling into a jar file
Output:
Note: Here we compile the java file ‘HelloWorld.java’ using javac command. This command compiles the .java file and creates a class file HelloWorld.class. We then create the jar file helloworld.jar using jar command.
Lastly now while running the JAR file we use the below command to run the created jar file. When we run the jar file, ‘Helloworld‘ class which has main() gets loaded by the JVM, and the code gets executed.
Java-Files
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": "\n26 May, 2021"
},
{
"code": null,
"e": 414,
"s": 28,
"text": "JAR stands for Java Archive file. It is a platform–independent file format that allows bundling and packaging all files associated with java application, class files, audio, and image files as well. These files are needed when we run an applet program. It bundles JAR files use a Data compression algorithm. These jar files can be manipulated using zip programs like WINZIP or WINRAR. "
},
{
"code": null,
"e": 824,
"s": 414,
"text": "It enables ease of distribution as all class files are packaged/bundled together and distributed to client applications. as one single jar file. These jar files can be signed by an author using digital certificate. These jar files can be authenticated using digital certificates and checking the author’s signature. The JRE (Java Runtime Environment) loads the classes from the JAR file without un-jarring it."
},
{
"code": null,
"e": 874,
"s": 824,
"text": "Methods: There are 2 ways of creating a JAR file."
},
{
"code": null,
"e": 906,
"s": 874,
"text": "Using IDEUsing the command line"
},
{
"code": null,
"e": 916,
"s": 906,
"text": "Using IDE"
},
{
"code": null,
"e": 939,
"s": 916,
"text": "Using the command line"
},
{
"code": null,
"e": 980,
"s": 939,
"text": "Let us do discuss both of them in depth."
},
{
"code": null,
"e": 1189,
"s": 980,
"text": "1. The creation of a JAR file through an IDE like Netbeans or Eclipse is pretty straightforward. In File, we have an export option that helps us to export the java application as a JAR file. After this go to"
},
{
"code": null,
"e": 1221,
"s": 1189,
"text": "File -> Export->Java-> JAR file"
},
{
"code": null,
"e": 1400,
"s": 1221,
"text": "2. Now in a JAR file specification dialog, specify the resources/files to be included in the JAR file. The export destination is the location where the jar file is to be created."
},
{
"code": null,
"e": 1430,
"s": 1400,
"text": "3. Click on the Finish button"
},
{
"code": null,
"e": 1506,
"s": 1430,
"text": "4. We then provide the location where we wish to have the jar file created."
},
{
"code": null,
"e": 1581,
"s": 1506,
"text": "5. It is pictorially depicted below in two snapshots which are as follows:"
},
{
"code": null,
"e": 1614,
"s": 1581,
"text": "Method 2: Using the command line"
},
{
"code": null,
"e": 1668,
"s": 1614,
"text": "Using the jar tool, we can create a jar file as below"
},
{
"code": null,
"e": 1718,
"s": 1668,
"text": "cmd>> jar cvf jarfile inputfileDir1 inputfileDir2"
},
{
"code": null,
"e": 1724,
"s": 1718,
"text": "Here,"
},
{
"code": null,
"e": 1750,
"s": 1724,
"text": "c – create a new jar file"
},
{
"code": null,
"e": 1826,
"s": 1750,
"text": "v – verbose mode which displays the messages while the jar file is created."
},
{
"code": null,
"e": 1918,
"s": 1826,
"text": "f – bundles into a jar file specified by the parameter jarfile instead of standard output."
},
{
"code": null,
"e": 2025,
"s": 1918,
"text": "inputfileDir1, inputfileDir2 – indicates the input files which are to be bundled together in the jar file."
},
{
"code": null,
"e": 2532,
"s": 2025,
"text": "Now we will be manifesting the file as this is a special file that is bundled in your JAR file. It has special metadata like main class name, version control, the digital signature of the author, the java version used for bundling the jar file. The file name is “MANIFEST.MF” and it is a part of the META-INF subdirectory. If this file is not provided during bundling of the JAR file, it gets created automatically. When we extract and open the jar file, we can view this file. It has the following details"
},
{
"code": null,
"e": 2554,
"s": 2532,
"text": "Manifest-Version: 1.0"
},
{
"code": null,
"e": 2802,
"s": 2554,
"text": "The jar file can be run by the java application directly if has a manifest file with the header as Main-class. The Main-class header has the fully qualified name of the class which has the main(). This specifies the entry point of the application."
},
{
"code": null,
"e": 2887,
"s": 2802,
"text": "Illustration: Consider creating a JAR file with a manifest File called helloworld.MF"
},
{
"code": null,
"e": 2950,
"s": 2887,
"text": "Manifest-Version : 1.0\nMain-class : com.sample.test.HelloWorld"
},
{
"code": null,
"e": 2959,
"s": 2950,
"text": "Example:"
},
{
"code": null,
"e": 2964,
"s": 2959,
"text": "Java"
},
{
"code": "// Importing the package package com.sample.test; // Main classpublic class HelloWorld { // Main driver method public static void main(String[] args) { // Print statements only System.out.println(\"Welcome to helloworld\"); System.out.println(\"Jar file to be created\"); }}",
"e": 3273,
"s": 2964,
"text": null
},
{
"code": null,
"e": 3366,
"s": 3273,
"text": "Keep a note here m indicates the manifest file to be included while bundling into a jar file"
},
{
"code": null,
"e": 3374,
"s": 3366,
"text": "Output:"
},
{
"code": null,
"e": 3591,
"s": 3374,
"text": "Note: Here we compile the java file ‘HelloWorld.java’ using javac command. This command compiles the .java file and creates a class file HelloWorld.class. We then create the jar file helloworld.jar using jar command."
},
{
"code": null,
"e": 3797,
"s": 3591,
"text": "Lastly now while running the JAR file we use the below command to run the created jar file. When we run the jar file, ‘Helloworld‘ class which has main() gets loaded by the JVM, and the code gets executed."
},
{
"code": null,
"e": 3808,
"s": 3797,
"text": "Java-Files"
},
{
"code": null,
"e": 3815,
"s": 3808,
"text": "Picked"
},
{
"code": null,
"e": 3820,
"s": 3815,
"text": "Java"
},
{
"code": null,
"e": 3825,
"s": 3820,
"text": "Java"
},
{
"code": null,
"e": 3923,
"s": 3825,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3938,
"s": 3923,
"text": "Stream In Java"
},
{
"code": null,
"e": 3959,
"s": 3938,
"text": "Introduction to Java"
},
{
"code": null,
"e": 3980,
"s": 3959,
"text": "Constructors in Java"
},
{
"code": null,
"e": 3999,
"s": 3980,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 4016,
"s": 3999,
"text": "Generics in Java"
},
{
"code": null,
"e": 4042,
"s": 4016,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 4072,
"s": 4042,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 4088,
"s": 4072,
"text": "Strings in Java"
},
{
"code": null,
"e": 4125,
"s": 4088,
"text": "Differences between JDK, JRE and JVM"
}
]
|
jQuery UI Dialog close Event | 02 Dec, 2021
jQuery UI Close event is triggered when the dialog box is closed.
Learn more about jQuery selectors and events here.
Syntax:
$(".selector").dialog (
close: function( event, ui ) {
console.log('closed')
},
Approach:
First, add jQuery Mobile scripts needed for your project.
<link href =
"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
rel = "stylesheet">
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js">
</script>
‘Open Dialog’ button will trigger the click function (#gfg) that will further open the <textarea> in a dialog (#gfg2).
close( event, ui ) : Triggers when we click on close button in the dialog. There is callback function attached to this close.event : Type -> Eventui : Type -> Objectcallback function : function( event, ui ) { console.log(‘closed’)}
event : Type -> Event
ui : Type -> Object
callback function : function( event, ui ) { console.log(‘closed’)}
Example 1:
HTML
<!doctype html><html lang = "en"> <head> <meta charset = "utf-8"> <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel = "stylesheet"> <script src = "https://code.jquery.com/jquery-1.10.2.js"> </script> <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"> </script> <script type = "text/javascript"> $(function() { $( "#gfg2" ).dialog({ autoOpen: false, close: function( event, ui ) { console.log('closed') }, }); $( "#gfg" ).click(function() { $( "#gfg2" ).dialog( "open" ); }); }); </script> </head> <body> <div id = "gfg2" title="GeeksforGeeks"> <textarea>jQuery UI | close(event, ui) Event</textarea> </div> <button id = "gfg">Open Dialog</button> </body></html>
Output:
jQuery-UI
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Dec, 2021"
},
{
"code": null,
"e": 94,
"s": 28,
"text": "jQuery UI Close event is triggered when the dialog box is closed."
},
{
"code": null,
"e": 145,
"s": 94,
"text": "Learn more about jQuery selectors and events here."
},
{
"code": null,
"e": 153,
"s": 145,
"text": "Syntax:"
},
{
"code": null,
"e": 246,
"s": 153,
"text": "$(\".selector\").dialog (\n close: function( event, ui ) {\n console.log('closed')\n },"
},
{
"code": null,
"e": 256,
"s": 246,
"text": "Approach:"
},
{
"code": null,
"e": 314,
"s": 256,
"text": "First, add jQuery Mobile scripts needed for your project."
},
{
"code": null,
"e": 563,
"s": 314,
"text": "<link href = \n\"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\"\n rel = \"stylesheet\">\n<script src = \"https://code.jquery.com/jquery-1.10.2.js\"></script>\n<script src = \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\">\n</script>"
},
{
"code": null,
"e": 682,
"s": 563,
"text": "‘Open Dialog’ button will trigger the click function (#gfg) that will further open the <textarea> in a dialog (#gfg2)."
},
{
"code": null,
"e": 915,
"s": 682,
"text": "close( event, ui ) : Triggers when we click on close button in the dialog. There is callback function attached to this close.event : Type -> Eventui : Type -> Objectcallback function : function( event, ui ) { console.log(‘closed’)}"
},
{
"code": null,
"e": 938,
"s": 915,
"text": "event : Type -> Event"
},
{
"code": null,
"e": 958,
"s": 938,
"text": "ui : Type -> Object"
},
{
"code": null,
"e": 1025,
"s": 958,
"text": "callback function : function( event, ui ) { console.log(‘closed’)}"
},
{
"code": null,
"e": 1036,
"s": 1025,
"text": "Example 1:"
},
{
"code": null,
"e": 1041,
"s": 1036,
"text": "HTML"
},
{
"code": "<!doctype html><html lang = \"en\"> <head> <meta charset = \"utf-8\"> <link href = \"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\" rel = \"stylesheet\"> <script src = \"https://code.jquery.com/jquery-1.10.2.js\"> </script> <script src = \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"> </script> <script type = \"text/javascript\"> $(function() { $( \"#gfg2\" ).dialog({ autoOpen: false, close: function( event, ui ) { console.log('closed') }, }); $( \"#gfg\" ).click(function() { $( \"#gfg2\" ).dialog( \"open\" ); }); }); </script> </head> <body> <div id = \"gfg2\" title=\"GeeksforGeeks\"> <textarea>jQuery UI | close(event, ui) Event</textarea> </div> <button id = \"gfg\">Open Dialog</button> </body></html>",
"e": 1981,
"s": 1041,
"text": null
},
{
"code": null,
"e": 1989,
"s": 1981,
"text": "Output:"
},
{
"code": null,
"e": 1999,
"s": 1989,
"text": "jQuery-UI"
},
{
"code": null,
"e": 2006,
"s": 1999,
"text": "JQuery"
},
{
"code": null,
"e": 2023,
"s": 2006,
"text": "Web Technologies"
}
]
|
Python | Merge two lists alternatively | 09 May, 2019
Given two lists, write a Python program to merge the given lists in an alternative fashion, provided that the two lists are of equal length.
Examples:
Input : lst1 = [1, 2, 3]
lst2 = ['a', 'b', 'c']
Output : [1, 'a', 2, 'b', 3, 'c']
Input : lst1 = ['name', 'alice', 'bob']
lst2 = ['marks', 87, 56]
Output : ['name', 'marks', 'alice', 87, 'bob', 56]
Method #1 : List comprehension
# Python3 program to merge two lists # alternatively def countList(lst1, lst2): return [sub[item] for item in range(len(lst2)) for sub in [lst1, lst2]] # Driver codelst1 = [1, 2, 3]lst2 = ['a', 'b', 'c']print(countList(lst1, lst2))
[1, 'a', 2, 'b', 3, 'c']
There is an alternative to use list comprehension with zip() as given below –
def countList(lst1, lst2): return [item for pair in zip(lst1, lst2 + [0]) for item in pair]
Method #2 : Using itertools.cycle()
# Python3 program to merge two lists # alternativelyfrom itertools import cycle def countList(lst1, lst2): iters = [iter(lst1), iter(lst2)] return list(iter.__next__() for iter in cycle(iters)) # Driver codelst1 = [1, 2, 3]lst2 = ['a', 'b', 'c']print(countList(lst1, lst2))
[1, 'a', 2, 'b', 3, 'c']
Method #3 : Using reduce()
# Python3 program to merge two lists # alternativelyimport operatorfrom functools import reduce def countList(lst1, lst2): return reduce(operator.add, zip(lst1, lst2)) # Driver codelst1 = [1, 2, 3]lst2 = ['a', 'b', 'c']print(countList(lst1, lst2))
(1, 'a', 2, 'b', 3, 'c')
Method #4 : Using numpy module
# Python3 program to merge two lists # alternativelyimport numpy as np def countList(lst1, lst2): return np.array([[i, j] for i, j in zip(lst1, lst2)]).ravel() # Driver codelst1 = [1, 2, 3]lst2 = ['a', 'b', 'c']print(countList(lst1, lst2))
['1' 'a' '2' 'b' '3' 'c']
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 May, 2019"
},
{
"code": null,
"e": 169,
"s": 28,
"text": "Given two lists, write a Python program to merge the given lists in an alternative fashion, provided that the two lists are of equal length."
},
{
"code": null,
"e": 179,
"s": 169,
"text": "Examples:"
},
{
"code": null,
"e": 395,
"s": 179,
"text": "Input : lst1 = [1, 2, 3]\n lst2 = ['a', 'b', 'c']\nOutput : [1, 'a', 2, 'b', 3, 'c']\n\nInput : lst1 = ['name', 'alice', 'bob']\n lst2 = ['marks', 87, 56]\nOutput : ['name', 'marks', 'alice', 87, 'bob', 56]\n"
},
{
"code": null,
"e": 427,
"s": 395,
"text": " Method #1 : List comprehension"
},
{
"code": "# Python3 program to merge two lists # alternatively def countList(lst1, lst2): return [sub[item] for item in range(len(lst2)) for sub in [lst1, lst2]] # Driver codelst1 = [1, 2, 3]lst2 = ['a', 'b', 'c']print(countList(lst1, lst2))",
"e": 689,
"s": 427,
"text": null
},
{
"code": null,
"e": 715,
"s": 689,
"text": "[1, 'a', 2, 'b', 3, 'c']\n"
},
{
"code": null,
"e": 793,
"s": 715,
"text": "There is an alternative to use list comprehension with zip() as given below –"
},
{
"code": "def countList(lst1, lst2): return [item for pair in zip(lst1, lst2 + [0]) for item in pair]",
"e": 920,
"s": 793,
"text": null
},
{
"code": null,
"e": 957,
"s": 920,
"text": " Method #2 : Using itertools.cycle()"
},
{
"code": "# Python3 program to merge two lists # alternativelyfrom itertools import cycle def countList(lst1, lst2): iters = [iter(lst1), iter(lst2)] return list(iter.__next__() for iter in cycle(iters)) # Driver codelst1 = [1, 2, 3]lst2 = ['a', 'b', 'c']print(countList(lst1, lst2))",
"e": 1243,
"s": 957,
"text": null
},
{
"code": null,
"e": 1269,
"s": 1243,
"text": "[1, 'a', 2, 'b', 3, 'c']\n"
},
{
"code": null,
"e": 1297,
"s": 1269,
"text": " Method #3 : Using reduce()"
},
{
"code": "# Python3 program to merge two lists # alternativelyimport operatorfrom functools import reduce def countList(lst1, lst2): return reduce(operator.add, zip(lst1, lst2)) # Driver codelst1 = [1, 2, 3]lst2 = ['a', 'b', 'c']print(countList(lst1, lst2))",
"e": 1554,
"s": 1297,
"text": null
},
{
"code": null,
"e": 1580,
"s": 1554,
"text": "(1, 'a', 2, 'b', 3, 'c')\n"
},
{
"code": null,
"e": 1612,
"s": 1580,
"text": " Method #4 : Using numpy module"
},
{
"code": "# Python3 program to merge two lists # alternativelyimport numpy as np def countList(lst1, lst2): return np.array([[i, j] for i, j in zip(lst1, lst2)]).ravel() # Driver codelst1 = [1, 2, 3]lst2 = ['a', 'b', 'c']print(countList(lst1, lst2))",
"e": 1861,
"s": 1612,
"text": null
},
{
"code": null,
"e": 1888,
"s": 1861,
"text": "['1' 'a' '2' 'b' '3' 'c']\n"
},
{
"code": null,
"e": 1909,
"s": 1888,
"text": "Python list-programs"
},
{
"code": null,
"e": 1916,
"s": 1909,
"text": "Python"
},
{
"code": null,
"e": 1932,
"s": 1916,
"text": "Python Programs"
}
]
|
SoundPool in Android with Examples | 02 Jul, 2020
In this article, we will learn about how to add SoundPool class in android. A collection of audio samples can be loaded into memory from a resource and can be used. SoundPool class is used to play short repeating sound whereas MediaPlayer class is used to play longer clips like music. It uses a MediaPlayer service to decode the audio. Forex:- A game consists of several levels of play. For each level, there is a set of unique sounds that are used only by that level. For that, we used the SoundPool class todo our work. So learning SoundPool class gives a better understanding to deal with the short audio clips.
Approach:
Create a new Android Resource Directory and for thatright-click on res folder -> Android Resource Directory,make sure to select resource type as raw. In this raw folder paste your audio clips.Add the following code in activity_main.xml file. Here three Buttons are added. Each button if clicked will invoke playSound method.activity_main.xmlactivity_main.xml<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" tools:context=".MainActivity"> <Button android:id="@+id/button_sound1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="playSound" android:text="Game Over" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <Button android:id="@+id/button_sound2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="playSound" android:text="Player Died" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.472" /> <Button android:id="@+id/button_sound3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="playSound" android:text="Level Complete" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.472" /> </androidx.constraintlayout.widget.ConstraintLayout>Add the following code in MainActivity.java file. Here, an object of SoundPool class is created and three audio clips, game_over, level_complete and player_died are added using load method. playSound method is also added which plays the audio clip associated with the respective button.MainActivity.javaMainActivity.javapackage org.geeksforgeeks.gfgsoundpool; import androidx.appcompat.app.AppCompatActivity;import android.media.AudioAttributes;import android.media.AudioManager;import android.media.SoundPool;import android.os.Build;import android.os.Bundle;import android.view.View; public class MainActivity extends AppCompatActivity { SoundPool soundPool; int game_over, level_complete, player_died; @Override protected void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { AudioAttributes audioAttributes = new AudioAttributes .Builder() .setUsage( AudioAttributes .USAGE_ASSISTANCE_SONIFICATION) .setContentType( AudioAttributes .CONTENT_TYPE_SONIFICATION) .build(); soundPool = new SoundPool .Builder() .setMaxStreams(3) .setAudioAttributes( audioAttributes) .build(); } else { soundPool = new SoundPool( 3, AudioManager.STREAM_MUSIC, 0); } // This load function takes // three parameter context, // file_name and priority. game_over = soundPool .load( this, R.raw.game_over, 1); level_complete = soundPool.load( this, R.raw.level_complete, 1); player_died = soundPool.load( this, R.raw.player_died, 1); } public void playSound(View v) { switch (v.getId()) { case R.id.button_sound1: // This play function // takes five parameter // leftVolume, rightVolume, // priority, loop and rate. soundPool.play( game_over, 1, 1, 0, 0, 1); soundPool.autoPause(); break; case R.id.button_sound2: soundPool.play( player_died, 1, 1, 0, 0, 1); break; case R.id.button_sound3: soundPool.play( level_complete, 1, 1, 0, 0, 1); break; } }}Output:Video Playerhttps://media.geeksforgeeks.org/wp-content/uploads/20200630220913/20200630-220134-720x1600.mp400:0000:0000:09Use Up/Down Arrow keys to increase or decrease volume.My Personal Notes
arrow_drop_upSave
Create a new Android Resource Directory and for thatright-click on res folder -> Android Resource Directory,make sure to select resource type as raw. In this raw folder paste your audio clips.
Add the following code in activity_main.xml file. Here three Buttons are added. Each button if clicked will invoke playSound method.activity_main.xmlactivity_main.xml<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" tools:context=".MainActivity"> <Button android:id="@+id/button_sound1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="playSound" android:text="Game Over" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <Button android:id="@+id/button_sound2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="playSound" android:text="Player Died" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.472" /> <Button android:id="@+id/button_sound3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="playSound" android:text="Level Complete" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.472" /> </androidx.constraintlayout.widget.ConstraintLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" tools:context=".MainActivity"> <Button android:id="@+id/button_sound1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="playSound" android:text="Game Over" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <Button android:id="@+id/button_sound2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="playSound" android:text="Player Died" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.472" /> <Button android:id="@+id/button_sound3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="playSound" android:text="Level Complete" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.472" /> </androidx.constraintlayout.widget.ConstraintLayout>
Add the following code in MainActivity.java file. Here, an object of SoundPool class is created and three audio clips, game_over, level_complete and player_died are added using load method. playSound method is also added which plays the audio clip associated with the respective button.MainActivity.javaMainActivity.javapackage org.geeksforgeeks.gfgsoundpool; import androidx.appcompat.app.AppCompatActivity;import android.media.AudioAttributes;import android.media.AudioManager;import android.media.SoundPool;import android.os.Build;import android.os.Bundle;import android.view.View; public class MainActivity extends AppCompatActivity { SoundPool soundPool; int game_over, level_complete, player_died; @Override protected void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { AudioAttributes audioAttributes = new AudioAttributes .Builder() .setUsage( AudioAttributes .USAGE_ASSISTANCE_SONIFICATION) .setContentType( AudioAttributes .CONTENT_TYPE_SONIFICATION) .build(); soundPool = new SoundPool .Builder() .setMaxStreams(3) .setAudioAttributes( audioAttributes) .build(); } else { soundPool = new SoundPool( 3, AudioManager.STREAM_MUSIC, 0); } // This load function takes // three parameter context, // file_name and priority. game_over = soundPool .load( this, R.raw.game_over, 1); level_complete = soundPool.load( this, R.raw.level_complete, 1); player_died = soundPool.load( this, R.raw.player_died, 1); } public void playSound(View v) { switch (v.getId()) { case R.id.button_sound1: // This play function // takes five parameter // leftVolume, rightVolume, // priority, loop and rate. soundPool.play( game_over, 1, 1, 0, 0, 1); soundPool.autoPause(); break; case R.id.button_sound2: soundPool.play( player_died, 1, 1, 0, 0, 1); break; case R.id.button_sound3: soundPool.play( level_complete, 1, 1, 0, 0, 1); break; } }}
MainActivity.java
package org.geeksforgeeks.gfgsoundpool; import androidx.appcompat.app.AppCompatActivity;import android.media.AudioAttributes;import android.media.AudioManager;import android.media.SoundPool;import android.os.Build;import android.os.Bundle;import android.view.View; public class MainActivity extends AppCompatActivity { SoundPool soundPool; int game_over, level_complete, player_died; @Override protected void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { AudioAttributes audioAttributes = new AudioAttributes .Builder() .setUsage( AudioAttributes .USAGE_ASSISTANCE_SONIFICATION) .setContentType( AudioAttributes .CONTENT_TYPE_SONIFICATION) .build(); soundPool = new SoundPool .Builder() .setMaxStreams(3) .setAudioAttributes( audioAttributes) .build(); } else { soundPool = new SoundPool( 3, AudioManager.STREAM_MUSIC, 0); } // This load function takes // three parameter context, // file_name and priority. game_over = soundPool .load( this, R.raw.game_over, 1); level_complete = soundPool.load( this, R.raw.level_complete, 1); player_died = soundPool.load( this, R.raw.player_died, 1); } public void playSound(View v) { switch (v.getId()) { case R.id.button_sound1: // This play function // takes five parameter // leftVolume, rightVolume, // priority, loop and rate. soundPool.play( game_over, 1, 1, 0, 0, 1); soundPool.autoPause(); break; case R.id.button_sound2: soundPool.play( player_died, 1, 1, 0, 0, 1); break; case R.id.button_sound3: soundPool.play( level_complete, 1, 1, 0, 0, 1); break; } }}
Output:
android
How To
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Set Git Username and Password in GitBash?
How to Install Jupyter Notebook on MacOS?
How to Install and Use NVM on Windows?
How to Install Python Packages for AWS Lambda Layers?
How to Install Git in VS Code?
Arrays in Java
Arrays.sort() in Java with examples
Split() String method in Java with examples
Reverse a string in Java
Object Oriented Programming (OOPs) Concept in Java | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n02 Jul, 2020"
},
{
"code": null,
"e": 670,
"s": 54,
"text": "In this article, we will learn about how to add SoundPool class in android. A collection of audio samples can be loaded into memory from a resource and can be used. SoundPool class is used to play short repeating sound whereas MediaPlayer class is used to play longer clips like music. It uses a MediaPlayer service to decode the audio. Forex:- A game consists of several levels of play. For each level, there is a set of unique sounds that are used only by that level. For that, we used the SoundPool class todo our work. So learning SoundPool class gives a better understanding to deal with the short audio clips."
},
{
"code": null,
"e": 680,
"s": 670,
"text": "Approach:"
},
{
"code": null,
"e": 5876,
"s": 680,
"text": "Create a new Android Resource Directory and for thatright-click on res folder -> Android Resource Directory,make sure to select resource type as raw. In this raw folder paste your audio clips.Add the following code in activity_main.xml file. Here three Buttons are added. Each button if clicked will invoke playSound method.activity_main.xmlactivity_main.xml<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:gravity=\"center\" tools:context=\".MainActivity\"> <Button android:id=\"@+id/button_sound1\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:onClick=\"playSound\" android:text=\"Game Over\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> <Button android:id=\"@+id/button_sound2\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:onClick=\"playSound\" android:text=\"Player Died\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" app:layout_constraintVertical_bias=\"0.472\" /> <Button android:id=\"@+id/button_sound3\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:onClick=\"playSound\" android:text=\"Level Complete\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" app:layout_constraintVertical_bias=\"0.472\" /> </androidx.constraintlayout.widget.ConstraintLayout>Add the following code in MainActivity.java file. Here, an object of SoundPool class is created and three audio clips, game_over, level_complete and player_died are added using load method. playSound method is also added which plays the audio clip associated with the respective button.MainActivity.javaMainActivity.javapackage org.geeksforgeeks.gfgsoundpool; import androidx.appcompat.app.AppCompatActivity;import android.media.AudioAttributes;import android.media.AudioManager;import android.media.SoundPool;import android.os.Build;import android.os.Bundle;import android.view.View; public class MainActivity extends AppCompatActivity { SoundPool soundPool; int game_over, level_complete, player_died; @Override protected void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { AudioAttributes audioAttributes = new AudioAttributes .Builder() .setUsage( AudioAttributes .USAGE_ASSISTANCE_SONIFICATION) .setContentType( AudioAttributes .CONTENT_TYPE_SONIFICATION) .build(); soundPool = new SoundPool .Builder() .setMaxStreams(3) .setAudioAttributes( audioAttributes) .build(); } else { soundPool = new SoundPool( 3, AudioManager.STREAM_MUSIC, 0); } // This load function takes // three parameter context, // file_name and priority. game_over = soundPool .load( this, R.raw.game_over, 1); level_complete = soundPool.load( this, R.raw.level_complete, 1); player_died = soundPool.load( this, R.raw.player_died, 1); } public void playSound(View v) { switch (v.getId()) { case R.id.button_sound1: // This play function // takes five parameter // leftVolume, rightVolume, // priority, loop and rate. soundPool.play( game_over, 1, 1, 0, 0, 1); soundPool.autoPause(); break; case R.id.button_sound2: soundPool.play( player_died, 1, 1, 0, 0, 1); break; case R.id.button_sound3: soundPool.play( level_complete, 1, 1, 0, 0, 1); break; } }}Output:Video Playerhttps://media.geeksforgeeks.org/wp-content/uploads/20200630220913/20200630-220134-720x1600.mp400:0000:0000:09Use Up/Down Arrow keys to increase or decrease volume.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 6069,
"s": 5876,
"text": "Create a new Android Resource Directory and for thatright-click on res folder -> Android Resource Directory,make sure to select resource type as raw. In this raw folder paste your audio clips."
},
{
"code": null,
"e": 7883,
"s": 6069,
"text": "Add the following code in activity_main.xml file. Here three Buttons are added. Each button if clicked will invoke playSound method.activity_main.xmlactivity_main.xml<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:gravity=\"center\" tools:context=\".MainActivity\"> <Button android:id=\"@+id/button_sound1\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:onClick=\"playSound\" android:text=\"Game Over\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> <Button android:id=\"@+id/button_sound2\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:onClick=\"playSound\" android:text=\"Player Died\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" app:layout_constraintVertical_bias=\"0.472\" /> <Button android:id=\"@+id/button_sound3\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:onClick=\"playSound\" android:text=\"Level Complete\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" app:layout_constraintVertical_bias=\"0.472\" /> </androidx.constraintlayout.widget.ConstraintLayout>"
},
{
"code": null,
"e": 7901,
"s": 7883,
"text": "activity_main.xml"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:gravity=\"center\" tools:context=\".MainActivity\"> <Button android:id=\"@+id/button_sound1\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:onClick=\"playSound\" android:text=\"Game Over\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> <Button android:id=\"@+id/button_sound2\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:onClick=\"playSound\" android:text=\"Player Died\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" app:layout_constraintVertical_bias=\"0.472\" /> <Button android:id=\"@+id/button_sound3\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:onClick=\"playSound\" android:text=\"Level Complete\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" app:layout_constraintVertical_bias=\"0.472\" /> </androidx.constraintlayout.widget.ConstraintLayout>",
"e": 9549,
"s": 7901,
"text": null
},
{
"code": null,
"e": 12523,
"s": 9549,
"text": "Add the following code in MainActivity.java file. Here, an object of SoundPool class is created and three audio clips, game_over, level_complete and player_died are added using load method. playSound method is also added which plays the audio clip associated with the respective button.MainActivity.javaMainActivity.javapackage org.geeksforgeeks.gfgsoundpool; import androidx.appcompat.app.AppCompatActivity;import android.media.AudioAttributes;import android.media.AudioManager;import android.media.SoundPool;import android.os.Build;import android.os.Bundle;import android.view.View; public class MainActivity extends AppCompatActivity { SoundPool soundPool; int game_over, level_complete, player_died; @Override protected void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { AudioAttributes audioAttributes = new AudioAttributes .Builder() .setUsage( AudioAttributes .USAGE_ASSISTANCE_SONIFICATION) .setContentType( AudioAttributes .CONTENT_TYPE_SONIFICATION) .build(); soundPool = new SoundPool .Builder() .setMaxStreams(3) .setAudioAttributes( audioAttributes) .build(); } else { soundPool = new SoundPool( 3, AudioManager.STREAM_MUSIC, 0); } // This load function takes // three parameter context, // file_name and priority. game_over = soundPool .load( this, R.raw.game_over, 1); level_complete = soundPool.load( this, R.raw.level_complete, 1); player_died = soundPool.load( this, R.raw.player_died, 1); } public void playSound(View v) { switch (v.getId()) { case R.id.button_sound1: // This play function // takes five parameter // leftVolume, rightVolume, // priority, loop and rate. soundPool.play( game_over, 1, 1, 0, 0, 1); soundPool.autoPause(); break; case R.id.button_sound2: soundPool.play( player_died, 1, 1, 0, 0, 1); break; case R.id.button_sound3: soundPool.play( level_complete, 1, 1, 0, 0, 1); break; } }}"
},
{
"code": null,
"e": 12541,
"s": 12523,
"text": "MainActivity.java"
},
{
"code": "package org.geeksforgeeks.gfgsoundpool; import androidx.appcompat.app.AppCompatActivity;import android.media.AudioAttributes;import android.media.AudioManager;import android.media.SoundPool;import android.os.Build;import android.os.Bundle;import android.view.View; public class MainActivity extends AppCompatActivity { SoundPool soundPool; int game_over, level_complete, player_died; @Override protected void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { AudioAttributes audioAttributes = new AudioAttributes .Builder() .setUsage( AudioAttributes .USAGE_ASSISTANCE_SONIFICATION) .setContentType( AudioAttributes .CONTENT_TYPE_SONIFICATION) .build(); soundPool = new SoundPool .Builder() .setMaxStreams(3) .setAudioAttributes( audioAttributes) .build(); } else { soundPool = new SoundPool( 3, AudioManager.STREAM_MUSIC, 0); } // This load function takes // three parameter context, // file_name and priority. game_over = soundPool .load( this, R.raw.game_over, 1); level_complete = soundPool.load( this, R.raw.level_complete, 1); player_died = soundPool.load( this, R.raw.player_died, 1); } public void playSound(View v) { switch (v.getId()) { case R.id.button_sound1: // This play function // takes five parameter // leftVolume, rightVolume, // priority, loop and rate. soundPool.play( game_over, 1, 1, 0, 0, 1); soundPool.autoPause(); break; case R.id.button_sound2: soundPool.play( player_died, 1, 1, 0, 0, 1); break; case R.id.button_sound3: soundPool.play( level_complete, 1, 1, 0, 0, 1); break; } }}",
"e": 15195,
"s": 12541,
"text": null
},
{
"code": null,
"e": 15203,
"s": 15195,
"text": "Output:"
},
{
"code": null,
"e": 15211,
"s": 15203,
"text": "android"
},
{
"code": null,
"e": 15218,
"s": 15211,
"text": "How To"
},
{
"code": null,
"e": 15223,
"s": 15218,
"text": "Java"
},
{
"code": null,
"e": 15228,
"s": 15223,
"text": "Java"
},
{
"code": null,
"e": 15326,
"s": 15228,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 15375,
"s": 15326,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 15417,
"s": 15375,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 15456,
"s": 15417,
"text": "How to Install and Use NVM on Windows?"
},
{
"code": null,
"e": 15510,
"s": 15456,
"text": "How to Install Python Packages for AWS Lambda Layers?"
},
{
"code": null,
"e": 15541,
"s": 15510,
"text": "How to Install Git in VS Code?"
},
{
"code": null,
"e": 15556,
"s": 15541,
"text": "Arrays in Java"
},
{
"code": null,
"e": 15592,
"s": 15556,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 15636,
"s": 15592,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 15661,
"s": 15636,
"text": "Reverse a string in Java"
}
]
|
Node.js fs.rmdirSync() Method | 11 Oct, 2021
The fs.rmdirSync() method is used to synchronously delete a directory at the given path. It can also be used recursively to remove nested directories by configuring the options object. It returns undefined.Syntax:
fs.rmdirSync( path, options )
Parameters: This method accept two parameters as mentioned above and described below:
path: It holds the path of the directory that has to be removed. It can be a String, Buffer or URL.
options: It is an object that can be used to specify optional parameters that will affect the operation. It has three optional parameters:recursive: It is a boolean value which specifies if recursive directory removal is performed. In this mode, errors are not reported if the specified path is not found and the operation is retried on failure. The default value is false.maxRetries: It is an integer value which specifies the number of times Node.js will try to perform the operation, if it fails due to any error. The operations are performed after the given retry delay. This option is ignored if the recursive option is not set to true. The default value is 0.retryDelay: It is an integer value which specifies the time in milliseconds to wait before the operation is retried. This option is ignored if the recursive option is not set to true. The default value is 100 milliseconds.
recursive: It is a boolean value which specifies if recursive directory removal is performed. In this mode, errors are not reported if the specified path is not found and the operation is retried on failure. The default value is false.
maxRetries: It is an integer value which specifies the number of times Node.js will try to perform the operation, if it fails due to any error. The operations are performed after the given retry delay. This option is ignored if the recursive option is not set to true. The default value is 0.
retryDelay: It is an integer value which specifies the time in milliseconds to wait before the operation is retried. This option is ignored if the recursive option is not set to true. The default value is 100 milliseconds.
Below examples illustrate the fs.rmdirSync() method in Node.js:Example 1: This example uses fs.rmdirSync() method to delete a directory.
javascript
// Node.js program to demonstrate the// fs.rmdirSync() method // Import the filesystem moduleconst fs = require('fs'); // Get the current filenames// in the directorygetCurrentFilenames(); fs.rmdirSync("directory_one");console.log("Folder Deleted!"); // Get the current filenames// in the directory to verifygetCurrentFilenames(); // Function to get current filenames// in directoryfunction getCurrentFilenames() { console.log("\nCurrent filenames:"); fs.readdirSync(__dirname).forEach(file => { console.log(file); }); // console.log("\n");}
Output:
Current filenames:
directory_one
index.js
package.json
Folder Deleted!
Current filenames:
index.js
package.json
Example 2: This example uses fs.rmdirSync() method with the recursive parameter to delete nested directories.
javascript
// Node.js program to demonstrate the// fs.rmdirSync() method // Get the current filenames// in the directorygetCurrentFilenames(); // Using the recursive option to delete// multiple directories that are nestedfs.rmdirSync("directory_one", { recursive: true,});console.log("Directories Deleted!"); // Get the current filenames// in the directory to verifygetCurrentFilenames(); // Function to get current filenames// in directoryfunction getCurrentFilenames() { console.log("\nCurrent filenames:"); fs.readdirSync(__dirname).forEach(file => { console.log(file); }); console.log("\n");}
Output:
Current filenames:
directory_one
index.js
package.json
Directories Deleted!
Current filenames:
index.js
package.json
Reference: https://nodejs.org/api/fs.html#fs_fs_rmdirsync_path_options
arorakashish0911
Node.js-fs-module
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Oct, 2021"
},
{
"code": null,
"e": 244,
"s": 28,
"text": "The fs.rmdirSync() method is used to synchronously delete a directory at the given path. It can also be used recursively to remove nested directories by configuring the options object. It returns undefined.Syntax: "
},
{
"code": null,
"e": 274,
"s": 244,
"text": "fs.rmdirSync( path, options )"
},
{
"code": null,
"e": 362,
"s": 274,
"text": "Parameters: This method accept two parameters as mentioned above and described below: "
},
{
"code": null,
"e": 462,
"s": 362,
"text": "path: It holds the path of the directory that has to be removed. It can be a String, Buffer or URL."
},
{
"code": null,
"e": 1350,
"s": 462,
"text": "options: It is an object that can be used to specify optional parameters that will affect the operation. It has three optional parameters:recursive: It is a boolean value which specifies if recursive directory removal is performed. In this mode, errors are not reported if the specified path is not found and the operation is retried on failure. The default value is false.maxRetries: It is an integer value which specifies the number of times Node.js will try to perform the operation, if it fails due to any error. The operations are performed after the given retry delay. This option is ignored if the recursive option is not set to true. The default value is 0.retryDelay: It is an integer value which specifies the time in milliseconds to wait before the operation is retried. This option is ignored if the recursive option is not set to true. The default value is 100 milliseconds."
},
{
"code": null,
"e": 1586,
"s": 1350,
"text": "recursive: It is a boolean value which specifies if recursive directory removal is performed. In this mode, errors are not reported if the specified path is not found and the operation is retried on failure. The default value is false."
},
{
"code": null,
"e": 1879,
"s": 1586,
"text": "maxRetries: It is an integer value which specifies the number of times Node.js will try to perform the operation, if it fails due to any error. The operations are performed after the given retry delay. This option is ignored if the recursive option is not set to true. The default value is 0."
},
{
"code": null,
"e": 2102,
"s": 1879,
"text": "retryDelay: It is an integer value which specifies the time in milliseconds to wait before the operation is retried. This option is ignored if the recursive option is not set to true. The default value is 100 milliseconds."
},
{
"code": null,
"e": 2240,
"s": 2102,
"text": "Below examples illustrate the fs.rmdirSync() method in Node.js:Example 1: This example uses fs.rmdirSync() method to delete a directory. "
},
{
"code": null,
"e": 2251,
"s": 2240,
"text": "javascript"
},
{
"code": "// Node.js program to demonstrate the// fs.rmdirSync() method // Import the filesystem moduleconst fs = require('fs'); // Get the current filenames// in the directorygetCurrentFilenames(); fs.rmdirSync(\"directory_one\");console.log(\"Folder Deleted!\"); // Get the current filenames// in the directory to verifygetCurrentFilenames(); // Function to get current filenames// in directoryfunction getCurrentFilenames() { console.log(\"\\nCurrent filenames:\"); fs.readdirSync(__dirname).forEach(file => { console.log(file); }); // console.log(\"\\n\");}",
"e": 2805,
"s": 2251,
"text": null
},
{
"code": null,
"e": 2815,
"s": 2805,
"text": "Output: "
},
{
"code": null,
"e": 2928,
"s": 2815,
"text": "Current filenames:\ndirectory_one\nindex.js\npackage.json\nFolder Deleted!\n\nCurrent filenames:\nindex.js\npackage.json"
},
{
"code": null,
"e": 3039,
"s": 2928,
"text": "Example 2: This example uses fs.rmdirSync() method with the recursive parameter to delete nested directories. "
},
{
"code": null,
"e": 3050,
"s": 3039,
"text": "javascript"
},
{
"code": "// Node.js program to demonstrate the// fs.rmdirSync() method // Get the current filenames// in the directorygetCurrentFilenames(); // Using the recursive option to delete// multiple directories that are nestedfs.rmdirSync(\"directory_one\", { recursive: true,});console.log(\"Directories Deleted!\"); // Get the current filenames// in the directory to verifygetCurrentFilenames(); // Function to get current filenames// in directoryfunction getCurrentFilenames() { console.log(\"\\nCurrent filenames:\"); fs.readdirSync(__dirname).forEach(file => { console.log(file); }); console.log(\"\\n\");}",
"e": 3650,
"s": 3050,
"text": null
},
{
"code": null,
"e": 3660,
"s": 3650,
"text": "Output: "
},
{
"code": null,
"e": 3780,
"s": 3660,
"text": "Current filenames:\ndirectory_one\nindex.js\npackage.json\n\n\nDirectories Deleted!\n\nCurrent filenames:\nindex.js\npackage.json"
},
{
"code": null,
"e": 3852,
"s": 3780,
"text": "Reference: https://nodejs.org/api/fs.html#fs_fs_rmdirsync_path_options "
},
{
"code": null,
"e": 3869,
"s": 3852,
"text": "arorakashish0911"
},
{
"code": null,
"e": 3887,
"s": 3869,
"text": "Node.js-fs-module"
},
{
"code": null,
"e": 3894,
"s": 3887,
"text": "Picked"
},
{
"code": null,
"e": 3902,
"s": 3894,
"text": "Node.js"
},
{
"code": null,
"e": 3919,
"s": 3902,
"text": "Web Technologies"
}
]
|
Toggle case of a string using Bitwise Operators | 16 Jun, 2022
Given a string, write a function that returns toggle case of a string using the bitwise operators in place.In ASCII codes, character ‘A’ is integer 65 = (0100 0001)2, while character ‘a’ is integer 97 = (0110 0001)2. Similarly, character ‘D’ is integer 68 = (0100 0100)2, while character ‘d’ is integer 100 = (0110 0100)2.
As we can see, only sixth least significant bit is different in ASCII code of ‘A’ and ‘a’. Similar behavior can be seen in ASCII code of ‘D’ and ‘d’. Therefore, we need to toggle this bit for toggling case.
Examples:
Input : "GeekSfOrgEEKs"
Output : "gEEKsFoRGeekS"
Input : "StRinG"
Output : "sTrINg"
The ASCII table is constructed in such way that the binary representation of lowercase letters is almost identical of binary representation of uppercase letters.
Toggling Case The integer with 6th LSB as 1 is 32 (0010 0000). Therefore, bitwise XORing of a character with 32 will toggle the 6th LSB of character and hence, will toggle its case. If character is upper case, it will be converted to lower case and vice versa.
C++
C
Java
Python3
C#
Javascript
// C++ program to get toggle case of a string#include <bits/stdc++.h>using namespace std; // tOGGLE cASE = swaps CAPS to lower// case and lower case to CAPSchar *toggleCase(char *a){ for(int i = 0; a[i] != '\0'; i++) { // Bitwise EXOR with 32 a[i] ^= 32; } return a;} // Driver Codeint main(){ char str[] = "CheRrY"; cout << "Toggle case: " << toggleCase(str) << endl; cout << "Original string: " << toggleCase(str) << endl; return 0;} // This code is contributed by noob2000
// C program to get toggle case of a string#include <stdio.h> // tOGGLE cASE = swaps CAPS to lower// case and lower case to CAPSchar *toggleCase(char *a){ for (int i=0; a[i]!='\0'; i++) { // Bitwise EXOR with 32 a[i] ^= 32; } return a;} // Driver Codeint main(){ char str[] = "CheRrY"; printf("Toggle case: %s\n", toggleCase(str)); printf("Original string: %s", toggleCase(str)); return 0;}
// program to get toggle case of a string public class Test{ static int x=32; // tOGGLE cASE = swaps CAPS to lower // case and lower case to CAPS static String toggleCase(char[] a) { for (int i=0; i<a.length; i++) { // Bitwise EXOR with 32 a[i]^=32; } return new String(a); } /* Driver program */ public static void main(String[] args) { String str = "CheRrY"; System.out.print("Toggle case: "); str = toggleCase(str.toCharArray()); System.out.println(str); System.out.print("Original string: "); str = toggleCase(str.toCharArray()); System.out.println(str); }}
# Python3 program to get toggle case of a stringx = 32; # tOGGLE cASE = swaps CAPS to lower# case and lower case to CAPSdef toggleCase(a): for i in range(len(a)): # Bitwise EXOR with 32 a = a[:i] + chr(ord(a[i]) ^ 32) + a[i + 1:]; return a; # Driver Codestr = "CheRrY";print("Toggle case: ", end = "");str = toggleCase(str);print(str); print("Original string: ", end = "");str = toggleCase(str);print(str); # This code is contributed by 29AjayKumar
// C# program to get toggle case of a stringusing System; class GFG { // tOGGLE cASE = swaps CAPS to lower // case and lower case to CAPS static string toggleCase(char []a) { for (int i = 0; i < a.Length; i++) { // Bitwise EXOR with 32 a[i] ^= (char)32; } return new string(a); } /* Driver program */ public static void Main() { string str = "CheRrY"; Console.Write("Toggle case: "); str = toggleCase(str.ToCharArray()); Console.WriteLine(str); Console.Write("Original string: "); str = toggleCase(str.ToCharArray()); Console.Write(str); }} // This code is contributed by nitin mittal.
<script>// program to get toggle case of a string x = 32; // tOGGLE cASE = swaps CAPS to lower// case and lower case to CAPSfunction toggleCase(a){ for (i = 0; i < a.length; i++) { // Bitwise EXOR with 32 a[i] = String.fromCharCode(a[i].charCodeAt(0)^32); } return a.join("");;} /* Driver program */var str = "CheRrY";document.write("Toggle case: ");str = toggleCase(str.split(''));document.write(str); document.write("<br>Original string: ");str = toggleCase(str.split(''));document.write(str); // This code is contributed by Princi Singh</script>
Output:
Toggle case: cHErRy
Original string: CheRrY
Time complexity : O(n) Auxiliary Space : O(1)
Thanks to Kumar Gaurav for improving the solution.Similar Article : Case conversion of a string using BitWise operators in C/C++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 write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nitin mittal
29AjayKumar
princi singh
noob2000
youmailmahibagi
Bit Magic
Strings
Strings
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Little and Big Endian Mystery
Bits manipulation (Important tactics)
Program to find whether a given number is power of 2
Binary representation of a given number
Divide two integers without using multiplication, division and mod operator
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Different Methods to Reverse a String in C++ | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n16 Jun, 2022"
},
{
"code": null,
"e": 375,
"s": 52,
"text": "Given a string, write a function that returns toggle case of a string using the bitwise operators in place.In ASCII codes, character ‘A’ is integer 65 = (0100 0001)2, while character ‘a’ is integer 97 = (0110 0001)2. Similarly, character ‘D’ is integer 68 = (0100 0100)2, while character ‘d’ is integer 100 = (0110 0100)2."
},
{
"code": null,
"e": 583,
"s": 375,
"text": "As we can see, only sixth least significant bit is different in ASCII code of ‘A’ and ‘a’. Similar behavior can be seen in ASCII code of ‘D’ and ‘d’. Therefore, we need to toggle this bit for toggling case. "
},
{
"code": null,
"e": 594,
"s": 583,
"text": "Examples: "
},
{
"code": null,
"e": 697,
"s": 594,
"text": "Input : \"GeekSfOrgEEKs\"\nOutput : \"gEEKsFoRGeekS\" \n\nInput : \"StRinG\"\nOutput : \"sTrINg\""
},
{
"code": null,
"e": 859,
"s": 697,
"text": "The ASCII table is constructed in such way that the binary representation of lowercase letters is almost identical of binary representation of uppercase letters."
},
{
"code": null,
"e": 1121,
"s": 859,
"text": "Toggling Case The integer with 6th LSB as 1 is 32 (0010 0000). Therefore, bitwise XORing of a character with 32 will toggle the 6th LSB of character and hence, will toggle its case. If character is upper case, it will be converted to lower case and vice versa. "
},
{
"code": null,
"e": 1125,
"s": 1121,
"text": "C++"
},
{
"code": null,
"e": 1127,
"s": 1125,
"text": "C"
},
{
"code": null,
"e": 1132,
"s": 1127,
"text": "Java"
},
{
"code": null,
"e": 1140,
"s": 1132,
"text": "Python3"
},
{
"code": null,
"e": 1143,
"s": 1140,
"text": "C#"
},
{
"code": null,
"e": 1154,
"s": 1143,
"text": "Javascript"
},
{
"code": "// C++ program to get toggle case of a string#include <bits/stdc++.h>using namespace std; // tOGGLE cASE = swaps CAPS to lower// case and lower case to CAPSchar *toggleCase(char *a){ for(int i = 0; a[i] != '\\0'; i++) { // Bitwise EXOR with 32 a[i] ^= 32; } return a;} // Driver Codeint main(){ char str[] = \"CheRrY\"; cout << \"Toggle case: \" << toggleCase(str) << endl; cout << \"Original string: \" << toggleCase(str) << endl; return 0;} // This code is contributed by noob2000",
"e": 1693,
"s": 1154,
"text": null
},
{
"code": "// C program to get toggle case of a string#include <stdio.h> // tOGGLE cASE = swaps CAPS to lower// case and lower case to CAPSchar *toggleCase(char *a){ for (int i=0; a[i]!='\\0'; i++) { // Bitwise EXOR with 32 a[i] ^= 32; } return a;} // Driver Codeint main(){ char str[] = \"CheRrY\"; printf(\"Toggle case: %s\\n\", toggleCase(str)); printf(\"Original string: %s\", toggleCase(str)); return 0;}",
"e": 2121,
"s": 1693,
"text": null
},
{
"code": "// program to get toggle case of a string public class Test{ static int x=32; // tOGGLE cASE = swaps CAPS to lower // case and lower case to CAPS static String toggleCase(char[] a) { for (int i=0; i<a.length; i++) { // Bitwise EXOR with 32 a[i]^=32; } return new String(a); } /* Driver program */ public static void main(String[] args) { String str = \"CheRrY\"; System.out.print(\"Toggle case: \"); str = toggleCase(str.toCharArray()); System.out.println(str); System.out.print(\"Original string: \"); str = toggleCase(str.toCharArray()); System.out.println(str); }}",
"e": 2839,
"s": 2121,
"text": null
},
{
"code": "# Python3 program to get toggle case of a stringx = 32; # tOGGLE cASE = swaps CAPS to lower# case and lower case to CAPSdef toggleCase(a): for i in range(len(a)): # Bitwise EXOR with 32 a = a[:i] + chr(ord(a[i]) ^ 32) + a[i + 1:]; return a; # Driver Codestr = \"CheRrY\";print(\"Toggle case: \", end = \"\");str = toggleCase(str);print(str); print(\"Original string: \", end = \"\");str = toggleCase(str);print(str); # This code is contributed by 29AjayKumar",
"e": 3310,
"s": 2839,
"text": null
},
{
"code": "// C# program to get toggle case of a stringusing System; class GFG { // tOGGLE cASE = swaps CAPS to lower // case and lower case to CAPS static string toggleCase(char []a) { for (int i = 0; i < a.Length; i++) { // Bitwise EXOR with 32 a[i] ^= (char)32; } return new string(a); } /* Driver program */ public static void Main() { string str = \"CheRrY\"; Console.Write(\"Toggle case: \"); str = toggleCase(str.ToCharArray()); Console.WriteLine(str); Console.Write(\"Original string: \"); str = toggleCase(str.ToCharArray()); Console.Write(str); }} // This code is contributed by nitin mittal.",
"e": 4059,
"s": 3310,
"text": null
},
{
"code": "<script>// program to get toggle case of a string x = 32; // tOGGLE cASE = swaps CAPS to lower// case and lower case to CAPSfunction toggleCase(a){ for (i = 0; i < a.length; i++) { // Bitwise EXOR with 32 a[i] = String.fromCharCode(a[i].charCodeAt(0)^32); } return a.join(\"\");;} /* Driver program */var str = \"CheRrY\";document.write(\"Toggle case: \");str = toggleCase(str.split(''));document.write(str); document.write(\"<br>Original string: \");str = toggleCase(str.split(''));document.write(str); // This code is contributed by Princi Singh</script>",
"e": 4638,
"s": 4059,
"text": null
},
{
"code": null,
"e": 4647,
"s": 4638,
"text": "Output: "
},
{
"code": null,
"e": 4691,
"s": 4647,
"text": "Toggle case: cHErRy\nOriginal string: CheRrY"
},
{
"code": null,
"e": 4737,
"s": 4691,
"text": "Time complexity : O(n) Auxiliary Space : O(1)"
},
{
"code": null,
"e": 5337,
"s": 4737,
"text": "Thanks to Kumar Gaurav for improving the solution.Similar Article : Case conversion of a string using BitWise operators in C/C++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 write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 5350,
"s": 5337,
"text": "nitin mittal"
},
{
"code": null,
"e": 5362,
"s": 5350,
"text": "29AjayKumar"
},
{
"code": null,
"e": 5375,
"s": 5362,
"text": "princi singh"
},
{
"code": null,
"e": 5384,
"s": 5375,
"text": "noob2000"
},
{
"code": null,
"e": 5400,
"s": 5384,
"text": "youmailmahibagi"
},
{
"code": null,
"e": 5410,
"s": 5400,
"text": "Bit Magic"
},
{
"code": null,
"e": 5418,
"s": 5410,
"text": "Strings"
},
{
"code": null,
"e": 5426,
"s": 5418,
"text": "Strings"
},
{
"code": null,
"e": 5436,
"s": 5426,
"text": "Bit Magic"
},
{
"code": null,
"e": 5534,
"s": 5436,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5564,
"s": 5534,
"text": "Little and Big Endian Mystery"
},
{
"code": null,
"e": 5602,
"s": 5564,
"text": "Bits manipulation (Important tactics)"
},
{
"code": null,
"e": 5655,
"s": 5602,
"text": "Program to find whether a given number is power of 2"
},
{
"code": null,
"e": 5695,
"s": 5655,
"text": "Binary representation of a given number"
},
{
"code": null,
"e": 5771,
"s": 5695,
"text": "Divide two integers without using multiplication, division and mod operator"
},
{
"code": null,
"e": 5817,
"s": 5771,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 5842,
"s": 5817,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 5902,
"s": 5842,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 5917,
"s": 5902,
"text": "C++ Data Types"
}
]
|
Maximum sum subarray having sum less than or equal to given sum | 09 Nov, 2021
Given an array of non-negative integers and a sum. We have to find sum of the subarray having a maximum sum less than or equal to the given sum in the array.
(Note: Given array contains only non-negative integers.)
Examples:
Input : arr[] = { 1, 2, 3, 4, 5 }
sum = 11
Output : 10
Subarray having maximum sum is { 1, 2, 3, 4 }
Input : arr[] = { 2, 4, 6, 8, 10 }
sum = 7
Output : 6
Subarray having maximum sum is { 2, 4 } or { 6 }
Naive Approach: We can find the maximum sum of the subarray by running two loops. But the time complexity will be O(N*N).
Efficient Approach: The subarray having maximum sum can be found by using a sliding window. If curr_sum is less than sum include array elements to it. If it becomes greater than sum removes elements from start in curr_sum. (This will work only in the case of non-negative elements.)
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find subarray having// maximum sum less than or equal to sum#include <bits/stdc++.h>using namespace std; // To find subarray with maximum sum// less than or equal to sumint findMaxSubarraySum(int arr[], int n, int sum){ // To store current sum and // max sum of subarrays int curr_sum = arr[0], max_sum = 0, start = 0; // To find max_sum less than sum for (int i = 1; i < n; i++) { // Update max_sum if it becomes // greater than curr_sum if (curr_sum <= sum) max_sum = max(max_sum, curr_sum); // If curr_sum becomes greater than // sum subtract starting elements of array while (start < i && curr_sum + arr[i] > sum) { curr_sum -= arr[start]; start++; } // If cur_sum becomes negative then start new subarray if (curr_sum < 0) { curr_sum = 0; } // Add elements to curr_sum curr_sum += arr[i]; } // Adding an extra check for last subarray if (curr_sum <= sum) max_sum = max(max_sum, curr_sum); return max_sum;} // Driver program to test above functionint main(){ int arr[] = {6, 8, 9}; int n = sizeof(arr) / sizeof(arr[0]); int sum = 20; cout << findMaxSubarraySum(arr, n, sum); return 0;}
// Java program to find subarray having// maximum sum less than or equal to sumpublic class Main { // To find subarray with maximum sum // less than or equal to sum static int findMaxSubarraySum(int arr[], int n, int sum) { // To store current sum and // max sum of subarrays int curr_sum = arr[0], max_sum = 0, start = 0; // To find max_sum less than sum for (int i = 1; i < n; i++) { // Update max_sum if it becomes // greater than curr_sum if (curr_sum <= sum) max_sum = Math.max(max_sum, curr_sum); // If curr_sum becomes greater than // sum subtract starting elements of array while (curr_sum + arr[i] > sum && start < i) { curr_sum -= arr[start]; start++; } // Add elements to curr_sum curr_sum += arr[i]; } // Adding an extra check for last subarray if (curr_sum <= sum) max_sum = Math.max(max_sum, curr_sum); return max_sum; } // Driver program to test above function public static void main(String[] args) { int arr[] = { 1, 2, 3, 4, 5 }; int n = arr.length; int sum = 11; System.out.println(findMaxSubarraySum(arr, n, sum)); }}
# Python3 program to find subarray having# maximum sum less than or equal to sum # To find subarray with maximum sum# less than or equal to sumdef findMaxSubarraySum(arr, n, sum): # To store current sum and # max sum of subarrays curr_sum = arr[0] max_sum = 0 start = 0; # To find max_sum less than sum for i in range(1, n): # Update max_sum if it becomes # greater than curr_sum if (curr_sum <= sum): max_sum = max(max_sum, curr_sum) # If curr_sum becomes greater than sum # subtract starting elements of array while (curr_sum + arr[i] > sum and start < i): curr_sum -= arr[start] start += 1 # Add elements to curr_sum curr_sum += arr[i] # Adding an extra check for last subarray if (curr_sum <= sum): max_sum = max(max_sum, curr_sum) return max_sum # Driver Codeif __name__ == '__main__': arr = [6, 8, 9] n = len(arr) sum = 20 print(findMaxSubarraySum(arr, n, sum)) # This code is contributed by# Surendra_Gangwar
// C# program to find subarray// having maximum sum less//than or equal to sumusing System; public class GFG{ // To find subarray with maximum // sum less than or equal // to sum static int findMaxSubarraySum(int []arr, int n, int sum) { // To store current sum and // max sum of subarrays int curr_sum = arr[0], max_sum = 0, start = 0; // To find max_sum less than sum for (int i = 1; i < n; i++) { // Update max_sum if it becomes // greater than curr_sum if (curr_sum <= sum) max_sum = Math.Max(max_sum, curr_sum); // If curr_sum becomes greater than // sum subtract starting elements of array while (curr_sum + arr[i] > sum && start < i) { curr_sum -= arr[start]; start++; } // Add elements to curr_sum curr_sum += arr[i]; } // Adding an extra check for last subarray if (curr_sum <= sum) max_sum = Math.Max(max_sum, curr_sum); return max_sum; } // Driver Code public static void Main() { int []arr = {1, 2, 3, 4, 5}; int n = arr.Length; int sum = 11; Console.Write(findMaxSubarraySum(arr, n, sum)); }} // This code is contributed by Nitin Mittal.
<?php// PHP program to find subarray having// maximum sum less than or equal to sum // To find subarray with maximum sum// less than or equal to sumfunction findMaxSubarraySum(&$arr, $n, $sum){ // To store current sum and // max sum of subarrays $curr_sum = $arr[0]; $max_sum = 0; $start = 0; // To find max_sum less than sum for ($i = 1; $i < $n; $i++) { // Update max_sum if it becomes // greater than curr_sum if ($curr_sum <= $sum) $max_sum = max($max_sum, $curr_sum); // If curr_sum becomes greater than // sum subtract starting elements of array while ($curr_sum + $arr[$i] > $sum && $start < $i) { $curr_sum -= $arr[$start]; $start++; } // Add elements to curr_sum $curr_sum += $arr[$i]; } // Adding an extra check for last subarray if ($curr_sum <= $sum) $max_sum = max($max_sum, $curr_sum); return $max_sum;} // Driver Code$arr = array(6, 8, 9);$n = sizeof($arr);$sum = 20; echo findMaxSubarraySum($arr, $n, $sum); // This code is contributed by ita_c?>
<script> // Javascript program to find subarray having// maximum sum less than or equal to sum // To find subarray with maximum sum// less than or equal to sumfunction findMaxSubarraySum(arr, n, sum){ // To store current sum and // max sum of subarrays let curr_sum = arr[0], max_sum = 0, start = 0; // To find max_sum less than sum for(let i = 1; i < n; i++) { // Update max_sum if it becomes // greater than curr_sum if (curr_sum <= sum) max_sum = Math.max(max_sum, curr_sum); // If curr_sum becomes greater than // sum subtract starting elements of array while (curr_sum + arr[i] > sum && start < i) { curr_sum -= arr[start]; start++; } // Add elements to curr_sum curr_sum += arr[i]; } // Adding an extra check for last subarray if (curr_sum <= sum) max_sum = Math.max(max_sum, curr_sum); return max_sum;} // Driver codelet arr = [ 6, 8, 9 ];let n = arr.length;let sum = 20; document.write(findMaxSubarraySum(arr, n, sum)); // This code is contributed by Mayank Tyagi </script>
17
Time Complexity: O(N*log(N))
Auxiliary Space: O(1)
If an array with all types(positive, negative or zero) of elements is given, we can use prefix sum and sets and worst case time complexity for that will be O(n.log(n)). You can refer Maximum Subarray sum less than or equal to k using set article for more clarity of this method.
This article is contributed by nuclode. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nitin mittal
ukasp
SURENDRA_GANGWAR
mayanktyagi1709
shreyadubey1802
pankajsharmagfg
rohitkumarsinghcna
sliding-window
subarray
subarray-sum
Arrays
sliding-window
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n09 Nov, 2021"
},
{
"code": null,
"e": 213,
"s": 54,
"text": "Given an array of non-negative integers and a sum. We have to find sum of the subarray having a maximum sum less than or equal to the given sum in the array. "
},
{
"code": null,
"e": 270,
"s": 213,
"text": "(Note: Given array contains only non-negative integers.)"
},
{
"code": null,
"e": 281,
"s": 270,
"text": "Examples: "
},
{
"code": null,
"e": 502,
"s": 281,
"text": "Input : arr[] = { 1, 2, 3, 4, 5 }\n sum = 11\nOutput : 10\nSubarray having maximum sum is { 1, 2, 3, 4 }\n\nInput : arr[] = { 2, 4, 6, 8, 10 }\n sum = 7\nOutput : 6\nSubarray having maximum sum is { 2, 4 } or { 6 }"
},
{
"code": null,
"e": 624,
"s": 502,
"text": "Naive Approach: We can find the maximum sum of the subarray by running two loops. But the time complexity will be O(N*N)."
},
{
"code": null,
"e": 908,
"s": 624,
"text": "Efficient Approach: The subarray having maximum sum can be found by using a sliding window. If curr_sum is less than sum include array elements to it. If it becomes greater than sum removes elements from start in curr_sum. (This will work only in the case of non-negative elements.)"
},
{
"code": null,
"e": 912,
"s": 908,
"text": "C++"
},
{
"code": null,
"e": 917,
"s": 912,
"text": "Java"
},
{
"code": null,
"e": 925,
"s": 917,
"text": "Python3"
},
{
"code": null,
"e": 928,
"s": 925,
"text": "C#"
},
{
"code": null,
"e": 932,
"s": 928,
"text": "PHP"
},
{
"code": null,
"e": 943,
"s": 932,
"text": "Javascript"
},
{
"code": "// C++ program to find subarray having// maximum sum less than or equal to sum#include <bits/stdc++.h>using namespace std; // To find subarray with maximum sum// less than or equal to sumint findMaxSubarraySum(int arr[], int n, int sum){ // To store current sum and // max sum of subarrays int curr_sum = arr[0], max_sum = 0, start = 0; // To find max_sum less than sum for (int i = 1; i < n; i++) { // Update max_sum if it becomes // greater than curr_sum if (curr_sum <= sum) max_sum = max(max_sum, curr_sum); // If curr_sum becomes greater than // sum subtract starting elements of array while (start < i && curr_sum + arr[i] > sum) { curr_sum -= arr[start]; start++; } // If cur_sum becomes negative then start new subarray if (curr_sum < 0) { curr_sum = 0; } // Add elements to curr_sum curr_sum += arr[i]; } // Adding an extra check for last subarray if (curr_sum <= sum) max_sum = max(max_sum, curr_sum); return max_sum;} // Driver program to test above functionint main(){ int arr[] = {6, 8, 9}; int n = sizeof(arr) / sizeof(arr[0]); int sum = 20; cout << findMaxSubarraySum(arr, n, sum); return 0;}",
"e": 2245,
"s": 943,
"text": null
},
{
"code": "// Java program to find subarray having// maximum sum less than or equal to sumpublic class Main { // To find subarray with maximum sum // less than or equal to sum static int findMaxSubarraySum(int arr[], int n, int sum) { // To store current sum and // max sum of subarrays int curr_sum = arr[0], max_sum = 0, start = 0; // To find max_sum less than sum for (int i = 1; i < n; i++) { // Update max_sum if it becomes // greater than curr_sum if (curr_sum <= sum) max_sum = Math.max(max_sum, curr_sum); // If curr_sum becomes greater than // sum subtract starting elements of array while (curr_sum + arr[i] > sum && start < i) { curr_sum -= arr[start]; start++; } // Add elements to curr_sum curr_sum += arr[i]; } // Adding an extra check for last subarray if (curr_sum <= sum) max_sum = Math.max(max_sum, curr_sum); return max_sum; } // Driver program to test above function public static void main(String[] args) { int arr[] = { 1, 2, 3, 4, 5 }; int n = arr.length; int sum = 11; System.out.println(findMaxSubarraySum(arr, n, sum)); }}",
"e": 3512,
"s": 2245,
"text": null
},
{
"code": "# Python3 program to find subarray having# maximum sum less than or equal to sum # To find subarray with maximum sum# less than or equal to sumdef findMaxSubarraySum(arr, n, sum): # To store current sum and # max sum of subarrays curr_sum = arr[0] max_sum = 0 start = 0; # To find max_sum less than sum for i in range(1, n): # Update max_sum if it becomes # greater than curr_sum if (curr_sum <= sum): max_sum = max(max_sum, curr_sum) # If curr_sum becomes greater than sum # subtract starting elements of array while (curr_sum + arr[i] > sum and start < i): curr_sum -= arr[start] start += 1 # Add elements to curr_sum curr_sum += arr[i] # Adding an extra check for last subarray if (curr_sum <= sum): max_sum = max(max_sum, curr_sum) return max_sum # Driver Codeif __name__ == '__main__': arr = [6, 8, 9] n = len(arr) sum = 20 print(findMaxSubarraySum(arr, n, sum)) # This code is contributed by# Surendra_Gangwar",
"e": 4594,
"s": 3512,
"text": null
},
{
"code": "// C# program to find subarray// having maximum sum less//than or equal to sumusing System; public class GFG{ // To find subarray with maximum // sum less than or equal // to sum static int findMaxSubarraySum(int []arr, int n, int sum) { // To store current sum and // max sum of subarrays int curr_sum = arr[0], max_sum = 0, start = 0; // To find max_sum less than sum for (int i = 1; i < n; i++) { // Update max_sum if it becomes // greater than curr_sum if (curr_sum <= sum) max_sum = Math.Max(max_sum, curr_sum); // If curr_sum becomes greater than // sum subtract starting elements of array while (curr_sum + arr[i] > sum && start < i) { curr_sum -= arr[start]; start++; } // Add elements to curr_sum curr_sum += arr[i]; } // Adding an extra check for last subarray if (curr_sum <= sum) max_sum = Math.Max(max_sum, curr_sum); return max_sum; } // Driver Code public static void Main() { int []arr = {1, 2, 3, 4, 5}; int n = arr.Length; int sum = 11; Console.Write(findMaxSubarraySum(arr, n, sum)); }} // This code is contributed by Nitin Mittal.",
"e": 5877,
"s": 4594,
"text": null
},
{
"code": "<?php// PHP program to find subarray having// maximum sum less than or equal to sum // To find subarray with maximum sum// less than or equal to sumfunction findMaxSubarraySum(&$arr, $n, $sum){ // To store current sum and // max sum of subarrays $curr_sum = $arr[0]; $max_sum = 0; $start = 0; // To find max_sum less than sum for ($i = 1; $i < $n; $i++) { // Update max_sum if it becomes // greater than curr_sum if ($curr_sum <= $sum) $max_sum = max($max_sum, $curr_sum); // If curr_sum becomes greater than // sum subtract starting elements of array while ($curr_sum + $arr[$i] > $sum && $start < $i) { $curr_sum -= $arr[$start]; $start++; } // Add elements to curr_sum $curr_sum += $arr[$i]; } // Adding an extra check for last subarray if ($curr_sum <= $sum) $max_sum = max($max_sum, $curr_sum); return $max_sum;} // Driver Code$arr = array(6, 8, 9);$n = sizeof($arr);$sum = 20; echo findMaxSubarraySum($arr, $n, $sum); // This code is contributed by ita_c?>",
"e": 7024,
"s": 5877,
"text": null
},
{
"code": "<script> // Javascript program to find subarray having// maximum sum less than or equal to sum // To find subarray with maximum sum// less than or equal to sumfunction findMaxSubarraySum(arr, n, sum){ // To store current sum and // max sum of subarrays let curr_sum = arr[0], max_sum = 0, start = 0; // To find max_sum less than sum for(let i = 1; i < n; i++) { // Update max_sum if it becomes // greater than curr_sum if (curr_sum <= sum) max_sum = Math.max(max_sum, curr_sum); // If curr_sum becomes greater than // sum subtract starting elements of array while (curr_sum + arr[i] > sum && start < i) { curr_sum -= arr[start]; start++; } // Add elements to curr_sum curr_sum += arr[i]; } // Adding an extra check for last subarray if (curr_sum <= sum) max_sum = Math.max(max_sum, curr_sum); return max_sum;} // Driver codelet arr = [ 6, 8, 9 ];let n = arr.length;let sum = 20; document.write(findMaxSubarraySum(arr, n, sum)); // This code is contributed by Mayank Tyagi </script>",
"e": 8184,
"s": 7024,
"text": null
},
{
"code": null,
"e": 8187,
"s": 8184,
"text": "17"
},
{
"code": null,
"e": 8218,
"s": 8189,
"text": "Time Complexity: O(N*log(N))"
},
{
"code": null,
"e": 8240,
"s": 8218,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 8520,
"s": 8240,
"text": "If an array with all types(positive, negative or zero) of elements is given, we can use prefix sum and sets and worst case time complexity for that will be O(n.log(n)). You can refer Maximum Subarray sum less than or equal to k using set article for more clarity of this method. "
},
{
"code": null,
"e": 8936,
"s": 8520,
"text": "This article is contributed by nuclode. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 8949,
"s": 8936,
"text": "nitin mittal"
},
{
"code": null,
"e": 8955,
"s": 8949,
"text": "ukasp"
},
{
"code": null,
"e": 8972,
"s": 8955,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 8988,
"s": 8972,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 9004,
"s": 8988,
"text": "shreyadubey1802"
},
{
"code": null,
"e": 9020,
"s": 9004,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 9039,
"s": 9020,
"text": "rohitkumarsinghcna"
},
{
"code": null,
"e": 9054,
"s": 9039,
"text": "sliding-window"
},
{
"code": null,
"e": 9063,
"s": 9054,
"text": "subarray"
},
{
"code": null,
"e": 9076,
"s": 9063,
"text": "subarray-sum"
},
{
"code": null,
"e": 9083,
"s": 9076,
"text": "Arrays"
},
{
"code": null,
"e": 9098,
"s": 9083,
"text": "sliding-window"
},
{
"code": null,
"e": 9105,
"s": 9098,
"text": "Arrays"
}
]
|
strings.Map() Function in Golang With Examples | 22 Dec, 2021
strings.Map() Function in Golang is used to return a copy of the string given string with all its characters modified according to the mapping function. If mapping returns a negative value, the character is dropped from the string with no replacement.
So whenever the user wants to make changes in a certain string, he can make use of the strings.Map() function. It replaces the character of a string with a user-desired character. If we need to mask certain characters including digits and spaces, this function can be used.
Syntax:
func Map(mapping func(rune) rune, s string) string
The mapping func(rune) rune parameter defines the character with which the original character needs to be replaced while the s parameter defines the original string inputted by the user.
Example 1:
// Golang program to illustrate // the strings.Map() Functionpackage main import ( "fmt"; "strings") func main() { modified := func(r rune) rune { if r == 'e' { return '@' } return r } input:= "Hello, Welcome to GeeksforGeeks" fmt.Println(input) // using the function result := strings.Map(modified, input) fmt.Println(result)}
Output:
Hello, Welcome to GeeksforGeeks
H@llo, W@lcom@ to G@@ksforG@@ks
Explanation: In the above example, we have used strings.Map() function to modify a string. We have defined a variable named “modified” that replaces character ‘e’ in the string with the symbol ‘@’. Another variable named “input” takes an input string that needs transformation.
Example 2: The strings.Map() function can also be used to remove the spaces between the words of a string.
// Golang program to illustrate // the strings.Map() Functionpackage main import ( "fmt"; "strings") func main() { transformed := func(r rune) rune { if r == ' ' { return 0 } return r } input:= "GeeksforGeeks is a computer science portal." fmt.Println(input) // using the function output := strings.Map(transformed, input) fmt.Println(output)}
Output:
GeeksforGeeks is a computer science portal.
GeeksforGeeksisacomputerscienceportal.
Explanation: In the above example, we have used strings.Map() function to remove the spaces in between a string. We have defined a variable named “transformed” that eliminates space ‘ ‘ in the string. This is done by returning 0 at the place of spaces. Another variable named “input” takes an input string whose in-between spaces need to be removed.
fakharanyhussein
Golang-String
Picked
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Go
Interfaces in Golang
Golang Maps
How to Split a String in Golang?
Different Ways to Find the Type of Variable in Golang
Slices in Golang
Anonymous function in Go Language
Channel in Golang
Go Programming Language (Introduction)
Strings in Golang | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Dec, 2021"
},
{
"code": null,
"e": 280,
"s": 28,
"text": "strings.Map() Function in Golang is used to return a copy of the string given string with all its characters modified according to the mapping function. If mapping returns a negative value, the character is dropped from the string with no replacement."
},
{
"code": null,
"e": 554,
"s": 280,
"text": "So whenever the user wants to make changes in a certain string, he can make use of the strings.Map() function. It replaces the character of a string with a user-desired character. If we need to mask certain characters including digits and spaces, this function can be used."
},
{
"code": null,
"e": 562,
"s": 554,
"text": "Syntax:"
},
{
"code": null,
"e": 613,
"s": 562,
"text": "func Map(mapping func(rune) rune, s string) string"
},
{
"code": null,
"e": 800,
"s": 613,
"text": "The mapping func(rune) rune parameter defines the character with which the original character needs to be replaced while the s parameter defines the original string inputted by the user."
},
{
"code": null,
"e": 811,
"s": 800,
"text": "Example 1:"
},
{
"code": "// Golang program to illustrate // the strings.Map() Functionpackage main import ( \"fmt\"; \"strings\") func main() { modified := func(r rune) rune { if r == 'e' { return '@' } return r } input:= \"Hello, Welcome to GeeksforGeeks\" fmt.Println(input) // using the function result := strings.Map(modified, input) fmt.Println(result)}",
"e": 1208,
"s": 811,
"text": null
},
{
"code": null,
"e": 1216,
"s": 1208,
"text": "Output:"
},
{
"code": null,
"e": 1281,
"s": 1216,
"text": "Hello, Welcome to GeeksforGeeks\nH@llo, W@lcom@ to G@@ksforG@@ks\n"
},
{
"code": null,
"e": 1559,
"s": 1281,
"text": "Explanation: In the above example, we have used strings.Map() function to modify a string. We have defined a variable named “modified” that replaces character ‘e’ in the string with the symbol ‘@’. Another variable named “input” takes an input string that needs transformation."
},
{
"code": null,
"e": 1666,
"s": 1559,
"text": "Example 2: The strings.Map() function can also be used to remove the spaces between the words of a string."
},
{
"code": "// Golang program to illustrate // the strings.Map() Functionpackage main import ( \"fmt\"; \"strings\") func main() { transformed := func(r rune) rune { if r == ' ' { return 0 } return r } input:= \"GeeksforGeeks is a computer science portal.\" fmt.Println(input) // using the function output := strings.Map(transformed, input) fmt.Println(output)}",
"e": 2090,
"s": 1666,
"text": null
},
{
"code": null,
"e": 2098,
"s": 2090,
"text": "Output:"
},
{
"code": null,
"e": 2182,
"s": 2098,
"text": "GeeksforGeeks is a computer science portal.\nGeeksforGeeksisacomputerscienceportal.\n"
},
{
"code": null,
"e": 2532,
"s": 2182,
"text": "Explanation: In the above example, we have used strings.Map() function to remove the spaces in between a string. We have defined a variable named “transformed” that eliminates space ‘ ‘ in the string. This is done by returning 0 at the place of spaces. Another variable named “input” takes an input string whose in-between spaces need to be removed."
},
{
"code": null,
"e": 2549,
"s": 2532,
"text": "fakharanyhussein"
},
{
"code": null,
"e": 2563,
"s": 2549,
"text": "Golang-String"
},
{
"code": null,
"e": 2570,
"s": 2563,
"text": "Picked"
},
{
"code": null,
"e": 2582,
"s": 2570,
"text": "Go Language"
},
{
"code": null,
"e": 2680,
"s": 2582,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2693,
"s": 2680,
"text": "Arrays in Go"
},
{
"code": null,
"e": 2714,
"s": 2693,
"text": "Interfaces in Golang"
},
{
"code": null,
"e": 2726,
"s": 2714,
"text": "Golang Maps"
},
{
"code": null,
"e": 2759,
"s": 2726,
"text": "How to Split a String in Golang?"
},
{
"code": null,
"e": 2813,
"s": 2759,
"text": "Different Ways to Find the Type of Variable in Golang"
},
{
"code": null,
"e": 2830,
"s": 2813,
"text": "Slices in Golang"
},
{
"code": null,
"e": 2864,
"s": 2830,
"text": "Anonymous function in Go Language"
},
{
"code": null,
"e": 2882,
"s": 2864,
"text": "Channel in Golang"
},
{
"code": null,
"e": 2921,
"s": 2882,
"text": "Go Programming Language (Introduction)"
}
]
|
Largest K digit number divisible by X | 16 Apr, 2021
Integers X and K are given. The task is to find the highest K-digit number divisible by X.Examples:
Input : X = 30, K = 3
Output : 990
990 is the largest three digit
number divisible by 30.
Input : X = 7, K = 2
Output : 98
A simple solution is to try all numbers starting from the largest K digit number (which is 999...K-times) and return the first number divisible by X.An efficient solution is to use below formula.
ans = MAX - (MAX % X)
where MAX is the largest K digit
number which is 999...K-times
The formula works on simple school method division. We remove remainder to get the largest divisible number.
C++
Java
Python3
C#
PHP
Javascript
// CPP code to find highest K-digit number divisible by X#include <bits/stdc++.h>using namespace std; // Function to compute the resultint answer(int X, int K){ // Computing MAX int MAX = pow(10, K) - 1; // returning ans return (MAX - (MAX % X));} // Driverint main(){ // Number whose divisible is to be found int X = 30; // Max K-digit divisible is to be found int K = 3; cout << answer(X, K);}
// Java code to find highest// K-digit number divisible by X import java.io.*;import java.lang.*; class GFG { public static double answer(double X, double K) { double i = 10; // Computing MAX double MAX = Math.pow(i, K) - 1; // returning ans return (MAX - (MAX % X)); } public static void main(String[] args) { // Number whose divisible is to be found double X = 30; // Max K-digit divisible is to be found double K = 3; System.out.println((int)answer(X, K)); }} // Code contributed by Mohit Gupta_OMG <(0_o)>
# Python code to find highest# K-digit number divisible by X def answer(X, K): # Computing MAX MAX = pow(10, K) - 1 # returning ans return (MAX - (MAX % X)) X = 30;K = 3; print(answer(X, K)); # Code contributed by Mohit Gupta_OMG <(0_o)>
// C# code to find highest// K-digit number divisible by X using System; class GFG { public static double answer(double X, double K) { double i = 10; // Computing MAX double MAX = Math.Pow(i, K) - 1; // returning ans return (MAX - (MAX % X)); } public static void Main() { // Number whose divisible is to be found double X = 30; // Max K-digit divisible is to be found double K = 3; Console.WriteLine((int)answer(X, K)); }} // This code is contributed by vt_m.
<?php// PHP code to find highest K-digit// number divisible by X // Function to compute the resultfunction answer($X, $K){ // Computing MAX $MAX = pow(10, $K) - 1; // returning ans return ($MAX - ($MAX % $X));} // Driver // Number whose divisible // is to be found $X = 30; // Max K-digit divisible // is to be found $K = 3; echo answer($X, $K); // This code is contributed by ajit?>
<script>// Javascript code to find highest K-digit// number divisible by X // Function to compute the resultfunction answer(X, K){ // Computing MAX let MAX = Math.pow(10, K) - 1; // returning ans return (MAX - (MAX % X));} // Driver // Number whose divisible // is to be found let X = 30; // Max K-digit divisible // is to be found let K = 3; document.write(answer(X, K)); // This code is contributed by gfgking</script>
Output:
990
This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
vt_m
jit_t
Akanksha_Rai
gfgking
divisibility
Mathematical
School Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Sieve of Eratosthenes
Prime Numbers
Find minimum number of coins that make a given value
Python Dictionary
Reverse a string in Java
Arrays in C/C++
Introduction To PYTHON
Interfaces in Java | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n16 Apr, 2021"
},
{
"code": null,
"e": 155,
"s": 53,
"text": "Integers X and K are given. The task is to find the highest K-digit number divisible by X.Examples: "
},
{
"code": null,
"e": 280,
"s": 155,
"text": "Input : X = 30, K = 3\nOutput : 990\n990 is the largest three digit \nnumber divisible by 30.\n\nInput : X = 7, K = 2\nOutput : 98"
},
{
"code": null,
"e": 480,
"s": 282,
"text": "A simple solution is to try all numbers starting from the largest K digit number (which is 999...K-times) and return the first number divisible by X.An efficient solution is to use below formula. "
},
{
"code": null,
"e": 567,
"s": 480,
"text": "ans = MAX - (MAX % X)\nwhere MAX is the largest K digit \nnumber which is 999...K-times"
},
{
"code": null,
"e": 677,
"s": 567,
"text": "The formula works on simple school method division. We remove remainder to get the largest divisible number. "
},
{
"code": null,
"e": 681,
"s": 677,
"text": "C++"
},
{
"code": null,
"e": 686,
"s": 681,
"text": "Java"
},
{
"code": null,
"e": 694,
"s": 686,
"text": "Python3"
},
{
"code": null,
"e": 697,
"s": 694,
"text": "C#"
},
{
"code": null,
"e": 701,
"s": 697,
"text": "PHP"
},
{
"code": null,
"e": 712,
"s": 701,
"text": "Javascript"
},
{
"code": "// CPP code to find highest K-digit number divisible by X#include <bits/stdc++.h>using namespace std; // Function to compute the resultint answer(int X, int K){ // Computing MAX int MAX = pow(10, K) - 1; // returning ans return (MAX - (MAX % X));} // Driverint main(){ // Number whose divisible is to be found int X = 30; // Max K-digit divisible is to be found int K = 3; cout << answer(X, K);}",
"e": 1138,
"s": 712,
"text": null
},
{
"code": "// Java code to find highest// K-digit number divisible by X import java.io.*;import java.lang.*; class GFG { public static double answer(double X, double K) { double i = 10; // Computing MAX double MAX = Math.pow(i, K) - 1; // returning ans return (MAX - (MAX % X)); } public static void main(String[] args) { // Number whose divisible is to be found double X = 30; // Max K-digit divisible is to be found double K = 3; System.out.println((int)answer(X, K)); }} // Code contributed by Mohit Gupta_OMG <(0_o)>",
"e": 1741,
"s": 1138,
"text": null
},
{
"code": "# Python code to find highest# K-digit number divisible by X def answer(X, K): # Computing MAX MAX = pow(10, K) - 1 # returning ans return (MAX - (MAX % X)) X = 30;K = 3; print(answer(X, K)); # Code contributed by Mohit Gupta_OMG <(0_o)>",
"e": 2001,
"s": 1741,
"text": null
},
{
"code": "// C# code to find highest// K-digit number divisible by X using System; class GFG { public static double answer(double X, double K) { double i = 10; // Computing MAX double MAX = Math.Pow(i, K) - 1; // returning ans return (MAX - (MAX % X)); } public static void Main() { // Number whose divisible is to be found double X = 30; // Max K-digit divisible is to be found double K = 3; Console.WriteLine((int)answer(X, K)); }} // This code is contributed by vt_m.",
"e": 2578,
"s": 2001,
"text": null
},
{
"code": "<?php// PHP code to find highest K-digit// number divisible by X // Function to compute the resultfunction answer($X, $K){ // Computing MAX $MAX = pow(10, $K) - 1; // returning ans return ($MAX - ($MAX % $X));} // Driver // Number whose divisible // is to be found $X = 30; // Max K-digit divisible // is to be found $K = 3; echo answer($X, $K); // This code is contributed by ajit?>",
"e": 3003,
"s": 2578,
"text": null
},
{
"code": "<script>// Javascript code to find highest K-digit// number divisible by X // Function to compute the resultfunction answer(X, K){ // Computing MAX let MAX = Math.pow(10, K) - 1; // returning ans return (MAX - (MAX % X));} // Driver // Number whose divisible // is to be found let X = 30; // Max K-digit divisible // is to be found let K = 3; document.write(answer(X, K)); // This code is contributed by gfgking</script>",
"e": 3465,
"s": 3003,
"text": null
},
{
"code": null,
"e": 3475,
"s": 3465,
"text": "Output: "
},
{
"code": null,
"e": 3479,
"s": 3475,
"text": "990"
},
{
"code": null,
"e": 3907,
"s": 3479,
"text": "This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 3912,
"s": 3907,
"text": "vt_m"
},
{
"code": null,
"e": 3918,
"s": 3912,
"text": "jit_t"
},
{
"code": null,
"e": 3931,
"s": 3918,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 3939,
"s": 3931,
"text": "gfgking"
},
{
"code": null,
"e": 3952,
"s": 3939,
"text": "divisibility"
},
{
"code": null,
"e": 3965,
"s": 3952,
"text": "Mathematical"
},
{
"code": null,
"e": 3984,
"s": 3965,
"text": "School Programming"
},
{
"code": null,
"e": 3997,
"s": 3984,
"text": "Mathematical"
},
{
"code": null,
"e": 4095,
"s": 3997,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4119,
"s": 4095,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 4140,
"s": 4119,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 4162,
"s": 4140,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 4176,
"s": 4162,
"text": "Prime Numbers"
},
{
"code": null,
"e": 4229,
"s": 4176,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 4247,
"s": 4229,
"text": "Python Dictionary"
},
{
"code": null,
"e": 4272,
"s": 4247,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 4288,
"s": 4272,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 4311,
"s": 4288,
"text": "Introduction To PYTHON"
}
]
|
Objdump Command in Linux with Examples | 25 Aug, 2020
When we have an object file and we don’t have the source code with us and we have to find out the maximum information from the file. To do so objdump plays a very vital role. The main purpose of the objdump command is to help in debugging the object file. It is used for the following listed purposes:
To retrieve archive header
To get the offset of the file
To get the bfdname
To get the demangle
To debug the file
To disassemble the file
To retrieve the file headers
Syntax :
objdump <option(s)> <file(s)>
1. To get the File headers of an Object File. This command will print all the File headers related information of the file.
objdump -f khushi
Here, Khushi is the name of the object file which you want to get the file headers of.
2. To print the object-specific file header content. This command will print the object-specific file header content of the file.
objdump -p khushi
Here, Khushi is the name of the object file which you want to get the file headers of.
3. To print the section header content of the file. This command will print all the section header related information of the file.
objdump -h khushiKhushi
Here, Khushi is the name of the object file which you want to get the file headers of.
4. To print the all header content of the file. This command will print all the content header related information of the file.
objdump -x khushi
Here, Khushi is the name of the object file which you want to get the file headers of.
5. To print the assembler content of the sections capable of execution. This command will print the content of the assembler of sections that are executable.
objdump -d khushi
Here, Khushi is the name of the object file which you want to get the file headers of.
6. To print the assembler content of all the sections of the file. This command will print all the assembler content of all the sections of the file.
objdump -D khushi
Here, Khushi is the name of the object file which you want to get the file headers of.
7. To print the complete content of all the sections of the file. This command will print all the content of all the sections of the file.
objdump -s khushi
Here, Khushi is the name of the object file which you want to get the file headers of.
8. To display the help section of the command. This command will display all the parameters and the values it could receive in order to process the file.
objdump --help
linux-command
Linux-file-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
mv command in Linux with examples
chmod command in Linux with examples
nohup Command in Linux with Examples
Introduction to Linux Operating System
Basic Operators in Shell Scripting
Array Basics in Shell Scripting | Set 1 | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Aug, 2020"
},
{
"code": null,
"e": 330,
"s": 28,
"text": "When we have an object file and we don’t have the source code with us and we have to find out the maximum information from the file. To do so objdump plays a very vital role. The main purpose of the objdump command is to help in debugging the object file. It is used for the following listed purposes:"
},
{
"code": null,
"e": 357,
"s": 330,
"text": "To retrieve archive header"
},
{
"code": null,
"e": 387,
"s": 357,
"text": "To get the offset of the file"
},
{
"code": null,
"e": 406,
"s": 387,
"text": "To get the bfdname"
},
{
"code": null,
"e": 426,
"s": 406,
"text": "To get the demangle"
},
{
"code": null,
"e": 444,
"s": 426,
"text": "To debug the file"
},
{
"code": null,
"e": 468,
"s": 444,
"text": "To disassemble the file"
},
{
"code": null,
"e": 497,
"s": 468,
"text": "To retrieve the file headers"
},
{
"code": null,
"e": 506,
"s": 497,
"text": "Syntax :"
},
{
"code": null,
"e": 537,
"s": 506,
"text": "objdump <option(s)> <file(s)>\n"
},
{
"code": null,
"e": 661,
"s": 537,
"text": "1. To get the File headers of an Object File. This command will print all the File headers related information of the file."
},
{
"code": null,
"e": 680,
"s": 661,
"text": "objdump -f khushi\n"
},
{
"code": null,
"e": 767,
"s": 680,
"text": "Here, Khushi is the name of the object file which you want to get the file headers of."
},
{
"code": null,
"e": 897,
"s": 767,
"text": "2. To print the object-specific file header content. This command will print the object-specific file header content of the file."
},
{
"code": null,
"e": 916,
"s": 897,
"text": "objdump -p khushi\n"
},
{
"code": null,
"e": 1003,
"s": 916,
"text": "Here, Khushi is the name of the object file which you want to get the file headers of."
},
{
"code": null,
"e": 1135,
"s": 1003,
"text": "3. To print the section header content of the file. This command will print all the section header related information of the file."
},
{
"code": null,
"e": 1160,
"s": 1135,
"text": "objdump -h khushiKhushi\n"
},
{
"code": null,
"e": 1247,
"s": 1160,
"text": "Here, Khushi is the name of the object file which you want to get the file headers of."
},
{
"code": null,
"e": 1375,
"s": 1247,
"text": "4. To print the all header content of the file. This command will print all the content header related information of the file."
},
{
"code": null,
"e": 1394,
"s": 1375,
"text": "objdump -x khushi\n"
},
{
"code": null,
"e": 1481,
"s": 1394,
"text": "Here, Khushi is the name of the object file which you want to get the file headers of."
},
{
"code": null,
"e": 1639,
"s": 1481,
"text": "5. To print the assembler content of the sections capable of execution. This command will print the content of the assembler of sections that are executable."
},
{
"code": null,
"e": 1658,
"s": 1639,
"text": "objdump -d khushi\n"
},
{
"code": null,
"e": 1745,
"s": 1658,
"text": "Here, Khushi is the name of the object file which you want to get the file headers of."
},
{
"code": null,
"e": 1895,
"s": 1745,
"text": "6. To print the assembler content of all the sections of the file. This command will print all the assembler content of all the sections of the file."
},
{
"code": null,
"e": 1914,
"s": 1895,
"text": "objdump -D khushi\n"
},
{
"code": null,
"e": 2001,
"s": 1914,
"text": "Here, Khushi is the name of the object file which you want to get the file headers of."
},
{
"code": null,
"e": 2140,
"s": 2001,
"text": "7. To print the complete content of all the sections of the file. This command will print all the content of all the sections of the file."
},
{
"code": null,
"e": 2159,
"s": 2140,
"text": "objdump -s khushi\n"
},
{
"code": null,
"e": 2246,
"s": 2159,
"text": "Here, Khushi is the name of the object file which you want to get the file headers of."
},
{
"code": null,
"e": 2400,
"s": 2246,
"text": "8. To display the help section of the command. This command will display all the parameters and the values it could receive in order to process the file."
},
{
"code": null,
"e": 2416,
"s": 2400,
"text": "objdump --help\n"
},
{
"code": null,
"e": 2430,
"s": 2416,
"text": "linux-command"
},
{
"code": null,
"e": 2450,
"s": 2430,
"text": "Linux-file-commands"
},
{
"code": null,
"e": 2461,
"s": 2450,
"text": "Linux-Unix"
},
{
"code": null,
"e": 2559,
"s": 2461,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2585,
"s": 2559,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 2620,
"s": 2585,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 2657,
"s": 2620,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 2686,
"s": 2657,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 2720,
"s": 2686,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 2757,
"s": 2720,
"text": "chmod command in Linux with examples"
},
{
"code": null,
"e": 2794,
"s": 2757,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 2833,
"s": 2794,
"text": "Introduction to Linux Operating System"
},
{
"code": null,
"e": 2868,
"s": 2833,
"text": "Basic Operators in Shell Scripting"
}
]
|
How to Use Weka Java API? | 21 Sep, 2021
To use the weka API you need to install weka according to your operating system. After downloading the archive and extracting it you’ll find the weka.jar file. The JAR file contains all the class files required i.e. weka API. Now we can find all the information about the classes and methods in the Weka Java API documentation. We need to add this jar as a classpath to our program.
Also, let us discuss the classpath before landing upon the implementation part. So classpath is something that tells the JDK about the external libraries (user class file). In order to add a classpath the recommended way is to use -cp option of JDK commands. If you are using any framework then the classpath can be added to the respective manifest file.
Example:
Java
// Java Program to Illustrate Usage of Weka API // Importing required classesimport java.io.BufferedReader;import java.io.FileReader;import java.util.Random;import weka.classifiers.Evaluation;import weka.classifiers.trees.J48;import weka.core.Instances; // Main class// BreastCancerpublic class GFG { // Main driver method public static void main(String args[]) { // Try block to check for exceptions try { // Create J48 classifier by // creating object of J48 class J48 j48Classifier = new J48(); // Dataset path String breastCancerDataset = "/home/droid/Tools/weka-3-8-5/data/breast-cancer.arff"; // Creating bufferedreader to read the dataset BufferedReader bufferedReader = new BufferedReader( new FileReader(breastCancerDataset)); // Create dataset instances Instances datasetInstances = new Instances(bufferedReader); // Set Target Class datasetInstances.setClassIndex( datasetInstances.numAttributes() - 1); // Evaluating by creating object of Evaluation // class Evaluation evaluation = new Evaluation(datasetInstances); // Cross Validate Model with 10 folds evaluation.crossValidateModel( j48Classifier, datasetInstances, 10, new Random(1)); System.out.println(evaluation.toSummaryString( "\nResults", false)); } // Catch block to handle the exceptions catch (Exception e) { // Print message on the console System.out.println("Error Occurred!!!! \n" + e.getMessage()); } }}
Output:
After coding your model using the weka API you can run the program using the following commands
$ javac -cp weka-3-8-5/weka.jar program.java
$ java -cp .:weka-3-8-5/weka.jar program
The weka-3-8-5/weka.jar is the path to the jar file available in the installation.
This will be the desired output generated as shown below:
anikakapoor
surindertarika1234
simranarora5sos
Java
Machine Learning
Java
Machine Learning
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
Naive Bayes Classifiers
ML | Linear Regression
Linear Regression (Python Implementation) | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Sep, 2021"
},
{
"code": null,
"e": 411,
"s": 28,
"text": "To use the weka API you need to install weka according to your operating system. After downloading the archive and extracting it you’ll find the weka.jar file. The JAR file contains all the class files required i.e. weka API. Now we can find all the information about the classes and methods in the Weka Java API documentation. We need to add this jar as a classpath to our program."
},
{
"code": null,
"e": 766,
"s": 411,
"text": "Also, let us discuss the classpath before landing upon the implementation part. So classpath is something that tells the JDK about the external libraries (user class file). In order to add a classpath the recommended way is to use -cp option of JDK commands. If you are using any framework then the classpath can be added to the respective manifest file."
},
{
"code": null,
"e": 775,
"s": 766,
"text": "Example:"
},
{
"code": null,
"e": 780,
"s": 775,
"text": "Java"
},
{
"code": "// Java Program to Illustrate Usage of Weka API // Importing required classesimport java.io.BufferedReader;import java.io.FileReader;import java.util.Random;import weka.classifiers.Evaluation;import weka.classifiers.trees.J48;import weka.core.Instances; // Main class// BreastCancerpublic class GFG { // Main driver method public static void main(String args[]) { // Try block to check for exceptions try { // Create J48 classifier by // creating object of J48 class J48 j48Classifier = new J48(); // Dataset path String breastCancerDataset = \"/home/droid/Tools/weka-3-8-5/data/breast-cancer.arff\"; // Creating bufferedreader to read the dataset BufferedReader bufferedReader = new BufferedReader( new FileReader(breastCancerDataset)); // Create dataset instances Instances datasetInstances = new Instances(bufferedReader); // Set Target Class datasetInstances.setClassIndex( datasetInstances.numAttributes() - 1); // Evaluating by creating object of Evaluation // class Evaluation evaluation = new Evaluation(datasetInstances); // Cross Validate Model with 10 folds evaluation.crossValidateModel( j48Classifier, datasetInstances, 10, new Random(1)); System.out.println(evaluation.toSummaryString( \"\\nResults\", false)); } // Catch block to handle the exceptions catch (Exception e) { // Print message on the console System.out.println(\"Error Occurred!!!! \\n\" + e.getMessage()); } }}",
"e": 2607,
"s": 780,
"text": null
},
{
"code": null,
"e": 2616,
"s": 2607,
"text": "Output: "
},
{
"code": null,
"e": 2712,
"s": 2616,
"text": "After coding your model using the weka API you can run the program using the following commands"
},
{
"code": null,
"e": 2757,
"s": 2712,
"text": "$ javac -cp weka-3-8-5/weka.jar program.java"
},
{
"code": null,
"e": 2798,
"s": 2757,
"text": "$ java -cp .:weka-3-8-5/weka.jar program"
},
{
"code": null,
"e": 2881,
"s": 2798,
"text": "The weka-3-8-5/weka.jar is the path to the jar file available in the installation."
},
{
"code": null,
"e": 2940,
"s": 2881,
"text": "This will be the desired output generated as shown below: "
},
{
"code": null,
"e": 2954,
"s": 2942,
"text": "anikakapoor"
},
{
"code": null,
"e": 2973,
"s": 2954,
"text": "surindertarika1234"
},
{
"code": null,
"e": 2989,
"s": 2973,
"text": "simranarora5sos"
},
{
"code": null,
"e": 2994,
"s": 2989,
"text": "Java"
},
{
"code": null,
"e": 3011,
"s": 2994,
"text": "Machine Learning"
},
{
"code": null,
"e": 3016,
"s": 3011,
"text": "Java"
},
{
"code": null,
"e": 3033,
"s": 3016,
"text": "Machine Learning"
},
{
"code": null,
"e": 3131,
"s": 3033,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3146,
"s": 3131,
"text": "Stream In Java"
},
{
"code": null,
"e": 3167,
"s": 3146,
"text": "Introduction to Java"
},
{
"code": null,
"e": 3188,
"s": 3167,
"text": "Constructors in Java"
},
{
"code": null,
"e": 3207,
"s": 3188,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 3224,
"s": 3207,
"text": "Generics in Java"
},
{
"code": null,
"e": 3248,
"s": 3224,
"text": "Naive Bayes Classifiers"
},
{
"code": null,
"e": 3271,
"s": 3248,
"text": "ML | Linear Regression"
}
]
|
Extract unique objects by attribute from array of objects. | 14 Feb, 2019
Given an array of objects and the task is to return the unique object by the attribute.
Examples:
Input:
[ { name: 'Geeks', id: 10 },
{ name: 'GeeksForGeeks', id: 10 },
{ name: 'Geeks', id: 20 },
{ name: 'Geeks', id: 10 } ]
Output:
[ { name: 'Geeks', id: 10 },
{ name: 'GeeksForGeeks', id: 10 } ]
Approach: Let’s assume that name as attribute that differentiate the objects and need the object with minimum id number if multiple objects exists for same name. Use the map to store objects and check whether similar object seen or not.
Initialize an empty map.
Iterate through array using filter method.
Check if there is any entry in map with same name as of current object.
—-If true: i.e. there exists an entry with same name then, check if its id is less than current object’s id.
——–If true: i.e current object’s id is less than the id of the object returned by map then delete the map entry and enter the current object and return true.
——–if false: i.e. id of current object is greater than the id of object returned by map then return false.
—-If false: i.e. there is no entry in map with same name then enter the current object into map.
Print unique objects.
Example:
<script>objects = [{ name: 'Geeks', id: 10}, { name: 'GeeksForGeeks', id: 10}, { name: 'Geeks', id: 20}, { name: 'Geeks', id: 10}]; let mymap = new Map(); unique = objects.filter(el => { const val = mymap.get(el.name); if(val) { if(el.id < val) { mymap.delete(el.name); mymap.set(el.name, el.id); return true; } else { return false; } } mymap.set(el.name, el.id); return true;}); console.log(unique);</script>
Output:
[ { name: 'Geeks', id: 10 },
{ name: 'GeeksForGeeks', id: 10 } ]
Time Complexity: O(n)Space Complexity: O(n)
Arrays
javascript-array
Arrays
JavaScript
Web Technologies
Web technologies Questions
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
How to append HTML code to a div using JavaScript ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Feb, 2019"
},
{
"code": null,
"e": 116,
"s": 28,
"text": "Given an array of objects and the task is to return the unique object by the attribute."
},
{
"code": null,
"e": 126,
"s": 116,
"text": "Examples:"
},
{
"code": null,
"e": 336,
"s": 126,
"text": "Input: \n[ { name: 'Geeks', id: 10 },\n { name: 'GeeksForGeeks', id: 10 },\n { name: 'Geeks', id: 20 },\n { name: 'Geeks', id: 10 } ]\nOutput:\n[ { name: 'Geeks', id: 10 }, \n { name: 'GeeksForGeeks', id: 10 } ]\n"
},
{
"code": null,
"e": 573,
"s": 336,
"text": "Approach: Let’s assume that name as attribute that differentiate the objects and need the object with minimum id number if multiple objects exists for same name. Use the map to store objects and check whether similar object seen or not."
},
{
"code": null,
"e": 598,
"s": 573,
"text": "Initialize an empty map."
},
{
"code": null,
"e": 641,
"s": 598,
"text": "Iterate through array using filter method."
},
{
"code": null,
"e": 713,
"s": 641,
"text": "Check if there is any entry in map with same name as of current object."
},
{
"code": null,
"e": 822,
"s": 713,
"text": "—-If true: i.e. there exists an entry with same name then, check if its id is less than current object’s id."
},
{
"code": null,
"e": 980,
"s": 822,
"text": "——–If true: i.e current object’s id is less than the id of the object returned by map then delete the map entry and enter the current object and return true."
},
{
"code": null,
"e": 1087,
"s": 980,
"text": "——–if false: i.e. id of current object is greater than the id of object returned by map then return false."
},
{
"code": null,
"e": 1184,
"s": 1087,
"text": "—-If false: i.e. there is no entry in map with same name then enter the current object into map."
},
{
"code": null,
"e": 1206,
"s": 1184,
"text": "Print unique objects."
},
{
"code": null,
"e": 1215,
"s": 1206,
"text": "Example:"
},
{
"code": "<script>objects = [{ name: 'Geeks', id: 10}, { name: 'GeeksForGeeks', id: 10}, { name: 'Geeks', id: 20}, { name: 'Geeks', id: 10}]; let mymap = new Map(); unique = objects.filter(el => { const val = mymap.get(el.name); if(val) { if(el.id < val) { mymap.delete(el.name); mymap.set(el.name, el.id); return true; } else { return false; } } mymap.set(el.name, el.id); return true;}); console.log(unique);</script>",
"e": 1732,
"s": 1215,
"text": null
},
{
"code": null,
"e": 1740,
"s": 1732,
"text": "Output:"
},
{
"code": null,
"e": 1809,
"s": 1740,
"text": "[ { name: 'Geeks', id: 10 }, \n { name: 'GeeksForGeeks', id: 10 } ]\n"
},
{
"code": null,
"e": 1853,
"s": 1809,
"text": "Time Complexity: O(n)Space Complexity: O(n)"
},
{
"code": null,
"e": 1860,
"s": 1853,
"text": "Arrays"
},
{
"code": null,
"e": 1877,
"s": 1860,
"text": "javascript-array"
},
{
"code": null,
"e": 1884,
"s": 1877,
"text": "Arrays"
},
{
"code": null,
"e": 1895,
"s": 1884,
"text": "JavaScript"
},
{
"code": null,
"e": 1912,
"s": 1895,
"text": "Web Technologies"
},
{
"code": null,
"e": 1939,
"s": 1912,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 1946,
"s": 1939,
"text": "Arrays"
},
{
"code": null,
"e": 2044,
"s": 1946,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2112,
"s": 2044,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 2156,
"s": 2112,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 2188,
"s": 2156,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 2236,
"s": 2188,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 2250,
"s": 2236,
"text": "Linear Search"
},
{
"code": null,
"e": 2311,
"s": 2250,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2383,
"s": 2311,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 2423,
"s": 2383,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2476,
"s": 2423,
"text": "Hide or show elements in HTML using display property"
}
]
|
What is the difference between properties and attributes in HTML? | 01 Feb, 2022
HTML is the standard language for creating documents that are intended to be displayed on web browsers. It is very usual to get confused with attributes and properties while performing DOM object manipulation in JavaScript. Before learning about the differences, let us first define the Document Object Model.
DOM: It is the acronym for the Document Object Model. When the browser parses your HTML code, it creates a corresponding DOM node. The HTML properties are accessed from this node object.
In simpler terms, DOM is an API for the HTML, and we use languages like JavaScript or frameworks like React, Vue.js to access and manipulate the HTML using the corresponding DOM objects.
Notes:
Some DOM properties don’t possess corresponding attributes.Some HTML attributes don’t possess corresponding properties.Some HTML attributes, like ‘class’, possess 1:1 mapping to properties.
Some DOM properties don’t possess corresponding attributes.
Some HTML attributes don’t possess corresponding properties.
Some HTML attributes, like ‘class’, possess 1:1 mapping to properties.
Let us take a look at some quick examples to demonstrate the differences between attributes and properties.
Example: Consider the following HTML code snippet.
html
<!DOCTYPE html><html> <body> <input id="input" type="number" value="Phone Number:"> <p id="display"></p> <script> var element = document.getElementById("input"); // Getting the property, returns "Phone Number:" window.alert(element.getAttribute("value")); element.value = 1234; var x = element.value; // Getting the attribute, returns "1234" document.getElementById("display").innerHTML = "Value Attribute: " + x; </script></body> </html>
Output:
Now, let us consider that the user inputs “1234”, then the element.getAttribute(“value”) will return “Phone Number:” because we have provided this as the initial value of this attribute. But element.value will return “1234”.
Thus, the value attribute has the initial text-content that was provided by the developer in the HTML source code because the value property reflects the current text-content inside the input box (provided by the user in this case).
Now we have a basic idea about the difference, let us dive deep and learn about more differences.
Attribute: Attributes are defined by HTML and are used to customize a tag.
html
<!DOCTYPE html><html> <body> <p> Click the button the display the number of attributes associated with it. </p> <button id="AttributeDemo" onclick="myFunction()"> Try it </button> <p id="display"></p> <script> function myFunction() { var Attrdemo = document.getElementById( "AttributeDemo").attributes.length; document.getElementById( "display").innerHTML = Attrdemo; } </script></body> </html>
The output is 2 because the two attributes are: id=”AttributeDemo” and onclick=”myFunction()”.
Note: The document.getElementsById(‘AttributeDemo’).attributes code snippet returns a collection of the specified node’s attributes, as a NamedNodeMap object. To access the nodes, we can use the generic indexing method. Replace the following line in the above code snippet.
javascript
var Attrdemo = document.getElementById( 'AtrributeDemo').attributes[1].name;
Output:
onclick
The attributes have a data type of string. So no matter the value of the attribute, it will always return a string. Example:
document.getElementById('AtrributeDemo').getAttribute('id')
Output:
AttributeDemo
Property: In contrast to the attributes, which are defined in HTML, properties belong to the DOM. Since DOM is an object in JavaScript, we can get and set properties.
javascript
<!DOCTYPE html><html> <body> <p> Click the "display" button for the number of attributes associated with it. </p> <button id="AttributeDemo" onclick="myFunction()"> Try it </button> <p id="display"></p> <script> function myFunction() { // Setting the property // 'geeksforgeeks' to a number document.getElementById('AttributeDemo') .geeksforgeeks = 777; // Getting the property, returns 1 var x = document.getElementById( 'AttributeDemo').geeksforgeeks; document.getElementById( "display").innerHTML = x; } </script></body> </html>
Output:
Default attributes (non-user-defined) change when corresponding property changes and vice-versa.
html
<!DOCTYPE html><html> <body> <p> Click the button the display the current className & the edited className </p> <button id="demo1" class="button" onclick="Function1()"> Click Me </button> <p id="displayCurrent"></p> <p id="diplayEdited"></p> <script> function Function1() { var div = document.getElementById("demo1"); // Returns "button" window.alert("Current Class : " + div.getAttribute("class")); div.setAttribute("class", "GeeksForGeeks"); // Returns : "GeeksForGeeks" window.alert("Edited Class : " + div.getAttribute("class")); } </script></body> </html>
Output:
Note:
Non-custom attributes (like id, class, etc.) have 1:1 mapping to the properties.We use ‘className’ to access (get or set) the ‘class’ property because ‘class’ is a reserved keyword in JavaScript.Attributes that have a defined default value remain constant when the corresponding property changes.
Non-custom attributes (like id, class, etc.) have 1:1 mapping to the properties.
We use ‘className’ to access (get or set) the ‘class’ property because ‘class’ is a reserved keyword in JavaScript.
Attributes that have a defined default value remain constant when the corresponding property changes.
Difference between HTML attributes and DOM properties:
shubhamyadav4
kishornathgupta1999
HTML-DOM
HTML-Misc
HTML-Property
Difference Between
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Feb, 2022"
},
{
"code": null,
"e": 338,
"s": 28,
"text": "HTML is the standard language for creating documents that are intended to be displayed on web browsers. It is very usual to get confused with attributes and properties while performing DOM object manipulation in JavaScript. Before learning about the differences, let us first define the Document Object Model."
},
{
"code": null,
"e": 525,
"s": 338,
"text": "DOM: It is the acronym for the Document Object Model. When the browser parses your HTML code, it creates a corresponding DOM node. The HTML properties are accessed from this node object."
},
{
"code": null,
"e": 712,
"s": 525,
"text": "In simpler terms, DOM is an API for the HTML, and we use languages like JavaScript or frameworks like React, Vue.js to access and manipulate the HTML using the corresponding DOM objects."
},
{
"code": null,
"e": 720,
"s": 712,
"text": "Notes: "
},
{
"code": null,
"e": 910,
"s": 720,
"text": "Some DOM properties don’t possess corresponding attributes.Some HTML attributes don’t possess corresponding properties.Some HTML attributes, like ‘class’, possess 1:1 mapping to properties."
},
{
"code": null,
"e": 970,
"s": 910,
"text": "Some DOM properties don’t possess corresponding attributes."
},
{
"code": null,
"e": 1031,
"s": 970,
"text": "Some HTML attributes don’t possess corresponding properties."
},
{
"code": null,
"e": 1102,
"s": 1031,
"text": "Some HTML attributes, like ‘class’, possess 1:1 mapping to properties."
},
{
"code": null,
"e": 1210,
"s": 1102,
"text": "Let us take a look at some quick examples to demonstrate the differences between attributes and properties."
},
{
"code": null,
"e": 1261,
"s": 1210,
"text": "Example: Consider the following HTML code snippet."
},
{
"code": null,
"e": 1266,
"s": 1261,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <body> <input id=\"input\" type=\"number\" value=\"Phone Number:\"> <p id=\"display\"></p> <script> var element = document.getElementById(\"input\"); // Getting the property, returns \"Phone Number:\" window.alert(element.getAttribute(\"value\")); element.value = 1234; var x = element.value; // Getting the attribute, returns \"1234\" document.getElementById(\"display\").innerHTML = \"Value Attribute: \" + x; </script></body> </html> ",
"e": 1804,
"s": 1266,
"text": null
},
{
"code": null,
"e": 1814,
"s": 1804,
"text": "Output: "
},
{
"code": null,
"e": 2042,
"s": 1816,
"text": "Now, let us consider that the user inputs “1234”, then the element.getAttribute(“value”) will return “Phone Number:” because we have provided this as the initial value of this attribute. But element.value will return “1234”. "
},
{
"code": null,
"e": 2275,
"s": 2042,
"text": "Thus, the value attribute has the initial text-content that was provided by the developer in the HTML source code because the value property reflects the current text-content inside the input box (provided by the user in this case)."
},
{
"code": null,
"e": 2373,
"s": 2275,
"text": "Now we have a basic idea about the difference, let us dive deep and learn about more differences."
},
{
"code": null,
"e": 2449,
"s": 2373,
"text": "Attribute: Attributes are defined by HTML and are used to customize a tag. "
},
{
"code": null,
"e": 2454,
"s": 2449,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <body> <p> Click the button the display the number of attributes associated with it. </p> <button id=\"AttributeDemo\" onclick=\"myFunction()\"> Try it </button> <p id=\"display\"></p> <script> function myFunction() { var Attrdemo = document.getElementById( \"AttributeDemo\").attributes.length; document.getElementById( \"display\").innerHTML = Attrdemo; } </script></body> </html>",
"e": 2990,
"s": 2454,
"text": null
},
{
"code": null,
"e": 3085,
"s": 2990,
"text": "The output is 2 because the two attributes are: id=”AttributeDemo” and onclick=”myFunction()”."
},
{
"code": null,
"e": 3359,
"s": 3085,
"text": "Note: The document.getElementsById(‘AttributeDemo’).attributes code snippet returns a collection of the specified node’s attributes, as a NamedNodeMap object. To access the nodes, we can use the generic indexing method. Replace the following line in the above code snippet."
},
{
"code": null,
"e": 3370,
"s": 3359,
"text": "javascript"
},
{
"code": "var Attrdemo = document.getElementById( 'AtrributeDemo').attributes[1].name;",
"e": 3450,
"s": 3370,
"text": null
},
{
"code": null,
"e": 3459,
"s": 3450,
"text": "Output: "
},
{
"code": null,
"e": 3467,
"s": 3459,
"text": "onclick"
},
{
"code": null,
"e": 3593,
"s": 3467,
"text": "The attributes have a data type of string. So no matter the value of the attribute, it will always return a string. Example: "
},
{
"code": null,
"e": 3653,
"s": 3593,
"text": "document.getElementById('AtrributeDemo').getAttribute('id')"
},
{
"code": null,
"e": 3662,
"s": 3653,
"text": "Output: "
},
{
"code": null,
"e": 3676,
"s": 3662,
"text": "AttributeDemo"
},
{
"code": null,
"e": 3843,
"s": 3676,
"text": "Property: In contrast to the attributes, which are defined in HTML, properties belong to the DOM. Since DOM is an object in JavaScript, we can get and set properties."
},
{
"code": null,
"e": 3854,
"s": 3843,
"text": "javascript"
},
{
"code": "<!DOCTYPE html><html> <body> <p> Click the \"display\" button for the number of attributes associated with it. </p> <button id=\"AttributeDemo\" onclick=\"myFunction()\"> Try it </button> <p id=\"display\"></p> <script> function myFunction() { // Setting the property // 'geeksforgeeks' to a number document.getElementById('AttributeDemo') .geeksforgeeks = 777; // Getting the property, returns 1 var x = document.getElementById( 'AttributeDemo').geeksforgeeks; document.getElementById( \"display\").innerHTML = x; } </script></body> </html>",
"e": 4588,
"s": 3854,
"text": null
},
{
"code": null,
"e": 4597,
"s": 4588,
"text": "Output: "
},
{
"code": null,
"e": 4695,
"s": 4597,
"text": "Default attributes (non-user-defined) change when corresponding property changes and vice-versa. "
},
{
"code": null,
"e": 4700,
"s": 4695,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <body> <p> Click the button the display the current className & the edited className </p> <button id=\"demo1\" class=\"button\" onclick=\"Function1()\"> Click Me </button> <p id=\"displayCurrent\"></p> <p id=\"diplayEdited\"></p> <script> function Function1() { var div = document.getElementById(\"demo1\"); // Returns \"button\" window.alert(\"Current Class : \" + div.getAttribute(\"class\")); div.setAttribute(\"class\", \"GeeksForGeeks\"); // Returns : \"GeeksForGeeks\" window.alert(\"Edited Class : \" + div.getAttribute(\"class\")); } </script></body> </html>",
"e": 5469,
"s": 4700,
"text": null
},
{
"code": null,
"e": 5479,
"s": 5469,
"text": "Output: "
},
{
"code": null,
"e": 5486,
"s": 5479,
"text": "Note: "
},
{
"code": null,
"e": 5783,
"s": 5486,
"text": "Non-custom attributes (like id, class, etc.) have 1:1 mapping to the properties.We use ‘className’ to access (get or set) the ‘class’ property because ‘class’ is a reserved keyword in JavaScript.Attributes that have a defined default value remain constant when the corresponding property changes."
},
{
"code": null,
"e": 5864,
"s": 5783,
"text": "Non-custom attributes (like id, class, etc.) have 1:1 mapping to the properties."
},
{
"code": null,
"e": 5980,
"s": 5864,
"text": "We use ‘className’ to access (get or set) the ‘class’ property because ‘class’ is a reserved keyword in JavaScript."
},
{
"code": null,
"e": 6082,
"s": 5980,
"text": "Attributes that have a defined default value remain constant when the corresponding property changes."
},
{
"code": null,
"e": 6137,
"s": 6082,
"text": "Difference between HTML attributes and DOM properties:"
},
{
"code": null,
"e": 6151,
"s": 6137,
"text": "shubhamyadav4"
},
{
"code": null,
"e": 6171,
"s": 6151,
"text": "kishornathgupta1999"
},
{
"code": null,
"e": 6180,
"s": 6171,
"text": "HTML-DOM"
},
{
"code": null,
"e": 6190,
"s": 6180,
"text": "HTML-Misc"
},
{
"code": null,
"e": 6204,
"s": 6190,
"text": "HTML-Property"
},
{
"code": null,
"e": 6223,
"s": 6204,
"text": "Difference Between"
},
{
"code": null,
"e": 6228,
"s": 6223,
"text": "HTML"
},
{
"code": null,
"e": 6245,
"s": 6228,
"text": "Web Technologies"
},
{
"code": null,
"e": 6250,
"s": 6245,
"text": "HTML"
}
]
|
How to write a running C code without main()? | 21 Jun, 2022
Write a C language code that prints GeeksforGeeks without any main function. Logically it’s seems impossible to write a C program without using a main() function. Since every program must have a main() function because:-
It’s an entry point of every C/C++ program.
All Predefined and User-defined Functions are called directly or indirectly through the main.
Therefore we will use preprocessor(a program which processes the source code before compilation) directive #define with arguments to give an impression that the program runs without main. But in reality it runs with a hidden main function. Let’s see how the preprocessor doing their job:-
Hence it can be solved in following ways:-
Using a macro that defines main
Using a macro that defines main
C
#include<stdio.h>#define fun mainint fun(void){ printf("Geeksforgeeks"); return 0;}
Output: Geeksforgeeks
2. Using Token-Pasting Operator The above solution has word ‘main’ in it. If we are not allowed to even write main, we can use token-pasting operator (see this for details)
C
#include<stdio.h>#define fun m##a##i##nint fun(){ printf("Geeksforgeeks"); return 0;}
Output: Geeksforgeeks
3. Using Argumented Macro
C
#include<stdio.h>#define begin(m,a,i,n) m##a##i##n#define start begin(m,a,i,n) void start() {printf("Geeksforgeeks");}
Output: Geeksforgeeks
4. Modify the entry point during compilation
C
#include<stdio.h>#include<stdlib.h> // entry point functionint nomain(); void _start(){ // calling entry point nomain(); exit(0);} int nomain(){ puts("Geeksforgeeks"); return 0;}
Output:
Geeksforgeeks
Compilation using command : gcc filename.c -nostartfiles (nostartfiles option tells the compiler to avoid standard linking) Explanation: Under normal compilation the body of _start() will contain a function call to main() [ this _start() will be appended to every code during normal compilation], so if that main() definition is not present it will result in error like “In function `_start’: (.text+0x20): undefined reference to `main’. In the above code what we have done is that we have defined our own _start() and defined our own entry point i.e nomain()
Refer Executing main() in C – behind the scene for another solution. References: Macros and Preprocessors in C
Time Complexity: O(1)
Auxiliary Space: O(1)
This article is contributed by Abhay Rathi and improved by Shubham Bansal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
ManasChhabra2
tarakki100
c-puzzle
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unordered Sets in C++ Standard Template Library
What is the purpose of a function prototype?
Operators in C / C++
Exception Handling in C++
TCP Server-Client implementation in C
Smart Pointers in C++ and How to Use Them
'this' pointer in C++
Ways to copy a vector in C++
Storage Classes in C
Understanding "extern" keyword in C | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 Jun, 2022"
},
{
"code": null,
"e": 273,
"s": 52,
"text": "Write a C language code that prints GeeksforGeeks without any main function. Logically it’s seems impossible to write a C program without using a main() function. Since every program must have a main() function because:-"
},
{
"code": null,
"e": 317,
"s": 273,
"text": "It’s an entry point of every C/C++ program."
},
{
"code": null,
"e": 411,
"s": 317,
"text": "All Predefined and User-defined Functions are called directly or indirectly through the main."
},
{
"code": null,
"e": 702,
"s": 411,
"text": "Therefore we will use preprocessor(a program which processes the source code before compilation) directive #define with arguments to give an impression that the program runs without main. But in reality it runs with a hidden main function. Let’s see how the preprocessor doing their job:- "
},
{
"code": null,
"e": 745,
"s": 702,
"text": "Hence it can be solved in following ways:-"
},
{
"code": null,
"e": 778,
"s": 745,
"text": "Using a macro that defines main "
},
{
"code": null,
"e": 811,
"s": 778,
"text": "Using a macro that defines main "
},
{
"code": null,
"e": 813,
"s": 811,
"text": "C"
},
{
"code": "#include<stdio.h>#define fun mainint fun(void){ printf(\"Geeksforgeeks\"); return 0;}",
"e": 903,
"s": 813,
"text": null
},
{
"code": null,
"e": 925,
"s": 903,
"text": "Output: Geeksforgeeks"
},
{
"code": null,
"e": 1108,
"s": 925,
"text": " 2. Using Token-Pasting Operator The above solution has word ‘main’ in it. If we are not allowed to even write main, we can use token-pasting operator (see this for details) "
},
{
"code": null,
"e": 1110,
"s": 1108,
"text": "C"
},
{
"code": "#include<stdio.h>#define fun m##a##i##nint fun(){ printf(\"Geeksforgeeks\"); return 0;}",
"e": 1202,
"s": 1110,
"text": null
},
{
"code": null,
"e": 1224,
"s": 1202,
"text": "Output: Geeksforgeeks"
},
{
"code": null,
"e": 1259,
"s": 1224,
"text": " 3. Using Argumented Macro "
},
{
"code": null,
"e": 1261,
"s": 1259,
"text": "C"
},
{
"code": "#include<stdio.h>#define begin(m,a,i,n) m##a##i##n#define start begin(m,a,i,n) void start() {printf(\"Geeksforgeeks\");}",
"e": 1380,
"s": 1261,
"text": null
},
{
"code": null,
"e": 1402,
"s": 1380,
"text": "Output: Geeksforgeeks"
},
{
"code": null,
"e": 1455,
"s": 1402,
"text": " 4. Modify the entry point during compilation "
},
{
"code": null,
"e": 1457,
"s": 1455,
"text": "C"
},
{
"code": "#include<stdio.h>#include<stdlib.h> // entry point functionint nomain(); void _start(){ // calling entry point nomain(); exit(0);} int nomain(){ puts(\"Geeksforgeeks\"); return 0;}",
"e": 1652,
"s": 1457,
"text": null
},
{
"code": null,
"e": 1675,
"s": 1652,
"text": "Output: \nGeeksforgeeks"
},
{
"code": null,
"e": 2235,
"s": 1675,
"text": "Compilation using command : gcc filename.c -nostartfiles (nostartfiles option tells the compiler to avoid standard linking) Explanation: Under normal compilation the body of _start() will contain a function call to main() [ this _start() will be appended to every code during normal compilation], so if that main() definition is not present it will result in error like “In function `_start’: (.text+0x20): undefined reference to `main’. In the above code what we have done is that we have defined our own _start() and defined our own entry point i.e nomain()"
},
{
"code": null,
"e": 2347,
"s": 2235,
"text": "Refer Executing main() in C – behind the scene for another solution. References: Macros and Preprocessors in C "
},
{
"code": null,
"e": 2369,
"s": 2347,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 2391,
"s": 2369,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 2591,
"s": 2391,
"text": "This article is contributed by Abhay Rathi and improved by Shubham Bansal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 2605,
"s": 2591,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 2616,
"s": 2605,
"text": "tarakki100"
},
{
"code": null,
"e": 2625,
"s": 2616,
"text": "c-puzzle"
},
{
"code": null,
"e": 2636,
"s": 2625,
"text": "C Language"
},
{
"code": null,
"e": 2734,
"s": 2636,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2782,
"s": 2734,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 2827,
"s": 2782,
"text": "What is the purpose of a function prototype?"
},
{
"code": null,
"e": 2848,
"s": 2827,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 2874,
"s": 2848,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 2912,
"s": 2874,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 2954,
"s": 2912,
"text": "Smart Pointers in C++ and How to Use Them"
},
{
"code": null,
"e": 2976,
"s": 2954,
"text": "'this' pointer in C++"
},
{
"code": null,
"e": 3005,
"s": 2976,
"text": "Ways to copy a vector in C++"
},
{
"code": null,
"e": 3026,
"s": 3005,
"text": "Storage Classes in C"
}
]
|
url – Django Template Tag | 03 Nov, 2021
A Django template is a text document or a Python string marked-up using the Django template language. Django being a powerful Batteries included framework provides convenience to rendering data in a template. Django templates not only allow passing data from view to template, but also provides some limited features of programming such as variables, for loops, comments, extends, url, etc.This article revolves about how to use url tag in Templates. url tag Returns an absolute path reference (a URL without the domain name) matching a given view and optional parameters. This is a way to output links without violating the DRY principle by having to hard-code URLs in your templates:
{% url 'some-url-name' v1 v2 %}
The first argument is a URL pattern name. It can be a quoted literal or any other context variable. Additional arguments are optional and should be space-separated values that will be used as arguments in the URL.
{% url 'template1' %}
Illustration of How to use url tag in Django templates 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 ?
Now create two views through which we will access the template,In geeks/views.py,
# import Http Response from djangofrom django.shortcuts import render # create a functiondef geeks_view(request): # return response return render(request, "geeks.html") def nav_view(request): # return response return render(request, "nav.html")
Create a url path to map to this view. URLs need to have a name which then can be used in templates and with url tag. In geeks/urls.py,
from django.urls import path # importing views from views..pyfrom .views import geeks_view, nav_view urlpatterns = [ path('1/', geeks_view, name = "template1"), path('2/', nav_view, name = "template2"),]
Now we will create two templates to demonstrate now tag. Create a template in geeks.html,
<html><h1>Template 1</h1><!-- Link to template 2 --><a href = "{% url 'template2' %}">Go to template 2</a></html>
Create a template in geeks.html,
<html><<h2>Template 2</h2><!-- Link to template 1 --><a href = "{% url 'template1' %}">Go to template 1</a></html>
Now visit http://127.0.0.1:8000/1,
Click on the link and it will redirect to other url.
suppose you have a view, app_views.client, whose URLconf takes a client ID (here, client() is a method inside the views file app_views.py). The URLconf line might look like this:
path('client/<int:id>/', app_views.client, name='app-views-client')
If this app’s URLconf is included into the project’s URLconf under a path such as this:
path('clients/', include('project_name.app_name.urls'))
...then, in a template, you can create a link to this view like this:
{% url 'app-views-client' client.id %}
The template tag will output the string /clients/client/123/.
simmytarika5
Django-templates
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n03 Nov, 2021"
},
{
"code": null,
"e": 738,
"s": 52,
"text": "A Django template is a text document or a Python string marked-up using the Django template language. Django being a powerful Batteries included framework provides convenience to rendering data in a template. Django templates not only allow passing data from view to template, but also provides some limited features of programming such as variables, for loops, comments, extends, url, etc.This article revolves about how to use url tag in Templates. url tag Returns an absolute path reference (a URL without the domain name) matching a given view and optional parameters. This is a way to output links without violating the DRY principle by having to hard-code URLs in your templates:"
},
{
"code": null,
"e": 771,
"s": 738,
"text": "{% url 'some-url-name' v1 v2 %}\n"
},
{
"code": null,
"e": 985,
"s": 771,
"text": "The first argument is a URL pattern name. It can be a quoted literal or any other context variable. Additional arguments are optional and should be space-separated values that will be used as arguments in the URL."
},
{
"code": null,
"e": 1008,
"s": 985,
"text": "{% url 'template1' %}\n"
},
{
"code": null,
"e": 1147,
"s": 1008,
"text": "Illustration of How to use url tag in Django templates using an Example. Consider a project named geeksforgeeks having an app named geeks."
},
{
"code": null,
"e": 1234,
"s": 1147,
"text": "Refer to the following articles to check how to create a project and an app in Django."
},
{
"code": null,
"e": 1285,
"s": 1234,
"text": "How to Create a Basic Project using MVT in Django?"
},
{
"code": null,
"e": 1318,
"s": 1285,
"text": "How to Create an App in Django ?"
},
{
"code": null,
"e": 1400,
"s": 1318,
"text": "Now create two views through which we will access the template,In geeks/views.py,"
},
{
"code": "# import Http Response from djangofrom django.shortcuts import render # create a functiondef geeks_view(request): # return response return render(request, \"geeks.html\") def nav_view(request): # return response return render(request, \"nav.html\")",
"e": 1660,
"s": 1400,
"text": null
},
{
"code": null,
"e": 1796,
"s": 1660,
"text": "Create a url path to map to this view. URLs need to have a name which then can be used in templates and with url tag. In geeks/urls.py,"
},
{
"code": "from django.urls import path # importing views from views..pyfrom .views import geeks_view, nav_view urlpatterns = [ path('1/', geeks_view, name = \"template1\"), path('2/', nav_view, name = \"template2\"),]",
"e": 2008,
"s": 1796,
"text": null
},
{
"code": null,
"e": 2098,
"s": 2008,
"text": "Now we will create two templates to demonstrate now tag. Create a template in geeks.html,"
},
{
"code": "<html><h1>Template 1</h1><!-- Link to template 2 --><a href = \"{% url 'template2' %}\">Go to template 2</a></html>",
"e": 2212,
"s": 2098,
"text": null
},
{
"code": null,
"e": 2245,
"s": 2212,
"text": "Create a template in geeks.html,"
},
{
"code": "<html><<h2>Template 2</h2><!-- Link to template 1 --><a href = \"{% url 'template1' %}\">Go to template 1</a></html>",
"e": 2360,
"s": 2245,
"text": null
},
{
"code": null,
"e": 2395,
"s": 2360,
"text": "Now visit http://127.0.0.1:8000/1,"
},
{
"code": null,
"e": 2448,
"s": 2395,
"text": "Click on the link and it will redirect to other url."
},
{
"code": null,
"e": 2627,
"s": 2448,
"text": "suppose you have a view, app_views.client, whose URLconf takes a client ID (here, client() is a method inside the views file app_views.py). The URLconf line might look like this:"
},
{
"code": null,
"e": 2695,
"s": 2627,
"text": "path('client/<int:id>/', app_views.client, name='app-views-client')"
},
{
"code": null,
"e": 2783,
"s": 2695,
"text": "If this app’s URLconf is included into the project’s URLconf under a path such as this:"
},
{
"code": null,
"e": 2839,
"s": 2783,
"text": "path('clients/', include('project_name.app_name.urls'))"
},
{
"code": null,
"e": 2909,
"s": 2839,
"text": "...then, in a template, you can create a link to this view like this:"
},
{
"code": null,
"e": 2948,
"s": 2909,
"text": "{% url 'app-views-client' client.id %}"
},
{
"code": null,
"e": 3010,
"s": 2948,
"text": "The template tag will output the string /clients/client/123/."
},
{
"code": null,
"e": 3023,
"s": 3010,
"text": "simmytarika5"
},
{
"code": null,
"e": 3040,
"s": 3023,
"text": "Django-templates"
},
{
"code": null,
"e": 3054,
"s": 3040,
"text": "Python Django"
},
{
"code": null,
"e": 3061,
"s": 3054,
"text": "Python"
},
{
"code": null,
"e": 3159,
"s": 3061,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3177,
"s": 3159,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3219,
"s": 3177,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3241,
"s": 3219,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3276,
"s": 3241,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 3302,
"s": 3276,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3334,
"s": 3302,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3363,
"s": 3334,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3390,
"s": 3363,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3420,
"s": 3390,
"text": "Iterate over a list in Python"
}
]
|
Check whether a given point lies inside a Triangle
| Three points of a triangle are given; another point P is also given to check whether the point P is inside the triangle or not.
To solve the problem, let consider the points of the triangle are A, B, and C. When the area of triangle ΔABC = ΔABP + ΔPBC + ΔAPC, then the point P is inside the triangle.
Input:
Points of the triangle {(0, 0), (20, 0), (10, 30)} and point p (10, 15) to check.
Output:
Point is inside the triangle.
isInside(p1, p2, p3, p)
Input: Three points of a triangle, the point p to check.
Output: True, when p is inside the triangle.
Begin
area := area of triangle(p1, p2, p3)
area1 := area of triangle(p, p2, p3)
area2 := area of triangle(p1, p, p3)
area3 := area of triangle(p1, p2, p)
if area = (area1 + area2 + area3), then
return true
else return false
End
#include <iostream>
#include<cmath>
using namespace std;
struct Point {
int x, y;
};
float triangleArea(Point p1, Point p2, Point p3) { //find area of triangle formed by p1, p2 and p3
return abs((p1.x*(p2.y-p3.y) + p2.x*(p3.y-p1.y)+ p3.x*(p1.yp2.y))/2.0);
}
bool isInside(Point p1, Point p2, Point p3, Point p) { //check whether p is inside or outside
float area = triangleArea (p1, p2, p3); //area of triangle ABC
float area1 = triangleArea (p, p2, p3); //area of PBC
float area2 = triangleArea (p1, p, p3); //area of APC
float area3 = triangleArea (p1, p2, p); //area of ABP
return (area == area1 + area2 + area3); //when three triangles are forming the whole triangle
}
int main() {
Point p1={0, 0}, p2={20, 0}, p3={10, 30};
Point p = {10, 15};
if (isInside(p1, p2, p3, p))
cout << "Point is inside the triangle.";
else
cout << "Point is not inside the triangle";
}
Point is inside the triangle. | [
{
"code": null,
"e": 1315,
"s": 1187,
"text": "Three points of a triangle are given; another point P is also given to check whether the point P is inside the triangle or not."
},
{
"code": null,
"e": 1488,
"s": 1315,
"text": "To solve the problem, let consider the points of the triangle are A, B, and C. When the area of triangle ΔABC = ΔABP + ΔPBC + ΔAPC, then the point P is inside the triangle."
},
{
"code": null,
"e": 1615,
"s": 1488,
"text": "Input:\nPoints of the triangle {(0, 0), (20, 0), (10, 30)} and point p (10, 15) to check.\nOutput:\nPoint is inside the triangle."
},
{
"code": null,
"e": 1639,
"s": 1615,
"text": "isInside(p1, p2, p3, p)"
},
{
"code": null,
"e": 1696,
"s": 1639,
"text": "Input: Three points of a triangle, the point p to check."
},
{
"code": null,
"e": 1741,
"s": 1696,
"text": "Output: True, when p is inside the triangle."
},
{
"code": null,
"e": 1993,
"s": 1741,
"text": "Begin\n area := area of triangle(p1, p2, p3)\n area1 := area of triangle(p, p2, p3)\n area2 := area of triangle(p1, p, p3)\n area3 := area of triangle(p1, p2, p)\n if area = (area1 + area2 + area3), then\n return true\n else return false\nEnd"
},
{
"code": null,
"e": 2964,
"s": 1993,
"text": "#include <iostream>\n#include<cmath>\nusing namespace std;\n\nstruct Point {\n int x, y;\n};\n\nfloat triangleArea(Point p1, Point p2, Point p3) { //find area of triangle formed by p1, p2 and p3\n return abs((p1.x*(p2.y-p3.y) + p2.x*(p3.y-p1.y)+ p3.x*(p1.yp2.y))/2.0);\n}\n\nbool isInside(Point p1, Point p2, Point p3, Point p) { //check whether p is inside or outside\n float area = triangleArea (p1, p2, p3); //area of triangle ABC\n float area1 = triangleArea (p, p2, p3); //area of PBC\n float area2 = triangleArea (p1, p, p3); //area of APC\n float area3 = triangleArea (p1, p2, p); //area of ABP\n\n return (area == area1 + area2 + area3); //when three triangles are forming the whole triangle\n}\n \nint main() {\n Point p1={0, 0}, p2={20, 0}, p3={10, 30};\n Point p = {10, 15};\n if (isInside(p1, p2, p3, p))\n cout << \"Point is inside the triangle.\";\n else\n cout << \"Point is not inside the triangle\";\n}"
},
{
"code": null,
"e": 2994,
"s": 2964,
"text": "Point is inside the triangle."
}
]
|
Python OpenCV – selectroi() Function | 24 Oct, 2021
In this article, we are going to see an interesting application of the OpenCV library, which is selectROI(). With this method, we can select a range of interest in an image manually by selecting the area on the image.
Syntax: cv2.selectROI(Window_name, source image)
Parameter:
window_name: name of the window where selection process will be shown.
source image: image to select a ROI.
showCrosshair: if true crosshair of the selection rectangle will be displayed.
fromCenter: if true origin of selection will match initial mouse position
Using this function in OpenCV, we can precisely and manually select the area of interest we needed from the image and hence we can perform many tasks for that specific area. We can pass that particular area as an input for another task. We can also draw a tracking figure(rectangle) on the area using the coordinates or we can precisely and freely crop an image. First of all, we need to import the required libraries which in our case it is OpenCV and NumPy. NumPy library plays a very crucial part in this program because OpenCV uses NumPy as the backbone to do all image manipulations.
Before doing all sorts of functions in an image it is obvious to read the image first. And store it in a variable to access it in the future for further manipulations.
Syntax:
cv2.imread(source image)
Now we are getting into the actual function which is selectROI(). So, basically, this function will allow us to select a range of interest in an image(a particular area of an image) and perform different actions in that area, in this particular example we are going to crop the image to display the cropped image.
Now we are going to call the selectRoi() function and pass in the image as a parameter and what the function is going to return is an array of different values which contained the coordinates of the selected area and we are storing it in a variable called “r”. Which is basically the starting and ending pixels of the selected area in an image and the output array in order of [Top_X, Top_Y, Bottom_X, Bottom_Y]
Which in OpenCV the x and y coordinates are kind of swapped,
Note: This selectedROI() function has its own default output which will show us the image automatically and let us manually select the ROI in the image. We can also name that window by passing windowname parameter in the function()
Controls of the function: After selecting the ROI, we are asked to press the space button or enter to proceed with the selected area. And C to cancel the selection. Using those coordinates we are going to select the particular selected area and crop it out and show the output. To crop the image with NumPy arrays,
Syntax:
source_image[ start_row : end_row, start_col : end_col]
In which we should pass the value of the starting and ending pixel values of the image. Finally, we are going to show the cropped image and destroy the windows.
Program: Program to select and crop an image.
Python3
import cv2import numpy as np # Read imageimage = cv2.imread("image.png") # Select ROIr = cv2.selectROI("select the area", image) # Crop imagecropped_image = image[int(r[1]):int(r[1]+r[3]), int(r[0]):int(r[0]+r[2])] # Display cropped imagecv2.imshow("Cropped image", cropped_image)cv2.waitKey(0)
Picked
Python-OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python OOPs Concepts
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Oct, 2021"
},
{
"code": null,
"e": 246,
"s": 28,
"text": "In this article, we are going to see an interesting application of the OpenCV library, which is selectROI(). With this method, we can select a range of interest in an image manually by selecting the area on the image."
},
{
"code": null,
"e": 295,
"s": 246,
"text": "Syntax: cv2.selectROI(Window_name, source image)"
},
{
"code": null,
"e": 306,
"s": 295,
"text": "Parameter:"
},
{
"code": null,
"e": 378,
"s": 306,
"text": "window_name: name of the window where selection process will be shown."
},
{
"code": null,
"e": 416,
"s": 378,
"text": "source image: image to select a ROI."
},
{
"code": null,
"e": 495,
"s": 416,
"text": "showCrosshair: if true crosshair of the selection rectangle will be displayed."
},
{
"code": null,
"e": 569,
"s": 495,
"text": "fromCenter: if true origin of selection will match initial mouse position"
},
{
"code": null,
"e": 1158,
"s": 569,
"text": "Using this function in OpenCV, we can precisely and manually select the area of interest we needed from the image and hence we can perform many tasks for that specific area. We can pass that particular area as an input for another task. We can also draw a tracking figure(rectangle) on the area using the coordinates or we can precisely and freely crop an image. First of all, we need to import the required libraries which in our case it is OpenCV and NumPy. NumPy library plays a very crucial part in this program because OpenCV uses NumPy as the backbone to do all image manipulations."
},
{
"code": null,
"e": 1326,
"s": 1158,
"text": "Before doing all sorts of functions in an image it is obvious to read the image first. And store it in a variable to access it in the future for further manipulations."
},
{
"code": null,
"e": 1335,
"s": 1326,
"text": "Syntax: "
},
{
"code": null,
"e": 1360,
"s": 1335,
"text": "cv2.imread(source image)"
},
{
"code": null,
"e": 1674,
"s": 1360,
"text": "Now we are getting into the actual function which is selectROI(). So, basically, this function will allow us to select a range of interest in an image(a particular area of an image) and perform different actions in that area, in this particular example we are going to crop the image to display the cropped image."
},
{
"code": null,
"e": 2087,
"s": 1674,
"text": "Now we are going to call the selectRoi() function and pass in the image as a parameter and what the function is going to return is an array of different values which contained the coordinates of the selected area and we are storing it in a variable called “r”. Which is basically the starting and ending pixels of the selected area in an image and the output array in order of [Top_X, Top_Y, Bottom_X, Bottom_Y]"
},
{
"code": null,
"e": 2149,
"s": 2087,
"text": "Which in OpenCV the x and y coordinates are kind of swapped,"
},
{
"code": null,
"e": 2381,
"s": 2149,
"text": "Note: This selectedROI() function has its own default output which will show us the image automatically and let us manually select the ROI in the image. We can also name that window by passing windowname parameter in the function()"
},
{
"code": null,
"e": 2696,
"s": 2381,
"text": "Controls of the function: After selecting the ROI, we are asked to press the space button or enter to proceed with the selected area. And C to cancel the selection. Using those coordinates we are going to select the particular selected area and crop it out and show the output. To crop the image with NumPy arrays,"
},
{
"code": null,
"e": 2705,
"s": 2696,
"text": "Syntax: "
},
{
"code": null,
"e": 2761,
"s": 2705,
"text": "source_image[ start_row : end_row, start_col : end_col]"
},
{
"code": null,
"e": 2922,
"s": 2761,
"text": "In which we should pass the value of the starting and ending pixel values of the image. Finally, we are going to show the cropped image and destroy the windows."
},
{
"code": null,
"e": 2968,
"s": 2922,
"text": "Program: Program to select and crop an image."
},
{
"code": null,
"e": 2976,
"s": 2968,
"text": "Python3"
},
{
"code": "import cv2import numpy as np # Read imageimage = cv2.imread(\"image.png\") # Select ROIr = cv2.selectROI(\"select the area\", image) # Crop imagecropped_image = image[int(r[1]):int(r[1]+r[3]), int(r[0]):int(r[0]+r[2])] # Display cropped imagecv2.imshow(\"Cropped image\", cropped_image)cv2.waitKey(0)",
"e": 3299,
"s": 2976,
"text": null
},
{
"code": null,
"e": 3306,
"s": 3299,
"text": "Picked"
},
{
"code": null,
"e": 3320,
"s": 3306,
"text": "Python-OpenCV"
},
{
"code": null,
"e": 3327,
"s": 3320,
"text": "Python"
},
{
"code": null,
"e": 3425,
"s": 3327,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3467,
"s": 3425,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3489,
"s": 3467,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3515,
"s": 3489,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3547,
"s": 3515,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3576,
"s": 3547,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3603,
"s": 3576,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3639,
"s": 3603,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 3660,
"s": 3639,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3691,
"s": 3660,
"text": "Python | os.path.join() method"
}
]
|
Minimum steps required to reduce all the elements of the array to zero - GeeksforGeeks | 19 Mar, 2022
Given an array arr[] of positive integers, the task is to find the minimum steps to reduce all the elements to 0. In a single step, -1 can be added to all the non-zero elements of the array at the same time.Examples:
Input: arr[] = {1, 5, 6} Output: 6 Operation 1: arr[] = {0, 4, 5} Operation 2: arr[] = {0, 3, 4} Operation 3: arr[] = {0, 2, 3} Operation 4: arr[] = {0, 1, 2} Operation 5: arr[] = {0, 0, 1} Operation 6: arr[] = {0, 0, 0}Input: arr[] = {1, 1} Output: 1
Naive approach: A simple approach is to first sort the array then starting from the minimum element, count the number of steps required to reduce it to 0. This count will then be reduced from the next array element as all the elements will be updated at the same time.Efficient approach: It can be observed that the minimum number of steps will always be equal to the maximum element from the array.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the minimum steps// required to reduce all the elements to 0int minSteps(int arr[], int n){ // Maximum element from the array int maxVal = *max_element(arr, arr + n); return maxVal;} // Driver codeint main(){ int arr[] = { 1, 2, 4 }; int n = sizeof(arr) / sizeof(int); cout << minSteps(arr, n); return 0;}
// Java implementation of the approachclass GFG{ // method to get maximum number from array elements static int getMax(int inputArray []) { int maxValue = inputArray[0]; for(int i = 1; i < inputArray.length; i++) { if(inputArray[i] > maxValue) { maxValue = inputArray[i]; } } return maxValue; } // Function to return the minimum steps // required to reduce all the elements to 0 static int minSteps(int arr[], int n) { // Maximum element from the array int maxVal = getMax(arr); return maxVal; } // Driver code public static void main (String[] args) { int arr[] = { 1, 2, 4 }; int n = arr.length; System.out.println(minSteps(arr, n)); }} // This code is contributed by AnkitRai01
# Python3 implementation of the approach # Function to return the minimum steps# required to reduce all the elements to 0def minSteps(arr, n): # Maximum element from the array maxVal = max(arr) return maxVal # Driver codearr = [1, 2, 4]n = len(arr) print(minSteps(arr, n)) # This code is contributed by Mohit Kumar
// C# implementation of the approachusing System; class GFG{ // method to get maximum number from array elements static int getMax(int []inputArray) { int maxValue = inputArray[0]; for(int i = 1; i < inputArray.Length; i++) { if(inputArray[i] > maxValue) { maxValue = inputArray[i]; } } return maxValue; } // Function to return the minimum steps // required to reduce all the elements to 0 static int minSteps(int []arr, int n) { // Maximum element from the array int maxVal = getMax(arr); return maxVal; } // Driver code public static void Main(String []args) { int []arr = { 1, 2, 4 }; int n = arr.Length; Console.WriteLine(minSteps(arr, n)); }} // This code is contributed by Arnab Kundu
<script>// Javascript implementation of the approach // Function to return the minimum steps// required to reduce all the elements to 0function minSteps(arr, n){ // Maximum element from the array let maxVal = Math.max(...arr); return maxVal;} // Driver code let arr = [ 1, 2, 4 ]; let n = arr.length; document.write(minSteps(arr, n)); </script>
4
Time Complexity: O(n)
Auxiliary Space: O(1)
mohit kumar 29
ankthon
andrew1234
subhammahato348
subham348
Arrays
Greedy
Mathematical
Sorting
Arrays
Greedy
Mathematical
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Multidimensional Arrays in Java
Introduction to Arrays
Linear Search
Python | Using 2D arrays/lists the right way
Dijkstra's shortest path algorithm | Greedy Algo-7
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Huffman Coding | Greedy Algo-3
Write a program to print all permutations of a given string | [
{
"code": null,
"e": 25339,
"s": 25311,
"text": "\n19 Mar, 2022"
},
{
"code": null,
"e": 25558,
"s": 25339,
"text": "Given an array arr[] of positive integers, the task is to find the minimum steps to reduce all the elements to 0. In a single step, -1 can be added to all the non-zero elements of the array at the same time.Examples: "
},
{
"code": null,
"e": 25812,
"s": 25558,
"text": "Input: arr[] = {1, 5, 6} Output: 6 Operation 1: arr[] = {0, 4, 5} Operation 2: arr[] = {0, 3, 4} Operation 3: arr[] = {0, 2, 3} Operation 4: arr[] = {0, 1, 2} Operation 5: arr[] = {0, 0, 1} Operation 6: arr[] = {0, 0, 0}Input: arr[] = {1, 1} Output: 1 "
},
{
"code": null,
"e": 26266,
"s": 25814,
"text": "Naive approach: A simple approach is to first sort the array then starting from the minimum element, count the number of steps required to reduce it to 0. This count will then be reduced from the next array element as all the elements will be updated at the same time.Efficient approach: It can be observed that the minimum number of steps will always be equal to the maximum element from the array.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26270,
"s": 26266,
"text": "C++"
},
{
"code": null,
"e": 26275,
"s": 26270,
"text": "Java"
},
{
"code": null,
"e": 26283,
"s": 26275,
"text": "Python3"
},
{
"code": null,
"e": 26286,
"s": 26283,
"text": "C#"
},
{
"code": null,
"e": 26297,
"s": 26286,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the minimum steps// required to reduce all the elements to 0int minSteps(int arr[], int n){ // Maximum element from the array int maxVal = *max_element(arr, arr + n); return maxVal;} // Driver codeint main(){ int arr[] = { 1, 2, 4 }; int n = sizeof(arr) / sizeof(int); cout << minSteps(arr, n); return 0;}",
"e": 26731,
"s": 26297,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG{ // method to get maximum number from array elements static int getMax(int inputArray []) { int maxValue = inputArray[0]; for(int i = 1; i < inputArray.length; i++) { if(inputArray[i] > maxValue) { maxValue = inputArray[i]; } } return maxValue; } // Function to return the minimum steps // required to reduce all the elements to 0 static int minSteps(int arr[], int n) { // Maximum element from the array int maxVal = getMax(arr); return maxVal; } // Driver code public static void main (String[] args) { int arr[] = { 1, 2, 4 }; int n = arr.length; System.out.println(minSteps(arr, n)); }} // This code is contributed by AnkitRai01",
"e": 27602,
"s": 26731,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to return the minimum steps# required to reduce all the elements to 0def minSteps(arr, n): # Maximum element from the array maxVal = max(arr) return maxVal # Driver codearr = [1, 2, 4]n = len(arr) print(minSteps(arr, n)) # This code is contributed by Mohit Kumar",
"e": 27927,
"s": 27602,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // method to get maximum number from array elements static int getMax(int []inputArray) { int maxValue = inputArray[0]; for(int i = 1; i < inputArray.Length; i++) { if(inputArray[i] > maxValue) { maxValue = inputArray[i]; } } return maxValue; } // Function to return the minimum steps // required to reduce all the elements to 0 static int minSteps(int []arr, int n) { // Maximum element from the array int maxVal = getMax(arr); return maxVal; } // Driver code public static void Main(String []args) { int []arr = { 1, 2, 4 }; int n = arr.Length; Console.WriteLine(minSteps(arr, n)); }} // This code is contributed by Arnab Kundu",
"e": 28808,
"s": 27927,
"text": null
},
{
"code": "<script>// Javascript implementation of the approach // Function to return the minimum steps// required to reduce all the elements to 0function minSteps(arr, n){ // Maximum element from the array let maxVal = Math.max(...arr); return maxVal;} // Driver code let arr = [ 1, 2, 4 ]; let n = arr.length; document.write(minSteps(arr, n)); </script>",
"e": 29173,
"s": 28808,
"text": null
},
{
"code": null,
"e": 29175,
"s": 29173,
"text": "4"
},
{
"code": null,
"e": 29199,
"s": 29177,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 29221,
"s": 29199,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 29236,
"s": 29221,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 29244,
"s": 29236,
"text": "ankthon"
},
{
"code": null,
"e": 29255,
"s": 29244,
"text": "andrew1234"
},
{
"code": null,
"e": 29271,
"s": 29255,
"text": "subhammahato348"
},
{
"code": null,
"e": 29281,
"s": 29271,
"text": "subham348"
},
{
"code": null,
"e": 29288,
"s": 29281,
"text": "Arrays"
},
{
"code": null,
"e": 29295,
"s": 29288,
"text": "Greedy"
},
{
"code": null,
"e": 29308,
"s": 29295,
"text": "Mathematical"
},
{
"code": null,
"e": 29316,
"s": 29308,
"text": "Sorting"
},
{
"code": null,
"e": 29323,
"s": 29316,
"text": "Arrays"
},
{
"code": null,
"e": 29330,
"s": 29323,
"text": "Greedy"
},
{
"code": null,
"e": 29343,
"s": 29330,
"text": "Mathematical"
},
{
"code": null,
"e": 29351,
"s": 29343,
"text": "Sorting"
},
{
"code": null,
"e": 29449,
"s": 29351,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29517,
"s": 29449,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 29549,
"s": 29517,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 29572,
"s": 29549,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 29586,
"s": 29572,
"text": "Linear Search"
},
{
"code": null,
"e": 29631,
"s": 29586,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 29682,
"s": 29631,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 29740,
"s": 29682,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 29791,
"s": 29740,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
},
{
"code": null,
"e": 29822,
"s": 29791,
"text": "Huffman Coding | Greedy Algo-3"
}
]
|
Fortran - Manipulation Functions | Manipulation functions are shift functions. The shift functions return the shape of an array unchanged, but move the elements.
cshift(array, shift, dim)
It performs circular shift by shift positions to the left, if shift is positive and to the right if it is negative. If array is a vector the shift is being done in a natural way, if it is an array of a higher rank then the shift is in all sections along the dimension dim. If dim is missing it is considered to be 1, in other cases it has to be a scalar integer number between 1 and n (where n equals the rank of array ). The argument shift is a scalar integer or an integer array of rank n-1 and the same shape as the array, except along the dimension dim (which is removed because of the lower rank). Different sections can therefore be shifted in various directions and with various numbers of positions.
eoshift(array, shift, boundary, dim)
It is end-off shift. It performs shift to the left if shift is positive and to the right if it is negative. Instead of the elements shifted out new elements are taken from boundary. If array is a vector the shift is being done in a natural way, if it is an array of a higher rank, the shift on all sections is along the dimension dim. if dim is missing, it is considered to be 1, in other cases it has to have a scalar integer value between 1 and n (where n equals the rank of array). The argument shift is a scalar integer if array has rank 1, in the other case it can be a scalar integer or an integer array of rank n-1 and with the same shape as the array array except along the dimension dim (which is removed because of the lower rank).
transpose (matrix)
It transposes a matrix, which is an array of rank 2. It replaces the rows and columns in the matrix.
The following example demonstrates the concept −
program arrayShift
implicit none
real, dimension(1:6) :: a = (/ 21.0, 22.0, 23.0, 24.0, 25.0, 26.0 /)
real, dimension(1:6) :: x, y
write(*,10) a
x = cshift ( a, shift = 2)
write(*,10) x
y = cshift (a, shift = -2)
write(*,10) y
x = eoshift ( a, shift = 2)
write(*,10) x
y = eoshift ( a, shift = -2)
write(*,10) y
10 format(1x,6f6.1)
end program arrayShift
When the above code is compiled and executed, it produces the following result −
21.0 22.0 23.0 24.0 25.0 26.0
23.0 24.0 25.0 26.0 21.0 22.0
25.0 26.0 21.0 22.0 23.0 24.0
23.0 24.0 25.0 26.0 0.0 0.0
0.0 0.0 21.0 22.0 23.0 24.0
The following example demonstrates transpose of a matrix −
program matrixTranspose
implicit none
interface
subroutine write_matrix(a)
integer, dimension(:,:) :: a
end subroutine write_matrix
end interface
integer, dimension(3,3) :: a, b
integer :: i, j
do i = 1, 3
do j = 1, 3
a(i, j) = i
end do
end do
print *, 'Matrix Transpose: A Matrix'
call write_matrix(a)
b = transpose(a)
print *, 'Transposed Matrix:'
call write_matrix(b)
end program matrixTranspose
subroutine write_matrix(a)
integer, dimension(:,:) :: a
write(*,*)
do i = lbound(a,1), ubound(a,1)
write(*,*) (a(i,j), j = lbound(a,2), ubound(a,2))
end do
end subroutine write_matrix
When the above code is compiled and executed, it produces the following result −
Matrix Transpose: A Matrix
1 1 1
2 2 2
3 3 3
Transposed Matrix:
1 2 3
1 2 3
1 2 3
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2273,
"s": 2146,
"text": "Manipulation functions are shift functions. The shift functions return the shape of an array unchanged, but move the elements."
},
{
"code": null,
"e": 2299,
"s": 2273,
"text": "cshift(array, shift, dim)"
},
{
"code": null,
"e": 3007,
"s": 2299,
"text": "It performs circular shift by shift positions to the left, if shift is positive and to the right if it is negative. If array is a vector the shift is being done in a natural way, if it is an array of a higher rank then the shift is in all sections along the dimension dim. If dim is missing it is considered to be 1, in other cases it has to be a scalar integer number between 1 and n (where n equals the rank of array ). The argument shift is a scalar integer or an integer array of rank n-1 and the same shape as the array, except along the dimension dim (which is removed because of the lower rank). Different sections can therefore be shifted in various directions and with various numbers of positions."
},
{
"code": null,
"e": 3044,
"s": 3007,
"text": "eoshift(array, shift, boundary, dim)"
},
{
"code": null,
"e": 3786,
"s": 3044,
"text": "It is end-off shift. It performs shift to the left if shift is positive and to the right if it is negative. Instead of the elements shifted out new elements are taken from boundary. If array is a vector the shift is being done in a natural way, if it is an array of a higher rank, the shift on all sections is along the dimension dim. if dim is missing, it is considered to be 1, in other cases it has to have a scalar integer value between 1 and n (where n equals the rank of array). The argument shift is a scalar integer if array has rank 1, in the other case it can be a scalar integer or an integer array of rank n-1 and with the same shape as the array array except along the dimension dim (which is removed because of the lower rank)."
},
{
"code": null,
"e": 3805,
"s": 3786,
"text": "transpose (matrix)"
},
{
"code": null,
"e": 3906,
"s": 3805,
"text": "It transposes a matrix, which is an array of rank 2. It replaces the rows and columns in the matrix."
},
{
"code": null,
"e": 3955,
"s": 3906,
"text": "The following example demonstrates the concept −"
},
{
"code": null,
"e": 4368,
"s": 3955,
"text": "program arrayShift\nimplicit none\n\n real, dimension(1:6) :: a = (/ 21.0, 22.0, 23.0, 24.0, 25.0, 26.0 /)\n real, dimension(1:6) :: x, y\n write(*,10) a\n \n x = cshift ( a, shift = 2)\n write(*,10) x\n \n y = cshift (a, shift = -2)\n write(*,10) y\n \n x = eoshift ( a, shift = 2)\n write(*,10) x\n \n y = eoshift ( a, shift = -2)\n write(*,10) y\n \n 10 format(1x,6f6.1)\n\nend program arrayShift"
},
{
"code": null,
"e": 4449,
"s": 4368,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 4625,
"s": 4449,
"text": "21.0 22.0 23.0 24.0 25.0 26.0\n23.0 24.0 25.0 26.0 21.0 22.0\n25.0 26.0 21.0 22.0 23.0 24.0\n23.0 24.0 25.0 26.0 0.0 0.0\n0.0 0.0 21.0 22.0 23.0 24.0\n"
},
{
"code": null,
"e": 4684,
"s": 4625,
"text": "The following example demonstrates transpose of a matrix −"
},
{
"code": null,
"e": 5390,
"s": 4684,
"text": "program matrixTranspose\nimplicit none\n\n interface\n subroutine write_matrix(a)\n integer, dimension(:,:) :: a\n end subroutine write_matrix\n end interface\n\n integer, dimension(3,3) :: a, b\n integer :: i, j\n \n do i = 1, 3\n do j = 1, 3\n a(i, j) = i\n end do\n end do\n \n print *, 'Matrix Transpose: A Matrix'\n \n call write_matrix(a)\n b = transpose(a)\n print *, 'Transposed Matrix:'\n \n call write_matrix(b)\nend program matrixTranspose\n\n\nsubroutine write_matrix(a)\n\n integer, dimension(:,:) :: a\n write(*,*)\n \n do i = lbound(a,1), ubound(a,1)\n write(*,*) (a(i,j), j = lbound(a,2), ubound(a,2))\n end do\n \nend subroutine write_matrix"
},
{
"code": null,
"e": 5471,
"s": 5390,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 5568,
"s": 5471,
"text": "Matrix Transpose: A Matrix\n\n1 1 1\n2 2 2\n3 3 3\nTransposed Matrix:\n\n1 2 3\n1 2 3\n1 2 3\n"
},
{
"code": null,
"e": 5575,
"s": 5568,
"text": " Print"
},
{
"code": null,
"e": 5586,
"s": 5575,
"text": " Add Notes"
}
]
|
Underline text with CSS | Use the text-decoration property to underline text with CSS. You can try to run the following code to underline text:
<html>
<head>
</head>
<body>
<p style = "text-decoration:underline;">
India
</p>
</body>
</html> | [
{
"code": null,
"e": 1180,
"s": 1062,
"text": "Use the text-decoration property to underline text with CSS. You can try to run the following code to underline text:"
},
{
"code": null,
"e": 1310,
"s": 1180,
"text": "<html>\n <head>\n </head>\n <body>\n <p style = \"text-decoration:underline;\">\n India\n </p>\n </body>\n</html>"
}
]
|
Lean Six Sigma with Python — Kruskal Wallis Test | by Samir Saci | Towards Data Science | Lean Six Sigma (LSS) is a method based on a stepwise approach to process improvements.
This approach usually follows 5 steps (Define, Measure, Analyze, Improve and Control) for improving existing process problems with unknown causes.
In this article, we will explore how Python can replace Minitab (Software widely used by LSS experts) in the Analysis step to test hypotheses and understand what could improve the performance metrics of a specific process.
SUMMARYI. Problem StatementCan we improve the operators' productivity by giving them a training designed by R&D team?II. Data Analysis1. Exploratory Data AnalysisAnalysis with Python sample data from experiment with few operators 2. Analysis of Variance (ANOVA)Verify the hypothesis that training impacts productivityANOVA assumptions are not verified3. Kruskal-Wallis testConfirm that the hypothesis can be generalizedIII. Conclusion
You are the Continous Improvement Manager of a Distribution Center (DC) for an iconic Luxury Maison focusing on Fashion, Fragrances and Watches.
The warehouse receives garments that require final assembling and value-added service (VAS) during the inbound process.
For each dress received your operators need to print a label in the local language and perform label sewing.
In this article, we will focus on the improvement of label sewing productivity. Labels are distributed to the operators by batches of 30 labels. The productivity is calculated based on the time (in seconds) needed to finish a batch.
Edit: You can find a Youtube version of this article with animations in the link below.
With the support of the R&D team, you designed training for the VAS operators to improve their productivity and reduce quality issues.
QuestionDoes the training have a positive impact on the productivity of operators?
HypothesisThe training has a positive impact on the productivity of VAS operators.
ExperimentRandomly select operators and measure the time per batch (Time to finish a batch of 30 labels in seconds) to build a sample of 56 records.
You can find the full code in this Github repository: LinkMy portfolio with other projects: Samir Saci
You can download the results of this experiment in this CSV file to run the whole code on your computer (here).
56 records35 records of operators without training21 records of operators with training
Box Plot
Based on the sample data, we can see that the median and the mean of the is considerably lower for the operators who had training.
HypothesisThe training reduces the average time per batch.
Code
MinitabMenu Graph > Box Plot > Simple > 1 Y with Groups
In this scenario, we want to check if the training (Variable X) is impacting the total time per batch (Variable Y).
Because X is a categorical variable (Training = Yes/No) and Y is numerical, the appropriate method is ANOVA.
ANOVA is a statistical method used to check if we can generalize the difference of means seen in the sample data to the entire population.
Step 1: Calculate the p-value
Source: Trainingddof: 11ddof: 245.267F: 17.1066p-unc: 0.000151308p: 20.173692p-value is below 5%
Code
MinitabMenu Stats > ANOVA > One-Way
Step 2: Validate the assumptions of ANOVA
Based on the p-value, we know that the difference of mean is real and not due to random fluctuation.
However, before jumping to a conclusion we need to check that the ANOVA assumptions are satisfied
Residuals are naturally distributed
Answer: No
There are no outliers or irregularities
Answer: No
ConclusionANOVA requirements are not met, we need another method to confirm that the training actually impacts operators productivity.
Code
MinitabMenu Stats > ANOVA > One-Way > Graphs > Four in one
If your sample data fails to meet ANOVA requirements, you can use Kruskal-Wallis Test to check if the difference of means is due to random fluctuation.
statistic = 54.99pvalue = 1.205e-13p-value is below 5%
ConclusionThe p-value is below 5% so we can conclude that the difference of means is statically significant.
We can confirm that the training has a positive impact on the productivity of the operators.
Code
MinitabMenu Stats > Non-parametric > Kruskal Wallis > Graphs > Four in one
If you are interested in other applications of Lean Six Sigma Methodology using Python you can have a look at the articles below:
www.samirsaci.com
www.samirsaci.com
This data-driven approach gave you enough elements to convince your management to invest in workforce training.
You brought enough insights with a moderate effort of experimentation by generalising patterns from sample data using statistics.
Please feel free to contact me, I am willing to share and exchange on topics related to Data Science and Supply Chain.My Portfolio: https://samirsaci.com
[1] ANOVA Analysis of Variation, Ted Hessing, Six Sigma Study Guide, link[2] Scheduling of Luxury Goods Final Assembly Lines with Python, Samir Saci, link | [
{
"code": null,
"e": 133,
"s": 46,
"text": "Lean Six Sigma (LSS) is a method based on a stepwise approach to process improvements."
},
{
"code": null,
"e": 280,
"s": 133,
"text": "This approach usually follows 5 steps (Define, Measure, Analyze, Improve and Control) for improving existing process problems with unknown causes."
},
{
"code": null,
"e": 503,
"s": 280,
"text": "In this article, we will explore how Python can replace Minitab (Software widely used by LSS experts) in the Analysis step to test hypotheses and understand what could improve the performance metrics of a specific process."
},
{
"code": null,
"e": 938,
"s": 503,
"text": "SUMMARYI. Problem StatementCan we improve the operators' productivity by giving them a training designed by R&D team?II. Data Analysis1. Exploratory Data AnalysisAnalysis with Python sample data from experiment with few operators 2. Analysis of Variance (ANOVA)Verify the hypothesis that training impacts productivityANOVA assumptions are not verified3. Kruskal-Wallis testConfirm that the hypothesis can be generalizedIII. Conclusion"
},
{
"code": null,
"e": 1083,
"s": 938,
"text": "You are the Continous Improvement Manager of a Distribution Center (DC) for an iconic Luxury Maison focusing on Fashion, Fragrances and Watches."
},
{
"code": null,
"e": 1203,
"s": 1083,
"text": "The warehouse receives garments that require final assembling and value-added service (VAS) during the inbound process."
},
{
"code": null,
"e": 1312,
"s": 1203,
"text": "For each dress received your operators need to print a label in the local language and perform label sewing."
},
{
"code": null,
"e": 1545,
"s": 1312,
"text": "In this article, we will focus on the improvement of label sewing productivity. Labels are distributed to the operators by batches of 30 labels. The productivity is calculated based on the time (in seconds) needed to finish a batch."
},
{
"code": null,
"e": 1633,
"s": 1545,
"text": "Edit: You can find a Youtube version of this article with animations in the link below."
},
{
"code": null,
"e": 1768,
"s": 1633,
"text": "With the support of the R&D team, you designed training for the VAS operators to improve their productivity and reduce quality issues."
},
{
"code": null,
"e": 1851,
"s": 1768,
"text": "QuestionDoes the training have a positive impact on the productivity of operators?"
},
{
"code": null,
"e": 1934,
"s": 1851,
"text": "HypothesisThe training has a positive impact on the productivity of VAS operators."
},
{
"code": null,
"e": 2083,
"s": 1934,
"text": "ExperimentRandomly select operators and measure the time per batch (Time to finish a batch of 30 labels in seconds) to build a sample of 56 records."
},
{
"code": null,
"e": 2186,
"s": 2083,
"text": "You can find the full code in this Github repository: LinkMy portfolio with other projects: Samir Saci"
},
{
"code": null,
"e": 2298,
"s": 2186,
"text": "You can download the results of this experiment in this CSV file to run the whole code on your computer (here)."
},
{
"code": null,
"e": 2386,
"s": 2298,
"text": "56 records35 records of operators without training21 records of operators with training"
},
{
"code": null,
"e": 2395,
"s": 2386,
"text": "Box Plot"
},
{
"code": null,
"e": 2526,
"s": 2395,
"text": "Based on the sample data, we can see that the median and the mean of the is considerably lower for the operators who had training."
},
{
"code": null,
"e": 2585,
"s": 2526,
"text": "HypothesisThe training reduces the average time per batch."
},
{
"code": null,
"e": 2590,
"s": 2585,
"text": "Code"
},
{
"code": null,
"e": 2647,
"s": 2590,
"text": "MinitabMenu Graph > Box Plot > Simple > 1 Y with Groups "
},
{
"code": null,
"e": 2763,
"s": 2647,
"text": "In this scenario, we want to check if the training (Variable X) is impacting the total time per batch (Variable Y)."
},
{
"code": null,
"e": 2872,
"s": 2763,
"text": "Because X is a categorical variable (Training = Yes/No) and Y is numerical, the appropriate method is ANOVA."
},
{
"code": null,
"e": 3011,
"s": 2872,
"text": "ANOVA is a statistical method used to check if we can generalize the difference of means seen in the sample data to the entire population."
},
{
"code": null,
"e": 3041,
"s": 3011,
"text": "Step 1: Calculate the p-value"
},
{
"code": null,
"e": 3153,
"s": 3041,
"text": "Source: Trainingddof: 11ddof: 245.267F: 17.1066p-unc: 0.000151308p: 20.173692p-value is below 5%"
},
{
"code": null,
"e": 3158,
"s": 3153,
"text": "Code"
},
{
"code": null,
"e": 3195,
"s": 3158,
"text": "MinitabMenu Stats > ANOVA > One-Way "
},
{
"code": null,
"e": 3237,
"s": 3195,
"text": "Step 2: Validate the assumptions of ANOVA"
},
{
"code": null,
"e": 3338,
"s": 3237,
"text": "Based on the p-value, we know that the difference of mean is real and not due to random fluctuation."
},
{
"code": null,
"e": 3436,
"s": 3338,
"text": "However, before jumping to a conclusion we need to check that the ANOVA assumptions are satisfied"
},
{
"code": null,
"e": 3472,
"s": 3436,
"text": "Residuals are naturally distributed"
},
{
"code": null,
"e": 3483,
"s": 3472,
"text": "Answer: No"
},
{
"code": null,
"e": 3523,
"s": 3483,
"text": "There are no outliers or irregularities"
},
{
"code": null,
"e": 3534,
"s": 3523,
"text": "Answer: No"
},
{
"code": null,
"e": 3669,
"s": 3534,
"text": "ConclusionANOVA requirements are not met, we need another method to confirm that the training actually impacts operators productivity."
},
{
"code": null,
"e": 3674,
"s": 3669,
"text": "Code"
},
{
"code": null,
"e": 3733,
"s": 3674,
"text": "MinitabMenu Stats > ANOVA > One-Way > Graphs > Four in one"
},
{
"code": null,
"e": 3885,
"s": 3733,
"text": "If your sample data fails to meet ANOVA requirements, you can use Kruskal-Wallis Test to check if the difference of means is due to random fluctuation."
},
{
"code": null,
"e": 3940,
"s": 3885,
"text": "statistic = 54.99pvalue = 1.205e-13p-value is below 5%"
},
{
"code": null,
"e": 4049,
"s": 3940,
"text": "ConclusionThe p-value is below 5% so we can conclude that the difference of means is statically significant."
},
{
"code": null,
"e": 4142,
"s": 4049,
"text": "We can confirm that the training has a positive impact on the productivity of the operators."
},
{
"code": null,
"e": 4147,
"s": 4142,
"text": "Code"
},
{
"code": null,
"e": 4222,
"s": 4147,
"text": "MinitabMenu Stats > Non-parametric > Kruskal Wallis > Graphs > Four in one"
},
{
"code": null,
"e": 4352,
"s": 4222,
"text": "If you are interested in other applications of Lean Six Sigma Methodology using Python you can have a look at the articles below:"
},
{
"code": null,
"e": 4370,
"s": 4352,
"text": "www.samirsaci.com"
},
{
"code": null,
"e": 4388,
"s": 4370,
"text": "www.samirsaci.com"
},
{
"code": null,
"e": 4500,
"s": 4388,
"text": "This data-driven approach gave you enough elements to convince your management to invest in workforce training."
},
{
"code": null,
"e": 4630,
"s": 4500,
"text": "You brought enough insights with a moderate effort of experimentation by generalising patterns from sample data using statistics."
},
{
"code": null,
"e": 4784,
"s": 4630,
"text": "Please feel free to contact me, I am willing to share and exchange on topics related to Data Science and Supply Chain.My Portfolio: https://samirsaci.com"
}
]
|
Differentiate between int main and int main(void) function in C | int main represents that the function returns some integer even ‘0’ at the end of the program execution. ‘0’ represents the successful execution of a program.
The syntax of int main is as follows −
int main(){
---
---
return 0;
}
int main(void) represents that the function takes NO argument. Suppose, if we don’t keep void in the bracket, the function will take any number of arguments.
The syntax of int main(void) is as follows −
int main(void){
---
---
return 0;
}
Actually, both seem to be the same but, int main(void) is technically better as it clearly mentions that main can only be called without any parameter.
Generally, in C language, if a function signature does not specify any argument, that is the function can be called with any number of parameters or without any parameters.
Let’s take the same logic to implement the code for both functions. The only difference is the syntax for these functions.
Given below is the C program for int main() function without arguments −
Live Demo
#include <stdio.h>
int main(){
static int a = 10;
if (a--){
printf("after decrement a =%d\n", a);
main(10);
}
return 0;
}
When the above program is executed, it produces the following result −
after decrement a =9
after decrement a =8
after decrement a =7
after decrement a =6
after decrement a =5
after decrement a =4
after decrement a =3
after decrement a =2
after decrement a =1
after decrement a =0
Given below is the same program but with int main(void) function −
#include <stdio.h>
int main(){
static int a = 10;
if (a--){
printf("after decrement a =%d\n", a);
main(10);
}
return 0;
}
When the above program is executed, it produces the following result −
error
If we write the same code for int main() and int main(void) we will get an error. This happens because void indicates that the function takes no parameters.
So, try to remove argument 10 in main in the above example and compile. Hence, after rectification the above code will be as follows −
Live Demo
#include <stdio.h>
int main(){
static int a = 10;
if (a--){
printf("after decrement a =%d\n", a);
main();
}
return 0;
}
When the above program is executed, it produces the following result −
after decrement a =9
after decrement a =8
after decrement a =7
after decrement a =6
after decrement a =5
after decrement a =4
after decrement a =3
after decrement a =2
after decrement a =1
after decrement a =0 | [
{
"code": null,
"e": 1221,
"s": 1062,
"text": "int main represents that the function returns some integer even ‘0’ at the end of the program execution. ‘0’ represents the successful execution of a program."
},
{
"code": null,
"e": 1260,
"s": 1221,
"text": "The syntax of int main is as follows −"
},
{
"code": null,
"e": 1301,
"s": 1260,
"text": "int main(){\n ---\n ---\n return 0;\n}"
},
{
"code": null,
"e": 1459,
"s": 1301,
"text": "int main(void) represents that the function takes NO argument. Suppose, if we don’t keep void in the bracket, the function will take any number of arguments."
},
{
"code": null,
"e": 1504,
"s": 1459,
"text": "The syntax of int main(void) is as follows −"
},
{
"code": null,
"e": 1549,
"s": 1504,
"text": "int main(void){\n ---\n ---\n return 0;\n}"
},
{
"code": null,
"e": 1701,
"s": 1549,
"text": "Actually, both seem to be the same but, int main(void) is technically better as it clearly mentions that main can only be called without any parameter."
},
{
"code": null,
"e": 1874,
"s": 1701,
"text": "Generally, in C language, if a function signature does not specify any argument, that is the function can be called with any number of parameters or without any parameters."
},
{
"code": null,
"e": 1997,
"s": 1874,
"text": "Let’s take the same logic to implement the code for both functions. The only difference is the syntax for these functions."
},
{
"code": null,
"e": 2070,
"s": 1997,
"text": "Given below is the C program for int main() function without arguments −"
},
{
"code": null,
"e": 2081,
"s": 2070,
"text": " Live Demo"
},
{
"code": null,
"e": 2227,
"s": 2081,
"text": "#include <stdio.h>\nint main(){\n static int a = 10;\n if (a--){\n printf(\"after decrement a =%d\\n\", a);\n main(10);\n }\n return 0;\n}"
},
{
"code": null,
"e": 2298,
"s": 2227,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 2508,
"s": 2298,
"text": "after decrement a =9\nafter decrement a =8\nafter decrement a =7\nafter decrement a =6\nafter decrement a =5\nafter decrement a =4\nafter decrement a =3\nafter decrement a =2\nafter decrement a =1\nafter decrement a =0"
},
{
"code": null,
"e": 2575,
"s": 2508,
"text": "Given below is the same program but with int main(void) function −"
},
{
"code": null,
"e": 2721,
"s": 2575,
"text": "#include <stdio.h>\nint main(){\n static int a = 10;\n if (a--){\n printf(\"after decrement a =%d\\n\", a);\n main(10);\n }\n return 0;\n}"
},
{
"code": null,
"e": 2792,
"s": 2721,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 2798,
"s": 2792,
"text": "error"
},
{
"code": null,
"e": 2955,
"s": 2798,
"text": "If we write the same code for int main() and int main(void) we will get an error. This happens because void indicates that the function takes no parameters."
},
{
"code": null,
"e": 3090,
"s": 2955,
"text": "So, try to remove argument 10 in main in the above example and compile. Hence, after rectification the above code will be as follows −"
},
{
"code": null,
"e": 3101,
"s": 3090,
"text": " Live Demo"
},
{
"code": null,
"e": 3245,
"s": 3101,
"text": "#include <stdio.h>\nint main(){\n static int a = 10;\n if (a--){\n printf(\"after decrement a =%d\\n\", a);\n main();\n }\n return 0;\n}"
},
{
"code": null,
"e": 3316,
"s": 3245,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 3526,
"s": 3316,
"text": "after decrement a =9\nafter decrement a =8\nafter decrement a =7\nafter decrement a =6\nafter decrement a =5\nafter decrement a =4\nafter decrement a =3\nafter decrement a =2\nafter decrement a =1\nafter decrement a =0"
}
]
|
AWS Quicksight - Using Data Sources | AWS Quicksight accepts data from various sources. Once you click on “New Dataset” on the home page, it gives you options of all the data sources that can be used.
Below are the sources containing the list of all internal and external sources −
Let us go through connecting Quicksight with some of the most commonly used data sources −
It allows you to input .csv, .tsv, .clf,.elf.xlsx and Json format files only. Once you select the file, Quicksight automatically recognizes the file and displays the data. When you click on Upload a File button, you need to provide the location of file which you want to use to create dataset.
The screen will appear as below. Under Data source name, you can enter the name to be displayed for the data set that would be created. Also you would require either uploading a manifest file from your local system or providing the S3 location of the manifest file.
Manifest file is a json format file, which specifies the url/location of input files and their format. You can enter more than one input files, provided the format is same. Here is an example of a manifest file. The “URI” parameter used to pass the location of input file is S3.
{
"fileLocations": [
{
"URIs": [
"url of first file",
"url of second file",
"url of 3rd file and so on"
]
},
],
}
"globalUploadSettings": {
"format": "CSV",
"delimiter": ",",
"textqualifier": "'",
"containsHeader": "true"
}
The parameters passed in globalUploadSettings are the default ones. You can change these parameters as per your requirements.
You need to enter the database information in the fields to connect to your database. Once it is connected to your database, you can import the data from it.
Following information is required when you connect to any RDBMS database −
DSN name
Type of connection
Database server name
Port
Database name
User name
Password
Following RDBMS based data sources are supported in Quicksight −
Amazon Athena
Amazon Aurora
Amazon Redshift
Amazon Redshift Spectrum
Amazon S3
Amazon S3 Analytics
Apache Spark 2.0 or later
MariaDB 10.0 or later
Microsoft SQL Server 2012 or later
MySQL 5.1 or later
PostgreSQL 9.3.1 or later
Presto 0.167 or later
Snowflake
Teradata 14.0 or later
Athena is the AWS tool to run queries on tables. You can choose any table from Athena or
run a custom query on those tables and use the output of those queries in Quicksight. There are couple of steps to choose data source
When you choose Athena, below screen appears. You can input any data source name which you want to give to your data source in Quicksight. Click on “Validate Connection”. Once the connection is validated, click on the “Create new source” button
Now choose the table name from the dropdown. The dropdown will show the databases present in Athena which will further show tables in that database. Else you can click on “Use custom SQL” to run query on Athena tables.
Once done, you can click on “Edit/Preview data” or “Visualize” to either edit your data or directly visualize the data as per your requirement.
When you delete a data source which is in use in any of the Quicksight dashboards, it can make associated data set unusable. It usually happens when you query a SQL based data source.
When you create a dataset based on S3, Sales force or SPICE, it does not affect your ability to use any dataset as data is stored in SPICE; however refresh option is not available in this case.
To delete a data source, select the data source. Navigate to From Existing Data Source tab on creating a dataset page.
Before deletion, you can also confirm estimated table size and other details of data source.
35 Lectures
7.5 hours
Mr. Pradeep Kshetrapal
30 Lectures
3.5 hours
Priyanka Choudhary
44 Lectures
7.5 hours
Eduonix Learning Solutions
51 Lectures
6 hours
Manuj Aggarwal
41 Lectures
5 hours
AR Shankar
14 Lectures
1 hours
Zach Miller
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2394,
"s": 2231,
"text": "AWS Quicksight accepts data from various sources. Once you click on “New Dataset” on the home page, it gives you options of all the data sources that can be used."
},
{
"code": null,
"e": 2475,
"s": 2394,
"text": "Below are the sources containing the list of all internal and external sources −"
},
{
"code": null,
"e": 2566,
"s": 2475,
"text": "Let us go through connecting Quicksight with some of the most commonly used data sources −"
},
{
"code": null,
"e": 2860,
"s": 2566,
"text": "It allows you to input .csv, .tsv, .clf,.elf.xlsx and Json format files only. Once you select the file, Quicksight automatically recognizes the file and displays the data. When you click on Upload a File button, you need to provide the location of file which you want to use to create dataset."
},
{
"code": null,
"e": 3126,
"s": 2860,
"text": "The screen will appear as below. Under Data source name, you can enter the name to be displayed for the data set that would be created. Also you would require either uploading a manifest file from your local system or providing the S3 location of the manifest file."
},
{
"code": null,
"e": 3405,
"s": 3126,
"text": "Manifest file is a json format file, which specifies the url/location of input files and their format. You can enter more than one input files, provided the format is same. Here is an example of a manifest file. The “URI” parameter used to pass the location of input file is S3."
},
{
"code": null,
"e": 3717,
"s": 3405,
"text": "{\n \"fileLocations\": [\n {\n \"URIs\": [\n \"url of first file\",\n \"url of second file\",\n \"url of 3rd file and so on\"\n ]\n },\n \n ],\n}\n\"globalUploadSettings\": {\n \"format\": \"CSV\",\n \"delimiter\": \",\",\n \"textqualifier\": \"'\",\n \"containsHeader\": \"true\"\n}"
},
{
"code": null,
"e": 3843,
"s": 3717,
"text": "The parameters passed in globalUploadSettings are the default ones. You can change these parameters as per your requirements."
},
{
"code": null,
"e": 4001,
"s": 3843,
"text": "You need to enter the database information in the fields to connect to your database. Once it is connected to your database, you can import the data from it."
},
{
"code": null,
"e": 4076,
"s": 4001,
"text": "Following information is required when you connect to any RDBMS database −"
},
{
"code": null,
"e": 4085,
"s": 4076,
"text": "DSN name"
},
{
"code": null,
"e": 4104,
"s": 4085,
"text": "Type of connection"
},
{
"code": null,
"e": 4125,
"s": 4104,
"text": "Database server name"
},
{
"code": null,
"e": 4130,
"s": 4125,
"text": "Port"
},
{
"code": null,
"e": 4144,
"s": 4130,
"text": "Database name"
},
{
"code": null,
"e": 4154,
"s": 4144,
"text": "User name"
},
{
"code": null,
"e": 4163,
"s": 4154,
"text": "Password"
},
{
"code": null,
"e": 4228,
"s": 4163,
"text": "Following RDBMS based data sources are supported in Quicksight −"
},
{
"code": null,
"e": 4242,
"s": 4228,
"text": "Amazon Athena"
},
{
"code": null,
"e": 4256,
"s": 4242,
"text": "Amazon Aurora"
},
{
"code": null,
"e": 4272,
"s": 4256,
"text": "Amazon Redshift"
},
{
"code": null,
"e": 4297,
"s": 4272,
"text": "Amazon Redshift Spectrum"
},
{
"code": null,
"e": 4307,
"s": 4297,
"text": "Amazon S3"
},
{
"code": null,
"e": 4327,
"s": 4307,
"text": "Amazon S3 Analytics"
},
{
"code": null,
"e": 4353,
"s": 4327,
"text": "Apache Spark 2.0 or later"
},
{
"code": null,
"e": 4375,
"s": 4353,
"text": "MariaDB 10.0 or later"
},
{
"code": null,
"e": 4410,
"s": 4375,
"text": "Microsoft SQL Server 2012 or later"
},
{
"code": null,
"e": 4429,
"s": 4410,
"text": "MySQL 5.1 or later"
},
{
"code": null,
"e": 4455,
"s": 4429,
"text": "PostgreSQL 9.3.1 or later"
},
{
"code": null,
"e": 4477,
"s": 4455,
"text": "Presto 0.167 or later"
},
{
"code": null,
"e": 4487,
"s": 4477,
"text": "Snowflake"
},
{
"code": null,
"e": 4510,
"s": 4487,
"text": "Teradata 14.0 or later"
},
{
"code": null,
"e": 4733,
"s": 4510,
"text": "Athena is the AWS tool to run queries on tables. You can choose any table from Athena or\nrun a custom query on those tables and use the output of those queries in Quicksight. There are couple of steps to choose data source"
},
{
"code": null,
"e": 4978,
"s": 4733,
"text": "When you choose Athena, below screen appears. You can input any data source name which you want to give to your data source in Quicksight. Click on “Validate Connection”. Once the connection is validated, click on the “Create new source” button"
},
{
"code": null,
"e": 5197,
"s": 4978,
"text": "Now choose the table name from the dropdown. The dropdown will show the databases present in Athena which will further show tables in that database. Else you can click on “Use custom SQL” to run query on Athena tables."
},
{
"code": null,
"e": 5341,
"s": 5197,
"text": "Once done, you can click on “Edit/Preview data” or “Visualize” to either edit your data or directly visualize the data as per your requirement."
},
{
"code": null,
"e": 5525,
"s": 5341,
"text": "When you delete a data source which is in use in any of the Quicksight dashboards, it can make associated data set unusable. It usually happens when you query a SQL based data source."
},
{
"code": null,
"e": 5719,
"s": 5525,
"text": "When you create a dataset based on S3, Sales force or SPICE, it does not affect your ability to use any dataset as data is stored in SPICE; however refresh option is not available in this case."
},
{
"code": null,
"e": 5838,
"s": 5719,
"text": "To delete a data source, select the data source. Navigate to From Existing Data Source tab on creating a dataset page."
},
{
"code": null,
"e": 5931,
"s": 5838,
"text": "Before deletion, you can also confirm estimated table size and other details of data source."
},
{
"code": null,
"e": 5966,
"s": 5931,
"text": "\n 35 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 5990,
"s": 5966,
"text": " Mr. Pradeep Kshetrapal"
},
{
"code": null,
"e": 6025,
"s": 5990,
"text": "\n 30 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 6045,
"s": 6025,
"text": " Priyanka Choudhary"
},
{
"code": null,
"e": 6080,
"s": 6045,
"text": "\n 44 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 6108,
"s": 6080,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 6141,
"s": 6108,
"text": "\n 51 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 6157,
"s": 6141,
"text": " Manuj Aggarwal"
},
{
"code": null,
"e": 6190,
"s": 6157,
"text": "\n 41 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 6202,
"s": 6190,
"text": " AR Shankar"
},
{
"code": null,
"e": 6235,
"s": 6202,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6248,
"s": 6235,
"text": " Zach Miller"
},
{
"code": null,
"e": 6255,
"s": 6248,
"text": " Print"
},
{
"code": null,
"e": 6266,
"s": 6255,
"text": " Add Notes"
}
]
|
Features of C++ - GeeksforGeeks | 09 Jul, 2021
C++ is a general-purpose programming language that was developed as an enhancement of the C language to include object-oriented paradigm. It is an imperative and a compiled language.
C++ is an Object-Oriented Programming Language, unlike C which is a procedural programming language. This is the most important feature of C++. It can create/destroy objects while programming. Also, It can create blueprints with which objects can be created. We have discussed the Object-Orient Programming Concepts in C++ in this article.
Concepts of Object-oriented programming Language:
Class
Objects
Encapsulation
Polymorphism
Inheritance
Abstraction
A C++ executable is not platform-independent (compiled programs on Linux won’t run on Windows), however they are machine independent.
Let us understand this feature of C++ with the help of an example. Suppose you have written a piece of code which can run on Linux/Windows/Mac OSx which makes C++ Machine Independent but the executable file of the C++ cannot run on different operating systems.
It is a simple language in the sense that programs can be broken down into logical units and parts, has rich library support, and a variety of data-types. Also, the Auto Keyword of the C++ makes life easier.
The auto keyword
The idea of the auto was to form the C++ compiler deduce the data type while compiling instead of making you declare the data type every-freaking-time. Do keep in mind that you cannot declare something without an initializer. There must be some way for the compiler to deduce your type.
C++
// C++ program for using auto keyword #include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Variables auto an_int = 26; auto a_bool = false; auto a_float = 26.24; auto ptr = &a_float; // Print typeid cout << typeid(a_bool).name() << "\n"; cout << typeid(an_int).name() << "\n"; return 0;}
b
i
C++ is a High-Level Language, unlike C which is a Mid-Level Programming Language. It makes life easier to work in C++ as it is a high-level language as it is closely associated with the human-comprehensible English language.
C++ can be the base language for many other programming languages that supports the feature of object-oriented programming. Bjarne Stroustrup found Simula 67, the first object-oriented language ever, lacking simulations and decided to develop C++.
It is clear that the C++ is a case-sensitive programming language. For example, cin is used to take input from the input stream. But if the “Cin” won’t work. Other languages like HTML and MySQL are not case-sensitive language.
C++ is a compiler-based language, unlike Python. That is C++ programs used to be compiled and their executable file is used to run it. Due to which C++ is a relatively faster language than Java and Python.
When the program executes in the C++ then the variables are allocated the dynamical heap space. Inside of the functions the variables are allocated in the stack space. Many times, We are not aware in advance that how much memory is needed to store particular information in a defined variable and the size of required memory can be determined at run time.
C++ allows us to allocate the memory of a variable or an array in run time. This is known as Dynamic Memory Allocation.
In other programming languages such as Java and Python, the compiler automatically manages the memories allocated to variables. But this is not the case in C++.
In C++, the memory must be de-allocate dynamically allocated memory manually after it is of no use.
The allocation and deallocation of the memory can be done using the new and delete operators respectively.
Below is the program to illustrate the Memory Management in C++:
C++
// C++ implementation to illustrate// the Memory Management #include <cstring>#include <iostream>using namespace std; // Driver Codeint main(){ int num = 5; float* ptr; // Memory allocation of // num number of floats ptr = new float[num]; for (int i = 0; i < num; ++i) { *(ptr + i) = i; } cout << "Display the GPA of students:" << endl; for (int i = 0; i < num; ++i) { cout << "Student" << i + 1 << ": " << *(ptr + i) << endl; } // Ptr memory is released delete[] ptr; return 0;}
Display the GPA of students:
Student1: 0
Student2: 1
Student3: 2
Student4: 3
Student5: 4
Multithreading is a specialized form of multitasking and multitasking is a feature that allows your system to execute two or more programs concurrently. In general, there are two sorts of multitasking: process-based and thread-based.
Process-based multitasking handles the concurrent execution of programs. Thread-based multitasking deals with the multiprogramming of pieces of an equivalent program.
A multithreaded program contains two or more parts that will run concurrently. Each a part of such a program is named a thread, and every thread defines a separate path of execution.
C++ doesn’t contain any built-in support for multithreaded applications. Instead, it relies entirely upon the OS to supply this feature.
Below is the program to illustrate Multithreading in C++:
C++
// C++ implementation to illustrate// the working of Multi-threading #include <cstdlib>#include <iostream>#include <pthread.h> using namespace std; #define NUM_THREADS 5 // Function to print Hello with// the thread idvoid* PrintHello(void* threadid){ // Thread ID long tid; tid = (long)threadid; // Print the thread ID cout << "Hello World! Thread ID, " << tid << endl; pthread_exit(NULL);} // Driver Codeint main(){ // Create thread pthread_t threads[NUM_THREADS]; int rc; int i; for (i = 0; i < NUM_THREADS; i++) { cout << "main() : creating thread, " << i << endl; rc = pthread_create(&threads[i], NULL, PrintHello, (void*)&i); // If thread is not created if (rc) { cout << "Error:unable to" << " create thread, " << rc << endl; exit(-1); } } pthread_exit(NULL);}
Output:
This tutorial assumes that you are working on Linux OS and we are going to write a multi-threaded C++ program using POSIX. POSIX Threads or Pthreads provides API which is available on many Unix-like POSIX systems such as FreeBSD, NetBSD, GNU/Linux, Mac OS X, and Solaris.
sagartomar9927
C++
Programming Language
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Sorting a vector in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
Arrow operator -> in C/C++ with Examples
Modulo Operator (%) in C/C++ with Examples
Structures in C++
Differences between Procedural and Object Oriented Programming
Top 10 Programming Languages to Learn in 2022 | [
{
"code": null,
"e": 24098,
"s": 24070,
"text": "\n09 Jul, 2021"
},
{
"code": null,
"e": 24282,
"s": 24098,
"text": "C++ is a general-purpose programming language that was developed as an enhancement of the C language to include object-oriented paradigm. It is an imperative and a compiled language. "
},
{
"code": null,
"e": 24622,
"s": 24282,
"text": "C++ is an Object-Oriented Programming Language, unlike C which is a procedural programming language. This is the most important feature of C++. It can create/destroy objects while programming. Also, It can create blueprints with which objects can be created. We have discussed the Object-Orient Programming Concepts in C++ in this article."
},
{
"code": null,
"e": 24672,
"s": 24622,
"text": "Concepts of Object-oriented programming Language:"
},
{
"code": null,
"e": 24678,
"s": 24672,
"text": "Class"
},
{
"code": null,
"e": 24686,
"s": 24678,
"text": "Objects"
},
{
"code": null,
"e": 24700,
"s": 24686,
"text": "Encapsulation"
},
{
"code": null,
"e": 24713,
"s": 24700,
"text": "Polymorphism"
},
{
"code": null,
"e": 24725,
"s": 24713,
"text": "Inheritance"
},
{
"code": null,
"e": 24737,
"s": 24725,
"text": "Abstraction"
},
{
"code": null,
"e": 24871,
"s": 24737,
"text": "A C++ executable is not platform-independent (compiled programs on Linux won’t run on Windows), however they are machine independent."
},
{
"code": null,
"e": 25132,
"s": 24871,
"text": "Let us understand this feature of C++ with the help of an example. Suppose you have written a piece of code which can run on Linux/Windows/Mac OSx which makes C++ Machine Independent but the executable file of the C++ cannot run on different operating systems."
},
{
"code": null,
"e": 25340,
"s": 25132,
"text": "It is a simple language in the sense that programs can be broken down into logical units and parts, has rich library support, and a variety of data-types. Also, the Auto Keyword of the C++ makes life easier."
},
{
"code": null,
"e": 25357,
"s": 25340,
"text": "The auto keyword"
},
{
"code": null,
"e": 25644,
"s": 25357,
"text": "The idea of the auto was to form the C++ compiler deduce the data type while compiling instead of making you declare the data type every-freaking-time. Do keep in mind that you cannot declare something without an initializer. There must be some way for the compiler to deduce your type."
},
{
"code": null,
"e": 25648,
"s": 25644,
"text": "C++"
},
{
"code": "// C++ program for using auto keyword #include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Variables auto an_int = 26; auto a_bool = false; auto a_float = 26.24; auto ptr = &a_float; // Print typeid cout << typeid(a_bool).name() << \"\\n\"; cout << typeid(an_int).name() << \"\\n\"; return 0;}",
"e": 25986,
"s": 25648,
"text": null
},
{
"code": null,
"e": 25990,
"s": 25986,
"text": "b\ni"
},
{
"code": null,
"e": 26217,
"s": 25992,
"text": "C++ is a High-Level Language, unlike C which is a Mid-Level Programming Language. It makes life easier to work in C++ as it is a high-level language as it is closely associated with the human-comprehensible English language."
},
{
"code": null,
"e": 26465,
"s": 26217,
"text": "C++ can be the base language for many other programming languages that supports the feature of object-oriented programming. Bjarne Stroustrup found Simula 67, the first object-oriented language ever, lacking simulations and decided to develop C++."
},
{
"code": null,
"e": 26692,
"s": 26465,
"text": "It is clear that the C++ is a case-sensitive programming language. For example, cin is used to take input from the input stream. But if the “Cin” won’t work. Other languages like HTML and MySQL are not case-sensitive language."
},
{
"code": null,
"e": 26898,
"s": 26692,
"text": "C++ is a compiler-based language, unlike Python. That is C++ programs used to be compiled and their executable file is used to run it. Due to which C++ is a relatively faster language than Java and Python."
},
{
"code": null,
"e": 27254,
"s": 26898,
"text": "When the program executes in the C++ then the variables are allocated the dynamical heap space. Inside of the functions the variables are allocated in the stack space. Many times, We are not aware in advance that how much memory is needed to store particular information in a defined variable and the size of required memory can be determined at run time."
},
{
"code": null,
"e": 27374,
"s": 27254,
"text": "C++ allows us to allocate the memory of a variable or an array in run time. This is known as Dynamic Memory Allocation."
},
{
"code": null,
"e": 27535,
"s": 27374,
"text": "In other programming languages such as Java and Python, the compiler automatically manages the memories allocated to variables. But this is not the case in C++."
},
{
"code": null,
"e": 27635,
"s": 27535,
"text": "In C++, the memory must be de-allocate dynamically allocated memory manually after it is of no use."
},
{
"code": null,
"e": 27742,
"s": 27635,
"text": "The allocation and deallocation of the memory can be done using the new and delete operators respectively."
},
{
"code": null,
"e": 27807,
"s": 27742,
"text": "Below is the program to illustrate the Memory Management in C++:"
},
{
"code": null,
"e": 27811,
"s": 27807,
"text": "C++"
},
{
"code": "// C++ implementation to illustrate// the Memory Management #include <cstring>#include <iostream>using namespace std; // Driver Codeint main(){ int num = 5; float* ptr; // Memory allocation of // num number of floats ptr = new float[num]; for (int i = 0; i < num; ++i) { *(ptr + i) = i; } cout << \"Display the GPA of students:\" << endl; for (int i = 0; i < num; ++i) { cout << \"Student\" << i + 1 << \": \" << *(ptr + i) << endl; } // Ptr memory is released delete[] ptr; return 0;}",
"e": 28382,
"s": 27811,
"text": null
},
{
"code": null,
"e": 28471,
"s": 28382,
"text": "Display the GPA of students:\nStudent1: 0\nStudent2: 1\nStudent3: 2\nStudent4: 3\nStudent5: 4"
},
{
"code": null,
"e": 28707,
"s": 28473,
"text": "Multithreading is a specialized form of multitasking and multitasking is a feature that allows your system to execute two or more programs concurrently. In general, there are two sorts of multitasking: process-based and thread-based."
},
{
"code": null,
"e": 28874,
"s": 28707,
"text": "Process-based multitasking handles the concurrent execution of programs. Thread-based multitasking deals with the multiprogramming of pieces of an equivalent program."
},
{
"code": null,
"e": 29057,
"s": 28874,
"text": "A multithreaded program contains two or more parts that will run concurrently. Each a part of such a program is named a thread, and every thread defines a separate path of execution."
},
{
"code": null,
"e": 29194,
"s": 29057,
"text": "C++ doesn’t contain any built-in support for multithreaded applications. Instead, it relies entirely upon the OS to supply this feature."
},
{
"code": null,
"e": 29252,
"s": 29194,
"text": "Below is the program to illustrate Multithreading in C++:"
},
{
"code": null,
"e": 29256,
"s": 29252,
"text": "C++"
},
{
"code": "// C++ implementation to illustrate// the working of Multi-threading #include <cstdlib>#include <iostream>#include <pthread.h> using namespace std; #define NUM_THREADS 5 // Function to print Hello with// the thread idvoid* PrintHello(void* threadid){ // Thread ID long tid; tid = (long)threadid; // Print the thread ID cout << \"Hello World! Thread ID, \" << tid << endl; pthread_exit(NULL);} // Driver Codeint main(){ // Create thread pthread_t threads[NUM_THREADS]; int rc; int i; for (i = 0; i < NUM_THREADS; i++) { cout << \"main() : creating thread, \" << i << endl; rc = pthread_create(&threads[i], NULL, PrintHello, (void*)&i); // If thread is not created if (rc) { cout << \"Error:unable to\" << \" create thread, \" << rc << endl; exit(-1); } } pthread_exit(NULL);}",
"e": 30261,
"s": 29256,
"text": null
},
{
"code": null,
"e": 30269,
"s": 30261,
"text": "Output:"
},
{
"code": null,
"e": 30542,
"s": 30269,
"text": "This tutorial assumes that you are working on Linux OS and we are going to write a multi-threaded C++ program using POSIX. POSIX Threads or Pthreads provides API which is available on many Unix-like POSIX systems such as FreeBSD, NetBSD, GNU/Linux, Mac OS X, and Solaris. "
},
{
"code": null,
"e": 30557,
"s": 30542,
"text": "sagartomar9927"
},
{
"code": null,
"e": 30561,
"s": 30557,
"text": "C++"
},
{
"code": null,
"e": 30582,
"s": 30561,
"text": "Programming Language"
},
{
"code": null,
"e": 30586,
"s": 30582,
"text": "CPP"
},
{
"code": null,
"e": 30684,
"s": 30586,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30712,
"s": 30684,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 30732,
"s": 30712,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 30756,
"s": 30732,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 30789,
"s": 30756,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 30833,
"s": 30789,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 30874,
"s": 30833,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 30917,
"s": 30874,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 30935,
"s": 30917,
"text": "Structures in C++"
},
{
"code": null,
"e": 30998,
"s": 30935,
"text": "Differences between Procedural and Object Oriented Programming"
}
]
|
How to check the existence of URL in PHP? | 15 May, 2019
Existence of an URL can be checked by checking the status code in the response header. The status code 200 is Standard response for successful HTTP requests and status code 404 means URL doesn’t exist.
Used Functions:
get_headers() Function: It fetches all the headers sent by the server in response to the HTTP request.
strpos() Function: This function is used to find the first occurrence of a string into another string.
Example 1: This example checks for the status code 200 in response header. If the status code is 200, it indicates URL exist otherwise not.
<?php // Initialize an URL to the variable$url = "https://www.geeksforgeeks.org"; // Use get_headers() function$headers = @get_headers($url); // Use condition to check the existence of URLif($headers && strpos( $headers[0], '200')) { $status = "URL Exist";}else { $status = "URL Doesn't Exist";} // Display resultecho($status); ?>
Output:
URL Exist
Example 2: This example checks for the status code 404 in response header. If the status code is 404, it indicates URL doesn’t exist otherwise URL exist.
<?php // Initialize an URL to the variable$url = "https://www.geeksforgeeks.org"; // Use get_headers() function$headers = @get_headers($url); // Use condition to check the existence of URLif($headers || strpos( $headers[0], '404')) { $status = "URL Doesn't Exist";}else { $status = "URL Exist";} // Display resultecho($status); ?>
Output:
URL Doesn't Exist
Example 3: This example uses curl_init() method to check the existence of an URL.
<?php // Initialize an URL to the variable$url = "https://www.geeksfgeeks.org"; // Use curl_init() function to initialize a cURL session$curl = curl_init($url); // Use curl_setopt() to set an option for cURL transfercurl_setopt($curl, CURLOPT_NOBODY, true); // Use curl_exec() to perform cURL session$result = curl_exec($curl); if ($result !== false) { // Use curl_getinfo() to get information // regarding a specific transfer $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE); if ($statusCode == 404) { echo "URL Doesn't Exist"; } else { echo "URL Exist"; }}else { echo "URL Doesn't Exist";} ?>
Output:
URL Doesn't Exist
Picked
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 May, 2019"
},
{
"code": null,
"e": 230,
"s": 28,
"text": "Existence of an URL can be checked by checking the status code in the response header. The status code 200 is Standard response for successful HTTP requests and status code 404 means URL doesn’t exist."
},
{
"code": null,
"e": 246,
"s": 230,
"text": "Used Functions:"
},
{
"code": null,
"e": 349,
"s": 246,
"text": "get_headers() Function: It fetches all the headers sent by the server in response to the HTTP request."
},
{
"code": null,
"e": 452,
"s": 349,
"text": "strpos() Function: This function is used to find the first occurrence of a string into another string."
},
{
"code": null,
"e": 592,
"s": 452,
"text": "Example 1: This example checks for the status code 200 in response header. If the status code is 200, it indicates URL exist otherwise not."
},
{
"code": "<?php // Initialize an URL to the variable$url = \"https://www.geeksforgeeks.org\"; // Use get_headers() function$headers = @get_headers($url); // Use condition to check the existence of URLif($headers && strpos( $headers[0], '200')) { $status = \"URL Exist\";}else { $status = \"URL Doesn't Exist\";} // Display resultecho($status); ?>",
"e": 934,
"s": 592,
"text": null
},
{
"code": null,
"e": 942,
"s": 934,
"text": "Output:"
},
{
"code": null,
"e": 953,
"s": 942,
"text": "URL Exist\n"
},
{
"code": null,
"e": 1107,
"s": 953,
"text": "Example 2: This example checks for the status code 404 in response header. If the status code is 404, it indicates URL doesn’t exist otherwise URL exist."
},
{
"code": "<?php // Initialize an URL to the variable$url = \"https://www.geeksforgeeks.org\"; // Use get_headers() function$headers = @get_headers($url); // Use condition to check the existence of URLif($headers || strpos( $headers[0], '404')) { $status = \"URL Doesn't Exist\";}else { $status = \"URL Exist\";} // Display resultecho($status); ?>",
"e": 1449,
"s": 1107,
"text": null
},
{
"code": null,
"e": 1457,
"s": 1449,
"text": "Output:"
},
{
"code": null,
"e": 1476,
"s": 1457,
"text": "URL Doesn't Exist\n"
},
{
"code": null,
"e": 1558,
"s": 1476,
"text": "Example 3: This example uses curl_init() method to check the existence of an URL."
},
{
"code": "<?php // Initialize an URL to the variable$url = \"https://www.geeksfgeeks.org\"; // Use curl_init() function to initialize a cURL session$curl = curl_init($url); // Use curl_setopt() to set an option for cURL transfercurl_setopt($curl, CURLOPT_NOBODY, true); // Use curl_exec() to perform cURL session$result = curl_exec($curl); if ($result !== false) { // Use curl_getinfo() to get information // regarding a specific transfer $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE); if ($statusCode == 404) { echo \"URL Doesn't Exist\"; } else { echo \"URL Exist\"; }}else { echo \"URL Doesn't Exist\";} ?>",
"e": 2214,
"s": 1558,
"text": null
},
{
"code": null,
"e": 2222,
"s": 2214,
"text": "Output:"
},
{
"code": null,
"e": 2241,
"s": 2222,
"text": "URL Doesn't Exist\n"
},
{
"code": null,
"e": 2248,
"s": 2241,
"text": "Picked"
},
{
"code": null,
"e": 2252,
"s": 2248,
"text": "PHP"
},
{
"code": null,
"e": 2265,
"s": 2252,
"text": "PHP Programs"
},
{
"code": null,
"e": 2282,
"s": 2265,
"text": "Web Technologies"
},
{
"code": null,
"e": 2309,
"s": 2282,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 2313,
"s": 2309,
"text": "PHP"
}
]
|
Comparing values of data frames in R Programming – all_equal() Function | 23 Dec, 2021
all_equal() function in R Language is used to compare the values between dataframes.
Syntax: all_equal(target, current, check.attributes, check.names)
Parameters:
target: object to compare
current: object to be compared with
check.attributes: If attributes of both be compared
check.names: If names be compared
Example 1: Comparing Equal Data frames
R
# R program to illustrate# all_equal function # Create three data framesdata1 <- data.frame(x1 = 1:10, x2 = LETTERS[1:10])data2 <- data.frame(x1 = 1:10, x2 = LETTERS[1:10])data3 <- data.frame(x1 = 2:12, x2 = LETTERS[1:5]) # Compare equal data framesall_equal(data1, data2, check.attributes = FALSE)
Output:
TRUE
Here in the above code, we have compared equal data frames data1 and data2, and thus the output seems to be “TRUE”.
Example 2: Comparing Unequal dataframes
R
# R program to illustrate# all_equal function # Create three data framesdata1 <- data.frame(x1 = 1:10, x2 = LETTERS[1:10])data2 <- data.frame(x1 = 1:10, x2 = LETTERS[1:10])data3 <- data.frame(x1 = 2:12, x2 = LETTERS[1:5]) # Compare unequal data framesall_equal(data1, data3, check.names = FALSE)
Output:
Rows in x but not y: 1, 2, 3, 4, 5, 6, 8, 9, 10.
Rows in y but not x: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10.
Here in the above code, we compared the unequal data frames data1 and data3, so we got an error explaining what’s wrong in the code.
kumar_satyam
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Dec, 2021"
},
{
"code": null,
"e": 113,
"s": 28,
"text": "all_equal() function in R Language is used to compare the values between dataframes."
},
{
"code": null,
"e": 179,
"s": 113,
"text": "Syntax: all_equal(target, current, check.attributes, check.names)"
},
{
"code": null,
"e": 192,
"s": 179,
"text": "Parameters: "
},
{
"code": null,
"e": 218,
"s": 192,
"text": "target: object to compare"
},
{
"code": null,
"e": 254,
"s": 218,
"text": "current: object to be compared with"
},
{
"code": null,
"e": 306,
"s": 254,
"text": "check.attributes: If attributes of both be compared"
},
{
"code": null,
"e": 340,
"s": 306,
"text": "check.names: If names be compared"
},
{
"code": null,
"e": 379,
"s": 340,
"text": "Example 1: Comparing Equal Data frames"
},
{
"code": null,
"e": 381,
"s": 379,
"text": "R"
},
{
"code": "# R program to illustrate# all_equal function # Create three data framesdata1 <- data.frame(x1 = 1:10, x2 = LETTERS[1:10])data2 <- data.frame(x1 = 1:10, x2 = LETTERS[1:10])data3 <- data.frame(x1 = 2:12, x2 = LETTERS[1:5]) # Compare equal data framesall_equal(data1, data2, check.attributes = FALSE) ",
"e": 767,
"s": 381,
"text": null
},
{
"code": null,
"e": 776,
"s": 767,
"text": "Output: "
},
{
"code": null,
"e": 781,
"s": 776,
"text": "TRUE"
},
{
"code": null,
"e": 897,
"s": 781,
"text": "Here in the above code, we have compared equal data frames data1 and data2, and thus the output seems to be “TRUE”."
},
{
"code": null,
"e": 937,
"s": 897,
"text": "Example 2: Comparing Unequal dataframes"
},
{
"code": null,
"e": 939,
"s": 937,
"text": "R"
},
{
"code": "# R program to illustrate# all_equal function # Create three data framesdata1 <- data.frame(x1 = 1:10, x2 = LETTERS[1:10])data2 <- data.frame(x1 = 1:10, x2 = LETTERS[1:10])data3 <- data.frame(x1 = 2:12, x2 = LETTERS[1:5]) # Compare unequal data framesall_equal(data1, data3, check.names = FALSE) ",
"e": 1322,
"s": 939,
"text": null
},
{
"code": null,
"e": 1331,
"s": 1322,
"text": "Output: "
},
{
"code": null,
"e": 1434,
"s": 1331,
"text": "Rows in x but not y: 1, 2, 3, 4, 5, 6, 8, 9, 10. \nRows in y but not x: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10. "
},
{
"code": null,
"e": 1567,
"s": 1434,
"text": "Here in the above code, we compared the unequal data frames data1 and data3, so we got an error explaining what’s wrong in the code."
},
{
"code": null,
"e": 1580,
"s": 1567,
"text": "kumar_satyam"
},
{
"code": null,
"e": 1591,
"s": 1580,
"text": "R Language"
}
]
|
Deutsche Bank Interview Experience 2020 | 21 May, 2021
Round 1(Online Test):
It was a string manipulation question. Suppose input was string1, string2, and k seconds. We have to choose every i from 1 to k and shift a character from the string by i index (eg: if i=3 then ‘a’ would be shifted to ‘d’). Each i could be chosen only once. We need to check if we can convert string1 to string2. (20 marks)Input:
k=3
string1 = 'abc'
string2 = 'ddd'
Output:
YesGiven N, find two numbers with a product greater than or equal to N and with minimum sum.(50 marks)Input -15
Output-8It was a DFS question where edges representing time, we had to find the total minimum time spent in visiting all vertices, but there was a sequence given in which we can visit vertices. (50 marks)Solved by defining a comparator and then sorting the edges.I did second question of 50 marks with all test cases passed and in first question I got 12 marks out of 20.So in total, I got 62 marks out of 120.Round 2(Technical): 45 minutesTell me about yourself.Tell me your favourite data structure(Linked list for me).Difference between linked list and array.Write a program in notepad and share your screen to find if 1st linked list is contained in 2nd linked list or not, if present then print “yes” otherwise “no”.Write structure of linked list.Explain the concepts of oops in detail with real-life examples and also tell the difference between procedural programming language and object-oriented programming language.(explain oops concept from starting and explain in detail).Explain your project in detail like which technology u used and how many modules are there in ur project ,everything which is related to ur project.and also explain database of ur project, relations between tables.Explain Queue data structure, explain its working with real-life example and what is enque and deque in it.Explain dynamic programming. Write a program of Fibonacci series using dp approach.Do you have any questions(Always ask some good questions)?Round 3(Technical): 1 hourWhat is circular linked list, try to confuse by giving some conditions.Write a program to insert a element in circular linked list, but the condition is you have to insert the element after getting smaller element from the given element. (After explaining my approach he was trying to confuse me by adding some more conditions in the question, so don’t be confused listen the conditions carefully and try to modify your code according to the given conditions).Explain your first project in detail that you have mentioned in your resume, he asked everything like database of my project, relations between tables in detail, then he starts asking SQL queries (very difficult), he gave some hypothetical tables to me and asked queries on that tables, and trying to confuse me by adding several conditions on the answer of the query.Draw a flowchart of your project.In your project, as you used userid and password for login, so how you store password in database in encrypted form (write code for it).Write a SQL query for finding second highest salary,55th highest salary.Asked all three projects in detail.What in Artificial neural network, the difference between ANN and CNN, how many types of neural networks are there, from where u download dataset for ur Ml project.What is blind write,dirty read?Difference between Strict schedule and cascadeless schedule .explain by giving example.Tip: if you have any database project prepare it very well and practice the database queries.in my second round interviewer focused only on my projects,asked all the things and confused me in sql queries.Round 4(PRO-FIT): 45 minutes It was a very long day ,u tired na????(you have to answer this question very carefully, don’t take it lightly or as a normal question).Tell about ur journey from 10th till MCA, what are the difficulties and challenging situations come in your life and how you deal with it. What are the qualities in you which become your strength in your hard time and what are your weakness in this situation(don’t be fake ,be real). After listening to my journey he appreciates my efforts, my strengths, very much happy by listening my journey.Explain in detail all the words in (public static void main).what is the need for writing static in main method syntax,Is JVM not able to create object.What would happen if I write public static int main in place of public static void main.(an error would come or not?? And if an error would come then which type of error runtime error or compile-time error and also tell the error msg in detail). Do you have any questions?Round 5(HR)Tell me about yourself that you are not mentioned in your resume.Explain your project(anyone). Do you have any questions? TIPS:Always be confident when you are giving answers, the interviewer also tests your confidence by confusing you.Read carefully all the things which you have mentioned in your resume. don’t write so much extra things.THAT’S ALL ABOUT MY EXPERIENCE HOPE THIS WILL BE HELPFUL TO YOUALL THE BEST.My Personal Notes
arrow_drop_upSave
It was a string manipulation question. Suppose input was string1, string2, and k seconds. We have to choose every i from 1 to k and shift a character from the string by i index (eg: if i=3 then ‘a’ would be shifted to ‘d’). Each i could be chosen only once. We need to check if we can convert string1 to string2. (20 marks)Input:
k=3
string1 = 'abc'
string2 = 'ddd'
Output:
Yes
Input:
k=3
string1 = 'abc'
string2 = 'ddd'
Output:
Yes
Given N, find two numbers with a product greater than or equal to N and with minimum sum.(50 marks)Input -15
Output-8
Input -15
Output-8
It was a DFS question where edges representing time, we had to find the total minimum time spent in visiting all vertices, but there was a sequence given in which we can visit vertices. (50 marks)Solved by defining a comparator and then sorting the edges.
Solved by defining a comparator and then sorting the edges.
I did second question of 50 marks with all test cases passed and in first question I got 12 marks out of 20.So in total, I got 62 marks out of 120.
Round 2(Technical): 45 minutes
Tell me about yourself.Tell me your favourite data structure(Linked list for me).Difference between linked list and array.Write a program in notepad and share your screen to find if 1st linked list is contained in 2nd linked list or not, if present then print “yes” otherwise “no”.Write structure of linked list.Explain the concepts of oops in detail with real-life examples and also tell the difference between procedural programming language and object-oriented programming language.(explain oops concept from starting and explain in detail).Explain your project in detail like which technology u used and how many modules are there in ur project ,everything which is related to ur project.and also explain database of ur project, relations between tables.Explain Queue data structure, explain its working with real-life example and what is enque and deque in it.Explain dynamic programming. Write a program of Fibonacci series using dp approach.Do you have any questions(Always ask some good questions)?
Tell me about yourself.
Tell me your favourite data structure(Linked list for me).
Difference between linked list and array.
Write a program in notepad and share your screen to find if 1st linked list is contained in 2nd linked list or not, if present then print “yes” otherwise “no”.
Write structure of linked list.
Explain the concepts of oops in detail with real-life examples and also tell the difference between procedural programming language and object-oriented programming language.(explain oops concept from starting and explain in detail).
Explain your project in detail like which technology u used and how many modules are there in ur project ,everything which is related to ur project.and also explain database of ur project, relations between tables.
Explain Queue data structure, explain its working with real-life example and what is enque and deque in it.
Explain dynamic programming. Write a program of Fibonacci series using dp approach.
Do you have any questions(Always ask some good questions)?
Round 3(Technical): 1 hour
What is circular linked list, try to confuse by giving some conditions.Write a program to insert a element in circular linked list, but the condition is you have to insert the element after getting smaller element from the given element. (After explaining my approach he was trying to confuse me by adding some more conditions in the question, so don’t be confused listen the conditions carefully and try to modify your code according to the given conditions).Explain your first project in detail that you have mentioned in your resume, he asked everything like database of my project, relations between tables in detail, then he starts asking SQL queries (very difficult), he gave some hypothetical tables to me and asked queries on that tables, and trying to confuse me by adding several conditions on the answer of the query.Draw a flowchart of your project.In your project, as you used userid and password for login, so how you store password in database in encrypted form (write code for it).Write a SQL query for finding second highest salary,55th highest salary.Asked all three projects in detail.What in Artificial neural network, the difference between ANN and CNN, how many types of neural networks are there, from where u download dataset for ur Ml project.What is blind write,dirty read?Difference between Strict schedule and cascadeless schedule .explain by giving example.
What is circular linked list, try to confuse by giving some conditions.
Write a program to insert a element in circular linked list, but the condition is you have to insert the element after getting smaller element from the given element. (After explaining my approach he was trying to confuse me by adding some more conditions in the question, so don’t be confused listen the conditions carefully and try to modify your code according to the given conditions).
Explain your first project in detail that you have mentioned in your resume, he asked everything like database of my project, relations between tables in detail, then he starts asking SQL queries (very difficult), he gave some hypothetical tables to me and asked queries on that tables, and trying to confuse me by adding several conditions on the answer of the query.
Draw a flowchart of your project.
In your project, as you used userid and password for login, so how you store password in database in encrypted form (write code for it).
Write a SQL query for finding second highest salary,55th highest salary.
Asked all three projects in detail.
What in Artificial neural network, the difference between ANN and CNN, how many types of neural networks are there, from where u download dataset for ur Ml project.
What is blind write,dirty read?
Difference between Strict schedule and cascadeless schedule .explain by giving example.
Tip:
if you have any database project prepare it very well and practice the database queries.in my second round interviewer focused only on my projects,asked all the things and confused me in sql queries.
Round 4(PRO-FIT): 45 minutes
It was a very long day ,u tired na????(you have to answer this question very carefully, don’t take it lightly or as a normal question).Tell about ur journey from 10th till MCA, what are the difficulties and challenging situations come in your life and how you deal with it. What are the qualities in you which become your strength in your hard time and what are your weakness in this situation(don’t be fake ,be real). After listening to my journey he appreciates my efforts, my strengths, very much happy by listening my journey.Explain in detail all the words in (public static void main).what is the need for writing static in main method syntax,Is JVM not able to create object.What would happen if I write public static int main in place of public static void main.(an error would come or not?? And if an error would come then which type of error runtime error or compile-time error and also tell the error msg in detail). Do you have any questions?
It was a very long day ,u tired na????(you have to answer this question very carefully, don’t take it lightly or as a normal question).
Tell about ur journey from 10th till MCA, what are the difficulties and challenging situations come in your life and how you deal with it. What are the qualities in you which become your strength in your hard time and what are your weakness in this situation(don’t be fake ,be real). After listening to my journey he appreciates my efforts, my strengths, very much happy by listening my journey.
Explain in detail all the words in (public static void main).what is the need for writing static in main method syntax,Is JVM not able to create object.
What would happen if I write public static int main in place of public static void main.(an error would come or not?? And if an error would come then which type of error runtime error or compile-time error and also tell the error msg in detail).
Do you have any questions?
Round 5(HR)
Tell me about yourself that you are not mentioned in your resume.Explain your project(anyone). Do you have any questions?
Tell me about yourself that you are not mentioned in your resume.
Explain your project(anyone).
Do you have any questions?
TIPS:
Always be confident when you are giving answers, the interviewer also tests your confidence by confusing you.Read carefully all the things which you have mentioned in your resume. don’t write so much extra things.
Always be confident when you are giving answers, the interviewer also tests your confidence by confusing you.
Read carefully all the things which you have mentioned in your resume. don’t write so much extra things.
THAT’S ALL ABOUT MY EXPERIENCE HOPE THIS WILL BE HELPFUL TO YOU
ALL THE BEST.
Deutsche Bank
Marketing
Interview Experiences
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n21 May, 2021"
},
{
"code": null,
"e": 76,
"s": 54,
"text": "Round 1(Online Test):"
},
{
"code": null,
"e": 5097,
"s": 76,
"text": "It was a string manipulation question. Suppose input was string1, string2, and k seconds. We have to choose every i from 1 to k and shift a character from the string by i index (eg: if i=3 then ‘a’ would be shifted to ‘d’). Each i could be chosen only once. We need to check if we can convert string1 to string2. (20 marks)Input: \nk=3\nstring1 = 'abc'\nstring2 = 'ddd'\nOutput: \nYesGiven N, find two numbers with a product greater than or equal to N and with minimum sum.(50 marks)Input -15\nOutput-8It was a DFS question where edges representing time, we had to find the total minimum time spent in visiting all vertices, but there was a sequence given in which we can visit vertices. (50 marks)Solved by defining a comparator and then sorting the edges.I did second question of 50 marks with all test cases passed and in first question I got 12 marks out of 20.So in total, I got 62 marks out of 120.Round 2(Technical): 45 minutesTell me about yourself.Tell me your favourite data structure(Linked list for me).Difference between linked list and array.Write a program in notepad and share your screen to find if 1st linked list is contained in 2nd linked list or not, if present then print “yes” otherwise “no”.Write structure of linked list.Explain the concepts of oops in detail with real-life examples and also tell the difference between procedural programming language and object-oriented programming language.(explain oops concept from starting and explain in detail).Explain your project in detail like which technology u used and how many modules are there in ur project ,everything which is related to ur project.and also explain database of ur project, relations between tables.Explain Queue data structure, explain its working with real-life example and what is enque and deque in it.Explain dynamic programming. Write a program of Fibonacci series using dp approach.Do you have any questions(Always ask some good questions)?Round 3(Technical): 1 hourWhat is circular linked list, try to confuse by giving some conditions.Write a program to insert a element in circular linked list, but the condition is you have to insert the element after getting smaller element from the given element. (After explaining my approach he was trying to confuse me by adding some more conditions in the question, so don’t be confused listen the conditions carefully and try to modify your code according to the given conditions).Explain your first project in detail that you have mentioned in your resume, he asked everything like database of my project, relations between tables in detail, then he starts asking SQL queries (very difficult), he gave some hypothetical tables to me and asked queries on that tables, and trying to confuse me by adding several conditions on the answer of the query.Draw a flowchart of your project.In your project, as you used userid and password for login, so how you store password in database in encrypted form (write code for it).Write a SQL query for finding second highest salary,55th highest salary.Asked all three projects in detail.What in Artificial neural network, the difference between ANN and CNN, how many types of neural networks are there, from where u download dataset for ur Ml project.What is blind write,dirty read?Difference between Strict schedule and cascadeless schedule .explain by giving example.Tip: if you have any database project prepare it very well and practice the database queries.in my second round interviewer focused only on my projects,asked all the things and confused me in sql queries.Round 4(PRO-FIT): 45 minutes It was a very long day ,u tired na????(you have to answer this question very carefully, don’t take it lightly or as a normal question).Tell about ur journey from 10th till MCA, what are the difficulties and challenging situations come in your life and how you deal with it. What are the qualities in you which become your strength in your hard time and what are your weakness in this situation(don’t be fake ,be real). After listening to my journey he appreciates my efforts, my strengths, very much happy by listening my journey.Explain in detail all the words in (public static void main).what is the need for writing static in main method syntax,Is JVM not able to create object.What would happen if I write public static int main in place of public static void main.(an error would come or not?? And if an error would come then which type of error runtime error or compile-time error and also tell the error msg in detail). Do you have any questions?Round 5(HR)Tell me about yourself that you are not mentioned in your resume.Explain your project(anyone). Do you have any questions? TIPS:Always be confident when you are giving answers, the interviewer also tests your confidence by confusing you.Read carefully all the things which you have mentioned in your resume. don’t write so much extra things.THAT’S ALL ABOUT MY EXPERIENCE HOPE THIS WILL BE HELPFUL TO YOUALL THE BEST.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 5479,
"s": 5097,
"text": "It was a string manipulation question. Suppose input was string1, string2, and k seconds. We have to choose every i from 1 to k and shift a character from the string by i index (eg: if i=3 then ‘a’ would be shifted to ‘d’). Each i could be chosen only once. We need to check if we can convert string1 to string2. (20 marks)Input: \nk=3\nstring1 = 'abc'\nstring2 = 'ddd'\nOutput: \nYes"
},
{
"code": null,
"e": 5538,
"s": 5479,
"text": "Input: \nk=3\nstring1 = 'abc'\nstring2 = 'ddd'\nOutput: \nYes"
},
{
"code": null,
"e": 5656,
"s": 5538,
"text": "Given N, find two numbers with a product greater than or equal to N and with minimum sum.(50 marks)Input -15\nOutput-8"
},
{
"code": null,
"e": 5675,
"s": 5656,
"text": "Input -15\nOutput-8"
},
{
"code": null,
"e": 5931,
"s": 5675,
"text": "It was a DFS question where edges representing time, we had to find the total minimum time spent in visiting all vertices, but there was a sequence given in which we can visit vertices. (50 marks)Solved by defining a comparator and then sorting the edges."
},
{
"code": null,
"e": 5991,
"s": 5931,
"text": "Solved by defining a comparator and then sorting the edges."
},
{
"code": null,
"e": 6139,
"s": 5991,
"text": "I did second question of 50 marks with all test cases passed and in first question I got 12 marks out of 20.So in total, I got 62 marks out of 120."
},
{
"code": null,
"e": 6170,
"s": 6139,
"text": "Round 2(Technical): 45 minutes"
},
{
"code": null,
"e": 7178,
"s": 6170,
"text": "Tell me about yourself.Tell me your favourite data structure(Linked list for me).Difference between linked list and array.Write a program in notepad and share your screen to find if 1st linked list is contained in 2nd linked list or not, if present then print “yes” otherwise “no”.Write structure of linked list.Explain the concepts of oops in detail with real-life examples and also tell the difference between procedural programming language and object-oriented programming language.(explain oops concept from starting and explain in detail).Explain your project in detail like which technology u used and how many modules are there in ur project ,everything which is related to ur project.and also explain database of ur project, relations between tables.Explain Queue data structure, explain its working with real-life example and what is enque and deque in it.Explain dynamic programming. Write a program of Fibonacci series using dp approach.Do you have any questions(Always ask some good questions)?"
},
{
"code": null,
"e": 7202,
"s": 7178,
"text": "Tell me about yourself."
},
{
"code": null,
"e": 7261,
"s": 7202,
"text": "Tell me your favourite data structure(Linked list for me)."
},
{
"code": null,
"e": 7303,
"s": 7261,
"text": "Difference between linked list and array."
},
{
"code": null,
"e": 7463,
"s": 7303,
"text": "Write a program in notepad and share your screen to find if 1st linked list is contained in 2nd linked list or not, if present then print “yes” otherwise “no”."
},
{
"code": null,
"e": 7495,
"s": 7463,
"text": "Write structure of linked list."
},
{
"code": null,
"e": 7728,
"s": 7495,
"text": "Explain the concepts of oops in detail with real-life examples and also tell the difference between procedural programming language and object-oriented programming language.(explain oops concept from starting and explain in detail)."
},
{
"code": null,
"e": 7944,
"s": 7728,
"text": "Explain your project in detail like which technology u used and how many modules are there in ur project ,everything which is related to ur project.and also explain database of ur project, relations between tables."
},
{
"code": null,
"e": 8052,
"s": 7944,
"text": "Explain Queue data structure, explain its working with real-life example and what is enque and deque in it."
},
{
"code": null,
"e": 8136,
"s": 8052,
"text": "Explain dynamic programming. Write a program of Fibonacci series using dp approach."
},
{
"code": null,
"e": 8195,
"s": 8136,
"text": "Do you have any questions(Always ask some good questions)?"
},
{
"code": null,
"e": 8222,
"s": 8195,
"text": "Round 3(Technical): 1 hour"
},
{
"code": null,
"e": 9612,
"s": 8222,
"text": "What is circular linked list, try to confuse by giving some conditions.Write a program to insert a element in circular linked list, but the condition is you have to insert the element after getting smaller element from the given element. (After explaining my approach he was trying to confuse me by adding some more conditions in the question, so don’t be confused listen the conditions carefully and try to modify your code according to the given conditions).Explain your first project in detail that you have mentioned in your resume, he asked everything like database of my project, relations between tables in detail, then he starts asking SQL queries (very difficult), he gave some hypothetical tables to me and asked queries on that tables, and trying to confuse me by adding several conditions on the answer of the query.Draw a flowchart of your project.In your project, as you used userid and password for login, so how you store password in database in encrypted form (write code for it).Write a SQL query for finding second highest salary,55th highest salary.Asked all three projects in detail.What in Artificial neural network, the difference between ANN and CNN, how many types of neural networks are there, from where u download dataset for ur Ml project.What is blind write,dirty read?Difference between Strict schedule and cascadeless schedule .explain by giving example."
},
{
"code": null,
"e": 9684,
"s": 9612,
"text": "What is circular linked list, try to confuse by giving some conditions."
},
{
"code": null,
"e": 10075,
"s": 9684,
"text": "Write a program to insert a element in circular linked list, but the condition is you have to insert the element after getting smaller element from the given element. (After explaining my approach he was trying to confuse me by adding some more conditions in the question, so don’t be confused listen the conditions carefully and try to modify your code according to the given conditions)."
},
{
"code": null,
"e": 10445,
"s": 10075,
"text": "Explain your first project in detail that you have mentioned in your resume, he asked everything like database of my project, relations between tables in detail, then he starts asking SQL queries (very difficult), he gave some hypothetical tables to me and asked queries on that tables, and trying to confuse me by adding several conditions on the answer of the query."
},
{
"code": null,
"e": 10479,
"s": 10445,
"text": "Draw a flowchart of your project."
},
{
"code": null,
"e": 10616,
"s": 10479,
"text": "In your project, as you used userid and password for login, so how you store password in database in encrypted form (write code for it)."
},
{
"code": null,
"e": 10689,
"s": 10616,
"text": "Write a SQL query for finding second highest salary,55th highest salary."
},
{
"code": null,
"e": 10725,
"s": 10689,
"text": "Asked all three projects in detail."
},
{
"code": null,
"e": 10890,
"s": 10725,
"text": "What in Artificial neural network, the difference between ANN and CNN, how many types of neural networks are there, from where u download dataset for ur Ml project."
},
{
"code": null,
"e": 10922,
"s": 10890,
"text": "What is blind write,dirty read?"
},
{
"code": null,
"e": 11011,
"s": 10922,
"text": "Difference between Strict schedule and cascadeless schedule .explain by giving example."
},
{
"code": null,
"e": 11017,
"s": 11011,
"text": "Tip: "
},
{
"code": null,
"e": 11221,
"s": 11017,
"text": "if you have any database project prepare it very well and practice the database queries.in my second round interviewer focused only on my projects,asked all the things and confused me in sql queries."
},
{
"code": null,
"e": 11250,
"s": 11221,
"text": "Round 4(PRO-FIT): 45 minutes"
},
{
"code": null,
"e": 12218,
"s": 11250,
"text": " It was a very long day ,u tired na????(you have to answer this question very carefully, don’t take it lightly or as a normal question).Tell about ur journey from 10th till MCA, what are the difficulties and challenging situations come in your life and how you deal with it. What are the qualities in you which become your strength in your hard time and what are your weakness in this situation(don’t be fake ,be real). After listening to my journey he appreciates my efforts, my strengths, very much happy by listening my journey.Explain in detail all the words in (public static void main).what is the need for writing static in main method syntax,Is JVM not able to create object.What would happen if I write public static int main in place of public static void main.(an error would come or not?? And if an error would come then which type of error runtime error or compile-time error and also tell the error msg in detail). Do you have any questions?"
},
{
"code": null,
"e": 12359,
"s": 12218,
"text": " It was a very long day ,u tired na????(you have to answer this question very carefully, don’t take it lightly or as a normal question)."
},
{
"code": null,
"e": 12756,
"s": 12359,
"text": "Tell about ur journey from 10th till MCA, what are the difficulties and challenging situations come in your life and how you deal with it. What are the qualities in you which become your strength in your hard time and what are your weakness in this situation(don’t be fake ,be real). After listening to my journey he appreciates my efforts, my strengths, very much happy by listening my journey."
},
{
"code": null,
"e": 12915,
"s": 12756,
"text": "Explain in detail all the words in (public static void main).what is the need for writing static in main method syntax,Is JVM not able to create object."
},
{
"code": null,
"e": 13163,
"s": 12915,
"text": "What would happen if I write public static int main in place of public static void main.(an error would come or not?? And if an error would come then which type of error runtime error or compile-time error and also tell the error msg in detail). "
},
{
"code": null,
"e": 13190,
"s": 13163,
"text": "Do you have any questions?"
},
{
"code": null,
"e": 13202,
"s": 13190,
"text": "Round 5(HR)"
},
{
"code": null,
"e": 13327,
"s": 13202,
"text": "Tell me about yourself that you are not mentioned in your resume.Explain your project(anyone). Do you have any questions? "
},
{
"code": null,
"e": 13393,
"s": 13327,
"text": "Tell me about yourself that you are not mentioned in your resume."
},
{
"code": null,
"e": 13425,
"s": 13393,
"text": "Explain your project(anyone). "
},
{
"code": null,
"e": 13454,
"s": 13425,
"text": "Do you have any questions? "
},
{
"code": null,
"e": 13460,
"s": 13454,
"text": "TIPS:"
},
{
"code": null,
"e": 13675,
"s": 13460,
"text": "Always be confident when you are giving answers, the interviewer also tests your confidence by confusing you.Read carefully all the things which you have mentioned in your resume. don’t write so much extra things."
},
{
"code": null,
"e": 13785,
"s": 13675,
"text": "Always be confident when you are giving answers, the interviewer also tests your confidence by confusing you."
},
{
"code": null,
"e": 13891,
"s": 13785,
"text": "Read carefully all the things which you have mentioned in your resume. don’t write so much extra things."
},
{
"code": null,
"e": 13955,
"s": 13891,
"text": "THAT’S ALL ABOUT MY EXPERIENCE HOPE THIS WILL BE HELPFUL TO YOU"
},
{
"code": null,
"e": 13969,
"s": 13955,
"text": "ALL THE BEST."
},
{
"code": null,
"e": 13983,
"s": 13969,
"text": "Deutsche Bank"
},
{
"code": null,
"e": 13993,
"s": 13983,
"text": "Marketing"
},
{
"code": null,
"e": 14015,
"s": 13993,
"text": "Interview Experiences"
}
]
|
How to Preserve Insertion Order of Java HashSet Elements? - GeeksforGeeks | 07 Jan, 2021
When elements get from the HashSet due to hashing the order they inserted is not maintained while retrieval. HashSet stores the elements by using a mechanism called hashing. We can achieve the given task using LinkedHashSet. The LinkedHashSet class implements a doubly-linked list so that it can traverse through all the elements.
Example:
Input : HashSetInput = {c, a, b}
Output: HashSetPrint = {c, a, b}
Input : HashSetInput = {"first", "second"}
Output: HashSetPrint = {"first", "second"}
Implementation With HashSet: (Order Not Maintained)
Syntax:
HashSet<String> num = new HashSet<String>();
Approach:
Create HashSet object.Insert multiple elements in the HashSet.Print the HashSet.(Order not maintained)
Create HashSet object.
Insert multiple elements in the HashSet.
Print the HashSet.(Order not maintained)
Below is the implementation of the above approach:
Java
// Preserve insertion order of Java HashSet elements// Order not maintained because HashSet usedimport java.util.HashSet;import java.util.Set; public class PreserveHashSetOrderExample { public static void main(String[] args) { Set<Integer> hSetNumbers = new HashSet<Integer>(); hSetNumbers.add(1); hSetNumbers.add(13); hSetNumbers.add(2); hSetNumbers.add(4); for (Integer number : hSetNumbers) { System.out.println(number); } }}
1
2
4
13
Implementation With LinkedHashSet: (Order Maintained)
Syntax:
HashSet<String> num = new LinkedHashSet<String>();
Approach:
Create a HashSet object and initialize it with the constructor of LinkedHashSet.Insert multiple elements in the HashSet.Print the HashSet.(Order maintained)
Create a HashSet object and initialize it with the constructor of LinkedHashSet.
Insert multiple elements in the HashSet.
Print the HashSet.(Order maintained)
Below is the implementation of the above approach:
Java
// Preserve insertion order of Java HashSet elements// Using LinkedHashSetimport java.util.LinkedHashSet;import java.util.Set; public class PreserveHashSetOrderExample { public static void main(String[] args) { Set<Integer> setNumbers = new LinkedHashSet<Integer>(); setNumbers.add(1); setNumbers.add(13); setNumbers.add(2); setNumbers.add(4); for (Integer number : setNumbers) { System.out.println(number); } }}
1
13
2
4
java-hashset
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Different ways of Reading a text file in Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java? | [
{
"code": null,
"e": 23948,
"s": 23920,
"text": "\n07 Jan, 2021"
},
{
"code": null,
"e": 24279,
"s": 23948,
"text": "When elements get from the HashSet due to hashing the order they inserted is not maintained while retrieval. HashSet stores the elements by using a mechanism called hashing. We can achieve the given task using LinkedHashSet. The LinkedHashSet class implements a doubly-linked list so that it can traverse through all the elements."
},
{
"code": null,
"e": 24288,
"s": 24279,
"text": "Example:"
},
{
"code": null,
"e": 24441,
"s": 24288,
"text": "Input : HashSetInput = {c, a, b}\nOutput: HashSetPrint = {c, a, b}\n\nInput : HashSetInput = {\"first\", \"second\"}\nOutput: HashSetPrint = {\"first\", \"second\"}"
},
{
"code": null,
"e": 24493,
"s": 24441,
"text": "Implementation With HashSet: (Order Not Maintained)"
},
{
"code": null,
"e": 24501,
"s": 24493,
"text": "Syntax:"
},
{
"code": null,
"e": 24546,
"s": 24501,
"text": "HashSet<String> num = new HashSet<String>();"
},
{
"code": null,
"e": 24556,
"s": 24546,
"text": "Approach:"
},
{
"code": null,
"e": 24659,
"s": 24556,
"text": "Create HashSet object.Insert multiple elements in the HashSet.Print the HashSet.(Order not maintained)"
},
{
"code": null,
"e": 24682,
"s": 24659,
"text": "Create HashSet object."
},
{
"code": null,
"e": 24723,
"s": 24682,
"text": "Insert multiple elements in the HashSet."
},
{
"code": null,
"e": 24764,
"s": 24723,
"text": "Print the HashSet.(Order not maintained)"
},
{
"code": null,
"e": 24815,
"s": 24764,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 24820,
"s": 24815,
"text": "Java"
},
{
"code": "// Preserve insertion order of Java HashSet elements// Order not maintained because HashSet usedimport java.util.HashSet;import java.util.Set; public class PreserveHashSetOrderExample { public static void main(String[] args) { Set<Integer> hSetNumbers = new HashSet<Integer>(); hSetNumbers.add(1); hSetNumbers.add(13); hSetNumbers.add(2); hSetNumbers.add(4); for (Integer number : hSetNumbers) { System.out.println(number); } }}",
"e": 25327,
"s": 24820,
"text": null
},
{
"code": null,
"e": 25336,
"s": 25327,
"text": "1\n2\n4\n13"
},
{
"code": null,
"e": 25390,
"s": 25336,
"text": "Implementation With LinkedHashSet: (Order Maintained)"
},
{
"code": null,
"e": 25398,
"s": 25390,
"text": "Syntax:"
},
{
"code": null,
"e": 25449,
"s": 25398,
"text": "HashSet<String> num = new LinkedHashSet<String>();"
},
{
"code": null,
"e": 25459,
"s": 25449,
"text": "Approach:"
},
{
"code": null,
"e": 25616,
"s": 25459,
"text": "Create a HashSet object and initialize it with the constructor of LinkedHashSet.Insert multiple elements in the HashSet.Print the HashSet.(Order maintained)"
},
{
"code": null,
"e": 25697,
"s": 25616,
"text": "Create a HashSet object and initialize it with the constructor of LinkedHashSet."
},
{
"code": null,
"e": 25738,
"s": 25697,
"text": "Insert multiple elements in the HashSet."
},
{
"code": null,
"e": 25775,
"s": 25738,
"text": "Print the HashSet.(Order maintained)"
},
{
"code": null,
"e": 25826,
"s": 25775,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 25831,
"s": 25826,
"text": "Java"
},
{
"code": "// Preserve insertion order of Java HashSet elements// Using LinkedHashSetimport java.util.LinkedHashSet;import java.util.Set; public class PreserveHashSetOrderExample { public static void main(String[] args) { Set<Integer> setNumbers = new LinkedHashSet<Integer>(); setNumbers.add(1); setNumbers.add(13); setNumbers.add(2); setNumbers.add(4); for (Integer number : setNumbers) { System.out.println(number); } }}",
"e": 26333,
"s": 25831,
"text": null
},
{
"code": null,
"e": 26342,
"s": 26333,
"text": "1\n13\n2\n4"
},
{
"code": null,
"e": 26355,
"s": 26342,
"text": "java-hashset"
},
{
"code": null,
"e": 26362,
"s": 26355,
"text": "Picked"
},
{
"code": null,
"e": 26386,
"s": 26362,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 26391,
"s": 26386,
"text": "Java"
},
{
"code": null,
"e": 26405,
"s": 26391,
"text": "Java Programs"
},
{
"code": null,
"e": 26424,
"s": 26405,
"text": "Technical Scripter"
},
{
"code": null,
"e": 26429,
"s": 26424,
"text": "Java"
},
{
"code": null,
"e": 26527,
"s": 26429,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26542,
"s": 26527,
"text": "Stream In Java"
},
{
"code": null,
"e": 26588,
"s": 26542,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 26609,
"s": 26588,
"text": "Constructors in Java"
},
{
"code": null,
"e": 26628,
"s": 26609,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 26658,
"s": 26628,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 26702,
"s": 26658,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 26728,
"s": 26702,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 26762,
"s": 26728,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 26809,
"s": 26762,
"text": "Implementing a Linked List in Java using Class"
}
]
|
JavaScript array.includes inside nested array returning false where as searched name is in array | It is a well-known dilemma that when we use includes() inside nested arrays i.e., multidimensional
array, it does not work, there exists a Array.prototype.flat() function which flats the
array and then searches through but it’s browser support is not very good yet.
So our job is to create a includesMultiDimension() function that takes in an array and a string
and returns a boolean based on the presence/absence of that string in the array.
There exist many solutions to this problem, most of them includes recursion, heavy array
function, loops and what not.
What we are going to discuss here is by far the easiest way to check for presence/absence of
string in nested arrays.
The code for this is −
const names = ['Ram', 'Shyam', 'Laxman', [
'Jay', 'Jessica', [
'Vikram'
]
]];
const includesMultiDimension = (arr, str) =>
JSON.stringify(arr).includes(str);
console.log(includesMultiDimension(names, 'Vikram'));
This one line solution includes converting the array into a JSON string so that we can simply
apply includes to it.
The console output will be −
True | [
{
"code": null,
"e": 1328,
"s": 1062,
"text": "It is a well-known dilemma that when we use includes() inside nested arrays i.e., multidimensional\narray, it does not work, there exists a Array.prototype.flat() function which flats the\narray and then searches through but it’s browser support is not very good yet."
},
{
"code": null,
"e": 1505,
"s": 1328,
"text": "So our job is to create a includesMultiDimension() function that takes in an array and a string\nand returns a boolean based on the presence/absence of that string in the array."
},
{
"code": null,
"e": 1624,
"s": 1505,
"text": "There exist many solutions to this problem, most of them includes recursion, heavy array\nfunction, loops and what not."
},
{
"code": null,
"e": 1742,
"s": 1624,
"text": "What we are going to discuss here is by far the easiest way to check for presence/absence of\nstring in nested arrays."
},
{
"code": null,
"e": 1765,
"s": 1742,
"text": "The code for this is −"
},
{
"code": null,
"e": 1989,
"s": 1765,
"text": "const names = ['Ram', 'Shyam', 'Laxman', [\n 'Jay', 'Jessica', [\n 'Vikram'\n ]\n]];\nconst includesMultiDimension = (arr, str) =>\nJSON.stringify(arr).includes(str);\nconsole.log(includesMultiDimension(names, 'Vikram'));"
},
{
"code": null,
"e": 2105,
"s": 1989,
"text": "This one line solution includes converting the array into a JSON string so that we can simply\napply includes to it."
},
{
"code": null,
"e": 2134,
"s": 2105,
"text": "The console output will be −"
},
{
"code": null,
"e": 2139,
"s": 2134,
"text": "True"
}
]
|
C++ Array (print an element) | Set 2 | Practice | GeeksforGeeks | Given an array A[] of N integers and an index Key. Your task is to print the element present at index key in the array.
Example 1:
Input:
5 2
10 20 30 40 50
Output:
30
Example 2:
Input:
7 4
10 20 30 40 50 60 70
Output:
50
Your Task:
You don't need to read input or print anything. Your task is to complete the function findElementAtIndex() which takes the array A[], its size N and an integer Key as inputs and returns the element present at index Key.
Expected Time Complexity: O(1)
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ N ≤ 100
0 ≤ Key ≤ N - 1
1 ≤ A[i] ≤ 100
0
rsbly7300952 weeks ago
class Solution{ public: int findElementAtIndex(int a[], int n, int key) { return a[key]; }};
0
ayushsunilkadam3 weeks ago
return a[key];
0
crsongirkar21 month ago
class Solution{ public: int findElementAtIndex(int a[], int n, int key) { return a[key]; // Your code goes here }};
0
0niharika22 months ago
return a[key];
0
amans603312 months ago
class Solution{ public: int findElementAtIndex(int a[], int n, int key) { return a[key]; }};
0
ishankumarsingh262 months ago
class Solution{
public:
int findElementAtIndex(int a[], int n, int key)
{
return a[key];
}
};
+1
sakshamraj2292 months ago
class Solution{
public:
int findElementAtIndex(int a[], int n, int key)
{
return a[key];
}
};
0
samarthsaxena3123 months ago
class Solution{ public: int findElementAtIndex(int a[], int n, int key) { for(int i=0;i<n;i++) { if(key==i) { return a[i]; break; } } }};
0
helloutkarsh983 months ago
int findElementAtIndex(int a[], int n, int key) { return a[key]; }
-1
viploveparsai13 months ago
class Solution{ public: int findElementAtIndex(int a[], int n, int key) { // Your code goes here return a[key]; }};
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": 346,
"s": 226,
"text": "Given an array A[] of N integers and an index Key. Your task is to print the element present at index key in the array."
},
{
"code": null,
"e": 359,
"s": 348,
"text": "Example 1:"
},
{
"code": null,
"e": 396,
"s": 359,
"text": "Input:\n5 2\n10 20 30 40 50\nOutput:\n30"
},
{
"code": null,
"e": 409,
"s": 398,
"text": "Example 2:"
},
{
"code": null,
"e": 452,
"s": 409,
"text": "Input:\n7 4\n10 20 30 40 50 60 70\nOutput:\n50"
},
{
"code": null,
"e": 687,
"s": 454,
"text": "Your Task: \nYou don't need to read input or print anything. Your task is to complete the function findElementAtIndex() which takes the array A[], its size N and an integer Key as inputs and returns the element present at index Key."
},
{
"code": null,
"e": 750,
"s": 687,
"text": "\nExpected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 808,
"s": 752,
"text": "Constraints:\n1 ≤ N ≤ 100\n0 ≤ Key ≤ N - 1\n1 ≤ A[i] ≤ 100"
},
{
"code": null,
"e": 810,
"s": 808,
"text": "0"
},
{
"code": null,
"e": 833,
"s": 810,
"text": "rsbly7300952 weeks ago"
},
{
"code": null,
"e": 941,
"s": 833,
"text": "class Solution{ public: int findElementAtIndex(int a[], int n, int key) { return a[key]; }};"
},
{
"code": null,
"e": 943,
"s": 941,
"text": "0"
},
{
"code": null,
"e": 970,
"s": 943,
"text": "ayushsunilkadam3 weeks ago"
},
{
"code": null,
"e": 985,
"s": 970,
"text": "return a[key];"
},
{
"code": null,
"e": 987,
"s": 985,
"text": "0"
},
{
"code": null,
"e": 1011,
"s": 987,
"text": "crsongirkar21 month ago"
},
{
"code": null,
"e": 1148,
"s": 1011,
"text": "class Solution{ public: int findElementAtIndex(int a[], int n, int key) { return a[key]; // Your code goes here }};"
},
{
"code": null,
"e": 1150,
"s": 1148,
"text": "0"
},
{
"code": null,
"e": 1173,
"s": 1150,
"text": "0niharika22 months ago"
},
{
"code": null,
"e": 1188,
"s": 1173,
"text": "return a[key];"
},
{
"code": null,
"e": 1190,
"s": 1188,
"text": "0"
},
{
"code": null,
"e": 1213,
"s": 1190,
"text": "amans603312 months ago"
},
{
"code": null,
"e": 1321,
"s": 1213,
"text": "class Solution{ public: int findElementAtIndex(int a[], int n, int key) { return a[key]; }};"
},
{
"code": null,
"e": 1323,
"s": 1321,
"text": "0"
},
{
"code": null,
"e": 1353,
"s": 1323,
"text": "ishankumarsingh262 months ago"
},
{
"code": null,
"e": 1472,
"s": 1353,
"text": "class Solution{\n public:\n int findElementAtIndex(int a[], int n, int key) \n {\n return a[key];\n }\n};"
},
{
"code": null,
"e": 1475,
"s": 1472,
"text": "+1"
},
{
"code": null,
"e": 1501,
"s": 1475,
"text": "sakshamraj2292 months ago"
},
{
"code": null,
"e": 1620,
"s": 1501,
"text": "class Solution{\n public:\n int findElementAtIndex(int a[], int n, int key) \n {\n return a[key];\n }\n};"
},
{
"code": null,
"e": 1622,
"s": 1620,
"text": "0"
},
{
"code": null,
"e": 1651,
"s": 1622,
"text": "samarthsaxena3123 months ago"
},
{
"code": null,
"e": 1866,
"s": 1651,
"text": "class Solution{ public: int findElementAtIndex(int a[], int n, int key) { for(int i=0;i<n;i++) { if(key==i) { return a[i]; break; } } }};"
},
{
"code": null,
"e": 1870,
"s": 1868,
"text": "0"
},
{
"code": null,
"e": 1897,
"s": 1870,
"text": "helloutkarsh983 months ago"
},
{
"code": null,
"e": 1978,
"s": 1897,
"text": " int findElementAtIndex(int a[], int n, int key) { return a[key]; }"
},
{
"code": null,
"e": 1981,
"s": 1978,
"text": "-1"
},
{
"code": null,
"e": 2008,
"s": 1981,
"text": "viploveparsai13 months ago"
},
{
"code": null,
"e": 2146,
"s": 2008,
"text": "class Solution{ public: int findElementAtIndex(int a[], int n, int key) { // Your code goes here return a[key]; }}; "
},
{
"code": null,
"e": 2292,
"s": 2146,
"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": 2328,
"s": 2292,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 2338,
"s": 2328,
"text": "\nProblem\n"
},
{
"code": null,
"e": 2348,
"s": 2338,
"text": "\nContest\n"
},
{
"code": null,
"e": 2411,
"s": 2348,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 2559,
"s": 2411,
"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": 2767,
"s": 2559,
"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": 2873,
"s": 2767,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
]
|
Count the number of operations required to reduce the given number - GeeksforGeeks | 03 Jun, 2021
Given an integer k and an array op[], in a single operation op[0] will be added to k and then in the second operation k = k + op[1] and so on in a circular manner until k > 0. The task is to print the operation number in which k will be reduced to ≤ 0. If it impossible to reduce k with the given operations then print -1.Examples:
Input: op[] = {-60, 10, -100}, k = 100 Output: 3 Operation 1: 100 – 60 = 40 Operation 2: 40 + 10 = 50 Operation 3: 50 – 100 = -50Input: op[] = {1, 1, -1}, k = 10 Output: -1Input: op[] = {-60, 65, -1, 14, -25}, k = 100000 Output: 71391
Approach: Count the number of times all the operations can be performed on the number k without actually reducing it to get the result. Then update count = times * n where n is the number of operations. Now, for the remaining operations perform each of the operation one by one and increment count. The first operation when k is reduced to ≤ 0, print the count.Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of the approach #include <bits/stdc++.h>using namespace std; int operations(int op[], int n, int k) { int i, count = 0; // To store the normalized value // of all the operations int nVal = 0; // Minimum possible value for // a series of operations int minimum = INT_MAX; for (i = 0; i < n; i++) { nVal += op[i]; minimum = min(minimum , nVal); // If k can be reduced with // first (i + 1) operations if ((k + nVal) <= 0) return (i + 1); } // Impossible to reduce k if (nVal >= 0) return -1; // Number of times all the operations // can be performed on k without // reducing it to <= 0 int times = (k - abs(minimum )) / abs(nVal); // Perform operations k = (k - (times * abs(nVal))); count = (times * n); // Final check while (k > 0) { for (i = 0; i < n; i++) { k = k + op[i]; count++; if (k <= 0) break; } } return count; } // Driver codeint main() { int op[] = { -60, 65, -1, 14, -25 }; int n = sizeof(op)/sizeof(op[0]); int k = 100000; cout << operations(op, n, k) << endl;}// This code is contributed by Ryuga
// Java implementation of the approachclass GFG { static int operations(int op[], int n, int k) { int i, count = 0; // To store the normalized value // of all the operations int nVal = 0; // Minimum possible value for // a series of operations int min = Integer.MAX_VALUE; for (i = 0; i < n; i++) { nVal += op[i]; min = Math.min(min, nVal); // If k can be reduced with // first (i + 1) operations if ((k + nVal) <= 0) return (i + 1); } // Impossible to reduce k if (nVal >= 0) return -1; // Number of times all the operations // can be performed on k without // reducing it to <= 0 int times = (k - Math.abs(min)) / Math.abs(nVal); // Perform operations k = (k - (times * Math.abs(nVal))); count = (times * n); // Final check while (k > 0) { for (i = 0; i < n; i++) { k = k + op[i]; count++; if (k <= 0) break; } } return count; } // Driver code public static void main(String[] args) { int op[] = { -60, 65, -1, 14, -25 }; int n = op.length; int k = 100000; System.out.print(operations(op, n, k)); }}
# Python3 implementation of the approachdef operations(op, n, k): i, count = 0, 0 # To store the normalized value # of all the operations nVal = 0 # Minimum possible value for # a series of operations minimum = 10**9 for i in range(n): nVal += op[i] minimum = min(minimum , nVal) # If k can be reduced with # first (i + 1) operations if ((k + nVal) <= 0): return (i + 1) # Impossible to reduce k if (nVal >= 0): return -1 # Number of times all the operations # can be performed on k without # reducing it to <= 0 times = (k - abs(minimum )) // abs(nVal) # Perform operations k = (k - (times * abs(nVal))) count = (times * n) # Final check while (k > 0): for i in range(n): k = k + op[i] count += 1 if (k <= 0): break return count # Driver codeop = [-60, 65, -1, 14, -25]n = len(op)k = 100000 print(operations(op, n, k)) # This code is contributed# by mohit kumar
// C# implementation of the approachusing System; class GFG{ static int operations(int []op, int n, int k) { int i, count = 0; // To store the normalized value // of all the operations int nVal = 0; // Minimum possible value for // a series of operations int min = int.MaxValue; for (i = 0; i < n; i++) { nVal += op[i]; min = Math.Min(min, nVal); // If k can be reduced with // first (i + 1) operations if ((k + nVal) <= 0) return (i + 1); } // Impossible to reduce k if (nVal >= 0) return -1; // Number of times all the operations // can be performed on k without // reducing it to <= 0 int times = (k - Math.Abs(min)) / Math.Abs(nVal); // Perform operations k = (k - (times * Math.Abs(nVal))); count = (times * n); // Final check while (k > 0) { for (i = 0; i < n; i++) { k = k + op[i]; count++; if (k <= 0) break; } } return count; } // Driver code static void Main() { int []op = { -60, 65, -1, 14, -25 }; int n = op.Length; int k = 100000; Console.WriteLine(operations(op, n, k)); }} // This code is contributed by mits
<?php// PHP implementation of the approachfunction operations($op, $n, $k){ $count = 0; // To store the normalized value // of all the operations $nVal = 0; // Minimum possible value for // a series of operations $minimum = PHP_INT_MAX; for ($i = 0; $i < $n; $i++) { $nVal += $op[$i]; $minimum = min($minimum , $nVal); // If k can be reduced with // first (i + 1) operations if (($k + $nVal) <= 0) return ($i + 1); } // Impossible to reduce k if ($nVal >= 0) return -1; // Number of times all the operations // can be performed on k without // reducing it to <= 0 $times = round(($k - abs($minimum )) / abs($nVal)); // Perform operations $k = ($k - ($times * abs($nVal))); $count = ($times * $n); // Final check while ($k > 0) { for ($i = 0; $i < $n; $i++) { $k = $k + $op[$i]; $count++; if ($k <= 0) break; } } return $count;} // Driver code$op = array(-60, 65, -1, 14, -25 );$n = sizeof($op);$k = 100000; echo operations($op, $n, $k); // This code is contributed by ihritik?>
<script>// Javascript implementation of the approach function operations(op,n,k){ let i, count = 0; // To store the normalized value // of all the operations let nVal = 0; // Minimum possible value for // a series of operations let min = Number.MAX_VALUE; for (i = 0; i < n; i++) { nVal += op[i]; min = Math.min(min, nVal); // If k can be reduced with // first (i + 1) operations if ((k + nVal) <= 0) return (i + 1); } // Impossible to reduce k if (nVal >= 0) return -1; // Number of times all the operations // can be performed on k without // reducing it to <= 0 let times = Math.floor((k - Math.abs(min)) / Math.abs(nVal)); // Perform operations k = (k - (times * Math.abs(nVal))); count = (times * n); // Final check while (k > 0) { for (i = 0; i < n; i++) { k = k + op[i]; count++; if (k <= 0) break; } } return count;} // Driver code let op=[-60, 65, -1, 14, -25]; let n = op.length; let k = 100000; document.write(operations(op, n, k)); // This code is contributed by unknown2108.</script>
71391
Mithun Kumar
ankthon
mohit kumar 29
ihritik
unknown2108
Numbers
Arrays
Mathematical
Searching
Arrays
Searching
Mathematical
Numbers
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": 25326,
"s": 25298,
"text": "\n03 Jun, 2021"
},
{
"code": null,
"e": 25660,
"s": 25326,
"text": "Given an integer k and an array op[], in a single operation op[0] will be added to k and then in the second operation k = k + op[1] and so on in a circular manner until k > 0. The task is to print the operation number in which k will be reduced to ≤ 0. If it impossible to reduce k with the given operations then print -1.Examples: "
},
{
"code": null,
"e": 25897,
"s": 25660,
"text": "Input: op[] = {-60, 10, -100}, k = 100 Output: 3 Operation 1: 100 – 60 = 40 Operation 2: 40 + 10 = 50 Operation 3: 50 – 100 = -50Input: op[] = {1, 1, -1}, k = 10 Output: -1Input: op[] = {-60, 65, -1, 14, -25}, k = 100000 Output: 71391 "
},
{
"code": null,
"e": 26313,
"s": 25899,
"text": "Approach: Count the number of times all the operations can be performed on the number k without actually reducing it to get the result. Then update count = times * n where n is the number of operations. Now, for the remaining operations perform each of the operation one by one and increment count. The first operation when k is reduced to ≤ 0, print the count.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26317,
"s": 26313,
"text": "C++"
},
{
"code": null,
"e": 26322,
"s": 26317,
"text": "Java"
},
{
"code": null,
"e": 26330,
"s": 26322,
"text": "Python3"
},
{
"code": null,
"e": 26333,
"s": 26330,
"text": "C#"
},
{
"code": null,
"e": 26337,
"s": 26333,
"text": "PHP"
},
{
"code": null,
"e": 26348,
"s": 26337,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach #include <bits/stdc++.h>using namespace std; int operations(int op[], int n, int k) { int i, count = 0; // To store the normalized value // of all the operations int nVal = 0; // Minimum possible value for // a series of operations int minimum = INT_MAX; for (i = 0; i < n; i++) { nVal += op[i]; minimum = min(minimum , nVal); // If k can be reduced with // first (i + 1) operations if ((k + nVal) <= 0) return (i + 1); } // Impossible to reduce k if (nVal >= 0) return -1; // Number of times all the operations // can be performed on k without // reducing it to <= 0 int times = (k - abs(minimum )) / abs(nVal); // Perform operations k = (k - (times * abs(nVal))); count = (times * n); // Final check while (k > 0) { for (i = 0; i < n; i++) { k = k + op[i]; count++; if (k <= 0) break; } } return count; } // Driver codeint main() { int op[] = { -60, 65, -1, 14, -25 }; int n = sizeof(op)/sizeof(op[0]); int k = 100000; cout << operations(op, n, k) << endl;}// This code is contributed by Ryuga",
"e": 27760,
"s": 26348,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG { static int operations(int op[], int n, int k) { int i, count = 0; // To store the normalized value // of all the operations int nVal = 0; // Minimum possible value for // a series of operations int min = Integer.MAX_VALUE; for (i = 0; i < n; i++) { nVal += op[i]; min = Math.min(min, nVal); // If k can be reduced with // first (i + 1) operations if ((k + nVal) <= 0) return (i + 1); } // Impossible to reduce k if (nVal >= 0) return -1; // Number of times all the operations // can be performed on k without // reducing it to <= 0 int times = (k - Math.abs(min)) / Math.abs(nVal); // Perform operations k = (k - (times * Math.abs(nVal))); count = (times * n); // Final check while (k > 0) { for (i = 0; i < n; i++) { k = k + op[i]; count++; if (k <= 0) break; } } return count; } // Driver code public static void main(String[] args) { int op[] = { -60, 65, -1, 14, -25 }; int n = op.length; int k = 100000; System.out.print(operations(op, n, k)); }}",
"e": 29143,
"s": 27760,
"text": null
},
{
"code": "# Python3 implementation of the approachdef operations(op, n, k): i, count = 0, 0 # To store the normalized value # of all the operations nVal = 0 # Minimum possible value for # a series of operations minimum = 10**9 for i in range(n): nVal += op[i] minimum = min(minimum , nVal) # If k can be reduced with # first (i + 1) operations if ((k + nVal) <= 0): return (i + 1) # Impossible to reduce k if (nVal >= 0): return -1 # Number of times all the operations # can be performed on k without # reducing it to <= 0 times = (k - abs(minimum )) // abs(nVal) # Perform operations k = (k - (times * abs(nVal))) count = (times * n) # Final check while (k > 0): for i in range(n): k = k + op[i] count += 1 if (k <= 0): break return count # Driver codeop = [-60, 65, -1, 14, -25]n = len(op)k = 100000 print(operations(op, n, k)) # This code is contributed# by mohit kumar",
"e": 30183,
"s": 29143,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ static int operations(int []op, int n, int k) { int i, count = 0; // To store the normalized value // of all the operations int nVal = 0; // Minimum possible value for // a series of operations int min = int.MaxValue; for (i = 0; i < n; i++) { nVal += op[i]; min = Math.Min(min, nVal); // If k can be reduced with // first (i + 1) operations if ((k + nVal) <= 0) return (i + 1); } // Impossible to reduce k if (nVal >= 0) return -1; // Number of times all the operations // can be performed on k without // reducing it to <= 0 int times = (k - Math.Abs(min)) / Math.Abs(nVal); // Perform operations k = (k - (times * Math.Abs(nVal))); count = (times * n); // Final check while (k > 0) { for (i = 0; i < n; i++) { k = k + op[i]; count++; if (k <= 0) break; } } return count; } // Driver code static void Main() { int []op = { -60, 65, -1, 14, -25 }; int n = op.Length; int k = 100000; Console.WriteLine(operations(op, n, k)); }} // This code is contributed by mits",
"e": 31614,
"s": 30183,
"text": null
},
{
"code": "<?php// PHP implementation of the approachfunction operations($op, $n, $k){ $count = 0; // To store the normalized value // of all the operations $nVal = 0; // Minimum possible value for // a series of operations $minimum = PHP_INT_MAX; for ($i = 0; $i < $n; $i++) { $nVal += $op[$i]; $minimum = min($minimum , $nVal); // If k can be reduced with // first (i + 1) operations if (($k + $nVal) <= 0) return ($i + 1); } // Impossible to reduce k if ($nVal >= 0) return -1; // Number of times all the operations // can be performed on k without // reducing it to <= 0 $times = round(($k - abs($minimum )) / abs($nVal)); // Perform operations $k = ($k - ($times * abs($nVal))); $count = ($times * $n); // Final check while ($k > 0) { for ($i = 0; $i < $n; $i++) { $k = $k + $op[$i]; $count++; if ($k <= 0) break; } } return $count;} // Driver code$op = array(-60, 65, -1, 14, -25 );$n = sizeof($op);$k = 100000; echo operations($op, $n, $k); // This code is contributed by ihritik?>",
"e": 32818,
"s": 31614,
"text": null
},
{
"code": "<script>// Javascript implementation of the approach function operations(op,n,k){ let i, count = 0; // To store the normalized value // of all the operations let nVal = 0; // Minimum possible value for // a series of operations let min = Number.MAX_VALUE; for (i = 0; i < n; i++) { nVal += op[i]; min = Math.min(min, nVal); // If k can be reduced with // first (i + 1) operations if ((k + nVal) <= 0) return (i + 1); } // Impossible to reduce k if (nVal >= 0) return -1; // Number of times all the operations // can be performed on k without // reducing it to <= 0 let times = Math.floor((k - Math.abs(min)) / Math.abs(nVal)); // Perform operations k = (k - (times * Math.abs(nVal))); count = (times * n); // Final check while (k > 0) { for (i = 0; i < n; i++) { k = k + op[i]; count++; if (k <= 0) break; } } return count;} // Driver code let op=[-60, 65, -1, 14, -25]; let n = op.length; let k = 100000; document.write(operations(op, n, k)); // This code is contributed by unknown2108.</script>",
"e": 34176,
"s": 32818,
"text": null
},
{
"code": null,
"e": 34182,
"s": 34176,
"text": "71391"
},
{
"code": null,
"e": 34197,
"s": 34184,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 34205,
"s": 34197,
"text": "ankthon"
},
{
"code": null,
"e": 34220,
"s": 34205,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 34228,
"s": 34220,
"text": "ihritik"
},
{
"code": null,
"e": 34240,
"s": 34228,
"text": "unknown2108"
},
{
"code": null,
"e": 34248,
"s": 34240,
"text": "Numbers"
},
{
"code": null,
"e": 34255,
"s": 34248,
"text": "Arrays"
},
{
"code": null,
"e": 34268,
"s": 34255,
"text": "Mathematical"
},
{
"code": null,
"e": 34278,
"s": 34268,
"text": "Searching"
},
{
"code": null,
"e": 34285,
"s": 34278,
"text": "Arrays"
},
{
"code": null,
"e": 34295,
"s": 34285,
"text": "Searching"
},
{
"code": null,
"e": 34308,
"s": 34295,
"text": "Mathematical"
},
{
"code": null,
"e": 34316,
"s": 34308,
"text": "Numbers"
},
{
"code": null,
"e": 34414,
"s": 34316,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34423,
"s": 34414,
"text": "Comments"
},
{
"code": null,
"e": 34436,
"s": 34423,
"text": "Old Comments"
},
{
"code": null,
"e": 34484,
"s": 34436,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 34528,
"s": 34484,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 34551,
"s": 34528,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 34583,
"s": 34551,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 34597,
"s": 34583,
"text": "Linear Search"
},
{
"code": null,
"e": 34627,
"s": 34597,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 34642,
"s": 34627,
"text": "C++ Data Types"
},
{
"code": null,
"e": 34702,
"s": 34642,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 34745,
"s": 34702,
"text": "Set in C++ Standard Template Library (STL)"
}
]
|
A Program to check if strings are rotations of each other or not - GeeksforGeeks | 21 Apr, 2022
Given a string s1 and a string s2, write a snippet to say whether s2 is a rotation of s1? (eg given s1 = ABCD and s2 = CDAB, return true, given s1 = ABCD, and s2 = ACBD , return false)
Algorithm: areRotations(str1, str2)
1. Create a temp string and store concatenation of str1 to
str1 in temp.
temp = str1.str1
2. If str2 is a substring of temp then str1 and str2 are
rotations of each other.
Example:
str1 = "ABACD"
str2 = "CDABA"
temp = str1.str1 = "ABACDABACD"
Since str2 is a substring of temp, str1 and str2 are
rotations of each other.
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to check if two given strings// are rotations of each other# include <bits/stdc++.h>using namespace std; /* Function checks if passed strings (str1 and str2) are rotations of each other */bool areRotations(string str1, string str2){ /* Check if sizes of two strings are same */ if (str1.length() != str2.length()) return false; string temp = str1 + str1; return (temp.find(str2) != string::npos);} /* Driver program to test areRotations */int main(){ string str1 = "AACD", str2 = "ACDA"; if (areRotations(str1, str2)) printf("Strings are rotations of each other"); else printf("Strings are not rotations of each other"); return 0;}
// C program to check if two given strings are rotations of// each other# include <stdio.h># include <string.h># include <stdlib.h> /* Function checks if passed strings (str1 and str2) are rotations of each other */int areRotations(char *str1, char *str2){ int size1 = strlen(str1); int size2 = strlen(str2); char *temp; void *ptr; /* Check if sizes of two strings are same */ if (size1 != size2) return 0; /* Create a temp string with value str1.str1 */ temp = (char *)malloc(sizeof(char)*(size1*2 + 1)); temp[0] = ''; strcat(temp, str1); strcat(temp, str1); /* Now check if str2 is a substring of temp */ ptr = strstr(temp, str2); free(temp); // Free dynamically allocated memory /* strstr returns NULL if the second string is NOT a substring of first string */ if (ptr != NULL) return 1; else return 0;} /* Driver program to test areRotations */int main(){ char *str1 = "AACD"; char *str2 = "ACDA"; if (areRotations(str1, str2)) printf("Strings are rotations of each other"); else printf("Strings are not rotations of each other"); getchar(); return 0;}
// Java program to check if two given strings are rotations of// each other class StringRotation{ /* Function checks if passed strings (str1 and str2) are rotations of each other */ static boolean areRotations(String str1, String str2) { // There lengths must be same and str2 must be // a substring of str1 concatenated with str1. return (str1.length() == str2.length()) && ((str1 + str1).indexOf(str2) != -1); } // Driver method public static void main (String[] args) { String str1 = "AACD"; String str2 = "ACDA"; if (areRotations(str1, str2)) System.out.println("Strings are rotations of each other"); else System.out.printf("Strings are not rotations of each other"); }}// This code is contributed by munjal
# Python program to check if strings are rotations of# each other or not # Function checks if passed strings (str1 and str2)# are rotations of each otherdef areRotations(string1, string2): size1 = len(string1) size2 = len(string2) temp = '' # Check if sizes of two strings are same if size1 != size2: return 0 # Create a temp string with value str1.str1 temp = string1 + string1 # Now check if str2 is a substring of temp # string.count returns the number of occurrences of # the second string in temp if (temp.count(string2)> 0): return 1 else: return 0 # Driver program to test the above functionstring1 = "AACD"string2 = "ACDA" if areRotations(string1, string2): print ("Strings are rotations of each other")else: print ("Strings are not rotations of each other") # This code is contributed by Bhavya Jain
// C# program to check if two given strings// are rotations of each otherusing System; class GFG { /* Function checks if passed strings (str1 and str2) are rotations of each other */ static bool areRotations(String str1, String str2) { // There lengths must be same and // str2 must be a substring of // str1 concatenated with str1. return (str1.Length == str2.Length ) && ((str1 + str1).IndexOf(str2) != -1); } // Driver method public static void Main () { String str1 = "FGABCDE"; String str2 = "ABCDEFG"; if (areRotations(str1, str2)) Console.Write("Strings are" + " rotation s of each other"); else Console.Write("Strings are " + "not rotations of each other"); }} // This code is contributed by nitin mittal.
<?php// Php program to check if// two given strings are// rotations of each other /* Function checks if passedstrings (str1 and str2) arerotations of each other */function areRotations($str1, $str2){/* Check if sizes of two strings are same */if (strlen($str1) != strlen($str2)){ return false;} $temp = $str1 + $str1;if ($temp.count($str2)> 0){ return true;}else{ return false;}} // Driver code$str1 = "AACD";$str2 = "ACDA";if (areRotations($str1, $str2)){ echo "Strings are rotations ". "of each other";}else{ echo "Strings are not " . "rotations of each other" ;} // This code is contributed// by Shivi_Aggarwal.?>
<script>// javascript program to check if two given strings are rotations of// each other /* Function checks if passed strings (str1 and str2) are rotations of each other */ function areRotations( str1, str2) { // There lengths must be same and str2 must be // a substring of str1 concatenated with str1. return (str1.length == str2.length) && ((str1 + str1).indexOf(str2) != -1); } // Driver method var str1 = "AACD"; var str2 = "ACDA"; if (areRotations(str1, str2)) document.write("Strings are rotations of each other"); else document.write("Strings are not rotations of each other"); // This code is contributed by umadevi9616</script>
Strings are rotations of each other
Method 2(Using STL):
Algorithm :
1. If the size of both the strings is not equal, then it can never be possible.
2. Push the original string into a queue q1.
3. Push the string to be checked inside another queue q2.
4. Keep popping q2‘s and pushing it back into it till the number of such operations are less than the size of the string.
5. If q2 becomes equal to q1 at any point during these operations, it is possible. Else not.
C++
Java
Python3
Javascript
#include <bits/stdc++.h>using namespace std;bool check_rotation(string s, string goal){ if (s.size() != goal.size()) return false; queue<char> q1; for (int i = 0; i < s.size(); i++) { q1.push(s[i]); } queue<char> q2; for (int i = 0; i < goal.size(); i++) { q2.push(goal[i]); } int k = goal.size(); while (k--) { char ch = q2.front(); q2.pop(); q2.push(ch); if (q2 == q1) return true; } return false;}int main(){ string s1 = "ABCD"; string s2 = "CDAB"; if (check_rotation(s1, s2)) cout << s2 << " is a rotated form of " << s1 << endl; else cout << s2 << " is not a rotated form of " << s1 << endl; string s3 = "ACBD"; if (check_rotation(s1, s3)) cout << s3 << " is a rotated form of " << s1 << endl; else cout << s3 << " is not a rotated form of " << s1 << endl; return 0;}
import java.util.*; class GFG{static boolean check_rotation(String s, String goal){ if (s.length() != goal.length()) ; Queue<Character> q1 = new LinkedList<>(); for (int i = 0; i < s.length(); i++) { q1.add(s.charAt(i)); } Queue<Character> q2 = new LinkedList<>(); for (int i = 0; i < goal.length(); i++) { q2.add(goal.charAt(i)); } int k = goal.length(); while (k>0) { k--; char ch = q2.peek(); q2.remove(); q2.add(ch); if (q2.equals(q1)) return true; } return false;}public static void main(String[] args){ String s1 = "ABCD"; String s2 = "CDAB"; if (check_rotation(s1, s2)) System.out.print(s2+ " is a rotated form of " + s1 +"\n"); else System.out.print(s2+ " is not a rotated form of " + s1 +"\n"); String s3 = "ACBD"; if (check_rotation(s1, s3)) System.out.print(s3+ " is a rotated form of " + s1 +"\n"); else System.out.print(s3+ " is not a rotated form of " + s1 +"\n");}} // This code is contributed by gauravrajput1
def check_rotation(s, goal): if (len(s) != len(goal)): skip q1 = [] for i in range(len(s)): q1.insert(0, s[i]) q2 = [] for i in range(len(goal)): q2.insert(0, goal[i]) k = len(goal) while (k > 0): ch = q2[0] q2.pop(0) q2.append(ch) if (q2 == q1): return True k -= 1 return False if __name__ == "__main__": s1 = "ABCD" s2 = "CDAB" if (check_rotation(s1, s2)): print(s2, " is a rotated form of ", s1) else: print(s2, " is not a rotated form of ", s1) s3 = "ACBD" if (check_rotation(s1, s3)): print(s3, " is a rotated form of ", s1) else: print(s3, " is not a rotated form of ", s1) # This code is contributed by ukasp.
<script> function check_rotation(s, goal){ if (s.length != goal.length){ return false; } let q1 = [] for(let i=0;i<s.length;i++) q1.push(s[i]) let q2 = [] for(let i=0;i<goal.length;i++) q2.push(goal[i]) let k = goal.length while (k--){ let ch = q2[0] q2.shift() q2.push(ch) if (JSON.stringify(q2) == JSON.stringify(q1)) return true } return false} // driver code let s1 = "ABCD"let s2 = "CDAB"if (check_rotation(s1, s2)) document.write(s2, " is a rotated form of ", s1,"</br>") else document.write(s2, " is not a rotated form of ", s1,"</br>") let s3 = "ACBD"if (check_rotation(s1, s3)) document.write(s3, " is a rotated form of ", s1,"</br>") else document.write(s3, " is not a rotated form of ", s1,"</br>") // This code is contributed by shinjanpatra. </script>
CDAB is a rotated form of ABCD
ACBD is not a rotated form of ABCD
Library Functions Used: strstr: strstr finds a sub-string within a string. Prototype: char * strstr(const char *s1, const char *s2); See http://www.lix.polytechnique.fr/Labo/Leo.Liberti/public/computing/prog/c/C/MAN/strstr.htm for more detailsstrcat: strncat concatenate two strings Prototype: char *strcat(char *dest, const char *src); See http://www.lix.polytechnique.fr/Labo/Leo.Liberti/public/computing/prog/c/C/MAN/strcat.htm for more details
Time Complexity: Time complexity of this problem depends on the implementation of strstr function. If the implementation of strstr is done using KMP matcher then complexity of the above program is (-)(n1 + n2) where n1 and n2 are lengths of strings. KMP matcher takes (-)(n) time to find a substring in a string of length n where length of substring is assumed to be smaller than the string.
Method 3:
Algorithm:
1.Find all the positions of first character of original string in the string to be checked.
2.For every position found, consider it to be the starting index of the string to be checked.
3.Beginning from the new starting index, compare both strings and check whether they are equal or not.
(Suppose original string to be s1,string to be checked be s2,n is length of strings and j is the position of first character of s1 in s2,
then for i < (length of original string) ,check if s1[i]==s2[(j+1)%n). Return false if any character mismatch is found, else return true.
4.Repeat 3rd step for all positions found.
C++
Python3
Javascript
#include <iostream>#include <vector>using namespace std; bool checkString(string &s1, string &s2, int indexFound, int Size){ for(int i=0;i<Size;i++){ //check whether the character is equal or not if(s1[i]!=s2[(indexFound+i)%Size])return false; // %Size keeps (indexFound+i) in bounds, since it ensures it's value is always less than Size } return true;} int main() { string s1="abcd"; string s2="cdab"; if(s1.length()!=s2.length()){ cout<<"s2 is not a rotation on s1"<<endl; } else{ vector<int> indexes; //store occurences of the first character of s1 int Size = s1.length(); char firstChar = s1[0]; for(int i=0;i<Size;i++) { if(s2[i]==firstChar) { indexes.push_back(i); } } bool isRotation=false; // check if the strings are rotation of each other for every occurence of firstChar in s2 for(int idx: indexes) { isRotation = checkString( s1, s2, idx, Size); if(isRotation) break; } if(isRotation)cout<<"s2 is rotation of s1"<<endl; else cout<<"s2 is not a rotation of s1"<<endl; } return 0;}
def checkString(s1, s2, indexFound, Size): for i in range(Size): # check whether the character is equal or not if(s1[i] != s2[(indexFound + i) % Size]): return False # %Size keeps (indexFound+i) in bounds, # since it ensures it's value is always less than Size return True # driver codes1 = "abcd"s2 = "cdab" if(len(s1) != len(s2)): print("s2 is not a rotation on s1") else: indexes = [] #store occurences of the first character of s1 Size = len(s1) firstChar = s1[0] for i in range(Size): if(s2[i] == firstChar): indexes.append(i) isRotation = False # check if the strings are rotation of each other # for every occurence of firstChar in s2 for idx in indexes: isRotation = checkString(s1, s2, idx, Size) if(isRotation): break if(isRotation): print("s2 is rotation of s1") else: print("s2 is not a rotation of s1") # This code is contributed by shinjanpatra
<script> function checkString(s1, s2, indexFound, Size){ for(let i = 0; i < Size; i++) { //check whether the character is equal or not if(s1[i] != s2[(indexFound + i) % Size])return false; // %Size keeps (indexFound+i) in bounds, since it ensures it's value is always less than Size } return true;} // driver codelet s1 = "abcd";let s2 = "cdab"; if(s1.length != s2.length){ document.write("s2 is not a rotation on s1");}else{ let indexes = []; //store occurences of the first character of s1 let Size = s1.length; let firstChar = s1[0]; for(let i = 0; i < Size; i++) { if(s2[i] == firstChar) { indexes.push(i); } } let isRotation = false; // check if the strings are rotation of each other for every occurence of firstChar in s2 for(let idx of indexes) { isRotation = checkString(s1, s2, idx, Size); if(isRotation) break; } if(isRotation)document.write("s2 is rotation of s1") else document.write("s2 is not a rotation of s1")} // This code is contributed by shinjanpatra </script>
s2 is rotation of s1
Time Complexity:
Time Complexity will be n*n in the worst case, where n is the length of the string.
YouTubeGeeksforGeeks501K subscribersA Program to check if strings are rotations of each other or not | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:12•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=-xX8WHd7Ztk" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
nitin mittal
Shivi_Aggarwal
nidhi_biet
adityamutharia
varshagumber28
umadevi9616
GauravRajput1
ukasp
vaibhavbansal642
amartyaghoshgfg
sakshisuryawanshi1234
shinjanpatra
ayush9460246125
rotation
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Convert string to char array in C++
Array of Strings in C++ (5 Different Ways to Create)
Caesar Cipher in Cryptography
Reverse words in a given string
Check whether two strings are anagram of each other
Length of the longest substring without repeating characters
Top 50 String Coding Problems for Interviews
Remove duplicates from a given string
How to split a string in C/C++, Python and Java?
Reverse string in Python (5 different ways) | [
{
"code": null,
"e": 25236,
"s": 25208,
"text": "\n21 Apr, 2022"
},
{
"code": null,
"e": 25421,
"s": 25236,
"text": "Given a string s1 and a string s2, write a snippet to say whether s2 is a rotation of s1? (eg given s1 = ABCD and s2 = CDAB, return true, given s1 = ABCD, and s2 = ACBD , return false)"
},
{
"code": null,
"e": 25457,
"s": 25421,
"text": "Algorithm: areRotations(str1, str2)"
},
{
"code": null,
"e": 25908,
"s": 25457,
"text": " 1. Create a temp string and store concatenation of str1 to\n str1 in temp.\n temp = str1.str1\n 2. If str2 is a substring of temp then str1 and str2 are \n rotations of each other.\n\n Example: \n str1 = \"ABACD\"\n str2 = \"CDABA\"\n\n temp = str1.str1 = \"ABACDABACD\"\n Since str2 is a substring of temp, str1 and str2 are \n rotations of each other."
},
{
"code": null,
"e": 25912,
"s": 25908,
"text": "C++"
},
{
"code": null,
"e": 25914,
"s": 25912,
"text": "C"
},
{
"code": null,
"e": 25919,
"s": 25914,
"text": "Java"
},
{
"code": null,
"e": 25927,
"s": 25919,
"text": "Python3"
},
{
"code": null,
"e": 25930,
"s": 25927,
"text": "C#"
},
{
"code": null,
"e": 25934,
"s": 25930,
"text": "PHP"
},
{
"code": null,
"e": 25945,
"s": 25934,
"text": "Javascript"
},
{
"code": "// C++ program to check if two given strings// are rotations of each other# include <bits/stdc++.h>using namespace std; /* Function checks if passed strings (str1 and str2) are rotations of each other */bool areRotations(string str1, string str2){ /* Check if sizes of two strings are same */ if (str1.length() != str2.length()) return false; string temp = str1 + str1; return (temp.find(str2) != string::npos);} /* Driver program to test areRotations */int main(){ string str1 = \"AACD\", str2 = \"ACDA\"; if (areRotations(str1, str2)) printf(\"Strings are rotations of each other\"); else printf(\"Strings are not rotations of each other\"); return 0;}",
"e": 26627,
"s": 25945,
"text": null
},
{
"code": "// C program to check if two given strings are rotations of// each other# include <stdio.h># include <string.h># include <stdlib.h> /* Function checks if passed strings (str1 and str2) are rotations of each other */int areRotations(char *str1, char *str2){ int size1 = strlen(str1); int size2 = strlen(str2); char *temp; void *ptr; /* Check if sizes of two strings are same */ if (size1 != size2) return 0; /* Create a temp string with value str1.str1 */ temp = (char *)malloc(sizeof(char)*(size1*2 + 1)); temp[0] = ''; strcat(temp, str1); strcat(temp, str1); /* Now check if str2 is a substring of temp */ ptr = strstr(temp, str2); free(temp); // Free dynamically allocated memory /* strstr returns NULL if the second string is NOT a substring of first string */ if (ptr != NULL) return 1; else return 0;} /* Driver program to test areRotations */int main(){ char *str1 = \"AACD\"; char *str2 = \"ACDA\"; if (areRotations(str1, str2)) printf(\"Strings are rotations of each other\"); else printf(\"Strings are not rotations of each other\"); getchar(); return 0;}",
"e": 27759,
"s": 26627,
"text": null
},
{
"code": "// Java program to check if two given strings are rotations of// each other class StringRotation{ /* Function checks if passed strings (str1 and str2) are rotations of each other */ static boolean areRotations(String str1, String str2) { // There lengths must be same and str2 must be // a substring of str1 concatenated with str1. return (str1.length() == str2.length()) && ((str1 + str1).indexOf(str2) != -1); } // Driver method public static void main (String[] args) { String str1 = \"AACD\"; String str2 = \"ACDA\"; if (areRotations(str1, str2)) System.out.println(\"Strings are rotations of each other\"); else System.out.printf(\"Strings are not rotations of each other\"); }}// This code is contributed by munjal",
"e": 28595,
"s": 27759,
"text": null
},
{
"code": "# Python program to check if strings are rotations of# each other or not # Function checks if passed strings (str1 and str2)# are rotations of each otherdef areRotations(string1, string2): size1 = len(string1) size2 = len(string2) temp = '' # Check if sizes of two strings are same if size1 != size2: return 0 # Create a temp string with value str1.str1 temp = string1 + string1 # Now check if str2 is a substring of temp # string.count returns the number of occurrences of # the second string in temp if (temp.count(string2)> 0): return 1 else: return 0 # Driver program to test the above functionstring1 = \"AACD\"string2 = \"ACDA\" if areRotations(string1, string2): print (\"Strings are rotations of each other\")else: print (\"Strings are not rotations of each other\") # This code is contributed by Bhavya Jain",
"e": 29470,
"s": 28595,
"text": null
},
{
"code": "// C# program to check if two given strings// are rotations of each otherusing System; class GFG { /* Function checks if passed strings (str1 and str2) are rotations of each other */ static bool areRotations(String str1, String str2) { // There lengths must be same and // str2 must be a substring of // str1 concatenated with str1. return (str1.Length == str2.Length ) && ((str1 + str1).IndexOf(str2) != -1); } // Driver method public static void Main () { String str1 = \"FGABCDE\"; String str2 = \"ABCDEFG\"; if (areRotations(str1, str2)) Console.Write(\"Strings are\" + \" rotation s of each other\"); else Console.Write(\"Strings are \" + \"not rotations of each other\"); }} // This code is contributed by nitin mittal.",
"e": 30413,
"s": 29470,
"text": null
},
{
"code": "<?php// Php program to check if// two given strings are// rotations of each other /* Function checks if passedstrings (str1 and str2) arerotations of each other */function areRotations($str1, $str2){/* Check if sizes of two strings are same */if (strlen($str1) != strlen($str2)){ return false;} $temp = $str1 + $str1;if ($temp.count($str2)> 0){ return true;}else{ return false;}} // Driver code$str1 = \"AACD\";$str2 = \"ACDA\";if (areRotations($str1, $str2)){ echo \"Strings are rotations \". \"of each other\";}else{ echo \"Strings are not \" . \"rotations of each other\" ;} // This code is contributed// by Shivi_Aggarwal.?>",
"e": 31080,
"s": 30413,
"text": null
},
{
"code": "<script>// javascript program to check if two given strings are rotations of// each other /* Function checks if passed strings (str1 and str2) are rotations of each other */ function areRotations( str1, str2) { // There lengths must be same and str2 must be // a substring of str1 concatenated with str1. return (str1.length == str2.length) && ((str1 + str1).indexOf(str2) != -1); } // Driver method var str1 = \"AACD\"; var str2 = \"ACDA\"; if (areRotations(str1, str2)) document.write(\"Strings are rotations of each other\"); else document.write(\"Strings are not rotations of each other\"); // This code is contributed by umadevi9616</script>",
"e": 31835,
"s": 31080,
"text": null
},
{
"code": null,
"e": 31871,
"s": 31835,
"text": "Strings are rotations of each other"
},
{
"code": null,
"e": 31892,
"s": 31871,
"text": "Method 2(Using STL):"
},
{
"code": null,
"e": 31904,
"s": 31892,
"text": "Algorithm :"
},
{
"code": null,
"e": 31984,
"s": 31904,
"text": "1. If the size of both the strings is not equal, then it can never be possible."
},
{
"code": null,
"e": 32029,
"s": 31984,
"text": "2. Push the original string into a queue q1."
},
{
"code": null,
"e": 32087,
"s": 32029,
"text": "3. Push the string to be checked inside another queue q2."
},
{
"code": null,
"e": 32210,
"s": 32087,
"text": " 4. Keep popping q2‘s and pushing it back into it till the number of such operations are less than the size of the string."
},
{
"code": null,
"e": 32303,
"s": 32210,
"text": "5. If q2 becomes equal to q1 at any point during these operations, it is possible. Else not."
},
{
"code": null,
"e": 32307,
"s": 32303,
"text": "C++"
},
{
"code": null,
"e": 32312,
"s": 32307,
"text": "Java"
},
{
"code": null,
"e": 32320,
"s": 32312,
"text": "Python3"
},
{
"code": null,
"e": 32331,
"s": 32320,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std;bool check_rotation(string s, string goal){ if (s.size() != goal.size()) return false; queue<char> q1; for (int i = 0; i < s.size(); i++) { q1.push(s[i]); } queue<char> q2; for (int i = 0; i < goal.size(); i++) { q2.push(goal[i]); } int k = goal.size(); while (k--) { char ch = q2.front(); q2.pop(); q2.push(ch); if (q2 == q1) return true; } return false;}int main(){ string s1 = \"ABCD\"; string s2 = \"CDAB\"; if (check_rotation(s1, s2)) cout << s2 << \" is a rotated form of \" << s1 << endl; else cout << s2 << \" is not a rotated form of \" << s1 << endl; string s3 = \"ACBD\"; if (check_rotation(s1, s3)) cout << s3 << \" is a rotated form of \" << s1 << endl; else cout << s3 << \" is not a rotated form of \" << s1 << endl; return 0;}",
"e": 33297,
"s": 32331,
"text": null
},
{
"code": "import java.util.*; class GFG{static boolean check_rotation(String s, String goal){ if (s.length() != goal.length()) ; Queue<Character> q1 = new LinkedList<>(); for (int i = 0; i < s.length(); i++) { q1.add(s.charAt(i)); } Queue<Character> q2 = new LinkedList<>(); for (int i = 0; i < goal.length(); i++) { q2.add(goal.charAt(i)); } int k = goal.length(); while (k>0) { k--; char ch = q2.peek(); q2.remove(); q2.add(ch); if (q2.equals(q1)) return true; } return false;}public static void main(String[] args){ String s1 = \"ABCD\"; String s2 = \"CDAB\"; if (check_rotation(s1, s2)) System.out.print(s2+ \" is a rotated form of \" + s1 +\"\\n\"); else System.out.print(s2+ \" is not a rotated form of \" + s1 +\"\\n\"); String s3 = \"ACBD\"; if (check_rotation(s1, s3)) System.out.print(s3+ \" is a rotated form of \" + s1 +\"\\n\"); else System.out.print(s3+ \" is not a rotated form of \" + s1 +\"\\n\");}} // This code is contributed by gauravrajput1",
"e": 34424,
"s": 33297,
"text": null
},
{
"code": "def check_rotation(s, goal): if (len(s) != len(goal)): skip q1 = [] for i in range(len(s)): q1.insert(0, s[i]) q2 = [] for i in range(len(goal)): q2.insert(0, goal[i]) k = len(goal) while (k > 0): ch = q2[0] q2.pop(0) q2.append(ch) if (q2 == q1): return True k -= 1 return False if __name__ == \"__main__\": s1 = \"ABCD\" s2 = \"CDAB\" if (check_rotation(s1, s2)): print(s2, \" is a rotated form of \", s1) else: print(s2, \" is not a rotated form of \", s1) s3 = \"ACBD\" if (check_rotation(s1, s3)): print(s3, \" is a rotated form of \", s1) else: print(s3, \" is not a rotated form of \", s1) # This code is contributed by ukasp.",
"e": 35200,
"s": 34424,
"text": null
},
{
"code": "<script> function check_rotation(s, goal){ if (s.length != goal.length){ return false; } let q1 = [] for(let i=0;i<s.length;i++) q1.push(s[i]) let q2 = [] for(let i=0;i<goal.length;i++) q2.push(goal[i]) let k = goal.length while (k--){ let ch = q2[0] q2.shift() q2.push(ch) if (JSON.stringify(q2) == JSON.stringify(q1)) return true } return false} // driver code let s1 = \"ABCD\"let s2 = \"CDAB\"if (check_rotation(s1, s2)) document.write(s2, \" is a rotated form of \", s1,\"</br>\") else document.write(s2, \" is not a rotated form of \", s1,\"</br>\") let s3 = \"ACBD\"if (check_rotation(s1, s3)) document.write(s3, \" is a rotated form of \", s1,\"</br>\") else document.write(s3, \" is not a rotated form of \", s1,\"</br>\") // This code is contributed by shinjanpatra. </script>",
"e": 36073,
"s": 35200,
"text": null
},
{
"code": null,
"e": 36139,
"s": 36073,
"text": "CDAB is a rotated form of ABCD\nACBD is not a rotated form of ABCD"
},
{
"code": null,
"e": 36587,
"s": 36139,
"text": "Library Functions Used: strstr: strstr finds a sub-string within a string. Prototype: char * strstr(const char *s1, const char *s2); See http://www.lix.polytechnique.fr/Labo/Leo.Liberti/public/computing/prog/c/C/MAN/strstr.htm for more detailsstrcat: strncat concatenate two strings Prototype: char *strcat(char *dest, const char *src); See http://www.lix.polytechnique.fr/Labo/Leo.Liberti/public/computing/prog/c/C/MAN/strcat.htm for more details"
},
{
"code": null,
"e": 36980,
"s": 36587,
"text": "Time Complexity: Time complexity of this problem depends on the implementation of strstr function. If the implementation of strstr is done using KMP matcher then complexity of the above program is (-)(n1 + n2) where n1 and n2 are lengths of strings. KMP matcher takes (-)(n) time to find a substring in a string of length n where length of substring is assumed to be smaller than the string. "
},
{
"code": null,
"e": 36990,
"s": 36980,
"text": "Method 3:"
},
{
"code": null,
"e": 37001,
"s": 36990,
"text": "Algorithm:"
},
{
"code": null,
"e": 37093,
"s": 37001,
"text": "1.Find all the positions of first character of original string in the string to be checked."
},
{
"code": null,
"e": 37187,
"s": 37093,
"text": "2.For every position found, consider it to be the starting index of the string to be checked."
},
{
"code": null,
"e": 37290,
"s": 37187,
"text": "3.Beginning from the new starting index, compare both strings and check whether they are equal or not."
},
{
"code": null,
"e": 37428,
"s": 37290,
"text": "(Suppose original string to be s1,string to be checked be s2,n is length of strings and j is the position of first character of s1 in s2,"
},
{
"code": null,
"e": 37571,
"s": 37428,
"text": " then for i < (length of original string) ,check if s1[i]==s2[(j+1)%n). Return false if any character mismatch is found, else return true."
},
{
"code": null,
"e": 37614,
"s": 37571,
"text": "4.Repeat 3rd step for all positions found."
},
{
"code": null,
"e": 37618,
"s": 37614,
"text": "C++"
},
{
"code": null,
"e": 37626,
"s": 37618,
"text": "Python3"
},
{
"code": null,
"e": 37637,
"s": 37626,
"text": "Javascript"
},
{
"code": "#include <iostream>#include <vector>using namespace std; bool checkString(string &s1, string &s2, int indexFound, int Size){ for(int i=0;i<Size;i++){ //check whether the character is equal or not if(s1[i]!=s2[(indexFound+i)%Size])return false; // %Size keeps (indexFound+i) in bounds, since it ensures it's value is always less than Size } return true;} int main() { string s1=\"abcd\"; string s2=\"cdab\"; if(s1.length()!=s2.length()){ cout<<\"s2 is not a rotation on s1\"<<endl; } else{ vector<int> indexes; //store occurences of the first character of s1 int Size = s1.length(); char firstChar = s1[0]; for(int i=0;i<Size;i++) { if(s2[i]==firstChar) { indexes.push_back(i); } } bool isRotation=false; // check if the strings are rotation of each other for every occurence of firstChar in s2 for(int idx: indexes) { isRotation = checkString( s1, s2, idx, Size); if(isRotation) break; } if(isRotation)cout<<\"s2 is rotation of s1\"<<endl; else cout<<\"s2 is not a rotation of s1\"<<endl; } return 0;}",
"e": 38867,
"s": 37637,
"text": null
},
{
"code": "def checkString(s1, s2, indexFound, Size): for i in range(Size): # check whether the character is equal or not if(s1[i] != s2[(indexFound + i) % Size]): return False # %Size keeps (indexFound+i) in bounds, # since it ensures it's value is always less than Size return True # driver codes1 = \"abcd\"s2 = \"cdab\" if(len(s1) != len(s2)): print(\"s2 is not a rotation on s1\") else: indexes = [] #store occurences of the first character of s1 Size = len(s1) firstChar = s1[0] for i in range(Size): if(s2[i] == firstChar): indexes.append(i) isRotation = False # check if the strings are rotation of each other # for every occurence of firstChar in s2 for idx in indexes: isRotation = checkString(s1, s2, idx, Size) if(isRotation): break if(isRotation): print(\"s2 is rotation of s1\") else: print(\"s2 is not a rotation of s1\") # This code is contributed by shinjanpatra",
"e": 39885,
"s": 38867,
"text": null
},
{
"code": "<script> function checkString(s1, s2, indexFound, Size){ for(let i = 0; i < Size; i++) { //check whether the character is equal or not if(s1[i] != s2[(indexFound + i) % Size])return false; // %Size keeps (indexFound+i) in bounds, since it ensures it's value is always less than Size } return true;} // driver codelet s1 = \"abcd\";let s2 = \"cdab\"; if(s1.length != s2.length){ document.write(\"s2 is not a rotation on s1\");}else{ let indexes = []; //store occurences of the first character of s1 let Size = s1.length; let firstChar = s1[0]; for(let i = 0; i < Size; i++) { if(s2[i] == firstChar) { indexes.push(i); } } let isRotation = false; // check if the strings are rotation of each other for every occurence of firstChar in s2 for(let idx of indexes) { isRotation = checkString(s1, s2, idx, Size); if(isRotation) break; } if(isRotation)document.write(\"s2 is rotation of s1\") else document.write(\"s2 is not a rotation of s1\")} // This code is contributed by shinjanpatra </script>",
"e": 41024,
"s": 39885,
"text": null
},
{
"code": null,
"e": 41045,
"s": 41024,
"text": "s2 is rotation of s1"
},
{
"code": null,
"e": 41062,
"s": 41045,
"text": "Time Complexity:"
},
{
"code": null,
"e": 41146,
"s": 41062,
"text": "Time Complexity will be n*n in the worst case, where n is the length of the string."
},
{
"code": null,
"e": 42009,
"s": 41146,
"text": "YouTubeGeeksforGeeks501K subscribersA Program to check if strings are rotations of each other or not | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:12•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=-xX8WHd7Ztk\" 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": 42022,
"s": 42009,
"text": "nitin mittal"
},
{
"code": null,
"e": 42037,
"s": 42022,
"text": "Shivi_Aggarwal"
},
{
"code": null,
"e": 42048,
"s": 42037,
"text": "nidhi_biet"
},
{
"code": null,
"e": 42063,
"s": 42048,
"text": "adityamutharia"
},
{
"code": null,
"e": 42078,
"s": 42063,
"text": "varshagumber28"
},
{
"code": null,
"e": 42090,
"s": 42078,
"text": "umadevi9616"
},
{
"code": null,
"e": 42104,
"s": 42090,
"text": "GauravRajput1"
},
{
"code": null,
"e": 42110,
"s": 42104,
"text": "ukasp"
},
{
"code": null,
"e": 42127,
"s": 42110,
"text": "vaibhavbansal642"
},
{
"code": null,
"e": 42143,
"s": 42127,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 42165,
"s": 42143,
"text": "sakshisuryawanshi1234"
},
{
"code": null,
"e": 42178,
"s": 42165,
"text": "shinjanpatra"
},
{
"code": null,
"e": 42194,
"s": 42178,
"text": "ayush9460246125"
},
{
"code": null,
"e": 42203,
"s": 42194,
"text": "rotation"
},
{
"code": null,
"e": 42211,
"s": 42203,
"text": "Strings"
},
{
"code": null,
"e": 42219,
"s": 42211,
"text": "Strings"
},
{
"code": null,
"e": 42317,
"s": 42219,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 42326,
"s": 42317,
"text": "Comments"
},
{
"code": null,
"e": 42339,
"s": 42326,
"text": "Old Comments"
},
{
"code": null,
"e": 42375,
"s": 42339,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 42428,
"s": 42375,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
},
{
"code": null,
"e": 42458,
"s": 42428,
"text": "Caesar Cipher in Cryptography"
},
{
"code": null,
"e": 42490,
"s": 42458,
"text": "Reverse words in a given string"
},
{
"code": null,
"e": 42542,
"s": 42490,
"text": "Check whether two strings are anagram of each other"
},
{
"code": null,
"e": 42603,
"s": 42542,
"text": "Length of the longest substring without repeating characters"
},
{
"code": null,
"e": 42648,
"s": 42603,
"text": "Top 50 String Coding Problems for Interviews"
},
{
"code": null,
"e": 42686,
"s": 42648,
"text": "Remove duplicates from a given string"
},
{
"code": null,
"e": 42735,
"s": 42686,
"text": "How to split a string in C/C++, Python and Java?"
}
]
|
How to create an image bullets in HTML ? - GeeksforGeeks | 12 Jan, 2021
In this article, we have given some list items and the task is to create a list items with image bullets. This task can be done by using the list-style-image property in CSS. This property is used to set the image that will be used as the list item marker.
Syntax:
list-style-image: url;
Example: Below code illustrates that how to create image bullets using css.
HTML
<!DOCTYPE html><html> <head> <title> How to create an image bullets in HTML? </title> <style> ul { list-style-image: url("https://contribute.geeksforgeeks.org/wp-content/uploads/listitem-1.png"); } </style></head> <body> <h1 style="color:green;"> GeeksforGeeks </h1> <h2> How to create an image bullets in HTML? </h2> <p>List of fruits</p> <ul> <li>apple</li> <li>mango</li> <li>banana</li> <li>grapes</li> <li>papaya</li> </ul></body> </html>
Output
Supported Browsers are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
CSS-Misc
HTML-Misc
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Design a web page using HTML and CSS
Form validation using jQuery
How to set space between the flexbox ?
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
How to Insert Form Data into Database using PHP ?
Hide or show elements in HTML using display property
REST API (Introduction) | [
{
"code": null,
"e": 25376,
"s": 25348,
"text": "\n12 Jan, 2021"
},
{
"code": null,
"e": 25637,
"s": 25376,
"text": "In this article, we have given some list items and the task is to create a list items with image bullets. This task can be done by using the list-style-image property in CSS. This property is used to set the image that will be used as the list item marker. "
},
{
"code": null,
"e": 25645,
"s": 25637,
"text": "Syntax:"
},
{
"code": null,
"e": 25669,
"s": 25645,
"text": "list-style-image: url; "
},
{
"code": null,
"e": 25747,
"s": 25669,
"text": "Example: Below code illustrates that how to create image bullets using css. "
},
{
"code": null,
"e": 25752,
"s": 25747,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to create an image bullets in HTML? </title> <style> ul { list-style-image: url(\"https://contribute.geeksforgeeks.org/wp-content/uploads/listitem-1.png\"); } </style></head> <body> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h2> How to create an image bullets in HTML? </h2> <p>List of fruits</p> <ul> <li>apple</li> <li>mango</li> <li>banana</li> <li>grapes</li> <li>papaya</li> </ul></body> </html>",
"e": 26325,
"s": 25752,
"text": null
},
{
"code": null,
"e": 26334,
"s": 26325,
"text": "Output "
},
{
"code": null,
"e": 26371,
"s": 26334,
"text": "Supported Browsers are listed below:"
},
{
"code": null,
"e": 26385,
"s": 26371,
"text": "Google Chrome"
},
{
"code": null,
"e": 26403,
"s": 26385,
"text": "Internet Explorer"
},
{
"code": null,
"e": 26411,
"s": 26403,
"text": "Firefox"
},
{
"code": null,
"e": 26418,
"s": 26411,
"text": "Safari"
},
{
"code": null,
"e": 26424,
"s": 26418,
"text": "Opera"
},
{
"code": null,
"e": 26561,
"s": 26424,
"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": 26570,
"s": 26561,
"text": "CSS-Misc"
},
{
"code": null,
"e": 26580,
"s": 26570,
"text": "HTML-Misc"
},
{
"code": null,
"e": 26584,
"s": 26580,
"text": "CSS"
},
{
"code": null,
"e": 26589,
"s": 26584,
"text": "HTML"
},
{
"code": null,
"e": 26606,
"s": 26589,
"text": "Web Technologies"
},
{
"code": null,
"e": 26611,
"s": 26606,
"text": "HTML"
},
{
"code": null,
"e": 26709,
"s": 26611,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26718,
"s": 26709,
"text": "Comments"
},
{
"code": null,
"e": 26731,
"s": 26718,
"text": "Old Comments"
},
{
"code": null,
"e": 26768,
"s": 26731,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 26797,
"s": 26768,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 26836,
"s": 26797,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 26878,
"s": 26836,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 26913,
"s": 26878,
"text": "How to style a checkbox using CSS?"
},
{
"code": null,
"e": 26973,
"s": 26913,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 27034,
"s": 26973,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 27084,
"s": 27034,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 27137,
"s": 27084,
"text": "Hide or show elements in HTML using display property"
}
]
|
How to get the list of all COBOL-DB2 programs using a DB2 table TAB1? | SYSIBM.SYSTABAUTH is a DB2 system table which records the privileges that users/program hold on tables and views. We can use this table to find out the list of programs accessing a particular table and what action the program is performing on the table like SELECT, UPDATE, INSERT or DELETE. The below SQL query can be fired on SYSTABAUTH in order to get list of programs.
SELECT GRANTEE, SELECTAUTH, UPDATEAUTH, INSERTAUTH, DELETEAUTH FROM SYSIBM.SYSABAUTH
WHERE GRANTEETYPE = ‘P’ AND TNAME = ‘TAB1’
The column SELECTAUTH, UPDATEAUTH, INSERTAUTH and DELETEAUTH represents SELECT, UPDATE, INSERT and DELETE authority respectively. In the WHERE clause we will add a GRANTEETYPE predicate as ‘P’ to make sure only program names are returned (and not the users). We can give the table name predicate for the TNAME column. | [
{
"code": null,
"e": 1435,
"s": 1062,
"text": "SYSIBM.SYSTABAUTH is a DB2 system table which records the privileges that users/program hold on tables and views. We can use this table to find out the list of programs accessing a particular table and what action the program is performing on the table like SELECT, UPDATE, INSERT or DELETE. The below SQL query can be fired on SYSTABAUTH in order to get list of programs."
},
{
"code": null,
"e": 1563,
"s": 1435,
"text": "SELECT GRANTEE, SELECTAUTH, UPDATEAUTH, INSERTAUTH, DELETEAUTH FROM SYSIBM.SYSABAUTH\nWHERE GRANTEETYPE = ‘P’ AND TNAME = ‘TAB1’"
},
{
"code": null,
"e": 1881,
"s": 1563,
"text": "The column SELECTAUTH, UPDATEAUTH, INSERTAUTH and DELETEAUTH represents SELECT, UPDATE, INSERT and DELETE authority respectively. In the WHERE clause we will add a GRANTEETYPE predicate as ‘P’ to make sure only program names are returned (and not the users). We can give the table name predicate for the TNAME column."
}
]
|
Elasticsearch - Quick Guide | Elasticsearch is an Apache Lucene-based search server. It was developed by Shay Banon and published in 2010. It is now maintained by Elasticsearch BV. Its latest version is 7.0.0.
Elasticsearch is a real-time distributed and open source full-text search and analytics engine. It is accessible from RESTful web service interface and uses schema less JSON (JavaScript Object Notation) documents to store data. It is built on Java programming language and hence Elasticsearch can run on different platforms. It enables users to explore very large amount of data at very high speed.
The general features of Elasticsearch are as follows −
Elasticsearch is scalable up to petabytes of structured and unstructured data.
Elasticsearch is scalable up to petabytes of structured and unstructured data.
Elasticsearch can be used as a replacement of document stores like MongoDB and RavenDB.
Elasticsearch can be used as a replacement of document stores like MongoDB and RavenDB.
Elasticsearch uses denormalization to improve the search performance.
Elasticsearch uses denormalization to improve the search performance.
Elasticsearch is one of the popular enterprise search engines, and is currently being used by many big organizations like Wikipedia, The Guardian, StackOverflow, GitHub etc.
Elasticsearch is one of the popular enterprise search engines, and is currently being used by many big organizations like Wikipedia, The Guardian, StackOverflow, GitHub etc.
Elasticsearch is an open source and available under the Apache license version 2.0.
Elasticsearch is an open source and available under the Apache license version 2.0.
The key concepts of Elasticsearch are as follows −
It refers to a single running instance of Elasticsearch. Single physical and virtual server accommodates multiple nodes depending upon the capabilities of their physical resources like RAM, storage and processing power.
It is a collection of one or more nodes. Cluster provides collective indexing and search capabilities across all the nodes for entire data.
It is a collection of different type of documents and their properties. Index also uses the concept of shards to improve the performance. For example, a set of document contains data of a social networking application.
It is a collection of fields in a specific manner defined in JSON format. Every document belongs to a type and resides inside an index. Every document is associated with a unique identifier called the UID.
Indexes are horizontally subdivided into shards. This means each shard contains all the properties of document but contains less number of JSON objects than index. The horizontal separation makes shard an independent node, which can be store in any node. Primary shard is the original horizontal part of an index and then these primary shards are replicated into replica shards.
Elasticsearch allows a user to create replicas of their indexes and shards. Replication not only helps in increasing the availability of data in case of failure, but also improves the performance of searching by carrying out a parallel search operation in these replicas.
Elasticsearch is developed on Java, which makes it compatible on almost every platform.
Elasticsearch is developed on Java, which makes it compatible on almost every platform.
Elasticsearch is real time, in other words after one second the added document is searchable in this engine
Elasticsearch is real time, in other words after one second the added document is searchable in this engine
Elasticsearch is distributed, which makes it easy to scale and integrate in any big organization.
Elasticsearch is distributed, which makes it easy to scale and integrate in any big organization.
Creating full backups are easy by using the concept of gateway, which is present in Elasticsearch.
Creating full backups are easy by using the concept of gateway, which is present in Elasticsearch.
Handling multi-tenancy is very easy in Elasticsearch when compared to Apache Solr.
Handling multi-tenancy is very easy in Elasticsearch when compared to Apache Solr.
Elasticsearch uses JSON objects as responses, which makes it possible to invoke the Elasticsearch server with a large number of different programming languages.
Elasticsearch uses JSON objects as responses, which makes it possible to invoke the Elasticsearch server with a large number of different programming languages.
Elasticsearch supports almost every document type except those that do not support text rendering.
Elasticsearch supports almost every document type except those that do not support text rendering.
Elasticsearch does not have multi-language support in terms of handling request and response data (only possible in JSON) unlike in Apache Solr, where it is possible in CSV, XML and JSON formats.
Elasticsearch does not have multi-language support in terms of handling request and response data (only possible in JSON) unlike in Apache Solr, where it is possible in CSV, XML and JSON formats.
Occasionally, Elasticsearch has a problem of Split brain situations.
Occasionally, Elasticsearch has a problem of Split brain situations.
In Elasticsearch, index is similar to tables in RDBMS (Relation Database Management System). Every table is a collection of rows just as every index is a collection of documents in Elasticsearch.
The following table gives a direct comparison between these terms−
In this chapter, we will understand the installation procedure of Elasticsearch in detail.
To install Elasticsearch on your local computer, you will have to follow the steps given below −
Step 1 − Check the version of java installed on your computer. It should be java 7 or higher. You can check by doing the following −
In Windows Operating System (OS) (using command prompt)−
> java -version
In UNIX OS (Using Terminal) −
$ echo $JAVA_HOME
Step 2 − Depending on your operating system, download Elasticsearch from www.elastic.co as mentioned below −
For windows OS, download ZIP file.
For windows OS, download ZIP file.
For UNIX OS, download TAR file.
For UNIX OS, download TAR file.
For Debian OS, download DEB file.
For Debian OS, download DEB file.
For Red Hat and other Linux distributions, download RPN file.
For Red Hat and other Linux distributions, download RPN file.
APT and Yum utilities can also be used to install Elasticsearch in many Linux distributions.
APT and Yum utilities can also be used to install Elasticsearch in many Linux distributions.
Step 3 − Installation process for Elasticsearch is simple and is described below for different OS −
Windows OS− Unzip the zip package and the Elasticsearch is installed.
Windows OS− Unzip the zip package and the Elasticsearch is installed.
UNIX OS− Extract tar file in any location and the Elasticsearch is installed.
UNIX OS− Extract tar file in any location and the Elasticsearch is installed.
$wget
https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch7.0.0-linux-x86_64.tar.gz
$tar -xzf elasticsearch-7.0.0-linux-x86_64.tar.gz
Using APT utility for Linux OS− Download and install the Public Signing Key
Using APT utility for Linux OS− Download and install the Public Signing Key
$ wget -qo - https://artifacts.elastic.co/GPG-KEY-elasticsearch | sudo
apt-key add -
Save the repository definition as shown below −
$ echo "deb https://artifacts.elastic.co/packages/7.x/apt stable main" |
sudo tee -a /etc/apt/sources.list.d/elastic-7.x.list
Run update using the following command −
$ sudo apt-get update
Now you can install by using the following command −
$ sudo apt-get install elasticsearch
Download and install the Debian package manually using the command given here −
Download and install the Debian package manually using the command given here −
$wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch7.0.0-amd64.deb
$sudo dpkg -i elasticsearch-7.0.0-amd64.deb0
Using YUM utility for Debian Linux OS
Using YUM utility for Debian Linux OS
Download and install the Public Signing Key −
$ rpm --import https://artifacts.elastic.co/GPG-KEY-elasticsearch
ADD the following text in the file with .repo suffix in your “/etc/yum.repos.d/” directory. For example, elasticsearch.repo
ADD the following text in the file with .repo suffix in your “/etc/yum.repos.d/” directory. For example, elasticsearch.repo
elasticsearch-7.x]
name=Elasticsearch repository for 7.x packages
baseurl=https://artifacts.elastic.co/packages/7.x/yum
gpgcheck=1
gpgkey=https://artifacts.elastic.co/GPG-KEY-elasticsearch
enabled=1
autorefresh=1
type=rpm-md
You can now install Elasticsearch by using the following command
You can now install Elasticsearch by using the following command
sudo yum install elasticsearch
Step 4 − Go to the Elasticsearch home directory and inside the bin folder. Run the
elasticsearch.bat file in case of Windows or you can do the same using command prompt and through terminal in case of UNIX rum Elasticsearch file.
> cd elasticsearch-2.1.0/bin
> elasticsearch
$ cd elasticsearch-2.1.0/bin
$ ./elasticsearch
Note − In case of windows, you might get an error stating JAVA_HOME is not set, please
set it in environment variables to “C:\Program Files\Java\jre1.8.0_31” or the location where you installed java.
Step 5 − The default port for Elasticsearch web interface is 9200 or you can change it by
changing http.port inside the elasticsearch.yml file present in bin directory. You can check if the server is up and running by browsing http://localhost:9200. It will return a JSON object, which contains the information about the installed Elasticsearch in the following manner −
{
"name" : "Brain-Child",
"cluster_name" : "elasticsearch", "version" : {
"number" : "2.1.0",
"build_hash" : "72cd1f1a3eee09505e036106146dc1949dc5dc87",
"build_timestamp" : "2015-11-18T22:40:03Z",
"build_snapshot" : false,
"lucene_version" : "5.3.1"
},
"tagline" : "You Know, for Search"
}
Step 6 − In this step, let us install Kibana. Follow the respective code given below for
installing on Linux and Windows −
For Installation on Linux −
wget https://artifacts.elastic.co/downloads/kibana/kibana-7.0.0-linuxx86_64.tar.gz
tar -xzf kibana-7.0.0-linux-x86_64.tar.gz
cd kibana-7.0.0-linux-x86_64/
./bin/kibana
For Installation on Windows −
Download Kibana for Windows from https://www.elastic.co/products/kibana. Once you click the link, you will find the home page as shown below −
Unzip and go to the Kibana home directory and then run it.
CD c:\kibana-7.0.0-windows-x86_64
.\bin\kibana.bat
In this chapter, let us learn how to add some index, mapping and data to Elasticsearch. Note that some of this data will be used in the examples explained in this tutorial.
You can use the following command to create an index −
PUT school
If the index is created, you can see the following output −
{"acknowledged": true}
Elasticsearch will store the documents we add to the index as shown in the following code. The documents are given some IDs which are used in identifying the document.
POST school/_doc/10
{
"name":"Saint Paul School", "description":"ICSE Afiliation",
"street":"Dawarka", "city":"Delhi", "state":"Delhi", "zip":"110075",
"location":[28.5733056, 77.0122136], "fees":5000,
"tags":["Good Faculty", "Great Sports"], "rating":"4.5"
}
{
"_index" : "school",
"_type" : "_doc",
"_id" : "10",
"_version" : 1,
"result" : "created",
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 2,
"_primary_term" : 1
}
Here, we are adding another similar document.
POST school/_doc/16
{
"name":"Crescent School", "description":"State Board Affiliation",
"street":"Tonk Road",
"city":"Jaipur", "state":"RJ", "zip":"176114","location":[26.8535922,75.7923988],
"fees":2500, "tags":["Well equipped labs"], "rating":"4.5"
}
{
"_index" : "school",
"_type" : "_doc",
"_id" : "16",
"_version" : 1,
"result" : "created",
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 9,
"_primary_term" : 7
}
In this way, we will keep adding any example data that we need for our working in the upcoming chapters.
Kibana is a GUI driven tool for accessing the data and creating the visualization. In this section, let us understand how we can add sample data to it.
In the Kibana home page, choose the following option to add sample ecommerce data −
The next screen will show some visualization and a button to Add data −
Clicking on Add Data will show the following screen which confirms the data has been added to an index named eCommerce.
In any system or software, when we are upgrading to newer version, we need to follow a few steps to maintain the application settings, configurations, data and other things. These steps are required to make the application stable in new system or to maintain the integrity of data (prevent data from getting corrupt).
You need to follow the following steps to upgrade Elasticsearch −
Read Upgrade docs from https://www.elastic.co/
Read Upgrade docs from https://www.elastic.co/
Test the upgraded version in your non production environments like in UAT, E2E, SIT or DEV environment.
Test the upgraded version in your non production environments like in UAT, E2E, SIT or DEV environment.
Note that rollback to previous Elasticsearch version is not possible without data backup. Hence, a data backup is recommended before upgrading to a higher version.
Note that rollback to previous Elasticsearch version is not possible without data backup. Hence, a data backup is recommended before upgrading to a higher version.
We can upgrade using full cluster restart or rolling upgrade. Rolling upgrade is for new versions. Note that there is no service outage, when you are using rolling upgrade method for migration.
We can upgrade using full cluster restart or rolling upgrade. Rolling upgrade is for new versions. Note that there is no service outage, when you are using rolling upgrade method for migration.
Test the upgrade in a dev environment before upgrading your production cluster.
Test the upgrade in a dev environment before upgrading your production cluster.
Back up your data. You cannot roll back to an earlier version unless you have a snapshot of your data.
Back up your data. You cannot roll back to an earlier version unless you have a snapshot of your data.
Consider closing machine learning jobs before you start the upgrade process. While machine learning jobs can continue to run during a rolling upgrade, it increases the overhead on the cluster during the upgrade process.
Consider closing machine learning jobs before you start the upgrade process. While machine learning jobs can continue to run during a rolling upgrade, it increases the overhead on the cluster during the upgrade process.
Upgrade the components of your Elastic Stack in the following order −
Elasticsearch
Kibana
Logstash
Beats
APM Server
Upgrade the components of your Elastic Stack in the following order −
Elasticsearch
Kibana
Logstash
Beats
APM Server
To upgrade directly to Elasticsearch 7.1.0 from versions 6.0-6.6, you must manually reindex any 5.x indices you need to carry forward, and perform a full cluster restart.
The process of full cluster restart involves shutting down each node in the cluster, upgrading each node to 7x and then restarting the cluster.
Following are the high level steps that need to be carried out for full cluster restart −
Disable shard allocation
Stop indexing and perform a synced flush
Shutdown all nodes
Upgrade all nodes
Upgrade any plugins
Start each upgraded node
Wait for all nodes to join the cluster and report a status of yellow
Re-enable allocation
Once allocation is re-enabled, the cluster starts allocating the replica shards to the data nodes. At this point, it is safe to resume indexing and searching, but your cluster will recover more quickly if you can wait until all primary and replica shards have been successfully allocated and the status of all nodes is green.
Application Programming Interface (API) in web is a group of function calls or other programming instructions to access the software component in that particular web application. For example, Facebook API helps a developer to create applications by accessing data or other functionalities from Facebook; it can be date of birth or status update.
Elasticsearch provides a REST API, which is accessed by JSON over HTTP. Elasticsearch uses some conventions which we shall discuss now.
Most of the operations, mainly searching and other operations, in APIs are for one or more than one indices. This helps the user to search in multiple places or all the available data by just executing a query once. Many different notations are used to perform operations in multiple indices. We will discuss a few of them here in this chapter.
POST /index1,index2,index3/_search
{
"query":{
"query_string":{
"query":"any_string"
}
}
}
JSON objects from index1, index2, index3 having any_string in it.
POST /_all/_search
{
"query":{
"query_string":{
"query":"any_string"
}
}
}
JSON objects from all indices and having any_string in it.
POST /school*/_search
{
"query":{
"query_string":{
"query":"CBSE"
}
}
}
JSON objects from all indices which start with school having CBSE in it.
Alternatively, you can use the following code as well −
POST /school*,-schools_gov /_search
{
"query":{
"query_string":{
"query":"CBSE"
}
}
}
JSON objects from all indices which start with “school” but not from schools_gov and having CBSE in it.
There are also some URL query string parameters −
ignore_unavailable − No error will occur or no operation will be stopped, if the one or more index(es) present in the URL does not exist. For example, schools index exists, but book_shops does not exist.
POST /school*,book_shops/_search
{
"query":{
"query_string":{
"query":"CBSE"
}
}
}
{
"error":{
"root_cause":[{
"type":"index_not_found_exception", "reason":"no such index",
"resource.type":"index_or_alias", "resource.id":"book_shops",
"index":"book_shops"
}],
"type":"index_not_found_exception", "reason":"no such index",
"resource.type":"index_or_alias", "resource.id":"book_shops",
"index":"book_shops"
},"status":404
}
Consider the following code −
POST /school*,book_shops/_search?ignore_unavailable = true
{
"query":{
"query_string":{
"query":"CBSE"
}
}
}
JSON objects from all indices which start with school having CBSE in it.
true value of this parameter will prevent error, if a URL with wildcard results in no indices. For example, there is no index that starts with schools_pri −
POST /schools_pri*/_search?allow_no_indices = true
{
"query":{
"match_all":{}
}
}
{
"took":1,"timed_out": false, "_shards":{"total":0, "successful":0, "failed":0},
"hits":{"total":0, "max_score":0.0, "hits":[]}
}
This parameter decides whether the wildcards need to be expanded to open indices or closed indices or perform both. The value of this parameter can be open and closed or none and all.
For example, close index schools −
POST /schools/_close
{"acknowledged":true}
Consider the following code −
POST /school*/_search?expand_wildcards = closed
{
"query":{
"match_all":{}
}
}
{
"error":{
"root_cause":[{
"type":"index_closed_exception", "reason":"closed", "index":"schools"
}],
"type":"index_closed_exception", "reason":"closed", "index":"schools"
}, "status":403
}
Elasticsearch offers a functionality to search indices according to date and time. We need to specify date and time in a specific format. For example, accountdetail-2015.12.30, index will store the bank account details of 30th December 2015. Mathematical operations can be performed to get details for a particular date or a range of date and time.
Format for date math index name −
<static_name{date_math_expr{date_format|time_zone}}>
/<accountdetail-{now-2d{YYYY.MM.dd|utc}}>/_search
static_name is a part of expression which remains the same in every date math index like account detail. date_math_expr contains the mathematical expression that determines the date and time dynamically like now-2d. date_format contains the format in which the date is written in index like YYYY.MM.dd. If today’s date is 30th December 2015, then <accountdetail-{now-2d{YYYY.MM.dd}}> will return accountdetail-2015.12.28.
We will now see some of the common options available in Elasticsearch that can be used to get the response in a specified format.
We can get response in a well-formatted JSON object by just appending a URL query parameter, i.e., pretty = true.
POST /schools/_search?pretty = true
{
"query":{
"match_all":{}
}
}
..........................
{
"_index" : "schools", "_type" : "school", "_id" : "1", "_score" : 1.0,
"_source":{
"name":"Central School", "description":"CBSE Affiliation",
"street":"Nagan", "city":"paprola", "state":"HP", "zip":"176115",
"location": [31.8955385, 76.8380405], "fees":2000,
"tags":["Senior Secondary", "beautiful campus"], "rating":"3.5"
}
}
......................
This option can change the statistical responses either into human readable form (If human = true) or computer readable form (if human = false). For example, if human = true then distance_kilometer = 20KM and if human = false then distance_meter = 20000, when response needs to be used by another computer program.
We can filter the response to less fields by adding them in the field_path parameter. For example,
POST /schools/_search?filter_path = hits.total
{
"query":{
"match_all":{}
}
}
{"hits":{"total":3}}
Elasticsearch provides single document APIs and multi-document APIs, where the API call is targeting a single document and multiple documents respectively.
It helps to add or update the JSON document in an index when a request is made to that respective index with specific mapping. For example, the following request will add the JSON object to index schools and under school mapping −
PUT schools/_doc/5
{
name":"City School", "description":"ICSE", "street":"West End",
"city":"Meerut",
"state":"UP", "zip":"250002", "location":[28.9926174, 77.692485],
"fees":3500,
"tags":["fully computerized"], "rating":"4.5"
}
On running the above code, we get the following result −
{
"_index" : "schools",
"_type" : "_doc",
"_id" : "5",
"_version" : 1,
"result" : "created",
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 2,
"_primary_term" : 1
}
When a request is made to add JSON object to a particular index and if that index does not exist, then this API automatically creates that index and also the underlying mapping for that particular JSON object. This functionality can be disabled by changing the values of following parameters to false, which are present in elasticsearch.yml file.
action.auto_create_index:false
index.mapper.dynamic:false
You can also restrict the auto creation of index, where only index name with specific patterns are allowed by changing the value of the following parameter −
action.auto_create_index:+acc*,-bank*
Note − Here + indicates allowed and – indicates not allowed.
Elasticsearch also provides version control facility. We can use a version query parameter to specify the version of a particular document.
PUT schools/_doc/5?version=7&version_type=external
{
"name":"Central School", "description":"CBSE Affiliation", "street":"Nagan",
"city":"paprola", "state":"HP", "zip":"176115", "location":[31.8955385, 76.8380405],
"fees":2200, "tags":["Senior Secondary", "beautiful campus"], "rating":"3.3"
}
On running the above code, we get the following result −
{
"_index" : "schools",
"_type" : "_doc",
"_id" : "5",
"_version" : 7,
"result" : "updated",
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 3,
"_primary_term" : 1
}
Versioning is a real-time process and it is not affected by the real time search operations.
There are two most important types of versioning −
Internal versioning is the default version that starts with 1 and increments with each update, deletes included.
It is used when the versioning of the documents is stored in an external system like third party versioning systems. To enable this functionality, we need to set version_type to external. Here Elasticsearch will store version number as designated by the external system and will not increment them automatically.
The operation type is used to force a create operation. This helps to avoid the overwriting
of existing document.
PUT chapter/_doc/1?op_type=create
{
"Text":"this is chapter one"
}
On running the above code, we get the following result −
{
"_index" : "chapter",
"_type" : "_doc",
"_id" : "1",
"_version" : 1,
"result" : "created",
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 0,
"_primary_term" : 1
}
When ID is not specified in index operation, then Elasticsearch automatically generates id
for that document.
POST chapter/_doc/
{
"user" : "tpoint",
"post_date" : "2018-12-25T14:12:12",
"message" : "Elasticsearch Tutorial"
}
On running the above code, we get the following result −
{
"_index" : "chapter",
"_type" : "_doc",
"_id" : "PVghWGoB7LiDTeV6LSGu",
"_version" : 1,
"result" : "created",
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 1,
"_primary_term" : 1
}
API helps to extract type JSON object by performing a get request for a particular document.
pre class="prettyprint notranslate" > GET schools/_doc/5
On running the above code, we get the following result −
{
"_index" : "schools",
"_type" : "_doc",
"_id" : "5",
"_version" : 7,
"_seq_no" : 3,
"_primary_term" : 1,
"found" : true,
"_source" : {
"name" : "Central School",
"description" : "CBSE Affiliation",
"street" : "Nagan",
"city" : "paprola",
"state" : "HP",
"zip" : "176115",
"location" : [
31.8955385,
76.8380405
],
"fees" : 2200,
"tags" : [
"Senior Secondary",
"beautiful campus"
],
"rating" : "3.3"
}
}
This operation is real time and does not get affected by the refresh rate of Index.
This operation is real time and does not get affected by the refresh rate of Index.
You can also specify the version, then Elasticsearch will fetch that version of document only.
You can also specify the version, then Elasticsearch will fetch that version of document only.
You can also specify the _all in the request, so that the Elasticsearch can search
for that document id in every type and it will return the first matched document.
You can also specify the _all in the request, so that the Elasticsearch can search
for that document id in every type and it will return the first matched document.
You can also specify the fields you want in your result from that particular document.
You can also specify the fields you want in your result from that particular document.
GET schools/_doc/5?_source_includes=name,fees
On running the above code, we get the following result −
{
"_index" : "schools",
"_type" : "_doc",
"_id" : "5",
"_version" : 7,
"_seq_no" : 3,
"_primary_term" : 1,
"found" : true,
"_source" : {
"fees" : 2200,
"name" : "Central School"
}
}
You can also fetch the source part in your result by just adding _source part in your get request.
GET schools/_doc/5?_source
On running the above code, we get the following result −
{
"_index" : "schools",
"_type" : "_doc",
"_id" : "5",
"_version" : 7,
"_seq_no" : 3,
"_primary_term" : 1,
"found" : true,
"_source" : {
"name" : "Central School",
"description" : "CBSE Affiliation",
"street" : "Nagan",
"city" : "paprola",
"state" : "HP",
"zip" : "176115",
"location" : [
31.8955385,
76.8380405
],
"fees" : 2200,
"tags" : [
"Senior Secondary",
"beautiful campus"
],
"rating" : "3.3"
}
}
You can also refresh the shard before doing get operation by set refresh parameter to true.
You can delete a particular index, mapping or a document by sending a HTTP DELETE request to Elasticsearch.
DELETE schools/_doc/4
On running the above code, we get the following result −
{
"found":true, "_index":"schools", "_type":"school", "_id":"4", "_version":2,
"_shards":{"total":2, "successful":1, "failed":0}
}
Version of the document can be specified to delete that particular version. Routing parameter can be specified to delete the document from a particular user and the operation fails if the document does not belong to that particular user. In this operation, you can specify refresh and timeout option same like GET API.
Script is used for performing this operation and versioning is used to make sure that no
updates have happened during the get and re-index. For example, you can update the fees of school using script −
POST schools/_update/4
{
"script" : {
"source": "ctx._source.name = params.sname",
"lang": "painless",
"params" : {
"sname" : "City Wise School"
}
}
}
On running the above code, we get the following result −
{
"_index" : "schools",
"_type" : "_doc",
"_id" : "4",
"_version" : 3,
"result" : "updated",
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 4,
"_primary_term" : 2
}
You can check the update by sending get request to the updated document.
This API is used to search content in Elasticsearch. A user can search by sending a get request with query string as a parameter or they can post a query in the message body of post request. Mainly all the search APIS are multi-index, multi-type.
Elasticsearch allows us to search for the documents present in all the indices or in some
specific indices. For example, if we need to search all the documents with a name that contains central, we can do as shown here −
GET /_all/_search?q=city:paprola
On running the above code, we get the following response −
{
"took" : 33,
"timed_out" : false,
"_shards" : {
"total" : 7,
"successful" : 7,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
"max_score" : 0.9808292,
"hits" : [
{
"_index" : "schools",
"_type" : "school",
"_id" : "5",
"_score" : 0.9808292,
"_source" : {
"name" : "Central School",
"description" : "CBSE Affiliation",
"street" : "Nagan",
"city" : "paprola",
"state" : "HP",
"zip" : "176115",
"location" : [
31.8955385,
76.8380405
],
"fees" : 2200,
"tags" : [
"Senior Secondary",
"beautiful campus"
],
"rating" : "3.3"
}
}
]
}
}
Many parameters can be passed in a search operation using Uniform Resource Identifier −
Q
This parameter is used to specify query string.
lenient
This parameter is used to specify query string.Format based errors can be ignored by just setting this parameter to true. It
is false by default.
fields
This parameter is used to specify query string.
sort
We can get sorted result by using this parameter, the possible values for this parameter is fieldName, fieldName:asc/fieldname:desc
timeout
We can restrict the search time by using this parameter and response only contains the hits in that specified time. By default, there is no timeout.
terminate_after
We can restrict the response to a specified number of documents for each shard, upon reaching which the query will terminate early. By default, there is no terminate_after.
from
The starting from index of the hits to return. Defaults to 0.
size
It denotes the number of hits to return. Defaults to 10.
We can also specify query using query DSL in request body and there are many examples already given in previous chapters. One such example is given here −
POST /schools/_search
{
"query":{
"query_string":{
"query":"up"
}
}
}
On running the above code, we get the following response −
{
"took" : 11,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
"max_score" : 0.47000363,
"hits" : [
{
"_index" : "schools",
"_type" : "school",
"_id" : "4",
"_score" : 0.47000363,
"_source" : {
"name" : "City Best School",
"description" : "ICSE",
"street" : "West End",
"city" : "Meerut",
"state" : "UP",
"zip" : "250002",
"location" : [
28.9926174,
77.692485
],
"fees" : 3500,
"tags" : [
"fully computerized"
],
"rating" : "4.5"
}
}
]
}
}
The aggregations framework collects all the data selected by the search query and consists of many building blocks, which help in building complex summaries of the data. The basic structure of an aggregation is shown here −
"aggregations" : {
"" : {
"" : {
}
[,"meta" : { [] } ]?
[,"aggregations" : { []+ } ]?
}
[,"" : { ... } ]*
}
There are different types of aggregations, each with its own purpose. They are discussed in detail in this chapter.
These aggregations help in computing matrices from the field’s values of the aggregated documents and sometime some values can be generated from scripts.
Numeric matrices are either single-valued like average aggregation or multi-valued like stats.
This aggregation is used to get the average of any numeric field present in the aggregated
documents. For example,
POST /schools/_search
{
"aggs":{
"avg_fees":{"avg":{"field":"fees"}}
}
}
On running the above code, we get the following result −
{
"took" : 41,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 2,
"relation" : "eq"
},
"max_score" : 1.0,
"hits" : [
{
"_index" : "schools",
"_type" : "school",
"_id" : "5",
"_score" : 1.0,
"_source" : {
"name" : "Central School",
"description" : "CBSE Affiliation",
"street" : "Nagan",
"city" : "paprola",
"state" : "HP",
"zip" : "176115",
"location" : [
31.8955385,
76.8380405
],
"fees" : 2200,
"tags" : [
"Senior Secondary",
"beautiful campus"
],
"rating" : "3.3"
}
},
{
"_index" : "schools",
"_type" : "school",
"_id" : "4",
"_score" : 1.0,
"_source" : {
"name" : "City Best School",
"description" : "ICSE",
"street" : "West End",
"city" : "Meerut",
"state" : "UP",
"zip" : "250002",
"location" : [
28.9926174,
77.692485
],
"fees" : 3500,
"tags" : [
"fully computerized"
],
"rating" : "4.5"
}
}
]
},
"aggregations" : {
"avg_fees" : {
"value" : 2850.0
}
}
}
This aggregation gives the count of distinct values of a particular field.
POST /schools/_search?size=0
{
"aggs":{
"distinct_name_count":{"cardinality":{"field":"fees"}}
}
}
On running the above code, we get the following result −
{
"took" : 2,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 2,
"relation" : "eq"
},
"max_score" : null,
"hits" : [ ]
},
"aggregations" : {
"distinct_name_count" : {
"value" : 2
}
}
}
Note − The value of cardinality is 2 because there are two distinct values in fees.
This aggregation generates all the statistics about a specific numerical field in aggregated documents.
POST /schools/_search?size=0
{
"aggs" : {
"fees_stats" : { "extended_stats" : { "field" : "fees" } }
}
}
On running the above code, we get the following result −
{
"took" : 8,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 2,
"relation" : "eq"
},
"max_score" : null,
"hits" : [ ]
},
"aggregations" : {
"fees_stats" : {
"count" : 2,
"min" : 2200.0,
"max" : 3500.0,
"avg" : 2850.0,
"sum" : 5700.0,
"sum_of_squares" : 1.709E7,
"variance" : 422500.0,
"std_deviation" : 650.0,
"std_deviation_bounds" : {
"upper" : 4150.0,
"lower" : 1550.0
}
}
}
}
This aggregation finds the max value of a specific numeric field in aggregated documents.
POST /schools/_search?size=0
{
"aggs" : {
"max_fees" : { "max" : { "field" : "fees" } }
}
}
On running the above code, we get the following result −
{
"took" : 16,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 2,
"relation" : "eq"
},
"max_score" : null,
"hits" : [ ]
},
"aggregations" : {
"max_fees" : {
"value" : 3500.0
}
}
}
This aggregation finds the min value of a specific numeric field in aggregated documents.
POST /schools/_search?size=0
{
"aggs" : {
"min_fees" : { "min" : { "field" : "fees" } }
}
}
On running the above code, we get the following result −
{
"took" : 2,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 2,
"relation" : "eq"
},
"max_score" : null,
"hits" : [ ]
},
"aggregations" : {
"min_fees" : {
"value" : 2200.0
}
}
}
This aggregation calculates the sum of a specific numeric field in aggregated documents.
POST /schools/_search?size=0
{
"aggs" : {
"total_fees" : { "sum" : { "field" : "fees" } }
}
}
On running the above code, we get the following result −
{
"took" : 8,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 2,
"relation" : "eq"
},
"max_score" : null,
"hits" : [ ]
},
"aggregations" : {
"total_fees" : {
"value" : 5700.0
}
}
}
There are some other metrics aggregations which are used in special cases like geo bounds aggregation and geo centroid aggregation for the purpose of geo location.
A multi-value metrics aggregation that computes stats over numeric values extracted from the aggregated documents.
POST /schools/_search?size=0
{
"aggs" : {
"grades_stats" : { "stats" : { "field" : "fees" } }
}
}
On running the above code, we get the following result −
{
"took" : 2,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 2,
"relation" : "eq"
},
"max_score" : null,
"hits" : [ ]
},
"aggregations" : {
"grades_stats" : {
"count" : 2,
"min" : 2200.0,
"max" : 3500.0,
"avg" : 2850.0,
"sum" : 5700.0
}
}
}
You can add some data about the aggregation at the time of request by using meta tag and can get that in response.
POST /schools/_search?size=0
{
"aggs" : {
"avg_fees" : { "avg" : { "field" : "fees" } ,
"meta" :{
"dsc" :"Lowest Fees This Year"
}
}
}
}
On running the above code, we get the following result −
{
"took" : 0,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 2,
"relation" : "eq"
},
"max_score" : null,
"hits" : [ ]
},
"aggregations" : {
"avg_fees" : {
"meta" : {
"dsc" : "Lowest Fees This Year"
},
"value" : 2850.0
}
}
}
These APIs are responsible for managing all the aspects of the index like settings, aliases, mappings, index templates.
This API helps you to create an index. An index can be created automatically when a user is passing JSON objects to any index or it can be created before that. To create an index, you just need to send a PUT request with settings, mappings and aliases or just a simple request without body.
PUT colleges
On running the above code, we get the output as shown below −
{
"acknowledged" : true,
"shards_acknowledged" : true,
"index" : "colleges"
}
We can also add some settings to the above command −
PUT colleges
{
"settings" : {
"index" : {
"number_of_shards" : 3,
"number_of_replicas" : 2
}
}
}
On running the above code, we get the output as shown below −
{
"acknowledged" : true,
"shards_acknowledged" : true,
"index" : "colleges"
}
This API helps you to delete any index. You just need to pass a delete request with the name of that particular Index.
DELETE /colleges
You can delete all indices by just using _all or *.
This API can be called by just sending get request to one or more than one indices. This returns the information about index.
GET colleges
On running the above code, we get the output as shown below −
{
"colleges" : {
"aliases" : {
"alias_1" : { },
"alias_2" : {
"filter" : {
"term" : {
"user" : "pkay"
}
},
"index_routing" : "pkay",
"search_routing" : "pkay"
}
},
"mappings" : { },
"settings" : {
"index" : {
"creation_date" : "1556245406616",
"number_of_shards" : "1",
"number_of_replicas" : "1",
"uuid" : "3ExJbdl2R1qDLssIkwDAug",
"version" : {
"created" : "7000099"
},
"provided_name" : "colleges"
}
}
}
}
You can get the information of all the indices by using _all or *.
Existence of an index can be determined by just sending a get request to that index. If the HTTP response is 200, it exists; if it is 404, it does not exist.
HEAD colleges
On running the above code, we get the output as shown below −
200-OK
You can get the index settings by just appending _settings keyword at the end of URL.
GET /colleges/_settings
On running the above code, we get the output as shown below −
{
"colleges" : {
"settings" : {
"index" : {
"creation_date" : "1556245406616",
"number_of_shards" : "1",
"number_of_replicas" : "1",
"uuid" : "3ExJbdl2R1qDLssIkwDAug",
"version" : {
"created" : "7000099"
},
"provided_name" : "colleges"
}
}
}
}
This API helps you to extract statistics about a particular index. You just need to send a get request with the index URL and _stats keyword at the end.
GET /_stats
On running the above code, we get the output as shown below −
......................................................
},
"request_cache" : {
"memory_size_in_bytes" : 849,
"evictions" : 0,
"hit_count" : 1171,
"miss_count" : 4
},
"recovery" : {
"current_as_source" : 0,
"current_as_target" : 0,
"throttle_time_in_millis" : 0
}
} ......................................................
The flush process of an index makes sure that any data that is currently only persisted in the transaction log is also permanently persisted in Lucene. This reduces recovery times as that data does not need to be reindexed from the transaction logs after the Lucene indexed is opened.
POST colleges/_flush
On running the above code, we get the output as shown below −
{
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
}
}
Usually the results from various Elasticsearch APIs are displayed in JSON format. But JSON is not easy to read always. So cat APIs feature is available in Elasticsearch helps in taking
care of giving an easier to read and comprehend printing format of the results. There are various parameters used in cat API which server different purpose, for example - the term V makes the output verbose.
Let us learn about cat APIs more in detail in this chapter.
The verbose output gives a nice display of results of a cat command. In the example given
below, we get the details of various indices present in the cluster.
GET /_cat/indices?v
On running the above code, we get the response as shown below −
health status index uuid pri rep docs.count docs.deleted store.size pri.store.size
yellow open schools RkMyEn2SQ4yUgzT6EQYuAA 1 1 2 1 21.6kb 21.6kb
yellow open index_4_analysis zVmZdM1sTV61YJYrNXf1gg 1 1 0 0 283b 283b
yellow open sensor-2018-01-01 KIrrHwABRB-ilGqTu3OaVQ 1 1 1 0 4.2kb 4.2kb
yellow open colleges 3ExJbdl2R1qDLssIkwDAug 1 1 0 0 283b 283b
The h parameter, also called header, is used to display only those columns mentioned in
the command.
GET /_cat/nodes?h=ip,port
On running the above code, we get the response as shown below −
127.0.0.1 9300
The sort command accepts query string which can sort the table by specified column in the query. The default sort is ascending but this can be changed by adding :desc to a column.
The below example, gives a result of templates arranged in descending order of the filed
index patterns.
GET _cat/templates?v&s=order:desc,index_patterns
On running the above code, we get the response as shown below −
name index_patterns order version
.triggered_watches [.triggered_watches*] 2147483647
.watch-history-9 [.watcher-history-9*] 2147483647
.watches [.watches*] 2147483647
.kibana_task_manager [.kibana_task_manager] 0 7000099
The count parameter provides the count of total number of documents in the entire cluster.
GET /_cat/count?v
On running the above code, we get the response as shown below −
epoch timestamp count
1557633536 03:58:56 17809
The cluster API is used for getting information about cluster and its nodes and to make changes in them. To call this API, we need to specify the node name, address or _local.
GET /_nodes/_local
On running the above code, we get the response as shown below −
......................................................
cluster_name" : "elasticsearch",
"nodes" : {
"FKH-5blYTJmff2rJ_lQOCg" : {
"name" : "ubuntu",
"transport_address" : "127.0.0.1:9300",
"host" : "127.0.0.1",
"ip" : "127.0.0.1",
"version" : "7.0.0",
"build_flavor" : "default",
"build_type" : "tar",
"build_hash" : "b7e28a7",
"total_indexing_buffer" : 106502553,
"roles" : [
"master",
"data",
"ingest"
],
"attributes" : {
......................................................
This API is used to get the status on the health of the cluster by appending the ‘health’
keyword.
GET /_cluster/health
On running the above code, we get the response as shown below −
{
"cluster_name" : "elasticsearch",
"status" : "yellow",
"timed_out" : false,
"number_of_nodes" : 1,
"number_of_data_nodes" : 1,
"active_primary_shards" : 7,
"active_shards" : 7,
"relocating_shards" : 0,
"initializing_shards" : 0,
"unassigned_shards" : 4,
"delayed_unassigned_shards" : 0,
"number_of_pending_tasks" : 0,
"number_of_in_flight_fetch" : 0,
"task_max_waiting_in_queue_millis" : 0,
"active_shards_percent_as_number" : 63.63636363636363
}
This API is used to get state information about a cluster by appending the ‘state’ keyword
URL. The state information contains version, master node, other nodes, routing table, metadata and blocks.
GET /_cluster/state
On running the above code, we get the response as shown below −
......................................................
{
"cluster_name" : "elasticsearch",
"cluster_uuid" : "IzKu0OoVTQ6LxqONJnN2eQ",
"version" : 89,
"state_uuid" : "y3BlwvspR1eUQBTo0aBjig",
"master_node" : "FKH-5blYTJmff2rJ_lQOCg",
"blocks" : { },
"nodes" : {
"FKH-5blYTJmff2rJ_lQOCg" : {
"name" : "ubuntu",
"ephemeral_id" : "426kTGpITGixhEzaM-5Qyg",
"transport
}
......................................................
This API helps to retrieve statistics about cluster by using the ‘stats’ keyword. This API
returns shard number, store size, memory usage, number of nodes, roles, OS, and file system.
GET /_cluster/stats
On running the above code, we get the response as shown below −
.................................................
"cluster_name" : "elasticsearch",
"cluster_uuid" : "IzKu0OoVTQ6LxqONJnN2eQ",
"timestamp" : 1556435464704,
"status" : "yellow",
"indices" : {
"count" : 7,
"shards" : {
"total" : 7,
"primaries" : 7,
"replication" : 0.0,
"index" : {
"shards" : {
"min" : 1,
"max" : 1,
"avg" : 1.0
},
"primaries" : {
"min" : 1,
"max" : 1,
"avg" : 1.0
},
"replication" : {
"min" : 0.0,
"max" : 0.0,
"avg" : 0.0
}
.................................................
This API allows you to update the settings of a cluster by using the ‘settings’ keyword.
There are two types of settings − persistent (applied across restarts) and transient (do not survive a full cluster restart).
This API is used to retrieve the statistics of one more nodes of the cluster. Node stats are
almost the same as cluster.
GET /_nodes/stats
On running the above code, we get the response as shown below −
{
"_nodes" : {
"total" : 1,
"successful" : 1,
"failed" : 0
},
"cluster_name" : "elasticsearch",
"nodes" : {
"FKH-5blYTJmff2rJ_lQOCg" : {
"timestamp" : 1556437348653,
"name" : "ubuntu",
"transport_address" : "127.0.0.1:9300",
"host" : "127.0.0.1",
"ip" : "127.0.0.1:9300",
"roles" : [
"master",
"data",
"ingest"
],
"attributes" : {
"ml.machine_memory" : "4112797696",
"xpack.installed" : "true",
"ml.max_open_jobs" : "20"
},
...................................................................
This API helps you to retrieve information about the current hot threads on each node in cluster.
GET /_nodes/hot_threads
On running the above code, we get the response as shown below −
:::{ubuntu}{FKH-5blYTJmff2rJ_lQOCg}{426kTGpITGixhEzaM5Qyg}{127.0.0.1}{127.0.0.1:9300}{ml.machine_memory=4112797696,
xpack.installed=true, ml.max_open_jobs=20}
Hot threads at 2019-04-28T07:43:58.265Z, interval=500ms, busiestThreads=3,
ignoreIdleThreads=true:
In Elasticsearch, searching is carried out by using query based on JSON. A query is made up of two clauses −
Leaf Query Clauses − These clauses are match, term or range, which look for a specific value in specific field.
Leaf Query Clauses − These clauses are match, term or range, which look for a specific value in specific field.
Compound Query Clauses − These queries are a combination of leaf query clauses and other compound queries to extract the desired information.
Compound Query Clauses − These queries are a combination of leaf query clauses and other compound queries to extract the desired information.
Elasticsearch supports a large number of queries. A query starts with a query key word and then has conditions and filters inside in the form of JSON object. The different types of queries have been described below.
This is the most basic query; it returns all the content and with the score of 1.0 for every object.
POST /schools/_search
{
"query":{
"match_all":{}
}
}
On running the above code, we get the following result −
{
"took" : 7,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 2,
"relation" : "eq"
},
"max_score" : 1.0,
"hits" : [
{
"_index" : "schools",
"_type" : "school",
"_id" : "5",
"_score" : 1.0,
"_source" : {
"name" : "Central School",
"description" : "CBSE Affiliation",
"street" : "Nagan",
"city" : "paprola",
"state" : "HP",
"zip" : "176115",
"location" : [
31.8955385,
76.8380405
],
"fees" : 2200,
"tags" : [
"Senior Secondary",
"beautiful campus"
],
"rating" : "3.3"
}
},
{
"_index" : "schools",
"_type" : "school",
"_id" : "4",
"_score" : 1.0,
"_source" : {
"name" : "City Best School",
"description" : "ICSE",
"street" : "West End",
"city" : "Meerut",
"state" : "UP",
"zip" : "250002",
"location" : [
28.9926174,
77.692485
],
"fees" : 3500,
"tags" : [
"fully computerized"
],
"rating" : "4.5"
}
}
]
}
}
These queries are used to search a full body of text like a chapter or a news article. This query works according to the analyser associated with that particular index or document. In this section, we will discuss the different types of full text queries.
This query matches a text or phrase with the values of one or more fields.
POST /schools*/_search
{
"query":{
"match" : {
"rating":"4.5"
}
}
}
On running the above code, we get the response as shown below −
{
"took" : 44,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
"max_score" : 0.47000363,
"hits" : [
{
"_index" : "schools",
"_type" : "school",
"_id" : "4",
"_score" : 0.47000363,
"_source" : {
"name" : "City Best School",
"description" : "ICSE",
"street" : "West End",
"city" : "Meerut",
"state" : "UP",
"zip" : "250002",
"location" : [
28.9926174,
77.692485
],
"fees" : 3500,
"tags" : [
"fully computerized"
],
"rating" : "4.5"
}
}
]
}
}
This query matches a text or phrase with more than one field.
POST /schools*/_search
{
"query":{
"multi_match" : {
"query": "paprola",
"fields": [ "city", "state" ]
}
}
}
On running the above code, we get the response as shown below −
{
"took" : 12,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
"max_score" : 0.9808292,
"hits" : [
{
"_index" : "schools",
"_type" : "school",
"_id" : "5",
"_score" : 0.9808292,
"_source" : {
"name" : "Central School",
"description" : "CBSE Affiliation",
"street" : "Nagan",
"city" : "paprola",
"state" : "HP",
"zip" : "176115",
"location" : [
31.8955385,
76.8380405
],
"fees" : 2200,
"tags" : [
"Senior Secondary",
"beautiful campus"
],
"rating" : "3.3"
}
}
]
}
}
This query uses query parser and query_string keyword.
POST /schools*/_search
{
"query":{
"query_string":{
"query":"beautiful"
}
}
}
On running the above code, we get the response as shown below −
{
"took" : 60,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
........................................
These queries mainly deal with structured data like numbers, dates and enums.
POST /schools*/_search
{
"query":{
"term":{"zip":"176115"}
}
}
On running the above code, we get the response as shown below −
...................................
hits" : [
{
"_index" : "schools",
"_type" : "school",
"_id" : "5",
"_score" : 0.9808292,
"_source" : {
"name" : "Central School",
"description" : "CBSE Affiliation",
"street" : "Nagan",
"city" : "paprola",
"state" : "HP",
"zip" : "176115",
"location" : [
31.8955385,
76.8380405
],
}
}
]
..................................................
This query is used to find the objects having values between the ranges of values given. For this, we need to use operators such as −
gte − greater than equal to
gt − greater-than
lte − less-than equal to
lt − less-than
For example, observe the code given below −
POST /schools*/_search
{
"query":{
"range":{
"rating":{
"gte":3.5
}
}
}
}
On running the above code, we get the response as shown below −
{
"took" : 24,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
"max_score" : 1.0,
"hits" : [
{
"_index" : "schools",
"_type" : "school",
"_id" : "4",
"_score" : 1.0,
"_source" : {
"name" : "City Best School",
"description" : "ICSE",
"street" : "West End",
"city" : "Meerut",
"state" : "UP",
"zip" : "250002",
"location" : [
28.9926174,
77.692485
],
"fees" : 3500,
"tags" : [
"fully computerized"
],
"rating" : "4.5"
}
}
]
}
}
There exist other types of term level queries also such as −
Exists query − If a certain field has non null value.
Exists query − If a certain field has non null value.
Missing query − This is completely opposite to exists query, this query searches for objects without specific fields or fields having null value.
Missing query − This is completely opposite to exists query, this query searches for objects without specific fields or fields having null value.
Wildcard or regexp query − This query uses regular expressions to find patterns in the objects.
Wildcard or regexp query − This query uses regular expressions to find patterns in the objects.
These queries are a collection of different queries merged with each other by using Boolean
operators like and, or, not or for different indices or having function calls etc.
POST /schools/_search
{
"query": {
"bool" : {
"must" : {
"term" : { "state" : "UP" }
},
"filter": {
"term" : { "fees" : "2200" }
},
"minimum_should_match" : 1,
"boost" : 1.0
}
}
}
On running the above code, we get the response as shown below −
{
"took" : 6,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 0,
"relation" : "eq"
},
"max_score" : null,
"hits" : [ ]
}
}
These queries deal with geo locations and geo points. These queries help to find out schools
or any other geographical object near to any location. You need to use geo point data type.
PUT /geo_example
{
"mappings": {
"properties": {
"location": {
"type": "geo_shape"
}
}
}
}
On running the above code, we get the response as shown below −
{ "acknowledged" : true,
"shards_acknowledged" : true,
"index" : "geo_example"
}
Now we post the data in the index created above.
POST /geo_example/_doc?refresh
{
"name": "Chapter One, London, UK",
"location": {
"type": "point",
"coordinates": [11.660544, 57.800286]
}
}
On running the above code, we get the response as shown below −
{
"took" : 1,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 2,
"relation" : "eq"
},
"max_score" : 1.0,
"hits" : [
"_index" : "geo_example",
"_type" : "_doc",
"_id" : "hASWZ2oBbkdGzVfiXHKD",
"_score" : 1.0,
"_source" : {
"name" : "Chapter One, London, UK",
"location" : {
"type" : "point",
"coordinates" : [
11.660544,
57.800286
]
}
}
}
}
Mapping is the outline of the documents stored in an index. It defines the data type like geo_point or string and format of the fields present in the documents and rules to control the mapping of dynamically added fields.
PUT bankaccountdetails
{
"mappings":{
"properties":{
"name": { "type":"text"}, "date":{ "type":"date"},
"balance":{ "type":"double"}, "liability":{ "type":"double"}
}
}
}
When we run the above code, we get the response as shown below −
{
"acknowledged" : true,
"shards_acknowledged" : true,
"index" : "bankaccountdetails"
}
Elasticsearch supports a number of different datatypes for the fields in a document. The
data types used to store fields in Elasticsearch are discussed in detail here.
These are the basic data types such as text, keyword, date, long, double, boolean or ip,
which are supported by almost all the systems.
These data types are a combination of core data types. These include array, JSON object
and nested data type. An example of nested data type is shown below &minus
POST /tabletennis/_doc/1
{
"group" : "players",
"user" : [
{
"first" : "dave", "last" : "jones"
},
{
"first" : "kevin", "last" : "morris"
}
]
}
When we run the above code, we get the response as shown below −
{
"_index" : "tabletennis",
"_type" : "_doc",
"_id" : "1",
_version" : 2,
"result" : "updated",
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 1,
"_primary_term" : 1
}
Another sample code is shown below −
POST /accountdetails/_doc/1
{
"from_acc":"7056443341", "to_acc":"7032460534",
"date":"11/1/2016", "amount":10000
}
When we run the above code, we get the response as shown below −
{ "_index" : "accountdetails",
"_type" : "_doc",
"_id" : "1",
"_version" : 1,
"result" : "created",
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 1,
"_primary_term" : 1
}
We can check the above document by using the following command −
GET /accountdetails/_mappings?include_type_name=false
Indices created in Elasticsearch 7.0.0 or later no longer accept a _default_ mapping. Indices created in 6.x will continue to function as before in Elasticsearch 6.x. Types are
deprecated in APIs in 7.0.
When a query is processed during a search operation, the content in any index is analyzed by the analysis module. This module consists of analyzer, tokenizer, tokenfilters and charfilters. If no analyzer is defined, then by default the built in analyzers, token, filters and tokenizers get registered with analysis module.
In the following example, we use a standard analyzer which is used when no other analyzer is specified. It will analyze the sentence based on the grammar and produce words used in the sentence.
POST _analyze
{
"analyzer": "standard",
"text": "Today's weather is beautiful"
}
On running the above code, we get the response as shown below −
{
"tokens" : [
{
"token" : "today's",
"start_offset" : 0,
"end_offset" : 7,
"type" : "",
"position" : 0
},
{
"token" : "weather",
"start_offset" : 8,
"end_offset" : 15,
"type" : "",
"position" : 1
},
{
"token" : "is",
"start_offset" : 16,
"end_offset" : 18,
"type" : "",
"position" : 2
},
{
"token" : "beautiful",
"start_offset" : 19,
"end_offset" : 28,
"type" : "",
"position" : 3
}
]
}
We can configure the standard analyser with various parameters to get our custom requirements.
In the following example, we configure the standard analyzer to have a max_token_length of 5.
For this, we first create an index with the analyser having max_length_token parameter.
PUT index_4_analysis
{
"settings": {
"analysis": {
"analyzer": {
"my_english_analyzer": {
"type": "standard",
"max_token_length": 5,
"stopwords": "_english_"
}
}
}
}
}
Next we apply the analyser with a text as shown below. Please note how the token is does not appear as it has two spaces in the beginning and two spaces at the end. For the word “is”, there is a space at the beginning of it and a space at the end of it. Taking all of them, it becomes 4 letters with spaces and that does not make it a word. There should be a nonspace character at least at the beginning or at the end, to make it a word to be counted.
POST index_4_analysis/_analyze
{
"analyzer": "my_english_analyzer",
"text": "Today's weather is beautiful"
}
On running the above code, we get the response as shown below −
{
"tokens" : [
{
"token" : "today",
"start_offset" : 0,
"end_offset" : 5,
"type" : "",
"position" : 0
},
{
"token" : "s",
"start_offset" : 6,
"end_offset" : 7,
"type" : "",
"position" : 1
},
{
"token" : "weath",
"start_offset" : 8,
"end_offset" : 13,
"type" : "",
"position" : 2
},
{
"token" : "er",
"start_offset" : 13,
"end_offset" : 15,
"type" : "",
"position" : 3
},
{
"token" : "beaut",
"start_offset" : 19,
"end_offset" : 24,
"type" : "",
"position" : 5
},
{
"token" : "iful",
"start_offset" : 24,
"end_offset" : 28,
"type" : "",
"position" : 6
}
]
}
The list of various analyzers and their description are given in the table shown below −
Standard analyzer (standard)
stopwords and max_token_length setting can be set for this analyzer. By default, stopwords list is empty and max_token_length is 255.
Simple analyzer (simple)
This analyzer is composed of lowercase tokenizer.
Whitespace analyzer (whitespace)
This analyzer is composed of whitespace tokenizer.
Stop analyzer (stop)
stopwords and stopwords_path can be configured. By default stopwords initialized to English stop words and stopwords_path contains path to a text file with stop words.
Tokenizers are used for generating tokens from a text in Elasticsearch. Text can be broken down into tokens by taking whitespace or other punctuations into account. Elasticsearch has plenty of built-in tokenizers, which can be used in custom analyzer.
An example of tokenizer that breaks text into terms whenever it encounters a character which is not a letter, but it also lowercases all terms, is shown below −
POST _analyze
{
"tokenizer": "lowercase",
"text": "It Was a Beautiful Weather 5 Days ago."
}
On running the above code, we get the response as shown below −
{
"tokens" : [
{
"token" : "it",
"start_offset" : 0,
"end_offset" : 2,
"type" : "word",
"position" : 0
},
{
"token" : "was",
"start_offset" : 3,
"end_offset" : 6,
"type" : "word",
"position" : 1
},
{
"token" : "a",
"start_offset" : 7,
"end_offset" : 8,
"type" : "word",
"position" : 2
},
{
"token" : "beautiful",
"start_offset" : 9,
"end_offset" : 18,
"type" : "word",
"position" : 3
},
{
"token" : "weather",
"start_offset" : 19,
"end_offset" : 26,
"type" : "word",
"position" : 4
},
{
"token" : "days",
"start_offset" : 29,
"end_offset" : 33,
"type" : "word",
"position" : 5
},
{
"token" : "ago",
"start_offset" : 34,
"end_offset" : 37,
"type" : "word",
"position" : 6
}
]
}
A list of Tokenizers and their descriptions are shown here in the table given below −
Standard tokenizer (standard)
This is built on grammar based tokenizer and max_token_length can be
configured for this tokenizer.
Edge NGram tokenizer (edgeNGram)
Settings like min_gram, max_gram, token_chars can be set for this tokenizer.
Keyword tokenizer (keyword)
This generates entire input as an output and buffer_size can be set for this.
Letter tokenizer (letter)
This captures the whole word until a non-letter is encountered.
Elasticsearch is composed of a number of modules, which are responsible for its functionality. These modules have two types of settings as follows −
Static Settings − These settings need to be configured in config (elasticsearch.yml) file before starting Elasticsearch. You need to update all the concern nodes in the cluster to reflect the changes by these settings.
Static Settings − These settings need to be configured in config (elasticsearch.yml) file before starting Elasticsearch. You need to update all the concern nodes in the cluster to reflect the changes by these settings.
Dynamic Settings − These settings can be set on live Elasticsearch.
Dynamic Settings − These settings can be set on live Elasticsearch.
We will discuss the different modules of Elasticsearch in the following sections of this chapter.
Cluster level settings decide the allocation of shards to different nodes and reallocation of shards to rebalance cluster. These are the following settings to control shard allocation.
This module helps a cluster to discover and maintain the state of all the nodes in it. The
state of cluster changes when a node is added or deleted from it. The cluster name setting is used to create logical difference between different clusters. There are some modules which help you to use the APIs provided by cloud vendors and those are as given below −
Azure discovery
EC2 discovery
Google compute engine discovery
Zen discovery
This module maintains the cluster state and the shard data across full cluster restarts. The
following are the static settings of this module −
This specifies the time for which the recovery process will wait to start regardless of the number of nodes joined in the cluster.
gateway.recover_ after_nodes
gateway.recover_after_master_nodes
gateway.recover_after_data_nodes
This module manages the communication between HTTP client and Elasticsearch APIs. This module can be disabled by changing the value of http.enabled to false.
The following are the settings (configured in elasticsearch.yml) to control this module −
http.port
This is a port to access Elasticsearch and it ranges from 9200-9300.
http.publish_port
This port is for http clients and is also useful in case of firewall.
http.bind_host
This is a host address for http service.
http.publish_host
This is a host address for http client.
http.max_content_length
This is the maximum size of content in an http request. Its default value is 100mb.
http.max_initial_line_length
This is the maximum size of URL and its default value is 4kb.
http.max_header_size
This is the maximum http header size and its default value is 8kb.
http.compression
This enables or disables support for compression and its default value is false.
http.pipelinig
This enables or disables HTTP pipelining.
http.pipelining.max_events
This restricts the number of events to be queued before closing an HTTP request.
This module maintains the settings, which are set globally for every index. The following
settings are mainly related to memory usage −
This is used for preventing operation from causing an OutOfMemroyError. The setting mainly restricts the JVM heap size. For example, indices.breaker.total.limit setting, which defaults to 70% of JVM heap.
This is used mainly when aggregating on a field. It is recommended to have enough memory to allocate it. The amount of memory used for the field data cache can be controlled using indices.fielddata.cache.size setting.
This memory is used for caching the query results. This cache uses Least Recently Used (LRU) eviction policy. Indices.queries.cahce.size setting controls the memory size of this cache.
This buffer stores the newly created documents in the index and flushes them when the buffer is full. Setting like indices.memory.index_buffer_size control the amount of heap allocated for this buffer.
This cache is used to store the local search data for every shard. Cache can be enabled
during the creation of index or can be disabled by sending URL parameter.
Disable cache - ?request_cache = true
Enable cache "index.requests.cache.enable": true
It controls the resources during recovery process. The following are the settings −
Time to Live (TTL) interval defines the time of a document, after which the document gets
deleted. The following are the dynamic settings for controlling this process −
Each node has an option to be data node or not. You can change this property by changing node.data setting. Setting the value as false defines that the node is not a data
node.
These are the modules which are created for every index and control the settings and behaviour of the indices. For example, how many shards an index can use or the number of replicas a primary shard can have for that index etc. There are two types of index settings −
Static − These can be set only at index creation time or on a closed index.
Dynamic − These can be changed on a live index.
The following table shows the list of static index settings −
The following table shows the list of dynamic index settings −
Sometimes we need to transform a document before we index it. For instance, we want to remove a field from the document or rename a field and then index it. This is handled by Ingest node.
Every node in the cluster has the ability to ingest but it can also be customized to be
processed only by specific nodes.
There are two steps involved in the working of the ingest node −
Creating a pipeline
Creating a doc
First creating a pipeline which contains the processors and then executing the pipeline, as
shown below −
PUT _ingest/pipeline/int-converter
{
"description": "converts the content of the seq field to an integer",
"processors" : [
{
"convert" : {
"field" : "seq",
"type": "integer"
}
}
]
}
On running the above code, we get the following result −
{
"acknowledged" : true
}
Next we create a document using the pipeline converter.
PUT /logs/_doc/1?pipeline=int-converter
{
"seq":"21",
"name":"Tutorialspoint",
"Addrs":"Hyderabad"
}
On running the above code, we get the response as shown below −
{
"_index" : "logs",
"_type" : "_doc",
"_id" : "1",
"_version" : 1,
"result" : "created",
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 0,
"_primary_term" : 1
}
Next we search for the doc created above by using the GET command as shown below −
GET /logs/_doc/1
On running the above code, we get the following result −
{
"_index" : "logs",
"_type" : "_doc",
"_id" : "1",
"_version" : 1,
"_seq_no" : 0,
"_primary_term" : 1,
"found" : true,
"_source" : {
"Addrs" : "Hyderabad",
"name" : "Tutorialspoint",
"seq" : 21
}
}
You can see above that 21 has become an integer.
Now we create a document without using the pipeline.
PUT /logs/_doc/2
{
"seq":"11",
"name":"Tutorix",
"Addrs":"Secunderabad"
}
GET /logs/_doc/2
On running the above code, we get the following result −
{
"_index" : "logs",
"_type" : "_doc",
"_id" : "2",
"_version" : 1,
"_seq_no" : 1,
"_primary_term" : 1,
"found" : true,
"_source" : {
"seq" : "11",
"name" : "Tutorix",
"Addrs" : "Secunderabad"
}
}
You can see above that 11 is a string without the pipeline being used.
Managing the index lifecycle involves performing management actions based on factors like shard size and performance requirements. The index lifecycle management (ILM) APIs enable you to automate how you want to manage your indices over time.
This chapter gives a list of ILM APIs and their usage.
It is a component that allows SQL-like queries to be executed in real-time against Elasticsearch. You can think of Elasticsearch SQL as a translator, one that understands both SQL and Elasticsearch and makes it easy to read and process data in real-time, at scale by leveraging Elasticsearch capabilities.
It has native integration − Each and every query is efficiently executed against the relevant nodes according to the underlying storage.
It has native integration − Each and every query is efficiently executed against the relevant nodes according to the underlying storage.
No external parts − No need for additional hardware, processes, runtimes or
libraries to query Elasticsearch.
No external parts − No need for additional hardware, processes, runtimes or
libraries to query Elasticsearch.
Lightweight and efficient − it embraces and exposes SQL to allow proper full-text search, in real-time.
Lightweight and efficient − it embraces and exposes SQL to allow proper full-text search, in real-time.
PUT /schoollist/_bulk?refresh
{"index":{"_id": "CBSE"}}
{"name": "GleanDale", "Address": "JR. Court Lane", "start_date": "2011-06-02",
"student_count": 561}
{"index":{"_id": "ICSE"}}
{"name": "Top-Notch", "Address": "Gachibowli Main Road", "start_date": "1989-
05-26", "student_count": 482}
{"index":{"_id": "State Board"}}
{"name": "Sunshine", "Address": "Main Street", "start_date": "1965-06-01",
"student_count": 604}
On running the above code, we get the response as shown below −
{
"took" : 277,
"errors" : false,
"items" : [
{
"index" : {
"_index" : "schoollist",
"_type" : "_doc",
"_id" : "CBSE",
"_version" : 1,
"result" : "created",
"forced_refresh" : true,
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 0,
"_primary_term" : 1,
"status" : 201
}
},
{
"index" : {
"_index" : "schoollist",
"_type" : "_doc",
"_id" : "ICSE",
"_version" : 1,
"result" : "created",
"forced_refresh" : true,
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 1,
"_primary_term" : 1,
"status" : 201
}
},
{
"index" : {
"_index" : "schoollist",
"_type" : "_doc",
"_id" : "State Board",
"_version" : 1,
"result" : "created",
"forced_refresh" : true,
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 2,
"_primary_term" : 1,
"status" : 201
}
}
]
}
The following example shows how we frame the SQL query −
POST /_sql?format=txt
{
"query": "SELECT * FROM schoollist WHERE start_date < '2000-01-01'"
}
On running the above code, we get the response as shown below −
Address | name | start_date | student_count
--------------------+---------------+------------------------+---------------
Gachibowli Main Road|Top-Notch |1989-05-26T00:00:00.000Z|482
Main Street |Sunshine |1965-06-01T00:00:00.000Z|604
Note − By changing the SQL query above, you can get different result sets.
To monitor the health of the cluster, the monitoring feature collects metrics from each node and stores them in Elasticsearch Indices. All settings associated with monitoring in Elasticsearch must be set in either the elasticsearch.yml file for each node or, where possible, in the dynamic cluster settings.
In order to start monitoring, we need to check the cluster settings, which can be done in the following way −
GET _cluster/settings
{
"persistent" : { },
"transient" : { }
}
Each component in the stack is responsible for monitoring itself and then forwarding those documents to the Elasticsearch production cluster for both routing and indexing (storage). The routing and indexing processes in Elasticsearch are handled by what are called collectors and exporters.
Collector runs once per each collection interval to obtain data from the public APIs in Elasticsearch that it chooses to monitor. When the data collection is finished, the data is handed in bulk to the exporters to be sent to the monitoring cluster.
There is only one collector per data type gathered. Each collector can create zero or more monitoring documents.
Exporters take data collected from any Elastic Stack source and route it to the monitoring cluster. It is possible to configure more than one exporter, but the general and default setup is to use a single exporter. Exporters are configurable at both the node and cluster level.
There are two types of exporters in Elasticsearch −
local − This exporter routes data back into the same cluster
local − This exporter routes data back into the same cluster
http − The preferred exporter, which you can use to route data into any supported Elasticsearch cluster accessible via HTTP.
http − The preferred exporter, which you can use to route data into any supported Elasticsearch cluster accessible via HTTP.
Before exporters can route monitoring data, they must set up certain Elasticsearch resources. These resources include templates and ingest pipelines
A rollup job is a periodic task that summarizes data from indices specified by an index pattern and rolls it into a new index. In the following example, we create an index named sensor with different date time stamps. Then we create a rollup job to rollup the data from these indices periodically using cron job.
PUT /sensor/_doc/1
{
"timestamp": 1516729294000,
"temperature": 200,
"voltage": 5.2,
"node": "a"
}
On running the above code, we get the following result −
{
"_index" : "sensor",
"_type" : "_doc",
"_id" : "1",
"_version" : 1,
"result" : "created",
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 0,
"_primary_term" : 1
}
Now, add a second document and so on for other documents as well.
PUT /sensor-2018-01-01/_doc/2
{
"timestamp": 1413729294000,
"temperature": 201,
"voltage": 5.9,
"node": "a"
}
PUT _rollup/job/sensor
{
"index_pattern": "sensor-*",
"rollup_index": "sensor_rollup",
"cron": "*/30 * * * * ?",
"page_size" :1000,
"groups" : {
"date_histogram": {
"field": "timestamp",
"interval": "60m"
},
"terms": {
"fields": ["node"]
}
},
"metrics": [
{
"field": "temperature",
"metrics": ["min", "max", "sum"]
},
{
"field": "voltage",
"metrics": ["avg"]
}
]
}
The cron parameter controls when and how often the job activates. When a rollup job’s cron schedule triggers, it will begin rolling up from where it left off after the last activation
After the job has run and processed some data, we can use the DSL Query to do some searching.
GET /sensor_rollup/_rollup_search
{
"size": 0,
"aggregations": {
"max_temperature": {
"max": {
"field": "temperature"
}
}
}
}
The indices that are searched frequently are held in memory because it takes time to rebuild them and help in an efficient search. On the other hand, there may be indices which we rarely access. Those indices need not occupy the memory and can be re-build when they are needed. Such indices are known as frozen indices.
Elasticsearch builds the transient data structures of each shard of a frozen index each time
that shard is searched and discards these data structures as soon as the search is complete. Because Elasticsearch does not maintain these transient data structures in memory, frozen indices consume much less heap than the normal indices. This allows for a much higher disk-to-heap ratio than would otherwise be possible.
The following example freezes and unfreezes an index −
POST /index_name/_freeze
POST /index_name/_unfreeze
Searches on frozen indices are expected to execute slowly. Frozen indices are not intended
for high search load. It is possible that a search of a frozen index may take seconds or minutes to complete, even if the same searches completed in milliseconds when the indices were not frozen.
The number of concurrently loaded frozen indices per node is limited by the number of threads in the search_throttled threadpool, which is 1 by default. To include frozen indices,
a search request must be executed with the query parameter − ignore_throttled=false.
GET /index_name/_search?q=user:tpoint&ignore_throttled=false
Frozen indices are ordinary indices that use search throttling and a memory efficient shard
implementation.
GET /_cat/indices/index_name?v&h=i,sth
Elasticsearch provides a jar file, which can be added to any java IDE and can be used to test the code which is related to Elasticsearch. A range of tests can be performed by using the framework provided by Elasticsearch. In this chapter, we will discuss these tests in detail −
Unit testing
Integration testing
Randomized testing
To start with testing, you need to add the Elasticsearch testing dependency to your program. You can use maven for this purpose and can add the following in pom.xml.
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>2.1.0</version>
</dependency>
EsSetup has been initialized to start and stop Elasticsearch node and also to create indices.
EsSetup esSetup = new EsSetup();
esSetup.execute() function with createIndex will create the indices, you need to specify the settings, type and data.
Unit test is carried out by using JUnit and Elasticsearch test framework. Node and indices can be created using Elasticsearch classes and in test method can be used to perform the testing. ESTestCase and ESTokenStreamTestCase classes are used for this testing.
Integration testing uses multiple nodes in a cluster. ESIntegTestCase class is used for this testing. There are various methods which make the job of preparing a test case easier.
refresh()
All the indices in a cluster are refreshed
ensureGreen()
Ensures a green health cluster state
ensureYellow()
Ensures a yellow health cluster state
createIndex(name)
Create index with the name passed to this method
flush()
All indices in cluster are flushed
flushAndRefresh()
flush() and refresh()
indexExists(name)
Verifies the existence of specified index
clusterService()
Returns the cluster service java class
cluster()
Returns the test cluster class
ensureAtLeastNumNodes(n)
Ensures minimum number of nodes up in a cluster is more than or equal to specified number.
ensureAtMostNumNodes(n)
Ensures maximum number of nodes up in a cluster is less than or equal to specified number.
stopRandomNode()
To stop a random node in a cluster
stopCurrentMasterNode()
To stop the master node
stopRandomNonMaster()
To stop a random node in a cluster, which is not a master node.
buildNode()
Create a new node
startNode(settings)
Start a new node
nodeSettings()
Override this method for changing node settings.
A client is used to access different nodes in a cluster and carry out some action. ESIntegTestCase.client() method is used for getting a random client. Elasticsearch offers other methods also to access client and those methods can be accessed using ESIntegTestCase.internalCluster() method.
iterator()
This helps you to access all the available clients.
masterClient()
This returns a client, which is communicating with master node.
nonMasterClient()
This returns a client, which is not communicating with master node.
clientNodeClient()
This returns a client currently up on client node.
This testing is used to test the user’s code with every possible data, so that there will be no failure in future with any type of data. Random data is the best option to carry out this testing.
In this testing, the Random class is instantiated by the instance provided by RandomizedTest and offers many methods for getting different types of data.
ElasticsearchAssertions and ElasticsearchGeoAssertions classes contain assertions, which are used for performing some common checks at the time of testing. For example, observe the code given here −
SearchResponse seearchResponse = client().prepareSearch();
assertHitCount(searchResponse, 6);
assertFirstHit(searchResponse, hasId("6"));
assertSearchHits(searchResponse, "1", "2", "3", "4",”5”,”6”);
A Kibana dashboard is a collection of visualizations and searches. You can arrange, resize,
and edit the dashboard content and then save the dashboard so you can share it. In this chapter, we will see how to create and edit a dashboard.
From the Kibana Homepage, select the dashboard option from the left control bars as shown below. This will prompt you to create a new dashboard.
To Add visualizations to the dashboard, we choose the menu Add and the select from the pre-built visualizations available. We chose the following visualization options from the list.
On selecting the above visualizations, we get the dashboard as shown here. We can later add and edit the dashboard for changing the elements and adding the new elements.
We can inspect the Dashboard elements by choosing the visualizations panel menu and selecting Inspect. This will bring out the data behind the element which also can be downloaded.
We can share the dashboard by choosing the share menu and selecting the option to get
a hyperlink as shown below −
The discover functionality available in Kibana home page allows us to explore the data sets
from various angles. You can search and filter data for the selected index patterns. The data is usually available in form of distribution of values over a period of time.
To explore the ecommerce data sample, we click on the Discover icon as shown in the
picture below. This will bring up the data along with the chart.
To filter out data by specific time interval we use the time filter option as shown below. By
default, the filter is set at 15 minutes.
The data set can also be filtered by fields using the Add Filter option as shown below. Here we add one or more fields and get the corresponding result after the filters are applied. In our example we choose the field day_of_week and then the operator for that field as is and value as Sunday.
Next, we click Save with above filter conditions. The result set containing the filter
conditions applied is shown below.
The data table is type of visualization that is used to display the raw data of a composed
aggregation. There are various types of aggregations that are presented by using Data tables. In order to create a Data Table, we should go through the steps that are discussed here in detail.
In Kibana Home screen we find the option name Visualize which allows us to create visualization and aggregations from the indices stored in Elasticsearch. The following image shows the option.
Next, we select the Data Table option from among the various visualization options available. The option is shown in the following image &miuns;
We then select the metrics needed for creating the data table visualization. This choice
decides the type of aggregation we are going to use. We select the specific fields shown below from the ecommerce data set for this.
On running the above configuration for Data Table, we get the result as shown in the
image here −
Region Maps show metrics on a geographic Map. It is useful in looking at the data anchored to different geographic regions with varying intensity. The darker shades usually indicate higher values and the lighter shades indicate lower values.
The steps to create this visualization are as explained in detail as follows −
In this step we go to the visualize button available in the left bar of the Kibana Home
screen and then choosing the option to add a new Visualization.
The following screen shows how we choose the region Map option.
The next screen prompts us for choosing the metrics which will be used in creating the Region Map. Here we choose the Average price as the metric and country_iso_code as the field in the bucket which will be used in creating the visualization.
The final result below shows the Region Map once we apply the selection. Please note the
shades of the colour and their values mentioned in the label.
Pie charts are one of the simplest and famous visualization tools. It represents the data as slices of a circle each coloured differently. The labels along with the percentage data values can be presented along with the circle. The circle can also take the shape of a donut.
In Kibana Home screen, we find the option name Visualize which allows us to create visualization and aggregations from the indices stored in Elasticsearch. We choose to add a new visualization and select pie chart as the option shown below.
The next screen prompts us for choosing the metrics which will be used in creating the Pie Chart. Here we choose the count of base unit price as the metric and Bucket Aggregation as histogram. Also, the minimum interval is chosen as 20. So, the prices will be displayed as blocks of values with 20 as a range.
The result below shows the pie chart after we apply the selection. Please note the shades of the colour and their values mentioned in the label.
On moving to the options tab under pie chart we can see various configuration options to change the look as well as the arrangement of data display in the pie chart. In the following example, the pie chart appears as donut and the labels appear at the top.
An area chart is an extension of line chart where the area between the line chart and the axes is highlighted with some colours. A bar chart represents data organized into a range of values and then plotted against the axes. It can consist of either horizontal bars or vertical bars.
In this chapter we will see all these three types of graphs that is created using Kibana. As
discussed in earlier chapters we will continue to use the data in the ecommerce index.
In Kibana Home screen, we find the option name Visualize which allows us to create
visualization and aggregations from the indices stored in Elasticsearch. We choose to add a new visualization and select Area Chart as the option shown in the image given below.
The next screen prompts us for choosing the metrics which will be used in creating the Area Chart. Here we choose the sum as the type of aggregation metric. Then we choose total_quantity field as the field to be used as metric. On the X-axis, we chose the order_date field and split the series with the given metric in a size of 5.
On running the above configuration, we get the following area chart as the output −
Similarly, for the Horizontal bar chart we choose new visualization from Kibana Home screen and choose the option for Horizontal Bar. Then we choose the metrics as shown in the image below. Here we choose Sum as the aggregation for the filed named product quantity. Then we choose buckets with date histogram for the field order date.
On running the above configuration, we can see a horizontal bar chart as shown below −
For the vertical bar chart, we choose new visualization from Kibana Home screen and choose the option for Vertical Bar. Then we choose the metrics as shown in the image below.
Here we choose Sum as the aggregation for the field named product quantity. Then we choose buckets with date histogram for the field order date with a weekly interval.
On running the above configuration, a chart will be generated as shown below −
Time series is a representation of sequence of data in a specific time sequence. For example, the data for each day starting from first day of the month to the last day. The interval between the data points remains constant. Any data set which has a time component in it can be represented as a time series.
In this chapter, we will use the sample e-commerce data set and plot the count of the number of orders for each day to create a time series.
First, we choose the index pattern, data field and interval which will be used for creating
the time series. From the sample ecommerce data set we choose order_date as the field and 1d as the interval. We use the Panel Options tab to make these choices. Also we leave the other values in this tab as default to get a default colour and format for the time series.
In the Data tab, we choose count as the aggregation option, group by option as everything and put a label for the time series chart.
The final result of this configuration appears as follows. Please note that we are using a
time period of Month to Date for this graph. Different time periods will give different results.
A tag cloud represents text which are mostly keywords and metadata in a visually appealing form. They are aligned in different angles and represented in different colours and font sizes. It helps in finding out the most prominent terms in the data. The prominence can be decided by one or more factors like frequency of the term, uniquness of the tag or based on some weightage attached to specific terms etc. Below we see the steps to create a Tag Cloud.
In Kibana Home screen, we find the option name Visualize which allows us to create
visualization and aggregations from the indices stored in Elasticsearch. We choose to add a new visualization and select Tag Cloud as the option shown below −
The next screen prompts us for choosing the metrics which will be used in creating the Tag Cloud. Here we choose the count as the type of aggregation metric. Then we choose productname field as the keyword to be used as tags.
The result shown here shows the pie chart after we apply the selection. Please note the
shades of the colour and their values mentioned in the label.
On moving to the options tab under Tag Cloud we can see various configuration options to change the look as well as the arrangement of data display in the Tag Cloud. In the below example the Tag Cloud appears with tags spread across both horizontal and vertical directions.
Heat map is a type of visualization in which different shades of colour represent different
areas in the graph. The values may be continuously varying and hence the colour r shades of a colour vary along with the values. They are very useful to represent both the continuously varying data as well as discrete data.
In this chapter we will use the data set named sample_data_flights to build a heatmap chart. In it we consider the variables named origin country and destination country of flights and take a count.
In Kibana Home screen, we find the option name Visualize which allows us to create
visualization and aggregations from the indices stored in Elasticsearch. We choose to add a new visualization and select Heat Map as the option shown below &mimus;
The next screen prompts us for choosing the metrics which will be used in creating the Heat Map Chart. Here we choose the count as the type of aggregation metric. Then for the buckets in Y-Axis, we choose Terms as the aggregation for the field OriginCountry. For the X-Axis, we choose the same aggregation but DestCountry as the field to be used. In both the cases, we choose the size of the bucket as 5.
On running the above shown configuration, we get the heat map chart generated as follows.
Note − You have to allow the date range as This Year so that the graph gathers data for a year to produce an effective heat map chart.
Canvas application is a part of Kibana which allows us to create dynamic, multi-page and
pixel perfect data displays. Its ability to create infographics and not just charts and metrices is what makes it unique and appealing. In this chapter we will see various features of canvas and how to use the canvas work pads.
Go to the Kibana homepage and select the option as shown in the below diagram. It opens up the list of canvas work pads you have. We choose the ecommerce Revenue tracking for our study.
We clone the [eCommerce] Revenue Tracking workpad to be used in our study. To clone it, we highlight the row with the name of this workpad and then use the clone button as shown in the diagram below −
As a result of the above clone, we will get a new work pad named as [eCommerce]
Revenue Tracking – Copy which on opening will show the below infographics.
It describes the total sales and Revenue by category along with nice pictures and charts.
We can change the style and figures in the workpad by using the options available in the
right hand side tab. Here we aim to change the background colour of the workpad by choosing a different colour as shown in the diagram below. The colour selection comes into effect immediately and we get the result as shown below −
Kibana can also help in visualizing log data from various sources. Logs are important sources of analysis for infrastructure health, performance needs and security breach analysis etc. Kibana can connect to various logs like web server logs, elasticsearch logs and cloudwatch logs etc.
In Kibana, we can connect to logstash logs for visualization. First we choose the Logs
button from the Kibana home screen as shown below −
Then we choose the option Change Source Configuration which brings us the option to choose Logstash as a source. The below screen also shows other types of options we have as a log source.
You can stream data for live log tailing or pause streaming to focus on historical log data.
When you are streaming logs, the most recent log appears at the bottom on the console.
For further reference, you can refer to our Logstash tutorial.
14 Lectures
5 hours
Manuj Aggarwal
20 Lectures
1 hours
Faizan Tayyab
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2761,
"s": 2581,
"text": "Elasticsearch is an Apache Lucene-based search server. It was developed by Shay Banon and published in 2010. It is now maintained by Elasticsearch BV. Its latest version is 7.0.0."
},
{
"code": null,
"e": 3160,
"s": 2761,
"text": "Elasticsearch is a real-time distributed and open source full-text search and analytics engine. It is accessible from RESTful web service interface and uses schema less JSON (JavaScript Object Notation) documents to store data. It is built on Java programming language and hence Elasticsearch can run on different platforms. It enables users to explore very large amount of data at very high speed."
},
{
"code": null,
"e": 3215,
"s": 3160,
"text": "The general features of Elasticsearch are as follows −"
},
{
"code": null,
"e": 3294,
"s": 3215,
"text": "Elasticsearch is scalable up to petabytes of structured and unstructured data."
},
{
"code": null,
"e": 3373,
"s": 3294,
"text": "Elasticsearch is scalable up to petabytes of structured and unstructured data."
},
{
"code": null,
"e": 3461,
"s": 3373,
"text": "Elasticsearch can be used as a replacement of document stores like MongoDB and RavenDB."
},
{
"code": null,
"e": 3549,
"s": 3461,
"text": "Elasticsearch can be used as a replacement of document stores like MongoDB and RavenDB."
},
{
"code": null,
"e": 3619,
"s": 3549,
"text": "Elasticsearch uses denormalization to improve the search performance."
},
{
"code": null,
"e": 3689,
"s": 3619,
"text": "Elasticsearch uses denormalization to improve the search performance."
},
{
"code": null,
"e": 3863,
"s": 3689,
"text": "Elasticsearch is one of the popular enterprise search engines, and is currently being used by many big organizations like Wikipedia, The Guardian, StackOverflow, GitHub etc."
},
{
"code": null,
"e": 4037,
"s": 3863,
"text": "Elasticsearch is one of the popular enterprise search engines, and is currently being used by many big organizations like Wikipedia, The Guardian, StackOverflow, GitHub etc."
},
{
"code": null,
"e": 4121,
"s": 4037,
"text": "Elasticsearch is an open source and available under the Apache license version 2.0."
},
{
"code": null,
"e": 4205,
"s": 4121,
"text": "Elasticsearch is an open source and available under the Apache license version 2.0."
},
{
"code": null,
"e": 4256,
"s": 4205,
"text": "The key concepts of Elasticsearch are as follows −"
},
{
"code": null,
"e": 4476,
"s": 4256,
"text": "It refers to a single running instance of Elasticsearch. Single physical and virtual server accommodates multiple nodes depending upon the capabilities of their physical resources like RAM, storage and processing power."
},
{
"code": null,
"e": 4616,
"s": 4476,
"text": "It is a collection of one or more nodes. Cluster provides collective indexing and search capabilities across all the nodes for entire data."
},
{
"code": null,
"e": 4835,
"s": 4616,
"text": "It is a collection of different type of documents and their properties. Index also uses the concept of shards to improve the performance. For example, a set of document contains data of a social networking application."
},
{
"code": null,
"e": 5041,
"s": 4835,
"text": "It is a collection of fields in a specific manner defined in JSON format. Every document belongs to a type and resides inside an index. Every document is associated with a unique identifier called the UID."
},
{
"code": null,
"e": 5420,
"s": 5041,
"text": "Indexes are horizontally subdivided into shards. This means each shard contains all the properties of document but contains less number of JSON objects than index. The horizontal separation makes shard an independent node, which can be store in any node. Primary shard is the original horizontal part of an index and then these primary shards are replicated into replica shards."
},
{
"code": null,
"e": 5692,
"s": 5420,
"text": "Elasticsearch allows a user to create replicas of their indexes and shards. Replication not only helps in increasing the availability of data in case of failure, but also improves the performance of searching by carrying out a parallel search operation in these replicas."
},
{
"code": null,
"e": 5780,
"s": 5692,
"text": "Elasticsearch is developed on Java, which makes it compatible on almost every platform."
},
{
"code": null,
"e": 5868,
"s": 5780,
"text": "Elasticsearch is developed on Java, which makes it compatible on almost every platform."
},
{
"code": null,
"e": 5976,
"s": 5868,
"text": "Elasticsearch is real time, in other words after one second the added document is searchable in this engine"
},
{
"code": null,
"e": 6084,
"s": 5976,
"text": "Elasticsearch is real time, in other words after one second the added document is searchable in this engine"
},
{
"code": null,
"e": 6182,
"s": 6084,
"text": "Elasticsearch is distributed, which makes it easy to scale and integrate in any big organization."
},
{
"code": null,
"e": 6280,
"s": 6182,
"text": "Elasticsearch is distributed, which makes it easy to scale and integrate in any big organization."
},
{
"code": null,
"e": 6380,
"s": 6280,
"text": "Creating full backups are easy by using the concept of gateway, which is present in Elasticsearch.\n"
},
{
"code": null,
"e": 6480,
"s": 6380,
"text": "Creating full backups are easy by using the concept of gateway, which is present in Elasticsearch.\n"
},
{
"code": null,
"e": 6563,
"s": 6480,
"text": "Handling multi-tenancy is very easy in Elasticsearch when compared to Apache Solr."
},
{
"code": null,
"e": 6646,
"s": 6563,
"text": "Handling multi-tenancy is very easy in Elasticsearch when compared to Apache Solr."
},
{
"code": null,
"e": 6807,
"s": 6646,
"text": "Elasticsearch uses JSON objects as responses, which makes it possible to invoke the Elasticsearch server with a large number of different programming languages."
},
{
"code": null,
"e": 6968,
"s": 6807,
"text": "Elasticsearch uses JSON objects as responses, which makes it possible to invoke the Elasticsearch server with a large number of different programming languages."
},
{
"code": null,
"e": 7067,
"s": 6968,
"text": "Elasticsearch supports almost every document type except those that do not support text rendering."
},
{
"code": null,
"e": 7166,
"s": 7067,
"text": "Elasticsearch supports almost every document type except those that do not support text rendering."
},
{
"code": null,
"e": 7362,
"s": 7166,
"text": "Elasticsearch does not have multi-language support in terms of handling request and response data (only possible in JSON) unlike in Apache Solr, where it is possible in CSV, XML and JSON formats."
},
{
"code": null,
"e": 7558,
"s": 7362,
"text": "Elasticsearch does not have multi-language support in terms of handling request and response data (only possible in JSON) unlike in Apache Solr, where it is possible in CSV, XML and JSON formats."
},
{
"code": null,
"e": 7627,
"s": 7558,
"text": "Occasionally, Elasticsearch has a problem of Split brain situations."
},
{
"code": null,
"e": 7696,
"s": 7627,
"text": "Occasionally, Elasticsearch has a problem of Split brain situations."
},
{
"code": null,
"e": 7893,
"s": 7696,
"text": "In Elasticsearch, index is similar to tables in RDBMS (Relation Database Management System). Every table is a collection of rows just as every index is a collection of documents in Elasticsearch. "
},
{
"code": null,
"e": 7960,
"s": 7893,
"text": "The following table gives a direct comparison between these terms−"
},
{
"code": null,
"e": 8051,
"s": 7960,
"text": "In this chapter, we will understand the installation procedure of Elasticsearch in detail."
},
{
"code": null,
"e": 8148,
"s": 8051,
"text": "To install Elasticsearch on your local computer, you will have to follow the steps given below −"
},
{
"code": null,
"e": 8281,
"s": 8148,
"text": "Step 1 − Check the version of java installed on your computer. It should be java 7 or higher. You can check by doing the following −"
},
{
"code": null,
"e": 8338,
"s": 8281,
"text": "In Windows Operating System (OS) (using command prompt)−"
},
{
"code": null,
"e": 8355,
"s": 8338,
"text": "> java -version\n"
},
{
"code": null,
"e": 8385,
"s": 8355,
"text": "In UNIX OS (Using Terminal) −"
},
{
"code": null,
"e": 8404,
"s": 8385,
"text": "$ echo $JAVA_HOME\n"
},
{
"code": null,
"e": 8513,
"s": 8404,
"text": "Step 2 − Depending on your operating system, download Elasticsearch from www.elastic.co as mentioned below −"
},
{
"code": null,
"e": 8548,
"s": 8513,
"text": "For windows OS, download ZIP file."
},
{
"code": null,
"e": 8583,
"s": 8548,
"text": "For windows OS, download ZIP file."
},
{
"code": null,
"e": 8615,
"s": 8583,
"text": "For UNIX OS, download TAR file."
},
{
"code": null,
"e": 8647,
"s": 8615,
"text": "For UNIX OS, download TAR file."
},
{
"code": null,
"e": 8681,
"s": 8647,
"text": "For Debian OS, download DEB file."
},
{
"code": null,
"e": 8715,
"s": 8681,
"text": "For Debian OS, download DEB file."
},
{
"code": null,
"e": 8777,
"s": 8715,
"text": "For Red Hat and other Linux distributions, download RPN file."
},
{
"code": null,
"e": 8839,
"s": 8777,
"text": "For Red Hat and other Linux distributions, download RPN file."
},
{
"code": null,
"e": 8932,
"s": 8839,
"text": "APT and Yum utilities can also be used to install Elasticsearch in many Linux distributions."
},
{
"code": null,
"e": 9025,
"s": 8932,
"text": "APT and Yum utilities can also be used to install Elasticsearch in many Linux distributions."
},
{
"code": null,
"e": 9125,
"s": 9025,
"text": "Step 3 − Installation process for Elasticsearch is simple and is described below for different OS −"
},
{
"code": null,
"e": 9195,
"s": 9125,
"text": "Windows OS− Unzip the zip package and the Elasticsearch is installed."
},
{
"code": null,
"e": 9265,
"s": 9195,
"text": "Windows OS− Unzip the zip package and the Elasticsearch is installed."
},
{
"code": null,
"e": 9343,
"s": 9265,
"text": "UNIX OS− Extract tar file in any location and the Elasticsearch is installed."
},
{
"code": null,
"e": 9421,
"s": 9343,
"text": "UNIX OS− Extract tar file in any location and the Elasticsearch is installed."
},
{
"code": null,
"e": 9571,
"s": 9421,
"text": "$wget\nhttps://artifacts.elastic.co/downloads/elasticsearch/elasticsearch7.0.0-linux-x86_64.tar.gz\n\n$tar -xzf elasticsearch-7.0.0-linux-x86_64.tar.gz\n"
},
{
"code": null,
"e": 9648,
"s": 9571,
"text": "Using APT utility for Linux OS− Download and install the Public Signing Key "
},
{
"code": null,
"e": 9725,
"s": 9648,
"text": "Using APT utility for Linux OS− Download and install the Public Signing Key "
},
{
"code": null,
"e": 9811,
"s": 9725,
"text": "$ wget -qo - https://artifacts.elastic.co/GPG-KEY-elasticsearch | sudo\napt-key add -\n"
},
{
"code": null,
"e": 9859,
"s": 9811,
"text": "Save the repository definition as shown below −"
},
{
"code": null,
"e": 9986,
"s": 9859,
"text": "$ echo \"deb https://artifacts.elastic.co/packages/7.x/apt stable main\" |\nsudo tee -a /etc/apt/sources.list.d/elastic-7.x.list\n"
},
{
"code": null,
"e": 10027,
"s": 9986,
"text": "Run update using the following command −"
},
{
"code": null,
"e": 10050,
"s": 10027,
"text": "$ sudo apt-get update\n"
},
{
"code": null,
"e": 10103,
"s": 10050,
"text": "Now you can install by using the following command −"
},
{
"code": null,
"e": 10141,
"s": 10103,
"text": "$ sudo apt-get install elasticsearch\n"
},
{
"code": null,
"e": 10221,
"s": 10141,
"text": "Download and install the Debian package manually using the command given here −"
},
{
"code": null,
"e": 10301,
"s": 10221,
"text": "Download and install the Debian package manually using the command given here −"
},
{
"code": null,
"e": 10435,
"s": 10301,
"text": "$wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch7.0.0-amd64.deb\n$sudo dpkg -i elasticsearch-7.0.0-amd64.deb0\n"
},
{
"code": null,
"e": 10473,
"s": 10435,
"text": "Using YUM utility for Debian Linux OS"
},
{
"code": null,
"e": 10511,
"s": 10473,
"text": "Using YUM utility for Debian Linux OS"
},
{
"code": null,
"e": 10557,
"s": 10511,
"text": "Download and install the Public Signing Key −"
},
{
"code": null,
"e": 10624,
"s": 10557,
"text": "$ rpm --import https://artifacts.elastic.co/GPG-KEY-elasticsearch\n"
},
{
"code": null,
"e": 10748,
"s": 10624,
"text": "ADD the following text in the file with .repo suffix in your “/etc/yum.repos.d/” directory. For example, elasticsearch.repo"
},
{
"code": null,
"e": 10872,
"s": 10748,
"text": "ADD the following text in the file with .repo suffix in your “/etc/yum.repos.d/” directory. For example, elasticsearch.repo"
},
{
"code": null,
"e": 11098,
"s": 10872,
"text": "elasticsearch-7.x]\nname=Elasticsearch repository for 7.x packages\nbaseurl=https://artifacts.elastic.co/packages/7.x/yum\ngpgcheck=1\ngpgkey=https://artifacts.elastic.co/GPG-KEY-elasticsearch\nenabled=1\nautorefresh=1\ntype=rpm-md\n"
},
{
"code": null,
"e": 11163,
"s": 11098,
"text": "You can now install Elasticsearch by using the following command"
},
{
"code": null,
"e": 11228,
"s": 11163,
"text": "You can now install Elasticsearch by using the following command"
},
{
"code": null,
"e": 11260,
"s": 11228,
"text": "sudo yum install elasticsearch\n"
},
{
"code": null,
"e": 11490,
"s": 11260,
"text": "Step 4 − Go to the Elasticsearch home directory and inside the bin folder. Run the\nelasticsearch.bat file in case of Windows or you can do the same using command prompt and through terminal in case of UNIX rum Elasticsearch file."
},
{
"code": null,
"e": 11536,
"s": 11490,
"text": "> cd elasticsearch-2.1.0/bin\n> elasticsearch\n"
},
{
"code": null,
"e": 11584,
"s": 11536,
"text": "$ cd elasticsearch-2.1.0/bin\n$ ./elasticsearch\n"
},
{
"code": null,
"e": 11784,
"s": 11584,
"text": "Note − In case of windows, you might get an error stating JAVA_HOME is not set, please\nset it in environment variables to “C:\\Program Files\\Java\\jre1.8.0_31” or the location where you installed java."
},
{
"code": null,
"e": 12155,
"s": 11784,
"text": "Step 5 − The default port for Elasticsearch web interface is 9200 or you can change it by\nchanging http.port inside the elasticsearch.yml file present in bin directory. You can check if the server is up and running by browsing http://localhost:9200. It will return a JSON object, which contains the information about the installed Elasticsearch in the following manner −"
},
{
"code": null,
"e": 12487,
"s": 12155,
"text": "{\n \"name\" : \"Brain-Child\",\n \"cluster_name\" : \"elasticsearch\", \"version\" : {\n \"number\" : \"2.1.0\",\n \"build_hash\" : \"72cd1f1a3eee09505e036106146dc1949dc5dc87\",\n \"build_timestamp\" : \"2015-11-18T22:40:03Z\",\n \"build_snapshot\" : false,\n \"lucene_version\" : \"5.3.1\"\n },\n \"tagline\" : \"You Know, for Search\"\n}"
},
{
"code": null,
"e": 12610,
"s": 12487,
"text": "Step 6 − In this step, let us install Kibana. Follow the respective code given below for\ninstalling on Linux and Windows −"
},
{
"code": null,
"e": 12638,
"s": 12610,
"text": "For Installation on Linux −"
},
{
"code": null,
"e": 12810,
"s": 12638,
"text": "wget https://artifacts.elastic.co/downloads/kibana/kibana-7.0.0-linuxx86_64.tar.gz\n\ntar -xzf kibana-7.0.0-linux-x86_64.tar.gz\n\ncd kibana-7.0.0-linux-x86_64/\n\n./bin/kibana\n"
},
{
"code": null,
"e": 12840,
"s": 12810,
"text": "For Installation on Windows −"
},
{
"code": null,
"e": 12983,
"s": 12840,
"text": "Download Kibana for Windows from https://www.elastic.co/products/kibana. Once you click the link, you will find the home page as shown below −"
},
{
"code": null,
"e": 13042,
"s": 12983,
"text": "Unzip and go to the Kibana home directory and then run it."
},
{
"code": null,
"e": 13094,
"s": 13042,
"text": "CD c:\\kibana-7.0.0-windows-x86_64\n.\\bin\\kibana.bat\n"
},
{
"code": null,
"e": 13267,
"s": 13094,
"text": "In this chapter, let us learn how to add some index, mapping and data to Elasticsearch. Note that some of this data will be used in the examples explained in this tutorial."
},
{
"code": null,
"e": 13322,
"s": 13267,
"text": "You can use the following command to create an index −"
},
{
"code": null,
"e": 13334,
"s": 13322,
"text": "PUT school\n"
},
{
"code": null,
"e": 13394,
"s": 13334,
"text": "If the index is created, you can see the following output −"
},
{
"code": null,
"e": 13418,
"s": 13394,
"text": "{\"acknowledged\": true}\n"
},
{
"code": null,
"e": 13586,
"s": 13418,
"text": "Elasticsearch will store the documents we add to the index as shown in the following code. The documents are given some IDs which are used in identifying the document."
},
{
"code": null,
"e": 13859,
"s": 13586,
"text": "POST school/_doc/10\n{\n \"name\":\"Saint Paul School\", \"description\":\"ICSE Afiliation\",\n \"street\":\"Dawarka\", \"city\":\"Delhi\", \"state\":\"Delhi\", \"zip\":\"110075\",\n \"location\":[28.5733056, 77.0122136], \"fees\":5000,\n \"tags\":[\"Good Faculty\", \"Great Sports\"], \"rating\":\"4.5\"\n}\n"
},
{
"code": null,
"e": 14096,
"s": 13859,
"text": "{\n \"_index\" : \"school\",\n \"_type\" : \"_doc\",\n \"_id\" : \"10\",\n \"_version\" : 1,\n \"result\" : \"created\",\n \"_shards\" : {\n \"total\" : 2,\n \"successful\" : 1,\n \"failed\" : 0\n },\n \"_seq_no\" : 2,\n \"_primary_term\" : 1\n}\n"
},
{
"code": null,
"e": 14142,
"s": 14096,
"text": "Here, we are adding another similar document."
},
{
"code": null,
"e": 14409,
"s": 14142,
"text": "POST school/_doc/16\n{\n \"name\":\"Crescent School\", \"description\":\"State Board Affiliation\",\n \"street\":\"Tonk Road\",\n \"city\":\"Jaipur\", \"state\":\"RJ\", \"zip\":\"176114\",\"location\":[26.8535922,75.7923988],\n \"fees\":2500, \"tags\":[\"Well equipped labs\"], \"rating\":\"4.5\"\n}\n"
},
{
"code": null,
"e": 14646,
"s": 14409,
"text": "{\n \"_index\" : \"school\",\n \"_type\" : \"_doc\",\n \"_id\" : \"16\",\n \"_version\" : 1,\n \"result\" : \"created\",\n \"_shards\" : {\n \"total\" : 2,\n \"successful\" : 1,\n \"failed\" : 0\n },\n \"_seq_no\" : 9,\n \"_primary_term\" : 7\n}\n"
},
{
"code": null,
"e": 14751,
"s": 14646,
"text": "In this way, we will keep adding any example data that we need for our working in the upcoming chapters."
},
{
"code": null,
"e": 14903,
"s": 14751,
"text": "Kibana is a GUI driven tool for accessing the data and creating the visualization. In this section, let us understand how we can add sample data to it."
},
{
"code": null,
"e": 14987,
"s": 14903,
"text": "In the Kibana home page, choose the following option to add sample ecommerce data −"
},
{
"code": null,
"e": 15059,
"s": 14987,
"text": "The next screen will show some visualization and a button to Add data −"
},
{
"code": null,
"e": 15179,
"s": 15059,
"text": "Clicking on Add Data will show the following screen which confirms the data has been added to an index named eCommerce."
},
{
"code": null,
"e": 15497,
"s": 15179,
"text": "In any system or software, when we are upgrading to newer version, we need to follow a few steps to maintain the application settings, configurations, data and other things. These steps are required to make the application stable in new system or to maintain the integrity of data (prevent data from getting corrupt)."
},
{
"code": null,
"e": 15563,
"s": 15497,
"text": "You need to follow the following steps to upgrade Elasticsearch −"
},
{
"code": null,
"e": 15610,
"s": 15563,
"text": "Read Upgrade docs from https://www.elastic.co/"
},
{
"code": null,
"e": 15657,
"s": 15610,
"text": "Read Upgrade docs from https://www.elastic.co/"
},
{
"code": null,
"e": 15761,
"s": 15657,
"text": "Test the upgraded version in your non production environments like in UAT, E2E, SIT or DEV environment."
},
{
"code": null,
"e": 15865,
"s": 15761,
"text": "Test the upgraded version in your non production environments like in UAT, E2E, SIT or DEV environment."
},
{
"code": null,
"e": 16029,
"s": 15865,
"text": "Note that rollback to previous Elasticsearch version is not possible without data backup. Hence, a data backup is recommended before upgrading to a higher version."
},
{
"code": null,
"e": 16193,
"s": 16029,
"text": "Note that rollback to previous Elasticsearch version is not possible without data backup. Hence, a data backup is recommended before upgrading to a higher version."
},
{
"code": null,
"e": 16387,
"s": 16193,
"text": "We can upgrade using full cluster restart or rolling upgrade. Rolling upgrade is for new versions. Note that there is no service outage, when you are using rolling upgrade method for migration."
},
{
"code": null,
"e": 16581,
"s": 16387,
"text": "We can upgrade using full cluster restart or rolling upgrade. Rolling upgrade is for new versions. Note that there is no service outage, when you are using rolling upgrade method for migration."
},
{
"code": null,
"e": 16661,
"s": 16581,
"text": "Test the upgrade in a dev environment before upgrading your production cluster."
},
{
"code": null,
"e": 16741,
"s": 16661,
"text": "Test the upgrade in a dev environment before upgrading your production cluster."
},
{
"code": null,
"e": 16844,
"s": 16741,
"text": "Back up your data. You cannot roll back to an earlier version unless you have a snapshot of your data."
},
{
"code": null,
"e": 16947,
"s": 16844,
"text": "Back up your data. You cannot roll back to an earlier version unless you have a snapshot of your data."
},
{
"code": null,
"e": 17167,
"s": 16947,
"text": "Consider closing machine learning jobs before you start the upgrade process. While machine learning jobs can continue to run during a rolling upgrade, it increases the overhead on the cluster during the upgrade process."
},
{
"code": null,
"e": 17387,
"s": 17167,
"text": "Consider closing machine learning jobs before you start the upgrade process. While machine learning jobs can continue to run during a rolling upgrade, it increases the overhead on the cluster during the upgrade process."
},
{
"code": null,
"e": 17507,
"s": 17387,
"text": "Upgrade the components of your Elastic Stack in the following order −\n\nElasticsearch\nKibana\nLogstash\nBeats\nAPM Server\n\n"
},
{
"code": null,
"e": 17577,
"s": 17507,
"text": "Upgrade the components of your Elastic Stack in the following order −"
},
{
"code": null,
"e": 17591,
"s": 17577,
"text": "Elasticsearch"
},
{
"code": null,
"e": 17598,
"s": 17591,
"text": "Kibana"
},
{
"code": null,
"e": 17607,
"s": 17598,
"text": "Logstash"
},
{
"code": null,
"e": 17613,
"s": 17607,
"text": "Beats"
},
{
"code": null,
"e": 17624,
"s": 17613,
"text": "APM Server"
},
{
"code": null,
"e": 17795,
"s": 17624,
"text": "To upgrade directly to Elasticsearch 7.1.0 from versions 6.0-6.6, you must manually reindex any 5.x indices you need to carry forward, and perform a full cluster restart."
},
{
"code": null,
"e": 17939,
"s": 17795,
"text": "The process of full cluster restart involves shutting down each node in the cluster, upgrading each node to 7x and then restarting the cluster."
},
{
"code": null,
"e": 18029,
"s": 17939,
"text": "Following are the high level steps that need to be carried out for full cluster restart −"
},
{
"code": null,
"e": 18054,
"s": 18029,
"text": "Disable shard allocation"
},
{
"code": null,
"e": 18097,
"s": 18056,
"text": "Stop indexing and perform a synced flush"
},
{
"code": null,
"e": 18118,
"s": 18099,
"text": "Shutdown all nodes"
},
{
"code": null,
"e": 18138,
"s": 18120,
"text": "Upgrade all nodes"
},
{
"code": null,
"e": 18160,
"s": 18140,
"text": "Upgrade any plugins"
},
{
"code": null,
"e": 18187,
"s": 18162,
"text": "Start each upgraded node"
},
{
"code": null,
"e": 18258,
"s": 18189,
"text": "Wait for all nodes to join the cluster and report a status of yellow"
},
{
"code": null,
"e": 18281,
"s": 18260,
"text": "Re-enable allocation"
},
{
"code": null,
"e": 18609,
"s": 18283,
"text": "Once allocation is re-enabled, the cluster starts allocating the replica shards to the data nodes. At this point, it is safe to resume indexing and searching, but your cluster will recover more quickly if you can wait until all primary and replica shards have been successfully allocated and the status of all nodes is green."
},
{
"code": null,
"e": 18955,
"s": 18609,
"text": "Application Programming Interface (API) in web is a group of function calls or other programming instructions to access the software component in that particular web application. For example, Facebook API helps a developer to create applications by accessing data or other functionalities from Facebook; it can be date of birth or status update."
},
{
"code": null,
"e": 19091,
"s": 18955,
"text": "Elasticsearch provides a REST API, which is accessed by JSON over HTTP. Elasticsearch uses some conventions which we shall discuss now."
},
{
"code": null,
"e": 19436,
"s": 19091,
"text": "Most of the operations, mainly searching and other operations, in APIs are for one or more than one indices. This helps the user to search in multiple places or all the available data by just executing a query once. Many different notations are used to perform operations in multiple indices. We will discuss a few of them here in this chapter."
},
{
"code": null,
"e": 19472,
"s": 19436,
"text": "POST /index1,index2,index3/_search\n"
},
{
"code": null,
"e": 19556,
"s": 19472,
"text": "{\n \"query\":{\n \"query_string\":{\n \"query\":\"any_string\"\n }\n }\n}\n"
},
{
"code": null,
"e": 19622,
"s": 19556,
"text": "JSON objects from index1, index2, index3 having any_string in it."
},
{
"code": null,
"e": 19642,
"s": 19622,
"text": "POST /_all/_search\n"
},
{
"code": null,
"e": 19726,
"s": 19642,
"text": "{\n \"query\":{\n \"query_string\":{\n \"query\":\"any_string\"\n }\n }\n}\n"
},
{
"code": null,
"e": 19785,
"s": 19726,
"text": "JSON objects from all indices and having any_string in it."
},
{
"code": null,
"e": 19808,
"s": 19785,
"text": "POST /school*/_search\n"
},
{
"code": null,
"e": 19886,
"s": 19808,
"text": "{\n \"query\":{\n \"query_string\":{\n \"query\":\"CBSE\"\n }\n }\n}\n"
},
{
"code": null,
"e": 19959,
"s": 19886,
"text": "JSON objects from all indices which start with school having CBSE in it."
},
{
"code": null,
"e": 20015,
"s": 19959,
"text": "Alternatively, you can use the following code as well −"
},
{
"code": null,
"e": 20052,
"s": 20015,
"text": "POST /school*,-schools_gov /_search\n"
},
{
"code": null,
"e": 20130,
"s": 20052,
"text": "{\n \"query\":{\n \"query_string\":{\n \"query\":\"CBSE\"\n }\n }\n}\n"
},
{
"code": null,
"e": 20234,
"s": 20130,
"text": "JSON objects from all indices which start with “school” but not from schools_gov and having CBSE in it."
},
{
"code": null,
"e": 20284,
"s": 20234,
"text": "There are also some URL query string parameters −"
},
{
"code": null,
"e": 20488,
"s": 20284,
"text": "ignore_unavailable − No error will occur or no operation will be stopped, if the one or more index(es) present in the URL does not exist. For example, schools index exists, but book_shops does not exist."
},
{
"code": null,
"e": 20522,
"s": 20488,
"text": "POST /school*,book_shops/_search\n"
},
{
"code": null,
"e": 20600,
"s": 20522,
"text": "{\n \"query\":{\n \"query_string\":{\n \"query\":\"CBSE\"\n }\n }\n}\n"
},
{
"code": null,
"e": 21003,
"s": 20600,
"text": "{\n \"error\":{\n \"root_cause\":[{\n \"type\":\"index_not_found_exception\", \"reason\":\"no such index\",\n \"resource.type\":\"index_or_alias\", \"resource.id\":\"book_shops\",\n \"index\":\"book_shops\"\n }],\n \"type\":\"index_not_found_exception\", \"reason\":\"no such index\",\n \"resource.type\":\"index_or_alias\", \"resource.id\":\"book_shops\",\n \"index\":\"book_shops\"\n },\"status\":404\n}\n"
},
{
"code": null,
"e": 21033,
"s": 21003,
"text": "Consider the following code −"
},
{
"code": null,
"e": 21093,
"s": 21033,
"text": "POST /school*,book_shops/_search?ignore_unavailable = true\n"
},
{
"code": null,
"e": 21171,
"s": 21093,
"text": "{\n \"query\":{\n \"query_string\":{\n \"query\":\"CBSE\"\n }\n }\n}\n"
},
{
"code": null,
"e": 21244,
"s": 21171,
"text": "JSON objects from all indices which start with school having CBSE in it."
},
{
"code": null,
"e": 21401,
"s": 21244,
"text": "true value of this parameter will prevent error, if a URL with wildcard results in no indices. For example, there is no index that starts with schools_pri −"
},
{
"code": null,
"e": 21453,
"s": 21401,
"text": "POST /schools_pri*/_search?allow_no_indices = true\n"
},
{
"code": null,
"e": 21497,
"s": 21453,
"text": "{\n \"query\":{\n \"match_all\":{}\n }\n}\n"
},
{
"code": null,
"e": 21635,
"s": 21497,
"text": "{\n \"took\":1,\"timed_out\": false, \"_shards\":{\"total\":0, \"successful\":0, \"failed\":0},\n \"hits\":{\"total\":0, \"max_score\":0.0, \"hits\":[]}\n}\n"
},
{
"code": null,
"e": 21819,
"s": 21635,
"text": "This parameter decides whether the wildcards need to be expanded to open indices or closed indices or perform both. The value of this parameter can be open and closed or none and all."
},
{
"code": null,
"e": 21854,
"s": 21819,
"text": "For example, close index schools −"
},
{
"code": null,
"e": 21876,
"s": 21854,
"text": "POST /schools/_close\n"
},
{
"code": null,
"e": 21899,
"s": 21876,
"text": "{\"acknowledged\":true}\n"
},
{
"code": null,
"e": 21929,
"s": 21899,
"text": "Consider the following code −"
},
{
"code": null,
"e": 21978,
"s": 21929,
"text": "POST /school*/_search?expand_wildcards = closed\n"
},
{
"code": null,
"e": 22022,
"s": 21978,
"text": "{\n \"query\":{\n \"match_all\":{}\n }\n}\n"
},
{
"code": null,
"e": 22246,
"s": 22022,
"text": "{\n \"error\":{\n \"root_cause\":[{\n \"type\":\"index_closed_exception\", \"reason\":\"closed\", \"index\":\"schools\"\n }],\n \"type\":\"index_closed_exception\", \"reason\":\"closed\", \"index\":\"schools\"\n }, \"status\":403\n}\n"
},
{
"code": null,
"e": 22595,
"s": 22246,
"text": "Elasticsearch offers a functionality to search indices according to date and time. We need to specify date and time in a specific format. For example, accountdetail-2015.12.30, index will store the bank account details of 30th December 2015. Mathematical operations can be performed to get details for a particular date or a range of date and time."
},
{
"code": null,
"e": 22629,
"s": 22595,
"text": "Format for date math index name −"
},
{
"code": null,
"e": 22733,
"s": 22629,
"text": "<static_name{date_math_expr{date_format|time_zone}}>\n/<accountdetail-{now-2d{YYYY.MM.dd|utc}}>/_search\n"
},
{
"code": null,
"e": 23155,
"s": 22733,
"text": "static_name is a part of expression which remains the same in every date math index like account detail. date_math_expr contains the mathematical expression that determines the date and time dynamically like now-2d. date_format contains the format in which the date is written in index like YYYY.MM.dd. If today’s date is 30th December 2015, then <accountdetail-{now-2d{YYYY.MM.dd}}> will return accountdetail-2015.12.28."
},
{
"code": null,
"e": 23285,
"s": 23155,
"text": "We will now see some of the common options available in Elasticsearch that can be used to get the response in a specified format."
},
{
"code": null,
"e": 23399,
"s": 23285,
"text": "We can get response in a well-formatted JSON object by just appending a URL query parameter, i.e., pretty = true."
},
{
"code": null,
"e": 23436,
"s": 23399,
"text": "POST /schools/_search?pretty = true\n"
},
{
"code": null,
"e": 23480,
"s": 23436,
"text": "{\n \"query\":{\n \"match_all\":{}\n }\n}\n"
},
{
"code": null,
"e": 23893,
"s": 23480,
"text": "..........................\n{\n \"_index\" : \"schools\", \"_type\" : \"school\", \"_id\" : \"1\", \"_score\" : 1.0,\n \"_source\":{\n \"name\":\"Central School\", \"description\":\"CBSE Affiliation\",\n \"street\":\"Nagan\", \"city\":\"paprola\", \"state\":\"HP\", \"zip\":\"176115\",\n \"location\": [31.8955385, 76.8380405], \"fees\":2000,\n \"tags\":[\"Senior Secondary\", \"beautiful campus\"], \"rating\":\"3.5\"\n }\n}\n......................\n"
},
{
"code": null,
"e": 24208,
"s": 23893,
"text": "This option can change the statistical responses either into human readable form (If human = true) or computer readable form (if human = false). For example, if human = true then distance_kilometer = 20KM and if human = false then distance_meter = 20000, when response needs to be used by another computer program."
},
{
"code": null,
"e": 24307,
"s": 24208,
"text": "We can filter the response to less fields by adding them in the field_path parameter. For example,"
},
{
"code": null,
"e": 24355,
"s": 24307,
"text": "POST /schools/_search?filter_path = hits.total\n"
},
{
"code": null,
"e": 24399,
"s": 24355,
"text": "{\n \"query\":{\n \"match_all\":{}\n }\n}\n"
},
{
"code": null,
"e": 24421,
"s": 24399,
"text": "{\"hits\":{\"total\":3}}\n"
},
{
"code": null,
"e": 24577,
"s": 24421,
"text": "Elasticsearch provides single document APIs and multi-document APIs, where the API call is targeting a single document and multiple documents respectively."
},
{
"code": null,
"e": 24808,
"s": 24577,
"text": "It helps to add or update the JSON document in an index when a request is made to that respective index with specific mapping. For example, the following request will add the JSON object to index schools and under school mapping −"
},
{
"code": null,
"e": 25052,
"s": 24808,
"text": "PUT schools/_doc/5\n{\n name\":\"City School\", \"description\":\"ICSE\", \"street\":\"West End\",\n \"city\":\"Meerut\",\n \"state\":\"UP\", \"zip\":\"250002\", \"location\":[28.9926174, 77.692485],\n \"fees\":3500,\n \"tags\":[\"fully computerized\"], \"rating\":\"4.5\"\n}"
},
{
"code": null,
"e": 25109,
"s": 25052,
"text": "On running the above code, we get the following result −"
},
{
"code": null,
"e": 25346,
"s": 25109,
"text": "{\n \"_index\" : \"schools\",\n \"_type\" : \"_doc\",\n \"_id\" : \"5\",\n \"_version\" : 1,\n \"result\" : \"created\",\n \"_shards\" : {\n \"total\" : 2,\n \"successful\" : 1,\n \"failed\" : 0\n },\n \"_seq_no\" : 2,\n \"_primary_term\" : 1\n}\n"
},
{
"code": null,
"e": 25693,
"s": 25346,
"text": "When a request is made to add JSON object to a particular index and if that index does not exist, then this API automatically creates that index and also the underlying mapping for that particular JSON object. This functionality can be disabled by changing the values of following parameters to false, which are present in elasticsearch.yml file."
},
{
"code": null,
"e": 25752,
"s": 25693,
"text": "action.auto_create_index:false\nindex.mapper.dynamic:false\n"
},
{
"code": null,
"e": 25910,
"s": 25752,
"text": "You can also restrict the auto creation of index, where only index name with specific patterns are allowed by changing the value of the following parameter −"
},
{
"code": null,
"e": 25949,
"s": 25910,
"text": "action.auto_create_index:+acc*,-bank*\n"
},
{
"code": null,
"e": 26010,
"s": 25949,
"text": "Note − Here + indicates allowed and – indicates not allowed."
},
{
"code": null,
"e": 26150,
"s": 26010,
"text": "Elasticsearch also provides version control facility. We can use a version query parameter to specify the version of a particular document."
},
{
"code": null,
"e": 26453,
"s": 26150,
"text": "PUT schools/_doc/5?version=7&version_type=external\n{\n \"name\":\"Central School\", \"description\":\"CBSE Affiliation\", \"street\":\"Nagan\",\n \"city\":\"paprola\", \"state\":\"HP\", \"zip\":\"176115\", \"location\":[31.8955385, 76.8380405],\n \"fees\":2200, \"tags\":[\"Senior Secondary\", \"beautiful campus\"], \"rating\":\"3.3\"\n}"
},
{
"code": null,
"e": 26510,
"s": 26453,
"text": "On running the above code, we get the following result −"
},
{
"code": null,
"e": 26747,
"s": 26510,
"text": "{\n \"_index\" : \"schools\",\n \"_type\" : \"_doc\",\n \"_id\" : \"5\",\n \"_version\" : 7,\n \"result\" : \"updated\",\n \"_shards\" : {\n \"total\" : 2,\n \"successful\" : 1,\n \"failed\" : 0\n },\n \"_seq_no\" : 3,\n \"_primary_term\" : 1\n}\n"
},
{
"code": null,
"e": 26840,
"s": 26747,
"text": "Versioning is a real-time process and it is not affected by the real time search operations."
},
{
"code": null,
"e": 26891,
"s": 26840,
"text": "There are two most important types of versioning −"
},
{
"code": null,
"e": 27004,
"s": 26891,
"text": "Internal versioning is the default version that starts with 1 and increments with each update, deletes included."
},
{
"code": null,
"e": 27317,
"s": 27004,
"text": "It is used when the versioning of the documents is stored in an external system like third party versioning systems. To enable this functionality, we need to set version_type to external. Here Elasticsearch will store version number as designated by the external system and will not increment them automatically."
},
{
"code": null,
"e": 27431,
"s": 27317,
"text": "The operation type is used to force a create operation. This helps to avoid the overwriting\nof existing document."
},
{
"code": null,
"e": 27501,
"s": 27431,
"text": "PUT chapter/_doc/1?op_type=create\n{\n \"Text\":\"this is chapter one\"\n}"
},
{
"code": null,
"e": 27558,
"s": 27501,
"text": "On running the above code, we get the following result −"
},
{
"code": null,
"e": 27795,
"s": 27558,
"text": "{\n \"_index\" : \"chapter\",\n \"_type\" : \"_doc\",\n \"_id\" : \"1\",\n \"_version\" : 1,\n \"result\" : \"created\",\n \"_shards\" : {\n \"total\" : 2,\n \"successful\" : 1,\n \"failed\" : 0\n },\n \"_seq_no\" : 0,\n \"_primary_term\" : 1\n}\n"
},
{
"code": null,
"e": 27905,
"s": 27795,
"text": "When ID is not specified in index operation, then Elasticsearch automatically generates id\nfor that document."
},
{
"code": null,
"e": 28030,
"s": 27905,
"text": "POST chapter/_doc/\n{\n \"user\" : \"tpoint\",\n \"post_date\" : \"2018-12-25T14:12:12\",\n \"message\" : \"Elasticsearch Tutorial\"\n}"
},
{
"code": null,
"e": 28087,
"s": 28030,
"text": "On running the above code, we get the following result −"
},
{
"code": null,
"e": 28343,
"s": 28087,
"text": "{\n \"_index\" : \"chapter\",\n \"_type\" : \"_doc\",\n \"_id\" : \"PVghWGoB7LiDTeV6LSGu\",\n \"_version\" : 1,\n \"result\" : \"created\",\n \"_shards\" : {\n \"total\" : 2,\n \"successful\" : 1,\n \"failed\" : 0\n },\n \"_seq_no\" : 1,\n \"_primary_term\" : 1\n}\n"
},
{
"code": null,
"e": 28436,
"s": 28343,
"text": "API helps to extract type JSON object by performing a get request for a particular document."
},
{
"code": null,
"e": 28493,
"s": 28436,
"text": "pre class=\"prettyprint notranslate\" > GET schools/_doc/5"
},
{
"code": null,
"e": 28550,
"s": 28493,
"text": "On running the above code, we get the following result −"
},
{
"code": null,
"e": 29090,
"s": 28550,
"text": "{\n \"_index\" : \"schools\",\n \"_type\" : \"_doc\",\n \"_id\" : \"5\",\n \"_version\" : 7,\n \"_seq_no\" : 3,\n \"_primary_term\" : 1,\n \"found\" : true,\n \"_source\" : {\n \"name\" : \"Central School\",\n \"description\" : \"CBSE Affiliation\",\n \"street\" : \"Nagan\",\n \"city\" : \"paprola\",\n \"state\" : \"HP\",\n \"zip\" : \"176115\",\n \"location\" : [\n 31.8955385,\n 76.8380405\n ],\n \"fees\" : 2200,\n \"tags\" : [\n \"Senior Secondary\",\n \"beautiful campus\"\n ],\n \"rating\" : \"3.3\"\n }\n}\n"
},
{
"code": null,
"e": 29174,
"s": 29090,
"text": "This operation is real time and does not get affected by the refresh rate of Index."
},
{
"code": null,
"e": 29258,
"s": 29174,
"text": "This operation is real time and does not get affected by the refresh rate of Index."
},
{
"code": null,
"e": 29353,
"s": 29258,
"text": "You can also specify the version, then Elasticsearch will fetch that version of document only."
},
{
"code": null,
"e": 29448,
"s": 29353,
"text": "You can also specify the version, then Elasticsearch will fetch that version of document only."
},
{
"code": null,
"e": 29613,
"s": 29448,
"text": "You can also specify the _all in the request, so that the Elasticsearch can search\nfor that document id in every type and it will return the first matched document."
},
{
"code": null,
"e": 29778,
"s": 29613,
"text": "You can also specify the _all in the request, so that the Elasticsearch can search\nfor that document id in every type and it will return the first matched document."
},
{
"code": null,
"e": 29865,
"s": 29778,
"text": "You can also specify the fields you want in your result from that particular document."
},
{
"code": null,
"e": 29952,
"s": 29865,
"text": "You can also specify the fields you want in your result from that particular document."
},
{
"code": null,
"e": 29999,
"s": 29952,
"text": "GET schools/_doc/5?_source_includes=name,fees "
},
{
"code": null,
"e": 30056,
"s": 29999,
"text": "On running the above code, we get the following result −"
},
{
"code": null,
"e": 30279,
"s": 30056,
"text": "{\n \"_index\" : \"schools\",\n \"_type\" : \"_doc\",\n \"_id\" : \"5\",\n \"_version\" : 7,\n \"_seq_no\" : 3,\n \"_primary_term\" : 1,\n \"found\" : true,\n \"_source\" : {\n \"fees\" : 2200,\n \"name\" : \"Central School\"\n }\n} \n"
},
{
"code": null,
"e": 30378,
"s": 30279,
"text": "You can also fetch the source part in your result by just adding _source part in your get request."
},
{
"code": null,
"e": 30406,
"s": 30378,
"text": "GET schools/_doc/5?_source "
},
{
"code": null,
"e": 30463,
"s": 30406,
"text": "On running the above code, we get the following result −"
},
{
"code": null,
"e": 31003,
"s": 30463,
"text": "{\n \"_index\" : \"schools\",\n \"_type\" : \"_doc\",\n \"_id\" : \"5\",\n \"_version\" : 7,\n \"_seq_no\" : 3,\n \"_primary_term\" : 1,\n \"found\" : true,\n \"_source\" : {\n \"name\" : \"Central School\",\n \"description\" : \"CBSE Affiliation\",\n \"street\" : \"Nagan\",\n \"city\" : \"paprola\",\n \"state\" : \"HP\",\n \"zip\" : \"176115\",\n \"location\" : [\n 31.8955385,\n 76.8380405\n ],\n \"fees\" : 2200,\n \"tags\" : [\n \"Senior Secondary\",\n \"beautiful campus\"\n ],\n \"rating\" : \"3.3\"\n }\n}\n"
},
{
"code": null,
"e": 31095,
"s": 31003,
"text": "You can also refresh the shard before doing get operation by set refresh parameter to true."
},
{
"code": null,
"e": 31203,
"s": 31095,
"text": "You can delete a particular index, mapping or a document by sending a HTTP DELETE request to Elasticsearch."
},
{
"code": null,
"e": 31227,
"s": 31203,
"text": "DELETE schools/_doc/4 "
},
{
"code": null,
"e": 31284,
"s": 31227,
"text": "On running the above code, we get the following result −"
},
{
"code": null,
"e": 31422,
"s": 31284,
"text": "{\n \"found\":true, \"_index\":\"schools\", \"_type\":\"school\", \"_id\":\"4\", \"_version\":2,\n \"_shards\":{\"total\":2, \"successful\":1, \"failed\":0}\n}\n"
},
{
"code": null,
"e": 31741,
"s": 31422,
"text": "Version of the document can be specified to delete that particular version. Routing parameter can be specified to delete the document from a particular user and the operation fails if the document does not belong to that particular user. In this operation, you can specify refresh and timeout option same like GET API."
},
{
"code": null,
"e": 31943,
"s": 31741,
"text": "Script is used for performing this operation and versioning is used to make sure that no\nupdates have happened during the get and re-index. For example, you can update the fees of school using script −"
},
{
"code": null,
"e": 32134,
"s": 31943,
"text": "POST schools/_update/4\n{\n \"script\" : {\n \"source\": \"ctx._source.name = params.sname\",\n \"lang\": \"painless\",\n \"params\" : {\n \"sname\" : \"City Wise School\"\n }\n }\n }"
},
{
"code": null,
"e": 32191,
"s": 32134,
"text": "On running the above code, we get the following result −"
},
{
"code": null,
"e": 32428,
"s": 32191,
"text": "{\n \"_index\" : \"schools\",\n \"_type\" : \"_doc\",\n \"_id\" : \"4\",\n \"_version\" : 3,\n \"result\" : \"updated\",\n \"_shards\" : {\n \"total\" : 2,\n \"successful\" : 1,\n \"failed\" : 0\n },\n \"_seq_no\" : 4,\n \"_primary_term\" : 2\n}\n"
},
{
"code": null,
"e": 32501,
"s": 32428,
"text": "You can check the update by sending get request to the updated document."
},
{
"code": null,
"e": 32748,
"s": 32501,
"text": "This API is used to search content in Elasticsearch. A user can search by sending a get request with query string as a parameter or they can post a query in the message body of post request. Mainly all the search APIS are multi-index, multi-type."
},
{
"code": null,
"e": 32969,
"s": 32748,
"text": "Elasticsearch allows us to search for the documents present in all the indices or in some\nspecific indices. For example, if we need to search all the documents with a name that contains central, we can do as shown here −"
},
{
"code": null,
"e": 33004,
"s": 32969,
"text": "GET /_all/_search?q=city:paprola \n"
},
{
"code": null,
"e": 33063,
"s": 33004,
"text": "On running the above code, we get the following response −"
},
{
"code": null,
"e": 34067,
"s": 33063,
"text": "{\n \"took\" : 33,\n \"timed_out\" : false,\n \"_shards\" : {\n \"total\" : 7,\n \"successful\" : 7,\n \"skipped\" : 0,\n \"failed\" : 0\n },\n \"hits\" : {\n \"total\" : {\n \"value\" : 1,\n \"relation\" : \"eq\"\n },\n \"max_score\" : 0.9808292,\n \"hits\" : [\n {\n \"_index\" : \"schools\",\n \"_type\" : \"school\",\n \"_id\" : \"5\",\n \"_score\" : 0.9808292,\n \"_source\" : {\n \"name\" : \"Central School\",\n \"description\" : \"CBSE Affiliation\",\n \"street\" : \"Nagan\",\n \"city\" : \"paprola\",\n \"state\" : \"HP\",\n \"zip\" : \"176115\",\n \"location\" : [\n 31.8955385,\n 76.8380405\n ],\n \"fees\" : 2200,\n \"tags\" : [\n \"Senior Secondary\",\n \"beautiful campus\"\n ],\n \"rating\" : \"3.3\"\n }\n }\n ]\n }\n}\n"
},
{
"code": null,
"e": 34155,
"s": 34067,
"text": "Many parameters can be passed in a search operation using Uniform Resource Identifier −"
},
{
"code": null,
"e": 34157,
"s": 34155,
"text": "Q"
},
{
"code": null,
"e": 34205,
"s": 34157,
"text": "This parameter is used to specify query string."
},
{
"code": null,
"e": 34213,
"s": 34205,
"text": "lenient"
},
{
"code": null,
"e": 34359,
"s": 34213,
"text": "This parameter is used to specify query string.Format based errors can be ignored by just setting this parameter to true. It\nis false by default."
},
{
"code": null,
"e": 34366,
"s": 34359,
"text": "fields"
},
{
"code": null,
"e": 34414,
"s": 34366,
"text": "This parameter is used to specify query string."
},
{
"code": null,
"e": 34419,
"s": 34414,
"text": "sort"
},
{
"code": null,
"e": 34551,
"s": 34419,
"text": "We can get sorted result by using this parameter, the possible values for this parameter is fieldName, fieldName:asc/fieldname:desc"
},
{
"code": null,
"e": 34559,
"s": 34551,
"text": "timeout"
},
{
"code": null,
"e": 34708,
"s": 34559,
"text": "We can restrict the search time by using this parameter and response only contains the hits in that specified time. By default, there is no timeout."
},
{
"code": null,
"e": 34724,
"s": 34708,
"text": "terminate_after"
},
{
"code": null,
"e": 34897,
"s": 34724,
"text": "We can restrict the response to a specified number of documents for each shard, upon reaching which the query will terminate early. By default, there is no terminate_after."
},
{
"code": null,
"e": 34902,
"s": 34897,
"text": "from"
},
{
"code": null,
"e": 34964,
"s": 34902,
"text": "The starting from index of the hits to return. Defaults to 0."
},
{
"code": null,
"e": 34969,
"s": 34964,
"text": "size"
},
{
"code": null,
"e": 35026,
"s": 34969,
"text": "It denotes the number of hits to return. Defaults to 10."
},
{
"code": null,
"e": 35181,
"s": 35026,
"text": "We can also specify query using query DSL in request body and there are many examples already given in previous chapters. One such example is given here −"
},
{
"code": null,
"e": 35278,
"s": 35181,
"text": "POST /schools/_search\n{\n \"query\":{\n \"query_string\":{\n \"query\":\"up\"\n }\n }\n}"
},
{
"code": null,
"e": 35337,
"s": 35278,
"text": "On running the above code, we get the following response −"
},
{
"code": null,
"e": 36298,
"s": 35337,
"text": "{\n \"took\" : 11,\n \"timed_out\" : false,\n \"_shards\" : {\n \"total\" : 1,\n \"successful\" : 1,\n \"skipped\" : 0,\n \"failed\" : 0\n },\n \"hits\" : {\n \"total\" : {\n \"value\" : 1,\n \"relation\" : \"eq\"\n },\n \"max_score\" : 0.47000363,\n \"hits\" : [\n {\n \"_index\" : \"schools\",\n \"_type\" : \"school\",\n \"_id\" : \"4\",\n \"_score\" : 0.47000363,\n \"_source\" : {\n \"name\" : \"City Best School\",\n \"description\" : \"ICSE\",\n \"street\" : \"West End\",\n \"city\" : \"Meerut\",\n \"state\" : \"UP\",\n \"zip\" : \"250002\",\n \"location\" : [\n 28.9926174,\n 77.692485\n ],\n \"fees\" : 3500,\n \"tags\" : [\n \"fully computerized\"\n ],\n \"rating\" : \"4.5\"\n }\n }\n ]\n }\n}\n"
},
{
"code": null,
"e": 36522,
"s": 36298,
"text": "The aggregations framework collects all the data selected by the search query and consists of many building blocks, which help in building complex summaries of the data. The basic structure of an aggregation is shown here −"
},
{
"code": null,
"e": 36666,
"s": 36522,
"text": "\"aggregations\" : {\n \"\" : {\n \"\" : {\n\n }\n \n [,\"meta\" : { [] } ]?\n [,\"aggregations\" : { []+ } ]?\n }\n [,\"\" : { ... } ]*\n}"
},
{
"code": null,
"e": 36782,
"s": 36666,
"text": "There are different types of aggregations, each with its own purpose. They are discussed in detail in this chapter."
},
{
"code": null,
"e": 36936,
"s": 36782,
"text": "These aggregations help in computing matrices from the field’s values of the aggregated documents and sometime some values can be generated from scripts."
},
{
"code": null,
"e": 37031,
"s": 36936,
"text": "Numeric matrices are either single-valued like average aggregation or multi-valued like stats."
},
{
"code": null,
"e": 37146,
"s": 37031,
"text": "This aggregation is used to get the average of any numeric field present in the aggregated\ndocuments. For example,"
},
{
"code": null,
"e": 37231,
"s": 37146,
"text": "POST /schools/_search\n{\n \"aggs\":{\n \"avg_fees\":{\"avg\":{\"field\":\"fees\"}}\n }\n}"
},
{
"code": null,
"e": 37288,
"s": 37231,
"text": "On running the above code, we get the following result −"
},
{
"code": null,
"e": 38917,
"s": 37288,
"text": "{\n \"took\" : 41,\n \"timed_out\" : false,\n \"_shards\" : {\n \"total\" : 1,\n \"successful\" : 1,\n \"skipped\" : 0,\n \"failed\" : 0\n },\n \"hits\" : {\n \"total\" : {\n \"value\" : 2,\n \"relation\" : \"eq\"\n },\n \"max_score\" : 1.0,\n \"hits\" : [\n {\n \"_index\" : \"schools\",\n \"_type\" : \"school\",\n \"_id\" : \"5\",\n \"_score\" : 1.0,\n \"_source\" : {\n \"name\" : \"Central School\",\n \"description\" : \"CBSE Affiliation\",\n \"street\" : \"Nagan\",\n \"city\" : \"paprola\",\n \"state\" : \"HP\",\n \"zip\" : \"176115\",\n \"location\" : [\n 31.8955385,\n 76.8380405\n ],\n \"fees\" : 2200,\n \"tags\" : [\n \"Senior Secondary\",\n \"beautiful campus\"\n ],\n \"rating\" : \"3.3\"\n }\n },\n {\n \"_index\" : \"schools\",\n \"_type\" : \"school\",\n \"_id\" : \"4\",\n \"_score\" : 1.0,\n \"_source\" : {\n \"name\" : \"City Best School\",\n \"description\" : \"ICSE\",\n \"street\" : \"West End\",\n \"city\" : \"Meerut\",\n \"state\" : \"UP\",\n \"zip\" : \"250002\",\n \"location\" : [\n 28.9926174,\n 77.692485\n ],\n \"fees\" : 3500,\n \"tags\" : [\n \"fully computerized\"\n ],\n \"rating\" : \"4.5\"\n }\n }\n ]\n },\n \"aggregations\" : {\n \"avg_fees\" : {\n \"value\" : 2850.0\n }\n }\n}\n"
},
{
"code": null,
"e": 38992,
"s": 38917,
"text": "This aggregation gives the count of distinct values of a particular field."
},
{
"code": null,
"e": 39103,
"s": 38992,
"text": "POST /schools/_search?size=0\n{\n \"aggs\":{\n \"distinct_name_count\":{\"cardinality\":{\"field\":\"fees\"}}\n }\n}"
},
{
"code": null,
"e": 39160,
"s": 39103,
"text": "On running the above code, we get the following result −"
},
{
"code": null,
"e": 39539,
"s": 39160,
"text": "{\n \"took\" : 2,\n \"timed_out\" : false,\n \"_shards\" : {\n \"total\" : 1,\n \"successful\" : 1,\n \"skipped\" : 0,\n \"failed\" : 0\n },\n \"hits\" : {\n \"total\" : {\n \"value\" : 2,\n \"relation\" : \"eq\"\n },\n \"max_score\" : null,\n \"hits\" : [ ]\n },\n \"aggregations\" : {\n \"distinct_name_count\" : {\n \"value\" : 2\n }\n }\n}\n"
},
{
"code": null,
"e": 39623,
"s": 39539,
"text": "Note − The value of cardinality is 2 because there are two distinct values in fees."
},
{
"code": null,
"e": 39727,
"s": 39623,
"text": "This aggregation generates all the statistics about a specific numerical field in aggregated documents."
},
{
"code": null,
"e": 39844,
"s": 39727,
"text": "POST /schools/_search?size=0\n{\n \"aggs\" : {\n \"fees_stats\" : { \"extended_stats\" : { \"field\" : \"fees\" } }\n }\n}"
},
{
"code": null,
"e": 39901,
"s": 39844,
"text": "On running the above code, we get the following result −"
},
{
"code": null,
"e": 40581,
"s": 39901,
"text": "{\n \"took\" : 8,\n \"timed_out\" : false,\n \"_shards\" : {\n \"total\" : 1,\n \"successful\" : 1,\n \"skipped\" : 0,\n \"failed\" : 0\n },\n \"hits\" : {\n \"total\" : {\n \"value\" : 2,\n \"relation\" : \"eq\"\n },\n \"max_score\" : null,\n \"hits\" : [ ]\n },\n \"aggregations\" : {\n \"fees_stats\" : {\n \"count\" : 2,\n \"min\" : 2200.0,\n \"max\" : 3500.0,\n \"avg\" : 2850.0,\n \"sum\" : 5700.0,\n \"sum_of_squares\" : 1.709E7,\n \"variance\" : 422500.0,\n \"std_deviation\" : 650.0,\n \"std_deviation_bounds\" : {\n \"upper\" : 4150.0,\n \"lower\" : 1550.0\n }\n }\n }\n}\n"
},
{
"code": null,
"e": 40671,
"s": 40581,
"text": "This aggregation finds the max value of a specific numeric field in aggregated documents."
},
{
"code": null,
"e": 40772,
"s": 40671,
"text": "POST /schools/_search?size=0\n{\n \"aggs\" : {\n \"max_fees\" : { \"max\" : { \"field\" : \"fees\" } }\n }\n}"
},
{
"code": null,
"e": 40829,
"s": 40772,
"text": "On running the above code, we get the following result −"
},
{
"code": null,
"e": 41202,
"s": 40829,
"text": "{\n \"took\" : 16,\n \"timed_out\" : false,\n \"_shards\" : {\n \"total\" : 1,\n \"successful\" : 1,\n \"skipped\" : 0,\n \"failed\" : 0\n },\n \"hits\" : {\n \"total\" : {\n \"value\" : 2,\n \"relation\" : \"eq\"\n },\n \"max_score\" : null,\n \"hits\" : [ ]\n },\n \"aggregations\" : {\n \"max_fees\" : {\n \"value\" : 3500.0\n }\n }\n}\n"
},
{
"code": null,
"e": 41292,
"s": 41202,
"text": "This aggregation finds the min value of a specific numeric field in aggregated documents."
},
{
"code": null,
"e": 41396,
"s": 41292,
"text": "POST /schools/_search?size=0\n{\n \"aggs\" : {\n \"min_fees\" : { \"min\" : { \"field\" : \"fees\" } }\n }\n}"
},
{
"code": null,
"e": 41453,
"s": 41396,
"text": "On running the above code, we get the following result −"
},
{
"code": null,
"e": 41825,
"s": 41453,
"text": "{\n \"took\" : 2,\n \"timed_out\" : false,\n \"_shards\" : {\n \"total\" : 1,\n \"successful\" : 1,\n \"skipped\" : 0,\n \"failed\" : 0\n },\n \"hits\" : {\n \"total\" : {\n \"value\" : 2,\n \"relation\" : \"eq\"\n },\n \"max_score\" : null,\n \"hits\" : [ ]\n },\n \"aggregations\" : {\n \"min_fees\" : {\n \"value\" : 2200.0\n }\n }\n}\n"
},
{
"code": null,
"e": 41914,
"s": 41825,
"text": "This aggregation calculates the sum of a specific numeric field in aggregated documents."
},
{
"code": null,
"e": 42020,
"s": 41914,
"text": "POST /schools/_search?size=0\n{\n \"aggs\" : {\n \"total_fees\" : { \"sum\" : { \"field\" : \"fees\" } }\n }\n}"
},
{
"code": null,
"e": 42077,
"s": 42020,
"text": "On running the above code, we get the following result −"
},
{
"code": null,
"e": 42452,
"s": 42077,
"text": "{\n \"took\" : 8,\n \"timed_out\" : false,\n \"_shards\" : {\n \"total\" : 1,\n \"successful\" : 1,\n \"skipped\" : 0,\n \"failed\" : 0\n },\n \"hits\" : {\n \"total\" : {\n \"value\" : 2,\n \"relation\" : \"eq\"\n },\n \"max_score\" : null,\n \"hits\" : [ ]\n },\n \"aggregations\" : {\n \"total_fees\" : {\n \"value\" : 5700.0\n }\n }\n}\n"
},
{
"code": null,
"e": 42616,
"s": 42452,
"text": "There are some other metrics aggregations which are used in special cases like geo bounds aggregation and geo centroid aggregation for the purpose of geo location."
},
{
"code": null,
"e": 42731,
"s": 42616,
"text": "A multi-value metrics aggregation that computes stats over numeric values extracted from the aggregated documents."
},
{
"code": null,
"e": 42841,
"s": 42731,
"text": "POST /schools/_search?size=0\n{\n \"aggs\" : {\n \"grades_stats\" : { \"stats\" : { \"field\" : \"fees\" } }\n }\n}"
},
{
"code": null,
"e": 42898,
"s": 42841,
"text": "On running the above code, we get the following result −"
},
{
"code": null,
"e": 43370,
"s": 42898,
"text": "{\n \"took\" : 2,\n \"timed_out\" : false,\n \"_shards\" : {\n \"total\" : 1,\n \"successful\" : 1,\n \"skipped\" : 0,\n \"failed\" : 0\n },\n \"hits\" : {\n \"total\" : {\n \"value\" : 2,\n \"relation\" : \"eq\"\n },\n \"max_score\" : null,\n \"hits\" : [ ]\n },\n \"aggregations\" : {\n \"grades_stats\" : {\n \"count\" : 2,\n \"min\" : 2200.0,\n \"max\" : 3500.0,\n \"avg\" : 2850.0,\n \"sum\" : 5700.0\n }\n }\n}\n"
},
{
"code": null,
"e": 43485,
"s": 43370,
"text": "You can add some data about the aggregation at the time of request by using meta tag and can get that in response."
},
{
"code": null,
"e": 43670,
"s": 43485,
"text": "POST /schools/_search?size=0\n{\n \"aggs\" : {\n \"avg_fees\" : { \"avg\" : { \"field\" : \"fees\" } ,\n \"meta\" :{\n \"dsc\" :\"Lowest Fees This Year\"\n }\n }\n }\n}"
},
{
"code": null,
"e": 43727,
"s": 43670,
"text": "On running the above code, we get the following result −"
},
{
"code": null,
"e": 44176,
"s": 43727,
"text": "{\n \"took\" : 0,\n \"timed_out\" : false,\n \"_shards\" : {\n \"total\" : 1,\n \"successful\" : 1,\n \"skipped\" : 0,\n \"failed\" : 0\n },\n \"hits\" : {\n \"total\" : {\n \"value\" : 2,\n \"relation\" : \"eq\"\n },\n \"max_score\" : null,\n \"hits\" : [ ]\n },\n \"aggregations\" : {\n \"avg_fees\" : {\n \"meta\" : {\n \"dsc\" : \"Lowest Fees This Year\"\n },\n \"value\" : 2850.0\n }\n }\n}\n"
},
{
"code": null,
"e": 44296,
"s": 44176,
"text": "These APIs are responsible for managing all the aspects of the index like settings, aliases, mappings, index templates."
},
{
"code": null,
"e": 44587,
"s": 44296,
"text": "This API helps you to create an index. An index can be created automatically when a user is passing JSON objects to any index or it can be created before that. To create an index, you just need to send a PUT request with settings, mappings and aliases or just a simple request without body."
},
{
"code": null,
"e": 44601,
"s": 44587,
"text": "PUT colleges\n"
},
{
"code": null,
"e": 44663,
"s": 44601,
"text": "On running the above code, we get the output as shown below −"
},
{
"code": null,
"e": 44751,
"s": 44663,
"text": "{\n \"acknowledged\" : true,\n \"shards_acknowledged\" : true,\n \"index\" : \"colleges\"\n}\n"
},
{
"code": null,
"e": 44804,
"s": 44751,
"text": "We can also add some settings to the above command −"
},
{
"code": null,
"e": 44937,
"s": 44804,
"text": "PUT colleges\n{\n \"settings\" : {\n \"index\" : {\n \"number_of_shards\" : 3,\n \"number_of_replicas\" : 2\n }\n }\n}\n"
},
{
"code": null,
"e": 44999,
"s": 44937,
"text": "On running the above code, we get the output as shown below −"
},
{
"code": null,
"e": 45087,
"s": 44999,
"text": "{\n \"acknowledged\" : true,\n \"shards_acknowledged\" : true,\n \"index\" : \"colleges\"\n}\n"
},
{
"code": null,
"e": 45206,
"s": 45087,
"text": "This API helps you to delete any index. You just need to pass a delete request with the name of that particular Index."
},
{
"code": null,
"e": 45224,
"s": 45206,
"text": "DELETE /colleges\n"
},
{
"code": null,
"e": 45276,
"s": 45224,
"text": "You can delete all indices by just using _all or *."
},
{
"code": null,
"e": 45402,
"s": 45276,
"text": "This API can be called by just sending get request to one or more than one indices. This returns the information about index."
},
{
"code": null,
"e": 45416,
"s": 45402,
"text": "GET colleges\n"
},
{
"code": null,
"e": 45478,
"s": 45416,
"text": "On running the above code, we get the output as shown below −"
},
{
"code": null,
"e": 46164,
"s": 45478,
"text": "{\n \"colleges\" : {\n \"aliases\" : {\n \"alias_1\" : { },\n \"alias_2\" : {\n \"filter\" : {\n \"term\" : {\n \"user\" : \"pkay\"\n }\n },\n \"index_routing\" : \"pkay\",\n \"search_routing\" : \"pkay\"\n }\n },\n \"mappings\" : { },\n \"settings\" : {\n \"index\" : {\n \"creation_date\" : \"1556245406616\",\n \"number_of_shards\" : \"1\",\n \"number_of_replicas\" : \"1\",\n \"uuid\" : \"3ExJbdl2R1qDLssIkwDAug\",\n \"version\" : {\n \"created\" : \"7000099\"\n },\n \"provided_name\" : \"colleges\"\n }\n }\n }\n}\n"
},
{
"code": null,
"e": 46231,
"s": 46164,
"text": "You can get the information of all the indices by using _all or *."
},
{
"code": null,
"e": 46389,
"s": 46231,
"text": "Existence of an index can be determined by just sending a get request to that index. If the HTTP response is 200, it exists; if it is 404, it does not exist."
},
{
"code": null,
"e": 46404,
"s": 46389,
"text": "HEAD colleges\n"
},
{
"code": null,
"e": 46466,
"s": 46404,
"text": "On running the above code, we get the output as shown below −"
},
{
"code": null,
"e": 46474,
"s": 46466,
"text": "200-OK\n"
},
{
"code": null,
"e": 46560,
"s": 46474,
"text": "You can get the index settings by just appending _settings keyword at the end of URL."
},
{
"code": null,
"e": 46585,
"s": 46560,
"text": "GET /colleges/_settings\n"
},
{
"code": null,
"e": 46647,
"s": 46585,
"text": "On running the above code, we get the output as shown below −"
},
{
"code": null,
"e": 47027,
"s": 46647,
"text": "{\n \"colleges\" : {\n \"settings\" : {\n \"index\" : {\n \"creation_date\" : \"1556245406616\",\n \"number_of_shards\" : \"1\",\n \"number_of_replicas\" : \"1\",\n \"uuid\" : \"3ExJbdl2R1qDLssIkwDAug\",\n \"version\" : {\n \"created\" : \"7000099\"\n },\n \"provided_name\" : \"colleges\"\n }\n }\n }\n}\n"
},
{
"code": null,
"e": 47180,
"s": 47027,
"text": "This API helps you to extract statistics about a particular index. You just need to send a get request with the index URL and _stats keyword at the end."
},
{
"code": null,
"e": 47193,
"s": 47180,
"text": "GET /_stats\n"
},
{
"code": null,
"e": 47255,
"s": 47193,
"text": "On running the above code, we get the output as shown below −"
},
{
"code": null,
"e": 47629,
"s": 47255,
"text": "......................................................\n},\n \"request_cache\" : {\n \"memory_size_in_bytes\" : 849,\n \"evictions\" : 0,\n \"hit_count\" : 1171,\n \"miss_count\" : 4\n },\n \"recovery\" : {\n \"current_as_source\" : 0,\n \"current_as_target\" : 0,\n \"throttle_time_in_millis\" : 0\n }\n} ......................................................\n"
},
{
"code": null,
"e": 47914,
"s": 47629,
"text": "The flush process of an index makes sure that any data that is currently only persisted in the transaction log is also permanently persisted in Lucene. This reduces recovery times as that data does not need to be reindexed from the transaction logs after the Lucene indexed is opened."
},
{
"code": null,
"e": 47936,
"s": 47914,
"text": "POST colleges/_flush\n"
},
{
"code": null,
"e": 47998,
"s": 47936,
"text": "On running the above code, we get the output as shown below −"
},
{
"code": null,
"e": 48088,
"s": 47998,
"text": "{\n \"_shards\" : {\n \"total\" : 2,\n \"successful\" : 1,\n \"failed\" : 0\n } \n}\n"
},
{
"code": null,
"e": 48481,
"s": 48088,
"text": "Usually the results from various Elasticsearch APIs are displayed in JSON format. But JSON is not easy to read always. So cat APIs feature is available in Elasticsearch helps in taking\ncare of giving an easier to read and comprehend printing format of the results. There are various parameters used in cat API which server different purpose, for example - the term V makes the output verbose."
},
{
"code": null,
"e": 48541,
"s": 48481,
"text": "Let us learn about cat APIs more in detail in this chapter."
},
{
"code": null,
"e": 48700,
"s": 48541,
"text": "The verbose output gives a nice display of results of a cat command. In the example given\nbelow, we get the details of various indices present in the cluster."
},
{
"code": null,
"e": 48721,
"s": 48700,
"text": "GET /_cat/indices?v\n"
},
{
"code": null,
"e": 48785,
"s": 48721,
"text": "On running the above code, we get the response as shown below −"
},
{
"code": null,
"e": 49139,
"s": 48785,
"text": "health status index uuid pri rep docs.count docs.deleted store.size pri.store.size\nyellow open schools RkMyEn2SQ4yUgzT6EQYuAA 1 1 2 1 21.6kb 21.6kb\nyellow open index_4_analysis zVmZdM1sTV61YJYrNXf1gg 1 1 0 0 283b 283b\nyellow open sensor-2018-01-01 KIrrHwABRB-ilGqTu3OaVQ 1 1 1 0 4.2kb 4.2kb\nyellow open colleges 3ExJbdl2R1qDLssIkwDAug 1 1 0 0 283b 283b\n"
},
{
"code": null,
"e": 49240,
"s": 49139,
"text": "The h parameter, also called header, is used to display only those columns mentioned in\nthe command."
},
{
"code": null,
"e": 49267,
"s": 49240,
"text": "GET /_cat/nodes?h=ip,port\n"
},
{
"code": null,
"e": 49331,
"s": 49267,
"text": "On running the above code, we get the response as shown below −"
},
{
"code": null,
"e": 49347,
"s": 49331,
"text": "127.0.0.1 9300\n"
},
{
"code": null,
"e": 49527,
"s": 49347,
"text": "The sort command accepts query string which can sort the table by specified column in the query. The default sort is ascending but this can be changed by adding :desc to a column."
},
{
"code": null,
"e": 49632,
"s": 49527,
"text": "The below example, gives a result of templates arranged in descending order of the filed\nindex patterns."
},
{
"code": null,
"e": 49682,
"s": 49632,
"text": "GET _cat/templates?v&s=order:desc,index_patterns\n"
},
{
"code": null,
"e": 49746,
"s": 49682,
"text": "On running the above code, we get the response as shown below −"
},
{
"code": null,
"e": 49969,
"s": 49746,
"text": "name index_patterns order version\n.triggered_watches [.triggered_watches*] 2147483647\n.watch-history-9 [.watcher-history-9*] 2147483647\n.watches [.watches*] 2147483647\n.kibana_task_manager [.kibana_task_manager] 0 7000099\n"
},
{
"code": null,
"e": 50060,
"s": 49969,
"text": "The count parameter provides the count of total number of documents in the entire cluster."
},
{
"code": null,
"e": 50079,
"s": 50060,
"text": "GET /_cat/count?v\n"
},
{
"code": null,
"e": 50143,
"s": 50079,
"text": "On running the above code, we get the response as shown below −"
},
{
"code": null,
"e": 50192,
"s": 50143,
"text": "epoch timestamp count\n1557633536 03:58:56 17809\n"
},
{
"code": null,
"e": 50368,
"s": 50192,
"text": "The cluster API is used for getting information about cluster and its nodes and to make changes in them. To call this API, we need to specify the node name, address or _local."
},
{
"code": null,
"e": 50388,
"s": 50368,
"text": "GET /_nodes/_local\n"
},
{
"code": null,
"e": 50452,
"s": 50388,
"text": "On running the above code, we get the response as shown below −"
},
{
"code": null,
"e": 51084,
"s": 50452,
"text": "......................................................\ncluster_name\" : \"elasticsearch\",\n \"nodes\" : {\n \"FKH-5blYTJmff2rJ_lQOCg\" : {\n \"name\" : \"ubuntu\",\n \"transport_address\" : \"127.0.0.1:9300\",\n \"host\" : \"127.0.0.1\",\n \"ip\" : \"127.0.0.1\",\n \"version\" : \"7.0.0\",\n \"build_flavor\" : \"default\",\n \"build_type\" : \"tar\",\n \"build_hash\" : \"b7e28a7\",\n \"total_indexing_buffer\" : 106502553,\n \"roles\" : [\n \"master\",\n \"data\",\n \"ingest\"\n ],\n \"attributes\" : {\n......................................................\n"
},
{
"code": null,
"e": 51183,
"s": 51084,
"text": "This API is used to get the status on the health of the cluster by appending the ‘health’\nkeyword."
},
{
"code": null,
"e": 51205,
"s": 51183,
"text": "GET /_cluster/health\n"
},
{
"code": null,
"e": 51269,
"s": 51205,
"text": "On running the above code, we get the response as shown below −"
},
{
"code": null,
"e": 51764,
"s": 51269,
"text": "{\n \"cluster_name\" : \"elasticsearch\",\n \"status\" : \"yellow\",\n \"timed_out\" : false,\n \"number_of_nodes\" : 1,\n \"number_of_data_nodes\" : 1,\n \"active_primary_shards\" : 7,\n \"active_shards\" : 7,\n \"relocating_shards\" : 0,\n \"initializing_shards\" : 0,\n \"unassigned_shards\" : 4,\n \"delayed_unassigned_shards\" : 0,\n \"number_of_pending_tasks\" : 0,\n \"number_of_in_flight_fetch\" : 0,\n \"task_max_waiting_in_queue_millis\" : 0,\n \"active_shards_percent_as_number\" : 63.63636363636363\n}\n"
},
{
"code": null,
"e": 51962,
"s": 51764,
"text": "This API is used to get state information about a cluster by appending the ‘state’ keyword\nURL. The state information contains version, master node, other nodes, routing table, metadata and blocks."
},
{
"code": null,
"e": 51983,
"s": 51962,
"text": "GET /_cluster/state\n"
},
{
"code": null,
"e": 52047,
"s": 51983,
"text": "On running the above code, we get the response as shown below −"
},
{
"code": null,
"e": 52516,
"s": 52047,
"text": "......................................................\n{\n \"cluster_name\" : \"elasticsearch\",\n \"cluster_uuid\" : \"IzKu0OoVTQ6LxqONJnN2eQ\",\n \"version\" : 89,\n \"state_uuid\" : \"y3BlwvspR1eUQBTo0aBjig\",\n \"master_node\" : \"FKH-5blYTJmff2rJ_lQOCg\",\n \"blocks\" : { },\n \"nodes\" : {\n \"FKH-5blYTJmff2rJ_lQOCg\" : {\n \"name\" : \"ubuntu\",\n \"ephemeral_id\" : \"426kTGpITGixhEzaM-5Qyg\",\n \"transport\n }\n......................................................\n"
},
{
"code": null,
"e": 52700,
"s": 52516,
"text": "This API helps to retrieve statistics about cluster by using the ‘stats’ keyword. This API\nreturns shard number, store size, memory usage, number of nodes, roles, OS, and file system."
},
{
"code": null,
"e": 52721,
"s": 52700,
"text": "GET /_cluster/stats\n"
},
{
"code": null,
"e": 52785,
"s": 52721,
"text": "On running the above code, we get the response as shown below −"
},
{
"code": null,
"e": 53427,
"s": 52785,
"text": ".................................................\n\"cluster_name\" : \"elasticsearch\",\n\"cluster_uuid\" : \"IzKu0OoVTQ6LxqONJnN2eQ\",\n\"timestamp\" : 1556435464704,\n\"status\" : \"yellow\",\n\"indices\" : {\n \"count\" : 7,\n \"shards\" : {\n \"total\" : 7,\n \"primaries\" : 7,\n \"replication\" : 0.0,\n \"index\" : {\n \"shards\" : {\n \"min\" : 1,\n \"max\" : 1,\n \"avg\" : 1.0\n },\n \"primaries\" : {\n \"min\" : 1,\n \"max\" : 1,\n \"avg\" : 1.0\n },\n \"replication\" : {\n \"min\" : 0.0,\n \"max\" : 0.0,\n \"avg\" : 0.0\n }\n.................................................\n"
},
{
"code": null,
"e": 53642,
"s": 53427,
"text": "This API allows you to update the settings of a cluster by using the ‘settings’ keyword.\nThere are two types of settings − persistent (applied across restarts) and transient (do not survive a full cluster restart)."
},
{
"code": null,
"e": 53763,
"s": 53642,
"text": "This API is used to retrieve the statistics of one more nodes of the cluster. Node stats are\nalmost the same as cluster."
},
{
"code": null,
"e": 53782,
"s": 53763,
"text": "GET /_nodes/stats\n"
},
{
"code": null,
"e": 53846,
"s": 53782,
"text": "On running the above code, we get the response as shown below −"
},
{
"code": null,
"e": 54528,
"s": 53846,
"text": "{\n \"_nodes\" : {\n \"total\" : 1,\n \"successful\" : 1,\n \"failed\" : 0\n },\n \"cluster_name\" : \"elasticsearch\",\n \"nodes\" : {\n \"FKH-5blYTJmff2rJ_lQOCg\" : {\n \"timestamp\" : 1556437348653,\n \"name\" : \"ubuntu\",\n \"transport_address\" : \"127.0.0.1:9300\",\n \"host\" : \"127.0.0.1\",\n \"ip\" : \"127.0.0.1:9300\",\n \"roles\" : [\n \"master\",\n \"data\",\n \"ingest\"\n ],\n \"attributes\" : {\n \"ml.machine_memory\" : \"4112797696\",\n \"xpack.installed\" : \"true\",\n \"ml.max_open_jobs\" : \"20\"\n },\n...................................................................\n"
},
{
"code": null,
"e": 54626,
"s": 54528,
"text": "This API helps you to retrieve information about the current hot threads on each node in cluster."
},
{
"code": null,
"e": 54651,
"s": 54626,
"text": "GET /_nodes/hot_threads\n"
},
{
"code": null,
"e": 54715,
"s": 54651,
"text": "On running the above code, we get the response as shown below −"
},
{
"code": null,
"e": 54975,
"s": 54715,
"text": ":::{ubuntu}{FKH-5blYTJmff2rJ_lQOCg}{426kTGpITGixhEzaM5Qyg}{127.0.0.1}{127.0.0.1:9300}{ml.machine_memory=4112797696,\nxpack.installed=true, ml.max_open_jobs=20}\n Hot threads at 2019-04-28T07:43:58.265Z, interval=500ms, busiestThreads=3,\nignoreIdleThreads=true:\n"
},
{
"code": null,
"e": 55084,
"s": 54975,
"text": "In Elasticsearch, searching is carried out by using query based on JSON. A query is made up of two clauses −"
},
{
"code": null,
"e": 55196,
"s": 55084,
"text": "Leaf Query Clauses − These clauses are match, term or range, which look for a specific value in specific field."
},
{
"code": null,
"e": 55308,
"s": 55196,
"text": "Leaf Query Clauses − These clauses are match, term or range, which look for a specific value in specific field."
},
{
"code": null,
"e": 55450,
"s": 55308,
"text": "Compound Query Clauses − These queries are a combination of leaf query clauses and other compound queries to extract the desired information."
},
{
"code": null,
"e": 55592,
"s": 55450,
"text": "Compound Query Clauses − These queries are a combination of leaf query clauses and other compound queries to extract the desired information."
},
{
"code": null,
"e": 55808,
"s": 55592,
"text": "Elasticsearch supports a large number of queries. A query starts with a query key word and then has conditions and filters inside in the form of JSON object. The different types of queries have been described below."
},
{
"code": null,
"e": 55909,
"s": 55808,
"text": "This is the most basic query; it returns all the content and with the score of 1.0 for every object."
},
{
"code": null,
"e": 55974,
"s": 55909,
"text": "POST /schools/_search\n{\n \"query\":{\n \"match_all\":{}\n }\n}"
},
{
"code": null,
"e": 56031,
"s": 55974,
"text": "On running the above code, we get the following result −"
},
{
"code": null,
"e": 57674,
"s": 56031,
"text": "{\n \"took\" : 7,\n \"timed_out\" : false,\n \"_shards\" : {\n \"total\" : 1,\n \"successful\" : 1,\n \"skipped\" : 0,\n \"failed\" : 0\n },\n \"hits\" : {\n \"total\" : {\n \"value\" : 2,\n \"relation\" : \"eq\"\n },\n \"max_score\" : 1.0,\n \"hits\" : [\n {\n \"_index\" : \"schools\",\n \"_type\" : \"school\",\n \"_id\" : \"5\",\n \"_score\" : 1.0,\n \"_source\" : {\n \"name\" : \"Central School\",\n \"description\" : \"CBSE Affiliation\",\n \"street\" : \"Nagan\",\n \"city\" : \"paprola\",\n \"state\" : \"HP\",\n \"zip\" : \"176115\",\n \"location\" : [\n 31.8955385,\n 76.8380405\n ],\n \"fees\" : 2200,\n \"tags\" : [\n \"Senior Secondary\",\n \"beautiful campus\"\n ],\n \"rating\" : \"3.3\"\n }\n },\n {\n \"_index\" : \"schools\",\n \"_type\" : \"school\",\n \"_id\" : \"4\",\n \"_score\" : 1.0,\n \"_source\" : {\n \"name\" : \"City Best School\",\n \"description\" : \"ICSE\",\n \"street\" : \"West End\",\n \"city\" : \"Meerut\",\n \"state\" : \"UP\",\n \"zip\" : \"250002\",\n \"location\" : [\n 28.9926174,\n 77.692485\n ],\n \"fees\" : 3500,\n \"tags\" : [\n \"fully computerized\"\n ],\n \"rating\" : \"4.5\"\n }\n }\n ]\n }\n}\n"
},
{
"code": null,
"e": 57930,
"s": 57674,
"text": "These queries are used to search a full body of text like a chapter or a news article. This query works according to the analyser associated with that particular index or document. In this section, we will discuss the different types of full text queries."
},
{
"code": null,
"e": 58005,
"s": 57930,
"text": "This query matches a text or phrase with the values of one or more fields."
},
{
"code": null,
"e": 58100,
"s": 58005,
"text": "POST /schools*/_search\n{\n \"query\":{\n \"match\" : {\n \"rating\":\"4.5\"\n }\n }\n}"
},
{
"code": null,
"e": 58164,
"s": 58100,
"text": "On running the above code, we get the response as shown below −"
},
{
"code": null,
"e": 59125,
"s": 58164,
"text": "{\n \"took\" : 44,\n \"timed_out\" : false,\n \"_shards\" : {\n \"total\" : 1,\n \"successful\" : 1,\n \"skipped\" : 0,\n \"failed\" : 0\n },\n \"hits\" : {\n \"total\" : {\n \"value\" : 1,\n \"relation\" : \"eq\"\n },\n \"max_score\" : 0.47000363,\n \"hits\" : [\n {\n \"_index\" : \"schools\",\n \"_type\" : \"school\",\n \"_id\" : \"4\",\n \"_score\" : 0.47000363,\n \"_source\" : {\n \"name\" : \"City Best School\",\n \"description\" : \"ICSE\",\n \"street\" : \"West End\",\n \"city\" : \"Meerut\",\n \"state\" : \"UP\",\n \"zip\" : \"250002\",\n \"location\" : [\n 28.9926174,\n 77.692485\n ],\n \"fees\" : 3500,\n \"tags\" : [\n \"fully computerized\"\n ],\n \"rating\" : \"4.5\"\n }\n }\n ]\n }\n}\n"
},
{
"code": null,
"e": 59187,
"s": 59125,
"text": "This query matches a text or phrase with more than one field."
},
{
"code": null,
"e": 59332,
"s": 59187,
"text": "POST /schools*/_search\n{\n \"query\":{\n \"multi_match\" : {\n \"query\": \"paprola\",\n \"fields\": [ \"city\", \"state\" ]\n }\n }\n}"
},
{
"code": null,
"e": 59396,
"s": 59332,
"text": "On running the above code, we get the response as shown below −"
},
{
"code": null,
"e": 60400,
"s": 59396,
"text": "{\n \"took\" : 12,\n \"timed_out\" : false,\n \"_shards\" : {\n \"total\" : 1,\n \"successful\" : 1,\n \"skipped\" : 0,\n \"failed\" : 0\n },\n \"hits\" : {\n \"total\" : {\n \"value\" : 1,\n \"relation\" : \"eq\"\n },\n \"max_score\" : 0.9808292,\n \"hits\" : [\n {\n \"_index\" : \"schools\",\n \"_type\" : \"school\",\n \"_id\" : \"5\",\n \"_score\" : 0.9808292,\n \"_source\" : {\n \"name\" : \"Central School\",\n \"description\" : \"CBSE Affiliation\",\n \"street\" : \"Nagan\",\n \"city\" : \"paprola\",\n \"state\" : \"HP\",\n \"zip\" : \"176115\",\n \"location\" : [\n 31.8955385,\n 76.8380405\n ],\n \"fees\" : 2200,\n \"tags\" : [\n \"Senior Secondary\",\n \"beautiful campus\"\n ],\n \"rating\" : \"3.3\"\n }\n }\n ]\n }\n}\n"
},
{
"code": null,
"e": 60455,
"s": 60400,
"text": "This query uses query parser and query_string keyword."
},
{
"code": null,
"e": 60562,
"s": 60455,
"text": "POST /schools*/_search\n{\n \"query\":{\n \"query_string\":{\n \"query\":\"beautiful\"\n }\n }\n} "
},
{
"code": null,
"e": 60626,
"s": 60562,
"text": "On running the above code, we get the response as shown below −"
},
{
"code": null,
"e": 60897,
"s": 60626,
"text": "{\n \"took\" : 60,\n \"timed_out\" : false,\n \"_shards\" : {\n \"total\" : 1,\n \"successful\" : 1,\n \"skipped\" : 0,\n \"failed\" : 0\n },\n \"hits\" : {\n \"total\" : {\n \"value\" : 1,\n \"relation\" : \"eq\"\n },\n........................................\n"
},
{
"code": null,
"e": 60975,
"s": 60897,
"text": "These queries mainly deal with structured data like numbers, dates and enums."
},
{
"code": null,
"e": 61050,
"s": 60975,
"text": "POST /schools*/_search\n{\n \"query\":{\n \"term\":{\"zip\":\"176115\"}\n }\n}"
},
{
"code": null,
"e": 61114,
"s": 61050,
"text": "On running the above code, we get the response as shown below −"
},
{
"code": null,
"e": 61630,
"s": 61114,
"text": "...................................\nhits\" : [\n {\n \"_index\" : \"schools\",\n \"_type\" : \"school\",\n \"_id\" : \"5\",\n \"_score\" : 0.9808292,\n \"_source\" : {\n \"name\" : \"Central School\",\n \"description\" : \"CBSE Affiliation\",\n \"street\" : \"Nagan\",\n \"city\" : \"paprola\",\n \"state\" : \"HP\",\n \"zip\" : \"176115\",\n \"location\" : [\n 31.8955385,\n 76.8380405\n ],\n }\n }\n] \n..................................................\n"
},
{
"code": null,
"e": 61764,
"s": 61630,
"text": "This query is used to find the objects having values between the ranges of values given. For this, we need to use operators such as −"
},
{
"code": null,
"e": 61792,
"s": 61764,
"text": "gte − greater than equal to"
},
{
"code": null,
"e": 61810,
"s": 61792,
"text": "gt − greater-than"
},
{
"code": null,
"e": 61835,
"s": 61810,
"text": "lte − less-than equal to"
},
{
"code": null,
"e": 61850,
"s": 61835,
"text": "lt − less-than"
},
{
"code": null,
"e": 61894,
"s": 61850,
"text": "For example, observe the code given below −"
},
{
"code": null,
"e": 62016,
"s": 61894,
"text": "POST /schools*/_search\n{\n \"query\":{\n \"range\":{\n \"rating\":{\n \"gte\":3.5\n }\n }\n }\n}"
},
{
"code": null,
"e": 62080,
"s": 62016,
"text": "On running the above code, we get the response as shown below −"
},
{
"code": null,
"e": 63027,
"s": 62080,
"text": "{\n \"took\" : 24,\n \"timed_out\" : false,\n \"_shards\" : {\n \"total\" : 1,\n \"successful\" : 1,\n \"skipped\" : 0,\n \"failed\" : 0\n },\n \"hits\" : {\n \"total\" : {\n \"value\" : 1,\n \"relation\" : \"eq\"\n },\n \"max_score\" : 1.0,\n \"hits\" : [\n {\n \"_index\" : \"schools\",\n \"_type\" : \"school\",\n \"_id\" : \"4\",\n \"_score\" : 1.0,\n \"_source\" : {\n \"name\" : \"City Best School\",\n \"description\" : \"ICSE\",\n \"street\" : \"West End\",\n \"city\" : \"Meerut\",\n \"state\" : \"UP\",\n \"zip\" : \"250002\",\n \"location\" : [\n 28.9926174,\n 77.692485\n ],\n \"fees\" : 3500,\n \"tags\" : [\n \"fully computerized\"\n ],\n \"rating\" : \"4.5\"\n }\n }\n ]\n }\n}\n"
},
{
"code": null,
"e": 63088,
"s": 63027,
"text": "There exist other types of term level queries also such as −"
},
{
"code": null,
"e": 63142,
"s": 63088,
"text": "Exists query − If a certain field has non null value."
},
{
"code": null,
"e": 63196,
"s": 63142,
"text": "Exists query − If a certain field has non null value."
},
{
"code": null,
"e": 63342,
"s": 63196,
"text": "Missing query − This is completely opposite to exists query, this query searches for objects without specific fields or fields having null value."
},
{
"code": null,
"e": 63488,
"s": 63342,
"text": "Missing query − This is completely opposite to exists query, this query searches for objects without specific fields or fields having null value."
},
{
"code": null,
"e": 63584,
"s": 63488,
"text": "Wildcard or regexp query − This query uses regular expressions to find patterns in the objects."
},
{
"code": null,
"e": 63680,
"s": 63584,
"text": "Wildcard or regexp query − This query uses regular expressions to find patterns in the objects."
},
{
"code": null,
"e": 63855,
"s": 63680,
"text": "These queries are a collection of different queries merged with each other by using Boolean\noperators like and, or, not or for different indices or having function calls etc."
},
{
"code": null,
"e": 64131,
"s": 63855,
"text": "POST /schools/_search\n{\n \"query\": {\n \"bool\" : {\n \"must\" : {\n \"term\" : { \"state\" : \"UP\" }\n },\n \"filter\": {\n \"term\" : { \"fees\" : \"2200\" }\n },\n \"minimum_should_match\" : 1,\n \"boost\" : 1.0\n }\n }\n}"
},
{
"code": null,
"e": 64195,
"s": 64131,
"text": "On running the above code, we get the response as shown below −"
},
{
"code": null,
"e": 64485,
"s": 64195,
"text": "{\n \"took\" : 6,\n \"timed_out\" : false,\n \"_shards\" : {\n \"total\" : 1,\n \"successful\" : 1,\n \"skipped\" : 0,\n \"failed\" : 0\n },\n \"hits\" : {\n \"total\" : {\n \"value\" : 0,\n \"relation\" : \"eq\"\n },\n \"max_score\" : null,\n \"hits\" : [ ]\n }\n}\n"
},
{
"code": null,
"e": 64670,
"s": 64485,
"text": "These queries deal with geo locations and geo points. These queries help to find out schools\nor any other geographical object near to any location. You need to use geo point data type."
},
{
"code": null,
"e": 64810,
"s": 64670,
"text": "PUT /geo_example\n{\n \"mappings\": {\n \"properties\": {\n \"location\": {\n \"type\": \"geo_shape\"\n }\n }\n }\n}\n"
},
{
"code": null,
"e": 64874,
"s": 64810,
"text": "On running the above code, we get the response as shown below −"
},
{
"code": null,
"e": 64963,
"s": 64874,
"text": "{ \"acknowledged\" : true,\n \"shards_acknowledged\" : true,\n \"index\" : \"geo_example\"\n}\n"
},
{
"code": null,
"e": 65012,
"s": 64963,
"text": "Now we post the data in the index created above."
},
{
"code": null,
"e": 65175,
"s": 65012,
"text": "POST /geo_example/_doc?refresh\n{\n \"name\": \"Chapter One, London, UK\",\n \"location\": {\n \"type\": \"point\",\n \"coordinates\": [11.660544, 57.800286]\n }\n}\n"
},
{
"code": null,
"e": 65239,
"s": 65175,
"text": "On running the above code, we get the response as shown below −"
},
{
"code": null,
"e": 65923,
"s": 65239,
"text": "{\n \"took\" : 1,\n \"timed_out\" : false,\n \"_shards\" : {\n \"total\" : 1,\n \"successful\" : 1,\n \"skipped\" : 0,\n \"failed\" : 0\n },\n \"hits\" : {\n \"total\" : {\n \"value\" : 2,\n \"relation\" : \"eq\"\n },\n \"max_score\" : 1.0,\n \"hits\" : [\n \"_index\" : \"geo_example\",\n \"_type\" : \"_doc\",\n \"_id\" : \"hASWZ2oBbkdGzVfiXHKD\",\n \"_score\" : 1.0,\n \"_source\" : {\n \"name\" : \"Chapter One, London, UK\",\n \"location\" : {\n \"type\" : \"point\",\n \"coordinates\" : [\n 11.660544,\n 57.800286\n ]\n }\n }\n }\n }\n"
},
{
"code": null,
"e": 66145,
"s": 65923,
"text": "Mapping is the outline of the documents stored in an index. It defines the data type like geo_point or string and format of the fields present in the documents and rules to control the mapping of dynamically added fields."
},
{
"code": null,
"e": 66353,
"s": 66145,
"text": "PUT bankaccountdetails\n{\n \"mappings\":{\n \"properties\":{\n \"name\": { \"type\":\"text\"}, \"date\":{ \"type\":\"date\"},\n \"balance\":{ \"type\":\"double\"}, \"liability\":{ \"type\":\"double\"}\n }\n }\n }"
},
{
"code": null,
"e": 66418,
"s": 66353,
"text": "When we run the above code, we get the response as shown below −"
},
{
"code": null,
"e": 66516,
"s": 66418,
"text": "{\n \"acknowledged\" : true,\n \"shards_acknowledged\" : true,\n \"index\" : \"bankaccountdetails\"\n}\n"
},
{
"code": null,
"e": 66684,
"s": 66516,
"text": "Elasticsearch supports a number of different datatypes for the fields in a document. The\ndata types used to store fields in Elasticsearch are discussed in detail here."
},
{
"code": null,
"e": 66820,
"s": 66684,
"text": "These are the basic data types such as text, keyword, date, long, double, boolean or ip,\nwhich are supported by almost all the systems."
},
{
"code": null,
"e": 66983,
"s": 66820,
"text": "These data types are a combination of core data types. These include array, JSON object\nand nested data type. An example of nested data type is shown below &minus"
},
{
"code": null,
"e": 67178,
"s": 66983,
"text": "POST /tabletennis/_doc/1\n{\n \"group\" : \"players\",\n \"user\" : [\n {\n \"first\" : \"dave\", \"last\" : \"jones\"\n },\n {\n \"first\" : \"kevin\", \"last\" : \"morris\"\n }\n ]\n}"
},
{
"code": null,
"e": 67243,
"s": 67178,
"text": "When we run the above code, we get the response as shown below −"
},
{
"code": null,
"e": 67483,
"s": 67243,
"text": "{\n \"_index\" : \"tabletennis\",\n \"_type\" : \"_doc\",\n \"_id\" : \"1\",\n _version\" : 2,\n \"result\" : \"updated\",\n \"_shards\" : {\n \"total\" : 2,\n \"successful\" : 1,\n \"failed\" : 0\n },\n \"_seq_no\" : 1,\n \"_primary_term\" : 1\n}\n"
},
{
"code": null,
"e": 67520,
"s": 67483,
"text": "Another sample code is shown below −"
},
{
"code": null,
"e": 67641,
"s": 67520,
"text": "POST /accountdetails/_doc/1\n{\n \"from_acc\":\"7056443341\", \"to_acc\":\"7032460534\",\n \"date\":\"11/1/2016\", \"amount\":10000\n}"
},
{
"code": null,
"e": 67706,
"s": 67641,
"text": "When we run the above code, we get the response as shown below −"
},
{
"code": null,
"e": 67948,
"s": 67706,
"text": "{ \"_index\" : \"accountdetails\",\n \"_type\" : \"_doc\",\n \"_id\" : \"1\",\n \"_version\" : 1,\n \"result\" : \"created\",\n \"_shards\" : {\n \"total\" : 2,\n \"successful\" : 1,\n \"failed\" : 0\n },\n \"_seq_no\" : 1,\n \"_primary_term\" : 1\n}\n"
},
{
"code": null,
"e": 68013,
"s": 67948,
"text": "We can check the above document by using the following command −"
},
{
"code": null,
"e": 68068,
"s": 68013,
"text": "GET /accountdetails/_mappings?include_type_name=false\n"
},
{
"code": null,
"e": 68272,
"s": 68068,
"text": "Indices created in Elasticsearch 7.0.0 or later no longer accept a _default_ mapping. Indices created in 6.x will continue to function as before in Elasticsearch 6.x. Types are\ndeprecated in APIs in 7.0."
},
{
"code": null,
"e": 68595,
"s": 68272,
"text": "When a query is processed during a search operation, the content in any index is analyzed by the analysis module. This module consists of analyzer, tokenizer, tokenfilters and charfilters. If no analyzer is defined, then by default the built in analyzers, token, filters and tokenizers get registered with analysis module."
},
{
"code": null,
"e": 68789,
"s": 68595,
"text": "In the following example, we use a standard analyzer which is used when no other analyzer is specified. It will analyze the sentence based on the grammar and produce words used in the sentence."
},
{
"code": null,
"e": 68876,
"s": 68789,
"text": "POST _analyze\n{\n \"analyzer\": \"standard\",\n \"text\": \"Today's weather is beautiful\"\n}"
},
{
"code": null,
"e": 68940,
"s": 68876,
"text": "On running the above code, we get the response as shown below −"
},
{
"code": null,
"e": 69563,
"s": 68940,
"text": "{\n \"tokens\" : [\n {\n \"token\" : \"today's\",\n \"start_offset\" : 0,\n \"end_offset\" : 7,\n \"type\" : \"\",\n \"position\" : 0\n },\n {\n \"token\" : \"weather\",\n \"start_offset\" : 8,\n \"end_offset\" : 15,\n \"type\" : \"\",\n \"position\" : 1\n },\n {\n \"token\" : \"is\",\n \"start_offset\" : 16,\n \"end_offset\" : 18,\n \"type\" : \"\",\n \"position\" : 2\n },\n {\n \"token\" : \"beautiful\",\n \"start_offset\" : 19,\n \"end_offset\" : 28,\n \"type\" : \"\",\n \"position\" : 3\n }\n ]\n}\n"
},
{
"code": null,
"e": 69658,
"s": 69563,
"text": "We can configure the standard analyser with various parameters to get our custom requirements."
},
{
"code": null,
"e": 69752,
"s": 69658,
"text": "In the following example, we configure the standard analyzer to have a max_token_length of 5."
},
{
"code": null,
"e": 69840,
"s": 69752,
"text": "For this, we first create an index with the analyser having max_length_token parameter."
},
{
"code": null,
"e": 70113,
"s": 69840,
"text": "PUT index_4_analysis\n{\n \"settings\": {\n \"analysis\": {\n \"analyzer\": {\n \"my_english_analyzer\": {\n \"type\": \"standard\",\n \"max_token_length\": 5,\n \"stopwords\": \"_english_\"\n }\n }\n }\n }\n}"
},
{
"code": null,
"e": 70565,
"s": 70113,
"text": "Next we apply the analyser with a text as shown below. Please note how the token is does not appear as it has two spaces in the beginning and two spaces at the end. For the word “is”, there is a space at the beginning of it and a space at the end of it. Taking all of them, it becomes 4 letters with spaces and that does not make it a word. There should be a nonspace character at least at the beginning or at the end, to make it a word to be counted."
},
{
"code": null,
"e": 70680,
"s": 70565,
"text": "POST index_4_analysis/_analyze\n{\n \"analyzer\": \"my_english_analyzer\",\n \"text\": \"Today's weather is beautiful\"\n}"
},
{
"code": null,
"e": 70744,
"s": 70680,
"text": "On running the above code, we get the response as shown below −"
},
{
"code": null,
"e": 71650,
"s": 70744,
"text": "{\n \"tokens\" : [\n {\n \"token\" : \"today\",\n \"start_offset\" : 0,\n \"end_offset\" : 5,\n \"type\" : \"\",\n \"position\" : 0\n },\n {\n \"token\" : \"s\",\n \"start_offset\" : 6,\n \"end_offset\" : 7,\n \"type\" : \"\",\n \"position\" : 1\n },\n {\n \"token\" : \"weath\",\n \"start_offset\" : 8,\n \"end_offset\" : 13,\n \"type\" : \"\",\n \"position\" : 2\n },\n {\n \"token\" : \"er\",\n \"start_offset\" : 13,\n \"end_offset\" : 15,\n \"type\" : \"\",\n \"position\" : 3\n },\n {\n \"token\" : \"beaut\",\n \"start_offset\" : 19,\n \"end_offset\" : 24,\n \"type\" : \"\",\n \"position\" : 5\n },\n {\n \"token\" : \"iful\",\n \"start_offset\" : 24,\n \"end_offset\" : 28,\n \"type\" : \"\",\n \"position\" : 6\n }\n ]\n}\n"
},
{
"code": null,
"e": 71739,
"s": 71650,
"text": "The list of various analyzers and their description are given in the table shown below −"
},
{
"code": null,
"e": 71768,
"s": 71739,
"text": "Standard analyzer (standard)"
},
{
"code": null,
"e": 71902,
"s": 71768,
"text": "stopwords and max_token_length setting can be set for this analyzer. By default, stopwords list is empty and max_token_length is 255."
},
{
"code": null,
"e": 71927,
"s": 71902,
"text": "Simple analyzer (simple)"
},
{
"code": null,
"e": 71977,
"s": 71927,
"text": "This analyzer is composed of lowercase tokenizer."
},
{
"code": null,
"e": 72010,
"s": 71977,
"text": "Whitespace analyzer (whitespace)"
},
{
"code": null,
"e": 72061,
"s": 72010,
"text": "This analyzer is composed of whitespace tokenizer."
},
{
"code": null,
"e": 72082,
"s": 72061,
"text": "Stop analyzer (stop)"
},
{
"code": null,
"e": 72250,
"s": 72082,
"text": "stopwords and stopwords_path can be configured. By default stopwords initialized to English stop words and stopwords_path contains path to a text file with stop words."
},
{
"code": null,
"e": 72502,
"s": 72250,
"text": "Tokenizers are used for generating tokens from a text in Elasticsearch. Text can be broken down into tokens by taking whitespace or other punctuations into account. Elasticsearch has plenty of built-in tokenizers, which can be used in custom analyzer."
},
{
"code": null,
"e": 72663,
"s": 72502,
"text": "An example of tokenizer that breaks text into terms whenever it encounters a character which is not a letter, but it also lowercases all terms, is shown below −"
},
{
"code": null,
"e": 72762,
"s": 72663,
"text": "POST _analyze\n{\n \"tokenizer\": \"lowercase\",\n \"text\": \"It Was a Beautiful Weather 5 Days ago.\"\n}"
},
{
"code": null,
"e": 72826,
"s": 72762,
"text": "On running the above code, we get the response as shown below −"
},
{
"code": null,
"e": 73909,
"s": 72826,
"text": "{\n \"tokens\" : [\n {\n \"token\" : \"it\",\n \"start_offset\" : 0,\n \"end_offset\" : 2,\n \"type\" : \"word\",\n \"position\" : 0\n },\n {\n \"token\" : \"was\",\n \"start_offset\" : 3,\n \"end_offset\" : 6,\n \"type\" : \"word\",\n \"position\" : 1\n },\n {\n \"token\" : \"a\",\n \"start_offset\" : 7,\n \"end_offset\" : 8,\n \"type\" : \"word\",\n \"position\" : 2\n },\n {\n \"token\" : \"beautiful\",\n \"start_offset\" : 9,\n \"end_offset\" : 18,\n \"type\" : \"word\",\n \"position\" : 3\n },\n {\n \"token\" : \"weather\",\n \"start_offset\" : 19,\n \"end_offset\" : 26,\n \"type\" : \"word\",\n \"position\" : 4\n },\n {\n \"token\" : \"days\",\n \"start_offset\" : 29,\n \"end_offset\" : 33,\n \"type\" : \"word\",\n \"position\" : 5\n },\n {\n \"token\" : \"ago\",\n \"start_offset\" : 34,\n \"end_offset\" : 37,\n \"type\" : \"word\",\n \"position\" : 6\n }\n ]\n}\n"
},
{
"code": null,
"e": 73995,
"s": 73909,
"text": "A list of Tokenizers and their descriptions are shown here in the table given below −"
},
{
"code": null,
"e": 74025,
"s": 73995,
"text": "Standard tokenizer (standard)"
},
{
"code": null,
"e": 74125,
"s": 74025,
"text": "This is built on grammar based tokenizer and max_token_length can be\nconfigured for this tokenizer."
},
{
"code": null,
"e": 74158,
"s": 74125,
"text": "Edge NGram tokenizer (edgeNGram)"
},
{
"code": null,
"e": 74235,
"s": 74158,
"text": "Settings like min_gram, max_gram, token_chars can be set for this tokenizer."
},
{
"code": null,
"e": 74263,
"s": 74235,
"text": "Keyword tokenizer (keyword)"
},
{
"code": null,
"e": 74341,
"s": 74263,
"text": "This generates entire input as an output and buffer_size can be set for this."
},
{
"code": null,
"e": 74367,
"s": 74341,
"text": "Letter tokenizer (letter)"
},
{
"code": null,
"e": 74431,
"s": 74367,
"text": "This captures the whole word until a non-letter is encountered."
},
{
"code": null,
"e": 74580,
"s": 74431,
"text": "Elasticsearch is composed of a number of modules, which are responsible for its functionality. These modules have two types of settings as follows −"
},
{
"code": null,
"e": 74799,
"s": 74580,
"text": "Static Settings − These settings need to be configured in config (elasticsearch.yml) file before starting Elasticsearch. You need to update all the concern nodes in the cluster to reflect the changes by these settings."
},
{
"code": null,
"e": 75018,
"s": 74799,
"text": "Static Settings − These settings need to be configured in config (elasticsearch.yml) file before starting Elasticsearch. You need to update all the concern nodes in the cluster to reflect the changes by these settings."
},
{
"code": null,
"e": 75086,
"s": 75018,
"text": "Dynamic Settings − These settings can be set on live Elasticsearch."
},
{
"code": null,
"e": 75154,
"s": 75086,
"text": "Dynamic Settings − These settings can be set on live Elasticsearch."
},
{
"code": null,
"e": 75252,
"s": 75154,
"text": "We will discuss the different modules of Elasticsearch in the following sections of this chapter."
},
{
"code": null,
"e": 75437,
"s": 75252,
"text": "Cluster level settings decide the allocation of shards to different nodes and reallocation of shards to rebalance cluster. These are the following settings to control shard allocation."
},
{
"code": null,
"e": 75795,
"s": 75437,
"text": "This module helps a cluster to discover and maintain the state of all the nodes in it. The\nstate of cluster changes when a node is added or deleted from it. The cluster name setting is used to create logical difference between different clusters. There are some modules which help you to use the APIs provided by cloud vendors and those are as given below −"
},
{
"code": null,
"e": 75811,
"s": 75795,
"text": "Azure discovery"
},
{
"code": null,
"e": 75825,
"s": 75811,
"text": "EC2 discovery"
},
{
"code": null,
"e": 75857,
"s": 75825,
"text": "Google compute engine discovery"
},
{
"code": null,
"e": 75871,
"s": 75857,
"text": "Zen discovery"
},
{
"code": null,
"e": 76015,
"s": 75871,
"text": "This module maintains the cluster state and the shard data across full cluster restarts. The\nfollowing are the static settings of this module −"
},
{
"code": null,
"e": 76146,
"s": 76015,
"text": "This specifies the time for which the recovery process will wait to start regardless of the number of nodes joined in the cluster."
},
{
"code": null,
"e": 76243,
"s": 76146,
"text": "gateway.recover_ after_nodes\ngateway.recover_after_master_nodes\ngateway.recover_after_data_nodes"
},
{
"code": null,
"e": 76401,
"s": 76243,
"text": "This module manages the communication between HTTP client and Elasticsearch APIs. This module can be disabled by changing the value of http.enabled to false."
},
{
"code": null,
"e": 76491,
"s": 76401,
"text": "The following are the settings (configured in elasticsearch.yml) to control this module −"
},
{
"code": null,
"e": 76501,
"s": 76491,
"text": "http.port"
},
{
"code": null,
"e": 76570,
"s": 76501,
"text": "This is a port to access Elasticsearch and it ranges from 9200-9300."
},
{
"code": null,
"e": 76588,
"s": 76570,
"text": "http.publish_port"
},
{
"code": null,
"e": 76658,
"s": 76588,
"text": "This port is for http clients and is also useful in case of firewall."
},
{
"code": null,
"e": 76673,
"s": 76658,
"text": "http.bind_host"
},
{
"code": null,
"e": 76714,
"s": 76673,
"text": "This is a host address for http service."
},
{
"code": null,
"e": 76732,
"s": 76714,
"text": "http.publish_host"
},
{
"code": null,
"e": 76772,
"s": 76732,
"text": "This is a host address for http client."
},
{
"code": null,
"e": 76796,
"s": 76772,
"text": "http.max_content_length"
},
{
"code": null,
"e": 76880,
"s": 76796,
"text": "This is the maximum size of content in an http request. Its default value is 100mb."
},
{
"code": null,
"e": 76909,
"s": 76880,
"text": "http.max_initial_line_length"
},
{
"code": null,
"e": 76971,
"s": 76909,
"text": "This is the maximum size of URL and its default value is 4kb."
},
{
"code": null,
"e": 76992,
"s": 76971,
"text": "http.max_header_size"
},
{
"code": null,
"e": 77059,
"s": 76992,
"text": "This is the maximum http header size and its default value is 8kb."
},
{
"code": null,
"e": 77076,
"s": 77059,
"text": "http.compression"
},
{
"code": null,
"e": 77157,
"s": 77076,
"text": "This enables or disables support for compression and its default value is false."
},
{
"code": null,
"e": 77172,
"s": 77157,
"text": "http.pipelinig"
},
{
"code": null,
"e": 77214,
"s": 77172,
"text": "This enables or disables HTTP pipelining."
},
{
"code": null,
"e": 77241,
"s": 77214,
"text": "http.pipelining.max_events"
},
{
"code": null,
"e": 77322,
"s": 77241,
"text": "This restricts the number of events to be queued before closing an HTTP request."
},
{
"code": null,
"e": 77458,
"s": 77322,
"text": "This module maintains the settings, which are set globally for every index. The following\nsettings are mainly related to memory usage −"
},
{
"code": null,
"e": 77663,
"s": 77458,
"text": "This is used for preventing operation from causing an OutOfMemroyError. The setting mainly restricts the JVM heap size. For example, indices.breaker.total.limit setting, which defaults to 70% of JVM heap."
},
{
"code": null,
"e": 77881,
"s": 77663,
"text": "This is used mainly when aggregating on a field. It is recommended to have enough memory to allocate it. The amount of memory used for the field data cache can be controlled using indices.fielddata.cache.size setting."
},
{
"code": null,
"e": 78066,
"s": 77881,
"text": "This memory is used for caching the query results. This cache uses Least Recently Used (LRU) eviction policy. Indices.queries.cahce.size setting controls the memory size of this cache."
},
{
"code": null,
"e": 78268,
"s": 78066,
"text": "This buffer stores the newly created documents in the index and flushes them when the buffer is full. Setting like indices.memory.index_buffer_size control the amount of heap allocated for this buffer."
},
{
"code": null,
"e": 78430,
"s": 78268,
"text": "This cache is used to store the local search data for every shard. Cache can be enabled\nduring the creation of index or can be disabled by sending URL parameter."
},
{
"code": null,
"e": 78518,
"s": 78430,
"text": "Disable cache - ?request_cache = true\nEnable cache \"index.requests.cache.enable\": true\n"
},
{
"code": null,
"e": 78602,
"s": 78518,
"text": "It controls the resources during recovery process. The following are the settings −"
},
{
"code": null,
"e": 78771,
"s": 78602,
"text": "Time to Live (TTL) interval defines the time of a document, after which the document gets\ndeleted. The following are the dynamic settings for controlling this process −"
},
{
"code": null,
"e": 78948,
"s": 78771,
"text": "Each node has an option to be data node or not. You can change this property by changing node.data setting. Setting the value as false defines that the node is not a data\nnode."
},
{
"code": null,
"e": 79216,
"s": 78948,
"text": "These are the modules which are created for every index and control the settings and behaviour of the indices. For example, how many shards an index can use or the number of replicas a primary shard can have for that index etc. There are two types of index settings −"
},
{
"code": null,
"e": 79292,
"s": 79216,
"text": "Static − These can be set only at index creation time or on a closed index."
},
{
"code": null,
"e": 79340,
"s": 79292,
"text": "Dynamic − These can be changed on a live index."
},
{
"code": null,
"e": 79402,
"s": 79340,
"text": "The following table shows the list of static index settings −"
},
{
"code": null,
"e": 79465,
"s": 79402,
"text": "The following table shows the list of dynamic index settings −"
},
{
"code": null,
"e": 79654,
"s": 79465,
"text": "Sometimes we need to transform a document before we index it. For instance, we want to remove a field from the document or rename a field and then index it. This is handled by Ingest node."
},
{
"code": null,
"e": 79776,
"s": 79654,
"text": "Every node in the cluster has the ability to ingest but it can also be customized to be\nprocessed only by specific nodes."
},
{
"code": null,
"e": 79841,
"s": 79776,
"text": "There are two steps involved in the working of the ingest node −"
},
{
"code": null,
"e": 79861,
"s": 79841,
"text": "Creating a pipeline"
},
{
"code": null,
"e": 79876,
"s": 79861,
"text": "Creating a doc"
},
{
"code": null,
"e": 79982,
"s": 79876,
"text": "First creating a pipeline which contains the processors and then executing the pipeline, as\nshown below −"
},
{
"code": null,
"e": 80228,
"s": 79982,
"text": "PUT _ingest/pipeline/int-converter\n{\n \"description\": \"converts the content of the seq field to an integer\",\n \"processors\" : [\n {\n \"convert\" : {\n \"field\" : \"seq\",\n \"type\": \"integer\"\n }\n }\n ]\n}"
},
{
"code": null,
"e": 80285,
"s": 80228,
"text": "On running the above code, we get the following result −"
},
{
"code": null,
"e": 80315,
"s": 80285,
"text": "{\n \"acknowledged\" : true\n}\n"
},
{
"code": null,
"e": 80371,
"s": 80315,
"text": "Next we create a document using the pipeline converter."
},
{
"code": null,
"e": 80481,
"s": 80371,
"text": "PUT /logs/_doc/1?pipeline=int-converter\n{\n \"seq\":\"21\",\n \"name\":\"Tutorialspoint\",\n \"Addrs\":\"Hyderabad\"\n}"
},
{
"code": null,
"e": 80545,
"s": 80481,
"text": "On running the above code, we get the response as shown below −"
},
{
"code": null,
"e": 80779,
"s": 80545,
"text": "{\n \"_index\" : \"logs\",\n \"_type\" : \"_doc\",\n \"_id\" : \"1\",\n \"_version\" : 1,\n \"result\" : \"created\",\n \"_shards\" : {\n \"total\" : 2,\n \"successful\" : 1,\n \"failed\" : 0\n },\n \"_seq_no\" : 0,\n \"_primary_term\" : 1\n}\n"
},
{
"code": null,
"e": 80862,
"s": 80779,
"text": "Next we search for the doc created above by using the GET command as shown below −"
},
{
"code": null,
"e": 80879,
"s": 80862,
"text": "GET /logs/_doc/1"
},
{
"code": null,
"e": 80936,
"s": 80879,
"text": "On running the above code, we get the following result −"
},
{
"code": null,
"e": 81181,
"s": 80936,
"text": "{\n \"_index\" : \"logs\",\n \"_type\" : \"_doc\",\n \"_id\" : \"1\",\n \"_version\" : 1,\n \"_seq_no\" : 0,\n \"_primary_term\" : 1,\n \"found\" : true,\n \"_source\" : {\n \"Addrs\" : \"Hyderabad\",\n \"name\" : \"Tutorialspoint\",\n \"seq\" : 21\n }\n}\n"
},
{
"code": null,
"e": 81230,
"s": 81181,
"text": "You can see above that 21 has become an integer."
},
{
"code": null,
"e": 81283,
"s": 81230,
"text": "Now we create a document without using the pipeline."
},
{
"code": null,
"e": 81383,
"s": 81283,
"text": "PUT /logs/_doc/2\n{\n \"seq\":\"11\",\n \"name\":\"Tutorix\",\n \"Addrs\":\"Secunderabad\"\n}\nGET /logs/_doc/2"
},
{
"code": null,
"e": 81440,
"s": 81383,
"text": "On running the above code, we get the following result −"
},
{
"code": null,
"e": 81683,
"s": 81440,
"text": "{\n \"_index\" : \"logs\",\n \"_type\" : \"_doc\",\n \"_id\" : \"2\",\n \"_version\" : 1,\n \"_seq_no\" : 1,\n \"_primary_term\" : 1,\n \"found\" : true,\n \"_source\" : {\n \"seq\" : \"11\",\n \"name\" : \"Tutorix\",\n \"Addrs\" : \"Secunderabad\"\n }\n}\n"
},
{
"code": null,
"e": 81754,
"s": 81683,
"text": "You can see above that 11 is a string without the pipeline being used."
},
{
"code": null,
"e": 81997,
"s": 81754,
"text": "Managing the index lifecycle involves performing management actions based on factors like shard size and performance requirements. The index lifecycle management (ILM) APIs enable you to automate how you want to manage your indices over time."
},
{
"code": null,
"e": 82052,
"s": 81997,
"text": "This chapter gives a list of ILM APIs and their usage."
},
{
"code": null,
"e": 82358,
"s": 82052,
"text": "It is a component that allows SQL-like queries to be executed in real-time against Elasticsearch. You can think of Elasticsearch SQL as a translator, one that understands both SQL and Elasticsearch and makes it easy to read and process data in real-time, at scale by leveraging Elasticsearch capabilities."
},
{
"code": null,
"e": 82495,
"s": 82358,
"text": "It has native integration − Each and every query is efficiently executed against the relevant nodes according to the underlying storage."
},
{
"code": null,
"e": 82632,
"s": 82495,
"text": "It has native integration − Each and every query is efficiently executed against the relevant nodes according to the underlying storage."
},
{
"code": null,
"e": 82742,
"s": 82632,
"text": "No external parts − No need for additional hardware, processes, runtimes or\nlibraries to query Elasticsearch."
},
{
"code": null,
"e": 82852,
"s": 82742,
"text": "No external parts − No need for additional hardware, processes, runtimes or\nlibraries to query Elasticsearch."
},
{
"code": null,
"e": 82956,
"s": 82852,
"text": "Lightweight and efficient − it embraces and exposes SQL to allow proper full-text search, in real-time."
},
{
"code": null,
"e": 83060,
"s": 82956,
"text": "Lightweight and efficient − it embraces and exposes SQL to allow proper full-text search, in real-time."
},
{
"code": null,
"e": 83508,
"s": 83060,
"text": "PUT /schoollist/_bulk?refresh\n {\"index\":{\"_id\": \"CBSE\"}}\n {\"name\": \"GleanDale\", \"Address\": \"JR. Court Lane\", \"start_date\": \"2011-06-02\",\n \"student_count\": 561}\n {\"index\":{\"_id\": \"ICSE\"}}\n {\"name\": \"Top-Notch\", \"Address\": \"Gachibowli Main Road\", \"start_date\": \"1989-\n 05-26\", \"student_count\": 482}\n {\"index\":{\"_id\": \"State Board\"}}\n {\"name\": \"Sunshine\", \"Address\": \"Main Street\", \"start_date\": \"1965-06-01\",\n \"student_count\": 604}"
},
{
"code": null,
"e": 83572,
"s": 83508,
"text": "On running the above code, we get the response as shown below −"
},
{
"code": null,
"e": 85021,
"s": 83572,
"text": "{\n \"took\" : 277,\n \"errors\" : false,\n \"items\" : [\n {\n \"index\" : {\n \"_index\" : \"schoollist\",\n \"_type\" : \"_doc\",\n \"_id\" : \"CBSE\",\n \"_version\" : 1,\n \"result\" : \"created\",\n \"forced_refresh\" : true,\n \"_shards\" : {\n \"total\" : 2,\n \"successful\" : 1,\n \"failed\" : 0\n },\n \"_seq_no\" : 0,\n \"_primary_term\" : 1,\n \"status\" : 201\n }\n },\n {\n \"index\" : {\n \"_index\" : \"schoollist\",\n \"_type\" : \"_doc\",\n \"_id\" : \"ICSE\",\n \"_version\" : 1,\n \"result\" : \"created\",\n \"forced_refresh\" : true,\n \"_shards\" : {\n \"total\" : 2,\n \"successful\" : 1,\n \"failed\" : 0\n },\n \"_seq_no\" : 1,\n \"_primary_term\" : 1,\n \"status\" : 201\n }\n },\n {\n \"index\" : {\n \"_index\" : \"schoollist\",\n \"_type\" : \"_doc\",\n \"_id\" : \"State Board\",\n \"_version\" : 1,\n \"result\" : \"created\",\n \"forced_refresh\" : true,\n \"_shards\" : {\n \"total\" : 2,\n \"successful\" : 1,\n \"failed\" : 0\n },\n \"_seq_no\" : 2,\n \"_primary_term\" : 1,\n \"status\" : 201\n }\n }\n ]\n}\n"
},
{
"code": null,
"e": 85078,
"s": 85021,
"text": "The following example shows how we frame the SQL query −"
},
{
"code": null,
"e": 85176,
"s": 85078,
"text": "POST /_sql?format=txt\n{\n \"query\": \"SELECT * FROM schoollist WHERE start_date < '2000-01-01'\"\n}\n"
},
{
"code": null,
"e": 85240,
"s": 85176,
"text": "On running the above code, we get the response as shown below −"
},
{
"code": null,
"e": 85528,
"s": 85240,
"text": "Address | name | start_date | student_count\n--------------------+---------------+------------------------+---------------\nGachibowli Main Road|Top-Notch |1989-05-26T00:00:00.000Z|482\nMain Street |Sunshine |1965-06-01T00:00:00.000Z|604\n"
},
{
"code": null,
"e": 85603,
"s": 85528,
"text": "Note − By changing the SQL query above, you can get different result sets."
},
{
"code": null,
"e": 85911,
"s": 85603,
"text": "To monitor the health of the cluster, the monitoring feature collects metrics from each node and stores them in Elasticsearch Indices. All settings associated with monitoring in Elasticsearch must be set in either the elasticsearch.yml file for each node or, where possible, in the dynamic cluster settings."
},
{
"code": null,
"e": 86021,
"s": 85911,
"text": "In order to start monitoring, we need to check the cluster settings, which can be done in the following way −"
},
{
"code": null,
"e": 86092,
"s": 86021,
"text": "GET _cluster/settings\n{\n \"persistent\" : { },\n \"transient\" : { }\n}\n"
},
{
"code": null,
"e": 86383,
"s": 86092,
"text": "Each component in the stack is responsible for monitoring itself and then forwarding those documents to the Elasticsearch production cluster for both routing and indexing (storage). The routing and indexing processes in Elasticsearch are handled by what are called collectors and exporters."
},
{
"code": null,
"e": 86633,
"s": 86383,
"text": "Collector runs once per each collection interval to obtain data from the public APIs in Elasticsearch that it chooses to monitor. When the data collection is finished, the data is handed in bulk to the exporters to be sent to the monitoring cluster."
},
{
"code": null,
"e": 86746,
"s": 86633,
"text": "There is only one collector per data type gathered. Each collector can create zero or more monitoring documents."
},
{
"code": null,
"e": 87024,
"s": 86746,
"text": "Exporters take data collected from any Elastic Stack source and route it to the monitoring cluster. It is possible to configure more than one exporter, but the general and default setup is to use a single exporter. Exporters are configurable at both the node and cluster level."
},
{
"code": null,
"e": 87076,
"s": 87024,
"text": "There are two types of exporters in Elasticsearch −"
},
{
"code": null,
"e": 87137,
"s": 87076,
"text": "local − This exporter routes data back into the same cluster"
},
{
"code": null,
"e": 87198,
"s": 87137,
"text": "local − This exporter routes data back into the same cluster"
},
{
"code": null,
"e": 87323,
"s": 87198,
"text": "http − The preferred exporter, which you can use to route data into any supported Elasticsearch cluster accessible via HTTP."
},
{
"code": null,
"e": 87448,
"s": 87323,
"text": "http − The preferred exporter, which you can use to route data into any supported Elasticsearch cluster accessible via HTTP."
},
{
"code": null,
"e": 87597,
"s": 87448,
"text": "Before exporters can route monitoring data, they must set up certain Elasticsearch resources. These resources include templates and ingest pipelines"
},
{
"code": null,
"e": 87910,
"s": 87597,
"text": "A rollup job is a periodic task that summarizes data from indices specified by an index pattern and rolls it into a new index. In the following example, we create an index named sensor with different date time stamps. Then we create a rollup job to rollup the data from these indices periodically using cron job."
},
{
"code": null,
"e": 88021,
"s": 87910,
"text": "PUT /sensor/_doc/1\n{\n \"timestamp\": 1516729294000,\n \"temperature\": 200,\n \"voltage\": 5.2,\n \"node\": \"a\"\n}"
},
{
"code": null,
"e": 88078,
"s": 88021,
"text": "On running the above code, we get the following result −"
},
{
"code": null,
"e": 88314,
"s": 88078,
"text": "{\n \"_index\" : \"sensor\",\n \"_type\" : \"_doc\",\n \"_id\" : \"1\",\n \"_version\" : 1,\n \"result\" : \"created\",\n \"_shards\" : {\n \"total\" : 2,\n \"successful\" : 1,\n \"failed\" : 0\n },\n \"_seq_no\" : 0,\n \"_primary_term\" : 1\n}\n"
},
{
"code": null,
"e": 88380,
"s": 88314,
"text": "Now, add a second document and so on for other documents as well."
},
{
"code": null,
"e": 88502,
"s": 88380,
"text": "PUT /sensor-2018-01-01/_doc/2\n{\n \"timestamp\": 1413729294000,\n \"temperature\": 201,\n \"voltage\": 5.9,\n \"node\": \"a\"\n}"
},
{
"code": null,
"e": 89003,
"s": 88502,
"text": "PUT _rollup/job/sensor\n{\n \"index_pattern\": \"sensor-*\",\n \"rollup_index\": \"sensor_rollup\",\n \"cron\": \"*/30 * * * * ?\",\n \"page_size\" :1000,\n \"groups\" : {\n \"date_histogram\": {\n \"field\": \"timestamp\",\n \"interval\": \"60m\"\n },\n \"terms\": {\n \"fields\": [\"node\"]\n }\n },\n \"metrics\": [\n {\n \"field\": \"temperature\",\n \"metrics\": [\"min\", \"max\", \"sum\"]\n },\n {\n \"field\": \"voltage\",\n \"metrics\": [\"avg\"]\n }\n ]\n}\n"
},
{
"code": null,
"e": 89187,
"s": 89003,
"text": "The cron parameter controls when and how often the job activates. When a rollup job’s cron schedule triggers, it will begin rolling up from where it left off after the last activation"
},
{
"code": null,
"e": 89281,
"s": 89187,
"text": "After the job has run and processed some data, we can use the DSL Query to do some searching."
},
{
"code": null,
"e": 89459,
"s": 89281,
"text": "GET /sensor_rollup/_rollup_search\n{\n \"size\": 0,\n \"aggregations\": {\n \"max_temperature\": {\n \"max\": {\n \"field\": \"temperature\"\n }\n }\n }\n}\n"
},
{
"code": null,
"e": 89779,
"s": 89459,
"text": "The indices that are searched frequently are held in memory because it takes time to rebuild them and help in an efficient search. On the other hand, there may be indices which we rarely access. Those indices need not occupy the memory and can be re-build when they are needed. Such indices are known as frozen indices."
},
{
"code": null,
"e": 90194,
"s": 89779,
"text": "Elasticsearch builds the transient data structures of each shard of a frozen index each time\nthat shard is searched and discards these data structures as soon as the search is complete. Because Elasticsearch does not maintain these transient data structures in memory, frozen indices consume much less heap than the normal indices. This allows for a much higher disk-to-heap ratio than would otherwise be possible."
},
{
"code": null,
"e": 90249,
"s": 90194,
"text": "The following example freezes and unfreezes an index −"
},
{
"code": null,
"e": 90302,
"s": 90249,
"text": "POST /index_name/_freeze\nPOST /index_name/_unfreeze\n"
},
{
"code": null,
"e": 90589,
"s": 90302,
"text": "Searches on frozen indices are expected to execute slowly. Frozen indices are not intended\nfor high search load. It is possible that a search of a frozen index may take seconds or minutes to complete, even if the same searches completed in milliseconds when the indices were not frozen."
},
{
"code": null,
"e": 90854,
"s": 90589,
"text": "The number of concurrently loaded frozen indices per node is limited by the number of threads in the search_throttled threadpool, which is 1 by default. To include frozen indices,\na search request must be executed with the query parameter − ignore_throttled=false."
},
{
"code": null,
"e": 90916,
"s": 90854,
"text": "GET /index_name/_search?q=user:tpoint&ignore_throttled=false\n"
},
{
"code": null,
"e": 91024,
"s": 90916,
"text": "Frozen indices are ordinary indices that use search throttling and a memory efficient shard\nimplementation."
},
{
"code": null,
"e": 91064,
"s": 91024,
"text": "GET /_cat/indices/index_name?v&h=i,sth\n"
},
{
"code": null,
"e": 91343,
"s": 91064,
"text": "Elasticsearch provides a jar file, which can be added to any java IDE and can be used to test the code which is related to Elasticsearch. A range of tests can be performed by using the framework provided by Elasticsearch. In this chapter, we will discuss these tests in detail −"
},
{
"code": null,
"e": 91356,
"s": 91343,
"text": "Unit testing"
},
{
"code": null,
"e": 91376,
"s": 91356,
"text": "Integration testing"
},
{
"code": null,
"e": 91395,
"s": 91376,
"text": "Randomized testing"
},
{
"code": null,
"e": 91561,
"s": 91395,
"text": "To start with testing, you need to add the Elasticsearch testing dependency to your program. You can use maven for this purpose and can add the following in pom.xml."
},
{
"code": null,
"e": 91698,
"s": 91561,
"text": "<dependency>\n <groupId>org.elasticsearch</groupId>\n <artifactId>elasticsearch</artifactId>\n <version>2.1.0</version>\n</dependency>"
},
{
"code": null,
"e": 91792,
"s": 91698,
"text": "EsSetup has been initialized to start and stop Elasticsearch node and also to create indices."
},
{
"code": null,
"e": 91826,
"s": 91792,
"text": "EsSetup esSetup = new EsSetup();\n"
},
{
"code": null,
"e": 91944,
"s": 91826,
"text": "esSetup.execute() function with createIndex will create the indices, you need to specify the settings, type and data."
},
{
"code": null,
"e": 92205,
"s": 91944,
"text": "Unit test is carried out by using JUnit and Elasticsearch test framework. Node and indices can be created using Elasticsearch classes and in test method can be used to perform the testing. ESTestCase and ESTokenStreamTestCase classes are used for this testing."
},
{
"code": null,
"e": 92385,
"s": 92205,
"text": "Integration testing uses multiple nodes in a cluster. ESIntegTestCase class is used for this testing. There are various methods which make the job of preparing a test case easier."
},
{
"code": null,
"e": 92395,
"s": 92385,
"text": "refresh()"
},
{
"code": null,
"e": 92438,
"s": 92395,
"text": "All the indices in a cluster are refreshed"
},
{
"code": null,
"e": 92452,
"s": 92438,
"text": "ensureGreen()"
},
{
"code": null,
"e": 92489,
"s": 92452,
"text": "Ensures a green health cluster state"
},
{
"code": null,
"e": 92504,
"s": 92489,
"text": "ensureYellow()"
},
{
"code": null,
"e": 92542,
"s": 92504,
"text": "Ensures a yellow health cluster state"
},
{
"code": null,
"e": 92560,
"s": 92542,
"text": "createIndex(name)"
},
{
"code": null,
"e": 92609,
"s": 92560,
"text": "Create index with the name passed to this method"
},
{
"code": null,
"e": 92617,
"s": 92609,
"text": "flush()"
},
{
"code": null,
"e": 92652,
"s": 92617,
"text": "All indices in cluster are flushed"
},
{
"code": null,
"e": 92670,
"s": 92652,
"text": "flushAndRefresh()"
},
{
"code": null,
"e": 92692,
"s": 92670,
"text": "flush() and refresh()"
},
{
"code": null,
"e": 92710,
"s": 92692,
"text": "indexExists(name)"
},
{
"code": null,
"e": 92752,
"s": 92710,
"text": "Verifies the existence of specified index"
},
{
"code": null,
"e": 92769,
"s": 92752,
"text": "clusterService()"
},
{
"code": null,
"e": 92808,
"s": 92769,
"text": "Returns the cluster service java class"
},
{
"code": null,
"e": 92818,
"s": 92808,
"text": "cluster()"
},
{
"code": null,
"e": 92849,
"s": 92818,
"text": "Returns the test cluster class"
},
{
"code": null,
"e": 92874,
"s": 92849,
"text": "ensureAtLeastNumNodes(n)"
},
{
"code": null,
"e": 92965,
"s": 92874,
"text": "Ensures minimum number of nodes up in a cluster is more than or equal to specified number."
},
{
"code": null,
"e": 92989,
"s": 92965,
"text": "ensureAtMostNumNodes(n)"
},
{
"code": null,
"e": 93080,
"s": 92989,
"text": "Ensures maximum number of nodes up in a cluster is less than or equal to specified number."
},
{
"code": null,
"e": 93097,
"s": 93080,
"text": "stopRandomNode()"
},
{
"code": null,
"e": 93132,
"s": 93097,
"text": "To stop a random node in a cluster"
},
{
"code": null,
"e": 93156,
"s": 93132,
"text": "stopCurrentMasterNode()"
},
{
"code": null,
"e": 93180,
"s": 93156,
"text": "To stop the master node"
},
{
"code": null,
"e": 93202,
"s": 93180,
"text": "stopRandomNonMaster()"
},
{
"code": null,
"e": 93266,
"s": 93202,
"text": "To stop a random node in a cluster, which is not a master node."
},
{
"code": null,
"e": 93278,
"s": 93266,
"text": "buildNode()"
},
{
"code": null,
"e": 93296,
"s": 93278,
"text": "Create a new node"
},
{
"code": null,
"e": 93316,
"s": 93296,
"text": "startNode(settings)"
},
{
"code": null,
"e": 93333,
"s": 93316,
"text": "Start a new node"
},
{
"code": null,
"e": 93348,
"s": 93333,
"text": "nodeSettings()"
},
{
"code": null,
"e": 93397,
"s": 93348,
"text": "Override this method for changing node settings."
},
{
"code": null,
"e": 93688,
"s": 93397,
"text": "A client is used to access different nodes in a cluster and carry out some action. ESIntegTestCase.client() method is used for getting a random client. Elasticsearch offers other methods also to access client and those methods can be accessed using ESIntegTestCase.internalCluster() method."
},
{
"code": null,
"e": 93699,
"s": 93688,
"text": "iterator()"
},
{
"code": null,
"e": 93751,
"s": 93699,
"text": "This helps you to access all the available clients."
},
{
"code": null,
"e": 93766,
"s": 93751,
"text": "masterClient()"
},
{
"code": null,
"e": 93830,
"s": 93766,
"text": "This returns a client, which is communicating with master node."
},
{
"code": null,
"e": 93848,
"s": 93830,
"text": "nonMasterClient()"
},
{
"code": null,
"e": 93916,
"s": 93848,
"text": "This returns a client, which is not communicating with master node."
},
{
"code": null,
"e": 93935,
"s": 93916,
"text": "clientNodeClient()"
},
{
"code": null,
"e": 93986,
"s": 93935,
"text": "This returns a client currently up on client node."
},
{
"code": null,
"e": 94181,
"s": 93986,
"text": "This testing is used to test the user’s code with every possible data, so that there will be no failure in future with any type of data. Random data is the best option to carry out this testing."
},
{
"code": null,
"e": 94335,
"s": 94181,
"text": "In this testing, the Random class is instantiated by the instance provided by RandomizedTest and offers many methods for getting different types of data."
},
{
"code": null,
"e": 94534,
"s": 94335,
"text": "ElasticsearchAssertions and ElasticsearchGeoAssertions classes contain assertions, which are used for performing some common checks at the time of testing. For example, observe the code given here −"
},
{
"code": null,
"e": 94735,
"s": 94534,
"text": "SearchResponse seearchResponse = client().prepareSearch();\nassertHitCount(searchResponse, 6);\nassertFirstHit(searchResponse, hasId(\"6\"));\nassertSearchHits(searchResponse, \"1\", \"2\", \"3\", \"4\",”5”,”6”);\n"
},
{
"code": null,
"e": 94972,
"s": 94735,
"text": "A Kibana dashboard is a collection of visualizations and searches. You can arrange, resize,\nand edit the dashboard content and then save the dashboard so you can share it. In this chapter, we will see how to create and edit a dashboard."
},
{
"code": null,
"e": 95117,
"s": 94972,
"text": "From the Kibana Homepage, select the dashboard option from the left control bars as shown below. This will prompt you to create a new dashboard."
},
{
"code": null,
"e": 95300,
"s": 95117,
"text": "To Add visualizations to the dashboard, we choose the menu Add and the select from the pre-built visualizations available. We chose the following visualization options from the list."
},
{
"code": null,
"e": 95470,
"s": 95300,
"text": "On selecting the above visualizations, we get the dashboard as shown here. We can later add and edit the dashboard for changing the elements and adding the new elements."
},
{
"code": null,
"e": 95651,
"s": 95470,
"text": "We can inspect the Dashboard elements by choosing the visualizations panel menu and selecting Inspect. This will bring out the data behind the element which also can be downloaded."
},
{
"code": null,
"e": 95766,
"s": 95651,
"text": "We can share the dashboard by choosing the share menu and selecting the option to get\na hyperlink as shown below −"
},
{
"code": null,
"e": 96030,
"s": 95766,
"text": "The discover functionality available in Kibana home page allows us to explore the data sets\nfrom various angles. You can search and filter data for the selected index patterns. The data is usually available in form of distribution of values over a period of time."
},
{
"code": null,
"e": 96179,
"s": 96030,
"text": "To explore the ecommerce data sample, we click on the Discover icon as shown in the\npicture below. This will bring up the data along with the chart."
},
{
"code": null,
"e": 96315,
"s": 96179,
"text": "To filter out data by specific time interval we use the time filter option as shown below. By\ndefault, the filter is set at 15 minutes."
},
{
"code": null,
"e": 96609,
"s": 96315,
"text": "The data set can also be filtered by fields using the Add Filter option as shown below. Here we add one or more fields and get the corresponding result after the filters are applied. In our example we choose the field day_of_week and then the operator for that field as is and value as Sunday."
},
{
"code": null,
"e": 96731,
"s": 96609,
"text": "Next, we click Save with above filter conditions. The result set containing the filter\nconditions applied is shown below."
},
{
"code": null,
"e": 97015,
"s": 96731,
"text": "The data table is type of visualization that is used to display the raw data of a composed\naggregation. There are various types of aggregations that are presented by using Data tables. In order to create a Data Table, we should go through the steps that are discussed here in detail."
},
{
"code": null,
"e": 97208,
"s": 97015,
"text": "In Kibana Home screen we find the option name Visualize which allows us to create visualization and aggregations from the indices stored in Elasticsearch. The following image shows the option."
},
{
"code": null,
"e": 97353,
"s": 97208,
"text": "Next, we select the Data Table option from among the various visualization options available. The option is shown in the following image &miuns;"
},
{
"code": null,
"e": 97575,
"s": 97353,
"text": "We then select the metrics needed for creating the data table visualization. This choice\ndecides the type of aggregation we are going to use. We select the specific fields shown below from the ecommerce data set for this."
},
{
"code": null,
"e": 97673,
"s": 97575,
"text": "On running the above configuration for Data Table, we get the result as shown in the\nimage here −"
},
{
"code": null,
"e": 97915,
"s": 97673,
"text": "Region Maps show metrics on a geographic Map. It is useful in looking at the data anchored to different geographic regions with varying intensity. The darker shades usually indicate higher values and the lighter shades indicate lower values."
},
{
"code": null,
"e": 97994,
"s": 97915,
"text": "The steps to create this visualization are as explained in detail as follows −"
},
{
"code": null,
"e": 98146,
"s": 97994,
"text": "In this step we go to the visualize button available in the left bar of the Kibana Home\nscreen and then choosing the option to add a new Visualization."
},
{
"code": null,
"e": 98210,
"s": 98146,
"text": "The following screen shows how we choose the region Map option."
},
{
"code": null,
"e": 98454,
"s": 98210,
"text": "The next screen prompts us for choosing the metrics which will be used in creating the Region Map. Here we choose the Average price as the metric and country_iso_code as the field in the bucket which will be used in creating the visualization."
},
{
"code": null,
"e": 98605,
"s": 98454,
"text": "The final result below shows the Region Map once we apply the selection. Please note the\nshades of the colour and their values mentioned in the label."
},
{
"code": null,
"e": 98880,
"s": 98605,
"text": "Pie charts are one of the simplest and famous visualization tools. It represents the data as slices of a circle each coloured differently. The labels along with the percentage data values can be presented along with the circle. The circle can also take the shape of a donut."
},
{
"code": null,
"e": 99121,
"s": 98880,
"text": "In Kibana Home screen, we find the option name Visualize which allows us to create visualization and aggregations from the indices stored in Elasticsearch. We choose to add a new visualization and select pie chart as the option shown below."
},
{
"code": null,
"e": 99431,
"s": 99121,
"text": "The next screen prompts us for choosing the metrics which will be used in creating the Pie Chart. Here we choose the count of base unit price as the metric and Bucket Aggregation as histogram. Also, the minimum interval is chosen as 20. So, the prices will be displayed as blocks of values with 20 as a range."
},
{
"code": null,
"e": 99576,
"s": 99431,
"text": "The result below shows the pie chart after we apply the selection. Please note the shades of the colour and their values mentioned in the label."
},
{
"code": null,
"e": 99833,
"s": 99576,
"text": "On moving to the options tab under pie chart we can see various configuration options to change the look as well as the arrangement of data display in the pie chart. In the following example, the pie chart appears as donut and the labels appear at the top."
},
{
"code": null,
"e": 100117,
"s": 99833,
"text": "An area chart is an extension of line chart where the area between the line chart and the axes is highlighted with some colours. A bar chart represents data organized into a range of values and then plotted against the axes. It can consist of either horizontal bars or vertical bars."
},
{
"code": null,
"e": 100297,
"s": 100117,
"text": "In this chapter we will see all these three types of graphs that is created using Kibana. As\ndiscussed in earlier chapters we will continue to use the data in the ecommerce index."
},
{
"code": null,
"e": 100558,
"s": 100297,
"text": "In Kibana Home screen, we find the option name Visualize which allows us to create\nvisualization and aggregations from the indices stored in Elasticsearch. We choose to add a new visualization and select Area Chart as the option shown in the image given below."
},
{
"code": null,
"e": 100890,
"s": 100558,
"text": "The next screen prompts us for choosing the metrics which will be used in creating the Area Chart. Here we choose the sum as the type of aggregation metric. Then we choose total_quantity field as the field to be used as metric. On the X-axis, we chose the order_date field and split the series with the given metric in a size of 5."
},
{
"code": null,
"e": 100974,
"s": 100890,
"text": "On running the above configuration, we get the following area chart as the output −"
},
{
"code": null,
"e": 101309,
"s": 100974,
"text": "Similarly, for the Horizontal bar chart we choose new visualization from Kibana Home screen and choose the option for Horizontal Bar. Then we choose the metrics as shown in the image below. Here we choose Sum as the aggregation for the filed named product quantity. Then we choose buckets with date histogram for the field order date."
},
{
"code": null,
"e": 101396,
"s": 101309,
"text": "On running the above configuration, we can see a horizontal bar chart as shown below −"
},
{
"code": null,
"e": 101572,
"s": 101396,
"text": "For the vertical bar chart, we choose new visualization from Kibana Home screen and choose the option for Vertical Bar. Then we choose the metrics as shown in the image below."
},
{
"code": null,
"e": 101740,
"s": 101572,
"text": "Here we choose Sum as the aggregation for the field named product quantity. Then we choose buckets with date histogram for the field order date with a weekly interval."
},
{
"code": null,
"e": 101819,
"s": 101740,
"text": "On running the above configuration, a chart will be generated as shown below −"
},
{
"code": null,
"e": 102127,
"s": 101819,
"text": "Time series is a representation of sequence of data in a specific time sequence. For example, the data for each day starting from first day of the month to the last day. The interval between the data points remains constant. Any data set which has a time component in it can be represented as a time series."
},
{
"code": null,
"e": 102268,
"s": 102127,
"text": "In this chapter, we will use the sample e-commerce data set and plot the count of the number of orders for each day to create a time series."
},
{
"code": null,
"e": 102632,
"s": 102268,
"text": "First, we choose the index pattern, data field and interval which will be used for creating\nthe time series. From the sample ecommerce data set we choose order_date as the field and 1d as the interval. We use the Panel Options tab to make these choices. Also we leave the other values in this tab as default to get a default colour and format for the time series."
},
{
"code": null,
"e": 102765,
"s": 102632,
"text": "In the Data tab, we choose count as the aggregation option, group by option as everything and put a label for the time series chart."
},
{
"code": null,
"e": 102953,
"s": 102765,
"text": "The final result of this configuration appears as follows. Please note that we are using a\ntime period of Month to Date for this graph. Different time periods will give different results."
},
{
"code": null,
"e": 103409,
"s": 102953,
"text": "A tag cloud represents text which are mostly keywords and metadata in a visually appealing form. They are aligned in different angles and represented in different colours and font sizes. It helps in finding out the most prominent terms in the data. The prominence can be decided by one or more factors like frequency of the term, uniquness of the tag or based on some weightage attached to specific terms etc. Below we see the steps to create a Tag Cloud."
},
{
"code": null,
"e": 103651,
"s": 103409,
"text": "In Kibana Home screen, we find the option name Visualize which allows us to create\nvisualization and aggregations from the indices stored in Elasticsearch. We choose to add a new visualization and select Tag Cloud as the option shown below −"
},
{
"code": null,
"e": 103877,
"s": 103651,
"text": "The next screen prompts us for choosing the metrics which will be used in creating the Tag Cloud. Here we choose the count as the type of aggregation metric. Then we choose productname field as the keyword to be used as tags."
},
{
"code": null,
"e": 104027,
"s": 103877,
"text": "The result shown here shows the pie chart after we apply the selection. Please note the\nshades of the colour and their values mentioned in the label."
},
{
"code": null,
"e": 104301,
"s": 104027,
"text": "On moving to the options tab under Tag Cloud we can see various configuration options to change the look as well as the arrangement of data display in the Tag Cloud. In the below example the Tag Cloud appears with tags spread across both horizontal and vertical directions."
},
{
"code": null,
"e": 104617,
"s": 104301,
"text": "Heat map is a type of visualization in which different shades of colour represent different\nareas in the graph. The values may be continuously varying and hence the colour r shades of a colour vary along with the values. They are very useful to represent both the continuously varying data as well as discrete data."
},
{
"code": null,
"e": 104816,
"s": 104617,
"text": "In this chapter we will use the data set named sample_data_flights to build a heatmap chart. In it we consider the variables named origin country and destination country of flights and take a count."
},
{
"code": null,
"e": 105063,
"s": 104816,
"text": "In Kibana Home screen, we find the option name Visualize which allows us to create\nvisualization and aggregations from the indices stored in Elasticsearch. We choose to add a new visualization and select Heat Map as the option shown below &mimus;"
},
{
"code": null,
"e": 105468,
"s": 105063,
"text": "The next screen prompts us for choosing the metrics which will be used in creating the Heat Map Chart. Here we choose the count as the type of aggregation metric. Then for the buckets in Y-Axis, we choose Terms as the aggregation for the field OriginCountry. For the X-Axis, we choose the same aggregation but DestCountry as the field to be used. In both the cases, we choose the size of the bucket as 5."
},
{
"code": null,
"e": 105559,
"s": 105468,
"text": "On running the above shown configuration, we get the heat map chart generated as follows. "
},
{
"code": null,
"e": 105694,
"s": 105559,
"text": "Note − You have to allow the date range as This Year so that the graph gathers data for a year to produce an effective heat map chart."
},
{
"code": null,
"e": 106011,
"s": 105694,
"text": "Canvas application is a part of Kibana which allows us to create dynamic, multi-page and\npixel perfect data displays. Its ability to create infographics and not just charts and metrices is what makes it unique and appealing. In this chapter we will see various features of canvas and how to use the canvas work pads."
},
{
"code": null,
"e": 106197,
"s": 106011,
"text": "Go to the Kibana homepage and select the option as shown in the below diagram. It opens up the list of canvas work pads you have. We choose the ecommerce Revenue tracking for our study."
},
{
"code": null,
"e": 106398,
"s": 106197,
"text": "We clone the [eCommerce] Revenue Tracking workpad to be used in our study. To clone it, we highlight the row with the name of this workpad and then use the clone button as shown in the diagram below −"
},
{
"code": null,
"e": 106553,
"s": 106398,
"text": "As a result of the above clone, we will get a new work pad named as [eCommerce]\nRevenue Tracking – Copy which on opening will show the below infographics."
},
{
"code": null,
"e": 106643,
"s": 106553,
"text": "It describes the total sales and Revenue by category along with nice pictures and charts."
},
{
"code": null,
"e": 106964,
"s": 106643,
"text": "We can change the style and figures in the workpad by using the options available in the\nright hand side tab. Here we aim to change the background colour of the workpad by choosing a different colour as shown in the diagram below. The colour selection comes into effect immediately and we get the result as shown below −"
},
{
"code": null,
"e": 107250,
"s": 106964,
"text": "Kibana can also help in visualizing log data from various sources. Logs are important sources of analysis for infrastructure health, performance needs and security breach analysis etc. Kibana can connect to various logs like web server logs, elasticsearch logs and cloudwatch logs etc."
},
{
"code": null,
"e": 107389,
"s": 107250,
"text": "In Kibana, we can connect to logstash logs for visualization. First we choose the Logs\nbutton from the Kibana home screen as shown below −"
},
{
"code": null,
"e": 107578,
"s": 107389,
"text": "Then we choose the option Change Source Configuration which brings us the option to choose Logstash as a source. The below screen also shows other types of options we have as a log source."
},
{
"code": null,
"e": 107758,
"s": 107578,
"text": "You can stream data for live log tailing or pause streaming to focus on historical log data.\nWhen you are streaming logs, the most recent log appears at the bottom on the console."
},
{
"code": null,
"e": 107821,
"s": 107758,
"text": "For further reference, you can refer to our Logstash tutorial."
},
{
"code": null,
"e": 107854,
"s": 107821,
"text": "\n 14 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 107870,
"s": 107854,
"text": " Manuj Aggarwal"
},
{
"code": null,
"e": 107903,
"s": 107870,
"text": "\n 20 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 107918,
"s": 107903,
"text": " Faizan Tayyab"
},
{
"code": null,
"e": 107925,
"s": 107918,
"text": " Print"
},
{
"code": null,
"e": 107936,
"s": 107925,
"text": " Add Notes"
}
]
|
Node at distance | Practice | GeeksforGeeks | Given a Binary Tree and a positive integer k. The task is to count all distinct nodes that are distance k from a leaf node. A node is at k distance from a leaf if it is present k levels above the leaf and also, is a direct ancestor of this leaf node. If k is more than the height of Binary Tree, then nothing should be counted.
Example 1:
Input:
1
/ \
2 3
/ \ / \
4 5 6 7
\
8
K = 2
Output: 2
Explanation: There are only two unique
nodes that are at a distance of 2 units
from the leaf node. (node 3 for leaf
with value 8 and node 1 for leaves with
values 4, 5 and 7)
Note that node 2
isn't considered for leaf with value
8 because it isn't a direct ancestor
of node 8.
Example 2:
Input:
1
/
3
/
5
/ \
7 8
\
9
K = 4
Output: 1
Explanation: Only one node is there
which is at a distance of 4 units
from the leaf node.(node 1 for leaf
with value 9)
Your Task:
You don't have to read input or print anything. Complete the function printKDistantfromLeaf() that takes root node and k as inputs and returns the number of nodes that are at distance k from a leaf node. Any such node should be counted only once. For example, if a node is at a distance k from 2 or more leaf nodes, then it would add only 1 to our count.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the Tree).
Constraints:
1 <= N <= 105
Note: The Input/Output format and Example are given are used for the system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from the stdin/console. The task is to complete the function specified, and not to write the full code.
+1
kalamarham4 days ago
bool solve(Node* root,int k){ if(root==NULL) return false; if(k==0 and root->left==NULL and root->right==NULL) return true; return solve(root->left,k-1) or solve(root->right,k-1);}void ok(Node* root,int k,int &c){ if(root==NULL) return; ok(root->left,k,c); if(solve(root,k)) { c++; } ok(root->right,k,c);}int printKDistantfromLeaf(Node* root, int k){//Add your code here.int c=0;ok(root,k,c);return c;}
0
aryanm4682 weeks ago
unordered_set<int> u;
int pd(Node* root,int k,int d,int &c){ if(root==NULL) return 0; u.insert(d); if(d>=k && root->left==NULL && root->right==NULL) { if(u.find(d-k)!=u.end()) { c++; auto i=u.find(d-k); u.erase(i); } } pd(root->left,k,d+1,c); pd(root->right,k,d+1,c);}
int printKDistantfromLeaf(Node* root, int k){int c=0;pd(root,k,0,c);return c;}
+1
shirurrohit1 month ago
PYTHON - No hashmap / Set
def helper(root, k):
global count
if root == None:
return False
if root.left == None and root.right == None and k == 0:
return True
return helper(root.left, k-1) or helper(root.right, k-1)
def inorder(root, k):
global count
if root == None:
return
inorder(root.left, k)
if helper(root, k):
count += 1
inorder(root.right, k)
def printKDistantfromLeaf(root, k):
global count
count = 0
inorder(root, k)
return count
0
alamfarhan3892 months ago
bool check(Node *root, int k) { if(root == NULL) return false; if(k == 0 && root->left == NULL && root->right == NULL) return true; return check(root->left, k-1) || check(root->right, k-1);}
int solve(Node *root, int k) { if(root == NULL) return 0; int ans = check(root, k) + solve(root->left, k) + solve(root->right, k); return ans;}int printKDistantfromLeaf(Node* root, int k) { return solve(root, k);}
+1
jai20222 months ago
EASY C++ SOLUTION WITH STEPS:
/*Idea: First traverse through the tree with any traversal technique and then while traversal,check for every node if its distance from leaf node is k or not.We simply move downwards from the root and decrease k for every level. if k becomes 0 at leaf nodewe simply add it in a data structure like set(or any) and return the size of it.As only those elements which are at k distance from leaf are stored in set,so size of set will return the total number of elements.*/
bool check(Node *root,int k){ if(root==NULL) return false; if(root->right==NULL && root->left==NULL){ if(k==0) return true; else return false; } bool left = check(root->left,k-1); bool right = check(root->right,k-1); return left||right;}
void inorder(Node *root,int k,unordered_set<Node*> &s){ if(root==NULL) return; inorder(root->left,k,s); if(check(root,k)){ s.insert(root); } inorder(root->right,k,s);}
int printKDistantfromLeaf(Node* root, int k){unordered_set<Node*> s;inorder(root,k,s);return s.size();}
+2
harendraseervi1234567892 months ago
void serAndPush(Node*root,vector<Node*>v,int k,set<Node*>&s){
if(root==NULL) return;
v.push_back(root);
serAndPush(root->left,v,k,s);
serAndPush(root->right,v,k,s);
if(root->left==NULL && root->right==NULL){
if(k>=v.size()) return;
int t=0;
for(int i=v.size()-1;i>=0;i--){
if(t==k){
s.insert(v[i]);
return;
}
t++;
}
}
}
int printKDistantfromLeaf(Node* root, int k)
{
set<Node*>s;
vector<Node*>v;
serAndPush(root,v,k,s);
return s.size();
}
+1
aloksinghbais023 months ago
C++ solution having time complexity as O(N) and space complexity as O(N) is as follows :-
Execution Time :- 0.2 / 1.1 sec
void preorder(Node *node,Node *p,unordered_map<Node*,Node*> &par,vector<Node*> &leaf){ if(!node) return; par[node] = p; preorder(node->left,node,par,leaf); preorder(node->right,node,par,leaf); if(!node->left && !node->right) leaf.push_back(node);}
int printKDistantfromLeaf(Node* root, int k){vector<Node*> leaf;unordered_map<Node*,Node*> par;preorder(root,nullptr,par,leaf);queue<pair<Node*,int>> q;for(Node *node: leaf) q.push({node,0});unordered_map<Node*,bool> taken;int cnt = 0;while(!q.empty()){ auto p = q.front(); q.pop(); Node *node = p.first; int dis = p.second; if(dis == k && !taken[node]){ cnt++; taken[node] = true; } if(par[node]){ q.push({par[node],dis+1}); }}return (cnt);}
+1
abhixhek053 months ago
//Using inorder traversal
unordered_set<Node*> s;
bool func(Node* root,int k)
{
if(root==NULL){
return false;
}
if(root->left==NULL && root->right==NULL){
if(k==0){
return true;
}
return false;
}
bool left=func(root->left,k-1);
bool right=func(root->right,k-1);
return left||right;
}
void inorder(Node* root,int k){
if(root==NULL){
return;
}
inorder(root->left,k);
if(func(root,k)){
s.insert(root);
}
inorder(root->right,k);
}
int printKDistantfromLeaf(Node* root, int k)
{
s.clear();
inorder(root,k);
return s.size();
}
0
shiva1090
This comment was deleted.
+1
shyamprakash8073 months ago
Simple Python Solution:
Time Taken : 0.3/1.4
from collections import dequedef printKDistantfromLeaf(root, k): q = deque() p = dict() q.append(root) leaf = [] while len(q)>0: curr = q.popleft() if curr.left != None: q.append(curr.left) p[curr.left] = curr if curr.right != None: q.append(curr.right) p[curr.right] = curr if curr.left == curr.right == None: leaf.append(curr) ans = set() for node in leaf: x = Present(node, p, k) if x != None: ans.add(x) return len(ans) def Present(node, p, k): if k == 0: return node if node in p: return Present(p[node], p, k-1) return None
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": 566,
"s": 238,
"text": "Given a Binary Tree and a positive integer k. The task is to count all distinct nodes that are distance k from a leaf node. A node is at k distance from a leaf if it is present k levels above the leaf and also, is a direct ancestor of this leaf node. If k is more than the height of Binary Tree, then nothing should be counted."
},
{
"code": null,
"e": 577,
"s": 566,
"text": "Example 1:"
},
{
"code": null,
"e": 969,
"s": 577,
"text": "Input:\n 1\n / \\\n 2 3\n / \\ / \\\n 4 5 6 7\n \\ \n 8\nK = 2\nOutput: 2\nExplanation: There are only two unique\nnodes that are at a distance of 2 units\nfrom the leaf node. (node 3 for leaf\nwith value 8 and node 1 for leaves with\nvalues 4, 5 and 7)\nNote that node 2\nisn't considered for leaf with value\n8 because it isn't a direct ancestor\nof node 8.\n"
},
{
"code": null,
"e": 980,
"s": 969,
"text": "Example 2:"
},
{
"code": null,
"e": 1216,
"s": 980,
"text": "Input:\n 1\n /\n 3\n /\n 5\n / \\\n 7 8\n \\\n 9\nK = 4\nOutput: 1\nExplanation: Only one node is there\nwhich is at a distance of 4 units\nfrom the leaf node.(node 1 for leaf\nwith value 9) "
},
{
"code": null,
"e": 1582,
"s": 1216,
"text": "Your Task:\nYou don't have to read input or print anything. Complete the function printKDistantfromLeaf() that takes root node and k as inputs and returns the number of nodes that are at distance k from a leaf node. Any such node should be counted only once. For example, if a node is at a distance k from 2 or more leaf nodes, then it would add only 1 to our count."
},
{
"code": null,
"e": 1663,
"s": 1582,
"text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(Height of the Tree)."
},
{
"code": null,
"e": 1690,
"s": 1663,
"text": "Constraints:\n1 <= N <= 105"
},
{
"code": null,
"e": 2013,
"s": 1690,
"text": "Note: The Input/Output format and Example are given are used for the system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from the stdin/console. The task is to complete the function specified, and not to write the full code."
},
{
"code": null,
"e": 2016,
"s": 2013,
"text": "+1"
},
{
"code": null,
"e": 2037,
"s": 2016,
"text": "kalamarham4 days ago"
},
{
"code": null,
"e": 2464,
"s": 2037,
"text": "bool solve(Node* root,int k){ if(root==NULL) return false; if(k==0 and root->left==NULL and root->right==NULL) return true; return solve(root->left,k-1) or solve(root->right,k-1);}void ok(Node* root,int k,int &c){ if(root==NULL) return; ok(root->left,k,c); if(solve(root,k)) { c++; } ok(root->right,k,c);}int printKDistantfromLeaf(Node* root, int k){//Add your code here.int c=0;ok(root,k,c);return c;}"
},
{
"code": null,
"e": 2466,
"s": 2464,
"text": "0"
},
{
"code": null,
"e": 2487,
"s": 2466,
"text": "aryanm4682 weeks ago"
},
{
"code": null,
"e": 2509,
"s": 2487,
"text": "unordered_set<int> u;"
},
{
"code": null,
"e": 2943,
"s": 2509,
"text": "int pd(Node* root,int k,int d,int &c){ if(root==NULL) return 0; u.insert(d); if(d>=k && root->left==NULL && root->right==NULL) { if(u.find(d-k)!=u.end()) { c++; auto i=u.find(d-k); u.erase(i); } } pd(root->left,k,d+1,c); pd(root->right,k,d+1,c);}"
},
{
"code": null,
"e": 3022,
"s": 2943,
"text": "int printKDistantfromLeaf(Node* root, int k){int c=0;pd(root,k,0,c);return c;}"
},
{
"code": null,
"e": 3025,
"s": 3022,
"text": "+1"
},
{
"code": null,
"e": 3048,
"s": 3025,
"text": "shirurrohit1 month ago"
},
{
"code": null,
"e": 3074,
"s": 3048,
"text": "PYTHON - No hashmap / Set"
},
{
"code": null,
"e": 3614,
"s": 3076,
"text": "def helper(root, k):\n global count\n \n if root == None:\n return False\n \n if root.left == None and root.right == None and k == 0:\n return True\n \n return helper(root.left, k-1) or helper(root.right, k-1)\n\ndef inorder(root, k):\n global count\n \n if root == None:\n return\n \n inorder(root.left, k)\n \n if helper(root, k):\n count += 1\n \n inorder(root.right, k)\n\ndef printKDistantfromLeaf(root, k):\n global count\n count = 0\n inorder(root, k)\n return count"
},
{
"code": null,
"e": 3616,
"s": 3614,
"text": "0"
},
{
"code": null,
"e": 3642,
"s": 3616,
"text": "alamfarhan3892 months ago"
},
{
"code": null,
"e": 3842,
"s": 3642,
"text": "bool check(Node *root, int k) { if(root == NULL) return false; if(k == 0 && root->left == NULL && root->right == NULL) return true; return check(root->left, k-1) || check(root->right, k-1);}"
},
{
"code": null,
"e": 4070,
"s": 3842,
"text": "int solve(Node *root, int k) { if(root == NULL) return 0; int ans = check(root, k) + solve(root->left, k) + solve(root->right, k); return ans;}int printKDistantfromLeaf(Node* root, int k) { return solve(root, k);}"
},
{
"code": null,
"e": 4073,
"s": 4070,
"text": "+1"
},
{
"code": null,
"e": 4093,
"s": 4073,
"text": "jai20222 months ago"
},
{
"code": null,
"e": 4123,
"s": 4093,
"text": "EASY C++ SOLUTION WITH STEPS:"
},
{
"code": null,
"e": 4593,
"s": 4123,
"text": "/*Idea: First traverse through the tree with any traversal technique and then while traversal,check for every node if its distance from leaf node is k or not.We simply move downwards from the root and decrease k for every level. if k becomes 0 at leaf nodewe simply add it in a data structure like set(or any) and return the size of it.As only those elements which are at k distance from leaf are stored in set,so size of set will return the total number of elements.*/"
},
{
"code": null,
"e": 4865,
"s": 4597,
"text": "bool check(Node *root,int k){ if(root==NULL) return false; if(root->right==NULL && root->left==NULL){ if(k==0) return true; else return false; } bool left = check(root->left,k-1); bool right = check(root->right,k-1); return left||right;}"
},
{
"code": null,
"e": 5051,
"s": 4867,
"text": "void inorder(Node *root,int k,unordered_set<Node*> &s){ if(root==NULL) return; inorder(root->left,k,s); if(check(root,k)){ s.insert(root); } inorder(root->right,k,s);}"
},
{
"code": null,
"e": 5157,
"s": 5053,
"text": "int printKDistantfromLeaf(Node* root, int k){unordered_set<Node*> s;inorder(root,k,s);return s.size();}"
},
{
"code": null,
"e": 5160,
"s": 5157,
"text": "+2"
},
{
"code": null,
"e": 5196,
"s": 5160,
"text": "harendraseervi1234567892 months ago"
},
{
"code": null,
"e": 5745,
"s": 5196,
"text": "void serAndPush(Node*root,vector<Node*>v,int k,set<Node*>&s){\n if(root==NULL) return;\n v.push_back(root);\n serAndPush(root->left,v,k,s);\n serAndPush(root->right,v,k,s);\n if(root->left==NULL && root->right==NULL){\n if(k>=v.size()) return;\n int t=0;\n for(int i=v.size()-1;i>=0;i--){\n if(t==k){\n s.insert(v[i]);\n return;\n }\n t++;\n }\n }\n}\nint printKDistantfromLeaf(Node* root, int k)\n{\nset<Node*>s;\nvector<Node*>v;\nserAndPush(root,v,k,s);\nreturn s.size();\n\n}"
},
{
"code": null,
"e": 5748,
"s": 5745,
"text": "+1"
},
{
"code": null,
"e": 5776,
"s": 5748,
"text": "aloksinghbais023 months ago"
},
{
"code": null,
"e": 5866,
"s": 5776,
"text": "C++ solution having time complexity as O(N) and space complexity as O(N) is as follows :-"
},
{
"code": null,
"e": 5900,
"s": 5868,
"text": "Execution Time :- 0.2 / 1.1 sec"
},
{
"code": null,
"e": 6160,
"s": 5902,
"text": "void preorder(Node *node,Node *p,unordered_map<Node*,Node*> &par,vector<Node*> &leaf){ if(!node) return; par[node] = p; preorder(node->left,node,par,leaf); preorder(node->right,node,par,leaf); if(!node->left && !node->right) leaf.push_back(node);}"
},
{
"code": null,
"e": 6656,
"s": 6160,
"text": "int printKDistantfromLeaf(Node* root, int k){vector<Node*> leaf;unordered_map<Node*,Node*> par;preorder(root,nullptr,par,leaf);queue<pair<Node*,int>> q;for(Node *node: leaf) q.push({node,0});unordered_map<Node*,bool> taken;int cnt = 0;while(!q.empty()){ auto p = q.front(); q.pop(); Node *node = p.first; int dis = p.second; if(dis == k && !taken[node]){ cnt++; taken[node] = true; } if(par[node]){ q.push({par[node],dis+1}); }}return (cnt);}"
},
{
"code": null,
"e": 6659,
"s": 6656,
"text": "+1"
},
{
"code": null,
"e": 6682,
"s": 6659,
"text": "abhixhek053 months ago"
},
{
"code": null,
"e": 7451,
"s": 6682,
"text": "//Using inorder traversal\n\nunordered_set<Node*> s;\n bool func(Node* root,int k)\n {\n if(root==NULL){\n return false;\n }\n if(root->left==NULL && root->right==NULL){\n if(k==0){\n return true;\n }\n return false;\n }\n bool left=func(root->left,k-1);\n bool right=func(root->right,k-1);\n return left||right;\n }\n void inorder(Node* root,int k){\n if(root==NULL){\n return;\n }\n inorder(root->left,k);\n if(func(root,k)){\n s.insert(root);\n }\n inorder(root->right,k);\n }\n int printKDistantfromLeaf(Node* root, int k)\n {\n s.clear();\n inorder(root,k);\n return s.size();\n }"
},
{
"code": null,
"e": 7453,
"s": 7451,
"text": "0"
},
{
"code": null,
"e": 7463,
"s": 7453,
"text": "shiva1090"
},
{
"code": null,
"e": 7489,
"s": 7463,
"text": "This comment was deleted."
},
{
"code": null,
"e": 7492,
"s": 7489,
"text": "+1"
},
{
"code": null,
"e": 7520,
"s": 7492,
"text": "shyamprakash8073 months ago"
},
{
"code": null,
"e": 7544,
"s": 7520,
"text": "Simple Python Solution:"
},
{
"code": null,
"e": 7565,
"s": 7544,
"text": "Time Taken : 0.3/1.4"
},
{
"code": null,
"e": 8229,
"s": 7567,
"text": "from collections import dequedef printKDistantfromLeaf(root, k): q = deque() p = dict() q.append(root) leaf = [] while len(q)>0: curr = q.popleft() if curr.left != None: q.append(curr.left) p[curr.left] = curr if curr.right != None: q.append(curr.right) p[curr.right] = curr if curr.left == curr.right == None: leaf.append(curr) ans = set() for node in leaf: x = Present(node, p, k) if x != None: ans.add(x) return len(ans) def Present(node, p, k): if k == 0: return node if node in p: return Present(p[node], p, k-1) return None"
},
{
"code": null,
"e": 8375,
"s": 8229,
"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": 8411,
"s": 8375,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 8421,
"s": 8411,
"text": "\nProblem\n"
},
{
"code": null,
"e": 8431,
"s": 8421,
"text": "\nContest\n"
},
{
"code": null,
"e": 8494,
"s": 8431,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 8642,
"s": 8494,
"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": 8850,
"s": 8642,
"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": 8956,
"s": 8850,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
]
|
KnockoutJS - Value Binding | This binding is used to link respective DOM element's value into ViewModel property. Mostly, this is used with elements such as input, select, and textarea. This is similar to text binding, the difference being, in value binding data can be changed by the user and the ViewModel will update it automatically.
Syntax
value: <binding-value>
Parameters
HTML DOM element's value property is set to parameter value. Earlier values will be overwritten.
HTML DOM element's value property is set to parameter value. Earlier values will be overwritten.
If the parameter is an observable value, then the elements value is updated as and when the underlying observable is changed. Element is processed only once if no observable is used.
If the parameter is an observable value, then the elements value is updated as and when the underlying observable is changed. Element is processed only once if no observable is used.
valueUpdate is an extra parameter which can also be supplied for extra features. KO uses additional events to detect extra changes when valueUpdate parameter is used in binding. Following are some common events −
input − ViewModel is updated when the value of input element changes.
keyup − ViewModel is updated when the key is released by the user.
keypress − ViewModel is updated when the key is typed.
afterkeydown − ViewModel keeps on updating as soon as the user starts typing the character.
valueUpdate is an extra parameter which can also be supplied for extra features. KO uses additional events to detect extra changes when valueUpdate parameter is used in binding. Following are some common events −
input − ViewModel is updated when the value of input element changes.
input − ViewModel is updated when the value of input element changes.
keyup − ViewModel is updated when the key is released by the user.
keyup − ViewModel is updated when the key is released by the user.
keypress − ViewModel is updated when the key is typed.
keypress − ViewModel is updated when the key is typed.
afterkeydown − ViewModel keeps on updating as soon as the user starts typing the character.
afterkeydown − ViewModel keeps on updating as soon as the user starts typing the character.
Example
Let us look at the following example which demonstrates the use of value binding.
<!DOCTYPE html>
<head>
<title>KnockoutJS Value Binding</title>
<script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
type = "text/javascript"></script>
</head>
<body>
<p>Enter your name:
<input data-bind = "value: yourName, valueUpdate: 'afterkeydown'" />
</p>
<p>Your name is : <span data-bind = "text: yourName"></span></p>
<script type = "text/javascript">
function ViewModel () {
this.yourName = ko.observable('');
};
var vm = new ViewModel();
ko.applyBindings(vm);
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works −
Save the above code in value-bind.htm file.
Save the above code in value-bind.htm file.
Open this HTML file in a browser.
Open this HTML file in a browser.
The data entered in the textbox is updated immediately due to the use of valueUpdate.
The data entered in the textbox is updated immediately due to the use of valueUpdate.
Enter your name:
Your name is :
If you want the input element to give immediate updates to your ViewModel, then use the textInput binding. It is better than valueUpdate options, taking into consideration the weird behavior of browsers.
KO supports drop-down list (<select> elements) in a special way. The value binding and options binding work together allowing you to read and write values, which are random JavaScript objects and not just String values.
Using this parameter, it is possible to set the model property with value which does not actually exist in the select element. This way one can keep the default option as blank when the user views drop-down for the very first time.
Example
Let us take a look at the following example in which valueAllowUnset option is used.
<!DOCTYPE html>
<head>
<title>KnockoutJS Value Binding - working with drop-down lists</title>
<script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
type = "text/javascript"></script>
</head>
<body>
<p>Select a City:
<select data-bind = " options: cities,
optionsCaption: 'Choose City...',
value: selectedCity,
valueAllowUnset: true"></select>
</p>
<script type = "text/javascript">
function ViewModel() {
this.cities = ko.observableArray(['Washington D.C.', 'Boston', 'Baltimore']);
selectedCity = ko.observable('Newark')
};
var vm = new ViewModel();
ko.applyBindings(vm);
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works −
Save the above code in value-bind-drop-down.htm file.
Save the above code in value-bind-drop-down.htm file.
Open this HTML file in a browser.
Open this HTML file in a browser.
selectedCity is assigned with value which is not present in the list. This makes the drop-down blank for the first time.
selectedCity is assigned with value which is not present in the list. This makes the drop-down blank for the first time.
Select a City:
Choose City...Washington D.C.BostonBaltimore
KO is able to create a two-way binding if you use value to link a form element to an Observable property, so that the changes between them are exchanged among them.
If you use a non-observable property (a plain String or a JavaScript expression), then KO will do the following −
If you refer a simple property on ViewModel, KO will set the form element's initial state to property value. If the form element is changed, then KO will write back the new values to property but it cannot detect any changes in the property, thus making it a one-way binding.
If you refer a simple property on ViewModel, KO will set the form element's initial state to property value. If the form element is changed, then KO will write back the new values to property but it cannot detect any changes in the property, thus making it a one-way binding.
If you refer something which is not simple, such as the result of comparison or a function call then, KO will set the form element's initial state to that value but cannot write any more changes made to the form element by the user. We can call this as one-time value setter.
If you refer something which is not simple, such as the result of comparison or a function call then, KO will set the form element's initial state to that value but cannot write any more changes made to the form element by the user. We can call this as one-time value setter.
Example
Following code snippet shows the use of observable and non-observable properties.
<!-- Two-way binding. Populates textbox; syncs both ways. -->
<p>First value: <input data-bind="value: firstVal" /></p>
<!-- One-way binding. Populates textbox; syncs only from textbox to model. -->
<p>Second value: <input data-bind="value: secondVal" /></p>
<!-- No binding. Populates textbox, but doesn't react to any changes. -->
<p>Third value: <input data-bind="value: secondVal.length > 8" /></p>
<script type = "text/javascript">
function viewModel() {
firstVal = ko.observable("hi there"), // Observable
secondVal = "Wats up!!!" // Not observable
};
</script>
If you include value binding with the checked binding, then the value binding will behave like checkedValue option, which can be used with checked binding. It will control the value used for updating ViewModel.
38 Lectures
2 hours
Skillbakerystudios
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2161,
"s": 1852,
"text": "This binding is used to link respective DOM element's value into ViewModel property. Mostly, this is used with elements such as input, select, and textarea. This is similar to text binding, the difference being, in value binding data can be changed by the user and the ViewModel will update it automatically."
},
{
"code": null,
"e": 2168,
"s": 2161,
"text": "Syntax"
},
{
"code": null,
"e": 2192,
"s": 2168,
"text": "value: <binding-value>\n"
},
{
"code": null,
"e": 2203,
"s": 2192,
"text": "Parameters"
},
{
"code": null,
"e": 2300,
"s": 2203,
"text": "HTML DOM element's value property is set to parameter value. Earlier values will be overwritten."
},
{
"code": null,
"e": 2397,
"s": 2300,
"text": "HTML DOM element's value property is set to parameter value. Earlier values will be overwritten."
},
{
"code": null,
"e": 2580,
"s": 2397,
"text": "If the parameter is an observable value, then the elements value is updated as and when the underlying observable is changed. Element is processed only once if no observable is used."
},
{
"code": null,
"e": 2763,
"s": 2580,
"text": "If the parameter is an observable value, then the elements value is updated as and when the underlying observable is changed. Element is processed only once if no observable is used."
},
{
"code": null,
"e": 3262,
"s": 2763,
"text": "valueUpdate is an extra parameter which can also be supplied for extra features. KO uses additional events to detect extra changes when valueUpdate parameter is used in binding. Following are some common events −\n\ninput − ViewModel is updated when the value of input element changes.\nkeyup − ViewModel is updated when the key is released by the user.\nkeypress − ViewModel is updated when the key is typed.\nafterkeydown − ViewModel keeps on updating as soon as the user starts typing the character.\n"
},
{
"code": null,
"e": 3475,
"s": 3262,
"text": "valueUpdate is an extra parameter which can also be supplied for extra features. KO uses additional events to detect extra changes when valueUpdate parameter is used in binding. Following are some common events −"
},
{
"code": null,
"e": 3545,
"s": 3475,
"text": "input − ViewModel is updated when the value of input element changes."
},
{
"code": null,
"e": 3615,
"s": 3545,
"text": "input − ViewModel is updated when the value of input element changes."
},
{
"code": null,
"e": 3682,
"s": 3615,
"text": "keyup − ViewModel is updated when the key is released by the user."
},
{
"code": null,
"e": 3749,
"s": 3682,
"text": "keyup − ViewModel is updated when the key is released by the user."
},
{
"code": null,
"e": 3804,
"s": 3749,
"text": "keypress − ViewModel is updated when the key is typed."
},
{
"code": null,
"e": 3859,
"s": 3804,
"text": "keypress − ViewModel is updated when the key is typed."
},
{
"code": null,
"e": 3951,
"s": 3859,
"text": "afterkeydown − ViewModel keeps on updating as soon as the user starts typing the character."
},
{
"code": null,
"e": 4043,
"s": 3951,
"text": "afterkeydown − ViewModel keeps on updating as soon as the user starts typing the character."
},
{
"code": null,
"e": 4051,
"s": 4043,
"text": "Example"
},
{
"code": null,
"e": 4133,
"s": 4051,
"text": "Let us look at the following example which demonstrates the use of value binding."
},
{
"code": null,
"e": 4788,
"s": 4133,
"text": "<!DOCTYPE html>\n <head>\n <title>KnockoutJS Value Binding</title>\n <script src = \"https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js\"\n type = \"text/javascript\"></script>\n </head>\n\n <body>\n <p>Enter your name: \n <input data-bind = \"value: yourName, valueUpdate: 'afterkeydown'\" />\n </p>\n \n <p>Your name is : <span data-bind = \"text: yourName\"></span></p>\n\n <script type = \"text/javascript\">\n function ViewModel () {\n this.yourName = ko.observable('');\n };\n\n var vm = new ViewModel();\n ko.applyBindings(vm);\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 4795,
"s": 4788,
"text": "Output"
},
{
"code": null,
"e": 4865,
"s": 4795,
"text": "Let's carry out the following steps to see how the above code works −"
},
{
"code": null,
"e": 4909,
"s": 4865,
"text": "Save the above code in value-bind.htm file."
},
{
"code": null,
"e": 4953,
"s": 4909,
"text": "Save the above code in value-bind.htm file."
},
{
"code": null,
"e": 4987,
"s": 4953,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 5021,
"s": 4987,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 5107,
"s": 5021,
"text": "The data entered in the textbox is updated immediately due to the use of valueUpdate."
},
{
"code": null,
"e": 5193,
"s": 5107,
"text": "The data entered in the textbox is updated immediately due to the use of valueUpdate."
},
{
"code": null,
"e": 5211,
"s": 5193,
"text": "Enter your name: "
},
{
"code": null,
"e": 5229,
"s": 5211,
"text": "Your name is : \n\n"
},
{
"code": null,
"e": 5433,
"s": 5229,
"text": "If you want the input element to give immediate updates to your ViewModel, then use the textInput binding. It is better than valueUpdate options, taking into consideration the weird behavior of browsers."
},
{
"code": null,
"e": 5653,
"s": 5433,
"text": "KO supports drop-down list (<select> elements) in a special way. The value binding and options binding work together allowing you to read and write values, which are random JavaScript objects and not just String values."
},
{
"code": null,
"e": 5885,
"s": 5653,
"text": "Using this parameter, it is possible to set the model property with value which does not actually exist in the select element. This way one can keep the default option as blank when the user views drop-down for the very first time."
},
{
"code": null,
"e": 5893,
"s": 5885,
"text": "Example"
},
{
"code": null,
"e": 5978,
"s": 5893,
"text": "Let us take a look at the following example in which valueAllowUnset option is used."
},
{
"code": null,
"e": 6779,
"s": 5978,
"text": "<!DOCTYPE html>\n <head>\n <title>KnockoutJS Value Binding - working with drop-down lists</title>\n <script src = \"https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js\"\n type = \"text/javascript\"></script>\n </head>\n\n <body>\n <p>Select a City:\n <select data-bind = \" options: cities,\n optionsCaption: 'Choose City...',\n value: selectedCity,\n valueAllowUnset: true\"></select>\n </p>\n\n <script type = \"text/javascript\">\n function ViewModel() {\n this.cities = ko.observableArray(['Washington D.C.', 'Boston', 'Baltimore']);\n selectedCity = ko.observable('Newark')\n };\n \n var vm = new ViewModel();\n ko.applyBindings(vm);\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 6786,
"s": 6779,
"text": "Output"
},
{
"code": null,
"e": 6856,
"s": 6786,
"text": "Let's carry out the following steps to see how the above code works −"
},
{
"code": null,
"e": 6910,
"s": 6856,
"text": "Save the above code in value-bind-drop-down.htm file."
},
{
"code": null,
"e": 6964,
"s": 6910,
"text": "Save the above code in value-bind-drop-down.htm file."
},
{
"code": null,
"e": 6998,
"s": 6964,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 7032,
"s": 6998,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 7153,
"s": 7032,
"text": "selectedCity is assigned with value which is not present in the list. This makes the drop-down blank for the first time."
},
{
"code": null,
"e": 7274,
"s": 7153,
"text": "selectedCity is assigned with value which is not present in the list. This makes the drop-down blank for the first time."
},
{
"code": null,
"e": 7341,
"s": 7274,
"text": "Select a City:\n Choose City...Washington D.C.BostonBaltimore\n"
},
{
"code": null,
"e": 7506,
"s": 7341,
"text": "KO is able to create a two-way binding if you use value to link a form element to an Observable property, so that the changes between them are exchanged among them."
},
{
"code": null,
"e": 7620,
"s": 7506,
"text": "If you use a non-observable property (a plain String or a JavaScript expression), then KO will do the following −"
},
{
"code": null,
"e": 7896,
"s": 7620,
"text": "If you refer a simple property on ViewModel, KO will set the form element's initial state to property value. If the form element is changed, then KO will write back the new values to property but it cannot detect any changes in the property, thus making it a one-way binding."
},
{
"code": null,
"e": 8172,
"s": 7896,
"text": "If you refer a simple property on ViewModel, KO will set the form element's initial state to property value. If the form element is changed, then KO will write back the new values to property but it cannot detect any changes in the property, thus making it a one-way binding."
},
{
"code": null,
"e": 8448,
"s": 8172,
"text": "If you refer something which is not simple, such as the result of comparison or a function call then, KO will set the form element's initial state to that value but cannot write any more changes made to the form element by the user. We can call this as one-time value setter."
},
{
"code": null,
"e": 8724,
"s": 8448,
"text": "If you refer something which is not simple, such as the result of comparison or a function call then, KO will set the form element's initial state to that value but cannot write any more changes made to the form element by the user. We can call this as one-time value setter."
},
{
"code": null,
"e": 8732,
"s": 8724,
"text": "Example"
},
{
"code": null,
"e": 8814,
"s": 8732,
"text": "Following code snippet shows the use of observable and non-observable properties."
},
{
"code": null,
"e": 9426,
"s": 8814,
"text": "<!-- Two-way binding. Populates textbox; syncs both ways. -->\n<p>First value: <input data-bind=\"value: firstVal\" /></p>\n\n<!-- One-way binding. Populates textbox; syncs only from textbox to model. -->\n<p>Second value: <input data-bind=\"value: secondVal\" /></p>\n\n<!-- No binding. Populates textbox, but doesn't react to any changes. -->\n<p>Third value: <input data-bind=\"value: secondVal.length > 8\" /></p>\n\n<script type = \"text/javascript\">\n function viewModel() {\n firstVal = ko.observable(\"hi there\"), // Observable\n secondVal = \"Wats up!!!\" // Not observable\n };\n</script>"
},
{
"code": null,
"e": 9637,
"s": 9426,
"text": "If you include value binding with the checked binding, then the value binding will behave like checkedValue option, which can be used with checked binding. It will control the value used for updating ViewModel."
},
{
"code": null,
"e": 9670,
"s": 9637,
"text": "\n 38 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 9690,
"s": 9670,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 9697,
"s": 9690,
"text": " Print"
},
{
"code": null,
"e": 9708,
"s": 9697,
"text": " Add Notes"
}
]
|
Python - Chart Properties | Python has excellent libraries for data visualization. A combination of Pandas, numpy and matplotlib can help in creating in nearly all types of visualizations charts. In this chapter we will get started with looking at some simple chart and the various properties of the chart.
We use numpy library to create the required numbers to be mapped for creating the chart and the pyplot method in matplotlib to draws the actual chart.
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0,10)
y = x ^ 2
#Simple Plot
plt.plot(x,y)
Its output is as follows −
We can apply labels to the axes as well as a title for the chart using appropriate methods from the library as shown below.
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0,10)
y = x ^ 2
#Labeling the Axes and Title
plt.title("Graph Drawing")
plt.xlabel("Time")
plt.ylabel("Distance")
#Simple Plot
plt.plot(x,y)
Its output is as follows −
The style as well as colour for the line in the chart can be specified using appropriate methods from the library as shown below.
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0,10)
y = x ^ 2
#Labeling the Axes and Title
plt.title("Graph Drawing")
plt.xlabel("Time")
plt.ylabel("Distance")
# Formatting the line colors
plt.plot(x,y,'r')
# Formatting the line type
plt.plot(x,y,'>')
Its output is as follows −
The chart can be saved in different image file formats using appropriate methods from the library as shown below.
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0,10)
y = x ^ 2
#Labeling the Axes and Title
plt.title("Graph Drawing")
plt.xlabel("Time")
plt.ylabel("Distance")
# Formatting the line colors
plt.plot(x,y,'r')
# Formatting the line type
plt.plot(x,y,'>')
# save in pdf formats
plt.savefig('timevsdist.pdf', format='pdf')
The above code creates the pdf file in the default path of the python environment.
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": 2808,
"s": 2529,
"text": "Python has excellent libraries for data visualization. A combination of Pandas, numpy and matplotlib can help in creating in nearly all types of visualizations charts. In this chapter we will get started with looking at some simple chart and the various properties of the chart."
},
{
"code": null,
"e": 2959,
"s": 2808,
"text": "We use numpy library to create the required numbers to be mapped for creating the chart and the pyplot method in matplotlib to draws the actual chart."
},
{
"code": null,
"e": 3072,
"s": 2959,
"text": "import numpy as np \nimport matplotlib.pyplot as plt \n\nx = np.arange(0,10) \ny = x ^ 2 \n#Simple Plot\nplt.plot(x,y)"
},
{
"code": null,
"e": 3099,
"s": 3072,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 3223,
"s": 3099,
"text": "We can apply labels to the axes as well as a title for the chart using appropriate methods from the library as shown below."
},
{
"code": null,
"e": 3437,
"s": 3223,
"text": "import numpy as np \nimport matplotlib.pyplot as plt \n\nx = np.arange(0,10) \ny = x ^ 2 \n#Labeling the Axes and Title\nplt.title(\"Graph Drawing\") \nplt.xlabel(\"Time\") \nplt.ylabel(\"Distance\") \n#Simple Plot\nplt.plot(x,y)"
},
{
"code": null,
"e": 3464,
"s": 3437,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 3594,
"s": 3464,
"text": "The style as well as colour for the line in the chart can be specified using appropriate methods from the library as shown below."
},
{
"code": null,
"e": 3878,
"s": 3594,
"text": "import numpy as np \nimport matplotlib.pyplot as plt \n\nx = np.arange(0,10) \ny = x ^ 2 \n#Labeling the Axes and Title\nplt.title(\"Graph Drawing\") \nplt.xlabel(\"Time\") \nplt.ylabel(\"Distance\") \n\n# Formatting the line colors\nplt.plot(x,y,'r')\n\n# Formatting the line type \nplt.plot(x,y,'>') "
},
{
"code": null,
"e": 3905,
"s": 3878,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 4019,
"s": 3905,
"text": "The chart can be saved in different image file formats using appropriate methods from the library as shown below."
},
{
"code": null,
"e": 4370,
"s": 4019,
"text": "import numpy as np \nimport matplotlib.pyplot as plt \n\nx = np.arange(0,10) \ny = x ^ 2 \n#Labeling the Axes and Title\nplt.title(\"Graph Drawing\") \nplt.xlabel(\"Time\") \nplt.ylabel(\"Distance\") \n\n# Formatting the line colors\nplt.plot(x,y,'r')\n\n# Formatting the line type \nplt.plot(x,y,'>') \n\n# save in pdf formats\nplt.savefig('timevsdist.pdf', format='pdf')"
},
{
"code": null,
"e": 4454,
"s": 4370,
"text": "The above code creates the pdf file in the default path of the python environment. "
},
{
"code": null,
"e": 4491,
"s": 4454,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 4507,
"s": 4491,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4540,
"s": 4507,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 4559,
"s": 4540,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4594,
"s": 4559,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 4616,
"s": 4594,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 4650,
"s": 4616,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 4678,
"s": 4650,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4713,
"s": 4678,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 4727,
"s": 4713,
"text": " Lets Kode It"
},
{
"code": null,
"e": 4760,
"s": 4727,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4777,
"s": 4760,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 4784,
"s": 4777,
"text": " Print"
},
{
"code": null,
"e": 4795,
"s": 4784,
"text": " Add Notes"
}
]
|
A quick guide to color image compression using PCA in python | by Iqbal Hussain | Towards Data Science | If you are a Data Science or Machine Learning enthusiast, you must have come across PCA (Principal Component Analysis) which is a popular unsupervised machine learning algorithm primarily used for dimensionality reduction of large dataset. We can use PCA for dimensionality reduction for images as well.
Let’s think of a case where you are working on an AI-ML project which deals with images. Normally images have a lot of pixels to retain their clarity, but that significantly increases its size and slows down the performance of the system when it has to process multiple images. To overcome this situation we can use the dimensionality reduction technique which comes under Unsupervised Machine Learning. Why don’t we check if PCA comes in handy in this case or not? We will use one picture in this article and reduce its dimensions or in other words compress the image using PCA in python.
At the end of the article, we will compare the resulted picture with the original picture to validate our effort.
I had explained the mathematics behind Principal Component Analysis (PCA) in my earlier article. If you have not gone through it yet, you can click here to go through the same.
We will first split the image into the three channels (Blue, Green, and Red) first and then and perform PCA separately on each dataset representing each channel and will then merge them to reconstruct the compressed image. Hence, if our colored image is of shape (m, n, 3), where (m X n) is the total number of pixels of the image on the three channels (b, g, r).
We can also perform the same thing without splitting into blue, green, and red channels and reshaping the data into (m, n X 3) pixels, but we have found that the explained variance ratio given by the same number of PCA component is better if we use the splitting method as mentioned in the earlier paragraph.
I will use the following photograph for the demonstration.
Let’s import the libraries first:
import numpy as npimport pandas as pdimport matplotlib.pyplot as pltfrom sklearn.decomposition import PCAimport cv2from scipy.stats import statsimport matplotlib.image as mpimg
Now let’s read the image rose.jpg and display it.
img = cv2.cvtColor(cv2.imread('rose.jpg'), cv2.COLOR_BGR2RGB)plt.imshow(img)plt.show()
Output:
Check the shape using the following line:
img.shape
Output:
(485, 485, 3)
Now, I will split the image into 3 channels and display each image:
#Splitting into channelsblue,green,red = cv2.split(img)# Plotting the imagesfig = plt.figure(figsize = (15, 7.2)) fig.add_subplot(131)plt.title("Blue Channel")plt.imshow(blue)fig.add_subplot(132)plt.title("Green Channel")plt.imshow(green)fig.add_subplot(133)plt.title("Red Channel")plt.imshow(red)plt.show()
Output:
Let’s verify the data of the blue channel:
blue_temp_df = pd.DataFrame(data = blue)blue_temp_df
Output:
I will divide all the data of all channels by 255 so that the data is scaled between 0 and 1.
df_blue = blue/255df_green = green/255df_red = red/255
We already have seen that each channel has 485 dimensions, and we will now consider only 50 dimensions for PCA and fit and transform the data and check how much variance is explained after reducing data to 50 dimensions.
pca_b = PCA(n_components=50)pca_b.fit(df_blue)trans_pca_b = pca_b.transform(df_blue)pca_g = PCA(n_components=50)pca_g.fit(df_green)trans_pca_g = pca_g.transform(df_green)pca_r = PCA(n_components=50)pca_r.fit(df_red)trans_pca_r = pca_r.transform(df_red)
We have fitted the data in PCA, let’s check the shape of the transformed image of each channel:
print(trans_pca_b.shape)print(trans_pca_r.shape)print(trans_pca_g.shape)
Output:
(485, 50)(485, 50)(485, 50)
That is as expected. Let’s check the sum of explained variance ratios of the 50 PCA components (i.e. most dominated 50 Eigenvalues) for each channel.
print(f"Blue Channel : {sum(pca_b.explained_variance_ratio_)}")print(f"Green Channel: {sum(pca_g.explained_variance_ratio_)}")print(f"Red Channel : {sum(pca_r.explained_variance_ratio_)}")
Output:
Blue Channel : 0.9946260772755372Green Channel: 0.9918219615668648Red Channel : 0.987736292777275
Wow, that’s superb! because only using 50 components we can keep around 99% of the variance in the data.
Let's plot bar charts to check the explained variance ratio by each Eigenvalues separately for each of the 3 channels:
fig = plt.figure(figsize = (15, 7.2)) fig.add_subplot(131)plt.title("Blue Channel")plt.ylabel('Variation explained')plt.xlabel('Eigen Value')plt.bar(list(range(1,51)),pca_b.explained_variance_ratio_)fig.add_subplot(132)plt.title("Green Channel")plt.ylabel('Variation explained')plt.xlabel('Eigen Value')plt.bar(list(range(1,51)),pca_g.explained_variance_ratio_)fig.add_subplot(133)plt.title("Red Channel")plt.ylabel('Variation explained')plt.xlabel('Eigen Value')plt.bar(list(range(1,51)),pca_r.explained_variance_ratio_)plt.show()
Output:
We have completed our PCA dimensionality reduction. Now we will visualize the image again and for that, we have to reverse transform the data first and then merge the data of all the 3 channels into one. Let’s proceed.
b_arr = pca_b.inverse_transform(trans_pca_b)g_arr = pca_g.inverse_transform(trans_pca_g)r_arr = pca_r.inverse_transform(trans_pca_r)print(b_arr.shape, g_arr.shape, r_arr.shape)
Output:
(485, 485) (485, 485) (485, 485)
We can inverse transform the data to the original shape (although each channel is still separated), but as we know all the images are already compressed.
We will merge all the channels into one and print the final shape:
img_reduced= (cv2.merge((b_arr, g_arr, r_arr)))print(img_reduced.shape)
Output:
(485, 485, 3)
That’s great to see the exact shape of the original image that we had imported at the very beginning. Now we will display both the Images (original and reduced) side by side.
fig = plt.figure(figsize = (10, 7.2)) fig.add_subplot(121)plt.title("Original Image")plt.imshow(img)fig.add_subplot(122)plt.title("Reduced Image")plt.imshow(img_reduced)plt.show()
Output:
It's amazing to see that the compressed image is very similar (at least we can still identify it as a rose) to that of the original one although we have reduced the dimension individually for each channel to only 50 from 485. But, we have achieved our goal. No doubt that now the reduced image will be processed much faster by the computer.
I have explained how we can use PCA to reduce the dimension of a color image by splitting it into 3 channels and then reconstruct it back for visualization.
I hope you have enjoyed reading and learning from the article.
You can download the complete code and also the image I shown here which is on the same directory from my github link mentioned below: | [
{
"code": null,
"e": 475,
"s": 171,
"text": "If you are a Data Science or Machine Learning enthusiast, you must have come across PCA (Principal Component Analysis) which is a popular unsupervised machine learning algorithm primarily used for dimensionality reduction of large dataset. We can use PCA for dimensionality reduction for images as well."
},
{
"code": null,
"e": 1065,
"s": 475,
"text": "Let’s think of a case where you are working on an AI-ML project which deals with images. Normally images have a lot of pixels to retain their clarity, but that significantly increases its size and slows down the performance of the system when it has to process multiple images. To overcome this situation we can use the dimensionality reduction technique which comes under Unsupervised Machine Learning. Why don’t we check if PCA comes in handy in this case or not? We will use one picture in this article and reduce its dimensions or in other words compress the image using PCA in python."
},
{
"code": null,
"e": 1179,
"s": 1065,
"text": "At the end of the article, we will compare the resulted picture with the original picture to validate our effort."
},
{
"code": null,
"e": 1356,
"s": 1179,
"text": "I had explained the mathematics behind Principal Component Analysis (PCA) in my earlier article. If you have not gone through it yet, you can click here to go through the same."
},
{
"code": null,
"e": 1720,
"s": 1356,
"text": "We will first split the image into the three channels (Blue, Green, and Red) first and then and perform PCA separately on each dataset representing each channel and will then merge them to reconstruct the compressed image. Hence, if our colored image is of shape (m, n, 3), where (m X n) is the total number of pixels of the image on the three channels (b, g, r)."
},
{
"code": null,
"e": 2029,
"s": 1720,
"text": "We can also perform the same thing without splitting into blue, green, and red channels and reshaping the data into (m, n X 3) pixels, but we have found that the explained variance ratio given by the same number of PCA component is better if we use the splitting method as mentioned in the earlier paragraph."
},
{
"code": null,
"e": 2088,
"s": 2029,
"text": "I will use the following photograph for the demonstration."
},
{
"code": null,
"e": 2122,
"s": 2088,
"text": "Let’s import the libraries first:"
},
{
"code": null,
"e": 2299,
"s": 2122,
"text": "import numpy as npimport pandas as pdimport matplotlib.pyplot as pltfrom sklearn.decomposition import PCAimport cv2from scipy.stats import statsimport matplotlib.image as mpimg"
},
{
"code": null,
"e": 2349,
"s": 2299,
"text": "Now let’s read the image rose.jpg and display it."
},
{
"code": null,
"e": 2436,
"s": 2349,
"text": "img = cv2.cvtColor(cv2.imread('rose.jpg'), cv2.COLOR_BGR2RGB)plt.imshow(img)plt.show()"
},
{
"code": null,
"e": 2444,
"s": 2436,
"text": "Output:"
},
{
"code": null,
"e": 2486,
"s": 2444,
"text": "Check the shape using the following line:"
},
{
"code": null,
"e": 2496,
"s": 2486,
"text": "img.shape"
},
{
"code": null,
"e": 2504,
"s": 2496,
"text": "Output:"
},
{
"code": null,
"e": 2518,
"s": 2504,
"text": "(485, 485, 3)"
},
{
"code": null,
"e": 2586,
"s": 2518,
"text": "Now, I will split the image into 3 channels and display each image:"
},
{
"code": null,
"e": 2894,
"s": 2586,
"text": "#Splitting into channelsblue,green,red = cv2.split(img)# Plotting the imagesfig = plt.figure(figsize = (15, 7.2)) fig.add_subplot(131)plt.title(\"Blue Channel\")plt.imshow(blue)fig.add_subplot(132)plt.title(\"Green Channel\")plt.imshow(green)fig.add_subplot(133)plt.title(\"Red Channel\")plt.imshow(red)plt.show()"
},
{
"code": null,
"e": 2902,
"s": 2894,
"text": "Output:"
},
{
"code": null,
"e": 2945,
"s": 2902,
"text": "Let’s verify the data of the blue channel:"
},
{
"code": null,
"e": 2998,
"s": 2945,
"text": "blue_temp_df = pd.DataFrame(data = blue)blue_temp_df"
},
{
"code": null,
"e": 3006,
"s": 2998,
"text": "Output:"
},
{
"code": null,
"e": 3100,
"s": 3006,
"text": "I will divide all the data of all channels by 255 so that the data is scaled between 0 and 1."
},
{
"code": null,
"e": 3155,
"s": 3100,
"text": "df_blue = blue/255df_green = green/255df_red = red/255"
},
{
"code": null,
"e": 3376,
"s": 3155,
"text": "We already have seen that each channel has 485 dimensions, and we will now consider only 50 dimensions for PCA and fit and transform the data and check how much variance is explained after reducing data to 50 dimensions."
},
{
"code": null,
"e": 3629,
"s": 3376,
"text": "pca_b = PCA(n_components=50)pca_b.fit(df_blue)trans_pca_b = pca_b.transform(df_blue)pca_g = PCA(n_components=50)pca_g.fit(df_green)trans_pca_g = pca_g.transform(df_green)pca_r = PCA(n_components=50)pca_r.fit(df_red)trans_pca_r = pca_r.transform(df_red)"
},
{
"code": null,
"e": 3725,
"s": 3629,
"text": "We have fitted the data in PCA, let’s check the shape of the transformed image of each channel:"
},
{
"code": null,
"e": 3798,
"s": 3725,
"text": "print(trans_pca_b.shape)print(trans_pca_r.shape)print(trans_pca_g.shape)"
},
{
"code": null,
"e": 3806,
"s": 3798,
"text": "Output:"
},
{
"code": null,
"e": 3834,
"s": 3806,
"text": "(485, 50)(485, 50)(485, 50)"
},
{
"code": null,
"e": 3984,
"s": 3834,
"text": "That is as expected. Let’s check the sum of explained variance ratios of the 50 PCA components (i.e. most dominated 50 Eigenvalues) for each channel."
},
{
"code": null,
"e": 4174,
"s": 3984,
"text": "print(f\"Blue Channel : {sum(pca_b.explained_variance_ratio_)}\")print(f\"Green Channel: {sum(pca_g.explained_variance_ratio_)}\")print(f\"Red Channel : {sum(pca_r.explained_variance_ratio_)}\")"
},
{
"code": null,
"e": 4182,
"s": 4174,
"text": "Output:"
},
{
"code": null,
"e": 4281,
"s": 4182,
"text": "Blue Channel : 0.9946260772755372Green Channel: 0.9918219615668648Red Channel : 0.987736292777275"
},
{
"code": null,
"e": 4386,
"s": 4281,
"text": "Wow, that’s superb! because only using 50 components we can keep around 99% of the variance in the data."
},
{
"code": null,
"e": 4505,
"s": 4386,
"text": "Let's plot bar charts to check the explained variance ratio by each Eigenvalues separately for each of the 3 channels:"
},
{
"code": null,
"e": 5037,
"s": 4505,
"text": "fig = plt.figure(figsize = (15, 7.2)) fig.add_subplot(131)plt.title(\"Blue Channel\")plt.ylabel('Variation explained')plt.xlabel('Eigen Value')plt.bar(list(range(1,51)),pca_b.explained_variance_ratio_)fig.add_subplot(132)plt.title(\"Green Channel\")plt.ylabel('Variation explained')plt.xlabel('Eigen Value')plt.bar(list(range(1,51)),pca_g.explained_variance_ratio_)fig.add_subplot(133)plt.title(\"Red Channel\")plt.ylabel('Variation explained')plt.xlabel('Eigen Value')plt.bar(list(range(1,51)),pca_r.explained_variance_ratio_)plt.show()"
},
{
"code": null,
"e": 5045,
"s": 5037,
"text": "Output:"
},
{
"code": null,
"e": 5264,
"s": 5045,
"text": "We have completed our PCA dimensionality reduction. Now we will visualize the image again and for that, we have to reverse transform the data first and then merge the data of all the 3 channels into one. Let’s proceed."
},
{
"code": null,
"e": 5441,
"s": 5264,
"text": "b_arr = pca_b.inverse_transform(trans_pca_b)g_arr = pca_g.inverse_transform(trans_pca_g)r_arr = pca_r.inverse_transform(trans_pca_r)print(b_arr.shape, g_arr.shape, r_arr.shape)"
},
{
"code": null,
"e": 5449,
"s": 5441,
"text": "Output:"
},
{
"code": null,
"e": 5482,
"s": 5449,
"text": "(485, 485) (485, 485) (485, 485)"
},
{
"code": null,
"e": 5636,
"s": 5482,
"text": "We can inverse transform the data to the original shape (although each channel is still separated), but as we know all the images are already compressed."
},
{
"code": null,
"e": 5703,
"s": 5636,
"text": "We will merge all the channels into one and print the final shape:"
},
{
"code": null,
"e": 5775,
"s": 5703,
"text": "img_reduced= (cv2.merge((b_arr, g_arr, r_arr)))print(img_reduced.shape)"
},
{
"code": null,
"e": 5783,
"s": 5775,
"text": "Output:"
},
{
"code": null,
"e": 5797,
"s": 5783,
"text": "(485, 485, 3)"
},
{
"code": null,
"e": 5972,
"s": 5797,
"text": "That’s great to see the exact shape of the original image that we had imported at the very beginning. Now we will display both the Images (original and reduced) side by side."
},
{
"code": null,
"e": 6152,
"s": 5972,
"text": "fig = plt.figure(figsize = (10, 7.2)) fig.add_subplot(121)plt.title(\"Original Image\")plt.imshow(img)fig.add_subplot(122)plt.title(\"Reduced Image\")plt.imshow(img_reduced)plt.show()"
},
{
"code": null,
"e": 6160,
"s": 6152,
"text": "Output:"
},
{
"code": null,
"e": 6501,
"s": 6160,
"text": "It's amazing to see that the compressed image is very similar (at least we can still identify it as a rose) to that of the original one although we have reduced the dimension individually for each channel to only 50 from 485. But, we have achieved our goal. No doubt that now the reduced image will be processed much faster by the computer."
},
{
"code": null,
"e": 6658,
"s": 6501,
"text": "I have explained how we can use PCA to reduce the dimension of a color image by splitting it into 3 channels and then reconstruct it back for visualization."
},
{
"code": null,
"e": 6721,
"s": 6658,
"text": "I hope you have enjoyed reading and learning from the article."
}
]
|
PyQt5 Input Dialog | Python - GeeksforGeeks | 16 Oct, 2021
PyQt5 provides a class named QInputDialog which is used to take input from the user. In most of the application, there comes a situation where some data is required to be entered by the user and hence input dialog is needed. Input can be of type String or Text, Integer, Double and item.Used methods: These methods return tuple having two elements – User input and Status, whether user clicked “ok”(true) or “cancel”(false) button after providing desired input.
getText(): This is used to take Text value from the user. getInt(): This is used to take integer value from the user. getDouble(): This is used to take Double value from the user. getItem(): This is used to take the selected item from multiple choice by the user.
getText(): This is used to take Text value from the user.
getInt(): This is used to take integer value from the user.
getDouble(): This is used to take Double value from the user.
getItem(): This is used to take the selected item from multiple choice by the user.
Let us create a simple application using QInputDialog where a Main Window will appear having a button “Proceed”. After clicking that button multiple input dialogs will open asking for name, roll, CGPA and learned programming language from a list of languages. Finally, Main Window will give a confirmation message along with the details provided by user.Below is the Code –
Python3
from PyQt5 import QtCore, QtGui, QtWidgetsimport sys class Ui_MainWindow(QtWidgets.QWidget): def setupUi(self, MainWindow): MainWindow.resize(422, 255) self.centralwidget = QtWidgets.QWidget(MainWindow) self.pushButton = QtWidgets.QPushButton(self.centralwidget) self.pushButton.setGeometry(QtCore.QRect(160, 130, 93, 28)) # For displaying confirmation message along with user's info. self.label = QtWidgets.QLabel(self.centralwidget) self.label.setGeometry(QtCore.QRect(170, 40, 201, 111)) # Keeping the text of label empty initially. self.label.setText("") MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow")) self.pushButton.setText(_translate("MainWindow", "Proceed")) self.pushButton.clicked.connect(self.takeinputs) def takeinputs(self): name, done1 = QtWidgets.QInputDialog.getText( self, 'Input Dialog', 'Enter your name:') roll, done2 = QtWidgets.QInputDialog.getInt( self, 'Input Dialog', 'Enter your roll:') cgpa, done3 = QtWidgets.QInputDialog.getDouble( self, 'Input Dialog', 'Enter your CGPA:') langs =['C', 'c++', 'Java', 'Python', 'Javascript'] lang, done4 = QtWidgets.QInputDialog.getItem( self, 'Input Dialog', 'Language you know:', langs) if done1 and done2 and done3 and done4 : # Showing confirmation message along # with information provided by user. self.label.setText('Information stored Successfully\nName: ' +str(name)+'('+str(roll)+')'+'\n'+'CGPA: ' +str(cgpa)+'\nSelected Language: '+str(lang)) # Hide the pushbutton after inputs provided by the use. self.pushButton.hide() if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() ' sys.exit(app.exec_())
Click “Proceed” button.
Give the details.
Confirmation message along with user data.
sooda367
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python | [
{
"code": null,
"e": 24640,
"s": 24612,
"text": "\n16 Oct, 2021"
},
{
"code": null,
"e": 25102,
"s": 24640,
"text": "PyQt5 provides a class named QInputDialog which is used to take input from the user. In most of the application, there comes a situation where some data is required to be entered by the user and hence input dialog is needed. Input can be of type String or Text, Integer, Double and item.Used methods: These methods return tuple having two elements – User input and Status, whether user clicked “ok”(true) or “cancel”(false) button after providing desired input."
},
{
"code": null,
"e": 25371,
"s": 25102,
"text": "getText(): This is used to take Text value from the user. getInt(): This is used to take integer value from the user. getDouble(): This is used to take Double value from the user. getItem(): This is used to take the selected item from multiple choice by the user. "
},
{
"code": null,
"e": 25431,
"s": 25371,
"text": "getText(): This is used to take Text value from the user. "
},
{
"code": null,
"e": 25493,
"s": 25431,
"text": "getInt(): This is used to take integer value from the user. "
},
{
"code": null,
"e": 25557,
"s": 25493,
"text": "getDouble(): This is used to take Double value from the user. "
},
{
"code": null,
"e": 25643,
"s": 25557,
"text": "getItem(): This is used to take the selected item from multiple choice by the user. "
},
{
"code": null,
"e": 26018,
"s": 25643,
"text": "Let us create a simple application using QInputDialog where a Main Window will appear having a button “Proceed”. After clicking that button multiple input dialogs will open asking for name, roll, CGPA and learned programming language from a list of languages. Finally, Main Window will give a confirmation message along with the details provided by user.Below is the Code – "
},
{
"code": null,
"e": 26026,
"s": 26018,
"text": "Python3"
},
{
"code": "from PyQt5 import QtCore, QtGui, QtWidgetsimport sys class Ui_MainWindow(QtWidgets.QWidget): def setupUi(self, MainWindow): MainWindow.resize(422, 255) self.centralwidget = QtWidgets.QWidget(MainWindow) self.pushButton = QtWidgets.QPushButton(self.centralwidget) self.pushButton.setGeometry(QtCore.QRect(160, 130, 93, 28)) # For displaying confirmation message along with user's info. self.label = QtWidgets.QLabel(self.centralwidget) self.label.setGeometry(QtCore.QRect(170, 40, 201, 111)) # Keeping the text of label empty initially. self.label.setText(\"\") MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate(\"MainWindow\", \"MainWindow\")) self.pushButton.setText(_translate(\"MainWindow\", \"Proceed\")) self.pushButton.clicked.connect(self.takeinputs) def takeinputs(self): name, done1 = QtWidgets.QInputDialog.getText( self, 'Input Dialog', 'Enter your name:') roll, done2 = QtWidgets.QInputDialog.getInt( self, 'Input Dialog', 'Enter your roll:') cgpa, done3 = QtWidgets.QInputDialog.getDouble( self, 'Input Dialog', 'Enter your CGPA:') langs =['C', 'c++', 'Java', 'Python', 'Javascript'] lang, done4 = QtWidgets.QInputDialog.getItem( self, 'Input Dialog', 'Language you know:', langs) if done1 and done2 and done3 and done4 : # Showing confirmation message along # with information provided by user. self.label.setText('Information stored Successfully\\nName: ' +str(name)+'('+str(roll)+')'+'\\n'+'CGPA: ' +str(cgpa)+'\\nSelected Language: '+str(lang)) # Hide the pushbutton after inputs provided by the use. self.pushButton.hide() if __name__ == \"__main__\": app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() ' sys.exit(app.exec_())",
"e": 28376,
"s": 26026,
"text": null
},
{
"code": null,
"e": 28402,
"s": 28376,
"text": "Click “Proceed” button. "
},
{
"code": null,
"e": 28421,
"s": 28402,
"text": "Give the details. "
},
{
"code": null,
"e": 28473,
"s": 28429,
"text": "Confirmation message along with user data. "
},
{
"code": null,
"e": 28482,
"s": 28473,
"text": "sooda367"
},
{
"code": null,
"e": 28493,
"s": 28482,
"text": "Python-gui"
},
{
"code": null,
"e": 28505,
"s": 28493,
"text": "Python-PyQt"
},
{
"code": null,
"e": 28512,
"s": 28505,
"text": "Python"
},
{
"code": null,
"e": 28610,
"s": 28512,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28619,
"s": 28610,
"text": "Comments"
},
{
"code": null,
"e": 28632,
"s": 28619,
"text": "Old Comments"
},
{
"code": null,
"e": 28650,
"s": 28632,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28685,
"s": 28650,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28707,
"s": 28685,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28739,
"s": 28707,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28769,
"s": 28739,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28811,
"s": 28769,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28837,
"s": 28811,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28880,
"s": 28837,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 28917,
"s": 28880,
"text": "Create a Pandas DataFrame from Lists"
}
]
|
Download and Install Python 3 Latest Version - GeeksforGeeks | 08 Jan, 2020
How to Download and Install Python 3 Latest Version? In this article, you will get the answer to all your questions related to installing Python on Windows/Linux/macOS. Python was developed by Guido van Rossum in the early 1990s and its latest version is 3.7.4, we can simply call it as Python3.
To understand how to install Python You need to know What Python is and where it is actually installed in your system.
Let’s consider a few points:
Python is a widely-used general-purpose, high-level programming language.
Every Release of Python is open-source. Python releases have also been GPL-compatible.
Any version of Python can be downloaded from Python Software Foundation website at python.org.
Most of the languages, notably Linux provide a package manager through which you can directly install Python on your Operating System
In this Python tutorial of Installation and Setup, you’ll see how to install Python on Windows, macOS, Linux, iOS, and Android.
Here you can choose your OS and see the corresponding tutorial,
Windows
Linux
macOS / Mac OS X
Android
iOS (iPhone / iPad)
Online Interpreters of Python
Since windows don’t come with Python preinstalled, it needs to be installed explicitly. Here we will define step by step tutorial on How to install Python on Windows.
Follow the steps below :
First and foremost step is to open a browser and open https://www.python.org/downloads/windows/
Underneath the Python Releases for Windows find Latest Python 3 Release – Python 3.7.4 (latest stable release as of now is Python 3.7.4).
On this page move to Files and click on Windows x86-64 executable installer for 64-bit or Windows x86 executable installer for 32-bit.
Run the Python Installer from downloads folder
Make sure to mark Add Python 3.7 to PATH otherwise you will have to do it explicitly.It will start installing python on windows.
After installation is complete click on Close.Bingo..!! Python is installed. Now go to windows and type IDLE.This is Python Interpreter. I printed Hello geeks, python is working smoothly.
This is Python Interpreter. I printed Hello geeks, python is working smoothly.
On every linux system including following OS,
Ubuntu
Linux Mint
Debian
openSUSE
CentOS
Fedora
and my favourite one, Arch Linux.You will find Python already installed. You can check it using the following command from the terminal$ python --versionTo check latest version of python 2.x.x :$ python2 --versionTo check latest version of python 3.x.x :$ python3 --versionClearly it won’t be the latest version of python. There can be multiple methods to install python on a linux base system and it all depends on your linux system.For almost every Linux system, the following commands would work definitely.$ sudo add-apt-repository ppa:deadsnakes/ppa
$ sudo apt-get update
$ sudo apt-get install python3.7
Download and install Python Latest Version on LinuxTo install the latest version from source code of Python follow below stepsDownload Python Latest Version from python.orgFirst and foremost step is to open a browser and openhttps://www.python.org/downloads/source/Underneath the Stable Releases find Download Gzipped source tarball (latest stable release as of now is Python 3.7.4).You can do all the above steps in a single command$ wget https://www.python.org/ftp/python/3.7.4/Python-3.7.4.tgzInstall Python 3.7.4 Latest Version on LinuxFor installing Python successfully on Linux, Enter Following command to get the prerequisites and other source files$ sudo apt-get update
$ sudo apt-get upgrade
$ sudo apt-get install -y make build-essential libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev xz-utils tk-dev
Now we are all ready to unpack the file downloaded from the python official website’Move to downloads directory using cd downloads in terminaland then enter following commands$ tar xvf Python-3.6.5.tgz
$ cd Python-3.6.5
$ ./configure --enable-optimizations --with-ensurepip=install
$ make -j 8
$ sudo make altinstallBingo..!! The latest version of Python language is installed on your Linux system. You can confirm it using the below command.python --versionHow to install Python on macOS / Mac OS X ?Like Linux, macOS also comes with Python pre-installed on the system. It might be Python version 2 or some similar outdated version. To update to the latest version, we will use the Homebrew Package manager. It is one of the best and convenient methods to install Python on macOS.To know more about Homebrew Package manager, visit hereDownload and install Homebrew Package ManagerIf you don’t have homebrew installed on your system, follow the steps belowOpen the Terminal Application of macOS from Application -> Utilities. Bash terminal will open where you can enter commandsEnter following command in macOS terminal/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Enter the system password if prompted. This will install the Homebrew package Manager on your OS.After you see a message called “Installation Successful”. You are ready to install python version 3 on your macOS.Install Python Latest Version on macOS / macOS XTo install python simple open Terminal app from Application -> Utilitiesand enter following commandbrew install python3After command processing is complete, Python’s version 3 would be installed on your mac.To verify the installation enter following commands in your Terminal apppythonpip3Bingo..!! Python is installed on your computer. You can explore more about python hereHow to install Python on Android ?Python can run on Android through various apps from play store library.This tutorial will explain how to run python on Android using Pydroid 3 – IDE for Python 3 application.Features :Offline Python 3.7 interpreter: no Internet is required to run Python programs.Pip package manager and a custom repository for prebuilt wheel packages for enhanced scientific libraries, such as numpy, scipy, matplotlib, scikit-learn and jupyter.Tensorflow is now also available.Examples available out-of-the-box for quicker learning.Complete Tkinter support for GUI.Full-featured Terminal Emulator, with a readline support (available in pip).Download Pydroid 3 – IDE for Python 3 app from Play storeTo install Pydroid app go to play store link here – Pydroid 3 – IDE for Python 3After installation is complete, run the app and it will show as installing python.Wait for a minute and it will show the ide. Here you can enter the Python code.Click on the yellow button to run the code.Python is installed successfully. You can check more features of this app hereHow to install Python on iOS (iPhone / iPad)?On iOS platform, Python can be installed using various apps from app store. One of the most popular app is Pythonista. Pythonista is a complete development environment for writing PythonTM scripts on your iPad or iPhone. Lots of examples are included — from games and animations to plotting, image manipulation, custom user interfaces, and automation scripts.You can download and buy Pythonista app from hereSince most of the apps are paid on IOS and it doesn’t allow any interpreters officially. One can run Python from online IDEs and ide.geeksforgeeks.org.Online Interpreters of PythonIn this modern era of digital technologies, one can run Python directly from its browser without explicitly installing Python on OS.Here is a list of famous IDEs for python.GeeksforGeeks IDE – ide.geeksforgeeks.orgPython Fiddle: pythonfiddle.comPython Anywhere: www.pythonanywhere.comOnline gdp compiler – onlinegdb.comFor expensive computations for deep learning libraries like TensorFlow, following IDEs can be usedkaggle – kaggle.comJuPyter/IPython Notebook – jupyter.orgGoogle Colab – colab.research.google.comThese interpreters can run Python codes easily except for complex Django codes or TensorFlow libraries. To run such advanced applications, you need to install Python explicitly.My Personal Notes
arrow_drop_upSave
You will find Python already installed. You can check it using the following command from the terminal
$ python --version
To check latest version of python 2.x.x :
$ python2 --version
To check latest version of python 3.x.x :
$ python3 --version
Clearly it won’t be the latest version of python. There can be multiple methods to install python on a linux base system and it all depends on your linux system.For almost every Linux system, the following commands would work definitely.
$ sudo add-apt-repository ppa:deadsnakes/ppa
$ sudo apt-get update
$ sudo apt-get install python3.7
To install the latest version from source code of Python follow below steps
First and foremost step is to open a browser and openhttps://www.python.org/downloads/source/
Underneath the Stable Releases find Download Gzipped source tarball (latest stable release as of now is Python 3.7.4).You can do all the above steps in a single command$ wget https://www.python.org/ftp/python/3.7.4/Python-3.7.4.tgzInstall Python 3.7.4 Latest Version on LinuxFor installing Python successfully on Linux, Enter Following command to get the prerequisites and other source files$ sudo apt-get update
$ sudo apt-get upgrade
$ sudo apt-get install -y make build-essential libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev xz-utils tk-dev
Now we are all ready to unpack the file downloaded from the python official website’Move to downloads directory using cd downloads in terminaland then enter following commands$ tar xvf Python-3.6.5.tgz
$ cd Python-3.6.5
$ ./configure --enable-optimizations --with-ensurepip=install
$ make -j 8
$ sudo make altinstallBingo..!! The latest version of Python language is installed on your Linux system. You can confirm it using the below command.python --versionHow to install Python on macOS / Mac OS X ?Like Linux, macOS also comes with Python pre-installed on the system. It might be Python version 2 or some similar outdated version. To update to the latest version, we will use the Homebrew Package manager. It is one of the best and convenient methods to install Python on macOS.To know more about Homebrew Package manager, visit here
You can do all the above steps in a single command
$ wget https://www.python.org/ftp/python/3.7.4/Python-3.7.4.tgz
For installing Python successfully on Linux, Enter Following command to get the prerequisites and other source files
$ sudo apt-get update
$ sudo apt-get upgrade
$ sudo apt-get install -y make build-essential libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev xz-utils tk-dev
Now we are all ready to unpack the file downloaded from the python official website’Move to downloads directory using cd downloads in terminaland then enter following commands
$ tar xvf Python-3.6.5.tgz
$ cd Python-3.6.5
$ ./configure --enable-optimizations --with-ensurepip=install
$ make -j 8
$ sudo make altinstall
Bingo..!! The latest version of Python language is installed on your Linux system. You can confirm it using the below command.
python --version
Like Linux, macOS also comes with Python pre-installed on the system. It might be Python version 2 or some similar outdated version. To update to the latest version, we will use the Homebrew Package manager. It is one of the best and convenient methods to install Python on macOS.To know more about Homebrew Package manager, visit here
Download and install Homebrew Package ManagerIf you don’t have homebrew installed on your system, follow the steps belowOpen the Terminal Application of macOS from Application -> Utilities. Bash terminal will open where you can enter commandsEnter following command in macOS terminal/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Enter the system password if prompted. This will install the Homebrew package Manager on your OS.After you see a message called “Installation Successful”. You are ready to install python version 3 on your macOS.
If you don’t have homebrew installed on your system, follow the steps belowOpen the Terminal Application of macOS from Application -> Utilities. Bash terminal will open where you can enter commandsEnter following command in macOS terminal
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Enter the system password if prompted. This will install the Homebrew package Manager on your OS.After you see a message called “Installation Successful”. You are ready to install python version 3 on your macOS.
Install Python Latest Version on macOS / macOS XTo install python simple open Terminal app from Application -> Utilitiesand enter following commandbrew install python3After command processing is complete, Python’s version 3 would be installed on your mac.To verify the installation enter following commands in your Terminal apppythonpip3Bingo..!! Python is installed on your computer. You can explore more about python hereHow to install Python on Android ?Python can run on Android through various apps from play store library.This tutorial will explain how to run python on Android using Pydroid 3 – IDE for Python 3 application.Features :
To install python simple open Terminal app from Application -> Utilitiesand enter following command
brew install python3
After command processing is complete, Python’s version 3 would be installed on your mac.To verify the installation enter following commands in your Terminal app
python
pip3
Bingo..!! Python is installed on your computer. You can explore more about python here
Python can run on Android through various apps from play store library.This tutorial will explain how to run python on Android using Pydroid 3 – IDE for Python 3 application.Features :
Offline Python 3.7 interpreter: no Internet is required to run Python programs.
Pip package manager and a custom repository for prebuilt wheel packages for enhanced scientific libraries, such as numpy, scipy, matplotlib, scikit-learn and jupyter.
Tensorflow is now also available.
Examples available out-of-the-box for quicker learning.
Complete Tkinter support for GUI.
Full-featured Terminal Emulator, with a readline support (available in pip).Download Pydroid 3 – IDE for Python 3 app from Play store
To install Pydroid app go to play store link here – Pydroid 3 – IDE for Python 3
After installation is complete, run the app and it will show as installing python.
Wait for a minute and it will show the ide. Here you can enter the Python code.
Click on the yellow button to run the code.Python is installed successfully. You can check more features of this app hereHow to install Python on iOS (iPhone / iPad)?On iOS platform, Python can be installed using various apps from app store. One of the most popular app is Pythonista. Pythonista is a complete development environment for writing PythonTM scripts on your iPad or iPhone. Lots of examples are included — from games and animations to plotting, image manipulation, custom user interfaces, and automation scripts.You can download and buy Pythonista app from hereSince most of the apps are paid on IOS and it doesn’t allow any interpreters officially. One can run Python from online IDEs and ide.geeksforgeeks.org.Online Interpreters of PythonIn this modern era of digital technologies, one can run Python directly from its browser without explicitly installing Python on OS.Here is a list of famous IDEs for python.GeeksforGeeks IDE – ide.geeksforgeeks.orgPython Fiddle: pythonfiddle.comPython Anywhere: www.pythonanywhere.comOnline gdp compiler – onlinegdb.comFor expensive computations for deep learning libraries like TensorFlow, following IDEs can be usedkaggle – kaggle.comJuPyter/IPython Notebook – jupyter.orgGoogle Colab – colab.research.google.comThese interpreters can run Python codes easily except for complex Django codes or TensorFlow libraries. To run such advanced applications, you need to install Python explicitly.My Personal Notes
arrow_drop_upSave
Python is installed successfully. You can check more features of this app here
On iOS platform, Python can be installed using various apps from app store. One of the most popular app is Pythonista. Pythonista is a complete development environment for writing PythonTM scripts on your iPad or iPhone. Lots of examples are included — from games and animations to plotting, image manipulation, custom user interfaces, and automation scripts.You can download and buy Pythonista app from here
Since most of the apps are paid on IOS and it doesn’t allow any interpreters officially. One can run Python from online IDEs and ide.geeksforgeeks.org.
In this modern era of digital technologies, one can run Python directly from its browser without explicitly installing Python on OS.Here is a list of famous IDEs for python.
GeeksforGeeks IDE – ide.geeksforgeeks.org
Python Fiddle: pythonfiddle.com
Python Anywhere: www.pythonanywhere.com
Online gdp compiler – onlinegdb.com
For expensive computations for deep learning libraries like TensorFlow, following IDEs can be used
kaggle – kaggle.com
JuPyter/IPython Notebook – jupyter.org
Google Colab – colab.research.google.com
These interpreters can run Python codes easily except for complex Django codes or TensorFlow libraries. To run such advanced applications, you need to install Python explicitly.
python-basics
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace() | [
{
"code": null,
"e": 41552,
"s": 41524,
"text": "\n08 Jan, 2020"
},
{
"code": null,
"e": 41848,
"s": 41552,
"text": "How to Download and Install Python 3 Latest Version? In this article, you will get the answer to all your questions related to installing Python on Windows/Linux/macOS. Python was developed by Guido van Rossum in the early 1990s and its latest version is 3.7.4, we can simply call it as Python3."
},
{
"code": null,
"e": 41967,
"s": 41848,
"text": "To understand how to install Python You need to know What Python is and where it is actually installed in your system."
},
{
"code": null,
"e": 41996,
"s": 41967,
"text": "Let’s consider a few points:"
},
{
"code": null,
"e": 42070,
"s": 41996,
"text": "Python is a widely-used general-purpose, high-level programming language."
},
{
"code": null,
"e": 42157,
"s": 42070,
"text": "Every Release of Python is open-source. Python releases have also been GPL-compatible."
},
{
"code": null,
"e": 42252,
"s": 42157,
"text": "Any version of Python can be downloaded from Python Software Foundation website at python.org."
},
{
"code": null,
"e": 42386,
"s": 42252,
"text": "Most of the languages, notably Linux provide a package manager through which you can directly install Python on your Operating System"
},
{
"code": null,
"e": 42514,
"s": 42386,
"text": "In this Python tutorial of Installation and Setup, you’ll see how to install Python on Windows, macOS, Linux, iOS, and Android."
},
{
"code": null,
"e": 42578,
"s": 42514,
"text": "Here you can choose your OS and see the corresponding tutorial,"
},
{
"code": null,
"e": 42586,
"s": 42578,
"text": "Windows"
},
{
"code": null,
"e": 42592,
"s": 42586,
"text": "Linux"
},
{
"code": null,
"e": 42609,
"s": 42592,
"text": "macOS / Mac OS X"
},
{
"code": null,
"e": 42617,
"s": 42609,
"text": "Android"
},
{
"code": null,
"e": 42637,
"s": 42617,
"text": "iOS (iPhone / iPad)"
},
{
"code": null,
"e": 42667,
"s": 42637,
"text": "Online Interpreters of Python"
},
{
"code": null,
"e": 42834,
"s": 42667,
"text": "Since windows don’t come with Python preinstalled, it needs to be installed explicitly. Here we will define step by step tutorial on How to install Python on Windows."
},
{
"code": null,
"e": 42859,
"s": 42834,
"text": "Follow the steps below :"
},
{
"code": null,
"e": 42955,
"s": 42859,
"text": "First and foremost step is to open a browser and open https://www.python.org/downloads/windows/"
},
{
"code": null,
"e": 43093,
"s": 42955,
"text": "Underneath the Python Releases for Windows find Latest Python 3 Release – Python 3.7.4 (latest stable release as of now is Python 3.7.4)."
},
{
"code": null,
"e": 43228,
"s": 43093,
"text": "On this page move to Files and click on Windows x86-64 executable installer for 64-bit or Windows x86 executable installer for 32-bit."
},
{
"code": null,
"e": 43275,
"s": 43228,
"text": "Run the Python Installer from downloads folder"
},
{
"code": null,
"e": 43404,
"s": 43275,
"text": "Make sure to mark Add Python 3.7 to PATH otherwise you will have to do it explicitly.It will start installing python on windows."
},
{
"code": null,
"e": 43592,
"s": 43404,
"text": "After installation is complete click on Close.Bingo..!! Python is installed. Now go to windows and type IDLE.This is Python Interpreter. I printed Hello geeks, python is working smoothly."
},
{
"code": null,
"e": 43671,
"s": 43592,
"text": "This is Python Interpreter. I printed Hello geeks, python is working smoothly."
},
{
"code": null,
"e": 43717,
"s": 43671,
"text": "On every linux system including following OS,"
},
{
"code": null,
"e": 43724,
"s": 43717,
"text": "Ubuntu"
},
{
"code": null,
"e": 43735,
"s": 43724,
"text": "Linux Mint"
},
{
"code": null,
"e": 43742,
"s": 43735,
"text": "Debian"
},
{
"code": null,
"e": 43751,
"s": 43742,
"text": "openSUSE"
},
{
"code": null,
"e": 43758,
"s": 43751,
"text": "CentOS"
},
{
"code": null,
"e": 43765,
"s": 43758,
"text": "Fedora"
},
{
"code": null,
"e": 49543,
"s": 43765,
"text": "and my favourite one, Arch Linux.You will find Python already installed. You can check it using the following command from the terminal$ python --versionTo check latest version of python 2.x.x :$ python2 --versionTo check latest version of python 3.x.x :$ python3 --versionClearly it won’t be the latest version of python. There can be multiple methods to install python on a linux base system and it all depends on your linux system.For almost every Linux system, the following commands would work definitely.$ sudo add-apt-repository ppa:deadsnakes/ppa\n$ sudo apt-get update\n$ sudo apt-get install python3.7\nDownload and install Python Latest Version on LinuxTo install the latest version from source code of Python follow below stepsDownload Python Latest Version from python.orgFirst and foremost step is to open a browser and openhttps://www.python.org/downloads/source/Underneath the Stable Releases find Download Gzipped source tarball (latest stable release as of now is Python 3.7.4).You can do all the above steps in a single command$ wget https://www.python.org/ftp/python/3.7.4/Python-3.7.4.tgzInstall Python 3.7.4 Latest Version on LinuxFor installing Python successfully on Linux, Enter Following command to get the prerequisites and other source files$ sudo apt-get update\n$ sudo apt-get upgrade\n$ sudo apt-get install -y make build-essential libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev xz-utils tk-dev\nNow we are all ready to unpack the file downloaded from the python official website’Move to downloads directory using cd downloads in terminaland then enter following commands$ tar xvf Python-3.6.5.tgz\n$ cd Python-3.6.5\n$ ./configure --enable-optimizations --with-ensurepip=install\n$ make -j 8\n$ sudo make altinstallBingo..!! The latest version of Python language is installed on your Linux system. You can confirm it using the below command.python --versionHow to install Python on macOS / Mac OS X ?Like Linux, macOS also comes with Python pre-installed on the system. It might be Python version 2 or some similar outdated version. To update to the latest version, we will use the Homebrew Package manager. It is one of the best and convenient methods to install Python on macOS.To know more about Homebrew Package manager, visit hereDownload and install Homebrew Package ManagerIf you don’t have homebrew installed on your system, follow the steps belowOpen the Terminal Application of macOS from Application -> Utilities. Bash terminal will open where you can enter commandsEnter following command in macOS terminal/usr/bin/ruby -e \"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)\"\nEnter the system password if prompted. This will install the Homebrew package Manager on your OS.After you see a message called “Installation Successful”. You are ready to install python version 3 on your macOS.Install Python Latest Version on macOS / macOS XTo install python simple open Terminal app from Application -> Utilitiesand enter following commandbrew install python3After command processing is complete, Python’s version 3 would be installed on your mac.To verify the installation enter following commands in your Terminal apppythonpip3Bingo..!! Python is installed on your computer. You can explore more about python hereHow to install Python on Android ?Python can run on Android through various apps from play store library.This tutorial will explain how to run python on Android using Pydroid 3 – IDE for Python 3 application.Features :Offline Python 3.7 interpreter: no Internet is required to run Python programs.Pip package manager and a custom repository for prebuilt wheel packages for enhanced scientific libraries, such as numpy, scipy, matplotlib, scikit-learn and jupyter.Tensorflow is now also available.Examples available out-of-the-box for quicker learning.Complete Tkinter support for GUI.Full-featured Terminal Emulator, with a readline support (available in pip).Download Pydroid 3 – IDE for Python 3 app from Play storeTo install Pydroid app go to play store link here – Pydroid 3 – IDE for Python 3After installation is complete, run the app and it will show as installing python.Wait for a minute and it will show the ide. Here you can enter the Python code.Click on the yellow button to run the code.Python is installed successfully. You can check more features of this app hereHow to install Python on iOS (iPhone / iPad)?On iOS platform, Python can be installed using various apps from app store. One of the most popular app is Pythonista. Pythonista is a complete development environment for writing PythonTM scripts on your iPad or iPhone. Lots of examples are included — from games and animations to plotting, image manipulation, custom user interfaces, and automation scripts.You can download and buy Pythonista app from hereSince most of the apps are paid on IOS and it doesn’t allow any interpreters officially. One can run Python from online IDEs and ide.geeksforgeeks.org.Online Interpreters of PythonIn this modern era of digital technologies, one can run Python directly from its browser without explicitly installing Python on OS.Here is a list of famous IDEs for python.GeeksforGeeks IDE – ide.geeksforgeeks.orgPython Fiddle: pythonfiddle.comPython Anywhere: www.pythonanywhere.comOnline gdp compiler – onlinegdb.comFor expensive computations for deep learning libraries like TensorFlow, following IDEs can be usedkaggle – kaggle.comJuPyter/IPython Notebook – jupyter.orgGoogle Colab – colab.research.google.comThese interpreters can run Python codes easily except for complex Django codes or TensorFlow libraries. To run such advanced applications, you need to install Python explicitly.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 49646,
"s": 49543,
"text": "You will find Python already installed. You can check it using the following command from the terminal"
},
{
"code": null,
"e": 49665,
"s": 49646,
"text": "$ python --version"
},
{
"code": null,
"e": 49707,
"s": 49665,
"text": "To check latest version of python 2.x.x :"
},
{
"code": null,
"e": 49727,
"s": 49707,
"text": "$ python2 --version"
},
{
"code": null,
"e": 49769,
"s": 49727,
"text": "To check latest version of python 3.x.x :"
},
{
"code": null,
"e": 49789,
"s": 49769,
"text": "$ python3 --version"
},
{
"code": null,
"e": 50027,
"s": 49789,
"text": "Clearly it won’t be the latest version of python. There can be multiple methods to install python on a linux base system and it all depends on your linux system.For almost every Linux system, the following commands would work definitely."
},
{
"code": null,
"e": 50128,
"s": 50027,
"text": "$ sudo add-apt-repository ppa:deadsnakes/ppa\n$ sudo apt-get update\n$ sudo apt-get install python3.7\n"
},
{
"code": null,
"e": 50204,
"s": 50128,
"text": "To install the latest version from source code of Python follow below steps"
},
{
"code": null,
"e": 50298,
"s": 50204,
"text": "First and foremost step is to open a browser and openhttps://www.python.org/downloads/source/"
},
{
"code": null,
"e": 51747,
"s": 50298,
"text": "Underneath the Stable Releases find Download Gzipped source tarball (latest stable release as of now is Python 3.7.4).You can do all the above steps in a single command$ wget https://www.python.org/ftp/python/3.7.4/Python-3.7.4.tgzInstall Python 3.7.4 Latest Version on LinuxFor installing Python successfully on Linux, Enter Following command to get the prerequisites and other source files$ sudo apt-get update\n$ sudo apt-get upgrade\n$ sudo apt-get install -y make build-essential libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev xz-utils tk-dev\nNow we are all ready to unpack the file downloaded from the python official website’Move to downloads directory using cd downloads in terminaland then enter following commands$ tar xvf Python-3.6.5.tgz\n$ cd Python-3.6.5\n$ ./configure --enable-optimizations --with-ensurepip=install\n$ make -j 8\n$ sudo make altinstallBingo..!! The latest version of Python language is installed on your Linux system. You can confirm it using the below command.python --versionHow to install Python on macOS / Mac OS X ?Like Linux, macOS also comes with Python pre-installed on the system. It might be Python version 2 or some similar outdated version. To update to the latest version, we will use the Homebrew Package manager. It is one of the best and convenient methods to install Python on macOS.To know more about Homebrew Package manager, visit here"
},
{
"code": null,
"e": 51798,
"s": 51747,
"text": "You can do all the above steps in a single command"
},
{
"code": null,
"e": 51862,
"s": 51798,
"text": "$ wget https://www.python.org/ftp/python/3.7.4/Python-3.7.4.tgz"
},
{
"code": null,
"e": 51979,
"s": 51862,
"text": "For installing Python successfully on Linux, Enter Following command to get the prerequisites and other source files"
},
{
"code": null,
"e": 52201,
"s": 51979,
"text": "$ sudo apt-get update\n$ sudo apt-get upgrade\n$ sudo apt-get install -y make build-essential libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev xz-utils tk-dev\n"
},
{
"code": null,
"e": 52377,
"s": 52201,
"text": "Now we are all ready to unpack the file downloaded from the python official website’Move to downloads directory using cd downloads in terminaland then enter following commands"
},
{
"code": null,
"e": 52519,
"s": 52377,
"text": "$ tar xvf Python-3.6.5.tgz\n$ cd Python-3.6.5\n$ ./configure --enable-optimizations --with-ensurepip=install\n$ make -j 8\n$ sudo make altinstall"
},
{
"code": null,
"e": 52646,
"s": 52519,
"text": "Bingo..!! The latest version of Python language is installed on your Linux system. You can confirm it using the below command."
},
{
"code": null,
"e": 52663,
"s": 52646,
"text": "python --version"
},
{
"code": null,
"e": 52999,
"s": 52663,
"text": "Like Linux, macOS also comes with Python pre-installed on the system. It might be Python version 2 or some similar outdated version. To update to the latest version, we will use the Homebrew Package manager. It is one of the best and convenient methods to install Python on macOS.To know more about Homebrew Package manager, visit here"
},
{
"code": null,
"e": 53593,
"s": 52999,
"text": "Download and install Homebrew Package ManagerIf you don’t have homebrew installed on your system, follow the steps belowOpen the Terminal Application of macOS from Application -> Utilities. Bash terminal will open where you can enter commandsEnter following command in macOS terminal/usr/bin/ruby -e \"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)\"\nEnter the system password if prompted. This will install the Homebrew package Manager on your OS.After you see a message called “Installation Successful”. You are ready to install python version 3 on your macOS."
},
{
"code": null,
"e": 53832,
"s": 53593,
"text": "If you don’t have homebrew installed on your system, follow the steps belowOpen the Terminal Application of macOS from Application -> Utilities. Bash terminal will open where you can enter commandsEnter following command in macOS terminal"
},
{
"code": null,
"e": 53932,
"s": 53832,
"text": "/usr/bin/ruby -e \"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)\"\n"
},
{
"code": null,
"e": 54144,
"s": 53932,
"text": "Enter the system password if prompted. This will install the Homebrew package Manager on your OS.After you see a message called “Installation Successful”. You are ready to install python version 3 on your macOS."
},
{
"code": null,
"e": 54786,
"s": 54144,
"text": "Install Python Latest Version on macOS / macOS XTo install python simple open Terminal app from Application -> Utilitiesand enter following commandbrew install python3After command processing is complete, Python’s version 3 would be installed on your mac.To verify the installation enter following commands in your Terminal apppythonpip3Bingo..!! Python is installed on your computer. You can explore more about python hereHow to install Python on Android ?Python can run on Android through various apps from play store library.This tutorial will explain how to run python on Android using Pydroid 3 – IDE for Python 3 application.Features :"
},
{
"code": null,
"e": 54886,
"s": 54786,
"text": "To install python simple open Terminal app from Application -> Utilitiesand enter following command"
},
{
"code": null,
"e": 54907,
"s": 54886,
"text": "brew install python3"
},
{
"code": null,
"e": 55068,
"s": 54907,
"text": "After command processing is complete, Python’s version 3 would be installed on your mac.To verify the installation enter following commands in your Terminal app"
},
{
"code": null,
"e": 55075,
"s": 55068,
"text": "python"
},
{
"code": null,
"e": 55080,
"s": 55075,
"text": "pip3"
},
{
"code": null,
"e": 55167,
"s": 55080,
"text": "Bingo..!! Python is installed on your computer. You can explore more about python here"
},
{
"code": null,
"e": 55352,
"s": 55167,
"text": "Python can run on Android through various apps from play store library.This tutorial will explain how to run python on Android using Pydroid 3 – IDE for Python 3 application.Features :"
},
{
"code": null,
"e": 55432,
"s": 55352,
"text": "Offline Python 3.7 interpreter: no Internet is required to run Python programs."
},
{
"code": null,
"e": 55599,
"s": 55432,
"text": "Pip package manager and a custom repository for prebuilt wheel packages for enhanced scientific libraries, such as numpy, scipy, matplotlib, scikit-learn and jupyter."
},
{
"code": null,
"e": 55633,
"s": 55599,
"text": "Tensorflow is now also available."
},
{
"code": null,
"e": 55689,
"s": 55633,
"text": "Examples available out-of-the-box for quicker learning."
},
{
"code": null,
"e": 55723,
"s": 55689,
"text": "Complete Tkinter support for GUI."
},
{
"code": null,
"e": 55857,
"s": 55723,
"text": "Full-featured Terminal Emulator, with a readline support (available in pip).Download Pydroid 3 – IDE for Python 3 app from Play store"
},
{
"code": null,
"e": 55938,
"s": 55857,
"text": "To install Pydroid app go to play store link here – Pydroid 3 – IDE for Python 3"
},
{
"code": null,
"e": 56021,
"s": 55938,
"text": "After installation is complete, run the app and it will show as installing python."
},
{
"code": null,
"e": 56101,
"s": 56021,
"text": "Wait for a minute and it will show the ide. Here you can enter the Python code."
},
{
"code": null,
"e": 57582,
"s": 56101,
"text": "Click on the yellow button to run the code.Python is installed successfully. You can check more features of this app hereHow to install Python on iOS (iPhone / iPad)?On iOS platform, Python can be installed using various apps from app store. One of the most popular app is Pythonista. Pythonista is a complete development environment for writing PythonTM scripts on your iPad or iPhone. Lots of examples are included — from games and animations to plotting, image manipulation, custom user interfaces, and automation scripts.You can download and buy Pythonista app from hereSince most of the apps are paid on IOS and it doesn’t allow any interpreters officially. One can run Python from online IDEs and ide.geeksforgeeks.org.Online Interpreters of PythonIn this modern era of digital technologies, one can run Python directly from its browser without explicitly installing Python on OS.Here is a list of famous IDEs for python.GeeksforGeeks IDE – ide.geeksforgeeks.orgPython Fiddle: pythonfiddle.comPython Anywhere: www.pythonanywhere.comOnline gdp compiler – onlinegdb.comFor expensive computations for deep learning libraries like TensorFlow, following IDEs can be usedkaggle – kaggle.comJuPyter/IPython Notebook – jupyter.orgGoogle Colab – colab.research.google.comThese interpreters can run Python codes easily except for complex Django codes or TensorFlow libraries. To run such advanced applications, you need to install Python explicitly.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 57661,
"s": 57582,
"text": "Python is installed successfully. You can check more features of this app here"
},
{
"code": null,
"e": 58070,
"s": 57661,
"text": "On iOS platform, Python can be installed using various apps from app store. One of the most popular app is Pythonista. Pythonista is a complete development environment for writing PythonTM scripts on your iPad or iPhone. Lots of examples are included — from games and animations to plotting, image manipulation, custom user interfaces, and automation scripts.You can download and buy Pythonista app from here"
},
{
"code": null,
"e": 58222,
"s": 58070,
"text": "Since most of the apps are paid on IOS and it doesn’t allow any interpreters officially. One can run Python from online IDEs and ide.geeksforgeeks.org."
},
{
"code": null,
"e": 58396,
"s": 58222,
"text": "In this modern era of digital technologies, one can run Python directly from its browser without explicitly installing Python on OS.Here is a list of famous IDEs for python."
},
{
"code": null,
"e": 58438,
"s": 58396,
"text": "GeeksforGeeks IDE – ide.geeksforgeeks.org"
},
{
"code": null,
"e": 58470,
"s": 58438,
"text": "Python Fiddle: pythonfiddle.com"
},
{
"code": null,
"e": 58510,
"s": 58470,
"text": "Python Anywhere: www.pythonanywhere.com"
},
{
"code": null,
"e": 58546,
"s": 58510,
"text": "Online gdp compiler – onlinegdb.com"
},
{
"code": null,
"e": 58645,
"s": 58546,
"text": "For expensive computations for deep learning libraries like TensorFlow, following IDEs can be used"
},
{
"code": null,
"e": 58665,
"s": 58645,
"text": "kaggle – kaggle.com"
},
{
"code": null,
"e": 58704,
"s": 58665,
"text": "JuPyter/IPython Notebook – jupyter.org"
},
{
"code": null,
"e": 58745,
"s": 58704,
"text": "Google Colab – colab.research.google.com"
},
{
"code": null,
"e": 58923,
"s": 58745,
"text": "These interpreters can run Python codes easily except for complex Django codes or TensorFlow libraries. To run such advanced applications, you need to install Python explicitly."
},
{
"code": null,
"e": 58937,
"s": 58923,
"text": "python-basics"
},
{
"code": null,
"e": 58944,
"s": 58937,
"text": "Python"
},
{
"code": null,
"e": 59042,
"s": 58944,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 59070,
"s": 59042,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 59120,
"s": 59070,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 59142,
"s": 59120,
"text": "Python map() function"
},
{
"code": null,
"e": 59186,
"s": 59142,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 59221,
"s": 59186,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 59243,
"s": 59221,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 59275,
"s": 59243,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 59305,
"s": 59275,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 59347,
"s": 59305,
"text": "Different ways to create Pandas Dataframe"
}
]
|
Prime factors in java | Factors are the numbers we multiply to get another number.
factors of 14 are 2 and 7, because 2 × 7 = 14.
Some numbers can be factored in more than one way.
16 can be factored as 1 × 16, 2 × 8, or 4 × 4.
A number that can only be factored as 1 times itself is called a prime number.
The first few primes are 2, 3, 5, 7, 11, and 13.
The list of all the prime-number factors of a given number is the prime factors of a number. The factorization of a number into its prime factors and expression of the number as a product of its prime factors is known as the prime factorization of that number. The prime factorization of a number includes ONLY the prime factors, not any products of those prime factors.
import java.util.Scanner;
public class PrimeFactors {
public static void main(String args[]){
int number;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number ::");
number = sc.nextInt();
for(int i = 2; i< number; i++) {
while(number%i == 0) {
System.out.println(i+" ");
number = number/i;
}
}
if(number >2) {
System.out.println(number);
}
}
}
Enter a number
24
2
2
2
3 | [
{
"code": null,
"e": 1121,
"s": 1062,
"text": "Factors are the numbers we multiply to get another number."
},
{
"code": null,
"e": 1168,
"s": 1121,
"text": "factors of 14 are 2 and 7, because 2 × 7 = 14."
},
{
"code": null,
"e": 1219,
"s": 1168,
"text": "Some numbers can be factored in more than one way."
},
{
"code": null,
"e": 1266,
"s": 1219,
"text": "16 can be factored as 1 × 16, 2 × 8, or 4 × 4."
},
{
"code": null,
"e": 1345,
"s": 1266,
"text": "A number that can only be factored as 1 times itself is called a prime number."
},
{
"code": null,
"e": 1394,
"s": 1345,
"text": "The first few primes are 2, 3, 5, 7, 11, and 13."
},
{
"code": null,
"e": 1765,
"s": 1394,
"text": "The list of all the prime-number factors of a given number is the prime factors of a number. The factorization of a number into its prime factors and expression of the number as a product of its prime factors is known as the prime factorization of that number. The prime factorization of a number includes ONLY the prime factors, not any products of those prime factors."
},
{
"code": null,
"e": 2240,
"s": 1765,
"text": "import java.util.Scanner;\n\npublic class PrimeFactors {\n public static void main(String args[]){\n int number;\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter a number ::\");\n number = sc.nextInt();\n \n for(int i = 2; i< number; i++) {\n while(number%i == 0) {\n System.out.println(i+\" \");\n number = number/i;\n }\n }\n if(number >2) {\n System.out.println(number);\n }\n }\n}"
},
{
"code": null,
"e": 2266,
"s": 2240,
"text": "Enter a number\n24\n2\n2\n2\n3"
}
]
|
PHP | String Functions - GeeksforGeeks | 09 Mar, 2018
We have learned about some basic string manipulation functions available in PHP in the article PHP | String . In this article, we will learn about few string functions that are used to change cases of characters of strings in PHP. Below are some most commonly used case manipulation functions for strings in PHP:
strtoupper() function in PHP
This function takes a string as argument and returns the string with all characters in Upper Case.
Syntax:
strtoupper($string)
Program to illustrate the use of strtoupper() function:
<?php# PHP code to convert to Upper Casefunction toUpper($string){ return(strtoupper($string));} // Driver Code$string="GeeksforGeeks"; echo (toUpper($string));?>
Output:
GEEKSFORGEEKS
strtolower() function in PHP
This function takes a string as argument ans returns the string with all of the characters in Lower Case.
Syntax:
strtolower($string)
Program to illustrate the use of strtolower() function:
<?php# PHP code to convert to Lower Casefunction toLower($string){ return(strtolower($string));} // Driver Code$string="GeeksforGeeks"; echo (toLower($string));?>
Output:
geeksforgeeks
ucfirst() function in PHP
This function takes a string as argument and returns the string with the first character in Upper Case and all other cases of the characters remains unchanged.
Syntax:
ucfirst($string)
Program to illustrate the use of ucfirst() function:
<?php# PHP code to convert the first letter to Upper Casefunction firstUpper($string){ return(ucfirst($string));} // Driver Code$string="welcome to GeeksforGeeks"; echo (firstUpper($string));?>
Output:
Welcome to GeeksforGeeks
lcfirst() function in PHP
This function takes a string as argument and returns the string with the first character in Lower Case and all other characters remains unchanged.
Syntax:
lcfirst($string)
Program to illustrate the use of lcfirst() function:
<?php# PHP code to convert the first letter to Lower Casefunction firstLower($string){ return(lcfirst($string));} // Driver Code$string="WELCOME to GeeksforGeeks"; echo (firstLower($string));?>
Output:
wELCOME to GeeksforGeeks
ucwords() function in PHP
This function takes a string as argument and returns the string with the first character of every word in Upper Case and all other characters remains unchanged.
Syntax:
ucwords($string)
Program to illustrate the use of ucwords() function:
<?php# PHP code to convert the first letter # of each word to Upper Casefunction firstUpper($string){ return(ucwords($string));} // Driver Code$string="welcome to GeeksforGeeks"; echo (firstUpper($string));?>
Output:
Welcome To GeeksforGeeks
strlen() function in PHP
This function takes a string as argument and returns and integer value representing the length of string. It calculates the length of the string including all the whitespaces and special characters.
Syntax:
strlen($string)
Program to illustrate the use of strlen() function:
<?php# PHP code to get the length of any stringfunction Length($string){ return(strlen($string));} // Driver Code$string="welcome to GeeksforGeeks"; echo (Length($string));?>
Output:
24
C-String-Question
Functions
PHP-function
PHP
Web Technologies
Functions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
How to receive JSON POST with PHP ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 23983,
"s": 23955,
"text": "\n09 Mar, 2018"
},
{
"code": null,
"e": 24296,
"s": 23983,
"text": "We have learned about some basic string manipulation functions available in PHP in the article PHP | String . In this article, we will learn about few string functions that are used to change cases of characters of strings in PHP. Below are some most commonly used case manipulation functions for strings in PHP:"
},
{
"code": null,
"e": 24325,
"s": 24296,
"text": "strtoupper() function in PHP"
},
{
"code": null,
"e": 24424,
"s": 24325,
"text": "This function takes a string as argument and returns the string with all characters in Upper Case."
},
{
"code": null,
"e": 24432,
"s": 24424,
"text": "Syntax:"
},
{
"code": null,
"e": 24452,
"s": 24432,
"text": "strtoupper($string)"
},
{
"code": null,
"e": 24508,
"s": 24452,
"text": "Program to illustrate the use of strtoupper() function:"
},
{
"code": "<?php# PHP code to convert to Upper Casefunction toUpper($string){ return(strtoupper($string));} // Driver Code$string=\"GeeksforGeeks\"; echo (toUpper($string));?> ",
"e": 24678,
"s": 24508,
"text": null
},
{
"code": null,
"e": 24686,
"s": 24678,
"text": "Output:"
},
{
"code": null,
"e": 24700,
"s": 24686,
"text": "GEEKSFORGEEKS"
},
{
"code": null,
"e": 24729,
"s": 24700,
"text": "strtolower() function in PHP"
},
{
"code": null,
"e": 24835,
"s": 24729,
"text": "This function takes a string as argument ans returns the string with all of the characters in Lower Case."
},
{
"code": null,
"e": 24843,
"s": 24835,
"text": "Syntax:"
},
{
"code": null,
"e": 24863,
"s": 24843,
"text": "strtolower($string)"
},
{
"code": null,
"e": 24919,
"s": 24863,
"text": "Program to illustrate the use of strtolower() function:"
},
{
"code": "<?php# PHP code to convert to Lower Casefunction toLower($string){ return(strtolower($string));} // Driver Code$string=\"GeeksforGeeks\"; echo (toLower($string));?> ",
"e": 25089,
"s": 24919,
"text": null
},
{
"code": null,
"e": 25097,
"s": 25089,
"text": "Output:"
},
{
"code": null,
"e": 25111,
"s": 25097,
"text": "geeksforgeeks"
},
{
"code": null,
"e": 25137,
"s": 25111,
"text": "ucfirst() function in PHP"
},
{
"code": null,
"e": 25297,
"s": 25137,
"text": "This function takes a string as argument and returns the string with the first character in Upper Case and all other cases of the characters remains unchanged."
},
{
"code": null,
"e": 25305,
"s": 25297,
"text": "Syntax:"
},
{
"code": null,
"e": 25322,
"s": 25305,
"text": "ucfirst($string)"
},
{
"code": null,
"e": 25375,
"s": 25322,
"text": "Program to illustrate the use of ucfirst() function:"
},
{
"code": "<?php# PHP code to convert the first letter to Upper Casefunction firstUpper($string){ return(ucfirst($string));} // Driver Code$string=\"welcome to GeeksforGeeks\"; echo (firstUpper($string));?>",
"e": 25574,
"s": 25375,
"text": null
},
{
"code": null,
"e": 25582,
"s": 25574,
"text": "Output:"
},
{
"code": null,
"e": 25607,
"s": 25582,
"text": "Welcome to GeeksforGeeks"
},
{
"code": null,
"e": 25633,
"s": 25607,
"text": "lcfirst() function in PHP"
},
{
"code": null,
"e": 25780,
"s": 25633,
"text": "This function takes a string as argument and returns the string with the first character in Lower Case and all other characters remains unchanged."
},
{
"code": null,
"e": 25788,
"s": 25780,
"text": "Syntax:"
},
{
"code": null,
"e": 25805,
"s": 25788,
"text": "lcfirst($string)"
},
{
"code": null,
"e": 25858,
"s": 25805,
"text": "Program to illustrate the use of lcfirst() function:"
},
{
"code": "<?php# PHP code to convert the first letter to Lower Casefunction firstLower($string){ return(lcfirst($string));} // Driver Code$string=\"WELCOME to GeeksforGeeks\"; echo (firstLower($string));?>",
"e": 26057,
"s": 25858,
"text": null
},
{
"code": null,
"e": 26065,
"s": 26057,
"text": "Output:"
},
{
"code": null,
"e": 26090,
"s": 26065,
"text": "wELCOME to GeeksforGeeks"
},
{
"code": null,
"e": 26116,
"s": 26090,
"text": "ucwords() function in PHP"
},
{
"code": null,
"e": 26277,
"s": 26116,
"text": "This function takes a string as argument and returns the string with the first character of every word in Upper Case and all other characters remains unchanged."
},
{
"code": null,
"e": 26285,
"s": 26277,
"text": "Syntax:"
},
{
"code": null,
"e": 26302,
"s": 26285,
"text": "ucwords($string)"
},
{
"code": null,
"e": 26355,
"s": 26302,
"text": "Program to illustrate the use of ucwords() function:"
},
{
"code": "<?php# PHP code to convert the first letter # of each word to Upper Casefunction firstUpper($string){ return(ucwords($string));} // Driver Code$string=\"welcome to GeeksforGeeks\"; echo (firstUpper($string));?>",
"e": 26569,
"s": 26355,
"text": null
},
{
"code": null,
"e": 26577,
"s": 26569,
"text": "Output:"
},
{
"code": null,
"e": 26602,
"s": 26577,
"text": "Welcome To GeeksforGeeks"
},
{
"code": null,
"e": 26627,
"s": 26602,
"text": "strlen() function in PHP"
},
{
"code": null,
"e": 26826,
"s": 26627,
"text": "This function takes a string as argument and returns and integer value representing the length of string. It calculates the length of the string including all the whitespaces and special characters."
},
{
"code": null,
"e": 26834,
"s": 26826,
"text": "Syntax:"
},
{
"code": null,
"e": 26850,
"s": 26834,
"text": "strlen($string)"
},
{
"code": null,
"e": 26902,
"s": 26850,
"text": "Program to illustrate the use of strlen() function:"
},
{
"code": "<?php# PHP code to get the length of any stringfunction Length($string){ return(strlen($string));} // Driver Code$string=\"welcome to GeeksforGeeks\"; echo (Length($string));?>",
"e": 27082,
"s": 26902,
"text": null
},
{
"code": null,
"e": 27090,
"s": 27082,
"text": "Output:"
},
{
"code": null,
"e": 27093,
"s": 27090,
"text": "24"
},
{
"code": null,
"e": 27111,
"s": 27093,
"text": "C-String-Question"
},
{
"code": null,
"e": 27121,
"s": 27111,
"text": "Functions"
},
{
"code": null,
"e": 27134,
"s": 27121,
"text": "PHP-function"
},
{
"code": null,
"e": 27138,
"s": 27134,
"text": "PHP"
},
{
"code": null,
"e": 27155,
"s": 27138,
"text": "Web Technologies"
},
{
"code": null,
"e": 27165,
"s": 27155,
"text": "Functions"
},
{
"code": null,
"e": 27169,
"s": 27165,
"text": "PHP"
},
{
"code": null,
"e": 27267,
"s": 27169,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27276,
"s": 27267,
"text": "Comments"
},
{
"code": null,
"e": 27289,
"s": 27276,
"text": "Old Comments"
},
{
"code": null,
"e": 27339,
"s": 27289,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 27379,
"s": 27339,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 27440,
"s": 27379,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 27490,
"s": 27440,
"text": "How to check whether an array is empty using PHP?"
},
{
"code": null,
"e": 27526,
"s": 27490,
"text": "How to receive JSON POST with PHP ?"
},
{
"code": null,
"e": 27582,
"s": 27526,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 27615,
"s": 27582,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27677,
"s": 27615,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 27720,
"s": 27677,
"text": "How to fetch data from an API in ReactJS ?"
}
]
|
unzip - Unix, Linux Command | "*.c" matches "foo.c" but not "mydir/foo.c"
"**.c" matches both "foo.c" and "mydir/foo.c"
"*/*.c" matches "bar/foo.c" but not "baz/bar/foo.c"
"??*/*" matches "ab/foo" and "abc/foo"
but not "a/foo" or "a/b/foo"
unzip --q[other options] zipfile
The first hyphen is the normal
switch character, and the second is a minus sign, acting on the q option.
Thus the effect here is to cancel one quantum of quietness. To cancel
both quiet flags, two (or more) minuses may be used:
unzip -t--q zipfile
unzip ---qt zipfile
(the two are equivalent). This may seem awkward
or confusing, but it is reasonably intuitive: just ignore the first
hyphen and go from there. It is also consistent with the behavior of
Unix nice(1).
As suggested by the examples above, the default variable names are UNZIP_OPTS
for VMS (where the symbol used to install unzip as a foreign command
would otherwise be confused with the environment variable), and UNZIP
for all other operating systems. For compatibility with zip(1L),
UNZIPOPT is also accepted (don’t ask). If both UNZIP and UNZIPOPT
are defined, however, UNZIP takes precedence. unzip’s diagnostic
option (-v with no zipfile name) can be used to check the values
of all four possible unzip and zipinfo environment variables.
The timezone variable (TZ) should be set according to the local timezone
in order for the -f and -u to operate correctly. See the
description of -f above for details. This variable may also be
necessary to get timestamps of extracted files to be set correctly.
The WIN32 (Win9x/ME/NT4/2K/XP/2K3) port of unzip gets the timezone
configuration from the registry, assuming it is correctly set in the
Control Panel. The TZ variable is ignored for this port.
Some compiled versions of unzip may not support decryption.
To check a version for crypt support, either attempt to test or extract
an encrypted archive, or else check unzip’s diagnostic
screen (see the -v option above) for ‘‘[decryption]’’ as one
of the special compilation options.
As noted above, the -P option may be used to supply a password on
the command line, but at a cost in security. The preferred decryption
method is simply to extract normally; if a zipfile member is encrypted,
unzip will prompt for the password without echoing what is typed.
unzip continues to use the same password as long as it appears to be
valid, by testing a 12-byte header on each file. The correct password will
always check out against the header, but there is a 1-in-256 chance that an
incorrect password will as well. (This is a security feature of the PKWARE
zipfile format; it helps prevent brute-force attacks that might otherwise
gain a large speed advantage by testing only the header.) In the case that
an incorrect password is given but it passes the header test anyway, either
an incorrect CRC will be generated for the extracted data or else unzip
will fail during the extraction because the ‘‘decrypted’’ bytes do not
constitute a valid compressed data stream.
If the first password fails the header check on some file, unzip will
prompt for another password, and so on until all files are extracted. If
a password is not known, entering a null password (that is, just a carriage
return or ‘‘Enter’’) is taken as a signal to skip all further prompting.
Only unencrypted files in the archive(s) will thereafter be extracted. (In
fact, that’s not quite true; older versions of zip(1L) and
zipcloak(1L) allowed null passwords, so unzip checks each encrypted
file to see if the null password works. This may result in ‘‘false positives’’
and extraction errors, as noted above.)
Archives encrypted with 8-bit passwords (for example, passwords with accented
European characters) may not be portable across systems and/or other
archivers. This problem stems from the use of multiple encoding methods for
such characters, including Latin-1 (ISO 8859-1) and OEM code page 850. DOS
PKZIP 2.04g uses the OEM code page; Windows PKZIP 2.50 uses
Latin-1 (and is therefore incompatible with DOS PKZIP); Info-ZIP uses
the OEM code page on DOS, OS/2 and Win3.x ports but Latin-1 everywhere
else; and Nico Mak’s WinZip 6.x does not allow 8-bit passwords at all.
UnZip 5.3 (or newer) attempts to use the default character set first
(e.g., Latin-1), followed by the alternate one (e.g., OEM code page) to test
passwords. On EBCDIC systems, if both of these fail, EBCDIC encoding will
be tested as a last resort. (EBCDIC is not tested on non-EBCDIC systems,
because there are no known archivers that encrypt using EBCDIC encoding.)
ISO character encodings other than Latin-1 are not supported.
unzip letters
To extract all members of letters.zip into the current directory only:
unzip -j letters
To test letters.zip, printing only a summary message indicating
whether the archive is OK or not:
unzip -tq letters
To test all zipfiles in the current directory, printing only the
summaries:
unzip -tq \*.zip
(The backslash before the asterisk is only required if the shell expands
wildcards, as in Unix; double quotes could have been used instead, as in
the source examples below.) To extract to standard output all members of
letters.zip whose names end in .tex, auto-converting to the
local end-of-line convention and piping the output into more(1):
unzip -ca letters \*.tex | more
To extract the binary file paper1.dvi to standard output and pipe it
to a printing program:
unzip -p articles paper1.dvi | dvips
To extract all FORTRAN and C source files--*.f, *.c, *.h, and Makefile--into
the /tmp directory:
unzip source.zip "*.[fch]" Makefile -d /tmp
(the double quotes are necessary only in Unix and only if globbing is turned
on). To extract all FORTRAN and C source files, regardless of case (e.g.,
both *.c and *.C, and any makefile, Makefile, MAKEFILE or similar):
unzip -C source.zip "*.[fch]" makefile -d /tmp
To extract any such files but convert any uppercase MS-DOS or VMS names to
lowercase and convert the line-endings of all of the files to the local
standard (without respect to any files that might be marked ‘‘binary’’):
unzip -aaCL source.zip "*.[fch]" makefile -d /tmp
To extract only newer versions of the files already in the current
directory, without querying (NOTE: be careful of unzipping in one timezone a
zipfile created in another--ZIP archives other than those created by Zip 2.1
or later contain no timezone information, and a ‘‘newer’’ file from an eastern
timezone may, in fact, be older):
unzip -fo sources
To extract newer versions of the files already in the current directory and
to create any files not already there (same caveat as previous example):
unzip -uo sources
To display a diagnostic screen showing which unzip and zipinfo
options are stored in environment variables, whether decryption support was
compiled in, the compiler with which unzip was compiled, etc.:
unzip -v
In the last five examples, assume that UNZIP or UNZIP_OPTS is set to -q.
To do a singly quiet listing:
unzip -l file.zip
To do a doubly quiet listing:
unzip -ql file.zip
(Note that the ‘‘.zip’’ is generally not necessary.) To do a standard
listing:
unzip --ql file.zip
unzip -l-q file.zip
unzip -l--q file.zip
The maintainer also finds it useful to set the UNZIP environment variable
to ‘‘-aL’’ and is tempted to add ‘‘-C’’ as well. His ZIPINFO
variable is set to ‘‘-z’’.
VMS interprets standard Unix (or PC) return values as other, scarier-looking
things, so unzip instead maps them into VMS-style status codes. The
current mapping is as follows: 1 (success) for normal exit, 0x7fff0001
for warning errors, and (0x7fff000? + 16*normal_unzip_exit_status) for all
other errors, where the ‘?’ is 2 (error) for unzip values 2, 9-11 and
80-82, and 4 (fatal error) for the remaining ones (3-8, 50, 51). In addition,
there is a compilation option to expand upon this behavior: defining
RETURN_CODES results in a human-readable explanation of what the error
status means.
Archives read from standard input are not yet supported, except with
funzip (and then only the first member of the archive can be extracted).
Archives encrypted with 8-bit passwords (e.g., passwords with accented
European characters) may not be portable across systems and/or other
archivers. See the discussion in DECRYPTION above.
unzip’s -M (‘‘more’’) option tries to take into account automatic
wrapping of long lines. However, the code may fail to detect the correct
wrapping locations. First, TAB characters (and similar control sequences) are
not taken into account, they are handled as ordinary printable characters.
Second, depending on the actual system / OS port, unzip may not detect
the true screen geometry but rather rely on "commonly used" default dimensions.
The correct handling of tabs would require the implementation of a query for
the actual tabulator setup on the output console.
Dates, times and permissions of stored directories are not restored except
under Unix. (On Windows NT and successors, timestamps are now restored.)
[MS-DOS] When extracting or testing files from an archive on a defective
floppy diskette, if the ‘‘Fail’’ option is chosen from DOS’s ‘‘Abort, Retry,
Fail?’’ message, older versions of unzip may hang the system, requiring
a reboot. This problem appears to be fixed, but control-C (or control-Break)
can still be used to terminate unzip.
Under DEC Ultrix, unzip would sometimes fail on long zipfiles (bad CRC,
not always reproducible). This was apparently due either to a hardware bug
(cache memory) or an operating system bug (improper handling of page faults?).
Since Ultrix has been abandoned in favor of Digital Unix (OSF/1), this may not
be an issue anymore.
[Unix] Unix special files such as FIFO buffers (named pipes), block devices
and character devices are not restored even if they are somehow represented
in the zipfile, nor are hard-linked files relinked. Basically the only file
types restored by unzip are regular files, directories and symbolic
(soft) links.
[OS/2] Extended attributes for existing directories are only updated if the
-o (‘‘overwrite all’’) option is given. This is a limitation of the
operating system; because directories only have a creation time associated
with them, unzip has no way to determine whether the stored attributes
are newer or older than those on disk. In practice this may mean a two-pass
approach is required: first unpack the archive normally (with or without
freshening/updating existing files), then overwrite just the directory entries
(e.g., ‘‘unzip -o foo */’’).
[VMS] When extracting to another directory, only the [.foo] syntax is
accepted for the -d option; the simple Unix foo syntax is
silently ignored (as is the less common VMS foo.dir syntax).
[VMS] When the file being extracted already exists, unzip’s query only
allows skipping, overwriting or renaming; there should additionally be a
choice for creating a new version of the file. In fact, the ‘‘overwrite’’
choice does create a new version; the old version is not overwritten or
deleted.
http://www.info-zip.org/pub/infozip/
ftp://ftp.info-zip.org/pub/infozip/ .
The following people were former members of the Info-ZIP development group
and provided major contributions to key parts of the current code:
Greg ‘‘Cave Newt’’ Roelofs (UnZip, unshrink decompression);
Jean-loup Gailly (deflate compression);
Mark Adler (inflate decompression, fUnZip).
The author of the original unzip code upon which Info-ZIP’s was based
is Samuel H. Smith; Carl Mascott did the first Unix port; and David P.
Kirschbaum organized and led Info-ZIP in its early days with Keith Petersen
hosting the original mailing list at WSMR-SimTel20. The full list of
contributors to UnZip has grown quite large; please refer to the CONTRIBS
file in the UnZip source distribution for a relatively complete version.
Advertisements
129 Lectures
23 hours
Eduonix Learning Solutions
5 Lectures
4.5 hours
Frahaan Hussain
35 Lectures
2 hours
Pradeep D
41 Lectures
2.5 hours
Musab Zayadneh
46 Lectures
4 hours
GUHARAJANM
6 Lectures
4 hours
Uplatz
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 10816,
"s": 10577,
"text": " \"*.c\" matches \"foo.c\" but not \"mydir/foo.c\"\n \"**.c\" matches both \"foo.c\" and \"mydir/foo.c\"\n \"*/*.c\" matches \"bar/foo.c\" but not \"baz/bar/foo.c\"\n \"??*/*\" matches \"ab/foo\" and \"abc/foo\"\n but not \"a/foo\" or \"a/b/foo\"\n"
},
{
"code": null,
"e": 10853,
"s": 10819,
"text": "unzip --q[other options] zipfile\n"
},
{
"code": null,
"e": 11084,
"s": 10853,
"text": "\nThe first hyphen is the normal\nswitch character, and the second is a minus sign, acting on the q option.\nThus the effect here is to cancel one quantum of quietness. To cancel\nboth quiet flags, two (or more) minuses may be used:\n"
},
{
"code": null,
"e": 11128,
"s": 11087,
"text": "unzip -t--q zipfile\nunzip ---qt zipfile\n"
},
{
"code": null,
"e": 11332,
"s": 11128,
"text": "\n(the two are equivalent). This may seem awkward\nor confusing, but it is reasonably intuitive: just ignore the first\nhyphen and go from there. It is also consistent with the behavior of\nUnix nice(1).\n"
},
{
"code": null,
"e": 11877,
"s": 11332,
"text": "\nAs suggested by the examples above, the default variable names are UNZIP_OPTS\nfor VMS (where the symbol used to install unzip as a foreign command\nwould otherwise be confused with the environment variable), and UNZIP\nfor all other operating systems. For compatibility with zip(1L),\nUNZIPOPT is also accepted (don’t ask). If both UNZIP and UNZIPOPT\nare defined, however, UNZIP takes precedence. unzip’s diagnostic\noption (-v with no zipfile name) can be used to check the values\nof all four possible unzip and zipinfo environment variables.\n"
},
{
"code": null,
"e": 12336,
"s": 11877,
"text": "\nThe timezone variable (TZ) should be set according to the local timezone\nin order for the -f and -u to operate correctly. See the\ndescription of -f above for details. This variable may also be\nnecessary to get timestamps of extracted files to be set correctly.\nThe WIN32 (Win9x/ME/NT4/2K/XP/2K3) port of unzip gets the timezone\nconfiguration from the registry, assuming it is correctly set in the\nControl Panel. The TZ variable is ignored for this port.\n"
},
{
"code": null,
"e": 12622,
"s": 12336,
"text": "\nSome compiled versions of unzip may not support decryption.\nTo check a version for crypt support, either attempt to test or extract\nan encrypted archive, or else check unzip’s diagnostic\nscreen (see the -v option above) for ‘‘[decryption]’’ as one\nof the special compilation options.\n"
},
{
"code": null,
"e": 13608,
"s": 12622,
"text": "\nAs noted above, the -P option may be used to supply a password on\nthe command line, but at a cost in security. The preferred decryption\nmethod is simply to extract normally; if a zipfile member is encrypted,\nunzip will prompt for the password without echoing what is typed.\nunzip continues to use the same password as long as it appears to be\nvalid, by testing a 12-byte header on each file. The correct password will\nalways check out against the header, but there is a 1-in-256 chance that an\nincorrect password will as well. (This is a security feature of the PKWARE\nzipfile format; it helps prevent brute-force attacks that might otherwise\ngain a large speed advantage by testing only the header.) In the case that\nan incorrect password is given but it passes the header test anyway, either\nan incorrect CRC will be generated for the extracted data or else unzip\nwill fail during the extraction because the ‘‘decrypted’’ bytes do not\nconstitute a valid compressed data stream.\n"
},
{
"code": null,
"e": 14226,
"s": 13608,
"text": "\nIf the first password fails the header check on some file, unzip will\nprompt for another password, and so on until all files are extracted. If\na password is not known, entering a null password (that is, just a carriage\nreturn or ‘‘Enter’’) is taken as a signal to skip all further prompting.\nOnly unencrypted files in the archive(s) will thereafter be extracted. (In\nfact, that’s not quite true; older versions of zip(1L) and\nzipcloak(1L) allowed null passwords, so unzip checks each encrypted\nfile to see if the null password works. This may result in ‘‘false positives’’\nand extraction errors, as noted above.)\n"
},
{
"code": null,
"e": 15231,
"s": 14226,
"text": "\nArchives encrypted with 8-bit passwords (for example, passwords with accented\nEuropean characters) may not be portable across systems and/or other\narchivers. This problem stems from the use of multiple encoding methods for\nsuch characters, including Latin-1 (ISO 8859-1) and OEM code page 850. DOS\nPKZIP 2.04g uses the OEM code page; Windows PKZIP 2.50 uses\nLatin-1 (and is therefore incompatible with DOS PKZIP); Info-ZIP uses\nthe OEM code page on DOS, OS/2 and Win3.x ports but Latin-1 everywhere\nelse; and Nico Mak’s WinZip 6.x does not allow 8-bit passwords at all.\nUnZip 5.3 (or newer) attempts to use the default character set first\n(e.g., Latin-1), followed by the alternate one (e.g., OEM code page) to test\npasswords. On EBCDIC systems, if both of these fail, EBCDIC encoding will\nbe tested as a last resort. (EBCDIC is not tested on non-EBCDIC systems,\nbecause there are no known archivers that encrypt using EBCDIC encoding.)\nISO character encodings other than Latin-1 are not supported.\n"
},
{
"code": null,
"e": 15249,
"s": 15234,
"text": "unzip letters\n"
},
{
"code": null,
"e": 15322,
"s": 15249,
"text": "\nTo extract all members of letters.zip into the current directory only:\n"
},
{
"code": null,
"e": 15343,
"s": 15325,
"text": "unzip -j letters\n"
},
{
"code": null,
"e": 15443,
"s": 15343,
"text": "\nTo test letters.zip, printing only a summary message indicating\nwhether the archive is OK or not:\n"
},
{
"code": null,
"e": 15465,
"s": 15446,
"text": "unzip -tq letters\n"
},
{
"code": null,
"e": 15543,
"s": 15465,
"text": "\nTo test all zipfiles in the current directory, printing only the\nsummaries:\n"
},
{
"code": null,
"e": 15564,
"s": 15546,
"text": "unzip -tq \\*.zip\n"
},
{
"code": null,
"e": 15911,
"s": 15564,
"text": "\n(The backslash before the asterisk is only required if the shell expands\nwildcards, as in Unix; double quotes could have been used instead, as in\nthe source examples below.) To extract to standard output all members of\nletters.zip whose names end in .tex, auto-converting to the\nlocal end-of-line convention and piping the output into more(1):\n"
},
{
"code": null,
"e": 15947,
"s": 15914,
"text": "unzip -ca letters \\*.tex | more\n"
},
{
"code": null,
"e": 16041,
"s": 15947,
"text": "\nTo extract the binary file paper1.dvi to standard output and pipe it\nto a printing program:\n"
},
{
"code": null,
"e": 16082,
"s": 16044,
"text": "unzip -p articles paper1.dvi | dvips\n"
},
{
"code": null,
"e": 16181,
"s": 16082,
"text": "\nTo extract all FORTRAN and C source files--*.f, *.c, *.h, and Makefile--into\nthe /tmp directory:\n"
},
{
"code": null,
"e": 16229,
"s": 16184,
"text": "unzip source.zip \"*.[fch]\" Makefile -d /tmp\n"
},
{
"code": null,
"e": 16451,
"s": 16229,
"text": "\n(the double quotes are necessary only in Unix and only if globbing is turned\non). To extract all FORTRAN and C source files, regardless of case (e.g.,\nboth *.c and *.C, and any makefile, Makefile, MAKEFILE or similar):\n"
},
{
"code": null,
"e": 16502,
"s": 16454,
"text": "unzip -C source.zip \"*.[fch]\" makefile -d /tmp\n"
},
{
"code": null,
"e": 16724,
"s": 16502,
"text": "\nTo extract any such files but convert any uppercase MS-DOS or VMS names to\nlowercase and convert the line-endings of all of the files to the local\nstandard (without respect to any files that might be marked ‘‘binary’’):\n"
},
{
"code": null,
"e": 16778,
"s": 16727,
"text": "unzip -aaCL source.zip \"*.[fch]\" makefile -d /tmp\n"
},
{
"code": null,
"e": 17115,
"s": 16778,
"text": "\nTo extract only newer versions of the files already in the current\ndirectory, without querying (NOTE: be careful of unzipping in one timezone a\nzipfile created in another--ZIP archives other than those created by Zip 2.1\nor later contain no timezone information, and a ‘‘newer’’ file from an eastern\ntimezone may, in fact, be older):\n"
},
{
"code": null,
"e": 17137,
"s": 17118,
"text": "unzip -fo sources\n"
},
{
"code": null,
"e": 17288,
"s": 17137,
"text": "\nTo extract newer versions of the files already in the current directory and\nto create any files not already there (same caveat as previous example):\n"
},
{
"code": null,
"e": 17310,
"s": 17291,
"text": "unzip -uo sources\n"
},
{
"code": null,
"e": 17514,
"s": 17310,
"text": "\nTo display a diagnostic screen showing which unzip and zipinfo\noptions are stored in environment variables, whether decryption support was\ncompiled in, the compiler with which unzip was compiled, etc.:\n"
},
{
"code": null,
"e": 17527,
"s": 17517,
"text": "unzip -v\n"
},
{
"code": null,
"e": 17632,
"s": 17527,
"text": "\nIn the last five examples, assume that UNZIP or UNZIP_OPTS is set to -q.\nTo do a singly quiet listing:\n"
},
{
"code": null,
"e": 17654,
"s": 17635,
"text": "unzip -l file.zip\n"
},
{
"code": null,
"e": 17686,
"s": 17654,
"text": "\nTo do a doubly quiet listing:\n"
},
{
"code": null,
"e": 17709,
"s": 17689,
"text": "unzip -ql file.zip\n"
},
{
"code": null,
"e": 17791,
"s": 17709,
"text": "\n(Note that the ‘‘.zip’’ is generally not necessary.) To do a standard\nlisting:\n"
},
{
"code": null,
"e": 17815,
"s": 17794,
"text": "unzip --ql file.zip\n"
},
{
"code": null,
"e": 17836,
"s": 17815,
"text": "unzip -l-q file.zip\n"
},
{
"code": null,
"e": 17858,
"s": 17836,
"text": "unzip -l--q file.zip\n"
},
{
"code": null,
"e": 18023,
"s": 17858,
"text": "\nThe maintainer also finds it useful to set the UNZIP environment variable\nto ‘‘-aL’’ and is tempted to add ‘‘-C’’ as well. His ZIPINFO\nvariable is set to ‘‘-z’’.\n"
},
{
"code": null,
"e": 18623,
"s": 18023,
"text": "\nVMS interprets standard Unix (or PC) return values as other, scarier-looking\nthings, so unzip instead maps them into VMS-style status codes. The\ncurrent mapping is as follows: 1 (success) for normal exit, 0x7fff0001\nfor warning errors, and (0x7fff000? + 16*normal_unzip_exit_status) for all\nother errors, where the ‘?’ is 2 (error) for unzip values 2, 9-11 and\n80-82, and 4 (fatal error) for the remaining ones (3-8, 50, 51). In addition,\nthere is a compilation option to expand upon this behavior: defining\nRETURN_CODES results in a human-readable explanation of what the error\nstatus means.\n"
},
{
"code": null,
"e": 18767,
"s": 18623,
"text": "\nArchives read from standard input are not yet supported, except with\nfunzip (and then only the first member of the archive can be extracted).\n"
},
{
"code": null,
"e": 18961,
"s": 18767,
"text": "\nArchives encrypted with 8-bit passwords (e.g., passwords with accented\nEuropean characters) may not be portable across systems and/or other\narchivers. See the discussion in DECRYPTION above.\n"
},
{
"code": null,
"e": 19533,
"s": 18961,
"text": "\nunzip’s -M (‘‘more’’) option tries to take into account automatic\nwrapping of long lines. However, the code may fail to detect the correct\nwrapping locations. First, TAB characters (and similar control sequences) are\nnot taken into account, they are handled as ordinary printable characters.\nSecond, depending on the actual system / OS port, unzip may not detect\nthe true screen geometry but rather rely on \"commonly used\" default dimensions.\nThe correct handling of tabs would require the implementation of a query for\nthe actual tabulator setup on the output console.\n"
},
{
"code": null,
"e": 19683,
"s": 19533,
"text": "\nDates, times and permissions of stored directories are not restored except\nunder Unix. (On Windows NT and successors, timestamps are now restored.)\n"
},
{
"code": null,
"e": 20023,
"s": 19683,
"text": "\n[MS-DOS] When extracting or testing files from an archive on a defective\nfloppy diskette, if the ‘‘Fail’’ option is chosen from DOS’s ‘‘Abort, Retry,\nFail?’’ message, older versions of unzip may hang the system, requiring\na reboot. This problem appears to be fixed, but control-C (or control-Break)\ncan still be used to terminate unzip.\n"
},
{
"code": null,
"e": 20352,
"s": 20023,
"text": "\nUnder DEC Ultrix, unzip would sometimes fail on long zipfiles (bad CRC,\nnot always reproducible). This was apparently due either to a hardware bug\n(cache memory) or an operating system bug (improper handling of page faults?).\nSince Ultrix has been abandoned in favor of Digital Unix (OSF/1), this may not\nbe an issue anymore.\n"
},
{
"code": null,
"e": 20665,
"s": 20352,
"text": "\n[Unix] Unix special files such as FIFO buffers (named pipes), block devices\nand character devices are not restored even if they are somehow represented\nin the zipfile, nor are hard-linked files relinked. Basically the only file\ntypes restored by unzip are regular files, directories and symbolic\n(soft) links.\n"
},
{
"code": null,
"e": 21217,
"s": 20665,
"text": "\n[OS/2] Extended attributes for existing directories are only updated if the\n-o (‘‘overwrite all’’) option is given. This is a limitation of the\noperating system; because directories only have a creation time associated\nwith them, unzip has no way to determine whether the stored attributes\nare newer or older than those on disk. In practice this may mean a two-pass\napproach is required: first unpack the archive normally (with or without\nfreshening/updating existing files), then overwrite just the directory entries\n(e.g., ‘‘unzip -o foo */’’).\n"
},
{
"code": null,
"e": 21408,
"s": 21217,
"text": "\n[VMS] When extracting to another directory, only the [.foo] syntax is\naccepted for the -d option; the simple Unix foo syntax is\nsilently ignored (as is the less common VMS foo.dir syntax).\n"
},
{
"code": null,
"e": 21710,
"s": 21408,
"text": "\n[VMS] When the file being extracted already exists, unzip’s query only\nallows skipping, overwriting or renaming; there should additionally be a\nchoice for creating a new version of the file. In fact, the ‘‘overwrite’’\nchoice does create a new version; the old version is not overwritten or\ndeleted.\n"
},
{
"code": null,
"e": 21748,
"s": 21710,
"text": "http://www.info-zip.org/pub/infozip/\n"
},
{
"code": null,
"e": 21787,
"s": 21748,
"text": "ftp://ftp.info-zip.org/pub/infozip/ .\n"
},
{
"code": null,
"e": 22075,
"s": 21787,
"text": "\nThe following people were former members of the Info-ZIP development group\nand provided major contributions to key parts of the current code:\nGreg ‘‘Cave Newt’’ Roelofs (UnZip, unshrink decompression);\nJean-loup Gailly (deflate compression);\nMark Adler (inflate decompression, fUnZip).\n"
},
{
"code": null,
"e": 22511,
"s": 22075,
"text": "\nThe author of the original unzip code upon which Info-ZIP’s was based\nis Samuel H. Smith; Carl Mascott did the first Unix port; and David P.\nKirschbaum organized and led Info-ZIP in its early days with Keith Petersen\nhosting the original mailing list at WSMR-SimTel20. The full list of\ncontributors to UnZip has grown quite large; please refer to the CONTRIBS\nfile in the UnZip source distribution for a relatively complete version.\n"
},
{
"code": null,
"e": 22528,
"s": 22511,
"text": "\nAdvertisements\n"
},
{
"code": null,
"e": 22563,
"s": 22528,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 22591,
"s": 22563,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 22625,
"s": 22591,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 22642,
"s": 22625,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 22675,
"s": 22642,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 22686,
"s": 22675,
"text": " Pradeep D"
},
{
"code": null,
"e": 22721,
"s": 22686,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 22737,
"s": 22721,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 22770,
"s": 22737,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 22782,
"s": 22770,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 22814,
"s": 22782,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 22822,
"s": 22814,
"text": " Uplatz"
},
{
"code": null,
"e": 22829,
"s": 22822,
"text": " Print"
},
{
"code": null,
"e": 22840,
"s": 22829,
"text": " Add Notes"
}
]
|
Double.IsNaN() Method in C# - GeeksforGeeks | 13 Feb, 2019
In C#, Double.IsNaN() is a Double struct method. This method is used to check whether the specified value is not a number (NaN).
Syntax: public static bool IsNaN (double d);
Parameter:d: It is a double-precision floating-point number of type System.Double
Return Type: This function returns a Boolean value i.e. True, if specified value is not a number(NaN), otherwise returns False.
Example:
Input : d = 0.0 / 0.0
Output : True
Input : d = 1.734
Output : False
Code: To demonstrate the Double.IsNaN(Double) method.
// C# code to demonstrate // Double.IsNaN(Double) method using System; class GFG { // Main Method public static void Main(String[] args) { // first example Double f1 = 1.0 / 0.0; bool res = Double.IsNaN(f1); // printing the output if (res) Console.WriteLine(f1 + " is NaN"); else Console.WriteLine(f1 + " is not NaN"); // second example double f2 = 0.0 / 0.0; bool res1 = Double.IsNaN(f2); // printing the output if (res1) Console.WriteLine(f2 + " is NaN"); else Console.WriteLine(f2 + " is not NaN"); } }
Infinity is not NaN
NaN is NaN
Note:
If we divide any value by 0 directly, the Compiler will show an error. So, in the above example, 0 is stored in a variable first.
Every floating point operation returns a NaN to show that the result of the operation is undefined.
CSharp-Double-Struct
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# | Delegates
Top 50 C# Interview Questions & Answers
Introduction to .NET Framework
Extension Method in C#
C# | Abstract Classes
C# | String.IndexOf( ) Method | Set - 1
Common Language Runtime (CLR) in C#
C# | Arrays
HashSet in C# with Examples
C# | Replace() Method | [
{
"code": null,
"e": 23871,
"s": 23843,
"text": "\n13 Feb, 2019"
},
{
"code": null,
"e": 24000,
"s": 23871,
"text": "In C#, Double.IsNaN() is a Double struct method. This method is used to check whether the specified value is not a number (NaN)."
},
{
"code": null,
"e": 24045,
"s": 24000,
"text": "Syntax: public static bool IsNaN (double d);"
},
{
"code": null,
"e": 24127,
"s": 24045,
"text": "Parameter:d: It is a double-precision floating-point number of type System.Double"
},
{
"code": null,
"e": 24255,
"s": 24127,
"text": "Return Type: This function returns a Boolean value i.e. True, if specified value is not a number(NaN), otherwise returns False."
},
{
"code": null,
"e": 24264,
"s": 24255,
"text": "Example:"
},
{
"code": null,
"e": 24338,
"s": 24264,
"text": "Input : d = 0.0 / 0.0 \nOutput : True\n\nInput : d = 1.734\nOutput : False\n"
},
{
"code": null,
"e": 24392,
"s": 24338,
"text": "Code: To demonstrate the Double.IsNaN(Double) method."
},
{
"code": "// C# code to demonstrate // Double.IsNaN(Double) method using System; class GFG { // Main Method public static void Main(String[] args) { // first example Double f1 = 1.0 / 0.0; bool res = Double.IsNaN(f1); // printing the output if (res) Console.WriteLine(f1 + \" is NaN\"); else Console.WriteLine(f1 + \" is not NaN\"); // second example double f2 = 0.0 / 0.0; bool res1 = Double.IsNaN(f2); // printing the output if (res1) Console.WriteLine(f2 + \" is NaN\"); else Console.WriteLine(f2 + \" is not NaN\"); } } ",
"e": 25075,
"s": 24392,
"text": null
},
{
"code": null,
"e": 25107,
"s": 25075,
"text": "Infinity is not NaN\nNaN is NaN\n"
},
{
"code": null,
"e": 25113,
"s": 25107,
"text": "Note:"
},
{
"code": null,
"e": 25243,
"s": 25113,
"text": "If we divide any value by 0 directly, the Compiler will show an error. So, in the above example, 0 is stored in a variable first."
},
{
"code": null,
"e": 25343,
"s": 25243,
"text": "Every floating point operation returns a NaN to show that the result of the operation is undefined."
},
{
"code": null,
"e": 25364,
"s": 25343,
"text": "CSharp-Double-Struct"
},
{
"code": null,
"e": 25378,
"s": 25364,
"text": "CSharp-method"
},
{
"code": null,
"e": 25381,
"s": 25378,
"text": "C#"
},
{
"code": null,
"e": 25479,
"s": 25381,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25488,
"s": 25479,
"text": "Comments"
},
{
"code": null,
"e": 25501,
"s": 25488,
"text": "Old Comments"
},
{
"code": null,
"e": 25516,
"s": 25501,
"text": "C# | Delegates"
},
{
"code": null,
"e": 25556,
"s": 25516,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 25587,
"s": 25556,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 25610,
"s": 25587,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 25632,
"s": 25610,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 25672,
"s": 25632,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 25708,
"s": 25672,
"text": "Common Language Runtime (CLR) in C#"
},
{
"code": null,
"e": 25720,
"s": 25708,
"text": "C# | Arrays"
},
{
"code": null,
"e": 25748,
"s": 25720,
"text": "HashSet in C# with Examples"
}
]
|
How to get the duplicates values from Arraylist<String> and then get those items in another Arraylist in Android? | This example demonstrate about How to get the duplicates values from Arraylist<String> and then get those items in another Arraylist.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:app = "http://schemas.android.com/apk/res-auto"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity">
<ListView
android:id = "@+id/list"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content" />
</android.support.constraint.ConstraintLayout>
In the above code, we have taken listview to show duplication list items from array list.
Step 3 − Add the following code to src/MainActivity.java
package com.example.andy.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
public class MainActivity extends AppCompatActivity {
ListView list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Set<String> set = new HashSet<>();
ArrayList<String> MainListItem = new ArrayList<String>();
MainListItem.add("Sai");
MainListItem.add("Sai");
MainListItem.add("ram");
MainListItem.add("Sai krishna");
MainListItem.add("Sai Ram Krishna");
MainListItem.add("tutorialspoint.com");
MainListItem.add("tutorialspoint.com");
ArrayList<String> duplicates = new ArrayList<String>();
for (String s : MainListItem) {
if (!set.add(s)) {
duplicates.add(s);
}
}
list = findViewById(R.id.list);
ArrayAdapter arrayAdapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, duplicates);
list.setAdapter(arrayAdapter);
}
}
In the above code we have taken arraylist as shown below –
ArrayList<String> MainListItem = new ArrayList<String>();
MainListItem.add("Sai");
MainListItem.add("Sai");
MainListItem.add("ram");
MainListItem.add("Sai krishna");
MainListItem.add("Sai Ram Krishna");
MainListItem.add("tutorialspoint.com");
MainListItem.add("tutorialspoint.com");
In the above code “sai” and “tutrialspoint.com” are duplicated values.
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
In the above result, it has shown duplicated values from arraylist.
Click here to download the project code | [
{
"code": null,
"e": 1196,
"s": 1062,
"text": "This example demonstrate about How to get the duplicates values from Arraylist<String> and then get those items in another Arraylist."
},
{
"code": null,
"e": 1325,
"s": 1196,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1390,
"s": 1325,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1950,
"s": 1390,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<android.support.constraint.ConstraintLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:app = \"http://schemas.android.com/apk/res-auto\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\">\n <ListView\n android:id = \"@+id/list\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\" />\n</android.support.constraint.ConstraintLayout>"
},
{
"code": null,
"e": 2040,
"s": 1950,
"text": "In the above code, we have taken listview to show duplication list items from array list."
},
{
"code": null,
"e": 2097,
"s": 2040,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3337,
"s": 2097,
"text": "package com.example.andy.myapplication;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.widget.ArrayAdapter;\nimport android.widget.ListView;\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.Set;\npublic class MainActivity extends AppCompatActivity {\n ListView list;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n Set<String> set = new HashSet<>();\n ArrayList<String> MainListItem = new ArrayList<String>();\n MainListItem.add(\"Sai\");\n MainListItem.add(\"Sai\");\n MainListItem.add(\"ram\");\n MainListItem.add(\"Sai krishna\");\n MainListItem.add(\"Sai Ram Krishna\");\n MainListItem.add(\"tutorialspoint.com\");\n MainListItem.add(\"tutorialspoint.com\");\n ArrayList<String> duplicates = new ArrayList<String>();\n for (String s : MainListItem) {\n if (!set.add(s)) {\n duplicates.add(s);\n }\n }\n list = findViewById(R.id.list);\n ArrayAdapter arrayAdapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, duplicates);\n list.setAdapter(arrayAdapter);\n }\n}"
},
{
"code": null,
"e": 3396,
"s": 3337,
"text": "In the above code we have taken arraylist as shown below –"
},
{
"code": null,
"e": 3679,
"s": 3396,
"text": "ArrayList<String> MainListItem = new ArrayList<String>();\nMainListItem.add(\"Sai\");\nMainListItem.add(\"Sai\");\nMainListItem.add(\"ram\");\nMainListItem.add(\"Sai krishna\");\nMainListItem.add(\"Sai Ram Krishna\");\nMainListItem.add(\"tutorialspoint.com\");\nMainListItem.add(\"tutorialspoint.com\");"
},
{
"code": null,
"e": 3750,
"s": 3679,
"text": "In the above code “sai” and “tutrialspoint.com” are duplicated values."
},
{
"code": null,
"e": 4097,
"s": 3750,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –"
},
{
"code": null,
"e": 4165,
"s": 4097,
"text": "In the above result, it has shown duplicated values from arraylist."
},
{
"code": null,
"e": 4205,
"s": 4165,
"text": "Click here to download the project code"
}
]
|
SQL Tryit Editor v1.6 | SELECT * FROM Customers;
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, Opera, and Edge(79).
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data. | [
{
"code": null,
"e": 25,
"s": 0,
"text": "SELECT * FROM Customers;"
},
{
"code": null,
"e": 27,
"s": 25,
"text": ""
},
{
"code": null,
"e": 90,
"s": 27,
"text": "Edit the SQL Statement, and click \"Run SQL\" to see the result."
},
{
"code": null,
"e": 150,
"s": 90,
"text": "This SQL-Statement is not supported in the WebSQL Database."
},
{
"code": null,
"e": 218,
"s": 150,
"text": "The example still works, because it uses a modified version of SQL."
},
{
"code": null,
"e": 256,
"s": 218,
"text": "Your browser does not support WebSQL."
},
{
"code": null,
"e": 341,
"s": 256,
"text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database."
},
{
"code": null,
"e": 515,
"s": 341,
"text": "If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time."
},
{
"code": null,
"e": 566,
"s": 515,
"text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL."
},
{
"code": null,
"e": 634,
"s": 566,
"text": "A Database-object is created in your browser, for testing purposes."
},
{
"code": null,
"e": 805,
"s": 634,
"text": "You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the \"Restore Database\" button."
},
{
"code": null,
"e": 905,
"s": 805,
"text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object."
},
{
"code": null,
"e": 965,
"s": 905,
"text": "WebSQL is supported in Chrome, Safari, Opera, and Edge(79)."
}
]
|
C# program to replace all spaces in a string with ‘%20’ | We have a sample string with spaces −
str ="Hello World !";
Use the Replace() method in C# to replace all spaces in a string with ‘%20’ −
str2 = str.Replace(" ", "%20");
You can try to run the following code to replace all spaces in a string with ‘%20’.
Live Demo
using System;
class Demo {
static void Main() {
String str, str2;
str ="Hello World !";
Console.WriteLine("String: "+str);
str2 = str.Replace(" ", "%20");
Console.WriteLine("String (After replacing): "+str2);
}
}
String: Hello World !
String (After replacing): Hello%20World%20! | [
{
"code": null,
"e": 1100,
"s": 1062,
"text": "We have a sample string with spaces −"
},
{
"code": null,
"e": 1122,
"s": 1100,
"text": "str =\"Hello World !\";"
},
{
"code": null,
"e": 1200,
"s": 1122,
"text": "Use the Replace() method in C# to replace all spaces in a string with ‘%20’ −"
},
{
"code": null,
"e": 1232,
"s": 1200,
"text": "str2 = str.Replace(\" \", \"%20\");"
},
{
"code": null,
"e": 1316,
"s": 1232,
"text": "You can try to run the following code to replace all spaces in a string with ‘%20’."
},
{
"code": null,
"e": 1326,
"s": 1316,
"text": "Live Demo"
},
{
"code": null,
"e": 1575,
"s": 1326,
"text": "using System;\nclass Demo {\n static void Main() {\n String str, str2;\n str =\"Hello World !\";\n Console.WriteLine(\"String: \"+str);\n str2 = str.Replace(\" \", \"%20\");\n Console.WriteLine(\"String (After replacing): \"+str2);\n }\n}"
},
{
"code": null,
"e": 1641,
"s": 1575,
"text": "String: Hello World !\nString (After replacing): Hello%20World%20!"
}
]
|
What’s new in YOLOv4?. YOLO is a real-time object recognition... | by Roman Orac | Towards Data Science | YOLO is short for You Only Look Once. It is a real-time object recognition system that can recognize multiple objects in a single frame. YOLO recognizes objects more precisely and faster than other recognition systems. It can predict up to 9000 classes and even unseen classes. The real-time recognition system will recognize multiple objects from an image and also make a boundary box around the object. It can be easily trained and deployed in a production system.
Here are few links that might interest you:
- Complete your Python analyses 10x faster with Mito [Product]- Free skill tests for Data Scientists & ML Engineers [Test]- All New Self-Driving Car Engineer Nanodegree [Course]
Would you like to read more such articles? If so, you can support me by clicking on any links above. Some of them are affiliate links, but you don’t need to buy anything.
YOLO is based on a single Convolutional Neural Network (CNN). The CNN divides an image into regions and then it predicts the boundary boxes and probabilities for each region. It simultaneously predicts multiple bounding boxes and probabilities for those classes. YOLO sees the entire image during training and test time so it implicitly encodes contextual information about classes as well as their appearance.
YOLO is developed by Joseph Redmon. The introduction of the YOLO real-time object recognition system in 2016 is the cornerstone of object recognition research. This led to better and faster Computer Vision algorithms.
YOLO v4 is developed by three developers Alexey Bochkovskiy, Chien-Yao Wang, and Hong-Yuan Mark Liao.
He quit developing YOLO v4 because of the potential misuse of his tech. He especially referring to “military applications and data protection issues”. He ceases his research for Computer Vision because he found that the ethical issues involved were “become impossible to ignore”.
YOLOv4’s architecture is composed of CSPDarknet53 as a backbone, spatial pyramid pooling additional module, PANet path-aggregation neck and YOLOv3 head.
CSPDarknet53 is a novel backbone that can enhance the learning capability of CNN. The spatial pyramid pooling block is added over CSPDarknet53 to increase the receptive field and separate out the most significant context features. Instead of Feature pyramid networks (FPN) for object detection used in YOLOv3, the PANet is used as the method for parameter aggregation for different detector levels.
YOLOv4 is twice as fast as EfficientDet (competitive recognition model) with comparable performance. In addition, AP (Average Precision) and FPS (Frames Per Second) increased by 10% and 12% compared to YOLOv3.
YOLO is a futuristic recognizer that has faster FPS and is more accurate than available detectors. The detector can be trained and used on a conventional GPU which enables widespread adoption. New features in YOLOv4 improve accuracy of the classifier and detector and may be used for other research projects.
YOLOv4: Optimal Speed and Accuracy of Object Detection
YOLO Is Back! Version 4 Boasts Improved Speed and Accuracy
YOLO Creator Joseph Redmon Stopped CV Research Due to Ethical Concerns
Follow me on Twitter, where I regularly tweet about Data Science and Machine Learning. | [
{
"code": null,
"e": 639,
"s": 172,
"text": "YOLO is short for You Only Look Once. It is a real-time object recognition system that can recognize multiple objects in a single frame. YOLO recognizes objects more precisely and faster than other recognition systems. It can predict up to 9000 classes and even unseen classes. The real-time recognition system will recognize multiple objects from an image and also make a boundary box around the object. It can be easily trained and deployed in a production system."
},
{
"code": null,
"e": 683,
"s": 639,
"text": "Here are few links that might interest you:"
},
{
"code": null,
"e": 861,
"s": 683,
"text": "- Complete your Python analyses 10x faster with Mito [Product]- Free skill tests for Data Scientists & ML Engineers [Test]- All New Self-Driving Car Engineer Nanodegree [Course]"
},
{
"code": null,
"e": 1032,
"s": 861,
"text": "Would you like to read more such articles? If so, you can support me by clicking on any links above. Some of them are affiliate links, but you don’t need to buy anything."
},
{
"code": null,
"e": 1443,
"s": 1032,
"text": "YOLO is based on a single Convolutional Neural Network (CNN). The CNN divides an image into regions and then it predicts the boundary boxes and probabilities for each region. It simultaneously predicts multiple bounding boxes and probabilities for those classes. YOLO sees the entire image during training and test time so it implicitly encodes contextual information about classes as well as their appearance."
},
{
"code": null,
"e": 1661,
"s": 1443,
"text": "YOLO is developed by Joseph Redmon. The introduction of the YOLO real-time object recognition system in 2016 is the cornerstone of object recognition research. This led to better and faster Computer Vision algorithms."
},
{
"code": null,
"e": 1763,
"s": 1661,
"text": "YOLO v4 is developed by three developers Alexey Bochkovskiy, Chien-Yao Wang, and Hong-Yuan Mark Liao."
},
{
"code": null,
"e": 2043,
"s": 1763,
"text": "He quit developing YOLO v4 because of the potential misuse of his tech. He especially referring to “military applications and data protection issues”. He ceases his research for Computer Vision because he found that the ethical issues involved were “become impossible to ignore”."
},
{
"code": null,
"e": 2196,
"s": 2043,
"text": "YOLOv4’s architecture is composed of CSPDarknet53 as a backbone, spatial pyramid pooling additional module, PANet path-aggregation neck and YOLOv3 head."
},
{
"code": null,
"e": 2595,
"s": 2196,
"text": "CSPDarknet53 is a novel backbone that can enhance the learning capability of CNN. The spatial pyramid pooling block is added over CSPDarknet53 to increase the receptive field and separate out the most significant context features. Instead of Feature pyramid networks (FPN) for object detection used in YOLOv3, the PANet is used as the method for parameter aggregation for different detector levels."
},
{
"code": null,
"e": 2805,
"s": 2595,
"text": "YOLOv4 is twice as fast as EfficientDet (competitive recognition model) with comparable performance. In addition, AP (Average Precision) and FPS (Frames Per Second) increased by 10% and 12% compared to YOLOv3."
},
{
"code": null,
"e": 3114,
"s": 2805,
"text": "YOLO is a futuristic recognizer that has faster FPS and is more accurate than available detectors. The detector can be trained and used on a conventional GPU which enables widespread adoption. New features in YOLOv4 improve accuracy of the classifier and detector and may be used for other research projects."
},
{
"code": null,
"e": 3169,
"s": 3114,
"text": "YOLOv4: Optimal Speed and Accuracy of Object Detection"
},
{
"code": null,
"e": 3228,
"s": 3169,
"text": "YOLO Is Back! Version 4 Boasts Improved Speed and Accuracy"
},
{
"code": null,
"e": 3299,
"s": 3228,
"text": "YOLO Creator Joseph Redmon Stopped CV Research Due to Ethical Concerns"
}
]
|
How to find the cube root of negative values in R? | There is no function in R to find the cube root of negative values, hence we need to create that. The code to create the function is as shown below −
CubeRoot<-function(x){
sign(x)*abs(x)^(1/3)
}
Now we just need to pass the values in the function to find the cube root of those values. These values can be a vector or a single value as well.
Examples of finding the cube roots using our function CubeRoot −
CubeRoot(-3)
[1] -1.44225
CubeRoot(-9)
[1] -2.080084
CubeRoot(-27)
[1] -3
CubeRoot(-125)
[1] -5
CubeRoot(-1000)
[1] -10
CubeRoot(-64)
[1] -4
CubeRoot(-1)
[1] -1
CubeRoot(-81)
[1] -4.326749
CubeRoot(-216)
[1] -6
CubeRoot(c(-1,-9,-64,-125,-216))
[1] -1.000000 -2.080084 -4.000000 -5.000000 -6.000000
x1<-c(-8,-100,-500,-1000,-5000,-10000)
CubeRoot(x1)
[1] -2.000000 -4.641589 -7.937005 -10.000000 -17.099759 -21.544347
Live Demo
x2<-sample(-10:-1,100,replace=TRUE)
x2
[1] -3 -1 -1 -4 -10 -7 -7 -2 -4 -8 -1 -9 -8 -6 -9 -5 -6 -5
[19] -2 -8 -1 -8 -5 -9 -3 -7 -9 -10 -3 -2 -1 -9 -1 -8 -8 -6
[37] -5 -4 -4 -2 -3 -3 -2 -4 -8 -7 -5 -7 -7 -6 -1 -5 -5 -6
[55] -7 -3 -1 -6 -1 -2 -2 -1 -5 -7 -3 -4 -7 -9 -7 -1 -10 -4
[73] -8 -8 -5 -8 -7 -3 -4 -5 -10 -10 -2 -3 -7 -8 -8 -2 -8 -5
[91] -2 -1 -5 -10 -5 -4 -1 -3 -4 -6
CubeRoot(x2)
[1] -2.154435 -2.154435 -1.259921 -1.817121 -1.709976 -1.259921 -1.000000 [8] -2.000000 -1.912931 -2.000000 -1.587401 -2.080084 -1.000000 -1.817121 [15] -2.154435 -1.587401 -1.000000 -1.817121 -1.587401 -1.259921 -1.000000 [22] -1.709976 -1.709976 -1.912931 -1.259921 -1.912931 -2.080084 -2.000000 [29] -1.587401 -2.154435 -1.259921 -1.912931 -2.080084 -1.442250 -2.000000 [36] -1.000000 -1.000000 -1.817121 -1.912931 -2.000000 -1.442250 -1.587401 [43] -1.259921 -2.154435 -1.817121 -2.080084 -1.259921 -1.587401 -2.154435 [50] -1.442250 -1.259921 -1.709976 -1.912931 -1.259921 -2.000000 -2.000000 [57] -1.817121 -1.442250 -1.587401 -1.587401 -2.000000 -2.080084 -1.587401 [64] -1.442250 -1.817121 -1.442250 -1.442250 -1.587401 -1.259921 -1.000000 [71] -1.709976 -1.442250 -1.587401 -1.587401 -2.000000 -1.709976 -1.709976 [78] -2.080084 -1.912931 -2.000000 -2.000000 -1.259921 -1.442250 -1.912931 [85] -1.912931 -1.912931 -1.259921 -2.154435 -2.080084 -2.080084 -1.259921 [92] -1.912931 -1.259921 -1.259921 -1.259921 -2.080084 -2.000000 -1.259921 [99] -2.000000 -2.000000
Live Demo
x3<-sample(-100:-1,50,replace=TRUE)
x3
[1] -5 -57 -31 -21 -9 -47 -13 -27 -59 -86 -94 -8 -41 -37 -5
[16] -88 -15 -75 -24 -52 -59 -100 -8 -51 -57 -61 -91 -46 -56 -24
[31] -62 -95 -17 -22 -83 -83 -37 -37 -52 -49 -29 -9 -67 -88 -100
[46] -15 -81 -32 -88 -48
CubeRoot(x3)
[1] -2.620741 -3.848501 -4.562903 -3.732511 -3.870877 -3.583048 -4.290840 [8] -3.419952 -3.174802 -2.000000 -3.779763 -4.121285 -2.620741 -4.272659 [15] -3.476027 -3.503398 -3.072317 -1.000000 -4.235824 -4.217163 -4.121285 [22] -3.556893 -4.235824 -4.061548 -1.442250 -3.892996 -3.756286 -3.239612 [29] -4.081655 -4.431048 -4.530655 -4.041240 -3.448217 -2.289428 -4.101566 [36] -4.272659 -2.000000 -3.914868 -4.326749 -4.578857 -4.160168 -2.289428 [43] -3.608826 -3.448217 -3.556893 -2.000000 -3.107233 -2.080084 -3.271066 [50] -2.410142
Live Demo
x4<-sample(-1000:-1,50)
x4
[1] -466 -806 -821 -759 -685 -503 -271 -340 -170 -437 -667 -943 -84 -78 -846
[16] -957 -383 -776 -351 -473 -77 -508 -958 -655 -408 -725 -773 -780 -738 -575
[31] -751 -240 -696 -154 -390 -823 -488 -516 -787 -450 -795 -775 -676 -724 -803
[46] -783 -566 -829 -645 -249
CubeRoot(x4)
[1] -7.146569 -9.461525 -3.914868 -7.080699 -9.483814 -8.987637 -9.739963 [8] -3.239612 -7.947574 -8.680124 -5.981424 -9.065368 -6.205822 -7.894447 [15] -8.836556 -7.747311 -4.121285 -5.838272 -6.634287 -9.420387 -8.173302 [22] -8.719760 -6.965820 -8.900130 -9.582840 -9.827025 -8.358678 -1.259921 [29] -7.067377 -6.153449 -9.809736 -8.545317 -9.959839 -9.868272 -4.379519 [36] -8.193213 -3.000000 -9.468966 -5.528775 -7.100588 -4.702669 -5.167649 [43] -5.604079 -9.561011 -9.888767 -3.659306 -5.828477 -8.879040 -6.656930 [50] -8.962809
Live Demo
x5<-sample(-999:-100,50)
x5
[1] -425 -563 -342 -776 -860 -985 -263 -871 -350 -845 -426 -509 -511 -706 -672
[16] -334 -789 -843 -372 -535 -247 -495 -249 -326 -476 -687 -365 -680 -549 -299
[31] -893 -628 -638 -284 -368 -886 -758 -167 -360 -553 -347 -128 -123 -681 -280
[46] -419 -108 -925 -763 -314
CubeRoot(x5)
[1] -9.405339 -5.217103 -9.321698 -6.526519 -7.791488 -8.767719 -5.838272 [8] -6.307994 -5.828477 -8.153294 -7.984344 -9.181500 -9.976612 -9.531750 [15] -6.000000 -9.830476 -9.953114 -7.968627 -5.667051 -7.524365 -6.875344 [22] -6.811285 -8.305865 -8.051748 -8.604252 -7.386437 -9.672740 -9.256022 [29] -6.626705 -8.971101 -5.383213 -9.542744 -9.267680 -8.372967 -7.434994 [36] -6.723951 -9.679860 -6.349604 -9.340839 -9.929504 -8.429638 -8.874810 [43] -8.173302 -7.299894 -6.179747 -7.736188 -7.963374 -8.715373 -4.747459 [50] -4.959676 | [
{
"code": null,
"e": 1212,
"s": 1062,
"text": "There is no function in R to find the cube root of negative values, hence we need to create that. The code to create the function is as shown below −"
},
{
"code": null,
"e": 1261,
"s": 1212,
"text": "CubeRoot<-function(x){\n sign(x)*abs(x)^(1/3)\n}"
},
{
"code": null,
"e": 1408,
"s": 1261,
"text": "Now we just need to pass the values in the function to find the cube root of those values. These values can be a vector or a single value as well."
},
{
"code": null,
"e": 1473,
"s": 1408,
"text": "Examples of finding the cube roots using our function CubeRoot −"
},
{
"code": null,
"e": 1486,
"s": 1473,
"text": "CubeRoot(-3)"
},
{
"code": null,
"e": 1499,
"s": 1486,
"text": "[1] -1.44225"
},
{
"code": null,
"e": 1512,
"s": 1499,
"text": "CubeRoot(-9)"
},
{
"code": null,
"e": 1526,
"s": 1512,
"text": "[1] -2.080084"
},
{
"code": null,
"e": 1540,
"s": 1526,
"text": "CubeRoot(-27)"
},
{
"code": null,
"e": 1547,
"s": 1540,
"text": "[1] -3"
},
{
"code": null,
"e": 1562,
"s": 1547,
"text": "CubeRoot(-125)"
},
{
"code": null,
"e": 1569,
"s": 1562,
"text": "[1] -5"
},
{
"code": null,
"e": 1585,
"s": 1569,
"text": "CubeRoot(-1000)"
},
{
"code": null,
"e": 1593,
"s": 1585,
"text": "[1] -10"
},
{
"code": null,
"e": 1607,
"s": 1593,
"text": "CubeRoot(-64)"
},
{
"code": null,
"e": 1614,
"s": 1607,
"text": "[1] -4"
},
{
"code": null,
"e": 1627,
"s": 1614,
"text": "CubeRoot(-1)"
},
{
"code": null,
"e": 1635,
"s": 1627,
"text": "[1] -1\n"
},
{
"code": null,
"e": 1649,
"s": 1635,
"text": "CubeRoot(-81)"
},
{
"code": null,
"e": 1663,
"s": 1649,
"text": "[1] -4.326749"
},
{
"code": null,
"e": 1678,
"s": 1663,
"text": "CubeRoot(-216)"
},
{
"code": null,
"e": 1685,
"s": 1678,
"text": "[1] -6"
},
{
"code": null,
"e": 1718,
"s": 1685,
"text": "CubeRoot(c(-1,-9,-64,-125,-216))"
},
{
"code": null,
"e": 1772,
"s": 1718,
"text": "[1] -1.000000 -2.080084 -4.000000 -5.000000 -6.000000"
},
{
"code": null,
"e": 1811,
"s": 1772,
"text": "x1<-c(-8,-100,-500,-1000,-5000,-10000)"
},
{
"code": null,
"e": 1824,
"s": 1811,
"text": "CubeRoot(x1)"
},
{
"code": null,
"e": 1891,
"s": 1824,
"text": "[1] -2.000000 -4.641589 -7.937005 -10.000000 -17.099759 -21.544347"
},
{
"code": null,
"e": 1902,
"s": 1891,
"text": " Live Demo"
},
{
"code": null,
"e": 1941,
"s": 1902,
"text": "x2<-sample(-10:-1,100,replace=TRUE)\nx2"
},
{
"code": null,
"e": 2276,
"s": 1941,
"text": "[1] -3 -1 -1 -4 -10 -7 -7 -2 -4 -8 -1 -9 -8 -6 -9 -5 -6 -5\n[19] -2 -8 -1 -8 -5 -9 -3 -7 -9 -10 -3 -2 -1 -9 -1 -8 -8 -6\n[37] -5 -4 -4 -2 -3 -3 -2 -4 -8 -7 -5 -7 -7 -6 -1 -5 -5 -6\n[55] -7 -3 -1 -6 -1 -2 -2 -1 -5 -7 -3 -4 -7 -9 -7 -1 -10 -4\n[73] -8 -8 -5 -8 -7 -3 -4 -5 -10 -10 -2 -3 -7 -8 -8 -2 -8 -5\n[91] -2 -1 -5 -10 -5 -4 -1 -3 -4 -6"
},
{
"code": null,
"e": 2289,
"s": 2276,
"text": "CubeRoot(x2)"
},
{
"code": null,
"e": 3362,
"s": 2289,
"text": "[1] -2.154435 -2.154435 -1.259921 -1.817121 -1.709976 -1.259921 -1.000000 [8] -2.000000 -1.912931 -2.000000 -1.587401 -2.080084 -1.000000 -1.817121 [15] -2.154435 -1.587401 -1.000000 -1.817121 -1.587401 -1.259921 -1.000000 [22] -1.709976 -1.709976 -1.912931 -1.259921 -1.912931 -2.080084 -2.000000 [29] -1.587401 -2.154435 -1.259921 -1.912931 -2.080084 -1.442250 -2.000000 [36] -1.000000 -1.000000 -1.817121 -1.912931 -2.000000 -1.442250 -1.587401 [43] -1.259921 -2.154435 -1.817121 -2.080084 -1.259921 -1.587401 -2.154435 [50] -1.442250 -1.259921 -1.709976 -1.912931 -1.259921 -2.000000 -2.000000 [57] -1.817121 -1.442250 -1.587401 -1.587401 -2.000000 -2.080084 -1.587401 [64] -1.442250 -1.817121 -1.442250 -1.442250 -1.587401 -1.259921 -1.000000 [71] -1.709976 -1.442250 -1.587401 -1.587401 -2.000000 -1.709976 -1.709976 [78] -2.080084 -1.912931 -2.000000 -2.000000 -1.259921 -1.442250 -1.912931 [85] -1.912931 -1.912931 -1.259921 -2.154435 -2.080084 -2.080084 -1.259921 [92] -1.912931 -1.259921 -1.259921 -1.259921 -2.080084 -2.000000 -1.259921 [99] -2.000000 -2.000000"
},
{
"code": null,
"e": 3373,
"s": 3362,
"text": " Live Demo"
},
{
"code": null,
"e": 3412,
"s": 3373,
"text": "x3<-sample(-100:-1,50,replace=TRUE)\nx3"
},
{
"code": null,
"e": 3627,
"s": 3412,
"text": "[1] -5 -57 -31 -21 -9 -47 -13 -27 -59 -86 -94 -8 -41 -37 -5\n[16] -88 -15 -75 -24 -52 -59 -100 -8 -51 -57 -61 -91 -46 -56 -24\n[31] -62 -95 -17 -22 -83 -83 -37 -37 -52 -49 -29 -9 -67 -88 -100\n[46] -15 -81 -32 -88 -48"
},
{
"code": null,
"e": 3640,
"s": 3627,
"text": "CubeRoot(x3)"
},
{
"code": null,
"e": 4178,
"s": 3640,
"text": "[1] -2.620741 -3.848501 -4.562903 -3.732511 -3.870877 -3.583048 -4.290840 [8] -3.419952 -3.174802 -2.000000 -3.779763 -4.121285 -2.620741 -4.272659 [15] -3.476027 -3.503398 -3.072317 -1.000000 -4.235824 -4.217163 -4.121285 [22] -3.556893 -4.235824 -4.061548 -1.442250 -3.892996 -3.756286 -3.239612 [29] -4.081655 -4.431048 -4.530655 -4.041240 -3.448217 -2.289428 -4.101566 [36] -4.272659 -2.000000 -3.914868 -4.326749 -4.578857 -4.160168 -2.289428 [43] -3.608826 -3.448217 -3.556893 -2.000000 -3.107233 -2.080084 -3.271066 [50] -2.410142"
},
{
"code": null,
"e": 4189,
"s": 4178,
"text": " Live Demo"
},
{
"code": null,
"e": 4216,
"s": 4189,
"text": "x4<-sample(-1000:-1,50)\nx4"
},
{
"code": null,
"e": 4482,
"s": 4216,
"text": "[1] -466 -806 -821 -759 -685 -503 -271 -340 -170 -437 -667 -943 -84 -78 -846\n[16] -957 -383 -776 -351 -473 -77 -508 -958 -655 -408 -725 -773 -780 -738 -575\n[31] -751 -240 -696 -154 -390 -823 -488 -516 -787 -450 -795 -775 -676 -724 -803\n[46] -783 -566 -829 -645 -249"
},
{
"code": null,
"e": 4495,
"s": 4482,
"text": "CubeRoot(x4)"
},
{
"code": null,
"e": 5033,
"s": 4495,
"text": "[1] -7.146569 -9.461525 -3.914868 -7.080699 -9.483814 -8.987637 -9.739963 [8] -3.239612 -7.947574 -8.680124 -5.981424 -9.065368 -6.205822 -7.894447 [15] -8.836556 -7.747311 -4.121285 -5.838272 -6.634287 -9.420387 -8.173302 [22] -8.719760 -6.965820 -8.900130 -9.582840 -9.827025 -8.358678 -1.259921 [29] -7.067377 -6.153449 -9.809736 -8.545317 -9.959839 -9.868272 -4.379519 [36] -8.193213 -3.000000 -9.468966 -5.528775 -7.100588 -4.702669 -5.167649 [43] -5.604079 -9.561011 -9.888767 -3.659306 -5.828477 -8.879040 -6.656930 [50] -8.962809"
},
{
"code": null,
"e": 5044,
"s": 5033,
"text": " Live Demo"
},
{
"code": null,
"e": 5072,
"s": 5044,
"text": "x5<-sample(-999:-100,50)\nx5"
},
{
"code": null,
"e": 5341,
"s": 5072,
"text": "[1] -425 -563 -342 -776 -860 -985 -263 -871 -350 -845 -426 -509 -511 -706 -672\n[16] -334 -789 -843 -372 -535 -247 -495 -249 -326 -476 -687 -365 -680 -549 -299\n[31] -893 -628 -638 -284 -368 -886 -758 -167 -360 -553 -347 -128 -123 -681 -280\n[46] -419 -108 -925 -763 -314"
},
{
"code": null,
"e": 5354,
"s": 5341,
"text": "CubeRoot(x5)"
},
{
"code": null,
"e": 5892,
"s": 5354,
"text": "[1] -9.405339 -5.217103 -9.321698 -6.526519 -7.791488 -8.767719 -5.838272 [8] -6.307994 -5.828477 -8.153294 -7.984344 -9.181500 -9.976612 -9.531750 [15] -6.000000 -9.830476 -9.953114 -7.968627 -5.667051 -7.524365 -6.875344 [22] -6.811285 -8.305865 -8.051748 -8.604252 -7.386437 -9.672740 -9.256022 [29] -6.626705 -8.971101 -5.383213 -9.542744 -9.267680 -8.372967 -7.434994 [36] -6.723951 -9.679860 -6.349604 -9.340839 -9.929504 -8.429638 -8.874810 [43] -8.173302 -7.299894 -6.179747 -7.736188 -7.963374 -8.715373 -4.747459 [50] -4.959676"
}
]
|
Debugging a Machine Learning model written in TensorFlow and Keras | by Lak Lakshmanan | Towards Data Science | In this article, you get to look over my shoulder as I go about debugging a TensorFlow model. I did a lot of dumb things, so please don’t judge.
You can see the final (working) model on GitHub. I’m building a model to predict lightning 30 minutes into the future and plan to present it at the American Meteorological Society. The basic idea is to create 64x64 image patches around each pixel of infrared and Global Lightning Mapper (GLM) GOES-16 data and label the pixel as “has_ltg=1” if the lighting image actually occurs 30 minutes later within a 16x16 image patch around the pixel.
A model trained in this way can be used to predict lightning 30 minutes ahead in real-time given the current infrared and GLM data.
I wrote up a convnet model borrowing liberally from the training loop of the ResNet model written for the TPU and adapted the input function (to read my data, not JPEG) and the model (a simple convolutional network, not ResNet).
The key bit of the code to get the input into a tensor:
parsed = tf.parse_single_example( example_data, { 'ref': tf.VarLenFeature(tf.float32), 'ltg': tf.VarLenFeature(tf.float32), 'has_ltg': tf.FixedLenFeature([], tf.int64, 1), })parsed['ref'] = _sparse_to_dense(parsed['ref'], height * width)parsed['ltg'] = _sparse_to_dense(parsed['ltg'], height * width)label = tf.cast(tf.reshape(parsed['has_ltg'], shape=[]), dtype=tf.int32)
Essentially, each TensorFlow record (created by an Apache Beam pipeline) consists of ref, ltg and has_ltg fields. The ref and ltg are variable length arrays that are reshaped into dense 64x64 matrices (using tf.sparse_tensor_to_dense). The label is simply 0 or 1.
Then, I take the two parsed images and stack them together:
stacked = tf.concat([parsed['ref'], parsed['ltg']], axis=1)img = tf.reshape(stacked, [height, width, n_channels])
At this point, I have a tensor that is [?, 64, 64, 2], i.e. a batch of 2-channel images. The rest of the input pipeline in make_input_fn (listing files, reading the files via parallel interleave, preprocessing the data, making the shape static, and prefetching) was essentially just copy-pasted from the ResNet code.
I developed the code by running the trainer locally for a few steps with a small batch size:
gcloud ml-engine local train \ --module-name=trainer.train_cnn --package-path=${PWD}/ltgpred/trainer \ -- \ --train_steps=10 --num_eval_records=512 --train_batch_size=16 \ --job-dir=$OUTDIR --train_data_path=${DATADIR}/train* --eval_data_path=${DATADIR}/eval*
Then, I ran it on a larger dataset on Cloud ML Engine using a large machine with a heftier GPU:
gcloud ml-engine jobs submit training $JOBNAME \ --module-name=trainer.train_cnn --package-path=${PWD}/ltgpred/trainer --job-dir=$OUTDIR \ --region=${REGION} --scale-tier=CUSTOM --config=largemachine.yaml \ --python-version=3.5 --runtime-version=1.8 \ -- \ --train_data_path=${DATADIR}/train* --eval_data_path=${DATADIR}/eval* \ --train_steps=5000 --train_batch_size=256 \ --num_eval_records=128000
This was useful. Much of my debugging and development was done by running locally. This way I could work disconnected and didn’t need a GPU mounted on my machine.
Once I had the code written and I ran it, I discovered that the model started quickly producing suspiciously identical losses:
and reached an accuracy metric that was stubbornly stuck at this number starting at epoch 1000:
'rmse': 0.49927762, 'accuracy': 0.6623125,
When a machine learning model won’t learn, there are a few usual suspects. I tried changing the initialization. By default, TensorFlow uses zeros_initializer [edit: Turns out I didn’t need to do this — tf.layers.conv2d inherits from Keras’ Conv2D which uses glorot_uniform which is the same as Xavier]. How about using Xavier (which uses small initial values), and setting the random seed for repeatability?
xavier = tf.contrib.layers.xavier_initializer(seed=13)c1 = tf.layers.conv2d( convout, filters=nfilters, kernel_size=ksize, kernel_initializer=xavier, strides=1, padding='same', activation=tf.nn.relu)
How about changing the gradient from the sophisticated AdamOptimizer to the trusty standby GradientDescentOptimizer?
How about reducing the learning rate from 0.01 to 1e-6?
None of these helped, but that’s what I first tried.
Was my input function perhaps returning the same data each time? That would explain why the model gets stuck. How do I know what the input function is reading in?
An easy way to verify that the input function is correct is to simply print out the values read. However, you can’t just print a tensor:
print(img)
That will simply print out the metadata of the tensor, not its values. Instead, you need to evaluate the value of the tensor while the program is being executed:
print(img.eval(sess=...))
and even that won’t work because the Estimator API doesn’t give you a handle to the session. The solution is to use tf.Print:
img = tf.Print(img, [img], "image values=")
What this does is to insert the print node between the original img node and the new img node, so that the value gets printed before the image node gets used again:
Once I did this, though, I got only the first 3 or 4 values (By default, tf.Print doesn’t print the whole tensor ) and they were mostly zero. Are they zero because satellite images tend to have a lot of zeros or is it zero because my input pipeline has a bug? Simply printing the image is not a great idea. So, I decided to print out statistics of the inputs:
numltg = tf.reduce_sum(labels)ref = tf.slice(img, [0, 0, 0, 0], [-1, -1, -1, 1])meanref = tf.reduce_mean(ref, [1, 2])ltg = tf.slice(img, [0, 0, 0, 1], [-1, -1, -1, 1])meanltg = tf.reduce_mean(ltg, [1, 2])ylogits = tf.Print(ylogits, [numltg, meanref, meanltg, ylogits], "...")
The reduce_* functions in TensorFlow allow you to sum along an axis. Hence the first function reduce_sum(labels) computes the sum of the labels over the batch. Since the label is 0 or 1, this sum tells me the number of lighting examples in the batch.
I also want to print the mean of the reflectivity and lightning input image patches. For that, I want to do a sum over the height and width but keep each example and channel separate — that’s why you see [1,2] in the reduce_mean calls. The first tf.slice gets the first channel, and the second slice gets me the second channel (-1 in tf.slice tells TensorFlow to get all the elements in that dimension).
Notice also that I have inserted the Print node at the location of ylogits and get to print a whole list of tensors. This is important — you have to stick in the Print() into the graph at a node that actually gets used. If I had done:
numltg = tf.Print(numltg, [numltg, meanref, meanltg], "...")
the whole branch would have been optimized away since my model doesn’t actually use numltg anywhere!
Once I ran the code, I found that each batch had a good (and differing) mix of lightning points, that the means looked sort of similar within each batch, but were different from batch to batch.
Although this is not the problem we are trying to solve, this similarity of means by batch is quite odd. Looking over the code with this curiosity in mind, I found that I had hardcoded a shuffle size:
dataset = dataset.shuffle(1024)
Changing this to
dataset = dataset.shuffle(batch_size * 50)
resolved the batch problem.
The issue is that because the data is created from sliding windows, successive examples tend to be highly correlated, so I need to shuffle over a large enough buffer that we get examples from a different part of the satellite image (or better still, different images). In the case of ResNet, each training example is a completely different image, so this is not an issue they were concerned about. Copy-paste strikes again!
But back to the original problem. Why are the accuracy and RMSE stuck? I kinda lucked out here. I had to insert the tf.Print() somewhere and so I stuck into a node that I knew I needed — on the output node of my model function (ylogits). I also happened to print out ylogits as well and lo and behold ... while the inputs were all different values each time, ylogits started out random but quickly became zero.
Why is the ylogits zero? Looking carefully at the ylogits calculation, I noticed that I had written:
ylogits = tf.layers.dense( convout, 1, activation=tf.nn.relu, kernel_initializer=xavier)
Oops! By setting the ReLu activation function on the output dense layer, I had made sure ylogits would never be negative. Meanwhile, lightning is rarer than non-lightning, so the optimizer was pushing ylogits to the smallest possible value it could take. Which is zero. Because ReLu saturates below zero, it is possible for things to get stuck there.
The last-but-one-layer of a classification network is like the last layer of a regression network. It has to be:
ylogits = tf.layers.dense( convout, 1, activation=None, kernel_initializer=xavier)
Silly, silly, bug. Found and fixed. Whew!
Now, when I ran it though, I didn’t get a stuck accuracy metric. Worse. I got ... “NaN loss during training.” If there is anything that will strike terror into the hearts of a ML practitioner, it’s NaN losses. Oh, well, if I can figure this thing out, I will get a blog post out of it.
As with a model that doesn’t train, there are a few usual suspects for NaN losses. Trying to compute cross entropy loss yourself is one of them. But I wasn’t doing that. I was computing the loss as:
loss = tf.reduce_mean( tf.nn.sigmoid_cross_entropy_with_logits( logits=tf.reshape(ylogits, [-1]), labels=tf.cast(labels, dtype=tf.float32)))
This should be numerically stable. The other problem is a learning rate that is too high. I switched back to AdamOptimizer and tried setting a low learning rate (1e-6). No go.
Another problem is that the input data might itself contain NaNs. This should not be possible — one of the benefits of using TFRecords is that the TFRecordWriter will not accept NaN values. Just to make sure, I went back to my input pipeline and added np.nan_to_num to the piece of code that inserted arrays into the TFRecord:
def _array_feature(value): value = np.nan_to_num(value.flatten()) return tf.train.Feature(float_list=tf.train.FloatList(value=value))
Still no go.
Maybe there are way too many weights? I made the number of layers in my model configurable and tried different numbers and smaller kernel sizes:
convout = imgfor layer in range(nlayers): nfilters = (nfil // (layer+1)) nfilters = 1 if nfilters < 1 else nfilters # convolution c1 = tf.layers.conv2d( convout, filters=nfilters, kernel_size=ksize, kernel_initializer=xavier, strides=1, padding='same', activation=tf.nn.relu) # maxpool convout = tf.layers.max_pooling2d(c1, pool_size=2, strides=2, padding='same') print('Shape of output of {}th layer = {} {}'.format( layer + 1, convout.shape, convout))outlen = convout.shape[1] * convout.shape[2] * convout.shape[3]p2flat = tf.reshape(convout, [-1, outlen]) # flattenedprint('Shape of flattened conv layers output = {}'.format(p2flat.shape))
Still no go. The NaN loss remained.
What if I completely remove the deep learning model? Remember my debugging statistics on the input image? What if we try to train a model to predict lighting based on just those engineered features:
halfsize = params['predsize']qtrsize = halfsize // 2ref_smbox = tf.slice(img, [0, qtrsize, qtrsize, 0], [-1, halfsize, halfsize, 1])ltg_smbox = tf.slice(img, [0, qtrsize, qtrsize, 1], [-1, halfsize, halfsize, 1])ref_bigbox = tf.slice(img, [0, 0, 0, 0], [-1, -1, -1, 1])ltg_bigbox = tf.slice(img, [0, 0, 0, 1], [-1, -1, -1, 1])engfeat = tf.concat([ tf.reduce_max(ref_bigbox, [1, 2]), # [?, 64, 64, 1] -> [?, 1] tf.reduce_max(ref_smbox, [1, 2]), tf.reduce_mean(ref_bigbox, [1, 2]), tf.reduce_mean(ref_smbox, [1, 2]), tf.reduce_mean(ltg_bigbox, [1, 2]), tf.reduce_mean(ltg_smbox, [1, 2])], axis=1)ylogits = tf.layers.dense( engfeat, 1, activation=None, kernel_initializer=xavier)
I decided to create two sets of statistics, one in a 64x64 box and the other in a 16x16 one and create a logistic regression model with just these 6 input features.
No go. Still NaN. This is very, very strange. A linear model should have never NaN-out. Mathematically, this is crazy.
But just before it NaN-ed out, the model reached a 75% accuracy. That’s awfully promising. But this NaN thing is getting to be super annoying. The funny thing is that just before it “diverges” with loss = NaN, the model hasn’t been diverging at all, the loss has been going down:
Poking around to find out whether there is an alternate way to compute the loss, I discover that there is now a convenience function:
loss = tf.losses.sigmoid_cross_entropy(labels, tf.reshape(ylogits, [-1]))
Of course, that probably won’t fix anything but it’s better to use this function rather than call reduce_mean myself. But while here, let’s add asserts to narrow down the problem:
with tf.control_dependencies([ tf.Assert(tf.is_numeric_tensor(ylogits),[ylogits]), tf.assert_non_negative(labels, [labels]), tf.assert_less_equal(labels, 1, [labels])]): loss = tf.losses.sigmoid_cross_entropy(labels, tf.reshape(ylogits, [-1]))
Essentially, I assert that ylogits is numeric, and that each label is between 0 and 1. Only if these conditions are met do I compute the loss. Otherwise, the program is supposed to throw an error.
The assertions don’t trigger, but the program still ends with a NaN loss. At this point, it seems clear the problem does not lie in the input data (because I have done a nan_to_num there) or in our model calculation (because assertions don’t trigger) itself. Could it instead be in the back-propagation, possibly in the gradient computation?
For example, perhaps an unusual (but correct) example leads to unexpectedly high gradient magnitudes. Let’s just limit the effect of such unusual examples by clipping the gradient:
optimizer = tf.train.AdamOptimizer(learning_rate=0.001)optimizer = tf.contrib.estimator.clip_gradients_by_norm( optimizer, 5)train_op = optimizer.minimize(loss, tf.train.get_global_step())
That didn’t help either.
If there are lot of very similar inputs, it is possible for the weights themselves to blow up. Over time, you might get a very high positive magnitude associated with one input node and a very high negative magnitude associated with the next input node. One way to get the network to avoid such a situation is to penalize high magnitude weights by adding an extra term to the loss function:
l2loss = tf.add_n( [tf.nn.l2_loss(v) for v in tf.trainable_variables()])loss = loss + 0.001 * l2loss
This gets all the trainable variables (weights and biases) and adds a penalty to the loss based on the value of those trainable variables. Ideally, we penalize just the weights (not the biases), but this is fine just for trying out.
Poking around some more, I realize that the documentation for the AdamOptimizer explains the default epsilon value of 1e-8 may be problematic. Essentially, small values of epsilon cause instability even though the purpose of the epsilon is to prevent a divide-by-zero. This begs the question of why this is the default, but let’s try the larger value that is recommended.
optimizer = tf.train.AdamOptimizer( learning_rate=params['learning_rate'], epsilon=0.1)
That pushes the NaN further out, but it still fails.
Another reason for this could be CUDA bugs and the like. Let’s try training on a different hardware (with P100 instead of Tesla K80) to see if the problem persists.
trainingInput: scaleTier: CUSTOM masterType: complex_model_m_p100
Still no go.
Sometimes, when left with an intractable bug, it is better to just try rewriting the model in a completely different way.
So, I decided to rewrite the model in Keras. This will also give me the opportunity to learn Keras, something I’ve been meaning to do for a while. Lemonade out of lemons and all that.
Creating a CNN with batchnorm (which will help keep gradients in range) is quite easy in Keras. (Thank you, Francois). So easy that I put batchnorm everywhere.
img = keras.Input(shape=[height, width, 2])cnn = keras.layers.BatchNormalization()(img)for layer in range(nlayers): nfilters = nfil * (layer + 1) cnn = keras.layers.Conv2D(nfilters, (ksize, ksize), padding='same')(cnn) cnn = keras.layers.Activation('elu')(cnn) cnn = keras.layers.BatchNormalization()(cnn) cnn = keras.layers.MaxPooling2D(pool_size=(2, 2))(cnn) cnn = keras.layers.Dropout(dprob)(cnn)cnn = keras.layers.Flatten()(cnn)ltgprob = keras.layers.Dense(10, activation='sigmoid')(cnn)
Notice also that the final layer directly adds a sigmoid activation. There is no need to muck around with the logits because the optimization takes care of the numeric problems for us:
optimizer = tf.keras.optimizers.Adam(lr=params['learning_rate'])model.compile(optimizer=optimizer, loss='binary_crossentropy', metrics=['accuracy', 'mse'])
Nice!
Unfortunately (you know it by now), I still got NaNs!
Gaah. Okay, back to the drawing board. Let’s do all the things we did in TensorFlow in Keras.
First step is to forget about all this deep learning stuff and build a linear model. How do you do that? I have an image. I need to do feature engineering and send it to a Dense layer. That means, in Keras, that I have to write my own layer to do the feature engineering:
def create_feateng_model(params): # input is a 2-channel image height = width = 2 * params[’predsize’] img = keras.Input(shape=[height, width, 2]) engfeat = keras.layers.Lambda( lambda x: engineered_features(x, height//2))(img) ltgprob = keras.layers.Dense(1, activation=’sigmoid’)(engfeat) # create a model model = keras.Model(img, ltgprob)
The engineered_features is exactly the same TensorFlow function as before! The key idea is that to wrap a TensorFlow function into a Keras layer, you can use a Lambda layer and invoke the TensorFlow function.
But I want to print out the layer to make sure that the numbers flowing through are correct. How do I do that? tf.Print() won’t work because, well, I don’t have tensors. I have Keras layers.
Well, tf.Print() is a TensorFlow function and so, use the same Lambda layer trick:
def print_layer(layer, message, first_n=3, summarize=1024): return keras.layers.Lambda(( lambda x: tf.Print(x, [x], message=message, first_n=first_n, summarize=summarize)))(layer)
which can then be invoked as:
engfeat = print_layer(engfeat, "engfeat=")
Clipping the gradient in Keras? Easy! Every optimizer supports clipnorm.
optimizer = tf.keras.optimizers.Adam(lr=params['learning_rate'], clipnorm=1.)
Hey, I’m liking this Keras thing — it gives me a nice, simple API. Plus, it interoperates nicely with TensorFlow to give me low-level control whenever I need it.
Oh, right. I still have the NaN problem
One final thing, something I kinda discounted. The NaN problem could also arise from unscaled data. But my reflectivity and lightning data are both in the range [0,1]. So, I don’t really need to scale things at all.
Still, I’m at a loose end. Why don’t I normalize the image data (subtract the mean, divide by the variance) and see if it helps.
To compute the variance, I need to walk through the entire dataset, and so this is a job for Beam. I could do this in TensorFlow Transform, but for now, let me hack it in Beam.
Since I am rewriting my pipeline, I might as well fix the shuffling issue (see section 2d) once and for all. Increasing the shuffle buffersize was a hack. I really don’t want to write the data in the order that I created the image patches. Let’s randomize the order of the image patches in Apache Beam:
# shuffle the examples so that each small batch doesn't contain# highly correlated recordsexamples = (examples | '{}_reshuffleA'.format(step) >> beam.Map( lambda t: (random.randint(1, 1000), t)) | '{}_reshuffleB'.format(step) >> beam.GroupByKey() | '{}_reshuffleC'.format(step) >> beam.FlatMap(lambda t: t[1]))
Essentially, I assign a random key (between 1 and 1000) to each record, group by that random key, remove the key and write out the records. Now, successive image patches will not follow one after the other.
How do I compute the variance in Apache Beam? I did what I always do, search on StackOverflow for something I can copy-paste. Unfortunately, all I found was an unanswered question. Oh, well, buckle down and write a custom Combiner:
import apache_beam as beamimport numpy as npclass MeanStddev(beam.CombineFn): def create_accumulator(self): return (0.0, 0.0, 0) # x, x^2, countdef add_input(self, sum_count, input): (sum, sumsq, count) = sum_count return sum + input, sumsq + input*input, count + 1def merge_accumulators(self, accumulators): sums, sumsqs, counts = zip(*accumulators) return sum(sums), sum(sumsqs), sum(counts)def extract_output(self, sum_count): (sum, sumsq, count) = sum_count if count: mean = sum / count variance = (sumsq / count) - mean*mean # -ve value could happen due to rounding stddev = np.sqrt(variance) if variance > 0 else 0 return { 'mean': mean, 'variance': variance, 'stddev': stddev, 'count': count } else: return { 'mean': float('NaN'), 'variance': float('NaN'), 'stddev': float('NaN'), 'count': 0 } [1.3, 3.0, 4.2] | beam.CombineGlobally(MeanStddev())
Note the workflow here — I can quickly test it on a list of numbers to make sure it works.
Then, I went and added the answer to StackOverflow. Maybe all I need is some good karma ...
I can then go to my pipeline code and add:
if step == 'train': _ = (examples | 'get_values' >> beam.FlatMap( lambda x : [(f, x[f]) for f in ['ref', 'ltg']]) | 'compute_stats' >> beam.CombinePerKey(MeanStddev()) | 'write_stats' >> beam.io.Write(beam.io.WriteToText( os.path.join(options['outdir'], 'stats'), num_shards=1)) )
Essentially, I pull out example[‘ref’] and example[‘ltg’] and create tuples that I group by key. Then, I can compute the mean and standard deviation of every pixel in both these images over the entire dataset.
Once I run the pipeline, I can print the resulting statistics:
gsutil cat gs://$BUCKET/lightning/preproc/stats*('ltg', {'count': 1028242, 'variance': 0.0770683210620995, 'stddev': 0.2776118172234379, 'mean': 0.08414945119923131})('ref', {'count': 1028242, 'variance': masked, 'stddev': 0, 'mean': masked})
Masked? What the @#$@#$@# does masked mean? Turns out that Masked arrays are a special numpy thing. Masked values are not NaN and so, if you process them with Numpy, nan_to_num() won’t do anything to it. On the other hand, it looks numeric, and so all my TensorFlow assertions don’t raise. Numeric operations with a masked value results in a masked value.
Masked values are just like NaN — they will slurp your milkshake from across a room but the regular numpy and TensorFlow library methods know nothing about masking.
Since the masking happens only in the reflectivity grids (I create the lightning grids myself by accumulating lightning flashes), I have to convert the masked values to a nice number after reading
ref = goesio.read_ir_data(ir_blob_path, griddef)ref = np.ma.filled(ref, 0) # mask -> 0
and now, when I rerun the pipeline, I get reasonable values:
('ref', {'count': 1028242, 'variance': 0.07368491739234752, 'stddev': 0.27144965903892293, 'mean': 0.3200035849321707})('ltg', {'count': 1028242, 'variance': 0.0770683210620995, 'stddev': 0.2776118172234379, 'mean': 0.08414945119923131})
These are small numbers. There should be no reason to scale anything. So, let’s just train with the masking problem fixed.
This time, no NaN. Instead the program crashes and logs show:
Filling up shuffle buffer (this may take a while): 251889 of 1280000The replica master 0 ran out-of-memory and exited with a non-zero status of 9(SIGKILL)
Replica zero is the input pipeline (reading data happens on the CPU). Why does it want to read 1280000 records all at once into the shuffle buffer?
Well, now that the input data are so well shuffled by my Beam/Dataflow, I don’t even need that large a shuffle buffer (this used to be 5000, see Section 2d):
dataset = dataset.shuffle(batch_size * 50) # shuffle by a bit
And ... 12 minutes later, the training finishes with an accuracy of 83%(!!!). No NaNs anywhere.
Woo hoo!
Remember that we did only a linear model consisting of engineered features. Let’s add back the convnet in parallel. The idea is to concatenate the two dense layers, so that my model architecture can contain both the CNN layers and the feature engineering:
This is how to do this in Keras, with some batchnorm and dropouts thrown in, just because they are so easy to add:
cnn = keras.layers.BatchNormalization()(img)for layer in range(nlayers): nfilters = nfil * (layer + 1) cnn = keras.layers.Conv2D(nfilters, (ksize, ksize), padding='same')(cnn) cnn = keras.layers.Activation('elu')(cnn) cnn = keras.layers.BatchNormalization()(cnn) cnn = keras.layers.MaxPooling2D(pool_size=(2, 2))(cnn)cnn = keras.layers.Flatten()(cnn)cnn = keras.layers.Dropout(dprob)(cnn)cnn = keras.layers.Dense(10, activation='relu')(cnn)# feature engineering part of modelengfeat = keras.layers.Lambda( lambda x: engineered_features(x, height//2))(img)# concatenate the two partsboth = keras.layers.concatenate([cnn, engfeat])ltgprob = keras.layers.Dense(1, activation='sigmoid')(both)
Now, I have an accuracy of 85%. This is still a small dataset (only 60 days of satellite data) and that’s probably why the deep learning path doesn’t add that much value. So, I’ll go back and generate more data, train longer, train on the TPU etc.
But those things can wait. Right now, I’m off to celebrate. | [
{
"code": null,
"e": 317,
"s": 172,
"text": "In this article, you get to look over my shoulder as I go about debugging a TensorFlow model. I did a lot of dumb things, so please don’t judge."
},
{
"code": null,
"e": 758,
"s": 317,
"text": "You can see the final (working) model on GitHub. I’m building a model to predict lightning 30 minutes into the future and plan to present it at the American Meteorological Society. The basic idea is to create 64x64 image patches around each pixel of infrared and Global Lightning Mapper (GLM) GOES-16 data and label the pixel as “has_ltg=1” if the lighting image actually occurs 30 minutes later within a 16x16 image patch around the pixel."
},
{
"code": null,
"e": 890,
"s": 758,
"text": "A model trained in this way can be used to predict lightning 30 minutes ahead in real-time given the current infrared and GLM data."
},
{
"code": null,
"e": 1119,
"s": 890,
"text": "I wrote up a convnet model borrowing liberally from the training loop of the ResNet model written for the TPU and adapted the input function (to read my data, not JPEG) and the model (a simple convolutional network, not ResNet)."
},
{
"code": null,
"e": 1175,
"s": 1119,
"text": "The key bit of the code to get the input into a tensor:"
},
{
"code": null,
"e": 1575,
"s": 1175,
"text": "parsed = tf.parse_single_example( example_data, { 'ref': tf.VarLenFeature(tf.float32), 'ltg': tf.VarLenFeature(tf.float32), 'has_ltg': tf.FixedLenFeature([], tf.int64, 1), })parsed['ref'] = _sparse_to_dense(parsed['ref'], height * width)parsed['ltg'] = _sparse_to_dense(parsed['ltg'], height * width)label = tf.cast(tf.reshape(parsed['has_ltg'], shape=[]), dtype=tf.int32)"
},
{
"code": null,
"e": 1839,
"s": 1575,
"text": "Essentially, each TensorFlow record (created by an Apache Beam pipeline) consists of ref, ltg and has_ltg fields. The ref and ltg are variable length arrays that are reshaped into dense 64x64 matrices (using tf.sparse_tensor_to_dense). The label is simply 0 or 1."
},
{
"code": null,
"e": 1899,
"s": 1839,
"text": "Then, I take the two parsed images and stack them together:"
},
{
"code": null,
"e": 2013,
"s": 1899,
"text": "stacked = tf.concat([parsed['ref'], parsed['ltg']], axis=1)img = tf.reshape(stacked, [height, width, n_channels])"
},
{
"code": null,
"e": 2330,
"s": 2013,
"text": "At this point, I have a tensor that is [?, 64, 64, 2], i.e. a batch of 2-channel images. The rest of the input pipeline in make_input_fn (listing files, reading the files via parallel interleave, preprocessing the data, making the shape static, and prefetching) was essentially just copy-pasted from the ResNet code."
},
{
"code": null,
"e": 2423,
"s": 2330,
"text": "I developed the code by running the trainer locally for a few steps with a small batch size:"
},
{
"code": null,
"e": 2695,
"s": 2423,
"text": "gcloud ml-engine local train \\ --module-name=trainer.train_cnn --package-path=${PWD}/ltgpred/trainer \\ -- \\ --train_steps=10 --num_eval_records=512 --train_batch_size=16 \\ --job-dir=$OUTDIR --train_data_path=${DATADIR}/train* --eval_data_path=${DATADIR}/eval*"
},
{
"code": null,
"e": 2791,
"s": 2695,
"text": "Then, I ran it on a larger dataset on Cloud ML Engine using a large machine with a heftier GPU:"
},
{
"code": null,
"e": 3212,
"s": 2791,
"text": "gcloud ml-engine jobs submit training $JOBNAME \\ --module-name=trainer.train_cnn --package-path=${PWD}/ltgpred/trainer --job-dir=$OUTDIR \\ --region=${REGION} --scale-tier=CUSTOM --config=largemachine.yaml \\ --python-version=3.5 --runtime-version=1.8 \\ -- \\ --train_data_path=${DATADIR}/train* --eval_data_path=${DATADIR}/eval* \\ --train_steps=5000 --train_batch_size=256 \\ --num_eval_records=128000 "
},
{
"code": null,
"e": 3375,
"s": 3212,
"text": "This was useful. Much of my debugging and development was done by running locally. This way I could work disconnected and didn’t need a GPU mounted on my machine."
},
{
"code": null,
"e": 3502,
"s": 3375,
"text": "Once I had the code written and I ran it, I discovered that the model started quickly producing suspiciously identical losses:"
},
{
"code": null,
"e": 3598,
"s": 3502,
"text": "and reached an accuracy metric that was stubbornly stuck at this number starting at epoch 1000:"
},
{
"code": null,
"e": 3641,
"s": 3598,
"text": "'rmse': 0.49927762, 'accuracy': 0.6623125,"
},
{
"code": null,
"e": 4049,
"s": 3641,
"text": "When a machine learning model won’t learn, there are a few usual suspects. I tried changing the initialization. By default, TensorFlow uses zeros_initializer [edit: Turns out I didn’t need to do this — tf.layers.conv2d inherits from Keras’ Conv2D which uses glorot_uniform which is the same as Xavier]. How about using Xavier (which uses small initial values), and setting the random seed for repeatability?"
},
{
"code": null,
"e": 4291,
"s": 4049,
"text": "xavier = tf.contrib.layers.xavier_initializer(seed=13)c1 = tf.layers.conv2d( convout, filters=nfilters, kernel_size=ksize, kernel_initializer=xavier, strides=1, padding='same', activation=tf.nn.relu)"
},
{
"code": null,
"e": 4408,
"s": 4291,
"text": "How about changing the gradient from the sophisticated AdamOptimizer to the trusty standby GradientDescentOptimizer?"
},
{
"code": null,
"e": 4464,
"s": 4408,
"text": "How about reducing the learning rate from 0.01 to 1e-6?"
},
{
"code": null,
"e": 4517,
"s": 4464,
"text": "None of these helped, but that’s what I first tried."
},
{
"code": null,
"e": 4680,
"s": 4517,
"text": "Was my input function perhaps returning the same data each time? That would explain why the model gets stuck. How do I know what the input function is reading in?"
},
{
"code": null,
"e": 4817,
"s": 4680,
"text": "An easy way to verify that the input function is correct is to simply print out the values read. However, you can’t just print a tensor:"
},
{
"code": null,
"e": 4828,
"s": 4817,
"text": "print(img)"
},
{
"code": null,
"e": 4990,
"s": 4828,
"text": "That will simply print out the metadata of the tensor, not its values. Instead, you need to evaluate the value of the tensor while the program is being executed:"
},
{
"code": null,
"e": 5016,
"s": 4990,
"text": "print(img.eval(sess=...))"
},
{
"code": null,
"e": 5142,
"s": 5016,
"text": "and even that won’t work because the Estimator API doesn’t give you a handle to the session. The solution is to use tf.Print:"
},
{
"code": null,
"e": 5186,
"s": 5142,
"text": "img = tf.Print(img, [img], \"image values=\")"
},
{
"code": null,
"e": 5351,
"s": 5186,
"text": "What this does is to insert the print node between the original img node and the new img node, so that the value gets printed before the image node gets used again:"
},
{
"code": null,
"e": 5711,
"s": 5351,
"text": "Once I did this, though, I got only the first 3 or 4 values (By default, tf.Print doesn’t print the whole tensor ) and they were mostly zero. Are they zero because satellite images tend to have a lot of zeros or is it zero because my input pipeline has a bug? Simply printing the image is not a great idea. So, I decided to print out statistics of the inputs:"
},
{
"code": null,
"e": 6000,
"s": 5711,
"text": "numltg = tf.reduce_sum(labels)ref = tf.slice(img, [0, 0, 0, 0], [-1, -1, -1, 1])meanref = tf.reduce_mean(ref, [1, 2])ltg = tf.slice(img, [0, 0, 0, 1], [-1, -1, -1, 1])meanltg = tf.reduce_mean(ltg, [1, 2])ylogits = tf.Print(ylogits, [numltg, meanref, meanltg, ylogits], \"...\")"
},
{
"code": null,
"e": 6251,
"s": 6000,
"text": "The reduce_* functions in TensorFlow allow you to sum along an axis. Hence the first function reduce_sum(labels) computes the sum of the labels over the batch. Since the label is 0 or 1, this sum tells me the number of lighting examples in the batch."
},
{
"code": null,
"e": 6655,
"s": 6251,
"text": "I also want to print the mean of the reflectivity and lightning input image patches. For that, I want to do a sum over the height and width but keep each example and channel separate — that’s why you see [1,2] in the reduce_mean calls. The first tf.slice gets the first channel, and the second slice gets me the second channel (-1 in tf.slice tells TensorFlow to get all the elements in that dimension)."
},
{
"code": null,
"e": 6890,
"s": 6655,
"text": "Notice also that I have inserted the Print node at the location of ylogits and get to print a whole list of tensors. This is important — you have to stick in the Print() into the graph at a node that actually gets used. If I had done:"
},
{
"code": null,
"e": 6964,
"s": 6890,
"text": "numltg = tf.Print(numltg, [numltg, meanref, meanltg], \"...\")"
},
{
"code": null,
"e": 7065,
"s": 6964,
"text": "the whole branch would have been optimized away since my model doesn’t actually use numltg anywhere!"
},
{
"code": null,
"e": 7259,
"s": 7065,
"text": "Once I ran the code, I found that each batch had a good (and differing) mix of lightning points, that the means looked sort of similar within each batch, but were different from batch to batch."
},
{
"code": null,
"e": 7460,
"s": 7259,
"text": "Although this is not the problem we are trying to solve, this similarity of means by batch is quite odd. Looking over the code with this curiosity in mind, I found that I had hardcoded a shuffle size:"
},
{
"code": null,
"e": 7492,
"s": 7460,
"text": "dataset = dataset.shuffle(1024)"
},
{
"code": null,
"e": 7509,
"s": 7492,
"text": "Changing this to"
},
{
"code": null,
"e": 7552,
"s": 7509,
"text": "dataset = dataset.shuffle(batch_size * 50)"
},
{
"code": null,
"e": 7580,
"s": 7552,
"text": "resolved the batch problem."
},
{
"code": null,
"e": 8004,
"s": 7580,
"text": "The issue is that because the data is created from sliding windows, successive examples tend to be highly correlated, so I need to shuffle over a large enough buffer that we get examples from a different part of the satellite image (or better still, different images). In the case of ResNet, each training example is a completely different image, so this is not an issue they were concerned about. Copy-paste strikes again!"
},
{
"code": null,
"e": 8415,
"s": 8004,
"text": "But back to the original problem. Why are the accuracy and RMSE stuck? I kinda lucked out here. I had to insert the tf.Print() somewhere and so I stuck into a node that I knew I needed — on the output node of my model function (ylogits). I also happened to print out ylogits as well and lo and behold ... while the inputs were all different values each time, ylogits started out random but quickly became zero."
},
{
"code": null,
"e": 8516,
"s": 8415,
"text": "Why is the ylogits zero? Looking carefully at the ylogits calculation, I noticed that I had written:"
},
{
"code": null,
"e": 8606,
"s": 8516,
"text": "ylogits = tf.layers.dense( convout, 1, activation=tf.nn.relu, kernel_initializer=xavier)"
},
{
"code": null,
"e": 8957,
"s": 8606,
"text": "Oops! By setting the ReLu activation function on the output dense layer, I had made sure ylogits would never be negative. Meanwhile, lightning is rarer than non-lightning, so the optimizer was pushing ylogits to the smallest possible value it could take. Which is zero. Because ReLu saturates below zero, it is possible for things to get stuck there."
},
{
"code": null,
"e": 9070,
"s": 8957,
"text": "The last-but-one-layer of a classification network is like the last layer of a regression network. It has to be:"
},
{
"code": null,
"e": 9154,
"s": 9070,
"text": "ylogits = tf.layers.dense( convout, 1, activation=None, kernel_initializer=xavier)"
},
{
"code": null,
"e": 9196,
"s": 9154,
"text": "Silly, silly, bug. Found and fixed. Whew!"
},
{
"code": null,
"e": 9482,
"s": 9196,
"text": "Now, when I ran it though, I didn’t get a stuck accuracy metric. Worse. I got ... “NaN loss during training.” If there is anything that will strike terror into the hearts of a ML practitioner, it’s NaN losses. Oh, well, if I can figure this thing out, I will get a blog post out of it."
},
{
"code": null,
"e": 9681,
"s": 9482,
"text": "As with a model that doesn’t train, there are a few usual suspects for NaN losses. Trying to compute cross entropy loss yourself is one of them. But I wasn’t doing that. I was computing the loss as:"
},
{
"code": null,
"e": 9839,
"s": 9681,
"text": "loss = tf.reduce_mean( tf.nn.sigmoid_cross_entropy_with_logits( logits=tf.reshape(ylogits, [-1]), labels=tf.cast(labels, dtype=tf.float32)))"
},
{
"code": null,
"e": 10015,
"s": 9839,
"text": "This should be numerically stable. The other problem is a learning rate that is too high. I switched back to AdamOptimizer and tried setting a low learning rate (1e-6). No go."
},
{
"code": null,
"e": 10342,
"s": 10015,
"text": "Another problem is that the input data might itself contain NaNs. This should not be possible — one of the benefits of using TFRecords is that the TFRecordWriter will not accept NaN values. Just to make sure, I went back to my input pipeline and added np.nan_to_num to the piece of code that inserted arrays into the TFRecord:"
},
{
"code": null,
"e": 10478,
"s": 10342,
"text": "def _array_feature(value): value = np.nan_to_num(value.flatten()) return tf.train.Feature(float_list=tf.train.FloatList(value=value))"
},
{
"code": null,
"e": 10491,
"s": 10478,
"text": "Still no go."
},
{
"code": null,
"e": 10636,
"s": 10491,
"text": "Maybe there are way too many weights? I made the number of layers in my model configurable and tried different numbers and smaller kernel sizes:"
},
{
"code": null,
"e": 11327,
"s": 10636,
"text": "convout = imgfor layer in range(nlayers): nfilters = (nfil // (layer+1)) nfilters = 1 if nfilters < 1 else nfilters # convolution c1 = tf.layers.conv2d( convout, filters=nfilters, kernel_size=ksize, kernel_initializer=xavier, strides=1, padding='same', activation=tf.nn.relu) # maxpool convout = tf.layers.max_pooling2d(c1, pool_size=2, strides=2, padding='same') print('Shape of output of {}th layer = {} {}'.format( layer + 1, convout.shape, convout))outlen = convout.shape[1] * convout.shape[2] * convout.shape[3]p2flat = tf.reshape(convout, [-1, outlen]) # flattenedprint('Shape of flattened conv layers output = {}'.format(p2flat.shape))"
},
{
"code": null,
"e": 11363,
"s": 11327,
"text": "Still no go. The NaN loss remained."
},
{
"code": null,
"e": 11562,
"s": 11363,
"text": "What if I completely remove the deep learning model? Remember my debugging statistics on the input image? What if we try to train a model to predict lighting based on just those engineered features:"
},
{
"code": null,
"e": 12246,
"s": 11562,
"text": "halfsize = params['predsize']qtrsize = halfsize // 2ref_smbox = tf.slice(img, [0, qtrsize, qtrsize, 0], [-1, halfsize, halfsize, 1])ltg_smbox = tf.slice(img, [0, qtrsize, qtrsize, 1], [-1, halfsize, halfsize, 1])ref_bigbox = tf.slice(img, [0, 0, 0, 0], [-1, -1, -1, 1])ltg_bigbox = tf.slice(img, [0, 0, 0, 1], [-1, -1, -1, 1])engfeat = tf.concat([ tf.reduce_max(ref_bigbox, [1, 2]), # [?, 64, 64, 1] -> [?, 1] tf.reduce_max(ref_smbox, [1, 2]), tf.reduce_mean(ref_bigbox, [1, 2]), tf.reduce_mean(ref_smbox, [1, 2]), tf.reduce_mean(ltg_bigbox, [1, 2]), tf.reduce_mean(ltg_smbox, [1, 2])], axis=1)ylogits = tf.layers.dense( engfeat, 1, activation=None, kernel_initializer=xavier)"
},
{
"code": null,
"e": 12411,
"s": 12246,
"text": "I decided to create two sets of statistics, one in a 64x64 box and the other in a 16x16 one and create a logistic regression model with just these 6 input features."
},
{
"code": null,
"e": 12530,
"s": 12411,
"text": "No go. Still NaN. This is very, very strange. A linear model should have never NaN-out. Mathematically, this is crazy."
},
{
"code": null,
"e": 12810,
"s": 12530,
"text": "But just before it NaN-ed out, the model reached a 75% accuracy. That’s awfully promising. But this NaN thing is getting to be super annoying. The funny thing is that just before it “diverges” with loss = NaN, the model hasn’t been diverging at all, the loss has been going down:"
},
{
"code": null,
"e": 12944,
"s": 12810,
"text": "Poking around to find out whether there is an alternate way to compute the loss, I discover that there is now a convenience function:"
},
{
"code": null,
"e": 13019,
"s": 12944,
"text": "loss = tf.losses.sigmoid_cross_entropy(labels, tf.reshape(ylogits, [-1]))"
},
{
"code": null,
"e": 13199,
"s": 13019,
"text": "Of course, that probably won’t fix anything but it’s better to use this function rather than call reduce_mean myself. But while here, let’s add asserts to narrow down the problem:"
},
{
"code": null,
"e": 13450,
"s": 13199,
"text": "with tf.control_dependencies([ tf.Assert(tf.is_numeric_tensor(ylogits),[ylogits]), tf.assert_non_negative(labels, [labels]), tf.assert_less_equal(labels, 1, [labels])]): loss = tf.losses.sigmoid_cross_entropy(labels, tf.reshape(ylogits, [-1]))"
},
{
"code": null,
"e": 13647,
"s": 13450,
"text": "Essentially, I assert that ylogits is numeric, and that each label is between 0 and 1. Only if these conditions are met do I compute the loss. Otherwise, the program is supposed to throw an error."
},
{
"code": null,
"e": 13989,
"s": 13647,
"text": "The assertions don’t trigger, but the program still ends with a NaN loss. At this point, it seems clear the problem does not lie in the input data (because I have done a nan_to_num there) or in our model calculation (because assertions don’t trigger) itself. Could it instead be in the back-propagation, possibly in the gradient computation?"
},
{
"code": null,
"e": 14170,
"s": 13989,
"text": "For example, perhaps an unusual (but correct) example leads to unexpectedly high gradient magnitudes. Let’s just limit the effect of such unusual examples by clipping the gradient:"
},
{
"code": null,
"e": 14360,
"s": 14170,
"text": "optimizer = tf.train.AdamOptimizer(learning_rate=0.001)optimizer = tf.contrib.estimator.clip_gradients_by_norm( optimizer, 5)train_op = optimizer.minimize(loss, tf.train.get_global_step())"
},
{
"code": null,
"e": 14385,
"s": 14360,
"text": "That didn’t help either."
},
{
"code": null,
"e": 14776,
"s": 14385,
"text": "If there are lot of very similar inputs, it is possible for the weights themselves to blow up. Over time, you might get a very high positive magnitude associated with one input node and a very high negative magnitude associated with the next input node. One way to get the network to avoid such a situation is to penalize high magnitude weights by adding an extra term to the loss function:"
},
{
"code": null,
"e": 14878,
"s": 14776,
"text": "l2loss = tf.add_n( [tf.nn.l2_loss(v) for v in tf.trainable_variables()])loss = loss + 0.001 * l2loss"
},
{
"code": null,
"e": 15111,
"s": 14878,
"text": "This gets all the trainable variables (weights and biases) and adds a penalty to the loss based on the value of those trainable variables. Ideally, we penalize just the weights (not the biases), but this is fine just for trying out."
},
{
"code": null,
"e": 15483,
"s": 15111,
"text": "Poking around some more, I realize that the documentation for the AdamOptimizer explains the default epsilon value of 1e-8 may be problematic. Essentially, small values of epsilon cause instability even though the purpose of the epsilon is to prevent a divide-by-zero. This begs the question of why this is the default, but let’s try the larger value that is recommended."
},
{
"code": null,
"e": 15574,
"s": 15483,
"text": "optimizer = tf.train.AdamOptimizer( learning_rate=params['learning_rate'], epsilon=0.1)"
},
{
"code": null,
"e": 15627,
"s": 15574,
"text": "That pushes the NaN further out, but it still fails."
},
{
"code": null,
"e": 15792,
"s": 15627,
"text": "Another reason for this could be CUDA bugs and the like. Let’s try training on a different hardware (with P100 instead of Tesla K80) to see if the problem persists."
},
{
"code": null,
"e": 15860,
"s": 15792,
"text": "trainingInput: scaleTier: CUSTOM masterType: complex_model_m_p100"
},
{
"code": null,
"e": 15873,
"s": 15860,
"text": "Still no go."
},
{
"code": null,
"e": 15995,
"s": 15873,
"text": "Sometimes, when left with an intractable bug, it is better to just try rewriting the model in a completely different way."
},
{
"code": null,
"e": 16179,
"s": 15995,
"text": "So, I decided to rewrite the model in Keras. This will also give me the opportunity to learn Keras, something I’ve been meaning to do for a while. Lemonade out of lemons and all that."
},
{
"code": null,
"e": 16339,
"s": 16179,
"text": "Creating a CNN with batchnorm (which will help keep gradients in range) is quite easy in Keras. (Thank you, Francois). So easy that I put batchnorm everywhere."
},
{
"code": null,
"e": 16837,
"s": 16339,
"text": "img = keras.Input(shape=[height, width, 2])cnn = keras.layers.BatchNormalization()(img)for layer in range(nlayers): nfilters = nfil * (layer + 1) cnn = keras.layers.Conv2D(nfilters, (ksize, ksize), padding='same')(cnn) cnn = keras.layers.Activation('elu')(cnn) cnn = keras.layers.BatchNormalization()(cnn) cnn = keras.layers.MaxPooling2D(pool_size=(2, 2))(cnn) cnn = keras.layers.Dropout(dprob)(cnn)cnn = keras.layers.Flatten()(cnn)ltgprob = keras.layers.Dense(10, activation='sigmoid')(cnn)"
},
{
"code": null,
"e": 17022,
"s": 16837,
"text": "Notice also that the final layer directly adds a sigmoid activation. There is no need to muck around with the logits because the optimization takes care of the numeric problems for us:"
},
{
"code": null,
"e": 17204,
"s": 17022,
"text": "optimizer = tf.keras.optimizers.Adam(lr=params['learning_rate'])model.compile(optimizer=optimizer, loss='binary_crossentropy', metrics=['accuracy', 'mse'])"
},
{
"code": null,
"e": 17210,
"s": 17204,
"text": "Nice!"
},
{
"code": null,
"e": 17264,
"s": 17210,
"text": "Unfortunately (you know it by now), I still got NaNs!"
},
{
"code": null,
"e": 17358,
"s": 17264,
"text": "Gaah. Okay, back to the drawing board. Let’s do all the things we did in TensorFlow in Keras."
},
{
"code": null,
"e": 17630,
"s": 17358,
"text": "First step is to forget about all this deep learning stuff and build a linear model. How do you do that? I have an image. I need to do feature engineering and send it to a Dense layer. That means, in Keras, that I have to write my own layer to do the feature engineering:"
},
{
"code": null,
"e": 17982,
"s": 17630,
"text": "def create_feateng_model(params): # input is a 2-channel image height = width = 2 * params[’predsize’] img = keras.Input(shape=[height, width, 2]) engfeat = keras.layers.Lambda( lambda x: engineered_features(x, height//2))(img) ltgprob = keras.layers.Dense(1, activation=’sigmoid’)(engfeat) # create a model model = keras.Model(img, ltgprob)"
},
{
"code": null,
"e": 18191,
"s": 17982,
"text": "The engineered_features is exactly the same TensorFlow function as before! The key idea is that to wrap a TensorFlow function into a Keras layer, you can use a Lambda layer and invoke the TensorFlow function."
},
{
"code": null,
"e": 18382,
"s": 18191,
"text": "But I want to print out the layer to make sure that the numbers flowing through are correct. How do I do that? tf.Print() won’t work because, well, I don’t have tensors. I have Keras layers."
},
{
"code": null,
"e": 18465,
"s": 18382,
"text": "Well, tf.Print() is a TensorFlow function and so, use the same Lambda layer trick:"
},
{
"code": null,
"e": 18712,
"s": 18465,
"text": "def print_layer(layer, message, first_n=3, summarize=1024): return keras.layers.Lambda(( lambda x: tf.Print(x, [x], message=message, first_n=first_n, summarize=summarize)))(layer)"
},
{
"code": null,
"e": 18742,
"s": 18712,
"text": "which can then be invoked as:"
},
{
"code": null,
"e": 18785,
"s": 18742,
"text": "engfeat = print_layer(engfeat, \"engfeat=\")"
},
{
"code": null,
"e": 18858,
"s": 18785,
"text": "Clipping the gradient in Keras? Easy! Every optimizer supports clipnorm."
},
{
"code": null,
"e": 18972,
"s": 18858,
"text": "optimizer = tf.keras.optimizers.Adam(lr=params['learning_rate'], clipnorm=1.)"
},
{
"code": null,
"e": 19134,
"s": 18972,
"text": "Hey, I’m liking this Keras thing — it gives me a nice, simple API. Plus, it interoperates nicely with TensorFlow to give me low-level control whenever I need it."
},
{
"code": null,
"e": 19174,
"s": 19134,
"text": "Oh, right. I still have the NaN problem"
},
{
"code": null,
"e": 19390,
"s": 19174,
"text": "One final thing, something I kinda discounted. The NaN problem could also arise from unscaled data. But my reflectivity and lightning data are both in the range [0,1]. So, I don’t really need to scale things at all."
},
{
"code": null,
"e": 19519,
"s": 19390,
"text": "Still, I’m at a loose end. Why don’t I normalize the image data (subtract the mean, divide by the variance) and see if it helps."
},
{
"code": null,
"e": 19696,
"s": 19519,
"text": "To compute the variance, I need to walk through the entire dataset, and so this is a job for Beam. I could do this in TensorFlow Transform, but for now, let me hack it in Beam."
},
{
"code": null,
"e": 19999,
"s": 19696,
"text": "Since I am rewriting my pipeline, I might as well fix the shuffling issue (see section 2d) once and for all. Increasing the shuffle buffersize was a hack. I really don’t want to write the data in the order that I created the image patches. Let’s randomize the order of the image patches in Apache Beam:"
},
{
"code": null,
"e": 20326,
"s": 19999,
"text": "# shuffle the examples so that each small batch doesn't contain# highly correlated recordsexamples = (examples | '{}_reshuffleA'.format(step) >> beam.Map( lambda t: (random.randint(1, 1000), t)) | '{}_reshuffleB'.format(step) >> beam.GroupByKey() | '{}_reshuffleC'.format(step) >> beam.FlatMap(lambda t: t[1]))"
},
{
"code": null,
"e": 20533,
"s": 20326,
"text": "Essentially, I assign a random key (between 1 and 1000) to each record, group by that random key, remove the key and write out the records. Now, successive image patches will not follow one after the other."
},
{
"code": null,
"e": 20765,
"s": 20533,
"text": "How do I compute the variance in Apache Beam? I did what I always do, search on StackOverflow for something I can copy-paste. Unfortunately, all I found was an unanswered question. Oh, well, buckle down and write a custom Combiner:"
},
{
"code": null,
"e": 21747,
"s": 20765,
"text": "import apache_beam as beamimport numpy as npclass MeanStddev(beam.CombineFn): def create_accumulator(self): return (0.0, 0.0, 0) # x, x^2, countdef add_input(self, sum_count, input): (sum, sumsq, count) = sum_count return sum + input, sumsq + input*input, count + 1def merge_accumulators(self, accumulators): sums, sumsqs, counts = zip(*accumulators) return sum(sums), sum(sumsqs), sum(counts)def extract_output(self, sum_count): (sum, sumsq, count) = sum_count if count: mean = sum / count variance = (sumsq / count) - mean*mean # -ve value could happen due to rounding stddev = np.sqrt(variance) if variance > 0 else 0 return { 'mean': mean, 'variance': variance, 'stddev': stddev, 'count': count } else: return { 'mean': float('NaN'), 'variance': float('NaN'), 'stddev': float('NaN'), 'count': 0 } [1.3, 3.0, 4.2] | beam.CombineGlobally(MeanStddev())"
},
{
"code": null,
"e": 21838,
"s": 21747,
"text": "Note the workflow here — I can quickly test it on a list of numbers to make sure it works."
},
{
"code": null,
"e": 21930,
"s": 21838,
"text": "Then, I went and added the answer to StackOverflow. Maybe all I need is some good karma ..."
},
{
"code": null,
"e": 21973,
"s": 21930,
"text": "I can then go to my pipeline code and add:"
},
{
"code": null,
"e": 22279,
"s": 21973,
"text": "if step == 'train': _ = (examples | 'get_values' >> beam.FlatMap( lambda x : [(f, x[f]) for f in ['ref', 'ltg']]) | 'compute_stats' >> beam.CombinePerKey(MeanStddev()) | 'write_stats' >> beam.io.Write(beam.io.WriteToText( os.path.join(options['outdir'], 'stats'), num_shards=1)) )"
},
{
"code": null,
"e": 22489,
"s": 22279,
"text": "Essentially, I pull out example[‘ref’] and example[‘ltg’] and create tuples that I group by key. Then, I can compute the mean and standard deviation of every pixel in both these images over the entire dataset."
},
{
"code": null,
"e": 22552,
"s": 22489,
"text": "Once I run the pipeline, I can print the resulting statistics:"
},
{
"code": null,
"e": 22795,
"s": 22552,
"text": "gsutil cat gs://$BUCKET/lightning/preproc/stats*('ltg', {'count': 1028242, 'variance': 0.0770683210620995, 'stddev': 0.2776118172234379, 'mean': 0.08414945119923131})('ref', {'count': 1028242, 'variance': masked, 'stddev': 0, 'mean': masked})"
},
{
"code": null,
"e": 23151,
"s": 22795,
"text": "Masked? What the @#$@#$@# does masked mean? Turns out that Masked arrays are a special numpy thing. Masked values are not NaN and so, if you process them with Numpy, nan_to_num() won’t do anything to it. On the other hand, it looks numeric, and so all my TensorFlow assertions don’t raise. Numeric operations with a masked value results in a masked value."
},
{
"code": null,
"e": 23316,
"s": 23151,
"text": "Masked values are just like NaN — they will slurp your milkshake from across a room but the regular numpy and TensorFlow library methods know nothing about masking."
},
{
"code": null,
"e": 23513,
"s": 23316,
"text": "Since the masking happens only in the reflectivity grids (I create the lightning grids myself by accumulating lightning flashes), I have to convert the masked values to a nice number after reading"
},
{
"code": null,
"e": 23600,
"s": 23513,
"text": "ref = goesio.read_ir_data(ir_blob_path, griddef)ref = np.ma.filled(ref, 0) # mask -> 0"
},
{
"code": null,
"e": 23661,
"s": 23600,
"text": "and now, when I rerun the pipeline, I get reasonable values:"
},
{
"code": null,
"e": 23899,
"s": 23661,
"text": "('ref', {'count': 1028242, 'variance': 0.07368491739234752, 'stddev': 0.27144965903892293, 'mean': 0.3200035849321707})('ltg', {'count': 1028242, 'variance': 0.0770683210620995, 'stddev': 0.2776118172234379, 'mean': 0.08414945119923131})"
},
{
"code": null,
"e": 24022,
"s": 23899,
"text": "These are small numbers. There should be no reason to scale anything. So, let’s just train with the masking problem fixed."
},
{
"code": null,
"e": 24084,
"s": 24022,
"text": "This time, no NaN. Instead the program crashes and logs show:"
},
{
"code": null,
"e": 24239,
"s": 24084,
"text": "Filling up shuffle buffer (this may take a while): 251889 of 1280000The replica master 0 ran out-of-memory and exited with a non-zero status of 9(SIGKILL)"
},
{
"code": null,
"e": 24387,
"s": 24239,
"text": "Replica zero is the input pipeline (reading data happens on the CPU). Why does it want to read 1280000 records all at once into the shuffle buffer?"
},
{
"code": null,
"e": 24545,
"s": 24387,
"text": "Well, now that the input data are so well shuffled by my Beam/Dataflow, I don’t even need that large a shuffle buffer (this used to be 5000, see Section 2d):"
},
{
"code": null,
"e": 24607,
"s": 24545,
"text": "dataset = dataset.shuffle(batch_size * 50) # shuffle by a bit"
},
{
"code": null,
"e": 24703,
"s": 24607,
"text": "And ... 12 minutes later, the training finishes with an accuracy of 83%(!!!). No NaNs anywhere."
},
{
"code": null,
"e": 24712,
"s": 24703,
"text": "Woo hoo!"
},
{
"code": null,
"e": 24968,
"s": 24712,
"text": "Remember that we did only a linear model consisting of engineered features. Let’s add back the convnet in parallel. The idea is to concatenate the two dense layers, so that my model architecture can contain both the CNN layers and the feature engineering:"
},
{
"code": null,
"e": 25083,
"s": 24968,
"text": "This is how to do this in Keras, with some batchnorm and dropouts thrown in, just because they are so easy to add:"
},
{
"code": null,
"e": 25778,
"s": 25083,
"text": "cnn = keras.layers.BatchNormalization()(img)for layer in range(nlayers): nfilters = nfil * (layer + 1) cnn = keras.layers.Conv2D(nfilters, (ksize, ksize), padding='same')(cnn) cnn = keras.layers.Activation('elu')(cnn) cnn = keras.layers.BatchNormalization()(cnn) cnn = keras.layers.MaxPooling2D(pool_size=(2, 2))(cnn)cnn = keras.layers.Flatten()(cnn)cnn = keras.layers.Dropout(dprob)(cnn)cnn = keras.layers.Dense(10, activation='relu')(cnn)# feature engineering part of modelengfeat = keras.layers.Lambda( lambda x: engineered_features(x, height//2))(img)# concatenate the two partsboth = keras.layers.concatenate([cnn, engfeat])ltgprob = keras.layers.Dense(1, activation='sigmoid')(both)"
},
{
"code": null,
"e": 26026,
"s": 25778,
"text": "Now, I have an accuracy of 85%. This is still a small dataset (only 60 days of satellite data) and that’s probably why the deep learning path doesn’t add that much value. So, I’ll go back and generate more data, train longer, train on the TPU etc."
}
]
|
How to Automatically Import Your Favorite Libraries into IPython or a Jupyter Notebook | by Will Koehrsen | Towards Data Science | If you often use interactive IPython sessions or Jupyter Notebooks and you’re getting tired of importing the same libraries over and over, try this:
Navigate to ~/.ipython/profile_defaultCreate a folder called startup if it’s not already thereAdd a new Python file called start.pyPut your favorite imports in this fileLaunch IPython or a Jupyter Notebook and your favorite libraries will be automatically loaded every time!
Navigate to ~/.ipython/profile_default
Create a folder called startup if it’s not already there
Add a new Python file called start.py
Put your favorite imports in this file
Launch IPython or a Jupyter Notebook and your favorite libraries will be automatically loaded every time!
Here are the steps in visual form. First, the location of start.py:
Here is the contents of my start.py:
Now, when I launch an IPython session, I see this:
We can confirm that the libraries have been loaded by inspecting globals() :
globals()['pd']<module 'pandas' from '/usr/local/lib/python3.6/site-packages/pandas/__init__.py'>globals()['np']<module 'numpy' from '/usr/local/lib/python3.6/site-packages/numpy/__init__.py'>
We’re all good to use our interactive session now without having to type the commands to load these libraries! This also works in Jupyter Notebook.
The file can be named anything ( start.py is easy to remember) and you can have multiple files in startup/. They are executed in lexicographical order when IPython is launched.
If you’re running this in a Jupyter Notebook, you won’t get a cell with the imports so when you share the notebook, make sure to copy over the start.py contents into the first cell. This will let people know what libraries you are using. (As an alternative, you can use the default_cell Jupyter Notebook extension I wrote.)
If you work on multiple computers, you’ll have to repeat the steps. Make sure to use the same start.py script so you get the same imports!
Thanks to this Stack Overflow answer and the official docs
This is certainly not life-changing (unlike writing about data science) but it saves you a few seconds every time you start IPython. It’s also useful as a demonstration of how you can customize your work environment to be as efficient as possible. There are many other tips you can find by reading documentation (such as for IPython magic commands), experimenting on your own, or even following helpful Twitter accounts. If you find yourself frustrated with an inefficiency like typing import pandas as pd ten times a day, don’t just accept it, find a better way to work.
As always, I welcome feedback and constructive criticism. I can be reached on Twitter @koehrsen_will. | [
{
"code": null,
"e": 321,
"s": 172,
"text": "If you often use interactive IPython sessions or Jupyter Notebooks and you’re getting tired of importing the same libraries over and over, try this:"
},
{
"code": null,
"e": 596,
"s": 321,
"text": "Navigate to ~/.ipython/profile_defaultCreate a folder called startup if it’s not already thereAdd a new Python file called start.pyPut your favorite imports in this fileLaunch IPython or a Jupyter Notebook and your favorite libraries will be automatically loaded every time!"
},
{
"code": null,
"e": 635,
"s": 596,
"text": "Navigate to ~/.ipython/profile_default"
},
{
"code": null,
"e": 692,
"s": 635,
"text": "Create a folder called startup if it’s not already there"
},
{
"code": null,
"e": 730,
"s": 692,
"text": "Add a new Python file called start.py"
},
{
"code": null,
"e": 769,
"s": 730,
"text": "Put your favorite imports in this file"
},
{
"code": null,
"e": 875,
"s": 769,
"text": "Launch IPython or a Jupyter Notebook and your favorite libraries will be automatically loaded every time!"
},
{
"code": null,
"e": 943,
"s": 875,
"text": "Here are the steps in visual form. First, the location of start.py:"
},
{
"code": null,
"e": 980,
"s": 943,
"text": "Here is the contents of my start.py:"
},
{
"code": null,
"e": 1031,
"s": 980,
"text": "Now, when I launch an IPython session, I see this:"
},
{
"code": null,
"e": 1108,
"s": 1031,
"text": "We can confirm that the libraries have been loaded by inspecting globals() :"
},
{
"code": null,
"e": 1301,
"s": 1108,
"text": "globals()['pd']<module 'pandas' from '/usr/local/lib/python3.6/site-packages/pandas/__init__.py'>globals()['np']<module 'numpy' from '/usr/local/lib/python3.6/site-packages/numpy/__init__.py'>"
},
{
"code": null,
"e": 1449,
"s": 1301,
"text": "We’re all good to use our interactive session now without having to type the commands to load these libraries! This also works in Jupyter Notebook."
},
{
"code": null,
"e": 1626,
"s": 1449,
"text": "The file can be named anything ( start.py is easy to remember) and you can have multiple files in startup/. They are executed in lexicographical order when IPython is launched."
},
{
"code": null,
"e": 1950,
"s": 1626,
"text": "If you’re running this in a Jupyter Notebook, you won’t get a cell with the imports so when you share the notebook, make sure to copy over the start.py contents into the first cell. This will let people know what libraries you are using. (As an alternative, you can use the default_cell Jupyter Notebook extension I wrote.)"
},
{
"code": null,
"e": 2089,
"s": 1950,
"text": "If you work on multiple computers, you’ll have to repeat the steps. Make sure to use the same start.py script so you get the same imports!"
},
{
"code": null,
"e": 2148,
"s": 2089,
"text": "Thanks to this Stack Overflow answer and the official docs"
},
{
"code": null,
"e": 2720,
"s": 2148,
"text": "This is certainly not life-changing (unlike writing about data science) but it saves you a few seconds every time you start IPython. It’s also useful as a demonstration of how you can customize your work environment to be as efficient as possible. There are many other tips you can find by reading documentation (such as for IPython magic commands), experimenting on your own, or even following helpful Twitter accounts. If you find yourself frustrated with an inefficiency like typing import pandas as pd ten times a day, don’t just accept it, find a better way to work."
}
]
|
Collectors groupingBy() method in Java with Examples - GeeksforGeeks | 29 Jul, 2021
The groupingBy() method of Collectors class in Java are used for grouping objects by some property and storing results in a Map instance. In order to use it, we always need to specify a property by which the grouping would be performed. This method provides similar functionality to SQL’s GROUP BY clause.
Syntax:
public static Collector<T, ?, Map<K, List>> groupingBy(Function classifier)
Type Parameter: This method takes two type parameters:
T- It is the type of the input elements.
K- It is the type the input elements to be converted.
Parameters: This method accepts two mandatory parameters:
Function- It is the property which is to be applied to the input elements.
Classifier- It is used to map input elements into the destination map.
Return value: It returns a collector as a map.
Below is the program implementation of groupingBy() method:Program 1:
Java
// Java program to demonstrate// Collectors groupingBy() method import java.util.*;import java.util.function.Function;import java.util.stream.Collectors; public class GFG { public static void main(String[] args) { // Get the List List<String> g = Arrays.asList("geeks", "for", "geeks"); // Collect the list as map // by groupingBy() method Map<String, Long> result = g.stream().collect( Collectors.groupingBy( Function.identity(), Collectors.counting())); // Print the result System.out.println(result); }}
{geeks=2, for=1}
Reference: https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#groupingBy-java.util.function.Function-
manikarora059
Java - util package
Java-Collectors
Java-Functions
Java-Stream-Collectors
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multithreading in Java
Multidimensional Arrays in Java | [
{
"code": null,
"e": 24425,
"s": 24397,
"text": "\n29 Jul, 2021"
},
{
"code": null,
"e": 24732,
"s": 24425,
"text": "The groupingBy() method of Collectors class in Java are used for grouping objects by some property and storing results in a Map instance. In order to use it, we always need to specify a property by which the grouping would be performed. This method provides similar functionality to SQL’s GROUP BY clause. "
},
{
"code": null,
"e": 24742,
"s": 24732,
"text": "Syntax: "
},
{
"code": null,
"e": 24820,
"s": 24742,
"text": "public static Collector<T, ?, Map<K, List>> groupingBy(Function classifier) "
},
{
"code": null,
"e": 24876,
"s": 24820,
"text": "Type Parameter: This method takes two type parameters: "
},
{
"code": null,
"e": 24918,
"s": 24876,
"text": "T- It is the type of the input elements. "
},
{
"code": null,
"e": 24972,
"s": 24918,
"text": "K- It is the type the input elements to be converted."
},
{
"code": null,
"e": 25032,
"s": 24972,
"text": "Parameters: This method accepts two mandatory parameters: "
},
{
"code": null,
"e": 25108,
"s": 25032,
"text": "Function- It is the property which is to be applied to the input elements. "
},
{
"code": null,
"e": 25179,
"s": 25108,
"text": "Classifier- It is used to map input elements into the destination map."
},
{
"code": null,
"e": 25227,
"s": 25179,
"text": "Return value: It returns a collector as a map. "
},
{
"code": null,
"e": 25298,
"s": 25227,
"text": "Below is the program implementation of groupingBy() method:Program 1: "
},
{
"code": null,
"e": 25303,
"s": 25298,
"text": "Java"
},
{
"code": "// Java program to demonstrate// Collectors groupingBy() method import java.util.*;import java.util.function.Function;import java.util.stream.Collectors; public class GFG { public static void main(String[] args) { // Get the List List<String> g = Arrays.asList(\"geeks\", \"for\", \"geeks\"); // Collect the list as map // by groupingBy() method Map<String, Long> result = g.stream().collect( Collectors.groupingBy( Function.identity(), Collectors.counting())); // Print the result System.out.println(result); }}",
"e": 25946,
"s": 25303,
"text": null
},
{
"code": null,
"e": 25963,
"s": 25946,
"text": "{geeks=2, for=1}"
},
{
"code": null,
"e": 26091,
"s": 25965,
"text": "Reference: https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#groupingBy-java.util.function.Function-"
},
{
"code": null,
"e": 26105,
"s": 26091,
"text": "manikarora059"
},
{
"code": null,
"e": 26125,
"s": 26105,
"text": "Java - util package"
},
{
"code": null,
"e": 26141,
"s": 26125,
"text": "Java-Collectors"
},
{
"code": null,
"e": 26156,
"s": 26141,
"text": "Java-Functions"
},
{
"code": null,
"e": 26179,
"s": 26156,
"text": "Java-Stream-Collectors"
},
{
"code": null,
"e": 26184,
"s": 26179,
"text": "Java"
},
{
"code": null,
"e": 26189,
"s": 26184,
"text": "Java"
},
{
"code": null,
"e": 26287,
"s": 26189,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26338,
"s": 26287,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 26368,
"s": 26338,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 26387,
"s": 26368,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 26418,
"s": 26387,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 26436,
"s": 26418,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 26468,
"s": 26436,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 26488,
"s": 26468,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 26512,
"s": 26488,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 26535,
"s": 26512,
"text": "Multithreading in Java"
}
]
|
Color N boxes using M colors such that K boxes have different color from the box on its left - GeeksforGeeks | 05 Nov, 2021
Given N number of boxes arranged in a row and M number of colors. The task is to find the number of ways to paint those N boxes using M colors such that there are exactly K boxes with a color different from the color of the box on its left. Print this answer modulo 998244353.Examples:
Input: N = 3, M = 3, K = 0 Output: 3 Since the value of K is zero, no box can have a different color from color of the box on its left. Thus, all boxes should be painted with same color and since there are 3 types of colors, so there are total 3 ways. Input: N = 3, M = 2, K = 1 Output: 4 Let’s number the colors as 1 and 2. Four possible sequences of painting 3 boxes with 1 box having different color from color of box on its left are (1 2 2), (1 1 2), (2 1 1) (2 2 1)
Prerequisites : Dynamic Programming
Approach: This problem can be solved using dynamic programming where dp[i][j] will denote the number of ways to paint i boxes using M colors such that there are exactly j boxes with a color different from the color of the box on its left. For every current box except 1st, either we can paint the same color as painted on its left box and solve for dp[i – 1][j] or we can paint it with remaining M – 1 color and solve for dp[i – 1][j – 1] recursively.Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// CPP Program to Paint N boxes using M// colors such that K boxes have color// different from color of box on its left#include <bits/stdc++.h>using namespace std; const int MOD = 998244353; vector<vector<int>> dp; // This function returns the required number// of ways where idx is the current index and// diff is number of boxes having different// color from box on its leftint solve(int idx, int diff, int N, int M, int K){ // Base Case if (idx > N) { if (diff == K) return 1; return 0; } // If already computed if (dp[idx][ diff] != -1) return dp[idx][ diff]; // Either paint with same color as // previous one int ans = solve(idx + 1, diff, N, M, K); // Or paint with remaining (M - 1) // colors ans = ans % MOD + ((M - 1) % MOD * solve(idx + 1, diff + 1, N, M, K) % MOD) % MOD; return dp[idx][ diff] = ans;} // Driver codeint main(){ int N = 3, M = 3, K = 0; dp = vector<vector<int>>(N+1,vector<int>(N+1,-1)); // Multiply M since first box can be // painted with any of the M colors and // start solving from 2nd box cout << (M * solve(2, 0, N, M, K)) << endl; return 0;}
// Java Program to Paint N boxes using M// colors such that K boxes have color// different from color of box on its left class GFG{ static int M = 1001; static int MOD = 998244353; static int[][] dp = new int[M][M]; // This function returns the required number // of ways where idx is the current index and // diff is number of boxes having different // color from box on its left static int solve(int idx, int diff, int N, int M, int K) { // Base Case if (idx > N) { if (diff == K) return 1; return 0; } // If already computed if (dp[idx][ diff] != -1) return dp[idx][ diff]; // Either paint with same color as // previous one int ans = solve(idx + 1, diff, N, M, K); // Or paint with remaining (M - 1) // colors ans += (M - 1) * solve(idx + 1, diff + 1, N, M, K); return dp[idx][ diff] = ans % MOD; } // Driver code public static void main (String[] args) { int N = 3, M = 3, K = 0; for(int i = 0; i <= M; i++) for(int j = 0; j <= M; j++) dp[i][j] = -1; // Multiply M since first box can be // painted with any of the M colors and // start solving from 2nd box System.out.println((M * solve(2, 0, N, M, K))); }} // This code is contributed by mits
# Python3 Program to Paint N boxes using M# colors such that K boxes have color# different from color of box on its left M = 1001;MOD = 998244353; dp = [[-1]* M ] * M # This function returns the required number# of ways where idx is the current index and# diff is number of boxes having different# color from box on its leftdef solve(idx, diff, N, M, K) : # Base Case if (idx > N) : if (diff == K) : return 1 return 0 # If already computed if (dp[idx][ diff] != -1) : return dp[idx]; # Either paint with same color as # previous one ans = solve(idx + 1, diff, N, M, K); # Or paint with remaining (M - 1) # colors ans += (M - 1) * solve(idx + 1, diff + 1, N, M, K); dp[idx][ diff] = ans % MOD; return dp[idx][ diff] # Driver codeif __name__ == "__main__" : N = 3 M = 3 K = 0 # Multiply M since first box can be # painted with any of the M colors and # start solving from 2nd box print(M * solve(2, 0, N, M, K)) # This code is contributed by Ryuga
// C# Program to Paint N boxes using M// colors such that K boxes have color// different from color of box on its leftusing System;class GFG{ static int M = 1001;static int MOD = 998244353; static int[,] dp = new int[M, M]; // This function returns the required number// of ways where idx is the current index and// diff is number of boxes having different// color from box on its leftstatic int solve(int idx, int diff, int N, int M, int K){ // Base Case if (idx > N) { if (diff == K) return 1; return 0; } // If already computed if (dp[idx, diff] != -1) return dp[idx, diff]; // Either paint with same color as // previous one int ans = solve(idx + 1, diff, N, M, K); // Or paint with remaining (M - 1) // colors ans += (M - 1) * solve(idx + 1, diff + 1, N, M, K); return dp[idx, diff] = ans % MOD;} // Driver codepublic static void Main (){ int N = 3, M = 3, K = 0; for(int i = 0; i <= M; i++) for(int j = 0; j <= M; j++) dp[i, j] = -1; // Multiply M since first box can be // painted with any of the M colors and // start solving from 2nd box Console.WriteLine((M * solve(2, 0, N, M, K)));}} // This code is contributed by chandan_jnu
<?php// PHP Program to Paint N boxes using M// colors such that K boxes have color// different from color of box on its left $M = 1001;$MOD = 998244353; $dp = array_fill(0, $M, array_fill(0, $M, -1)); // This function returns the required number// of ways where idx is the current index// and diff is number of boxes having// different color from box on its leftfunction solve($idx, $diff, $N, $M, $K){ global $dp, $MOD; // Base Case if ($idx > $N) { if ($diff == $K) return 1; return 0; } // If already computed if ($dp[$idx][$diff] != -1) return $dp[$idx][$diff]; // Either paint with same color // as previous one $ans = solve($idx + 1, $diff, $N, $M, $K); // Or paint with remaining (M - 1) // colors $ans += ($M - 1) * solve($idx + 1, $diff + 1, $N, $M, $K); return $dp[$idx][$diff] = $ans % $MOD;} // Driver code$N = 3;$M = 3;$K = 0; // Multiply M since first box can be// painted with any of the M colors and// start solving from 2nd boxecho ($M * solve(2, 0, $N, $M, $K)); // This code is contributed by chandan_jnu?>
<script> // JavaScript Program to Paint N boxes using M // colors such that K boxes have color // different from color of box on its left let m = 1001; let MOD = 998244353; let dp = new Array(m); for(let i = 0; i < m; i++) { dp[i] = new Array(m); for(let j = 0; j < m; j++) { dp[i][j] = 0; } } // This function returns the required number // of ways where idx is the current index and // diff is number of boxes having different // color from box on its left function solve(idx, diff, N, M, K) { // Base Case if (idx > N) { if (diff == K) return 1; return 0; } // If already computed if (dp[idx][ diff] != -1) return dp[idx][ diff]; // Either paint with same color as // previous one let ans = solve(idx + 1, diff, N, M, K); // Or paint with remaining (M - 1) // colors ans += (M - 1) * solve(idx + 1, diff + 1, N, M, K); dp[idx][ diff] = ans % MOD; return dp[idx][ diff]; } let N = 3, M = 3, K = 0; for(let i = 0; i <= M; i++) for(let j = 0; j <= M; j++) dp[i][j] = -1; // Multiply M since first box can be // painted with any of the M colors and // start solving from 2nd box document.write((M * solve(2, 0, N, M, K))); </script>
3
Time Complexity: O(M*M)Auxiliary Space: O(M*M)
ankthon
Mithun Kumar
Chandan_Kumar
mukesh07
pankajsharmagfg
ashutoshsinghgeeksforgeeks
Technical Scripter 2018
Algorithms
Competitive Programming
Dynamic Programming
Mathematical
Dynamic Programming
Mathematical
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
Introduction to Algorithms
Playfair Cipher with Examples
How to write a Pseudo Code?
Practice for cracking any coding interview
Arrow operator -> in C/C++ with Examples
Competitive Programming - A Complete Guide
Modulo 10^9+7 (1000000007)
Top 10 Algorithms and Data Structures for Competitive Programming | [
{
"code": null,
"e": 25442,
"s": 25414,
"text": "\n05 Nov, 2021"
},
{
"code": null,
"e": 25730,
"s": 25442,
"text": "Given N number of boxes arranged in a row and M number of colors. The task is to find the number of ways to paint those N boxes using M colors such that there are exactly K boxes with a color different from the color of the box on its left. Print this answer modulo 998244353.Examples: "
},
{
"code": null,
"e": 26203,
"s": 25730,
"text": "Input: N = 3, M = 3, K = 0 Output: 3 Since the value of K is zero, no box can have a different color from color of the box on its left. Thus, all boxes should be painted with same color and since there are 3 types of colors, so there are total 3 ways. Input: N = 3, M = 2, K = 1 Output: 4 Let’s number the colors as 1 and 2. Four possible sequences of painting 3 boxes with 1 box having different color from color of box on its left are (1 2 2), (1 1 2), (2 1 1) (2 2 1) "
},
{
"code": null,
"e": 26240,
"s": 26203,
"text": "Prerequisites : Dynamic Programming "
},
{
"code": null,
"e": 26744,
"s": 26240,
"text": "Approach: This problem can be solved using dynamic programming where dp[i][j] will denote the number of ways to paint i boxes using M colors such that there are exactly j boxes with a color different from the color of the box on its left. For every current box except 1st, either we can paint the same color as painted on its left box and solve for dp[i – 1][j] or we can paint it with remaining M – 1 color and solve for dp[i – 1][j – 1] recursively.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26748,
"s": 26744,
"text": "C++"
},
{
"code": null,
"e": 26753,
"s": 26748,
"text": "Java"
},
{
"code": null,
"e": 26761,
"s": 26753,
"text": "Python3"
},
{
"code": null,
"e": 26764,
"s": 26761,
"text": "C#"
},
{
"code": null,
"e": 26768,
"s": 26764,
"text": "PHP"
},
{
"code": null,
"e": 26779,
"s": 26768,
"text": "Javascript"
},
{
"code": "// CPP Program to Paint N boxes using M// colors such that K boxes have color// different from color of box on its left#include <bits/stdc++.h>using namespace std; const int MOD = 998244353; vector<vector<int>> dp; // This function returns the required number// of ways where idx is the current index and// diff is number of boxes having different// color from box on its leftint solve(int idx, int diff, int N, int M, int K){ // Base Case if (idx > N) { if (diff == K) return 1; return 0; } // If already computed if (dp[idx][ diff] != -1) return dp[idx][ diff]; // Either paint with same color as // previous one int ans = solve(idx + 1, diff, N, M, K); // Or paint with remaining (M - 1) // colors ans = ans % MOD + ((M - 1) % MOD * solve(idx + 1, diff + 1, N, M, K) % MOD) % MOD; return dp[idx][ diff] = ans;} // Driver codeint main(){ int N = 3, M = 3, K = 0; dp = vector<vector<int>>(N+1,vector<int>(N+1,-1)); // Multiply M since first box can be // painted with any of the M colors and // start solving from 2nd box cout << (M * solve(2, 0, N, M, K)) << endl; return 0;}",
"e": 27952,
"s": 26779,
"text": null
},
{
"code": "// Java Program to Paint N boxes using M// colors such that K boxes have color// different from color of box on its left class GFG{ static int M = 1001; static int MOD = 998244353; static int[][] dp = new int[M][M]; // This function returns the required number // of ways where idx is the current index and // diff is number of boxes having different // color from box on its left static int solve(int idx, int diff, int N, int M, int K) { // Base Case if (idx > N) { if (diff == K) return 1; return 0; } // If already computed if (dp[idx][ diff] != -1) return dp[idx][ diff]; // Either paint with same color as // previous one int ans = solve(idx + 1, diff, N, M, K); // Or paint with remaining (M - 1) // colors ans += (M - 1) * solve(idx + 1, diff + 1, N, M, K); return dp[idx][ diff] = ans % MOD; } // Driver code public static void main (String[] args) { int N = 3, M = 3, K = 0; for(int i = 0; i <= M; i++) for(int j = 0; j <= M; j++) dp[i][j] = -1; // Multiply M since first box can be // painted with any of the M colors and // start solving from 2nd box System.out.println((M * solve(2, 0, N, M, K))); }} // This code is contributed by mits",
"e": 29406,
"s": 27952,
"text": null
},
{
"code": "# Python3 Program to Paint N boxes using M# colors such that K boxes have color# different from color of box on its left M = 1001;MOD = 998244353; dp = [[-1]* M ] * M # This function returns the required number# of ways where idx is the current index and# diff is number of boxes having different# color from box on its leftdef solve(idx, diff, N, M, K) : # Base Case if (idx > N) : if (diff == K) : return 1 return 0 # If already computed if (dp[idx][ diff] != -1) : return dp[idx]; # Either paint with same color as # previous one ans = solve(idx + 1, diff, N, M, K); # Or paint with remaining (M - 1) # colors ans += (M - 1) * solve(idx + 1, diff + 1, N, M, K); dp[idx][ diff] = ans % MOD; return dp[idx][ diff] # Driver codeif __name__ == \"__main__\" : N = 3 M = 3 K = 0 # Multiply M since first box can be # painted with any of the M colors and # start solving from 2nd box print(M * solve(2, 0, N, M, K)) # This code is contributed by Ryuga",
"e": 30457,
"s": 29406,
"text": null
},
{
"code": "// C# Program to Paint N boxes using M// colors such that K boxes have color// different from color of box on its leftusing System;class GFG{ static int M = 1001;static int MOD = 998244353; static int[,] dp = new int[M, M]; // This function returns the required number// of ways where idx is the current index and// diff is number of boxes having different// color from box on its leftstatic int solve(int idx, int diff, int N, int M, int K){ // Base Case if (idx > N) { if (diff == K) return 1; return 0; } // If already computed if (dp[idx, diff] != -1) return dp[idx, diff]; // Either paint with same color as // previous one int ans = solve(idx + 1, diff, N, M, K); // Or paint with remaining (M - 1) // colors ans += (M - 1) * solve(idx + 1, diff + 1, N, M, K); return dp[idx, diff] = ans % MOD;} // Driver codepublic static void Main (){ int N = 3, M = 3, K = 0; for(int i = 0; i <= M; i++) for(int j = 0; j <= M; j++) dp[i, j] = -1; // Multiply M since first box can be // painted with any of the M colors and // start solving from 2nd box Console.WriteLine((M * solve(2, 0, N, M, K)));}} // This code is contributed by chandan_jnu",
"e": 31743,
"s": 30457,
"text": null
},
{
"code": "<?php// PHP Program to Paint N boxes using M// colors such that K boxes have color// different from color of box on its left $M = 1001;$MOD = 998244353; $dp = array_fill(0, $M, array_fill(0, $M, -1)); // This function returns the required number// of ways where idx is the current index// and diff is number of boxes having// different color from box on its leftfunction solve($idx, $diff, $N, $M, $K){ global $dp, $MOD; // Base Case if ($idx > $N) { if ($diff == $K) return 1; return 0; } // If already computed if ($dp[$idx][$diff] != -1) return $dp[$idx][$diff]; // Either paint with same color // as previous one $ans = solve($idx + 1, $diff, $N, $M, $K); // Or paint with remaining (M - 1) // colors $ans += ($M - 1) * solve($idx + 1, $diff + 1, $N, $M, $K); return $dp[$idx][$diff] = $ans % $MOD;} // Driver code$N = 3;$M = 3;$K = 0; // Multiply M since first box can be// painted with any of the M colors and// start solving from 2nd boxecho ($M * solve(2, 0, $N, $M, $K)); // This code is contributed by chandan_jnu?>",
"e": 32869,
"s": 31743,
"text": null
},
{
"code": "<script> // JavaScript Program to Paint N boxes using M // colors such that K boxes have color // different from color of box on its left let m = 1001; let MOD = 998244353; let dp = new Array(m); for(let i = 0; i < m; i++) { dp[i] = new Array(m); for(let j = 0; j < m; j++) { dp[i][j] = 0; } } // This function returns the required number // of ways where idx is the current index and // diff is number of boxes having different // color from box on its left function solve(idx, diff, N, M, K) { // Base Case if (idx > N) { if (diff == K) return 1; return 0; } // If already computed if (dp[idx][ diff] != -1) return dp[idx][ diff]; // Either paint with same color as // previous one let ans = solve(idx + 1, diff, N, M, K); // Or paint with remaining (M - 1) // colors ans += (M - 1) * solve(idx + 1, diff + 1, N, M, K); dp[idx][ diff] = ans % MOD; return dp[idx][ diff]; } let N = 3, M = 3, K = 0; for(let i = 0; i <= M; i++) for(let j = 0; j <= M; j++) dp[i][j] = -1; // Multiply M since first box can be // painted with any of the M colors and // start solving from 2nd box document.write((M * solve(2, 0, N, M, K))); </script>",
"e": 34312,
"s": 32869,
"text": null
},
{
"code": null,
"e": 34314,
"s": 34312,
"text": "3"
},
{
"code": null,
"e": 34363,
"s": 34316,
"text": "Time Complexity: O(M*M)Auxiliary Space: O(M*M)"
},
{
"code": null,
"e": 34371,
"s": 34363,
"text": "ankthon"
},
{
"code": null,
"e": 34384,
"s": 34371,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 34398,
"s": 34384,
"text": "Chandan_Kumar"
},
{
"code": null,
"e": 34407,
"s": 34398,
"text": "mukesh07"
},
{
"code": null,
"e": 34423,
"s": 34407,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 34450,
"s": 34423,
"text": "ashutoshsinghgeeksforgeeks"
},
{
"code": null,
"e": 34474,
"s": 34450,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 34485,
"s": 34474,
"text": "Algorithms"
},
{
"code": null,
"e": 34509,
"s": 34485,
"text": "Competitive Programming"
},
{
"code": null,
"e": 34529,
"s": 34509,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 34542,
"s": 34529,
"text": "Mathematical"
},
{
"code": null,
"e": 34562,
"s": 34542,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 34575,
"s": 34562,
"text": "Mathematical"
},
{
"code": null,
"e": 34586,
"s": 34575,
"text": "Algorithms"
},
{
"code": null,
"e": 34684,
"s": 34586,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34693,
"s": 34684,
"text": "Comments"
},
{
"code": null,
"e": 34706,
"s": 34693,
"text": "Old Comments"
},
{
"code": null,
"e": 34755,
"s": 34706,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 34780,
"s": 34755,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 34807,
"s": 34780,
"text": "Introduction to Algorithms"
},
{
"code": null,
"e": 34837,
"s": 34807,
"text": "Playfair Cipher with Examples"
},
{
"code": null,
"e": 34865,
"s": 34837,
"text": "How to write a Pseudo Code?"
},
{
"code": null,
"e": 34908,
"s": 34865,
"text": "Practice for cracking any coding interview"
},
{
"code": null,
"e": 34949,
"s": 34908,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 34992,
"s": 34949,
"text": "Competitive Programming - A Complete Guide"
},
{
"code": null,
"e": 35019,
"s": 34992,
"text": "Modulo 10^9+7 (1000000007)"
}
]
|
Euler Totient Function | Practice | GeeksforGeeks | Find the Euler Totient Function (ETF) Φ(N) for an input N. ETF is the count of numbers in {1, 2, 3, ..., N} that are relatively prime to N, i.e., the numbers whose GCD (Greatest Common Divisor) with N is 1.
Example 1:
Input:
N = 11
Output:
10
Explanation:
From 1 to 11,
1,2,3,4,5,6,7,8,9,10
are relatively prime to 11.
Example 2:
Input:
N = 16
Output:
8
Explanation:
From 1 to 16
1,3,5,7,9,11,13,15
are relatively prime
to 16.
Your Task:
You don't need to read input or print anything. Your task is to complete the function ETF() which takes one integer value N, as input parameter and return the value of Φ(N).
Expected Time Complexity: O(NLog N)
Expected Space Complexity: O(1)
Constraints:
1<=N<=105
-1
Nikhil Kumar1 year ago
Nikhil Kumar
long long int gcd(long long int a, long long int b){ if (b == 0) return a; return gcd(b, a % b); }
// function to find totient of n long long ETF(long long N){ long long count=0; for(long long i=1; i<=N; i++){ if(gcd(N, i)==1) count++; } return count; // code here }
N logN is not getting accepted? why?
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": 447,
"s": 238,
"text": "Find the Euler Totient Function (ETF) Φ(N) for an input N. ETF is the count of numbers in {1, 2, 3, ..., N} that are relatively prime to N, i.e., the numbers whose GCD (Greatest Common Divisor) with N is 1.\n "
},
{
"code": null,
"e": 458,
"s": 447,
"text": "Example 1:"
},
{
"code": null,
"e": 560,
"s": 458,
"text": "Input:\nN = 11\nOutput:\n10\nExplanation:\nFrom 1 to 11,\n1,2,3,4,5,6,7,8,9,10\nare relatively prime to 11.\n"
},
{
"code": null,
"e": 571,
"s": 560,
"text": "Example 2:"
},
{
"code": null,
"e": 670,
"s": 571,
"text": "Input:\nN = 16\nOutput:\n8\nExplanation:\nFrom 1 to 16\n1,3,5,7,9,11,13,15 \nare relatively prime\nto 16.\n"
},
{
"code": null,
"e": 858,
"s": 670,
"text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function ETF() which takes one integer value N, as input parameter and return the value of Φ(N).\n "
},
{
"code": null,
"e": 928,
"s": 858,
"text": "Expected Time Complexity: O(NLog N)\nExpected Space Complexity: O(1)\n "
},
{
"code": null,
"e": 951,
"s": 928,
"text": "Constraints:\n1<=N<=105"
},
{
"code": null,
"e": 954,
"s": 951,
"text": "-1"
},
{
"code": null,
"e": 977,
"s": 954,
"text": "Nikhil Kumar1 year ago"
},
{
"code": null,
"e": 990,
"s": 977,
"text": "Nikhil Kumar"
},
{
"code": null,
"e": 1117,
"s": 990,
"text": "long long int gcd(long long int a, long long int b){ if (b == 0) return a; return gcd(b, a % b); }"
},
{
"code": null,
"e": 1356,
"s": 1117,
"text": " // function to find totient of n long long ETF(long long N){ long long count=0; for(long long i=1; i<=N; i++){ if(gcd(N, i)==1) count++; } return count; // code here }"
},
{
"code": null,
"e": 1393,
"s": 1356,
"text": "N logN is not getting accepted? why?"
},
{
"code": null,
"e": 1539,
"s": 1393,
"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": 1575,
"s": 1539,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 1585,
"s": 1575,
"text": "\nProblem\n"
},
{
"code": null,
"e": 1595,
"s": 1585,
"text": "\nContest\n"
},
{
"code": null,
"e": 1658,
"s": 1595,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 1806,
"s": 1658,
"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": 2014,
"s": 1806,
"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": 2120,
"s": 2014,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
]
|
EnumSet range() Method in Java - GeeksforGeeks | 02 Jul, 2018
The java.util.EnumSet.range(E start_point, E end_point) method in Java is used to create an enum set with the elements defined by the specified range in the parameters.
Syntax:
Enum_set = EnumSet.range(E start_point, E end_point)
Parameters: The method accepts two parameters of the object type of enum:
start_point: This refers to the starting element that is needed to be added to the enum set.
end_point: This refers to the last element which is needed to be added to the enum set.
Return Value: The method returns the enum set created by the elements mentioned within the specified range.
Exceptions: The method throws two types of exception:
NullPointerException is thrown if any of the starting or the last element is NULL.
IllegalArgumentException is thrown when the first element is greater than the last element with respect to the position.
Below programs illustrate the use of range() method:Program 1:
// Java program to demonstrate range() methodimport java.util.*; // Creating an enum of GFG typeenum GFG { Welcome, To, The, World, of, Geeks}; public class Enum_Set_Demo { public static void main(String[] args) { // Creating an EnumSet EnumSet<GFG> e_set; // Input the values using range() e_set = EnumSet.range(GFG.The, GFG.Geeks); // Displaying the new set System.out.println("The enum set is: " + e_set); }}
The enum set is: [The, World, of, Geeks]
Program 2:
// Java program to demonstrate range() methodimport java.util.*; // Creating an enum of CARS typeenum CARS { RANGE_ROVER, MUSTANG, CAMARO, AUDI, BMW}; public class Enum_Set_Demo { public static void main(String[] args) { // Creating an EnumSet EnumSet<CARS> e_set; // Input the values using range() e_set = EnumSet.range(CARS.RANGE_ROVER, CARS.CAMARO); // Displaying the new set System.out.println("The enum set is: " + e_set); }}
The enum set is: [RANGE_ROVER, MUSTANG, CAMARO]
java-EnumSet
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways of Reading a text file in Java
Constructors in Java
Stream In Java
Exceptions in Java
Generics in Java
Comparator Interface in Java with Examples
StringBuilder Class in Java with Examples
HashMap get() Method in Java
Functional Interfaces in Java
Strings in Java | [
{
"code": null,
"e": 23868,
"s": 23840,
"text": "\n02 Jul, 2018"
},
{
"code": null,
"e": 24037,
"s": 23868,
"text": "The java.util.EnumSet.range(E start_point, E end_point) method in Java is used to create an enum set with the elements defined by the specified range in the parameters."
},
{
"code": null,
"e": 24045,
"s": 24037,
"text": "Syntax:"
},
{
"code": null,
"e": 24098,
"s": 24045,
"text": "Enum_set = EnumSet.range(E start_point, E end_point)"
},
{
"code": null,
"e": 24172,
"s": 24098,
"text": "Parameters: The method accepts two parameters of the object type of enum:"
},
{
"code": null,
"e": 24265,
"s": 24172,
"text": "start_point: This refers to the starting element that is needed to be added to the enum set."
},
{
"code": null,
"e": 24353,
"s": 24265,
"text": "end_point: This refers to the last element which is needed to be added to the enum set."
},
{
"code": null,
"e": 24461,
"s": 24353,
"text": "Return Value: The method returns the enum set created by the elements mentioned within the specified range."
},
{
"code": null,
"e": 24515,
"s": 24461,
"text": "Exceptions: The method throws two types of exception:"
},
{
"code": null,
"e": 24598,
"s": 24515,
"text": "NullPointerException is thrown if any of the starting or the last element is NULL."
},
{
"code": null,
"e": 24719,
"s": 24598,
"text": "IllegalArgumentException is thrown when the first element is greater than the last element with respect to the position."
},
{
"code": null,
"e": 24782,
"s": 24719,
"text": "Below programs illustrate the use of range() method:Program 1:"
},
{
"code": "// Java program to demonstrate range() methodimport java.util.*; // Creating an enum of GFG typeenum GFG { Welcome, To, The, World, of, Geeks}; public class Enum_Set_Demo { public static void main(String[] args) { // Creating an EnumSet EnumSet<GFG> e_set; // Input the values using range() e_set = EnumSet.range(GFG.The, GFG.Geeks); // Displaying the new set System.out.println(\"The enum set is: \" + e_set); }}",
"e": 25273,
"s": 24782,
"text": null
},
{
"code": null,
"e": 25315,
"s": 25273,
"text": "The enum set is: [The, World, of, Geeks]\n"
},
{
"code": null,
"e": 25326,
"s": 25315,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate range() methodimport java.util.*; // Creating an enum of CARS typeenum CARS { RANGE_ROVER, MUSTANG, CAMARO, AUDI, BMW}; public class Enum_Set_Demo { public static void main(String[] args) { // Creating an EnumSet EnumSet<CARS> e_set; // Input the values using range() e_set = EnumSet.range(CARS.RANGE_ROVER, CARS.CAMARO); // Displaying the new set System.out.println(\"The enum set is: \" + e_set); }}",
"e": 25833,
"s": 25326,
"text": null
},
{
"code": null,
"e": 25882,
"s": 25833,
"text": "The enum set is: [RANGE_ROVER, MUSTANG, CAMARO]\n"
},
{
"code": null,
"e": 25895,
"s": 25882,
"text": "java-EnumSet"
},
{
"code": null,
"e": 25900,
"s": 25895,
"text": "Java"
},
{
"code": null,
"e": 25905,
"s": 25900,
"text": "Java"
},
{
"code": null,
"e": 26003,
"s": 25905,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26012,
"s": 26003,
"text": "Comments"
},
{
"code": null,
"e": 26025,
"s": 26012,
"text": "Old Comments"
},
{
"code": null,
"e": 26071,
"s": 26025,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 26092,
"s": 26071,
"text": "Constructors in Java"
},
{
"code": null,
"e": 26107,
"s": 26092,
"text": "Stream In Java"
},
{
"code": null,
"e": 26126,
"s": 26107,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 26143,
"s": 26126,
"text": "Generics in Java"
},
{
"code": null,
"e": 26186,
"s": 26143,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 26228,
"s": 26186,
"text": "StringBuilder Class in Java with Examples"
},
{
"code": null,
"e": 26257,
"s": 26228,
"text": "HashMap get() Method in Java"
},
{
"code": null,
"e": 26287,
"s": 26257,
"text": "Functional Interfaces in Java"
}
]
|
Get distinct record values in MongoDB? | You can use distinct() method in MongoDB to get distinct record values. The syntax is as follows −
db.yourCollectionName.distinct(“yourFieldName”);
To understand the above syntax, let us create a collection with document. The query to create a collection with document is as follows −
> db.distinctRecordDemo.insertOne({"StudentId":1,"StudentName":"John","StudentAge":21});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c77a78299b97a65744c1b50")
}
> db.distinctRecordDemo.insertOne({"StudentId":2,"StudentName":"John","StudentAge":22});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c77a78b99b97a65744c1b51")
}
> db.distinctRecordDemo.insertOne({"StudentId":3,"StudentName":"Carol","StudentAge":21});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c77a79a99b97a65744c1b52")
}
> db.distinctRecordDemo.insertOne({"StudentId":4,"StudentName":"Carol","StudentAge":26});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c77a7a499b97a65744c1b53")
}
> db.distinctRecordDemo.insertOne({"StudentId":5,"StudentName":"Sam","StudentAge":24});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c77a7b499b97a65744c1b54")
}
> db.distinctRecordDemo.insertOne({"StudentId":6,"StudentName":"Mike","StudentAge":27});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c77a7c799b97a65744c1b55")
}
> db.distinctRecordDemo.insertOne({"StudentId":7,"StudentName":"Sam","StudentAge":28});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c77a7d399b97a65744c1b56")
}
Display all documents from a collection with the help of find() method. The query is as follows −
> db.distinctRecordDemo.find().pretty();
The following is the output:
{
"_id" : ObjectId("5c77a78299b97a65744c1b50"),
"StudentId" : 1,
"StudentName" : "John",
"StudentAge" : 21
}
{
"_id" : ObjectId("5c77a78b99b97a65744c1b51"),
"StudentId" : 2,
"StudentName" : "John",
"StudentAge" : 22
}
{
"_id" : ObjectId("5c77a79a99b97a65744c1b52"),
"StudentId" : 3,
"StudentName" : "Carol",
"StudentAge" : 21
}
{
"_id" : ObjectId("5c77a7a499b97a65744c1b53"),
"StudentId" : 4,
"StudentName" : "Carol",
"StudentAge" : 26
}
{
"_id" : ObjectId("5c77a7b499b97a65744c1b54"),
"StudentId" : 5,
"StudentName" : "Sam",
"StudentAge" : 24
}
{
"_id" : ObjectId("5c77a7c799b97a65744c1b55"),
"StudentId" : 6,
"StudentName" : "Mike",
"StudentAge" : 27
}
{
"_id" : ObjectId("5c77a7d399b97a65744c1b56"),
"StudentId" : 7,
"StudentName" : "Sam",
"StudentAge" : 28
}
Here is the query to get distinct records values in MongoDB.
Case 1 − Here the field is “StudentName”.
The query is as follows −
> db.distinctRecordDemo.distinct("StudentName");
The following is the output displaying distinct record for StudentName −
[ "John", "Carol", "Sam", "Mike" ]
Case 2 − Here the field is “StudentAge”.
The query is as follows −
> db.distinctRecordDemo.distinct("StudentAge");
The following is the output displaying distinct record for StudentAge −
[ 21, 22, 26, 24, 27, 28 ] | [
{
"code": null,
"e": 1161,
"s": 1062,
"text": "You can use distinct() method in MongoDB to get distinct record values. The syntax is as follows −"
},
{
"code": null,
"e": 1210,
"s": 1161,
"text": "db.yourCollectionName.distinct(“yourFieldName”);"
},
{
"code": null,
"e": 1347,
"s": 1210,
"text": "To understand the above syntax, let us create a collection with document. The query to create a collection with document is as follows −"
},
{
"code": null,
"e": 2565,
"s": 1347,
"text": "> db.distinctRecordDemo.insertOne({\"StudentId\":1,\"StudentName\":\"John\",\"StudentAge\":21});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c77a78299b97a65744c1b50\")\n}\n> db.distinctRecordDemo.insertOne({\"StudentId\":2,\"StudentName\":\"John\",\"StudentAge\":22});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c77a78b99b97a65744c1b51\")\n}\n> db.distinctRecordDemo.insertOne({\"StudentId\":3,\"StudentName\":\"Carol\",\"StudentAge\":21});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c77a79a99b97a65744c1b52\")\n}\n> db.distinctRecordDemo.insertOne({\"StudentId\":4,\"StudentName\":\"Carol\",\"StudentAge\":26});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c77a7a499b97a65744c1b53\")\n}\n> db.distinctRecordDemo.insertOne({\"StudentId\":5,\"StudentName\":\"Sam\",\"StudentAge\":24});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c77a7b499b97a65744c1b54\")\n}\n> db.distinctRecordDemo.insertOne({\"StudentId\":6,\"StudentName\":\"Mike\",\"StudentAge\":27});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c77a7c799b97a65744c1b55\")\n}\n> db.distinctRecordDemo.insertOne({\"StudentId\":7,\"StudentName\":\"Sam\",\"StudentAge\":28});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c77a7d399b97a65744c1b56\")\n}"
},
{
"code": null,
"e": 2663,
"s": 2565,
"text": "Display all documents from a collection with the help of find() method. The query is as follows −"
},
{
"code": null,
"e": 2704,
"s": 2663,
"text": "> db.distinctRecordDemo.find().pretty();"
},
{
"code": null,
"e": 2733,
"s": 2704,
"text": "The following is the output:"
},
{
"code": null,
"e": 3580,
"s": 2733,
"text": "{\n \"_id\" : ObjectId(\"5c77a78299b97a65744c1b50\"),\n \"StudentId\" : 1,\n \"StudentName\" : \"John\",\n \"StudentAge\" : 21\n}\n{\n \"_id\" : ObjectId(\"5c77a78b99b97a65744c1b51\"),\n \"StudentId\" : 2,\n \"StudentName\" : \"John\",\n \"StudentAge\" : 22\n}\n{\n \"_id\" : ObjectId(\"5c77a79a99b97a65744c1b52\"),\n \"StudentId\" : 3,\n \"StudentName\" : \"Carol\",\n \"StudentAge\" : 21\n}\n{\n \"_id\" : ObjectId(\"5c77a7a499b97a65744c1b53\"),\n \"StudentId\" : 4,\n \"StudentName\" : \"Carol\",\n \"StudentAge\" : 26\n}\n{\n \"_id\" : ObjectId(\"5c77a7b499b97a65744c1b54\"),\n \"StudentId\" : 5,\n \"StudentName\" : \"Sam\",\n \"StudentAge\" : 24\n}\n{\n \"_id\" : ObjectId(\"5c77a7c799b97a65744c1b55\"),\n \"StudentId\" : 6,\n \"StudentName\" : \"Mike\",\n \"StudentAge\" : 27\n}\n{\n \"_id\" : ObjectId(\"5c77a7d399b97a65744c1b56\"),\n \"StudentId\" : 7,\n \"StudentName\" : \"Sam\",\n \"StudentAge\" : 28\n}"
},
{
"code": null,
"e": 3641,
"s": 3580,
"text": "Here is the query to get distinct records values in MongoDB."
},
{
"code": null,
"e": 3683,
"s": 3641,
"text": "Case 1 − Here the field is “StudentName”."
},
{
"code": null,
"e": 3709,
"s": 3683,
"text": "The query is as follows −"
},
{
"code": null,
"e": 3758,
"s": 3709,
"text": "> db.distinctRecordDemo.distinct(\"StudentName\");"
},
{
"code": null,
"e": 3831,
"s": 3758,
"text": "The following is the output displaying distinct record for StudentName −"
},
{
"code": null,
"e": 3866,
"s": 3831,
"text": "[ \"John\", \"Carol\", \"Sam\", \"Mike\" ]"
},
{
"code": null,
"e": 3907,
"s": 3866,
"text": "Case 2 − Here the field is “StudentAge”."
},
{
"code": null,
"e": 3933,
"s": 3907,
"text": "The query is as follows −"
},
{
"code": null,
"e": 3981,
"s": 3933,
"text": "> db.distinctRecordDemo.distinct(\"StudentAge\");"
},
{
"code": null,
"e": 4053,
"s": 3981,
"text": "The following is the output displaying distinct record for StudentAge −"
},
{
"code": null,
"e": 4080,
"s": 4053,
"text": "[ 21, 22, 26, 24, 27, 28 ]"
}
]
|
Majority Element | Practice | GeeksforGeeks | Given an array A of N elements. Find the majority element in the array. A majority element in an array A of size N is an element that appears more than N/2 times in the array.
Example 1:
Input:
N = 3
A[] = {1,2,3}
Output:
-1
Explanation:
Since, each element in
{1,2,3} appears only once so there
is no majority element.
Example 2:
Input:
N = 5
A[] = {3,1,3,3,2}
Output:
3
Explanation:
Since, 3 is present more
than N/2 times, so it is
the majority element.
Your Task:
The task is to complete the function majorityElement() which returns the majority element in the array. If no majority exists, return -1.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(1).
Constraints:
1 ≤ N ≤ 107
0 ≤ Ai ≤ 106
0
2016yashpratapin 6 hours
Beginner friendly...
class Solution{ static int majorityElement(int nums[], int size) { Arrays.sort(nums); int count =1; int n = nums.length-1; if( size==1) return nums[0]; for(int i=0;i<n;i++) { if(nums[i]==nums[i+1]) { count++; if(count>(size/2)) return nums[i]; } else { count = 1; } } return -1; }}
0
himanshusethin1 day ago
map<int,int> temp; for(int i =0;i<size;i++){ auto itr = temp.find(a[i]); if(itr == temp.end()){ temp.insert({a[i],1}); itr = temp.find(a[i]); } else itr->second = itr->second+1; if(itr->second > size/2) return itr->first; } return -1;
0
subhashishde081 day ago
#include<bits/stdc++.h>
int majorityElement(int a[], int size)
{
int x = size/2;
unordered_map<int,int> m;
for(int i=0;i<size;i++){
m[a[i]]++;
}
int res = -1;
for(int i=0;i<size;i++){
if(m[a[i]] > x){
res = a[i];
break;
}
}
return res;
}
0
sangrambachu2 days ago
Based on Expected Space and Time Complexity we can get to know that we need to apply moore's algorithm for this problem.
class Solution
{
static int majorityElement(int a[], int size)
{
// your code here
int count = 1;
int index = 0;
for(int i=0; i<size; i++) {
if(a[i] == a[index]) {
count++;
} else {
count--;
}
if(count == 0) {
index = i;
count = 1;
}
}
int element = a[index];
int realCount = 0;
for(int i=0; i<size; i++) {
if(element == a[i]) {
realCount++;
}
}
if(realCount > (size/2)) {
return element;
} else {
return -1;
}
}
}
0
lovesinghkalbhor2 days ago
class Solution{ public: // Function to find majority element in the array // a: input array // size: size of input array int majorityElement(int a[], int size) { int max = *max_element(a,a+size); int arr[max+1] = {0}; for(int i = 0; i<size; i++){ arr[a[i]] += 1; } int smax = *max_element(arr,arr+(max+1)); int i; if(smax>size/2){ for(i = 0;i<max+1;i++){ if(arr[i] == smax){ return i; } } }else{ return -1; } }};
0
abhishekdipu2 days ago
Javascript(Node) Solution :
class Solution { majorityElement (a, size){ let memo = {}; for (let i=0; i<size; i++){ if(!(a[i] in memo)){ memo[a[i]] = 1 }else{ memo[a[i]]++; } let freq = memo[a[i]]; if(freq > size/2) return a[i] } return -1 }}
0
kalaiabster2 days ago
JAVA SOLUTION : time taken (3.06/4.59)
static int majorityElement(int a[], int size) { Arrays.sort(a); int max=1,count=1,out=0; if(size==1) return a[0]; else { for(int i=1;i<a.length;i++) { if(a[i]==a[i-1]) count++; if(a[i]!=a[i-1]) count=1; if(count>max&&count>size/2) { max=count; out=a[i]; } } if(max==1) out=-1; return out; } }
0
riteshthakare11913 days ago
For begineer:
int majorityElement(int a[], int size) { int ans=-1; sort(a,a+size); for (int i=0;i<size;i++){ int count=1; while(i<(size-1) && a[i+1]==a[i]){ i++; count++; } if (count>(size/2)){ ans=a[i]; } } return ans; }
0
rohankurdekar06204 days ago
We can sort the array in c++ using library “algorithm”
and then traverse the array in O(n).
int majorityElement(int a[], int size) { sort(a,a+size); int i=0; int c=1; if(size<2) { return a[0]; } for(i=0;i<size-1;i++) { if(a[i]!=a[i+1]) { c=1; continue; } else { c++; if(c>size/2) { return a[i]; } } } return -1; }
0
akasksingh0804 days ago
The optimal algorithm for this type of question is based on :
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": 416,
"s": 238,
"text": "Given an array A of N elements. Find the majority element in the array. A majority element in an array A of size N is an element that appears more than N/2 times in the array.\n "
},
{
"code": null,
"e": 427,
"s": 416,
"text": "Example 1:"
},
{
"code": null,
"e": 565,
"s": 427,
"text": "Input:\nN = 3 \nA[] = {1,2,3} \nOutput:\n-1\nExplanation:\nSince, each element in \n{1,2,3} appears only once so there \nis no majority element.\n"
},
{
"code": null,
"e": 576,
"s": 565,
"text": "Example 2:"
},
{
"code": null,
"e": 706,
"s": 576,
"text": "Input:\nN = 5 \nA[] = {3,1,3,3,2} \nOutput:\n3\nExplanation:\nSince, 3 is present more\nthan N/2 times, so it is \nthe majority element.\n"
},
{
"code": null,
"e": 858,
"s": 706,
"text": "\nYour Task:\nThe task is to complete the function majorityElement() which returns the majority element in the array. If no majority exists, return -1.\n "
},
{
"code": null,
"e": 924,
"s": 858,
"text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(1).\n "
},
{
"code": null,
"e": 962,
"s": 924,
"text": "Constraints:\n1 ≤ N ≤ 107\n0 ≤ Ai ≤ 106"
},
{
"code": null,
"e": 964,
"s": 962,
"text": "0"
},
{
"code": null,
"e": 989,
"s": 964,
"text": "2016yashpratapin 6 hours"
},
{
"code": null,
"e": 1010,
"s": 989,
"text": "Beginner friendly..."
},
{
"code": null,
"e": 1480,
"s": 1012,
"text": "class Solution{ static int majorityElement(int nums[], int size) { Arrays.sort(nums); int count =1; int n = nums.length-1; if( size==1) return nums[0]; for(int i=0;i<n;i++) { if(nums[i]==nums[i+1]) { count++; if(count>(size/2)) return nums[i]; } else { count = 1; } } return -1; }}"
},
{
"code": null,
"e": 1482,
"s": 1480,
"text": "0"
},
{
"code": null,
"e": 1506,
"s": 1482,
"text": "himanshusethin1 day ago"
},
{
"code": null,
"e": 1869,
"s": 1506,
"text": "map<int,int> temp; for(int i =0;i<size;i++){ auto itr = temp.find(a[i]); if(itr == temp.end()){ temp.insert({a[i],1}); itr = temp.find(a[i]); } else itr->second = itr->second+1; if(itr->second > size/2) return itr->first; } return -1;"
},
{
"code": null,
"e": 1871,
"s": 1869,
"text": "0"
},
{
"code": null,
"e": 1895,
"s": 1871,
"text": "subhashishde081 day ago"
},
{
"code": null,
"e": 2213,
"s": 1895,
"text": "#include<bits/stdc++.h>\nint majorityElement(int a[], int size)\n{\n int x = size/2;\n unordered_map<int,int> m;\n for(int i=0;i<size;i++){\n m[a[i]]++;\n }\n int res = -1;\n for(int i=0;i<size;i++){\n if(m[a[i]] > x){\n res = a[i];\n break;\n }\n }\n return res;\n}"
},
{
"code": null,
"e": 2215,
"s": 2213,
"text": "0"
},
{
"code": null,
"e": 2238,
"s": 2215,
"text": "sangrambachu2 days ago"
},
{
"code": null,
"e": 2359,
"s": 2238,
"text": "Based on Expected Space and Time Complexity we can get to know that we need to apply moore's algorithm for this problem."
},
{
"code": null,
"e": 3121,
"s": 2361,
"text": "class Solution\n{\n static int majorityElement(int a[], int size)\n {\n // your code here\n int count = 1;\n int index = 0;\n \n for(int i=0; i<size; i++) {\n if(a[i] == a[index]) {\n count++;\n } else {\n count--;\n }\n \n if(count == 0) {\n index = i;\n count = 1;\n }\n }\n \n int element = a[index];\n int realCount = 0;\n for(int i=0; i<size; i++) {\n if(element == a[i]) {\n realCount++;\n }\n }\n \n if(realCount > (size/2)) {\n return element;\n } else {\n return -1;\n }\n \n }\n}"
},
{
"code": null,
"e": 3123,
"s": 3121,
"text": "0"
},
{
"code": null,
"e": 3150,
"s": 3123,
"text": "lovesinghkalbhor2 days ago"
},
{
"code": null,
"e": 3681,
"s": 3150,
"text": "class Solution{ public: // Function to find majority element in the array // a: input array // size: size of input array int majorityElement(int a[], int size) { int max = *max_element(a,a+size); int arr[max+1] = {0}; for(int i = 0; i<size; i++){ arr[a[i]] += 1; } int smax = *max_element(arr,arr+(max+1)); int i; if(smax>size/2){ for(i = 0;i<max+1;i++){ if(arr[i] == smax){ return i; } } }else{ return -1; } }};"
},
{
"code": null,
"e": 3683,
"s": 3681,
"text": "0"
},
{
"code": null,
"e": 3706,
"s": 3683,
"text": "abhishekdipu2 days ago"
},
{
"code": null,
"e": 3735,
"s": 3706,
"text": "Javascript(Node) Solution : "
},
{
"code": null,
"e": 4065,
"s": 3737,
"text": "class Solution { majorityElement (a, size){ let memo = {}; for (let i=0; i<size; i++){ if(!(a[i] in memo)){ memo[a[i]] = 1 }else{ memo[a[i]]++; } let freq = memo[a[i]]; if(freq > size/2) return a[i] } return -1 }}"
},
{
"code": null,
"e": 4067,
"s": 4065,
"text": "0"
},
{
"code": null,
"e": 4089,
"s": 4067,
"text": "kalaiabster2 days ago"
},
{
"code": null,
"e": 4130,
"s": 4089,
"text": "JAVA SOLUTION : time taken (3.06/4.59) "
},
{
"code": null,
"e": 4616,
"s": 4130,
"text": " static int majorityElement(int a[], int size) { Arrays.sort(a); int max=1,count=1,out=0; if(size==1) return a[0]; else { for(int i=1;i<a.length;i++) { if(a[i]==a[i-1]) count++; if(a[i]!=a[i-1]) count=1; if(count>max&&count>size/2) { max=count; out=a[i]; } } if(max==1) out=-1; return out; } }"
},
{
"code": null,
"e": 4618,
"s": 4616,
"text": "0"
},
{
"code": null,
"e": 4646,
"s": 4618,
"text": "riteshthakare11913 days ago"
},
{
"code": null,
"e": 4660,
"s": 4646,
"text": "For begineer:"
},
{
"code": null,
"e": 4951,
"s": 4660,
"text": "int majorityElement(int a[], int size) { int ans=-1; sort(a,a+size); for (int i=0;i<size;i++){ int count=1; while(i<(size-1) && a[i+1]==a[i]){ i++; count++; } if (count>(size/2)){ ans=a[i]; } } return ans; }"
},
{
"code": null,
"e": 4955,
"s": 4953,
"text": "0"
},
{
"code": null,
"e": 4983,
"s": 4955,
"text": "rohankurdekar06204 days ago"
},
{
"code": null,
"e": 5038,
"s": 4983,
"text": "We can sort the array in c++ using library “algorithm”"
},
{
"code": null,
"e": 5075,
"s": 5038,
"text": "and then traverse the array in O(n)."
},
{
"code": null,
"e": 5527,
"s": 5077,
"text": " int majorityElement(int a[], int size) { sort(a,a+size); int i=0; int c=1; if(size<2) { return a[0]; } for(i=0;i<size-1;i++) { if(a[i]!=a[i+1]) { c=1; continue; } else { c++; if(c>size/2) { return a[i]; } } } return -1; }"
},
{
"code": null,
"e": 5529,
"s": 5527,
"text": "0"
},
{
"code": null,
"e": 5553,
"s": 5529,
"text": "akasksingh0804 days ago"
},
{
"code": null,
"e": 5615,
"s": 5553,
"text": "The optimal algorithm for this type of question is based on :"
},
{
"code": null,
"e": 5761,
"s": 5615,
"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": 5797,
"s": 5761,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 5807,
"s": 5797,
"text": "\nProblem\n"
},
{
"code": null,
"e": 5817,
"s": 5807,
"text": "\nContest\n"
},
{
"code": null,
"e": 5880,
"s": 5817,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 6028,
"s": 5880,
"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": 6236,
"s": 6028,
"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": 6342,
"s": 6236,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
]
|
How to write inline if statement for print in Python? | Python provides two ways to write inline if statements. These are:
1. if condition: statement
2. s1 if condition else s2
Note that second type of if cannot be used without an else. Now you can use these inline in a print statement as well. For example,
a = True
if a: print("Hello")
This will give the output:
Hello
a = False
print("True" if a else "False")
This will give the output:
False | [
{
"code": null,
"e": 1129,
"s": 1062,
"text": "Python provides two ways to write inline if statements. These are:"
},
{
"code": null,
"e": 1156,
"s": 1129,
"text": "1. if condition: statement"
},
{
"code": null,
"e": 1183,
"s": 1156,
"text": "2. s1 if condition else s2"
},
{
"code": null,
"e": 1315,
"s": 1183,
"text": "Note that second type of if cannot be used without an else. Now you can use these inline in a print statement as well. For example,"
},
{
"code": null,
"e": 1345,
"s": 1315,
"text": "a = True\nif a: print(\"Hello\")"
},
{
"code": null,
"e": 1372,
"s": 1345,
"text": "This will give the output:"
},
{
"code": null,
"e": 1378,
"s": 1372,
"text": "Hello"
},
{
"code": null,
"e": 1420,
"s": 1378,
"text": "a = False\nprint(\"True\" if a else \"False\")"
},
{
"code": null,
"e": 1447,
"s": 1420,
"text": "This will give the output:"
},
{
"code": null,
"e": 1453,
"s": 1447,
"text": "False"
}
]
|
Convert Excel to CSV in Python - GeeksforGeeks | 06 Dec, 2021
In this article, we will be dealing with the conversion of Excel (.xlsx) file into .csv. There are two formats mostly used in Excel :
(*.xlsx) : Excel Microsoft Office Open XML Format Spreadsheet file.(*.xls) : Excel Spreadsheet (Excel 97-2003 workbook).
(*.xlsx) : Excel Microsoft Office Open XML Format Spreadsheet file.
(*.xls) : Excel Spreadsheet (Excel 97-2003 workbook).
Let’s Consider a dataset of a shopping store having data about Customer Serial Number, Customer Name, Customer ID, and Product Cost stored in Excel file.
check all used files here.
Python3
# importing pandas as pdimport pandas as pd # read an excel file and convert # into a dataframe objectdf = pd.DataFrame(pd.read_excel("Test.xlsx")) # show the dataframedf
Output :
Now, let’s see different ways to convert an Excel file into a CSV file :
Pandas is an open-source software library built for data manipulation and analysis for Python programming language. It offers various functionality in terms of data structures and operations for manipulating numerical tables and time series. It can read, filter, and re-arrange small and large datasets and output them in a range of formats including Excel, JSON, CSV.
For reading an excel file, using the read_excel() method and convert the data frame into the CSV file, use to_csv() method of pandas.
Code:
Python3
#importing pandas as pdimport pandas as pd # Read and store content# of an excel file read_file = pd.read_excel ("Test.xlsx") # Write the dataframe object# into csv fileread_file.to_csv ("Test.csv", index = None, header=True) # read csv file and convert # into a dataframe objectdf = pd.DataFrame(pd.read_csv("Test.csv")) # show the dataframedf
Output:
xlrd is a library with the main purpose to read an excel file.
csv is a library with the main purpose to read and write a csv file.
Code:
Python3
# import all required libraryimport xlrd import csvimport pandas as pd # open workbook by sheet index,# optional - sheet_by_index()sheet = xlrd.open_workbook("Test.xlsx").sheet_by_index(0) # writer object is createdcol = csv.writer(open("T.csv", 'w', newline="")) # writing the data into csv filefor row in range(sheet.nrows): # row by row write # operation is perform col.writerow(sheet.row_values(row)) # read csv file and convert # into a dataframe objectdf = pd.DataFrame(pd.read_csv("T.csv")) # show the dataframedf
Output:
openpyxl is a library to read/write Excel 2010 xlsx/xlsm/xltx/xltm files.It was born from lack of existing library to read/write natively from Python the Office Open XML format.
Code:
Python3
# importe required librariesimport openpyxlimport csvimport pandas as pd # open given workbook # and store in excel object excel = openpyxl.load_workbook("Test.xlsx") # select the active sheetsheet = excel.active # writer object is createdcol = csv.writer(open("tt.csv", 'w', newline="")) # writing the data in csv filefor r in sheet.rows: # row by row write # operation is perform col.writerow([cell.value for cell in r]) # read the csv file and # convert into dataframe object df = pd.DataFrame(pd.read_csv("tt.csv")) # show the dataframedf
Output:
sooda367
python-csv
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Read a file line by line in Python
Enumerate() in Python
Different ways to create Pandas Dataframe
Create a Pandas DataFrame from Lists
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
How to drop one or multiple columns in Pandas Dataframe | [
{
"code": null,
"e": 24820,
"s": 24792,
"text": "\n06 Dec, 2021"
},
{
"code": null,
"e": 24955,
"s": 24820,
"text": "In this article, we will be dealing with the conversion of Excel (.xlsx) file into .csv. There are two formats mostly used in Excel :"
},
{
"code": null,
"e": 25076,
"s": 24955,
"text": "(*.xlsx) : Excel Microsoft Office Open XML Format Spreadsheet file.(*.xls) : Excel Spreadsheet (Excel 97-2003 workbook)."
},
{
"code": null,
"e": 25144,
"s": 25076,
"text": "(*.xlsx) : Excel Microsoft Office Open XML Format Spreadsheet file."
},
{
"code": null,
"e": 25198,
"s": 25144,
"text": "(*.xls) : Excel Spreadsheet (Excel 97-2003 workbook)."
},
{
"code": null,
"e": 25353,
"s": 25198,
"text": "Let’s Consider a dataset of a shopping store having data about Customer Serial Number, Customer Name, Customer ID, and Product Cost stored in Excel file. "
},
{
"code": null,
"e": 25380,
"s": 25353,
"text": "check all used files here."
},
{
"code": null,
"e": 25388,
"s": 25380,
"text": "Python3"
},
{
"code": "# importing pandas as pdimport pandas as pd # read an excel file and convert # into a dataframe objectdf = pd.DataFrame(pd.read_excel(\"Test.xlsx\")) # show the dataframedf",
"e": 25561,
"s": 25388,
"text": null
},
{
"code": null,
"e": 25571,
"s": 25561,
"text": "Output : "
},
{
"code": null,
"e": 25644,
"s": 25571,
"text": "Now, let’s see different ways to convert an Excel file into a CSV file :"
},
{
"code": null,
"e": 26013,
"s": 25644,
"text": "Pandas is an open-source software library built for data manipulation and analysis for Python programming language. It offers various functionality in terms of data structures and operations for manipulating numerical tables and time series. It can read, filter, and re-arrange small and large datasets and output them in a range of formats including Excel, JSON, CSV."
},
{
"code": null,
"e": 26147,
"s": 26013,
"text": "For reading an excel file, using the read_excel() method and convert the data frame into the CSV file, use to_csv() method of pandas."
},
{
"code": null,
"e": 26153,
"s": 26147,
"text": "Code:"
},
{
"code": null,
"e": 26161,
"s": 26153,
"text": "Python3"
},
{
"code": "#importing pandas as pdimport pandas as pd # Read and store content# of an excel file read_file = pd.read_excel (\"Test.xlsx\") # Write the dataframe object# into csv fileread_file.to_csv (\"Test.csv\", index = None, header=True) # read csv file and convert # into a dataframe objectdf = pd.DataFrame(pd.read_csv(\"Test.csv\")) # show the dataframedf",
"e": 26547,
"s": 26161,
"text": null
},
{
"code": null,
"e": 26557,
"s": 26547,
"text": " Output: "
},
{
"code": null,
"e": 26623,
"s": 26559,
"text": "xlrd is a library with the main purpose to read an excel file. "
},
{
"code": null,
"e": 26692,
"s": 26623,
"text": "csv is a library with the main purpose to read and write a csv file."
},
{
"code": null,
"e": 26698,
"s": 26692,
"text": "Code:"
},
{
"code": null,
"e": 26706,
"s": 26698,
"text": "Python3"
},
{
"code": "# import all required libraryimport xlrd import csvimport pandas as pd # open workbook by sheet index,# optional - sheet_by_index()sheet = xlrd.open_workbook(\"Test.xlsx\").sheet_by_index(0) # writer object is createdcol = csv.writer(open(\"T.csv\", 'w', newline=\"\")) # writing the data into csv filefor row in range(sheet.nrows): # row by row write # operation is perform col.writerow(sheet.row_values(row)) # read csv file and convert # into a dataframe objectdf = pd.DataFrame(pd.read_csv(\"T.csv\")) # show the dataframedf",
"e": 27286,
"s": 26706,
"text": null
},
{
"code": null,
"e": 27296,
"s": 27286,
"text": " Output: "
},
{
"code": null,
"e": 27474,
"s": 27296,
"text": "openpyxl is a library to read/write Excel 2010 xlsx/xlsm/xltx/xltm files.It was born from lack of existing library to read/write natively from Python the Office Open XML format."
},
{
"code": null,
"e": 27480,
"s": 27474,
"text": "Code:"
},
{
"code": null,
"e": 27488,
"s": 27480,
"text": "Python3"
},
{
"code": "# importe required librariesimport openpyxlimport csvimport pandas as pd # open given workbook # and store in excel object excel = openpyxl.load_workbook(\"Test.xlsx\") # select the active sheetsheet = excel.active # writer object is createdcol = csv.writer(open(\"tt.csv\", 'w', newline=\"\")) # writing the data in csv filefor r in sheet.rows: # row by row write # operation is perform col.writerow([cell.value for cell in r]) # read the csv file and # convert into dataframe object df = pd.DataFrame(pd.read_csv(\"tt.csv\")) # show the dataframedf",
"e": 28090,
"s": 27488,
"text": null
},
{
"code": null,
"e": 28100,
"s": 28090,
"text": " Output: "
},
{
"code": null,
"e": 28109,
"s": 28100,
"text": "sooda367"
},
{
"code": null,
"e": 28120,
"s": 28109,
"text": "python-csv"
},
{
"code": null,
"e": 28134,
"s": 28120,
"text": "Python-pandas"
},
{
"code": null,
"e": 28141,
"s": 28134,
"text": "Python"
},
{
"code": null,
"e": 28239,
"s": 28141,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28248,
"s": 28239,
"text": "Comments"
},
{
"code": null,
"e": 28261,
"s": 28248,
"text": "Old Comments"
},
{
"code": null,
"e": 28279,
"s": 28261,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28311,
"s": 28279,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28346,
"s": 28311,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28368,
"s": 28346,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28410,
"s": 28368,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28447,
"s": 28410,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 28473,
"s": 28447,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28517,
"s": 28473,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 28546,
"s": 28517,
"text": "*args and **kwargs in Python"
}
]
|
Calculate the Root of a Equation within an interval in R Programming - uniroot() Function - GeeksforGeeks | 12 Jun, 2020
uniroot() function in R Language is used to calculate the root of an equation with the lower and upper range of the interval passed as arguments.
Syntax: uniroot(fun, interval, lower, upper)
Parameters:fun: function with the equationinterval: with upper and lower range of rootlower: lower end point of the intervalupper: upper end point of the interval
Example 1:
# R program to calculate root of an equation # Function with equationfun <- function(x) {2 * x ^ 2 - 4 * x -10} # Calling uniroot() functionuniroot(fun, lower = 0, upper = 4)
Output:
$root
[1] 3.449485
$f.root
[1] -4.310493e-05
$iter
[1] 5
$init.it
[1] NA
$estim.prec
[1] 6.103516e-05
Example 2:
# R program to calculate root of an equation # Function with equationfun <- function(x) {2 * x ^ 2 - 4 * x -10} # Calling uniroot() functionuniroot(fun, c(0, 4))$rootuniroot(fun, lower = -4, upper = 0)$root
Output:
[1] 3.449485
[1] -1.44949
R Math-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Replace specific values in column in R DataFrame ?
How to change Row Names of DataFrame in R ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
K-Means Clustering in R Programming
Remove rows with NA in one column of R DataFrame | [
{
"code": null,
"e": 24527,
"s": 24499,
"text": "\n12 Jun, 2020"
},
{
"code": null,
"e": 24673,
"s": 24527,
"text": "uniroot() function in R Language is used to calculate the root of an equation with the lower and upper range of the interval passed as arguments."
},
{
"code": null,
"e": 24718,
"s": 24673,
"text": "Syntax: uniroot(fun, interval, lower, upper)"
},
{
"code": null,
"e": 24881,
"s": 24718,
"text": "Parameters:fun: function with the equationinterval: with upper and lower range of rootlower: lower end point of the intervalupper: upper end point of the interval"
},
{
"code": null,
"e": 24892,
"s": 24881,
"text": "Example 1:"
},
{
"code": "# R program to calculate root of an equation # Function with equationfun <- function(x) {2 * x ^ 2 - 4 * x -10} # Calling uniroot() functionuniroot(fun, lower = 0, upper = 4)",
"e": 25069,
"s": 24892,
"text": null
},
{
"code": null,
"e": 25077,
"s": 25069,
"text": "Output:"
},
{
"code": null,
"e": 25184,
"s": 25077,
"text": "$root\n[1] 3.449485\n\n$f.root\n[1] -4.310493e-05\n\n$iter\n[1] 5\n\n$init.it\n[1] NA\n\n$estim.prec\n[1] 6.103516e-05\n"
},
{
"code": null,
"e": 25195,
"s": 25184,
"text": "Example 2:"
},
{
"code": "# R program to calculate root of an equation # Function with equationfun <- function(x) {2 * x ^ 2 - 4 * x -10} # Calling uniroot() functionuniroot(fun, c(0, 4))$rootuniroot(fun, lower = -4, upper = 0)$root",
"e": 25404,
"s": 25195,
"text": null
},
{
"code": null,
"e": 25412,
"s": 25404,
"text": "Output:"
},
{
"code": null,
"e": 25439,
"s": 25412,
"text": "[1] 3.449485\n[1] -1.44949\n"
},
{
"code": null,
"e": 25455,
"s": 25439,
"text": "R Math-Function"
},
{
"code": null,
"e": 25466,
"s": 25455,
"text": "R Language"
},
{
"code": null,
"e": 25564,
"s": 25466,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25573,
"s": 25564,
"text": "Comments"
},
{
"code": null,
"e": 25586,
"s": 25573,
"text": "Old Comments"
},
{
"code": null,
"e": 25644,
"s": 25586,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 25688,
"s": 25644,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 25740,
"s": 25688,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 25772,
"s": 25740,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 25824,
"s": 25772,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 25862,
"s": 25824,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 25897,
"s": 25862,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 25955,
"s": 25897,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 25991,
"s": 25955,
"text": "K-Means Clustering in R Programming"
}
]
|
Data Structures and Algorithms | Set 2 - GeeksforGeeks | 12 Apr, 2019
Following questions have been asked in GATE CS exam.
1. Consider the function f defined below.
struct item { int data; struct item * next; }; int f(struct item *p) { return ( (p == NULL) || (p->next == NULL) || (( P->data <= p->next->data) && f(p->next)) ); }
For a given linked list p, the function f returns 1 if and only if (GATE CS 2003)a) the list is empty or has exactly one elementb) the elements in the list are sorted in non-decreasing order of data valuec) the elements in the list are sorted in non-increasing order of data valued) not all elements in the list have the same data value.
Answer (b)The function f() works as follows1) If linked list is empty return 12) Else If linked list has only one element return 13) Else if node->data is smaller than equal to node->next->data and the same thing holds for rest of the list then return 14) Else return 0
2. Consider the label sequences obtained by the following pairs of traversals on a labeled binary tree. Which of these pairs identify a tree uniquely (GATE CS 2004)?i) preorder and postorderii) inorder and postorderiii) preorder and inorderiv) level order and postorder
a) (i) onlyb) (ii), (iii)c) (iii) onlyd) (iv) only
Answer (b)Please see this post for the explanation.
3. The following numbers are inserted into an empty binary search tree in the given order: 10, 1, 3, 5, 15, 12, 16. What is the height of the binary search tree (the height is the maximum distance of a leaf node from the root)? (GATE CS 2004)a) 2b) 3c) 4d) 6
Answer(b)Constructed binary search tree will be..
10
/ \
1 15
\ / \
3 12 16
\
5
4. A data structure is required for storing a set of integers such that each of the following operations can be done in (log n) time, where n is the number of elements in the set.
o Deletion of the smallest element
o Insertion of an element if it is not already present in the set
Which of the following data structures can be used for this purpose?(a) A heap can be used but not a balanced binary search tree(b) A balanced binary search tree can be used but not a heap(c) Both balanced binary search tree and heap can be used(d) Neither balanced binary search tree nor heap can be used
Answer(b)A self-balancing balancing binary search tree containing n items allows the lookup, insertion, and removal of an item in O(log n) worst-case time. Since it’s a self-balancing BST, we can easily find out minimum element in O(logn) time which is always the leftmost element (See Find the node with the minimum value in a Binary Search Tree).
Since Heap is a balanced binary tree (or almost complete binary tree), insertion complexity for heap is O(logn). Also, complexity to get minimum in a min heap is O(logn) because removal of root node causes a call to heapify (after removing the first element from the array) to maintain the heap tree property. But a heap cannot be used for the above purpose as the question says – insert an element if it is not already present. For a heap, we cannot find out in O(logn) if an element is present or not. Thanks to the game for providing the correct solution.
5. A circularly linked list is used to represent a Queue. A single variable p is used to access the Queue. To which node should p point such that both the operations enQueue and deQueue can be performed in constant time? (GATE 2004)
a) rear nodeb) front nodec) not possible with a single pointerd) node next to the front
Answer(a)The answer is not “(b) front node”, as we can not get rear from the front in O(1), but if p is rear we can implement both enQueue and deQueue in O(1) because from rear we can get front in O(1). Below are sample functions. Note that these functions are just sample and are not working. Code to handle base cases is missing.
/* p is pointer to address of rear (double pointer). This function adds new node after rear and updates rear which is *p to point to new node */void enQueue(struct node **p, struct node *new_node){ /* Missing code to handle base cases like *p is NULL */ new_node->next = (*p)->next; (*p)->next = new_node; (*p) = new_node /* new is now rear */ /* Note that p is again front and p->next is rear */ } /* p is pointer to rear. This function removes the front element and returns the new front */struct node *deQueue(struct node *p){ /* Missing code to handle base cases like p is NULL, p->next is NULL,... etc */ struct node *temp = p->next->next; p->next = p->next->next; return temp; /* Note that p is again front and p->next is rear */}
Akanksha_Rai
GATE-CS-2003
GATE-CS-2004
GATE-CS-DS-&-Algo
GATE CS
MCQ
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Page Replacement Algorithms in Operating Systems
Differences between TCP and UDP
Data encryption standard (DES) | Set 1
Introduction of Operating System - Set 1
Types of Network Topology
Data Structures and Algorithms | Set 21
Practice questions on Height balanced/AVL Tree
Operating Systems | Set 1
Computer Networks | Set 1
Computer Networks | Set 2 | [
{
"code": null,
"e": 23885,
"s": 23857,
"text": "\n12 Apr, 2019"
},
{
"code": null,
"e": 23938,
"s": 23885,
"text": "Following questions have been asked in GATE CS exam."
},
{
"code": null,
"e": 23980,
"s": 23938,
"text": "1. Consider the function f defined below."
},
{
"code": "struct item { int data; struct item * next; }; int f(struct item *p) { return ( (p == NULL) || (p->next == NULL) || (( P->data <= p->next->data) && f(p->next)) ); } ",
"e": 24191,
"s": 23980,
"text": null
},
{
"code": null,
"e": 24529,
"s": 24191,
"text": "For a given linked list p, the function f returns 1 if and only if (GATE CS 2003)a) the list is empty or has exactly one elementb) the elements in the list are sorted in non-decreasing order of data valuec) the elements in the list are sorted in non-increasing order of data valued) not all elements in the list have the same data value."
},
{
"code": null,
"e": 24799,
"s": 24529,
"text": "Answer (b)The function f() works as follows1) If linked list is empty return 12) Else If linked list has only one element return 13) Else if node->data is smaller than equal to node->next->data and the same thing holds for rest of the list then return 14) Else return 0"
},
{
"code": null,
"e": 25069,
"s": 24799,
"text": "2. Consider the label sequences obtained by the following pairs of traversals on a labeled binary tree. Which of these pairs identify a tree uniquely (GATE CS 2004)?i) preorder and postorderii) inorder and postorderiii) preorder and inorderiv) level order and postorder"
},
{
"code": null,
"e": 25120,
"s": 25069,
"text": "a) (i) onlyb) (ii), (iii)c) (iii) onlyd) (iv) only"
},
{
"code": null,
"e": 25172,
"s": 25120,
"text": "Answer (b)Please see this post for the explanation."
},
{
"code": null,
"e": 25431,
"s": 25172,
"text": "3. The following numbers are inserted into an empty binary search tree in the given order: 10, 1, 3, 5, 15, 12, 16. What is the height of the binary search tree (the height is the maximum distance of a leaf node from the root)? (GATE CS 2004)a) 2b) 3c) 4d) 6"
},
{
"code": null,
"e": 25481,
"s": 25431,
"text": "Answer(b)Constructed binary search tree will be.."
},
{
"code": null,
"e": 25663,
"s": 25481,
"text": " 10\n / \\\n 1 15\n \\ / \\\n 3 12 16\n \\\n 5"
},
{
"code": null,
"e": 25843,
"s": 25663,
"text": "4. A data structure is required for storing a set of integers such that each of the following operations can be done in (log n) time, where n is the number of elements in the set."
},
{
"code": null,
"e": 25958,
"s": 25843,
"text": " o Deletion of the smallest element \n o Insertion of an element if it is not already present in the set\n"
},
{
"code": null,
"e": 26264,
"s": 25958,
"text": "Which of the following data structures can be used for this purpose?(a) A heap can be used but not a balanced binary search tree(b) A balanced binary search tree can be used but not a heap(c) Both balanced binary search tree and heap can be used(d) Neither balanced binary search tree nor heap can be used"
},
{
"code": null,
"e": 26613,
"s": 26264,
"text": "Answer(b)A self-balancing balancing binary search tree containing n items allows the lookup, insertion, and removal of an item in O(log n) worst-case time. Since it’s a self-balancing BST, we can easily find out minimum element in O(logn) time which is always the leftmost element (See Find the node with the minimum value in a Binary Search Tree)."
},
{
"code": null,
"e": 27172,
"s": 26613,
"text": "Since Heap is a balanced binary tree (or almost complete binary tree), insertion complexity for heap is O(logn). Also, complexity to get minimum in a min heap is O(logn) because removal of root node causes a call to heapify (after removing the first element from the array) to maintain the heap tree property. But a heap cannot be used for the above purpose as the question says – insert an element if it is not already present. For a heap, we cannot find out in O(logn) if an element is present or not. Thanks to the game for providing the correct solution."
},
{
"code": null,
"e": 27405,
"s": 27172,
"text": "5. A circularly linked list is used to represent a Queue. A single variable p is used to access the Queue. To which node should p point such that both the operations enQueue and deQueue can be performed in constant time? (GATE 2004)"
},
{
"code": null,
"e": 27493,
"s": 27405,
"text": "a) rear nodeb) front nodec) not possible with a single pointerd) node next to the front"
},
{
"code": null,
"e": 27825,
"s": 27493,
"text": "Answer(a)The answer is not “(b) front node”, as we can not get rear from the front in O(1), but if p is rear we can implement both enQueue and deQueue in O(1) because from rear we can get front in O(1). Below are sample functions. Note that these functions are just sample and are not working. Code to handle base cases is missing."
},
{
"code": "/* p is pointer to address of rear (double pointer). This function adds new node after rear and updates rear which is *p to point to new node */void enQueue(struct node **p, struct node *new_node){ /* Missing code to handle base cases like *p is NULL */ new_node->next = (*p)->next; (*p)->next = new_node; (*p) = new_node /* new is now rear */ /* Note that p is again front and p->next is rear */ } /* p is pointer to rear. This function removes the front element and returns the new front */struct node *deQueue(struct node *p){ /* Missing code to handle base cases like p is NULL, p->next is NULL,... etc */ struct node *temp = p->next->next; p->next = p->next->next; return temp; /* Note that p is again front and p->next is rear */}",
"e": 28626,
"s": 27825,
"text": null
},
{
"code": null,
"e": 28639,
"s": 28626,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 28652,
"s": 28639,
"text": "GATE-CS-2003"
},
{
"code": null,
"e": 28665,
"s": 28652,
"text": "GATE-CS-2004"
},
{
"code": null,
"e": 28683,
"s": 28665,
"text": "GATE-CS-DS-&-Algo"
},
{
"code": null,
"e": 28691,
"s": 28683,
"text": "GATE CS"
},
{
"code": null,
"e": 28695,
"s": 28691,
"text": "MCQ"
},
{
"code": null,
"e": 28793,
"s": 28695,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28802,
"s": 28793,
"text": "Comments"
},
{
"code": null,
"e": 28815,
"s": 28802,
"text": "Old Comments"
},
{
"code": null,
"e": 28864,
"s": 28815,
"text": "Page Replacement Algorithms in Operating Systems"
},
{
"code": null,
"e": 28896,
"s": 28864,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 28935,
"s": 28896,
"text": "Data encryption standard (DES) | Set 1"
},
{
"code": null,
"e": 28976,
"s": 28935,
"text": "Introduction of Operating System - Set 1"
},
{
"code": null,
"e": 29002,
"s": 28976,
"text": "Types of Network Topology"
},
{
"code": null,
"e": 29042,
"s": 29002,
"text": "Data Structures and Algorithms | Set 21"
},
{
"code": null,
"e": 29089,
"s": 29042,
"text": "Practice questions on Height balanced/AVL Tree"
},
{
"code": null,
"e": 29115,
"s": 29089,
"text": "Operating Systems | Set 1"
},
{
"code": null,
"e": 29141,
"s": 29115,
"text": "Computer Networks | Set 1"
}
]
|
ggplot2 - Themes | In this chapter, we will focus on using customized theme which is used for changing the look and feel of workspace. We will use “ggthemes” package to understand the concept of theme management in workspace of R.
Let us implement following steps to use the required theme within mentioned dataset.
Install “ggthemes” package with the required package in R workspace.
> install.packages("ggthemes")
> Library(ggthemes)
Implement new theme to generate legends of manufacturers with year of production and displacement.
> library(ggthemes)
> ggplot(mpg, aes(year, displ, color=factor(manufacturer)))+
+ geom_point()+ggtitle("This plot looks a lot different from the default")+
+ theme_economist()+scale_colour_economist()
It can be observed that the default size of the tick text, legends and other elements are little small with previous theme management. It is incredibly easy to change the size of all the text elements at once. This can be done on creating a custom theme which we can observe in below step that the sizes of all the elements are relative (rel()) to the base_size.
> theme_set(theme_gray(base_size = 30))
> ggplot(mpg, aes(x=year, y=class))+geom_point(color="red")
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2234,
"s": 2022,
"text": "In this chapter, we will focus on using customized theme which is used for changing the look and feel of workspace. We will use “ggthemes” package to understand the concept of theme management in workspace of R."
},
{
"code": null,
"e": 2319,
"s": 2234,
"text": "Let us implement following steps to use the required theme within mentioned dataset."
},
{
"code": null,
"e": 2388,
"s": 2319,
"text": "Install “ggthemes” package with the required package in R workspace."
},
{
"code": null,
"e": 2440,
"s": 2388,
"text": "> install.packages(\"ggthemes\")\n> Library(ggthemes)\n"
},
{
"code": null,
"e": 2539,
"s": 2440,
"text": "Implement new theme to generate legends of manufacturers with year of production and displacement."
},
{
"code": null,
"e": 2742,
"s": 2539,
"text": "> library(ggthemes)\n> ggplot(mpg, aes(year, displ, color=factor(manufacturer)))+\n+ geom_point()+ggtitle(\"This plot looks a lot different from the default\")+\n+ theme_economist()+scale_colour_economist()\n"
},
{
"code": null,
"e": 3105,
"s": 2742,
"text": "It can be observed that the default size of the tick text, legends and other elements are little small with previous theme management. It is incredibly easy to change the size of all the text elements at once. This can be done on creating a custom theme which we can observe in below step that the sizes of all the elements are relative (rel()) to the base_size."
},
{
"code": null,
"e": 3206,
"s": 3105,
"text": "> theme_set(theme_gray(base_size = 30))\n> ggplot(mpg, aes(x=year, y=class))+geom_point(color=\"red\")\n"
},
{
"code": null,
"e": 3213,
"s": 3206,
"text": " Print"
},
{
"code": null,
"e": 3224,
"s": 3213,
"text": " Add Notes"
}
]
|
Explain the characteristics and operations of arrays in C language | An array is a homogeneous sequential collection of data items over a single variable name.
For example, int student[30];
Here, student is an array name holds 30 collection of data item, with a single variable name.
The characteristics of arrays are as follows −
An array is always stored in consecutive memory location.
An array is always stored in consecutive memory location.
It can store multiple value of similar type, which can be referred with single name.
It can store multiple value of similar type, which can be referred with single name.
The pointer points to the first location of memory block, which is allocated to the
array name.
The pointer points to the first location of memory block, which is allocated to the
array name.
An array can either be an integer, character, or float data type that can be initialised only during the declaration.
An array can either be an integer, character, or float data type that can be initialised only during the declaration.
The particular element of an array can be modified separately without changing the
other elements.
The particular element of an array can be modified separately without changing the
other elements.
All elements of an array can be distinguishing with the help of index number.
All elements of an array can be distinguishing with the help of index number.
The operations of an array include −
Searching − It is used to find whether particular element is present or not.
Searching − It is used to find whether particular element is present or not.
Sorting − Helps in arranging the elements in an array either in an ascending or descending order.
Sorting − Helps in arranging the elements in an array either in an ascending or descending order.
Traversing − Processing every element in an array, sequentially.
Traversing − Processing every element in an array, sequentially.
Inserting − Helps in inserting elements in an array.
Inserting − Helps in inserting elements in an array.
Deleting − helps in deleting the element in an array.
Deleting − helps in deleting the element in an array.
Following is the C program for searching an element in an array −
Live Demo
#include <stdio.h>
#define MAX 100 // Maximum array size
int main(){
int array[MAX];
int size, i, search, found;
printf("Enter size of array: ");
scanf("%d", &size);
printf("Enter elements in array: ");
for(i=0; i<size; i++){
scanf("%d", &array[i]);
}
printf("\nEnter element to search: ");
scanf("%d", &search);
found = 0;
for(i=0; i<size; i++){
if(array[i] == search){
found = 1;
break;
}
}
if(found == 1){
printf("\n%d is found at position %d", search, i + 1);
} else {
printf("\n%d is not found in the array", search);
}
return 0;
}
The output is as follows −
Enter size of array: 5
Enter elements in array: 11 24 13 12 45
Enter element to search: 13
13 found at position 3found | [
{
"code": null,
"e": 1153,
"s": 1062,
"text": "An array is a homogeneous sequential collection of data items over a single variable name."
},
{
"code": null,
"e": 1183,
"s": 1153,
"text": "For example, int student[30];"
},
{
"code": null,
"e": 1277,
"s": 1183,
"text": "Here, student is an array name holds 30 collection of data item, with a single variable name."
},
{
"code": null,
"e": 1324,
"s": 1277,
"text": "The characteristics of arrays are as follows −"
},
{
"code": null,
"e": 1382,
"s": 1324,
"text": "An array is always stored in consecutive memory location."
},
{
"code": null,
"e": 1440,
"s": 1382,
"text": "An array is always stored in consecutive memory location."
},
{
"code": null,
"e": 1525,
"s": 1440,
"text": "It can store multiple value of similar type, which can be referred with single name."
},
{
"code": null,
"e": 1610,
"s": 1525,
"text": "It can store multiple value of similar type, which can be referred with single name."
},
{
"code": null,
"e": 1706,
"s": 1610,
"text": "The pointer points to the first location of memory block, which is allocated to the\narray name."
},
{
"code": null,
"e": 1802,
"s": 1706,
"text": "The pointer points to the first location of memory block, which is allocated to the\narray name."
},
{
"code": null,
"e": 1920,
"s": 1802,
"text": "An array can either be an integer, character, or float data type that can be initialised only during the declaration."
},
{
"code": null,
"e": 2038,
"s": 1920,
"text": "An array can either be an integer, character, or float data type that can be initialised only during the declaration."
},
{
"code": null,
"e": 2137,
"s": 2038,
"text": "The particular element of an array can be modified separately without changing the\nother elements."
},
{
"code": null,
"e": 2236,
"s": 2137,
"text": "The particular element of an array can be modified separately without changing the\nother elements."
},
{
"code": null,
"e": 2314,
"s": 2236,
"text": "All elements of an array can be distinguishing with the help of index number."
},
{
"code": null,
"e": 2392,
"s": 2314,
"text": "All elements of an array can be distinguishing with the help of index number."
},
{
"code": null,
"e": 2429,
"s": 2392,
"text": "The operations of an array include −"
},
{
"code": null,
"e": 2506,
"s": 2429,
"text": "Searching − It is used to find whether particular element is present or not."
},
{
"code": null,
"e": 2583,
"s": 2506,
"text": "Searching − It is used to find whether particular element is present or not."
},
{
"code": null,
"e": 2681,
"s": 2583,
"text": "Sorting − Helps in arranging the elements in an array either in an ascending or descending order."
},
{
"code": null,
"e": 2779,
"s": 2681,
"text": "Sorting − Helps in arranging the elements in an array either in an ascending or descending order."
},
{
"code": null,
"e": 2844,
"s": 2779,
"text": "Traversing − Processing every element in an array, sequentially."
},
{
"code": null,
"e": 2909,
"s": 2844,
"text": "Traversing − Processing every element in an array, sequentially."
},
{
"code": null,
"e": 2962,
"s": 2909,
"text": "Inserting − Helps in inserting elements in an array."
},
{
"code": null,
"e": 3015,
"s": 2962,
"text": "Inserting − Helps in inserting elements in an array."
},
{
"code": null,
"e": 3069,
"s": 3015,
"text": "Deleting − helps in deleting the element in an array."
},
{
"code": null,
"e": 3123,
"s": 3069,
"text": "Deleting − helps in deleting the element in an array."
},
{
"code": null,
"e": 3189,
"s": 3123,
"text": "Following is the C program for searching an element in an array −"
},
{
"code": null,
"e": 3200,
"s": 3189,
"text": " Live Demo"
},
{
"code": null,
"e": 3833,
"s": 3200,
"text": "#include <stdio.h>\n#define MAX 100 // Maximum array size\nint main(){\n int array[MAX];\n int size, i, search, found;\n printf(\"Enter size of array: \");\n scanf(\"%d\", &size);\n printf(\"Enter elements in array: \");\n for(i=0; i<size; i++){\n scanf(\"%d\", &array[i]);\n }\n printf(\"\\nEnter element to search: \");\n scanf(\"%d\", &search);\n found = 0;\n for(i=0; i<size; i++){\n if(array[i] == search){\n found = 1;\n break;\n }\n }\n if(found == 1){\n printf(\"\\n%d is found at position %d\", search, i + 1);\n } else {\n printf(\"\\n%d is not found in the array\", search);\n }\n return 0;\n}"
},
{
"code": null,
"e": 3860,
"s": 3833,
"text": "The output is as follows −"
},
{
"code": null,
"e": 3979,
"s": 3860,
"text": "Enter size of array: 5\nEnter elements in array: 11 24 13 12 45\nEnter element to search: 13\n13 found at position 3found"
}
]
|
Creating a Function module in ABAP to take any table and write it to the screen | SAP List Viewer is used to add an ALV component and provides a flexible environment to display lists and tabular structure. A standard output consists of header, toolbar, and an output table. The user can adjust the settings to add column display, aggregations, and sorting options using additional dialog boxes.
You can use following code to display any table:
DATA: go_alv TYPE REF TO cl_salv_table.
CALL METHODcl_salv_table=>factory
IMPORTING
r_salv_table = go_alv
CHANGING
t_table = itab.
go_alv->display( ).
Another Dynamic Way to Output Any Internal Table is by using field-symbol, this is a particular field type in ABAP. Without going into the details of it, you must know that a field symbol works like a pointer without pointer arithmetic, but has a value semantics.
FIELD-SYMBOLS:<row> TYPE ANY.
FIELD-SYMBOLS:<comp> TYPE ANY.
The typing ANY is necessary because the field symbol should be able to refer to data of any type. And this is what our loop looks like now using a dynamic assignment to the various components of the work area:
LOOP ATitab_flight INTO row.
DO.
ASSIGN COMPONENTsy-index OF STRUCTURE <row> TO <wa_comp>.
IF sy-subrc <>0.
SKIP.
EXIT.
ENDIF.
WRITE <wa_comp>.
ENDDO.
ENDLOOP | [
{
"code": null,
"e": 1375,
"s": 1062,
"text": "SAP List Viewer is used to add an ALV component and provides a flexible environment to display lists and tabular structure. A standard output consists of header, toolbar, and an output table. The user can adjust the settings to add column display, aggregations, and sorting options using additional dialog boxes."
},
{
"code": null,
"e": 1424,
"s": 1375,
"text": "You can use following code to display any table:"
},
{
"code": null,
"e": 1601,
"s": 1424,
"text": "DATA: go_alv TYPE REF TO cl_salv_table.\n CALL METHODcl_salv_table=>factory\n IMPORTING\n r_salv_table = go_alv\n CHANGING\n t_table = itab.\n go_alv->display( )."
},
{
"code": null,
"e": 1865,
"s": 1601,
"text": "Another Dynamic Way to Output Any Internal Table is by using field-symbol, this is a particular field type in ABAP. Without going into the details of it, you must know that a field symbol works like a pointer without pointer arithmetic, but has a value semantics."
},
{
"code": null,
"e": 1895,
"s": 1865,
"text": "FIELD-SYMBOLS:<row> TYPE ANY."
},
{
"code": null,
"e": 1926,
"s": 1895,
"text": "FIELD-SYMBOLS:<comp> TYPE ANY."
},
{
"code": null,
"e": 2136,
"s": 1926,
"text": "The typing ANY is necessary because the field symbol should be able to refer to data of any type. And this is what our loop looks like now using a dynamic assignment to the various components of the work area:"
},
{
"code": null,
"e": 2343,
"s": 2136,
"text": "LOOP ATitab_flight INTO row.\n DO.\n ASSIGN COMPONENTsy-index OF STRUCTURE <row> TO <wa_comp>.\n IF sy-subrc <>0.\n SKIP.\n EXIT.\n ENDIF.\n WRITE <wa_comp>.\n ENDDO.\nENDLOOP"
}
]
|
How to dynamically update a ListView on Android Kotlin? | This example demonstrates how to dynamically update a ListView on Android Kotlin.
Step 1 − Create a new project in Android Studio, go to File ⇉ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="4dp">
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter an item here"
android:inputType="text" />
<Button
android:id="@+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/editText"
android:text="Add item" />
<ListView
android:id="@+id/listView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/btnAdd" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.EditText
import android.widget.ListView
class MainActivity : AppCompatActivity() {
lateinit var editText: EditText
lateinit var button: Button
lateinit var listView: ListView
var list: ArrayList<String> = ArrayList()
lateinit var arrayAdapter: ArrayAdapter<String>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "Kotlin"
listView = findViewById(R.id.listView)
editText = findViewById(R.id.editText)
button = findViewById(R.id.btnAdd)
arrayAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, list)
button.setOnClickListener {
list.add(editText.text.toString())
editText.setText("")
arrayAdapter.notifyDataSetChanged()
listView.adapter = arrayAdapter
}
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="app.com.kotlipapp">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code. | [
{
"code": null,
"e": 1144,
"s": 1062,
"text": "This example demonstrates how to dynamically update a ListView on Android Kotlin."
},
{
"code": null,
"e": 1273,
"s": 1144,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇉ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1338,
"s": 1273,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2184,
"s": 1338,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"fill_parent\"\n android:layout_height=\"fill_parent\"\n android:orientation=\"vertical\"\n android:padding=\"4dp\">\n <EditText\n android:id=\"@+id/editText\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:hint=\"Enter an item here\"\n android:inputType=\"text\" />\n <Button\n android:id=\"@+id/btnAdd\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@id/editText\"\n android:text=\"Add item\" />\n <ListView\n android:id=\"@+id/listView\"\n android:layout_width=\"fill_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@id/btnAdd\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2239,
"s": 2184,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 3266,
"s": 2239,
"text": "import androidx.appcompat.app.AppCompatActivity\nimport android.os.Bundle\nimport android.widget.ArrayAdapter\nimport android.widget.Button\nimport android.widget.EditText\nimport android.widget.ListView\nclass MainActivity : AppCompatActivity() {\n lateinit var editText: EditText\n lateinit var button: Button\n lateinit var listView: ListView\n var list: ArrayList<String> = ArrayList()\n lateinit var arrayAdapter: ArrayAdapter<String>\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"Kotlin\"\n listView = findViewById(R.id.listView)\n editText = findViewById(R.id.editText)\n button = findViewById(R.id.btnAdd)\n arrayAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, list)\n button.setOnClickListener {\n list.add(editText.text.toString())\n editText.setText(\"\")\n arrayAdapter.notifyDataSetChanged()\n listView.adapter = arrayAdapter\n }\n }\n}"
},
{
"code": null,
"e": 3321,
"s": 3266,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3997,
"s": 3321,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.kotlipapp\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 4348,
"s": 3997,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
},
{
"code": null,
"e": 4389,
"s": 4348,
"text": "Click here to download the project code."
}
]
|
Can we create a table with a space in name in MySQL? | To create a table with a space in the table name in MySQL, you must use backticks otherwise you will get an error.
Let us first see what error will arise by creating a table with a space in the name i.e. “Demo Table” table name below:
mysql> create table Demo Table
(
Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
EmployeeFirstName varchar(20),
EmployeeLastName varchar(20),
EmployeeAge int,
EmployeeSalary int,
EmployeeAddress varchar(200)
);
ERROR 1064 (42000): You have an error in your syntax; check the manual that corresponds
to your MySQL server version for the right syntax to use near 'Table37
(
Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, EmployeeFirstName varchar(' at line 1 )
Let us use the concept of backticks for table name to remove the error. The query to create a table with a space in MySQL is as follows:
mysql> create table `Demo Table37`
(
Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
EmployeeFirstName varchar(20),
EmployeeLastName varchar(20),
EmployeeAge int,
EmployeeSalary int,
EmployeeAddress varchar(200)
);
Query OK, 0 rows affected (0.66 sec)
Above, we have set the table name with space surrounded by backtick symbol, therefore no error:
`Demo Table37` | [
{
"code": null,
"e": 1177,
"s": 1062,
"text": "To create a table with a space in the table name in MySQL, you must use backticks otherwise you will get an error."
},
{
"code": null,
"e": 1297,
"s": 1177,
"text": "Let us first see what error will arise by creating a table with a space in the name i.e. “Demo Table” table name below:"
},
{
"code": null,
"e": 1767,
"s": 1297,
"text": "mysql> create table Demo Table\n(\n Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n EmployeeFirstName varchar(20),\n EmployeeLastName varchar(20),\n EmployeeAge int,\n EmployeeSalary int,\n EmployeeAddress varchar(200)\n);\nERROR 1064 (42000): You have an error in your syntax; check the manual that corresponds\nto your MySQL server version for the right syntax to use near 'Table37\n(\nId int NOT NULL AUTO_INCREMENT PRIMARY KEY, EmployeeFirstName varchar(' at line 1 )"
},
{
"code": null,
"e": 1904,
"s": 1767,
"text": "Let us use the concept of backticks for table name to remove the error. The query to create a table with a space in MySQL is as follows:"
},
{
"code": null,
"e": 2171,
"s": 1904,
"text": "mysql> create table `Demo Table37`\n(\n Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n EmployeeFirstName varchar(20),\n EmployeeLastName varchar(20),\n EmployeeAge int,\n EmployeeSalary int,\n EmployeeAddress varchar(200)\n);\nQuery OK, 0 rows affected (0.66 sec)\n"
},
{
"code": null,
"e": 2267,
"s": 2171,
"text": "Above, we have set the table name with space surrounded by backtick symbol, therefore no error:"
},
{
"code": null,
"e": 2282,
"s": 2267,
"text": "`Demo Table37`"
}
]
|
Explain the functions fread() and fwrite() used in files in C | Write a C program for storing the details of 5 students into a file and print the same using fread() and fwrite()
The fread() function reads the entire record at a time.
fread( & structure variable, size of (structure variable), no of records, file pointer);
struct emp{
int eno;
char ename [30];
float sal;
} e;
FILE *fp;
fread (&e, sizeof (e), 1, fp);
The fwrite() function writes an entire record at a time.
fwrite( & structure variable , size of structure variable, no of records, file pointer);
struct emp{
int eno:
char ename [30];
float sal;
} e;
FILE *fp;
fwrite (&e, sizeof(e), 1, fp);
#include<stdio.h>
struct student{
int sno;
char sname [30];
float marks;
char temp;
};
main ( ){
struct student s[60];
int i;
FILE *fp;
fp = fopen ("student1.txt", "w");
for (i=0; i<2; i++){
printf ("enter details of student %d\n", i+1);
printf("student number:");
scanf("%d",&s[i].sno);
scanf("%c",&s[i].temp);
printf("student name:");
gets(s[i].sname);
printf("student marks:");
scanf("%f",&s[i].marks);
fwrite(&s[i], sizeof(s[i]),1,fp);
}
fclose (fp);
fp = fopen ("student1.txt", "r");
for (i=0; i<2; i++){
printf ("details of student %d are\n", i+1);
fread (&s[i], sizeof (s[i]) ,1,fp);
printf("student number = %d\n", s[i]. sno);
printf("student name = %s\n", s[i]. sname);
printf("marks = %f\n", s[i]. marks);
}
fclose(fp);
getch( );
}
enter details of student 1
student number:1
student name:pinky
student marks:56
enter details of student 2
student number:2
student name:rosy
student marks:87
details of student 1 are
student number = 1
student name = pinky
marks = 56.000000
details of student 2 are
student number = 2
student name = rosy
marks = 87.000000 | [
{
"code": null,
"e": 1176,
"s": 1062,
"text": "Write a C program for storing the details of 5 students into a file and print the same using fread() and fwrite()"
},
{
"code": null,
"e": 1232,
"s": 1176,
"text": "The fread() function reads the entire record at a time."
},
{
"code": null,
"e": 1321,
"s": 1232,
"text": "fread( & structure variable, size of (structure variable), no of records, file pointer);"
},
{
"code": null,
"e": 1425,
"s": 1321,
"text": "struct emp{\n int eno;\n char ename [30];\n float sal;\n} e;\nFILE *fp;\nfread (&e, sizeof (e), 1, fp);"
},
{
"code": null,
"e": 1482,
"s": 1425,
"text": "The fwrite() function writes an entire record at a time."
},
{
"code": null,
"e": 1571,
"s": 1482,
"text": "fwrite( & structure variable , size of structure variable, no of records, file pointer);"
},
{
"code": null,
"e": 1675,
"s": 1571,
"text": "struct emp{\n int eno:\n char ename [30];\n float sal;\n} e;\nFILE *fp;\nfwrite (&e, sizeof(e), 1, fp);"
},
{
"code": null,
"e": 2549,
"s": 1675,
"text": "#include<stdio.h>\nstruct student{\n int sno;\n char sname [30];\n float marks;\n char temp;\n};\nmain ( ){\n struct student s[60];\n int i;\n FILE *fp;\n fp = fopen (\"student1.txt\", \"w\");\n for (i=0; i<2; i++){\n printf (\"enter details of student %d\\n\", i+1);\n printf(\"student number:\");\n scanf(\"%d\",&s[i].sno);\n scanf(\"%c\",&s[i].temp);\n printf(\"student name:\");\n gets(s[i].sname);\n printf(\"student marks:\");\n scanf(\"%f\",&s[i].marks);\n fwrite(&s[i], sizeof(s[i]),1,fp);\n }\n fclose (fp);\n fp = fopen (\"student1.txt\", \"r\");\n for (i=0; i<2; i++){\n printf (\"details of student %d are\\n\", i+1);\n fread (&s[i], sizeof (s[i]) ,1,fp);\n printf(\"student number = %d\\n\", s[i]. sno);\n printf(\"student name = %s\\n\", s[i]. sname);\n printf(\"marks = %f\\n\", s[i]. marks);\n }\n fclose(fp);\n getch( );\n}"
},
{
"code": null,
"e": 2873,
"s": 2549,
"text": "enter details of student 1\nstudent number:1\nstudent name:pinky\nstudent marks:56\nenter details of student 2\nstudent number:2\nstudent name:rosy\nstudent marks:87\ndetails of student 1 are\nstudent number = 1\nstudent name = pinky\nmarks = 56.000000\ndetails of student 2 are\nstudent number = 2\nstudent name = rosy\nmarks = 87.000000"
}
]
|
Python 3 - String isalnum() Method | The isalnum() method checks whether the string consists of alphanumeric characters.
Following is the syntax for isalnum() method −
str.isa1num()
NA
This method returns true if all characters in the string are alphanumeric and there is at least one character, false otherwise.
The following example shows the usage of isalnum() method.
#!/usr/bin/python3
str = "this2016" # No space in this string
print (str.isalnum())
str = "this is string example....wow!!!"
print (str.isalnum())
When we run the above program, it produces the following result −
True
False
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": 2424,
"s": 2340,
"text": "The isalnum() method checks whether the string consists of alphanumeric characters."
},
{
"code": null,
"e": 2471,
"s": 2424,
"text": "Following is the syntax for isalnum() method −"
},
{
"code": null,
"e": 2486,
"s": 2471,
"text": "str.isa1num()\n"
},
{
"code": null,
"e": 2489,
"s": 2486,
"text": "NA"
},
{
"code": null,
"e": 2617,
"s": 2489,
"text": "This method returns true if all characters in the string are alphanumeric and there is at least one character, false otherwise."
},
{
"code": null,
"e": 2676,
"s": 2617,
"text": "The following example shows the usage of isalnum() method."
},
{
"code": null,
"e": 2826,
"s": 2676,
"text": "#!/usr/bin/python3\n\nstr = \"this2016\" # No space in this string\nprint (str.isalnum())\n\nstr = \"this is string example....wow!!!\"\nprint (str.isalnum())"
},
{
"code": null,
"e": 2892,
"s": 2826,
"text": "When we run the above program, it produces the following result −"
},
{
"code": null,
"e": 2904,
"s": 2892,
"text": "True\nFalse\n"
},
{
"code": null,
"e": 2941,
"s": 2904,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 2957,
"s": 2941,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 2990,
"s": 2957,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3009,
"s": 2990,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3044,
"s": 3009,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3066,
"s": 3044,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3100,
"s": 3066,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3128,
"s": 3100,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3163,
"s": 3128,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3177,
"s": 3163,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3210,
"s": 3177,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3227,
"s": 3210,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3234,
"s": 3227,
"text": " Print"
},
{
"code": null,
"e": 3245,
"s": 3234,
"text": " Add Notes"
}
]
|
Program to convert List of String to List of Integer in Java | Here’s our List of String −
List<String> listString = Arrays.asList("25", "50", "75", "100", "125", "150");
Now, convert the list of string to list of integer −
List<Integer> listInteger = listString.stream().map(Integer::parseInt).collect(Collectors.toList());
Following is the program to convert List of String to List of Integer in Java −
import java.util.*;
import java.util.stream.*;
import java.util.function.*;
public class Demo {
public static void main(String[] args) {
List<String> listString = Arrays.asList("25", "50", "75", "100", "125", "150");
System.out.println("List of String = " + listString);
List<Integer> listInteger = listString.stream().map(Integer::parseInt)
.collect(Collectors.toList());
System.out.println("List of Integer (converted from List of String) = " + listInteger);
}
}
List of String = [25, 50, 75, 100, 125, 150]
List of Integer (converted from List of String) = [25, 50, 75, 100, 125, 150] | [
{
"code": null,
"e": 1090,
"s": 1062,
"text": "Here’s our List of String −"
},
{
"code": null,
"e": 1170,
"s": 1090,
"text": "List<String> listString = Arrays.asList(\"25\", \"50\", \"75\", \"100\", \"125\", \"150\");"
},
{
"code": null,
"e": 1223,
"s": 1170,
"text": "Now, convert the list of string to list of integer −"
},
{
"code": null,
"e": 1324,
"s": 1223,
"text": "List<Integer> listInteger = listString.stream().map(Integer::parseInt).collect(Collectors.toList());"
},
{
"code": null,
"e": 1404,
"s": 1324,
"text": "Following is the program to convert List of String to List of Integer in Java −"
},
{
"code": null,
"e": 1908,
"s": 1404,
"text": "import java.util.*;\nimport java.util.stream.*;\nimport java.util.function.*;\npublic class Demo {\n public static void main(String[] args) {\n List<String> listString = Arrays.asList(\"25\", \"50\", \"75\", \"100\", \"125\", \"150\");\n System.out.println(\"List of String = \" + listString);\n List<Integer> listInteger = listString.stream().map(Integer::parseInt)\n .collect(Collectors.toList());\n System.out.println(\"List of Integer (converted from List of String) = \" + listInteger);\n }\n}"
},
{
"code": null,
"e": 2031,
"s": 1908,
"text": "List of String = [25, 50, 75, 100, 125, 150]\nList of Integer (converted from List of String) = [25, 50, 75, 100, 125, 150]"
}
]
|
Enter key press event in JavaScript? | For ENTER key press event, you can call a function on −
onkeypress=”yourFunctionName”
Use the ENTER’s keycode 13.
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fontawesome/
4.7.0/css/font-awesome.min.css">
</head>
<body>
<input id="enterDemo" type="text" onkeypress="return
enterKeyPressed(event)" />
<script>
function enterKeyPressed(event) {
if (event.keyCode == 13) {
console.log("Enter key is pressed");
return true;
} else {
return false;
}
}
</script>
</body>
</html>
To run the above program, save the file name “anyName.html(index.html)” and right click on the
file. Select the option “Open with Live Server” in VS Code editor.
This will produce the following output −
On pressing ENTER key, the following output is visible on console − | [
{
"code": null,
"e": 1118,
"s": 1062,
"text": "For ENTER key press event, you can call a function on −"
},
{
"code": null,
"e": 1148,
"s": 1118,
"text": "onkeypress=”yourFunctionName”"
},
{
"code": null,
"e": 1176,
"s": 1148,
"text": "Use the ENTER’s keycode 13."
},
{
"code": null,
"e": 1187,
"s": 1176,
"text": " Live Demo"
},
{
"code": null,
"e": 1998,
"s": 1187,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initialscale=1.0\">\n<title>Document</title>\n<link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\">\n<script src=\"https://code.jquery.com/jquery-1.12.4.js\"></script>\n<script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"></script>\n<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/fontawesome/\n4.7.0/css/font-awesome.min.css\">\n</head>\n<body>\n<input id=\"enterDemo\" type=\"text\" onkeypress=\"return\nenterKeyPressed(event)\" />\n<script>\n function enterKeyPressed(event) {\n if (event.keyCode == 13) {\n console.log(\"Enter key is pressed\");\n return true;\n } else {\n return false;\n }\n }\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2160,
"s": 1998,
"text": "To run the above program, save the file name “anyName.html(index.html)” and right click on the\nfile. Select the option “Open with Live Server” in VS Code editor."
},
{
"code": null,
"e": 2201,
"s": 2160,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2269,
"s": 2201,
"text": "On pressing ENTER key, the following output is visible on console −"
}
]
|
Python | Printing String with double quotes | 22 Apr, 2020
Many times, while working with Python strings, we have a problem in which we need to use double quotes in a string and then wish to print it. This kind of problem occurs in many domains like day-day programming and web-development domain. Lets discuss certain ways in which this task can be performed.
Method #1 : Using backslash (“\”)This is one way to solve this problem. In this, we just employ a backslash before a double quote and it is escaped.
# Python3 code to demonstrate working of # Printing String with double quotes# Using backslash # initializing string# using backslashtest_str = "geeks\"for\"geeks" # printing stringprint("The string escaped with backslash : " + test_str)
The string escaped with backslash : geeks"for"geeks
Method #2 : Using triple quotesThis is one more way in python to print and initialize a string. Apart from multiline comment, triple quotes are also good way of escaping.
# Python3 code to demonstrate working of # Printing String with double quotes# Using triple quotes # initializing string# using triple quotestest_str = """geeks"for"geeks""" # printing stringprint("The string escaped with triple quotes : " + test_str)
The string escaped with triple quotes : geeks"for"geeks
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Apr, 2020"
},
{
"code": null,
"e": 330,
"s": 28,
"text": "Many times, while working with Python strings, we have a problem in which we need to use double quotes in a string and then wish to print it. This kind of problem occurs in many domains like day-day programming and web-development domain. Lets discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 479,
"s": 330,
"text": "Method #1 : Using backslash (“\\”)This is one way to solve this problem. In this, we just employ a backslash before a double quote and it is escaped."
},
{
"code": "# Python3 code to demonstrate working of # Printing String with double quotes# Using backslash # initializing string# using backslashtest_str = \"geeks\\\"for\\\"geeks\" # printing stringprint(\"The string escaped with backslash : \" + test_str)",
"e": 719,
"s": 479,
"text": null
},
{
"code": null,
"e": 772,
"s": 719,
"text": "The string escaped with backslash : geeks\"for\"geeks\n"
},
{
"code": null,
"e": 945,
"s": 774,
"text": "Method #2 : Using triple quotesThis is one more way in python to print and initialize a string. Apart from multiline comment, triple quotes are also good way of escaping."
},
{
"code": "# Python3 code to demonstrate working of # Printing String with double quotes# Using triple quotes # initializing string# using triple quotestest_str = \"\"\"geeks\"for\"geeks\"\"\" # printing stringprint(\"The string escaped with triple quotes : \" + test_str)",
"e": 1199,
"s": 945,
"text": null
},
{
"code": null,
"e": 1256,
"s": 1199,
"text": "The string escaped with triple quotes : geeks\"for\"geeks\n"
},
{
"code": null,
"e": 1279,
"s": 1256,
"text": "Python string-programs"
},
{
"code": null,
"e": 1286,
"s": 1279,
"text": "Python"
},
{
"code": null,
"e": 1302,
"s": 1286,
"text": "Python Programs"
}
]
|
Total numbers with no repeated digits in a range | 10 Jun, 2022
Given a range find total such numbers in the given range such that they have no repeated digits.For example:12 has no repeated digit.22 has repeated digit.102, 194 and 213 have no repeated digit.212, 171 and 4004 have repeated digits.
Examples:
Input : 10 12
Output : 2
Explanation : In the given range
10 and 12 have no repeated digit
where as 11 has repeated digit.
Input : 1 100
Output : 90
Brute Force
We will traverse through each element in the given range and count the number of digits which do not have repeated digits.
C++
Java
Python3
C#
PHP
// C++ implementation of brute// force solution.#include <bits/stdc++.h>using namespace std; // Function to check if the given// number has repeated digit or notint repeated_digit(int n){ unordered_set<int> s; // Traversing through each digit while(n != 0) { int d = n % 10; // if the digit is present // more than once in the // number if(s.find(d) != s.end()) { // return 0 if the number // has repeated digit return 0; } s.insert(d); n = n / 10; } // return 1 if the number has // no repeated digit return 1;} // Function to find total number// in the given range which has// no repeated digitint calculate(int L,int R){ int answer = 0; // Traversing through the range for(int i = L; i < R + 1; ++i) { // Add 1 to the answer if i has // no repeated digit else 0 answer = answer + repeated_digit(i); } return answer ;} // Driver Codeint main(){ int L = 1, R = 100; // Calling the calculate cout << calculate(L, R); return 0;} // This code is contributed by// Sanjit_Prasad
// Java implementation of brute // force solution. import java.util.LinkedHashSet; class GFG{// Function to check if the given // number has repeated digit or not static int repeated_digit(int n) { LinkedHashSet<Integer> s = new LinkedHashSet<>(); // Traversing through each digit while (n != 0) { int d = n % 10; // if the digit is present // more than once in the // number if (s.contains(d)) { // return 0 if the number // has repeated digit return 0; } s.add(d); n = n / 10; } // return 1 if the number has // no repeated digit return 1;} // Function to find total number // in the given range which has // no repeated digit static int calculate(int L, int R) { int answer = 0; // Traversing through the range for (int i = L; i < R + 1; ++i) { // Add 1 to the answer if i has // no repeated digit else 0 answer = answer + repeated_digit(i); } return answer;} // Driver Code public static void main(String[] args) { int L = 1, R = 100; // Calling the calculate System.out.println(calculate(L, R));}} // This code is contributed by RAJPUT-JI
# Python implementation of brute # force solution. # Function to check if the given # number has repeated digit or not def repeated_digit(n): a = [] # Traversing through each digit while n != 0: d = n%10 # if the digit is present # more than once in the # number if d in a: # return 0 if the number # has repeated digit return 0 a.append(d) n = n//10 # return 1 if the number has no # repeated digit return 1 # Function to find total number# in the given range which has # no repeated digitdef calculate(L,R): answer = 0 # Traversing through the range for i in range(L,R+1): # Add 1 to the answer if i has # no repeated digit else 0 answer = answer + repeated_digit(i) # return answer return answer # Driver's Code L=1R=100 # Calling the calculateprint(calculate(L, R))
// C# implementation of brute // force solution. using System; using System.Collections.Generic; class GFG { // Function to check if the given // number has repeated digit or not static int repeated_digit(int n){ var s = new HashSet<int>(); // Traversing through each digit while (n != 0) { int d = n % 10; // if the digit is present // more than once in the // number if (s.Contains(d)) { // return 0 if the number // has repeated digit return 0; } s.Add(d); n = n / 10; } // return 1 if the number has // no repeated digit return 1;} // Function to find total number // in the given range which has // no repeated digit static int calculate(int L, int R) { int answer = 0; // Traversing through the range for (int i = L; i < R + 1; ++i) { // Add 1 to the answer if i has // no repeated digit else 0 answer = answer + repeated_digit(i); } return answer;} // Driver Code public static void Main(String[] args){ int L = 1, R = 100; // Calling the calculate Console.WriteLine(calculate(L, R));}} // This code is contributed by RAJPUT-JI
<?php// PHP implementation of // brute force solution. // Function to check if // the given number has// repeated digit or not function repeated_digit($n){ $c = 10; $a = array_fill(0, $c, 0); // Traversing through // each digit while($n > 0) { $d = $n % 10; // if the digit is present // more than once in the // number if ($a[$d] > 0) { // return 0 if the number // has repeated digit return 0; } $a[$d]++; $n = (int)($n / 10); } // return 1 if the number // has no repeated digit return 1;} // Function to find total // number in the given range // which has no repeated digitfunction calculate($L, $R){ $answer = 0; // Traversing through // the range for($i = $L; $i <= $R; $i++) { // Add 1 to the answer if // i has no repeated digit // else 0 $answer += repeated_digit($i); } // return answer return $answer;} // Driver Code $L = 1;$R = 100; // Calling the calculateecho calculate($L, $R); // This code is contributed by mits?>
90
This method will answer each query in O( N ) time.
Efficient Approach
We will calculate a prefix array of the numbers which have no repeated digit.
= Total number with no repeated digit less than or equal to 1.
Therefore each query can be solved in O(1) time.
Below is the implementation of above idea.
C++
Java
Python3
C#
JavaScript
// C++ implementation of above idea #include <bits/stdc++.h> using namespace std; // Maximum int MAX = 1000; // Prefix Array vector<int> Prefix = {0}; // Function to check if the given // number has repeated digit or not int repeated_digit(int n){ unordered_set<int> a; int d; // Traversing through each digit while (n != 0) { d = n % 10; // if the digit is present // more than once in the // number if (a.find(d) != a.end()) // return 0 if the number // has repeated digit return 0; a.insert(d); n = n / 10; } // return 1 if the number has no // repeated digit return 1;} // Function to pre calculate // the Prefix array void pre_calculation(int MAX){ Prefix.push_back(repeated_digit(1)); // Traversing through the numbers // from 2 to MAX for (int i = 2; i < MAX + 1; i++) // Generating the Prefix array Prefix.push_back(repeated_digit(i) + Prefix[i-1]);} // Calclute Function int calculate(int L,int R){ // Answer return Prefix[R] - Prefix[L-1];} // Driver codeint main(){ int L = 1, R = 100; // Pre-calculating the Prefix array. pre_calculation(MAX); // Calling the calculate function // to find the total number of number // which has no repeated digit cout << calculate(L, R) << endl; return 0;} // This code is contributed by Rituraj Jain
// Java implementation of above ideaimport java.util.*; class GFG { // Maximum static int MAX = 100; // Prefix Array static Vector<Integer> Prefix = new Vector<>(); // Function to check if the given // number has repeated digit or not static int repeated_digit(int n) { HashSet<Integer> a = new HashSet<>(); int d; // Traversing through each digit while (n != 0) { d = n % 10; // if the digit is present // more than once in the // number if (a.contains(d)) // return 0 if the number // has repeated digit return 0; a.add(d); n /= 10; } // return 1 if the number has no // repeated digit return 1; } // Function to pre calculate // the Prefix array static void pre_calculations() { Prefix.add(0); Prefix.add(repeated_digit(1)); // Traversing through the numbers // from 2 to MAX for (int i = 2; i < MAX + 1; i++) // Generating the Prefix array Prefix.add(repeated_digit(i) + Prefix.elementAt(i - 1)); } // Calclute Function static int calculate(int L, int R) { // Answer return Prefix.elementAt(R) - Prefix.elementAt(L - 1); } // Driver Code public static void main(String[] args) { int L = 1, R = 100; // Pre-calculating the Prefix array. pre_calculations(); // Calling the calculate function // to find the total number of number // which has no repeated digit System.out.println(calculate(L, R)); }} // This code is contributed by// sanjeev2552
# Python implementation of # above idea # Prefix ArrayPrefix = [0] # Function to check if # the given number has # repeated digit or not def repeated_digit(n): a = [] # Traversing through each digit while n != 0: d = n%10 # if the digit is present # more than once in the # number if d in a: # return 0 if the number # has repeated digit return 0 a.append(d) n = n//10 # return 1 if the number has no # repeated digit return 1 # Function to pre calculate# the Prefix arraydef pre_calculation(MAX): # To use to global Prefix array global Prefix Prefix.append(repeated_digit(1)) # Traversing through the numbers # from 2 to MAX for i in range(2,MAX+1): # Generating the Prefix array Prefix.append( repeated_digit(i) + Prefix[i-1] ) # Calclute Functiondef calculate(L,R): # Answer return Prefix[R]-Prefix[L-1] # Driver Code # Maximum MAX = 1000 # Pre-calculating the Prefix array.pre_calculation(MAX) # RangeL=1R=100 # Calling the calculate function# to find the total number of number# which has no repeated digitprint(calculate(L, R))
// C# implementation of above ideausing System;using System.Collections.Generic; class GFG { // Maximum static int MAX = 100; // Prefix Array static List<int> Prefix = new List<int>(); // Function to check if the given // number has repeated digit or not static int repeated_digit(int n) { HashSet<int> a = new HashSet<int>(); int d; // Traversing through each digit while (n != 0) { d = n % 10; // if the digit is present // more than once in the // number if (a.Contains(d)) // return 0 if the number // has repeated digit return 0; a.Add(d); n /= 10; } // return 1 if the number has no // repeated digit return 1; } // Function to pre calculate // the Prefix array static void pre_calculations() { Prefix.Add(0); Prefix.Add(repeated_digit(1)); // Traversing through the numbers // from 2 to MAX for (int i = 2; i < MAX + 1; i++) // Generating the Prefix array Prefix.Add(repeated_digit(i) + Prefix[i - 1]); } // Calclute Function static int calculate(int L, int R) { // Answer return Prefix[R] - Prefix[L - 1]; } // Driver Code public static void Main(String[] args) { int L = 1, R = 100; // Pre-calculating the Prefix array. pre_calculations(); // Calling the calculate function // to find the total number of number // which has no repeated digit Console.WriteLine(calculate(L, R)); }} // This code is contributed by 29AjayKumar
<script> // JavaScript implementation of brute// force solution. // Function to check if the given// number has repeated digit or notfunction repeated_digit(n){ const s = new Set(); // Traversing through each digit while(n != 0){ let d = n % 10; // if the digit is present // more than once in the // number if(s.has(d)){ // return 0 if the number // has repeated digit return 0; } s.add(d); n = Math.floor(n / 10); } // return 1 if the number has // no repeated digit return 1;} // Function to find total number// in the given range which has// no repeated digitfunction calculate(L, R){ let answer = 0; // Traversing through the range for(let i = L; i < R + 1; ++i){ // Add 1 to the answer if i has // no repeated digit else 0 answer = answer + repeated_digit(i); } return answer ;} // Driver Code{ let L = 1, R = 100; // Calling the calculate console.log(calculate(L, R));} // This code is contributed by Gautam goel (gautamgoel962)</script>
90
Mithun Kumar
Sanjit_Prasad
Rajput-Ji
rituraj_jain
sanjeev2552
29AjayKumar
gautamgoel962
array-range-queries
number-digits
prefix-sum
Mathematical
prefix-sum
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n10 Jun, 2022"
},
{
"code": null,
"e": 290,
"s": 54,
"text": "Given a range find total such numbers in the given range such that they have no repeated digits.For example:12 has no repeated digit.22 has repeated digit.102, 194 and 213 have no repeated digit.212, 171 and 4004 have repeated digits."
},
{
"code": null,
"e": 300,
"s": 290,
"text": "Examples:"
},
{
"code": null,
"e": 453,
"s": 300,
"text": "Input : 10 12\nOutput : 2\nExplanation : In the given range \n10 and 12 have no repeated digit \nwhere as 11 has repeated digit.\n\nInput : 1 100\nOutput : 90\n"
},
{
"code": null,
"e": 465,
"s": 453,
"text": "Brute Force"
},
{
"code": null,
"e": 588,
"s": 465,
"text": "We will traverse through each element in the given range and count the number of digits which do not have repeated digits."
},
{
"code": null,
"e": 592,
"s": 588,
"text": "C++"
},
{
"code": null,
"e": 597,
"s": 592,
"text": "Java"
},
{
"code": null,
"e": 605,
"s": 597,
"text": "Python3"
},
{
"code": null,
"e": 608,
"s": 605,
"text": "C#"
},
{
"code": null,
"e": 612,
"s": 608,
"text": "PHP"
},
{
"code": "// C++ implementation of brute// force solution.#include <bits/stdc++.h>using namespace std; // Function to check if the given// number has repeated digit or notint repeated_digit(int n){ unordered_set<int> s; // Traversing through each digit while(n != 0) { int d = n % 10; // if the digit is present // more than once in the // number if(s.find(d) != s.end()) { // return 0 if the number // has repeated digit return 0; } s.insert(d); n = n / 10; } // return 1 if the number has // no repeated digit return 1;} // Function to find total number// in the given range which has// no repeated digitint calculate(int L,int R){ int answer = 0; // Traversing through the range for(int i = L; i < R + 1; ++i) { // Add 1 to the answer if i has // no repeated digit else 0 answer = answer + repeated_digit(i); } return answer ;} // Driver Codeint main(){ int L = 1, R = 100; // Calling the calculate cout << calculate(L, R); return 0;} // This code is contributed by// Sanjit_Prasad",
"e": 1775,
"s": 612,
"text": null
},
{
"code": "// Java implementation of brute // force solution. import java.util.LinkedHashSet; class GFG{// Function to check if the given // number has repeated digit or not static int repeated_digit(int n) { LinkedHashSet<Integer> s = new LinkedHashSet<>(); // Traversing through each digit while (n != 0) { int d = n % 10; // if the digit is present // more than once in the // number if (s.contains(d)) { // return 0 if the number // has repeated digit return 0; } s.add(d); n = n / 10; } // return 1 if the number has // no repeated digit return 1;} // Function to find total number // in the given range which has // no repeated digit static int calculate(int L, int R) { int answer = 0; // Traversing through the range for (int i = L; i < R + 1; ++i) { // Add 1 to the answer if i has // no repeated digit else 0 answer = answer + repeated_digit(i); } return answer;} // Driver Code public static void main(String[] args) { int L = 1, R = 100; // Calling the calculate System.out.println(calculate(L, R));}} // This code is contributed by RAJPUT-JI",
"e": 3027,
"s": 1775,
"text": null
},
{
"code": "# Python implementation of brute # force solution. # Function to check if the given # number has repeated digit or not def repeated_digit(n): a = [] # Traversing through each digit while n != 0: d = n%10 # if the digit is present # more than once in the # number if d in a: # return 0 if the number # has repeated digit return 0 a.append(d) n = n//10 # return 1 if the number has no # repeated digit return 1 # Function to find total number# in the given range which has # no repeated digitdef calculate(L,R): answer = 0 # Traversing through the range for i in range(L,R+1): # Add 1 to the answer if i has # no repeated digit else 0 answer = answer + repeated_digit(i) # return answer return answer # Driver's Code L=1R=100 # Calling the calculateprint(calculate(L, R))",
"e": 3999,
"s": 3027,
"text": null
},
{
"code": "// C# implementation of brute // force solution. using System; using System.Collections.Generic; class GFG { // Function to check if the given // number has repeated digit or not static int repeated_digit(int n){ var s = new HashSet<int>(); // Traversing through each digit while (n != 0) { int d = n % 10; // if the digit is present // more than once in the // number if (s.Contains(d)) { // return 0 if the number // has repeated digit return 0; } s.Add(d); n = n / 10; } // return 1 if the number has // no repeated digit return 1;} // Function to find total number // in the given range which has // no repeated digit static int calculate(int L, int R) { int answer = 0; // Traversing through the range for (int i = L; i < R + 1; ++i) { // Add 1 to the answer if i has // no repeated digit else 0 answer = answer + repeated_digit(i); } return answer;} // Driver Code public static void Main(String[] args){ int L = 1, R = 100; // Calling the calculate Console.WriteLine(calculate(L, R));}} // This code is contributed by RAJPUT-JI",
"e": 5244,
"s": 3999,
"text": null
},
{
"code": "<?php// PHP implementation of // brute force solution. // Function to check if // the given number has// repeated digit or not function repeated_digit($n){ $c = 10; $a = array_fill(0, $c, 0); // Traversing through // each digit while($n > 0) { $d = $n % 10; // if the digit is present // more than once in the // number if ($a[$d] > 0) { // return 0 if the number // has repeated digit return 0; } $a[$d]++; $n = (int)($n / 10); } // return 1 if the number // has no repeated digit return 1;} // Function to find total // number in the given range // which has no repeated digitfunction calculate($L, $R){ $answer = 0; // Traversing through // the range for($i = $L; $i <= $R; $i++) { // Add 1 to the answer if // i has no repeated digit // else 0 $answer += repeated_digit($i); } // return answer return $answer;} // Driver Code $L = 1;$R = 100; // Calling the calculateecho calculate($L, $R); // This code is contributed by mits?>",
"e": 6408,
"s": 5244,
"text": null
},
{
"code": null,
"e": 6412,
"s": 6408,
"text": "90\n"
},
{
"code": null,
"e": 6463,
"s": 6412,
"text": "This method will answer each query in O( N ) time."
},
{
"code": null,
"e": 6482,
"s": 6463,
"text": "Efficient Approach"
},
{
"code": null,
"e": 6560,
"s": 6482,
"text": "We will calculate a prefix array of the numbers which have no repeated digit."
},
{
"code": null,
"e": 6624,
"s": 6560,
"text": " = Total number with no repeated digit less than or equal to 1."
},
{
"code": null,
"e": 6673,
"s": 6624,
"text": "Therefore each query can be solved in O(1) time."
},
{
"code": null,
"e": 6716,
"s": 6673,
"text": "Below is the implementation of above idea."
},
{
"code": null,
"e": 6720,
"s": 6716,
"text": "C++"
},
{
"code": null,
"e": 6725,
"s": 6720,
"text": "Java"
},
{
"code": null,
"e": 6733,
"s": 6725,
"text": "Python3"
},
{
"code": null,
"e": 6736,
"s": 6733,
"text": "C#"
},
{
"code": null,
"e": 6747,
"s": 6736,
"text": "JavaScript"
},
{
"code": "// C++ implementation of above idea #include <bits/stdc++.h> using namespace std; // Maximum int MAX = 1000; // Prefix Array vector<int> Prefix = {0}; // Function to check if the given // number has repeated digit or not int repeated_digit(int n){ unordered_set<int> a; int d; // Traversing through each digit while (n != 0) { d = n % 10; // if the digit is present // more than once in the // number if (a.find(d) != a.end()) // return 0 if the number // has repeated digit return 0; a.insert(d); n = n / 10; } // return 1 if the number has no // repeated digit return 1;} // Function to pre calculate // the Prefix array void pre_calculation(int MAX){ Prefix.push_back(repeated_digit(1)); // Traversing through the numbers // from 2 to MAX for (int i = 2; i < MAX + 1; i++) // Generating the Prefix array Prefix.push_back(repeated_digit(i) + Prefix[i-1]);} // Calclute Function int calculate(int L,int R){ // Answer return Prefix[R] - Prefix[L-1];} // Driver codeint main(){ int L = 1, R = 100; // Pre-calculating the Prefix array. pre_calculation(MAX); // Calling the calculate function // to find the total number of number // which has no repeated digit cout << calculate(L, R) << endl; return 0;} // This code is contributed by Rituraj Jain",
"e": 8283,
"s": 6747,
"text": null
},
{
"code": "// Java implementation of above ideaimport java.util.*; class GFG { // Maximum static int MAX = 100; // Prefix Array static Vector<Integer> Prefix = new Vector<>(); // Function to check if the given // number has repeated digit or not static int repeated_digit(int n) { HashSet<Integer> a = new HashSet<>(); int d; // Traversing through each digit while (n != 0) { d = n % 10; // if the digit is present // more than once in the // number if (a.contains(d)) // return 0 if the number // has repeated digit return 0; a.add(d); n /= 10; } // return 1 if the number has no // repeated digit return 1; } // Function to pre calculate // the Prefix array static void pre_calculations() { Prefix.add(0); Prefix.add(repeated_digit(1)); // Traversing through the numbers // from 2 to MAX for (int i = 2; i < MAX + 1; i++) // Generating the Prefix array Prefix.add(repeated_digit(i) + Prefix.elementAt(i - 1)); } // Calclute Function static int calculate(int L, int R) { // Answer return Prefix.elementAt(R) - Prefix.elementAt(L - 1); } // Driver Code public static void main(String[] args) { int L = 1, R = 100; // Pre-calculating the Prefix array. pre_calculations(); // Calling the calculate function // to find the total number of number // which has no repeated digit System.out.println(calculate(L, R)); }} // This code is contributed by// sanjeev2552",
"e": 10036,
"s": 8283,
"text": null
},
{
"code": "# Python implementation of # above idea # Prefix ArrayPrefix = [0] # Function to check if # the given number has # repeated digit or not def repeated_digit(n): a = [] # Traversing through each digit while n != 0: d = n%10 # if the digit is present # more than once in the # number if d in a: # return 0 if the number # has repeated digit return 0 a.append(d) n = n//10 # return 1 if the number has no # repeated digit return 1 # Function to pre calculate# the Prefix arraydef pre_calculation(MAX): # To use to global Prefix array global Prefix Prefix.append(repeated_digit(1)) # Traversing through the numbers # from 2 to MAX for i in range(2,MAX+1): # Generating the Prefix array Prefix.append( repeated_digit(i) + Prefix[i-1] ) # Calclute Functiondef calculate(L,R): # Answer return Prefix[R]-Prefix[L-1] # Driver Code # Maximum MAX = 1000 # Pre-calculating the Prefix array.pre_calculation(MAX) # RangeL=1R=100 # Calling the calculate function# to find the total number of number# which has no repeated digitprint(calculate(L, R))",
"e": 11306,
"s": 10036,
"text": null
},
{
"code": "// C# implementation of above ideausing System;using System.Collections.Generic; class GFG { // Maximum static int MAX = 100; // Prefix Array static List<int> Prefix = new List<int>(); // Function to check if the given // number has repeated digit or not static int repeated_digit(int n) { HashSet<int> a = new HashSet<int>(); int d; // Traversing through each digit while (n != 0) { d = n % 10; // if the digit is present // more than once in the // number if (a.Contains(d)) // return 0 if the number // has repeated digit return 0; a.Add(d); n /= 10; } // return 1 if the number has no // repeated digit return 1; } // Function to pre calculate // the Prefix array static void pre_calculations() { Prefix.Add(0); Prefix.Add(repeated_digit(1)); // Traversing through the numbers // from 2 to MAX for (int i = 2; i < MAX + 1; i++) // Generating the Prefix array Prefix.Add(repeated_digit(i) + Prefix[i - 1]); } // Calclute Function static int calculate(int L, int R) { // Answer return Prefix[R] - Prefix[L - 1]; } // Driver Code public static void Main(String[] args) { int L = 1, R = 100; // Pre-calculating the Prefix array. pre_calculations(); // Calling the calculate function // to find the total number of number // which has no repeated digit Console.WriteLine(calculate(L, R)); }} // This code is contributed by 29AjayKumar",
"e": 13072,
"s": 11306,
"text": null
},
{
"code": "<script> // JavaScript implementation of brute// force solution. // Function to check if the given// number has repeated digit or notfunction repeated_digit(n){ const s = new Set(); // Traversing through each digit while(n != 0){ let d = n % 10; // if the digit is present // more than once in the // number if(s.has(d)){ // return 0 if the number // has repeated digit return 0; } s.add(d); n = Math.floor(n / 10); } // return 1 if the number has // no repeated digit return 1;} // Function to find total number// in the given range which has// no repeated digitfunction calculate(L, R){ let answer = 0; // Traversing through the range for(let i = L; i < R + 1; ++i){ // Add 1 to the answer if i has // no repeated digit else 0 answer = answer + repeated_digit(i); } return answer ;} // Driver Code{ let L = 1, R = 100; // Calling the calculate console.log(calculate(L, R));} // This code is contributed by Gautam goel (gautamgoel962)</script>",
"e": 14189,
"s": 13072,
"text": null
},
{
"code": null,
"e": 14193,
"s": 14189,
"text": "90\n"
},
{
"code": null,
"e": 14206,
"s": 14193,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 14220,
"s": 14206,
"text": "Sanjit_Prasad"
},
{
"code": null,
"e": 14230,
"s": 14220,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 14243,
"s": 14230,
"text": "rituraj_jain"
},
{
"code": null,
"e": 14255,
"s": 14243,
"text": "sanjeev2552"
},
{
"code": null,
"e": 14267,
"s": 14255,
"text": "29AjayKumar"
},
{
"code": null,
"e": 14281,
"s": 14267,
"text": "gautamgoel962"
},
{
"code": null,
"e": 14301,
"s": 14281,
"text": "array-range-queries"
},
{
"code": null,
"e": 14315,
"s": 14301,
"text": "number-digits"
},
{
"code": null,
"e": 14326,
"s": 14315,
"text": "prefix-sum"
},
{
"code": null,
"e": 14339,
"s": 14326,
"text": "Mathematical"
},
{
"code": null,
"e": 14350,
"s": 14339,
"text": "prefix-sum"
},
{
"code": null,
"e": 14363,
"s": 14350,
"text": "Mathematical"
}
]
|
S – attributed and L – attributed SDTs in Syntax directed translation | 03 May, 2019
Before coming up to S-attributed and L-attributed SDTs, here is a brief intro to Synthesized or Inherited attributes
Types of attributes –Attributes may be of two types – Synthesized or Inherited.
Synthesized attributes –A Synthesized attribute is an attribute of the non-terminal on the left-hand side of a production. Synthesized attributes represent information that is being passed up the parse tree. The attribute can take value only from its children (Variables in the RHS of the production).For eg. let’s say A -> BC is a production of a grammar, and A’s attribute is dependent on B’s attributes or C’s attributes then it will be synthesized attribute.Inherited attributes –An attribute of a nonterminal on the right-hand side of a production is called an inherited attribute. The attribute can take value either from its parent or from its siblings (variables in the LHS or RHS of the production).For example, let’s say A -> BC is a production of a grammar and B’s attribute is dependent on A’s attributes or C’s attributes then it will be inherited attribute.
Synthesized attributes –A Synthesized attribute is an attribute of the non-terminal on the left-hand side of a production. Synthesized attributes represent information that is being passed up the parse tree. The attribute can take value only from its children (Variables in the RHS of the production).For eg. let’s say A -> BC is a production of a grammar, and A’s attribute is dependent on B’s attributes or C’s attributes then it will be synthesized attribute.
For eg. let’s say A -> BC is a production of a grammar, and A’s attribute is dependent on B’s attributes or C’s attributes then it will be synthesized attribute.
Inherited attributes –An attribute of a nonterminal on the right-hand side of a production is called an inherited attribute. The attribute can take value either from its parent or from its siblings (variables in the LHS or RHS of the production).For example, let’s say A -> BC is a production of a grammar and B’s attribute is dependent on A’s attributes or C’s attributes then it will be inherited attribute.
For example, let’s say A -> BC is a production of a grammar and B’s attribute is dependent on A’s attributes or C’s attributes then it will be inherited attribute.
Now, let’s discuss about S-attributed and L-attributed SDT.
S-attributed SDT :If an SDT uses only synthesized attributes, it is called as S-attributed SDT.S-attributed SDTs are evaluated in bottom-up parsing, as the values of the parent nodes depend upon the values of the child nodes.Semantic actions are placed in rightmost place of RHS.L-attributed SDT:If an SDT uses both synthesized attributes and inherited attributes with a restriction that inherited attribute can inherit values from left siblings only, it is called as L-attributed SDT.Attributes in L-attributed SDTs are evaluated by depth-first and left-to-right parsing manner.Semantic actions are placed anywhere in RHS.For example,A -> XYZ {Y.S = A.S, Y.S = X.S, Y.S = Z.S} is not an L-attributed grammar since Y.S = A.S and Y.S = X.S are allowed but Y.S = Z.S violates the L-attributed SDT definition as attributed is inheriting the value from its right sibling.Note – If a definition is S-attributed, then it is also L-attributed but NOT vice-versa.Example – Consider the given below SDT.P1: S -> MN {S.val= M.val + N.val}
P2: M -> PQ {M.val = P.val * Q.val and P.val =Q.val} Select the correct option.A. Both P1 and P2 are S attributed.B. P1 is S attributed and P2 is L-attributed.C. P1 is L attributed but P2 is not L-attributed.D. None of the aboveExplanation –The correct answer is option C as, In P1, S is a synthesized attribute and in L-attribute definition synthesized is allowed. So P1 follows the L-attributed definition. But P2 doesn’t follow L-attributed definition as P is depending on Q which is RHS to it.My Personal Notes
arrow_drop_upSave
S-attributed SDT :If an SDT uses only synthesized attributes, it is called as S-attributed SDT.S-attributed SDTs are evaluated in bottom-up parsing, as the values of the parent nodes depend upon the values of the child nodes.Semantic actions are placed in rightmost place of RHS.
If an SDT uses only synthesized attributes, it is called as S-attributed SDT.
S-attributed SDTs are evaluated in bottom-up parsing, as the values of the parent nodes depend upon the values of the child nodes.
Semantic actions are placed in rightmost place of RHS.
L-attributed SDT:If an SDT uses both synthesized attributes and inherited attributes with a restriction that inherited attribute can inherit values from left siblings only, it is called as L-attributed SDT.Attributes in L-attributed SDTs are evaluated by depth-first and left-to-right parsing manner.Semantic actions are placed anywhere in RHS.For example,A -> XYZ {Y.S = A.S, Y.S = X.S, Y.S = Z.S} is not an L-attributed grammar since Y.S = A.S and Y.S = X.S are allowed but Y.S = Z.S violates the L-attributed SDT definition as attributed is inheriting the value from its right sibling.Note – If a definition is S-attributed, then it is also L-attributed but NOT vice-versa.Example – Consider the given below SDT.P1: S -> MN {S.val= M.val + N.val}
P2: M -> PQ {M.val = P.val * Q.val and P.val =Q.val} Select the correct option.A. Both P1 and P2 are S attributed.B. P1 is S attributed and P2 is L-attributed.C. P1 is L attributed but P2 is not L-attributed.D. None of the aboveExplanation –The correct answer is option C as, In P1, S is a synthesized attribute and in L-attribute definition synthesized is allowed. So P1 follows the L-attributed definition. But P2 doesn’t follow L-attributed definition as P is depending on Q which is RHS to it.My Personal Notes
arrow_drop_upSave
If an SDT uses both synthesized attributes and inherited attributes with a restriction that inherited attribute can inherit values from left siblings only, it is called as L-attributed SDT.
Attributes in L-attributed SDTs are evaluated by depth-first and left-to-right parsing manner.
Semantic actions are placed anywhere in RHS.
For example,
A -> XYZ {Y.S = A.S, Y.S = X.S, Y.S = Z.S}
is not an L-attributed grammar since Y.S = A.S and Y.S = X.S are allowed but Y.S = Z.S violates the L-attributed SDT definition as attributed is inheriting the value from its right sibling.
Note – If a definition is S-attributed, then it is also L-attributed but NOT vice-versa.
Example – Consider the given below SDT.
P1: S -> MN {S.val= M.val + N.val}
P2: M -> PQ {M.val = P.val * Q.val and P.val =Q.val}
Select the correct option.A. Both P1 and P2 are S attributed.B. P1 is S attributed and P2 is L-attributed.C. P1 is L attributed but P2 is not L-attributed.D. None of the above
Explanation –The correct answer is option C as, In P1, S is a synthesized attribute and in L-attribute definition synthesized is allowed. So P1 follows the L-attributed definition. But P2 doesn’t follow L-attributed definition as P is depending on Q which is RHS to it.
AnupKumarGupta
VaibhavRai3
VedantMoktali
Compiler Design
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n03 May, 2019"
},
{
"code": null,
"e": 169,
"s": 52,
"text": "Before coming up to S-attributed and L-attributed SDTs, here is a brief intro to Synthesized or Inherited attributes"
},
{
"code": null,
"e": 249,
"s": 169,
"text": "Types of attributes –Attributes may be of two types – Synthesized or Inherited."
},
{
"code": null,
"e": 1121,
"s": 249,
"text": "Synthesized attributes –A Synthesized attribute is an attribute of the non-terminal on the left-hand side of a production. Synthesized attributes represent information that is being passed up the parse tree. The attribute can take value only from its children (Variables in the RHS of the production).For eg. let’s say A -> BC is a production of a grammar, and A’s attribute is dependent on B’s attributes or C’s attributes then it will be synthesized attribute.Inherited attributes –An attribute of a nonterminal on the right-hand side of a production is called an inherited attribute. The attribute can take value either from its parent or from its siblings (variables in the LHS or RHS of the production).For example, let’s say A -> BC is a production of a grammar and B’s attribute is dependent on A’s attributes or C’s attributes then it will be inherited attribute."
},
{
"code": null,
"e": 1584,
"s": 1121,
"text": "Synthesized attributes –A Synthesized attribute is an attribute of the non-terminal on the left-hand side of a production. Synthesized attributes represent information that is being passed up the parse tree. The attribute can take value only from its children (Variables in the RHS of the production).For eg. let’s say A -> BC is a production of a grammar, and A’s attribute is dependent on B’s attributes or C’s attributes then it will be synthesized attribute."
},
{
"code": null,
"e": 1746,
"s": 1584,
"text": "For eg. let’s say A -> BC is a production of a grammar, and A’s attribute is dependent on B’s attributes or C’s attributes then it will be synthesized attribute."
},
{
"code": null,
"e": 2156,
"s": 1746,
"text": "Inherited attributes –An attribute of a nonterminal on the right-hand side of a production is called an inherited attribute. The attribute can take value either from its parent or from its siblings (variables in the LHS or RHS of the production).For example, let’s say A -> BC is a production of a grammar and B’s attribute is dependent on A’s attributes or C’s attributes then it will be inherited attribute."
},
{
"code": null,
"e": 2320,
"s": 2156,
"text": "For example, let’s say A -> BC is a production of a grammar and B’s attribute is dependent on A’s attributes or C’s attributes then it will be inherited attribute."
},
{
"code": null,
"e": 2380,
"s": 2320,
"text": "Now, let’s discuss about S-attributed and L-attributed SDT."
},
{
"code": null,
"e": 3945,
"s": 2380,
"text": "S-attributed SDT :If an SDT uses only synthesized attributes, it is called as S-attributed SDT.S-attributed SDTs are evaluated in bottom-up parsing, as the values of the parent nodes depend upon the values of the child nodes.Semantic actions are placed in rightmost place of RHS.L-attributed SDT:If an SDT uses both synthesized attributes and inherited attributes with a restriction that inherited attribute can inherit values from left siblings only, it is called as L-attributed SDT.Attributes in L-attributed SDTs are evaluated by depth-first and left-to-right parsing manner.Semantic actions are placed anywhere in RHS.For example,A -> XYZ {Y.S = A.S, Y.S = X.S, Y.S = Z.S} is not an L-attributed grammar since Y.S = A.S and Y.S = X.S are allowed but Y.S = Z.S violates the L-attributed SDT definition as attributed is inheriting the value from its right sibling.Note – If a definition is S-attributed, then it is also L-attributed but NOT vice-versa.Example – Consider the given below SDT.P1: S -> MN {S.val= M.val + N.val}\nP2: M -> PQ {M.val = P.val * Q.val and P.val =Q.val} Select the correct option.A. Both P1 and P2 are S attributed.B. P1 is S attributed and P2 is L-attributed.C. P1 is L attributed but P2 is not L-attributed.D. None of the aboveExplanation –The correct answer is option C as, In P1, S is a synthesized attribute and in L-attribute definition synthesized is allowed. So P1 follows the L-attributed definition. But P2 doesn’t follow L-attributed definition as P is depending on Q which is RHS to it.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 4225,
"s": 3945,
"text": "S-attributed SDT :If an SDT uses only synthesized attributes, it is called as S-attributed SDT.S-attributed SDTs are evaluated in bottom-up parsing, as the values of the parent nodes depend upon the values of the child nodes.Semantic actions are placed in rightmost place of RHS."
},
{
"code": null,
"e": 4303,
"s": 4225,
"text": "If an SDT uses only synthesized attributes, it is called as S-attributed SDT."
},
{
"code": null,
"e": 4434,
"s": 4303,
"text": "S-attributed SDTs are evaluated in bottom-up parsing, as the values of the parent nodes depend upon the values of the child nodes."
},
{
"code": null,
"e": 4489,
"s": 4434,
"text": "Semantic actions are placed in rightmost place of RHS."
},
{
"code": null,
"e": 5775,
"s": 4489,
"text": "L-attributed SDT:If an SDT uses both synthesized attributes and inherited attributes with a restriction that inherited attribute can inherit values from left siblings only, it is called as L-attributed SDT.Attributes in L-attributed SDTs are evaluated by depth-first and left-to-right parsing manner.Semantic actions are placed anywhere in RHS.For example,A -> XYZ {Y.S = A.S, Y.S = X.S, Y.S = Z.S} is not an L-attributed grammar since Y.S = A.S and Y.S = X.S are allowed but Y.S = Z.S violates the L-attributed SDT definition as attributed is inheriting the value from its right sibling.Note – If a definition is S-attributed, then it is also L-attributed but NOT vice-versa.Example – Consider the given below SDT.P1: S -> MN {S.val= M.val + N.val}\nP2: M -> PQ {M.val = P.val * Q.val and P.val =Q.val} Select the correct option.A. Both P1 and P2 are S attributed.B. P1 is S attributed and P2 is L-attributed.C. P1 is L attributed but P2 is not L-attributed.D. None of the aboveExplanation –The correct answer is option C as, In P1, S is a synthesized attribute and in L-attribute definition synthesized is allowed. So P1 follows the L-attributed definition. But P2 doesn’t follow L-attributed definition as P is depending on Q which is RHS to it.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 5965,
"s": 5775,
"text": "If an SDT uses both synthesized attributes and inherited attributes with a restriction that inherited attribute can inherit values from left siblings only, it is called as L-attributed SDT."
},
{
"code": null,
"e": 6060,
"s": 5965,
"text": "Attributes in L-attributed SDTs are evaluated by depth-first and left-to-right parsing manner."
},
{
"code": null,
"e": 6105,
"s": 6060,
"text": "Semantic actions are placed anywhere in RHS."
},
{
"code": null,
"e": 6118,
"s": 6105,
"text": "For example,"
},
{
"code": null,
"e": 6162,
"s": 6118,
"text": "A -> XYZ {Y.S = A.S, Y.S = X.S, Y.S = Z.S} "
},
{
"code": null,
"e": 6352,
"s": 6162,
"text": "is not an L-attributed grammar since Y.S = A.S and Y.S = X.S are allowed but Y.S = Z.S violates the L-attributed SDT definition as attributed is inheriting the value from its right sibling."
},
{
"code": null,
"e": 6441,
"s": 6352,
"text": "Note – If a definition is S-attributed, then it is also L-attributed but NOT vice-versa."
},
{
"code": null,
"e": 6481,
"s": 6441,
"text": "Example – Consider the given below SDT."
},
{
"code": null,
"e": 6573,
"s": 6481,
"text": "P1: S -> MN {S.val= M.val + N.val}\nP2: M -> PQ {M.val = P.val * Q.val and P.val =Q.val} "
},
{
"code": null,
"e": 6749,
"s": 6573,
"text": "Select the correct option.A. Both P1 and P2 are S attributed.B. P1 is S attributed and P2 is L-attributed.C. P1 is L attributed but P2 is not L-attributed.D. None of the above"
},
{
"code": null,
"e": 7019,
"s": 6749,
"text": "Explanation –The correct answer is option C as, In P1, S is a synthesized attribute and in L-attribute definition synthesized is allowed. So P1 follows the L-attributed definition. But P2 doesn’t follow L-attributed definition as P is depending on Q which is RHS to it."
},
{
"code": null,
"e": 7034,
"s": 7019,
"text": "AnupKumarGupta"
},
{
"code": null,
"e": 7046,
"s": 7034,
"text": "VaibhavRai3"
},
{
"code": null,
"e": 7060,
"s": 7046,
"text": "VedantMoktali"
},
{
"code": null,
"e": 7076,
"s": 7060,
"text": "Compiler Design"
},
{
"code": null,
"e": 7084,
"s": 7076,
"text": "GATE CS"
}
]
|
SQL Query to Insert Multiple Rows | 13 Sep, 2021
Insertion in a table is a DML (Data manipulation language) operation in SQL. When we want to store data we need to insert the data into the database. We use the INSERT statement to insert the data into the database. In this article, we see how to insert individual as well as multiple rows in a database using the INSERT statement in the MSSQL server.
Creating a Database: Use the below command to create a database named GeeksforGeeks:
Query:
CREATE DATABASE GeeksforGeeks;
Output:
Using the Database: To use the GeeksforGeeks database use the below command:
Query:
USE GeeksforGeeks
Output:
Creating a Table: Create a table employee_details with 4 columns using the following SQL query:
Query:
CREATE TABLE employee_details(
emp_id VARCHAR(8),
emp_name VARCHAR(20),
emp_dept_id VARCHAR(20),
emp_age INT);
Output:
Verifying the table: To view the description of the tables in the database using the following SQL query:
Query:
EXEC sp_columns employee_details;
Output:
The query for Inserting rows into the Table :
Inserting rows into employee_details table using the following SQL query:
1. Inserting individual rows into the table :
Query:
INSERT INTO employee_details VALUES('E40001','PRADEEP','E101',36);
INSERT INTO employee_details VALUES('E40002','ASHOK','E102',28);
INSERT INTO employee_details VALUES('E40003','PAVAN KUMAR','E103',28);
Output:
2. Viewing the inserted data:
Query:
SELECT * FROM employee_details;
Output:
3. Inserting multiple rows into the table:
Query:
INSERT INTO employee_details VALUES
('E40004','SANTHOSH','E102',25),
('E40005','THAMAN','E103',26),
('E40006','HARSH','E101',25),
('E40007','SAMHITH','E102',26);
Output:
4. Viewing the inserted data now:
Query:
SELECT * FROM employee_details;
Output:
Picked
Blogathon
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n13 Sep, 2021"
},
{
"code": null,
"e": 405,
"s": 52,
"text": "Insertion in a table is a DML (Data manipulation language) operation in SQL. When we want to store data we need to insert the data into the database. We use the INSERT statement to insert the data into the database. In this article, we see how to insert individual as well as multiple rows in a database using the INSERT statement in the MSSQL server."
},
{
"code": null,
"e": 490,
"s": 405,
"text": "Creating a Database: Use the below command to create a database named GeeksforGeeks:"
},
{
"code": null,
"e": 497,
"s": 490,
"text": "Query:"
},
{
"code": null,
"e": 528,
"s": 497,
"text": "CREATE DATABASE GeeksforGeeks;"
},
{
"code": null,
"e": 536,
"s": 528,
"text": "Output:"
},
{
"code": null,
"e": 613,
"s": 536,
"text": "Using the Database: To use the GeeksforGeeks database use the below command:"
},
{
"code": null,
"e": 620,
"s": 613,
"text": "Query:"
},
{
"code": null,
"e": 638,
"s": 620,
"text": "USE GeeksforGeeks"
},
{
"code": null,
"e": 646,
"s": 638,
"text": "Output:"
},
{
"code": null,
"e": 744,
"s": 646,
"text": "Creating a Table: Create a table employee_details with 4 columns using the following SQL query: "
},
{
"code": null,
"e": 751,
"s": 744,
"text": "Query:"
},
{
"code": null,
"e": 874,
"s": 751,
"text": "CREATE TABLE employee_details(\n emp_id VARCHAR(8),\n emp_name VARCHAR(20),\n emp_dept_id VARCHAR(20),\n emp_age INT);"
},
{
"code": null,
"e": 882,
"s": 874,
"text": "Output:"
},
{
"code": null,
"e": 988,
"s": 882,
"text": "Verifying the table: To view the description of the tables in the database using the following SQL query:"
},
{
"code": null,
"e": 995,
"s": 988,
"text": "Query:"
},
{
"code": null,
"e": 1029,
"s": 995,
"text": "EXEC sp_columns employee_details;"
},
{
"code": null,
"e": 1037,
"s": 1029,
"text": "Output:"
},
{
"code": null,
"e": 1084,
"s": 1037,
"text": "The query for Inserting rows into the Table :"
},
{
"code": null,
"e": 1158,
"s": 1084,
"text": "Inserting rows into employee_details table using the following SQL query:"
},
{
"code": null,
"e": 1204,
"s": 1158,
"text": "1. Inserting individual rows into the table :"
},
{
"code": null,
"e": 1211,
"s": 1204,
"text": "Query:"
},
{
"code": null,
"e": 1415,
"s": 1211,
"text": "INSERT INTO employee_details VALUES('E40001','PRADEEP','E101',36);\nINSERT INTO employee_details VALUES('E40002','ASHOK','E102',28);\nINSERT INTO employee_details VALUES('E40003','PAVAN KUMAR','E103',28); "
},
{
"code": null,
"e": 1423,
"s": 1415,
"text": "Output:"
},
{
"code": null,
"e": 1453,
"s": 1423,
"text": "2. Viewing the inserted data:"
},
{
"code": null,
"e": 1460,
"s": 1453,
"text": "Query:"
},
{
"code": null,
"e": 1492,
"s": 1460,
"text": "SELECT * FROM employee_details;"
},
{
"code": null,
"e": 1500,
"s": 1492,
"text": "Output:"
},
{
"code": null,
"e": 1543,
"s": 1500,
"text": "3. Inserting multiple rows into the table:"
},
{
"code": null,
"e": 1550,
"s": 1543,
"text": "Query:"
},
{
"code": null,
"e": 1718,
"s": 1550,
"text": "INSERT INTO employee_details VALUES\n ('E40004','SANTHOSH','E102',25),\n ('E40005','THAMAN','E103',26),\n('E40006','HARSH','E101',25),\n ('E40007','SAMHITH','E102',26);"
},
{
"code": null,
"e": 1726,
"s": 1718,
"text": "Output:"
},
{
"code": null,
"e": 1760,
"s": 1726,
"text": "4. Viewing the inserted data now:"
},
{
"code": null,
"e": 1767,
"s": 1760,
"text": "Query:"
},
{
"code": null,
"e": 1799,
"s": 1767,
"text": "SELECT * FROM employee_details;"
},
{
"code": null,
"e": 1807,
"s": 1799,
"text": "Output:"
},
{
"code": null,
"e": 1814,
"s": 1807,
"text": "Picked"
},
{
"code": null,
"e": 1824,
"s": 1814,
"text": "Blogathon"
},
{
"code": null,
"e": 1828,
"s": 1824,
"text": "SQL"
},
{
"code": null,
"e": 1832,
"s": 1828,
"text": "SQL"
}
]
|
Set add() method in Java with Examples | 31 Dec, 2018
The add() method of Set in Java is used to add a specific element into a Set collection. The function adds the element only if the specified element is not already present in the set else the function return False if the element is already present in the Set.
Syntax:
boolean add(E element)
Where, E is the type of element maintained
by this Set collection.
Parameters: The parameter element is of the type of element maintained by this Set and it refers to the element to be added to the Set.
Return Value: The function returns True if the element is not present in the set and is new, else it returns False if the element is already present in the set.
Below programs illustrate the use of Java.util.Set.add() method:
Program 1:
// Java code to illustrate add() methodimport java.io.*;import java.util.*; public class TreeSetDemo { public static void main(String args[]) { // Creating an empty Set Set<String> s = new HashSet<String>(); // Use add() method to add elements into the Set s.add("Welcome"); s.add("To"); s.add("Geeks"); s.add("4"); s.add("Geeks"); s.add("Set"); // Displaying the Set System.out.println("Set: " + s); }}
Set: [Set, 4, Geeks, Welcome, To]
Program 2:
// Java code to illustrate add() methodimport java.io.*;import java.util.*; public class TreeSetDemo { public static void main(String args[]) { // Creating an empty Set Set<Integer> s = new HashSet<Integer>(); // Use add() method to add elements into the Set s.add(10); s.add(20); s.add(30); s.add(40); s.add(50); s.add(60); // Displaying the Set System.out.println("Set: " + s); }}
Set: [50, 20, 40, 10, 60, 30]
Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#add(E)
Java-Collections
Java-Functions
java-set
Misc
Misc
Misc
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 Dec, 2018"
},
{
"code": null,
"e": 288,
"s": 28,
"text": "The add() method of Set in Java is used to add a specific element into a Set collection. The function adds the element only if the specified element is not already present in the set else the function return False if the element is already present in the Set."
},
{
"code": null,
"e": 296,
"s": 288,
"text": "Syntax:"
},
{
"code": null,
"e": 388,
"s": 296,
"text": "boolean add(E element)\n\nWhere, E is the type of element maintained\nby this Set collection.\n"
},
{
"code": null,
"e": 524,
"s": 388,
"text": "Parameters: The parameter element is of the type of element maintained by this Set and it refers to the element to be added to the Set."
},
{
"code": null,
"e": 685,
"s": 524,
"text": "Return Value: The function returns True if the element is not present in the set and is new, else it returns False if the element is already present in the set."
},
{
"code": null,
"e": 750,
"s": 685,
"text": "Below programs illustrate the use of Java.util.Set.add() method:"
},
{
"code": null,
"e": 761,
"s": 750,
"text": "Program 1:"
},
{
"code": "// Java code to illustrate add() methodimport java.io.*;import java.util.*; public class TreeSetDemo { public static void main(String args[]) { // Creating an empty Set Set<String> s = new HashSet<String>(); // Use add() method to add elements into the Set s.add(\"Welcome\"); s.add(\"To\"); s.add(\"Geeks\"); s.add(\"4\"); s.add(\"Geeks\"); s.add(\"Set\"); // Displaying the Set System.out.println(\"Set: \" + s); }}",
"e": 1256,
"s": 761,
"text": null
},
{
"code": null,
"e": 1291,
"s": 1256,
"text": "Set: [Set, 4, Geeks, Welcome, To]\n"
},
{
"code": null,
"e": 1302,
"s": 1291,
"text": "Program 2:"
},
{
"code": "// Java code to illustrate add() methodimport java.io.*;import java.util.*; public class TreeSetDemo { public static void main(String args[]) { // Creating an empty Set Set<Integer> s = new HashSet<Integer>(); // Use add() method to add elements into the Set s.add(10); s.add(20); s.add(30); s.add(40); s.add(50); s.add(60); // Displaying the Set System.out.println(\"Set: \" + s); }}",
"e": 1776,
"s": 1302,
"text": null
},
{
"code": null,
"e": 1807,
"s": 1776,
"text": "Set: [50, 20, 40, 10, 60, 30]\n"
},
{
"code": null,
"e": 1886,
"s": 1807,
"text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#add(E)"
},
{
"code": null,
"e": 1903,
"s": 1886,
"text": "Java-Collections"
},
{
"code": null,
"e": 1918,
"s": 1903,
"text": "Java-Functions"
},
{
"code": null,
"e": 1927,
"s": 1918,
"text": "java-set"
},
{
"code": null,
"e": 1932,
"s": 1927,
"text": "Misc"
},
{
"code": null,
"e": 1937,
"s": 1932,
"text": "Misc"
},
{
"code": null,
"e": 1942,
"s": 1937,
"text": "Misc"
},
{
"code": null,
"e": 1959,
"s": 1942,
"text": "Java-Collections"
}
]
|
General purpose registers in 8086 microprocessor | 24 Jun, 2022
General-purpose registers are used to store temporary data within the microprocessor. There are 8 general-purpose registers in the 8086 microprocessor.
1. AX: This is the accumulator. It is of 16 bits and is divided into two 8-bit registers AH and AL to also perform 8-bit instructions. It is generally used for arithmetical and logical instructions but in 8086 microprocessor it is not mandatory to have an accumulator as the destination operand. Example:
ADD AX, AX (AX = AX + AX)
2. BX: This is the base register. It is of 16 bits and is divided into two 8-bit registers BH and BL to also perform 8-bit instructions. It is used to store the value of the offset. Example:
MOV BL, [500] (BL = 500H)
3. CX: This is the counter register. It is of 16 bits and is divided into two 8-bit registers CH and CL to also perform 8-bit instructions. It is used in looping and rotation. Example:
MOV CX, 0005
LOOP
4. DX: This is the data register. It is of 16 bits and is divided into two 8-bit registers DH and DL to also perform 8-bit instructions. It is used in the multiplication and input/output port addressing. Example:
MUL BX (DX, AX = AX * BX)
5. SP: This is the stack pointer. It is of 16 bits. It points to the topmost item of the stack. If the stack is empty the stack pointer will be (FFFE)H. Its offset address is relative to the stack segment.
6. BP – This is the base pointer. It is of 16 bits. It is primarily used in accessing parameters passed by the stack. Its offset address is relative to the stack segment.
7. SI – This is the source index register. It is of 16 bits. It is used in the pointer addressing of data and as a source in some string-related operations. Its offset is relative to the data segment.
8. DI – This is the destination index register. It is of 16 bits. It is used in the pointer addressing of data and as a destination in some string-related operations. Its offset is relative to the extra segment.
tilakraj7050
Computer Organization & Architecture
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Control Characters
Direct Access Media (DMA) Controller in Computer Architecture
Computer Organization | RISC and CISC
Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)
Memory Hierarchy Design and its Characteristics
Programmable peripheral interface 8255
Architecture of 8085 microprocessor
Interrupts
Write Through and Write Back in Cache
Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard) | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n24 Jun, 2022"
},
{
"code": null,
"e": 205,
"s": 53,
"text": "General-purpose registers are used to store temporary data within the microprocessor. There are 8 general-purpose registers in the 8086 microprocessor."
},
{
"code": null,
"e": 512,
"s": 207,
"text": "1. AX: This is the accumulator. It is of 16 bits and is divided into two 8-bit registers AH and AL to also perform 8-bit instructions. It is generally used for arithmetical and logical instructions but in 8086 microprocessor it is not mandatory to have an accumulator as the destination operand. Example:"
},
{
"code": null,
"e": 538,
"s": 512,
"text": "ADD AX, AX (AX = AX + AX)"
},
{
"code": null,
"e": 729,
"s": 538,
"text": "2. BX: This is the base register. It is of 16 bits and is divided into two 8-bit registers BH and BL to also perform 8-bit instructions. It is used to store the value of the offset. Example:"
},
{
"code": null,
"e": 755,
"s": 729,
"text": "MOV BL, [500] (BL = 500H)"
},
{
"code": null,
"e": 940,
"s": 755,
"text": "3. CX: This is the counter register. It is of 16 bits and is divided into two 8-bit registers CH and CL to also perform 8-bit instructions. It is used in looping and rotation. Example:"
},
{
"code": null,
"e": 958,
"s": 940,
"text": "MOV CX, 0005\nLOOP"
},
{
"code": null,
"e": 1171,
"s": 958,
"text": "4. DX: This is the data register. It is of 16 bits and is divided into two 8-bit registers DH and DL to also perform 8-bit instructions. It is used in the multiplication and input/output port addressing. Example:"
},
{
"code": null,
"e": 1197,
"s": 1171,
"text": "MUL BX (DX, AX = AX * BX)"
},
{
"code": null,
"e": 1403,
"s": 1197,
"text": "5. SP: This is the stack pointer. It is of 16 bits. It points to the topmost item of the stack. If the stack is empty the stack pointer will be (FFFE)H. Its offset address is relative to the stack segment."
},
{
"code": null,
"e": 1574,
"s": 1403,
"text": "6. BP – This is the base pointer. It is of 16 bits. It is primarily used in accessing parameters passed by the stack. Its offset address is relative to the stack segment."
},
{
"code": null,
"e": 1775,
"s": 1574,
"text": "7. SI – This is the source index register. It is of 16 bits. It is used in the pointer addressing of data and as a source in some string-related operations. Its offset is relative to the data segment."
},
{
"code": null,
"e": 1987,
"s": 1775,
"text": "8. DI – This is the destination index register. It is of 16 bits. It is used in the pointer addressing of data and as a destination in some string-related operations. Its offset is relative to the extra segment."
},
{
"code": null,
"e": 2000,
"s": 1987,
"text": "tilakraj7050"
},
{
"code": null,
"e": 2037,
"s": 2000,
"text": "Computer Organization & Architecture"
},
{
"code": null,
"e": 2135,
"s": 2037,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2154,
"s": 2135,
"text": "Control Characters"
},
{
"code": null,
"e": 2216,
"s": 2154,
"text": "Direct Access Media (DMA) Controller in Computer Architecture"
},
{
"code": null,
"e": 2254,
"s": 2216,
"text": "Computer Organization | RISC and CISC"
},
{
"code": null,
"e": 2349,
"s": 2254,
"text": "Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)"
},
{
"code": null,
"e": 2397,
"s": 2349,
"text": "Memory Hierarchy Design and its Characteristics"
},
{
"code": null,
"e": 2436,
"s": 2397,
"text": "Programmable peripheral interface 8255"
},
{
"code": null,
"e": 2472,
"s": 2436,
"text": "Architecture of 8085 microprocessor"
},
{
"code": null,
"e": 2483,
"s": 2472,
"text": "Interrupts"
},
{
"code": null,
"e": 2521,
"s": 2483,
"text": "Write Through and Write Back in Cache"
}
]
|
Union and Intersection of two Linked Lists | 11 Jul, 2022
Given two Linked Lists, create union and intersection lists that contain union and intersection of the elements present in the given lists. The order of elements in output lists doesn’t matter.Example:
Input:
List1: 10->15->4->20
List2: 8->4->2->10
Output:
Intersection List: 4->10
Union List: 2->8->20->4->15->10
Method 1 (Simple):
The following are simple algorithms to get union and intersection lists respectively.Intersection (list1, list2)Initialize the result list as NULL. Traverse list1 and look for every element in list2, if the element is present in list2, then add the element to the result.Union (list1, list2):Initialize a new list ans and store first and second list data to set to remove duplicate data and then store it into our new list ans and return its head.
C++
C
Java
C#
Javascript
// C++ program to find union// and intersection of two unsorted// linked lists#include "bits/stdc++.h"using namespace std; /* Link list node */struct Node { int data; struct Node* next; Node(int x) { data = x; next = NULL; }}; /* A utility function to insert anode at the beginning ofa linked list*/void push(struct Node** head_ref, int new_data); /* A utility function to check ifgiven data is present in a list */bool isPresent(struct Node* head, int data); /* Function to get union of twolinked lists head1 and head2 */struct Node* getUnion(struct Node* head1, struct Node* head2){ struct Node* ans = new Node(-1); struct Node* head = ans; set<int> st; while (head1 != NULL) { st.insert(head1->data); head1 = head1->next; } while (head2 != NULL) { st.insert(head2->data); head2 = head2->next; } for (auto it : st) { struct Node* t = new Node(it); ans->next = t; ans = ans->next; } head = head->next; return head;} /* Function to get intersection oftwo linked lists head1 and head2 */struct Node* getIntersection(struct Node* head1, struct Node* head2){ struct Node* result = NULL; struct Node* t1 = head1; // Traverse list1 and search each element of it in // list2. If the element is present in list 2, then // insert the element to result while (t1 != NULL) { if (isPresent(head2, t1->data)) push(&result, t1->data); t1 = t1->next; } return result;}/* A utility function to insert anode at the beginning of a linked list*/void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* A utility function to print a linked list*/void printList(struct Node* node){ while (node != NULL) { cout << " " << node->data; node = node->next; }}bool isPresent(struct Node* head, int data){ struct Node* t = head; while (t != NULL) { if (t->data == data) return 1; t = t->next; } return 0;} /* Driver program to test above function*/int main(){ /* Start with the empty list */ struct Node* head1 = NULL; struct Node* head2 = NULL; struct Node* intersecn = NULL; struct Node* unin = NULL; /*create a linked lists 10->15->5->20 */ push(&head1, 20); push(&head1, 4); push(&head1, 15); push(&head1, 10); /*create a linked lists 8->4->2->10 */ push(&head2, 10); push(&head2, 2); push(&head2, 4); push(&head2, 8); intersecn = getIntersection(head1, head2); unin = getUnion(head1, head2); cout << "\n First list is " << endl; printList(head1); cout << "\n Second list is " << endl; printList(head2); cout << "\n Intersection list is " << endl; printList(intersecn); cout << "\n Union list is " << endl; printList(unin); return 0;} // This code is contributed by zishanahmad786
// C program to find union// and intersection of two unsorted// linked lists#include <stdbool.h>#include <stdio.h>#include <stdlib.h>/* Link list node */struct Node { int data; struct Node* next;}; /* A utility function to insert a node at the beginning ofa linked list*/void push(struct Node** head_ref, int new_data); /* A utility function to check if given data is present in a list */bool isPresent(struct Node* head, int data); /* Function to get union of two linked lists head1 and head2 */struct Node* getUnion(struct Node* head1, struct Node* head2){ struct Node* result = NULL; struct Node *t1 = head1, *t2 = head2; // Insert all elements of // list1 to the result list while (t1 != NULL) { push(&result, t1->data); t1 = t1->next; } // Insert those elements of list2 // which are not present in result list while (t2 != NULL) { if (!isPresent(result, t2->data)) push(&result, t2->data); t2 = t2->next; } return result;} /* Function to get intersection of two linked lists head1 and head2 */struct Node* getIntersection(struct Node* head1, struct Node* head2){ struct Node* result = NULL; struct Node* t1 = head1; // Traverse list1 and search each element of it in // list2. If the element is present in list 2, then // insert the element to result while (t1 != NULL) { if (isPresent(head2, t1->data)) push(&result, t1->data); t1 = t1->next; } return result;} /* A utility function to insert a node at the beginning of a linked list*/void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* A utility function to print a linked list*/void printList(struct Node* node){ while (node != NULL) { printf("%d ", node->data); node = node->next; }} /* A utility function that returns true if data is present in linked list else return false */bool isPresent(struct Node* head, int data){ struct Node* t = head; while (t != NULL) { if (t->data == data) return 1; t = t->next; } return 0;} /* Driver program to test above function*/int main(){ /* Start with the empty list */ struct Node* head1 = NULL; struct Node* head2 = NULL; struct Node* intersecn = NULL; struct Node* unin = NULL; /*create a linked lists 10->15->5->20 */ push(&head1, 20); push(&head1, 4); push(&head1, 15); push(&head1, 10); /*create a linked lists 8->4->2->10 */ push(&head2, 10); push(&head2, 2); push(&head2, 4); push(&head2, 8); intersecn = getIntersection(head1, head2); unin = getUnion(head1, head2); printf("\n First list is \n"); printList(head1); printf("\n Second list is \n"); printList(head2); printf("\n Intersection list is \n"); printList(intersecn); printf("\n Union list is \n"); printList(unin); return 0;}
// Java program to find union and// intersection of two unsorted// linked listsclass LinkedList { Node head; // head of list /* Linked list Node*/ class Node { int data; Node next; Node(int d) { data = d; next = null; } } /* Function to get Union of 2 Linked Lists */ void getUnion(Node head1, Node head2) { Node t1 = head1, t2 = head2; // insert all elements of list1 in the result while (t1 != null) { push(t1.data); t1 = t1.next; } // insert those elements of list2 // that are not present while (t2 != null) { if (!isPresent(head, t2.data)) push(t2.data); t2 = t2.next; } } void getIntersection(Node head1, Node head2) { Node result = null; Node t1 = head1; // Traverse list1 and search each // element of it in list2. // If the element is present in // list 2, then insert the // element to result while (t1 != null) { if (isPresent(head2, t1.data)) push(t1.data); t1 = t1.next; } } /* Utility function to print list */ void printList() { Node temp = head; while (temp != null) { System.out.print(temp.data + " "); temp = temp.next; } System.out.println(); } /* Inserts a node at start of linked list */ void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* A utility function that returns true if data is present in linked list else return false */ boolean isPresent(Node head, int data) { Node t = head; while (t != null) { if (t.data == data) return true; t = t.next; } return false; } /* Driver program to test above functions */ public static void main(String args[]) { LinkedList llist1 = new LinkedList(); LinkedList llist2 = new LinkedList(); LinkedList unin = new LinkedList(); LinkedList intersecn = new LinkedList(); /*create a linked lists 10->15->4->20 */ llist1.push(20); llist1.push(4); llist1.push(15); llist1.push(10); /*create a linked lists 8->4->2->10 */ llist2.push(10); llist2.push(2); llist2.push(4); llist2.push(8); intersecn.getIntersection(llist1.head, llist2.head); unin.getUnion(llist1.head, llist2.head); System.out.println("First List is"); llist1.printList(); System.out.println("Second List is"); llist2.printList(); System.out.println("Intersection List is"); intersecn.printList(); System.out.println("Union List is"); unin.printList(); }} /* This code is contributed by Rajat Mishra */
// C# program to find union and// intersection of two unsorted// linked listsusing System;class LinkedList { public Node head; // head of list /* Linked list Node*/ public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } /* Function to get Union of 2 Linked Lists */ void getUnion(Node head1, Node head2) { Node t1 = head1, t2 = head2; // insert all elements of list1 in the result while (t1 != null) { push(t1.data); t1 = t1.next; } // insert those elements of list2 // that are not present while (t2 != null) { if (!isPresent(head, t2.data)) push(t2.data); t2 = t2.next; } } void getIntersection(Node head1, Node head2) { Node t1 = head1; // Traverse list1 and search each // element of it in list2. // If the element is present in // list 2, then insert the // element to result while (t1 != null) { if (isPresent(head2, t1.data)) push(t1.data); t1 = t1.next; } } /* Utility function to print list */ void printList() { Node temp = head; while (temp != null) { Console.Write(temp.data + " "); temp = temp.next; } Console.WriteLine(); } /* Inserts a node at start of linked list */ void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* A utility function that returns true if data is present in linked list else return false */ bool isPresent(Node head, int data) { Node t = head; while (t != null) { if (t.data == data) return true; t = t.next; } return false; } /* Driver code*/ public static void Main(string[] args) { LinkedList llist1 = new LinkedList(); LinkedList llist2 = new LinkedList(); LinkedList unin = new LinkedList(); LinkedList intersecn = new LinkedList(); /*create a linked lists 10->15->5->20 */ llist1.push(20); llist1.push(4); llist1.push(15); llist1.push(10); /*create a linked lists 8->4->2->10 */ llist2.push(10); llist2.push(2); llist2.push(4); llist2.push(8); intersecn.getIntersection(llist1.head, llist2.head); unin.getUnion(llist1.head, llist2.head); Console.WriteLine("First List is"); llist1.printList(); Console.WriteLine("Second List is"); llist2.printList(); Console.WriteLine("Intersection List is"); intersecn.printList(); Console.WriteLine("Union List is"); unin.printList(); }} // This code is contributed by rutvik_56.
<script> //Javascript program to find union and // intersection of two unsorted // linked lists /* Linked list Node*/ class Node { constructor(d) { this.data = d; this.next = null; } } class LinkedList{ constructor(){ this.head=null; } /* Inserts a node at start of linked list */ push(new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ var new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = this.head; /* 4. Move the head to point to new Node */ this.head = new_node; } /* A utility function that returns true if data is present in linked list else return false */ isPresent(head, data) { var t = head; while (t != null) { if (t.data == data) return true; t = t.next; } return false; } /* Function to get Union of 2 Linked Lists */ getUnion(head1, head2) { var t1 = head1, t2 = head2; // insert all elements of list1 in the result while (t1 != null) { this.push(t1.data); t1 = t1.next; } // insert those elements of list2 // that are not present while (t2 != null) { if (!this.isPresent(this.head, t2.data)) this.push(t2.data); t2 = t2.next; } } getIntersection(head1, head2) { var result = null; var t1 = head1; // Traverse list1 and search each // element of it in list2. // If the element is present in // list 2, then insert the // element to result while (t1 != null) { if (this.isPresent(head2, t1.data)) this.push(t1.data); t1 = t1.next; } } /* Utility function to print list */ printList() { var temp = this.head; while (temp != null) { document.write(temp.data + " "); temp = temp.next; } } } const llist1 = new LinkedList(); const llist2 = new LinkedList(); const unin = new LinkedList(); const intersecn = new LinkedList(); /*create a linked lists 10->15->4->20 */ llist1.push(20); llist1.push(4); llist1.push(15); llist1.push(10); /*create a linked lists 8->4->2->10 */ llist2.push(10); llist2.push(2); llist2.push(4); llist2.push(8); intersecn.getIntersection(llist1.head, llist2.head); unin.getUnion(llist1.head, llist2.head); document.write("First List is "); llist1.printList(); document.write("Second List is "); llist2.printList(); document.write("Intersection List is "); intersecn.printList(); document.write("Union List is "); unin.printList(); //This code is contributed by shruti456rawal</script>
First list is
10 15 4 20
Second list is
8 4 2 10
Intersection list is
4 10
Union list is
2 8 20 4 15 10
Complexity Analysis:
Time Complexity: O(m*n).Here ‘m’ and ‘n’ are number of elements present in the first and second lists respectively. For union: For every element in list-2 we check if that element is already present in the resultant list made using list-1.For intersection: For every element in list-1 we check if that element is also present in list-2.
Auxiliary Space: O(1). No use of any data structure for storing values.
Method 2 (Use Merge Sort):
In this method, algorithms for Union and Intersection are very similar. First, we sort the given lists, then we traverse the sorted lists to get union and intersection. The following are the steps to be followed to get union and intersection lists.
Sort the first Linked List using merge sort. This step takes O(mLogm) time. Refer this post for details of this step.Sort the second Linked List using merge sort. This step takes O(nLogn) time. Refer this post for details of this step.Linearly scan both sorted lists to get the union and intersection. This step takes O(m + n) time. This step can be implemented using the same algorithm as sorted arrays algorithm discussed here.
Sort the first Linked List using merge sort. This step takes O(mLogm) time. Refer this post for details of this step.
Sort the second Linked List using merge sort. This step takes O(nLogn) time. Refer this post for details of this step.
Linearly scan both sorted lists to get the union and intersection. This step takes O(m + n) time. This step can be implemented using the same algorithm as sorted arrays algorithm discussed here.
The time complexity of this method is O(mLogm + nLogn) which is better than method 1’s time complexity.
Method 3 (Use Hashing):
Union (list1, list2)Initialize the result list as NULL and create an empty hash table. Traverse both lists one by one, for each element being visited, look at the element in the hash table. If the element is not present, then insert the element into the result list. If the element is present, then ignore it.Intersection (list1, list2)Initialize the result list as NULL and create an empty hash table. Traverse list1. For each element being visited in list1, insert the element in the hash table. Traverse list2, for each element being visited in list2, look the element in the hash table. If the element is present, then insert the element to the result list. If the element is not present, then ignore it.Both of the above methods assume that there are no duplicates.
Java
C#
// Java code for Union and Intersection of two// Linked Listsimport java.util.HashMap;import java.util.HashSet; class LinkedList { Node head; // head of list /* Linked list Node*/ class Node { int data; Node next; Node(int d) { data = d; next = null; } } /* Utility function to print list */ void printList() { Node temp = head; while (temp != null) { System.out.print(temp.data + " "); temp = temp.next; } System.out.println(); } /* Inserts a node at start of linked list */ void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } public void append(int new_data) { if (this.head == null) { Node n = new Node(new_data); this.head = n; return; } Node n1 = this.head; Node n2 = new Node(new_data); while (n1.next != null) { n1 = n1.next; } n1.next = n2; n2.next = null; } /* A utility function that returns true if data is present in linked list else return false */ boolean isPresent(Node head, int data) { Node t = head; while (t != null) { if (t.data == data) return true; t = t.next; } return false; } LinkedList getIntersection(Node head1, Node head2) { HashSet<Integer> hset = new HashSet<>(); Node n1 = head1; Node n2 = head2; LinkedList result = new LinkedList(); // loop stores all the elements of list1 in hset while (n1 != null) { if (hset.contains(n1.data)) { hset.add(n1.data); } else { hset.add(n1.data); } n1 = n1.next; } // For every element of list2 present in hset // loop inserts the element into the result while (n2 != null) { if (hset.contains(n2.data)) { result.push(n2.data); } n2 = n2.next; } return result; } LinkedList getUnion(Node head1, Node head2) { // HashMap that will store the // elements of the lists with their counts HashMap<Integer, Integer> hmap = new HashMap<>(); Node n1 = head1; Node n2 = head2; LinkedList result = new LinkedList(); // loop inserts the elements and the count of // that element of list1 into the hmap while (n1 != null) { if (hmap.containsKey(n1.data)) { int val = hmap.get(n1.data); hmap.put(n1.data, val + 1); } else { hmap.put(n1.data, 1); } n1 = n1.next; } // loop further adds the elements of list2 with // their counts into the hmap while (n2 != null) { if (hmap.containsKey(n2.data)) { int val = hmap.get(n2.data); hmap.put(n2.data, val + 1); } else { hmap.put(n2.data, 1); } n2 = n2.next; } // Eventually add all the elements // into the result that are present in the hmap for (int a : hmap.keySet()) { result.append(a); } return result; } /* Driver program to test above functions */ public static void main(String args[]) { LinkedList llist1 = new LinkedList(); LinkedList llist2 = new LinkedList(); LinkedList union = new LinkedList(); LinkedList intersection = new LinkedList(); /*create a linked list 10->15->4->20 */ llist1.push(20); llist1.push(4); llist1.push(15); llist1.push(10); /*create a linked list 8->4->2->10 */ llist2.push(10); llist2.push(2); llist2.push(4); llist2.push(8); intersection = intersection.getIntersection(llist1.head, llist2.head); union = union.getUnion(llist1.head, llist2.head); System.out.println("First List is"); llist1.printList(); System.out.println("Second List is"); llist2.printList(); System.out.println("Intersection List is"); intersection.printList(); System.out.println("Union List is"); union.printList(); }}// This code is contributed by Kamal Rawal
// C# code for Union and Intersection of two// Linked Listsusing System;using System.Collections;using System.Collections.Generic; class LinkedList{ public Node head; // head of list /* Linked list Node*/ public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } /* Utility function to print list */ void printList() { Node temp = head; while (temp != null) { Console.Write(temp.data + " "); temp = temp.next; } Console.WriteLine(); } /* Inserts a node at start of linked list */ void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } public void append(int new_data) { if (this.head == null) { Node n = new Node(new_data); this.head = n; return; } Node n1 = this.head; Node n2 = new Node(new_data); while (n1.next != null) { n1 = n1.next; } n1.next = n2; n2.next = null; } /* A utility function that returns true if data is present in linked list else return false */ bool isPresent(Node head, int data) { Node t = head; while (t != null) { if (t.data == data) return true; t = t.next; } return false; } LinkedList getIntersection(Node head1, Node head2) { HashSet<int> hset = new HashSet<int>(); Node n1 = head1; Node n2 = head2; LinkedList result = new LinkedList(); // loop stores all the elements of list1 in hset while (n1 != null) { if (hset.Contains(n1.data)) { hset.Add(n1.data); } else { hset.Add(n1.data); } n1 = n1.next; } // For every element of list2 present in hset // loop inserts the element into the result while (n2 != null) { if (hset.Contains(n2.data)) { result.push(n2.data); } n2 = n2.next; } return result; } LinkedList getUnion(Node head1, Node head2) { // HashMap that will store the // elements of the lists with their counts SortedDictionary<int, int> hmap = new SortedDictionary<int, int>(); Node n1 = head1; Node n2 = head2; LinkedList result = new LinkedList(); // loop inserts the elements and the count of // that element of list1 into the hmap while (n1 != null) { if (hmap.ContainsKey(n1.data)) { hmap[n1.data]++; } else { hmap[n1.data]= 1; } n1 = n1.next; } // loop further adds the elements of list2 with // their counts into the hmap while (n2 != null) { if (hmap.ContainsKey(n2.data)) { hmap[n2.data]++; } else { hmap[n2.data]= 1; } n2 = n2.next; } // Eventually add all the elements // into the result that are present in the hmap foreach(int a in hmap.Keys) { result.append(a); } return result; } /* Driver program to test above functions */ public static void Main(string []args) { LinkedList llist1 = new LinkedList(); LinkedList llist2 = new LinkedList(); LinkedList union = new LinkedList(); LinkedList intersection = new LinkedList(); /*create a linked list 10->15->4->20 */ llist1.push(20); llist1.push(4); llist1.push(15); llist1.push(10); /*create a linked list 8->4->2->10 */ llist2.push(10); llist2.push(2); llist2.push(4); llist2.push(8); intersection = intersection.getIntersection(llist1.head, llist2.head); union = union.getUnion(llist1.head, llist2.head); Console.WriteLine("First List is"); llist1.printList(); Console.WriteLine("Second List is"); llist2.printList(); Console.WriteLine("Intersection List is"); intersection.printList(); Console.WriteLine("Union List is"); union.printList(); }} //This code is contributed by pratham76
First List is
10 15 4 20
Second List is
8 4 2 10
Intersection List is
10 4
Union List is
2 4 20 8 10 15
Complexity Analysis:
Time Complexity: O(m+n).Here ‘m’ and ‘n’ are number of elements present in the first and second lists respectively. For union: Traverse both the lists, store the elements in Hash-map and update the respective count.For intersection: First traverse list-1, store its elements in Hash-map and then for every element in list-2 check if it is already present in the map. This takes O(1) time.
Auxiliary Space:O(m+n).Use of Hash-map data structure for storing values.
bidibaaz123
Akanksha_Rai
rutvik_56
shivanisinghss2110
pratham76
gabaa406
simmytarika5
saurabh1990aror
akash8900
sumitgumber28
zishanahmad786
shruti456rawal
hardikkoriintern
24*7 Innovation Labs
Accolite
Amazon
Flipkart
Komli Media
Microsoft
Taxi4Sure
VMWare
Walmart
Hash
Linked List
Sorting
VMWare
Flipkart
Accolite
Amazon
Microsoft
24*7 Innovation Labs
Walmart
Komli Media
Taxi4Sure
Linked List
Hash
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n11 Jul, 2022"
},
{
"code": null,
"e": 257,
"s": 54,
"text": "Given two Linked Lists, create union and intersection lists that contain union and intersection of the elements present in the given lists. The order of elements in output lists doesn’t matter.Example: "
},
{
"code": null,
"e": 383,
"s": 257,
"text": "Input:\n List1: 10->15->4->20\n List2: 8->4->2->10\nOutput:\n Intersection List: 4->10\n Union List: 2->8->20->4->15->10 "
},
{
"code": null,
"e": 402,
"s": 383,
"text": "Method 1 (Simple):"
},
{
"code": null,
"e": 850,
"s": 402,
"text": "The following are simple algorithms to get union and intersection lists respectively.Intersection (list1, list2)Initialize the result list as NULL. Traverse list1 and look for every element in list2, if the element is present in list2, then add the element to the result.Union (list1, list2):Initialize a new list ans and store first and second list data to set to remove duplicate data and then store it into our new list ans and return its head."
},
{
"code": null,
"e": 854,
"s": 850,
"text": "C++"
},
{
"code": null,
"e": 856,
"s": 854,
"text": "C"
},
{
"code": null,
"e": 861,
"s": 856,
"text": "Java"
},
{
"code": null,
"e": 864,
"s": 861,
"text": "C#"
},
{
"code": null,
"e": 875,
"s": 864,
"text": "Javascript"
},
{
"code": "// C++ program to find union// and intersection of two unsorted// linked lists#include \"bits/stdc++.h\"using namespace std; /* Link list node */struct Node { int data; struct Node* next; Node(int x) { data = x; next = NULL; }}; /* A utility function to insert anode at the beginning ofa linked list*/void push(struct Node** head_ref, int new_data); /* A utility function to check ifgiven data is present in a list */bool isPresent(struct Node* head, int data); /* Function to get union of twolinked lists head1 and head2 */struct Node* getUnion(struct Node* head1, struct Node* head2){ struct Node* ans = new Node(-1); struct Node* head = ans; set<int> st; while (head1 != NULL) { st.insert(head1->data); head1 = head1->next; } while (head2 != NULL) { st.insert(head2->data); head2 = head2->next; } for (auto it : st) { struct Node* t = new Node(it); ans->next = t; ans = ans->next; } head = head->next; return head;} /* Function to get intersection oftwo linked lists head1 and head2 */struct Node* getIntersection(struct Node* head1, struct Node* head2){ struct Node* result = NULL; struct Node* t1 = head1; // Traverse list1 and search each element of it in // list2. If the element is present in list 2, then // insert the element to result while (t1 != NULL) { if (isPresent(head2, t1->data)) push(&result, t1->data); t1 = t1->next; } return result;}/* A utility function to insert anode at the beginning of a linked list*/void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* A utility function to print a linked list*/void printList(struct Node* node){ while (node != NULL) { cout << \" \" << node->data; node = node->next; }}bool isPresent(struct Node* head, int data){ struct Node* t = head; while (t != NULL) { if (t->data == data) return 1; t = t->next; } return 0;} /* Driver program to test above function*/int main(){ /* Start with the empty list */ struct Node* head1 = NULL; struct Node* head2 = NULL; struct Node* intersecn = NULL; struct Node* unin = NULL; /*create a linked lists 10->15->5->20 */ push(&head1, 20); push(&head1, 4); push(&head1, 15); push(&head1, 10); /*create a linked lists 8->4->2->10 */ push(&head2, 10); push(&head2, 2); push(&head2, 4); push(&head2, 8); intersecn = getIntersection(head1, head2); unin = getUnion(head1, head2); cout << \"\\n First list is \" << endl; printList(head1); cout << \"\\n Second list is \" << endl; printList(head2); cout << \"\\n Intersection list is \" << endl; printList(intersecn); cout << \"\\n Union list is \" << endl; printList(unin); return 0;} // This code is contributed by zishanahmad786",
"e": 4105,
"s": 875,
"text": null
},
{
"code": "// C program to find union// and intersection of two unsorted// linked lists#include <stdbool.h>#include <stdio.h>#include <stdlib.h>/* Link list node */struct Node { int data; struct Node* next;}; /* A utility function to insert a node at the beginning ofa linked list*/void push(struct Node** head_ref, int new_data); /* A utility function to check if given data is present in a list */bool isPresent(struct Node* head, int data); /* Function to get union of two linked lists head1 and head2 */struct Node* getUnion(struct Node* head1, struct Node* head2){ struct Node* result = NULL; struct Node *t1 = head1, *t2 = head2; // Insert all elements of // list1 to the result list while (t1 != NULL) { push(&result, t1->data); t1 = t1->next; } // Insert those elements of list2 // which are not present in result list while (t2 != NULL) { if (!isPresent(result, t2->data)) push(&result, t2->data); t2 = t2->next; } return result;} /* Function to get intersection of two linked lists head1 and head2 */struct Node* getIntersection(struct Node* head1, struct Node* head2){ struct Node* result = NULL; struct Node* t1 = head1; // Traverse list1 and search each element of it in // list2. If the element is present in list 2, then // insert the element to result while (t1 != NULL) { if (isPresent(head2, t1->data)) push(&result, t1->data); t1 = t1->next; } return result;} /* A utility function to insert a node at the beginning of a linked list*/void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* A utility function to print a linked list*/void printList(struct Node* node){ while (node != NULL) { printf(\"%d \", node->data); node = node->next; }} /* A utility function that returns true if data is present in linked list else return false */bool isPresent(struct Node* head, int data){ struct Node* t = head; while (t != NULL) { if (t->data == data) return 1; t = t->next; } return 0;} /* Driver program to test above function*/int main(){ /* Start with the empty list */ struct Node* head1 = NULL; struct Node* head2 = NULL; struct Node* intersecn = NULL; struct Node* unin = NULL; /*create a linked lists 10->15->5->20 */ push(&head1, 20); push(&head1, 4); push(&head1, 15); push(&head1, 10); /*create a linked lists 8->4->2->10 */ push(&head2, 10); push(&head2, 2); push(&head2, 4); push(&head2, 8); intersecn = getIntersection(head1, head2); unin = getUnion(head1, head2); printf(\"\\n First list is \\n\"); printList(head1); printf(\"\\n Second list is \\n\"); printList(head2); printf(\"\\n Intersection list is \\n\"); printList(intersecn); printf(\"\\n Union list is \\n\"); printList(unin); return 0;}",
"e": 7367,
"s": 4105,
"text": null
},
{
"code": "// Java program to find union and// intersection of two unsorted// linked listsclass LinkedList { Node head; // head of list /* Linked list Node*/ class Node { int data; Node next; Node(int d) { data = d; next = null; } } /* Function to get Union of 2 Linked Lists */ void getUnion(Node head1, Node head2) { Node t1 = head1, t2 = head2; // insert all elements of list1 in the result while (t1 != null) { push(t1.data); t1 = t1.next; } // insert those elements of list2 // that are not present while (t2 != null) { if (!isPresent(head, t2.data)) push(t2.data); t2 = t2.next; } } void getIntersection(Node head1, Node head2) { Node result = null; Node t1 = head1; // Traverse list1 and search each // element of it in list2. // If the element is present in // list 2, then insert the // element to result while (t1 != null) { if (isPresent(head2, t1.data)) push(t1.data); t1 = t1.next; } } /* Utility function to print list */ void printList() { Node temp = head; while (temp != null) { System.out.print(temp.data + \" \"); temp = temp.next; } System.out.println(); } /* Inserts a node at start of linked list */ void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* A utility function that returns true if data is present in linked list else return false */ boolean isPresent(Node head, int data) { Node t = head; while (t != null) { if (t.data == data) return true; t = t.next; } return false; } /* Driver program to test above functions */ public static void main(String args[]) { LinkedList llist1 = new LinkedList(); LinkedList llist2 = new LinkedList(); LinkedList unin = new LinkedList(); LinkedList intersecn = new LinkedList(); /*create a linked lists 10->15->4->20 */ llist1.push(20); llist1.push(4); llist1.push(15); llist1.push(10); /*create a linked lists 8->4->2->10 */ llist2.push(10); llist2.push(2); llist2.push(4); llist2.push(8); intersecn.getIntersection(llist1.head, llist2.head); unin.getUnion(llist1.head, llist2.head); System.out.println(\"First List is\"); llist1.printList(); System.out.println(\"Second List is\"); llist2.printList(); System.out.println(\"Intersection List is\"); intersecn.printList(); System.out.println(\"Union List is\"); unin.printList(); }} /* This code is contributed by Rajat Mishra */",
"e": 10522,
"s": 7367,
"text": null
},
{
"code": "// C# program to find union and// intersection of two unsorted// linked listsusing System;class LinkedList { public Node head; // head of list /* Linked list Node*/ public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } /* Function to get Union of 2 Linked Lists */ void getUnion(Node head1, Node head2) { Node t1 = head1, t2 = head2; // insert all elements of list1 in the result while (t1 != null) { push(t1.data); t1 = t1.next; } // insert those elements of list2 // that are not present while (t2 != null) { if (!isPresent(head, t2.data)) push(t2.data); t2 = t2.next; } } void getIntersection(Node head1, Node head2) { Node t1 = head1; // Traverse list1 and search each // element of it in list2. // If the element is present in // list 2, then insert the // element to result while (t1 != null) { if (isPresent(head2, t1.data)) push(t1.data); t1 = t1.next; } } /* Utility function to print list */ void printList() { Node temp = head; while (temp != null) { Console.Write(temp.data + \" \"); temp = temp.next; } Console.WriteLine(); } /* Inserts a node at start of linked list */ void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* A utility function that returns true if data is present in linked list else return false */ bool isPresent(Node head, int data) { Node t = head; while (t != null) { if (t.data == data) return true; t = t.next; } return false; } /* Driver code*/ public static void Main(string[] args) { LinkedList llist1 = new LinkedList(); LinkedList llist2 = new LinkedList(); LinkedList unin = new LinkedList(); LinkedList intersecn = new LinkedList(); /*create a linked lists 10->15->5->20 */ llist1.push(20); llist1.push(4); llist1.push(15); llist1.push(10); /*create a linked lists 8->4->2->10 */ llist2.push(10); llist2.push(2); llist2.push(4); llist2.push(8); intersecn.getIntersection(llist1.head, llist2.head); unin.getUnion(llist1.head, llist2.head); Console.WriteLine(\"First List is\"); llist1.printList(); Console.WriteLine(\"Second List is\"); llist2.printList(); Console.WriteLine(\"Intersection List is\"); intersecn.printList(); Console.WriteLine(\"Union List is\"); unin.printList(); }} // This code is contributed by rutvik_56.",
"e": 13655,
"s": 10522,
"text": null
},
{
"code": "<script> //Javascript program to find union and // intersection of two unsorted // linked lists /* Linked list Node*/ class Node { constructor(d) { this.data = d; this.next = null; } } class LinkedList{ constructor(){ this.head=null; } /* Inserts a node at start of linked list */ push(new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ var new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = this.head; /* 4. Move the head to point to new Node */ this.head = new_node; } /* A utility function that returns true if data is present in linked list else return false */ isPresent(head, data) { var t = head; while (t != null) { if (t.data == data) return true; t = t.next; } return false; } /* Function to get Union of 2 Linked Lists */ getUnion(head1, head2) { var t1 = head1, t2 = head2; // insert all elements of list1 in the result while (t1 != null) { this.push(t1.data); t1 = t1.next; } // insert those elements of list2 // that are not present while (t2 != null) { if (!this.isPresent(this.head, t2.data)) this.push(t2.data); t2 = t2.next; } } getIntersection(head1, head2) { var result = null; var t1 = head1; // Traverse list1 and search each // element of it in list2. // If the element is present in // list 2, then insert the // element to result while (t1 != null) { if (this.isPresent(head2, t1.data)) this.push(t1.data); t1 = t1.next; } } /* Utility function to print list */ printList() { var temp = this.head; while (temp != null) { document.write(temp.data + \" \"); temp = temp.next; } } } const llist1 = new LinkedList(); const llist2 = new LinkedList(); const unin = new LinkedList(); const intersecn = new LinkedList(); /*create a linked lists 10->15->4->20 */ llist1.push(20); llist1.push(4); llist1.push(15); llist1.push(10); /*create a linked lists 8->4->2->10 */ llist2.push(10); llist2.push(2); llist2.push(4); llist2.push(8); intersecn.getIntersection(llist1.head, llist2.head); unin.getUnion(llist1.head, llist2.head); document.write(\"First List is \"); llist1.printList(); document.write(\"Second List is \"); llist2.printList(); document.write(\"Intersection List is \"); intersecn.printList(); document.write(\"Union List is \"); unin.printList(); //This code is contributed by shruti456rawal</script>",
"e": 16947,
"s": 13655,
"text": null
},
{
"code": null,
"e": 17063,
"s": 16947,
"text": " First list is \n 10 15 4 20\n Second list is \n 8 4 2 10\n Intersection list is \n 4 10\n Union list is \n 2 8 20 4 15 10"
},
{
"code": null,
"e": 17086,
"s": 17063,
"text": " Complexity Analysis:"
},
{
"code": null,
"e": 17423,
"s": 17086,
"text": "Time Complexity: O(m*n).Here ‘m’ and ‘n’ are number of elements present in the first and second lists respectively. For union: For every element in list-2 we check if that element is already present in the resultant list made using list-1.For intersection: For every element in list-1 we check if that element is also present in list-2."
},
{
"code": null,
"e": 17495,
"s": 17423,
"text": "Auxiliary Space: O(1). No use of any data structure for storing values."
},
{
"code": null,
"e": 17522,
"s": 17495,
"text": "Method 2 (Use Merge Sort):"
},
{
"code": null,
"e": 17771,
"s": 17522,
"text": "In this method, algorithms for Union and Intersection are very similar. First, we sort the given lists, then we traverse the sorted lists to get union and intersection. The following are the steps to be followed to get union and intersection lists."
},
{
"code": null,
"e": 18201,
"s": 17771,
"text": "Sort the first Linked List using merge sort. This step takes O(mLogm) time. Refer this post for details of this step.Sort the second Linked List using merge sort. This step takes O(nLogn) time. Refer this post for details of this step.Linearly scan both sorted lists to get the union and intersection. This step takes O(m + n) time. This step can be implemented using the same algorithm as sorted arrays algorithm discussed here."
},
{
"code": null,
"e": 18319,
"s": 18201,
"text": "Sort the first Linked List using merge sort. This step takes O(mLogm) time. Refer this post for details of this step."
},
{
"code": null,
"e": 18438,
"s": 18319,
"text": "Sort the second Linked List using merge sort. This step takes O(nLogn) time. Refer this post for details of this step."
},
{
"code": null,
"e": 18633,
"s": 18438,
"text": "Linearly scan both sorted lists to get the union and intersection. This step takes O(m + n) time. This step can be implemented using the same algorithm as sorted arrays algorithm discussed here."
},
{
"code": null,
"e": 18737,
"s": 18633,
"text": "The time complexity of this method is O(mLogm + nLogn) which is better than method 1’s time complexity."
},
{
"code": null,
"e": 18761,
"s": 18737,
"text": "Method 3 (Use Hashing):"
},
{
"code": null,
"e": 19533,
"s": 18761,
"text": "Union (list1, list2)Initialize the result list as NULL and create an empty hash table. Traverse both lists one by one, for each element being visited, look at the element in the hash table. If the element is not present, then insert the element into the result list. If the element is present, then ignore it.Intersection (list1, list2)Initialize the result list as NULL and create an empty hash table. Traverse list1. For each element being visited in list1, insert the element in the hash table. Traverse list2, for each element being visited in list2, look the element in the hash table. If the element is present, then insert the element to the result list. If the element is not present, then ignore it.Both of the above methods assume that there are no duplicates. "
},
{
"code": null,
"e": 19538,
"s": 19533,
"text": "Java"
},
{
"code": null,
"e": 19541,
"s": 19538,
"text": "C#"
},
{
"code": "// Java code for Union and Intersection of two// Linked Listsimport java.util.HashMap;import java.util.HashSet; class LinkedList { Node head; // head of list /* Linked list Node*/ class Node { int data; Node next; Node(int d) { data = d; next = null; } } /* Utility function to print list */ void printList() { Node temp = head; while (temp != null) { System.out.print(temp.data + \" \"); temp = temp.next; } System.out.println(); } /* Inserts a node at start of linked list */ void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } public void append(int new_data) { if (this.head == null) { Node n = new Node(new_data); this.head = n; return; } Node n1 = this.head; Node n2 = new Node(new_data); while (n1.next != null) { n1 = n1.next; } n1.next = n2; n2.next = null; } /* A utility function that returns true if data is present in linked list else return false */ boolean isPresent(Node head, int data) { Node t = head; while (t != null) { if (t.data == data) return true; t = t.next; } return false; } LinkedList getIntersection(Node head1, Node head2) { HashSet<Integer> hset = new HashSet<>(); Node n1 = head1; Node n2 = head2; LinkedList result = new LinkedList(); // loop stores all the elements of list1 in hset while (n1 != null) { if (hset.contains(n1.data)) { hset.add(n1.data); } else { hset.add(n1.data); } n1 = n1.next; } // For every element of list2 present in hset // loop inserts the element into the result while (n2 != null) { if (hset.contains(n2.data)) { result.push(n2.data); } n2 = n2.next; } return result; } LinkedList getUnion(Node head1, Node head2) { // HashMap that will store the // elements of the lists with their counts HashMap<Integer, Integer> hmap = new HashMap<>(); Node n1 = head1; Node n2 = head2; LinkedList result = new LinkedList(); // loop inserts the elements and the count of // that element of list1 into the hmap while (n1 != null) { if (hmap.containsKey(n1.data)) { int val = hmap.get(n1.data); hmap.put(n1.data, val + 1); } else { hmap.put(n1.data, 1); } n1 = n1.next; } // loop further adds the elements of list2 with // their counts into the hmap while (n2 != null) { if (hmap.containsKey(n2.data)) { int val = hmap.get(n2.data); hmap.put(n2.data, val + 1); } else { hmap.put(n2.data, 1); } n2 = n2.next; } // Eventually add all the elements // into the result that are present in the hmap for (int a : hmap.keySet()) { result.append(a); } return result; } /* Driver program to test above functions */ public static void main(String args[]) { LinkedList llist1 = new LinkedList(); LinkedList llist2 = new LinkedList(); LinkedList union = new LinkedList(); LinkedList intersection = new LinkedList(); /*create a linked list 10->15->4->20 */ llist1.push(20); llist1.push(4); llist1.push(15); llist1.push(10); /*create a linked list 8->4->2->10 */ llist2.push(10); llist2.push(2); llist2.push(4); llist2.push(8); intersection = intersection.getIntersection(llist1.head, llist2.head); union = union.getUnion(llist1.head, llist2.head); System.out.println(\"First List is\"); llist1.printList(); System.out.println(\"Second List is\"); llist2.printList(); System.out.println(\"Intersection List is\"); intersection.printList(); System.out.println(\"Union List is\"); union.printList(); }}// This code is contributed by Kamal Rawal",
"e": 24228,
"s": 19541,
"text": null
},
{
"code": "// C# code for Union and Intersection of two// Linked Listsusing System;using System.Collections;using System.Collections.Generic; class LinkedList{ public Node head; // head of list /* Linked list Node*/ public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } /* Utility function to print list */ void printList() { Node temp = head; while (temp != null) { Console.Write(temp.data + \" \"); temp = temp.next; } Console.WriteLine(); } /* Inserts a node at start of linked list */ void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } public void append(int new_data) { if (this.head == null) { Node n = new Node(new_data); this.head = n; return; } Node n1 = this.head; Node n2 = new Node(new_data); while (n1.next != null) { n1 = n1.next; } n1.next = n2; n2.next = null; } /* A utility function that returns true if data is present in linked list else return false */ bool isPresent(Node head, int data) { Node t = head; while (t != null) { if (t.data == data) return true; t = t.next; } return false; } LinkedList getIntersection(Node head1, Node head2) { HashSet<int> hset = new HashSet<int>(); Node n1 = head1; Node n2 = head2; LinkedList result = new LinkedList(); // loop stores all the elements of list1 in hset while (n1 != null) { if (hset.Contains(n1.data)) { hset.Add(n1.data); } else { hset.Add(n1.data); } n1 = n1.next; } // For every element of list2 present in hset // loop inserts the element into the result while (n2 != null) { if (hset.Contains(n2.data)) { result.push(n2.data); } n2 = n2.next; } return result; } LinkedList getUnion(Node head1, Node head2) { // HashMap that will store the // elements of the lists with their counts SortedDictionary<int, int> hmap = new SortedDictionary<int, int>(); Node n1 = head1; Node n2 = head2; LinkedList result = new LinkedList(); // loop inserts the elements and the count of // that element of list1 into the hmap while (n1 != null) { if (hmap.ContainsKey(n1.data)) { hmap[n1.data]++; } else { hmap[n1.data]= 1; } n1 = n1.next; } // loop further adds the elements of list2 with // their counts into the hmap while (n2 != null) { if (hmap.ContainsKey(n2.data)) { hmap[n2.data]++; } else { hmap[n2.data]= 1; } n2 = n2.next; } // Eventually add all the elements // into the result that are present in the hmap foreach(int a in hmap.Keys) { result.append(a); } return result; } /* Driver program to test above functions */ public static void Main(string []args) { LinkedList llist1 = new LinkedList(); LinkedList llist2 = new LinkedList(); LinkedList union = new LinkedList(); LinkedList intersection = new LinkedList(); /*create a linked list 10->15->4->20 */ llist1.push(20); llist1.push(4); llist1.push(15); llist1.push(10); /*create a linked list 8->4->2->10 */ llist2.push(10); llist2.push(2); llist2.push(4); llist2.push(8); intersection = intersection.getIntersection(llist1.head, llist2.head); union = union.getUnion(llist1.head, llist2.head); Console.WriteLine(\"First List is\"); llist1.printList(); Console.WriteLine(\"Second List is\"); llist2.printList(); Console.WriteLine(\"Intersection List is\"); intersection.printList(); Console.WriteLine(\"Union List is\"); union.printList(); }} //This code is contributed by pratham76",
"e": 28852,
"s": 24228,
"text": null
},
{
"code": null,
"e": 28959,
"s": 28852,
"text": "First List is\n10 15 4 20 \nSecond List is\n8 4 2 10 \nIntersection List is\n10 4 \nUnion List is\n2 4 20 8 10 15"
},
{
"code": null,
"e": 28981,
"s": 28959,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 29370,
"s": 28981,
"text": "Time Complexity: O(m+n).Here ‘m’ and ‘n’ are number of elements present in the first and second lists respectively. For union: Traverse both the lists, store the elements in Hash-map and update the respective count.For intersection: First traverse list-1, store its elements in Hash-map and then for every element in list-2 check if it is already present in the map. This takes O(1) time."
},
{
"code": null,
"e": 29444,
"s": 29370,
"text": "Auxiliary Space:O(m+n).Use of Hash-map data structure for storing values."
},
{
"code": null,
"e": 29456,
"s": 29444,
"text": "bidibaaz123"
},
{
"code": null,
"e": 29469,
"s": 29456,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 29479,
"s": 29469,
"text": "rutvik_56"
},
{
"code": null,
"e": 29498,
"s": 29479,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 29508,
"s": 29498,
"text": "pratham76"
},
{
"code": null,
"e": 29517,
"s": 29508,
"text": "gabaa406"
},
{
"code": null,
"e": 29530,
"s": 29517,
"text": "simmytarika5"
},
{
"code": null,
"e": 29546,
"s": 29530,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 29556,
"s": 29546,
"text": "akash8900"
},
{
"code": null,
"e": 29570,
"s": 29556,
"text": "sumitgumber28"
},
{
"code": null,
"e": 29585,
"s": 29570,
"text": "zishanahmad786"
},
{
"code": null,
"e": 29600,
"s": 29585,
"text": "shruti456rawal"
},
{
"code": null,
"e": 29617,
"s": 29600,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 29638,
"s": 29617,
"text": "24*7 Innovation Labs"
},
{
"code": null,
"e": 29647,
"s": 29638,
"text": "Accolite"
},
{
"code": null,
"e": 29654,
"s": 29647,
"text": "Amazon"
},
{
"code": null,
"e": 29663,
"s": 29654,
"text": "Flipkart"
},
{
"code": null,
"e": 29675,
"s": 29663,
"text": "Komli Media"
},
{
"code": null,
"e": 29685,
"s": 29675,
"text": "Microsoft"
},
{
"code": null,
"e": 29695,
"s": 29685,
"text": "Taxi4Sure"
},
{
"code": null,
"e": 29702,
"s": 29695,
"text": "VMWare"
},
{
"code": null,
"e": 29710,
"s": 29702,
"text": "Walmart"
},
{
"code": null,
"e": 29715,
"s": 29710,
"text": "Hash"
},
{
"code": null,
"e": 29727,
"s": 29715,
"text": "Linked List"
},
{
"code": null,
"e": 29735,
"s": 29727,
"text": "Sorting"
},
{
"code": null,
"e": 29742,
"s": 29735,
"text": "VMWare"
},
{
"code": null,
"e": 29751,
"s": 29742,
"text": "Flipkart"
},
{
"code": null,
"e": 29760,
"s": 29751,
"text": "Accolite"
},
{
"code": null,
"e": 29767,
"s": 29760,
"text": "Amazon"
},
{
"code": null,
"e": 29777,
"s": 29767,
"text": "Microsoft"
},
{
"code": null,
"e": 29798,
"s": 29777,
"text": "24*7 Innovation Labs"
},
{
"code": null,
"e": 29806,
"s": 29798,
"text": "Walmart"
},
{
"code": null,
"e": 29818,
"s": 29806,
"text": "Komli Media"
},
{
"code": null,
"e": 29828,
"s": 29818,
"text": "Taxi4Sure"
},
{
"code": null,
"e": 29840,
"s": 29828,
"text": "Linked List"
},
{
"code": null,
"e": 29845,
"s": 29840,
"text": "Hash"
},
{
"code": null,
"e": 29853,
"s": 29845,
"text": "Sorting"
}
]
|
NumPy – Filtering rows by multiple conditions | 05 Aug, 2021
In this article, we will discuss how to filter rows of NumPy array by multiple conditions. Before jumping into filtering rows by multiple conditions, let us first see how can we apply filter based on one condition. There are basically two approaches to do so:
Method 1: Using mask array
The mask function filters out the numbers from array arr which are at the indices of false in mask array. The developer can set the mask array as per their requirement–it becomes very helpful when its is tough to form a logic of filtering.
Approach
Import module
Make initial array
Define mask
Make a new array based on the mask
Print new array
Program:
Python3
# importing numpy libimport numpy as np # making a numpy arrayarr = np.array([x for x in range(11, 20)]) print("Original array")print(arr) # defining maskmask = [True, False, True, False, True, True, False, False, False] # making new array on conditionsnew_arr = arr[mask] print("New array")print(new_arr)
Output
Original array
[11 12 13 14 15 16 17 18 19]
New array
[11 13 15 16]
Method 2: Using iterative method
Rather than using masks, the developer iterates the array arr and apply condition on each of the array element.
Approach
Import module
Create array
Create an empty array
Iterate through array
Select items based on some condition
Add selected items to the empty array
Display array
Program:
Python3
# importing numpy libimport numpy as np # making a numpy arrayarr = np.array([x for x in range(11, 20)]) print("Original array")print(arr) # making a blank listnew_arr = [] for x in arr: # applying condition: appending even numbers if x % 2 == 0: new_arr.append(x) # Converting new list into numpy arraynew_arr = np.array(new_arr)print("New array")print(new_arr)
Output
Original array
[11 12 13 14 15 16 17 18 19]
New array
[12 14 16 18]
Now let’s try to apply multiple conditions on the NumPy array
Method 1: Using mask
Approach
Import module
Create initial array
Define mask based on multiple conditions
Add values to the new array according to the mask
Display array
Example
Python3
# importing numpy libimport numpy as np # making a numpy arrayarr = np.array([x for x in range(11, 40)]) print("Original array")print(arr) # defining mask based on two conditions:# array element must be greater than 15# and must be a divisible by 2mask = (arr > 15) & (arr % 2 == 0) # making new array on conditionsnew_arr = arr[mask]print("New array")print(new_arr)
Output
Original array
[11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
35 36 37 38 39]
New array
[16 18 20 22 24 26 28 30 32 34 36 38]
Method 2: Iterative method
Approach
Import module
Create initial array
Create an empty array
Iterate through the array
Select items based on multiple conditions
Add selected items to the empty list
Display array
Example
Python3
# importing numpy libimport numpy as np # making a numpy arrayarr = np.array([x for x in range(11, 40)]) print("Original array")print(arr) # making a blank listnew_arr = [] for x in arr: # applying two conditions: number is divisible by 2 and is greater than 15 if x % 2 == 0 and x > 15: new_arr.append(x) # Converting new list into numpy arraynew_arr = np.array(new_arr)print("New array")print(new_arr)
Output
Original array
[11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
35 36 37 38 39]
New array
[16 18 20 22 24 26 28 30 32 34 36 38]
Method 3: Using lambda
Approach
Import module
Create initial array
Apply multiple conditions using lambda function
Select items accordingly
Add items to a new array
Display array
Example
Python3
# importing numpy libimport numpy as np # making a numpy arrayarr = np.array([x for x in range(11, 40)]) print("Original array")print(arr) # using lambda to apply conditionnew_arr = list(filter(lambda x: x > 15 and x % 2 == 0 and x % 10 != 0, arr)) # Converting new list into numpy arraynew_arr = np.array(new_arr)print("New array")print(new_arr)
Output
Original array
[11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
35 36 37 38 39]
New array
[16 18 22 24 26 28 32 34 36 38]
sagar0719kumar
arorakashish0911
Picked
Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Aug, 2021"
},
{
"code": null,
"e": 288,
"s": 28,
"text": "In this article, we will discuss how to filter rows of NumPy array by multiple conditions. Before jumping into filtering rows by multiple conditions, let us first see how can we apply filter based on one condition. There are basically two approaches to do so:"
},
{
"code": null,
"e": 315,
"s": 288,
"text": "Method 1: Using mask array"
},
{
"code": null,
"e": 555,
"s": 315,
"text": "The mask function filters out the numbers from array arr which are at the indices of false in mask array. The developer can set the mask array as per their requirement–it becomes very helpful when its is tough to form a logic of filtering."
},
{
"code": null,
"e": 564,
"s": 555,
"text": "Approach"
},
{
"code": null,
"e": 578,
"s": 564,
"text": "Import module"
},
{
"code": null,
"e": 597,
"s": 578,
"text": "Make initial array"
},
{
"code": null,
"e": 609,
"s": 597,
"text": "Define mask"
},
{
"code": null,
"e": 644,
"s": 609,
"text": "Make a new array based on the mask"
},
{
"code": null,
"e": 660,
"s": 644,
"text": "Print new array"
},
{
"code": null,
"e": 669,
"s": 660,
"text": "Program:"
},
{
"code": null,
"e": 677,
"s": 669,
"text": "Python3"
},
{
"code": "# importing numpy libimport numpy as np # making a numpy arrayarr = np.array([x for x in range(11, 20)]) print(\"Original array\")print(arr) # defining maskmask = [True, False, True, False, True, True, False, False, False] # making new array on conditionsnew_arr = arr[mask] print(\"New array\")print(new_arr)",
"e": 983,
"s": 677,
"text": null
},
{
"code": null,
"e": 990,
"s": 983,
"text": "Output"
},
{
"code": null,
"e": 1005,
"s": 990,
"text": "Original array"
},
{
"code": null,
"e": 1034,
"s": 1005,
"text": "[11 12 13 14 15 16 17 18 19]"
},
{
"code": null,
"e": 1044,
"s": 1034,
"text": "New array"
},
{
"code": null,
"e": 1058,
"s": 1044,
"text": "[11 13 15 16]"
},
{
"code": null,
"e": 1091,
"s": 1058,
"text": "Method 2: Using iterative method"
},
{
"code": null,
"e": 1204,
"s": 1091,
"text": "Rather than using masks, the developer iterates the array arr and apply condition on each of the array element. "
},
{
"code": null,
"e": 1213,
"s": 1204,
"text": "Approach"
},
{
"code": null,
"e": 1227,
"s": 1213,
"text": "Import module"
},
{
"code": null,
"e": 1240,
"s": 1227,
"text": "Create array"
},
{
"code": null,
"e": 1262,
"s": 1240,
"text": "Create an empty array"
},
{
"code": null,
"e": 1284,
"s": 1262,
"text": "Iterate through array"
},
{
"code": null,
"e": 1321,
"s": 1284,
"text": "Select items based on some condition"
},
{
"code": null,
"e": 1359,
"s": 1321,
"text": "Add selected items to the empty array"
},
{
"code": null,
"e": 1373,
"s": 1359,
"text": "Display array"
},
{
"code": null,
"e": 1382,
"s": 1373,
"text": "Program:"
},
{
"code": null,
"e": 1390,
"s": 1382,
"text": "Python3"
},
{
"code": "# importing numpy libimport numpy as np # making a numpy arrayarr = np.array([x for x in range(11, 20)]) print(\"Original array\")print(arr) # making a blank listnew_arr = [] for x in arr: # applying condition: appending even numbers if x % 2 == 0: new_arr.append(x) # Converting new list into numpy arraynew_arr = np.array(new_arr)print(\"New array\")print(new_arr)",
"e": 1764,
"s": 1390,
"text": null
},
{
"code": null,
"e": 1771,
"s": 1764,
"text": "Output"
},
{
"code": null,
"e": 1786,
"s": 1771,
"text": "Original array"
},
{
"code": null,
"e": 1815,
"s": 1786,
"text": "[11 12 13 14 15 16 17 18 19]"
},
{
"code": null,
"e": 1825,
"s": 1815,
"text": "New array"
},
{
"code": null,
"e": 1839,
"s": 1825,
"text": "[12 14 16 18]"
},
{
"code": null,
"e": 1901,
"s": 1839,
"text": "Now let’s try to apply multiple conditions on the NumPy array"
},
{
"code": null,
"e": 1922,
"s": 1901,
"text": "Method 1: Using mask"
},
{
"code": null,
"e": 1931,
"s": 1922,
"text": "Approach"
},
{
"code": null,
"e": 1945,
"s": 1931,
"text": "Import module"
},
{
"code": null,
"e": 1966,
"s": 1945,
"text": "Create initial array"
},
{
"code": null,
"e": 2007,
"s": 1966,
"text": "Define mask based on multiple conditions"
},
{
"code": null,
"e": 2057,
"s": 2007,
"text": "Add values to the new array according to the mask"
},
{
"code": null,
"e": 2071,
"s": 2057,
"text": "Display array"
},
{
"code": null,
"e": 2079,
"s": 2071,
"text": "Example"
},
{
"code": null,
"e": 2087,
"s": 2079,
"text": "Python3"
},
{
"code": "# importing numpy libimport numpy as np # making a numpy arrayarr = np.array([x for x in range(11, 40)]) print(\"Original array\")print(arr) # defining mask based on two conditions:# array element must be greater than 15# and must be a divisible by 2mask = (arr > 15) & (arr % 2 == 0) # making new array on conditionsnew_arr = arr[mask]print(\"New array\")print(new_arr)",
"e": 2454,
"s": 2087,
"text": null
},
{
"code": null,
"e": 2461,
"s": 2454,
"text": "Output"
},
{
"code": null,
"e": 2476,
"s": 2461,
"text": "Original array"
},
{
"code": null,
"e": 2549,
"s": 2476,
"text": "[11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34"
},
{
"code": null,
"e": 2565,
"s": 2549,
"text": "35 36 37 38 39]"
},
{
"code": null,
"e": 2575,
"s": 2565,
"text": "New array"
},
{
"code": null,
"e": 2613,
"s": 2575,
"text": "[16 18 20 22 24 26 28 30 32 34 36 38]"
},
{
"code": null,
"e": 2640,
"s": 2613,
"text": "Method 2: Iterative method"
},
{
"code": null,
"e": 2649,
"s": 2640,
"text": "Approach"
},
{
"code": null,
"e": 2663,
"s": 2649,
"text": "Import module"
},
{
"code": null,
"e": 2684,
"s": 2663,
"text": "Create initial array"
},
{
"code": null,
"e": 2706,
"s": 2684,
"text": "Create an empty array"
},
{
"code": null,
"e": 2732,
"s": 2706,
"text": "Iterate through the array"
},
{
"code": null,
"e": 2774,
"s": 2732,
"text": "Select items based on multiple conditions"
},
{
"code": null,
"e": 2811,
"s": 2774,
"text": "Add selected items to the empty list"
},
{
"code": null,
"e": 2825,
"s": 2811,
"text": "Display array"
},
{
"code": null,
"e": 2833,
"s": 2825,
"text": "Example"
},
{
"code": null,
"e": 2841,
"s": 2833,
"text": "Python3"
},
{
"code": "# importing numpy libimport numpy as np # making a numpy arrayarr = np.array([x for x in range(11, 40)]) print(\"Original array\")print(arr) # making a blank listnew_arr = [] for x in arr: # applying two conditions: number is divisible by 2 and is greater than 15 if x % 2 == 0 and x > 15: new_arr.append(x) # Converting new list into numpy arraynew_arr = np.array(new_arr)print(\"New array\")print(new_arr)",
"e": 3258,
"s": 2841,
"text": null
},
{
"code": null,
"e": 3265,
"s": 3258,
"text": "Output"
},
{
"code": null,
"e": 3280,
"s": 3265,
"text": "Original array"
},
{
"code": null,
"e": 3353,
"s": 3280,
"text": "[11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34"
},
{
"code": null,
"e": 3369,
"s": 3353,
"text": "35 36 37 38 39]"
},
{
"code": null,
"e": 3379,
"s": 3369,
"text": "New array"
},
{
"code": null,
"e": 3417,
"s": 3379,
"text": "[16 18 20 22 24 26 28 30 32 34 36 38]"
},
{
"code": null,
"e": 3440,
"s": 3417,
"text": "Method 3: Using lambda"
},
{
"code": null,
"e": 3449,
"s": 3440,
"text": "Approach"
},
{
"code": null,
"e": 3463,
"s": 3449,
"text": "Import module"
},
{
"code": null,
"e": 3484,
"s": 3463,
"text": "Create initial array"
},
{
"code": null,
"e": 3532,
"s": 3484,
"text": "Apply multiple conditions using lambda function"
},
{
"code": null,
"e": 3557,
"s": 3532,
"text": "Select items accordingly"
},
{
"code": null,
"e": 3582,
"s": 3557,
"text": "Add items to a new array"
},
{
"code": null,
"e": 3596,
"s": 3582,
"text": "Display array"
},
{
"code": null,
"e": 3604,
"s": 3596,
"text": "Example"
},
{
"code": null,
"e": 3612,
"s": 3604,
"text": "Python3"
},
{
"code": "# importing numpy libimport numpy as np # making a numpy arrayarr = np.array([x for x in range(11, 40)]) print(\"Original array\")print(arr) # using lambda to apply conditionnew_arr = list(filter(lambda x: x > 15 and x % 2 == 0 and x % 10 != 0, arr)) # Converting new list into numpy arraynew_arr = np.array(new_arr)print(\"New array\")print(new_arr)",
"e": 3959,
"s": 3612,
"text": null
},
{
"code": null,
"e": 3966,
"s": 3959,
"text": "Output"
},
{
"code": null,
"e": 3981,
"s": 3966,
"text": "Original array"
},
{
"code": null,
"e": 4054,
"s": 3981,
"text": "[11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34"
},
{
"code": null,
"e": 4070,
"s": 4054,
"text": "35 36 37 38 39]"
},
{
"code": null,
"e": 4080,
"s": 4070,
"text": "New array"
},
{
"code": null,
"e": 4112,
"s": 4080,
"text": "[16 18 22 24 26 28 32 34 36 38]"
},
{
"code": null,
"e": 4127,
"s": 4112,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 4144,
"s": 4127,
"text": "arorakashish0911"
},
{
"code": null,
"e": 4151,
"s": 4144,
"text": "Picked"
},
{
"code": null,
"e": 4182,
"s": 4151,
"text": "Python numpy-arrayManipulation"
},
{
"code": null,
"e": 4195,
"s": 4182,
"text": "Python-numpy"
},
{
"code": null,
"e": 4202,
"s": 4195,
"text": "Python"
}
]
|
Python – Specific Characters Frequency in String List | 05 Sep, 2020
Given String list, extract frequency of specific characters in whole strings list.
Input : test_list = [“geeksforgeeks is best for geeks”], chr_list = [‘e’, ‘b’, ‘g’, ‘f’]Output : {‘g’: 3, ‘e’: 7, ‘b’: 1, ‘f’ : 1}Explanation : Frequency of certain characters extracted.
Input : test_list = [“geeksforgeeks], chr_list = [‘e’, ‘g’]Output : {‘g’: 2, ‘e’: 4}Explanation : Frequency of certain characters extracted.
Method #1 : Using join() + Counter()
In this, we concatenate all the strings, and then Counter() performs task of getting all frequencies. Last step is to get only specific characters from List in dictionary using dictionary comprehension.
Python3
# Python3 code to demonstrate working of # Specific Characters Frequency in String List# Using join() + Counter()from collections import Counter # initializing liststest_list = ["geeksforgeeks is best for geeks"] # printing original listprint("The original list : " + str(test_list)) # char list chr_list = ['e', 'b', 'g'] # dict comprehension to retrieve on certain Frequenciesres = {key:val for key, val in dict(Counter("".join(test_list))).items() if key in chr_list} # printing result print("Specific Characters Frequencies : " + str(res))
The original list : ['geeksforgeeks is best for geeks']
Specific Characters Frequencies : {'g': 3, 'e': 7, 'b': 1}
Method #2 : Using chain.from_iterable() + Counter() + dictionary comprehension
In this, task of concatenation is done using chain.from_iterable() rather than join(). Rest all tasks are done as above method.
Python3
# Python3 code to demonstrate working of # Specific Characters Frequency in String List# Using chain.from_iterable() + Counter() + dictionary comprehensionfrom collections import Counterfrom itertools import chain # initializing liststest_list = ["geeksforgeeks is best for geeks"] # printing original listprint("The original list : " + str(test_list)) # char list chr_list = ['e', 'b', 'g'] # dict comprehension to retrieve on certain Frequencies# from_iterable to flatten / joinres = {key:val for key, val in dict(Counter(chain.from_iterable(test_list))).items() if key in chr_list} # printing result print("Specific Characters Frequencies : " + str(res))
The original list : ['geeksforgeeks is best for geeks']
Specific Characters Frequencies : {'g': 3, 'e': 7, 'b': 1}
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n05 Sep, 2020"
},
{
"code": null,
"e": 135,
"s": 52,
"text": "Given String list, extract frequency of specific characters in whole strings list."
},
{
"code": null,
"e": 322,
"s": 135,
"text": "Input : test_list = [“geeksforgeeks is best for geeks”], chr_list = [‘e’, ‘b’, ‘g’, ‘f’]Output : {‘g’: 3, ‘e’: 7, ‘b’: 1, ‘f’ : 1}Explanation : Frequency of certain characters extracted."
},
{
"code": null,
"e": 463,
"s": 322,
"text": "Input : test_list = [“geeksforgeeks], chr_list = [‘e’, ‘g’]Output : {‘g’: 2, ‘e’: 4}Explanation : Frequency of certain characters extracted."
},
{
"code": null,
"e": 500,
"s": 463,
"text": "Method #1 : Using join() + Counter()"
},
{
"code": null,
"e": 703,
"s": 500,
"text": "In this, we concatenate all the strings, and then Counter() performs task of getting all frequencies. Last step is to get only specific characters from List in dictionary using dictionary comprehension."
},
{
"code": null,
"e": 711,
"s": 703,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Specific Characters Frequency in String List# Using join() + Counter()from collections import Counter # initializing liststest_list = [\"geeksforgeeks is best for geeks\"] # printing original listprint(\"The original list : \" + str(test_list)) # char list chr_list = ['e', 'b', 'g'] # dict comprehension to retrieve on certain Frequenciesres = {key:val for key, val in dict(Counter(\"\".join(test_list))).items() if key in chr_list} # printing result print(\"Specific Characters Frequencies : \" + str(res))",
"e": 1264,
"s": 711,
"text": null
},
{
"code": null,
"e": 1380,
"s": 1264,
"text": "The original list : ['geeksforgeeks is best for geeks']\nSpecific Characters Frequencies : {'g': 3, 'e': 7, 'b': 1}\n"
},
{
"code": null,
"e": 1459,
"s": 1380,
"text": "Method #2 : Using chain.from_iterable() + Counter() + dictionary comprehension"
},
{
"code": null,
"e": 1587,
"s": 1459,
"text": "In this, task of concatenation is done using chain.from_iterable() rather than join(). Rest all tasks are done as above method."
},
{
"code": null,
"e": 1595,
"s": 1587,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Specific Characters Frequency in String List# Using chain.from_iterable() + Counter() + dictionary comprehensionfrom collections import Counterfrom itertools import chain # initializing liststest_list = [\"geeksforgeeks is best for geeks\"] # printing original listprint(\"The original list : \" + str(test_list)) # char list chr_list = ['e', 'b', 'g'] # dict comprehension to retrieve on certain Frequencies# from_iterable to flatten / joinres = {key:val for key, val in dict(Counter(chain.from_iterable(test_list))).items() if key in chr_list} # printing result print(\"Specific Characters Frequencies : \" + str(res))",
"e": 2262,
"s": 1595,
"text": null
},
{
"code": null,
"e": 2378,
"s": 2262,
"text": "The original list : ['geeksforgeeks is best for geeks']\nSpecific Characters Frequencies : {'g': 3, 'e': 7, 'b': 1}\n"
},
{
"code": null,
"e": 2401,
"s": 2378,
"text": "Python string-programs"
},
{
"code": null,
"e": 2408,
"s": 2401,
"text": "Python"
},
{
"code": null,
"e": 2424,
"s": 2408,
"text": "Python Programs"
}
]
|
Program to print factors of a number in pairs | 12 Apr, 2021
Given a number n, the task of the programmer is to print the factors of the number in such a way that they occur in pairs. A pair signifies that the product of the pair should result in the number itself;Examples:
Input : 24
Output : 1*24
2*12
3*8
4*6
Input : 50
Output : 1*50
2*25
5*10
The simplest approach for this program is that we run a loop from 1 to the square root of N and print and print ‘i’ and ‘N%i’ if the number N is dividing ‘i’. The mathematical reason why we run the loop till square root of N is given below:If a*b = N where 1 < a ≤ b < N N = ab ≥ a^2 ⇔ a^2 ≤ N ⇔ a ≤ √N
C++
Java
C#
Python 3
PHP
Javascript
// CPP program to print prime factors in// pairs.#include <iostream>using namespace std; void printPFsInPairs(int n){ for (int i = 1; i * i <= n; i++) if (n % i == 0) cout << i << "*" << n / i << endl;} // Driver codeint main(){ int n = 24; printPFsInPairs(n); return 0;}
// Java program to print prime factors in// pairs.public class GEE { static void printPFsInPairs(int n) { for (int i = 1; i * i <= n; i++) if (n % i == 0) System.out.println(i + "*" + n / i); } // Driver code public static void main(String[] args) { int n = 24; printPFsInPairs(n); }}
// C# program to print prime factors in// pairs.using System;public class GEE { static void printPFsInPairs(int n) { for (int i = 1; i * i <= n; i++) if (n % i == 0) Console.Write(i + "*" + n / i + "\n"); } // Driver code public static void Main() { int n = 24; printPFsInPairs(n); }}
# Python 3 program to print prime factors in# pairs. def printPFsInPairs(n): for i in range(1, int(pow(n, 1 / 2))+1): if n % i == 0: print(str(i) +"*"+str(int(n / i))) # Driver coden = 24printPFsInPairs(n)
<?php// PHP program to print prime factors in// pairs. function printPFsInPairs($n){ for ($i = 1; $i*$i <= $n; $i++) if ($n % $i == 0) echo $i."*". $n / $i ."\n"; } // Driver code$n = 24;printPFsInPairs($n);return 0;?>
<script> // Javascript program to print prime factors in// pairs. function printPFsInPairs(n){ for (let i = 1; i * i <= n; i++) if (n % i == 0) document.write(i + "*" + parseInt(n / i) + "<br>");} // Driver codelet n = 24;printPFsInPairs(n); </script>
1*24
2*12
3*8
4*6
ukasp
subham348
prime-factor
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Merge two sorted arrays with O(1) extra space
Program to print prime numbers from 1 to N.
Sum of the series (1*2) + (2*3) + (3*4) + ...... upto n terms
Segment Tree | Set 1 (Sum of given range)
Count ways to reach the n'th stair
Check if a number is Palindrome
Median of two sorted arrays of same size
Product of Array except itself
Fizz Buzz Implementation | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Apr, 2021"
},
{
"code": null,
"e": 244,
"s": 28,
"text": "Given a number n, the task of the programmer is to print the factors of the number in such a way that they occur in pairs. A pair signifies that the product of the pair should result in the number itself;Examples: "
},
{
"code": null,
"e": 363,
"s": 244,
"text": "Input : 24\nOutput : 1*24\n 2*12\n 3*8\n 4*6\n\nInput : 50\nOutput : 1*50\n 2*25\n 5*10"
},
{
"code": null,
"e": 669,
"s": 365,
"text": "The simplest approach for this program is that we run a loop from 1 to the square root of N and print and print ‘i’ and ‘N%i’ if the number N is dividing ‘i’. The mathematical reason why we run the loop till square root of N is given below:If a*b = N where 1 < a ≤ b < N N = ab ≥ a^2 ⇔ a^2 ≤ N ⇔ a ≤ √N "
},
{
"code": null,
"e": 673,
"s": 669,
"text": "C++"
},
{
"code": null,
"e": 678,
"s": 673,
"text": "Java"
},
{
"code": null,
"e": 681,
"s": 678,
"text": "C#"
},
{
"code": null,
"e": 690,
"s": 681,
"text": "Python 3"
},
{
"code": null,
"e": 694,
"s": 690,
"text": "PHP"
},
{
"code": null,
"e": 705,
"s": 694,
"text": "Javascript"
},
{
"code": "// CPP program to print prime factors in// pairs.#include <iostream>using namespace std; void printPFsInPairs(int n){ for (int i = 1; i * i <= n; i++) if (n % i == 0) cout << i << \"*\" << n / i << endl;} // Driver codeint main(){ int n = 24; printPFsInPairs(n); return 0;}",
"e": 1007,
"s": 705,
"text": null
},
{
"code": "// Java program to print prime factors in// pairs.public class GEE { static void printPFsInPairs(int n) { for (int i = 1; i * i <= n; i++) if (n % i == 0) System.out.println(i + \"*\" + n / i); } // Driver code public static void main(String[] args) { int n = 24; printPFsInPairs(n); }}",
"e": 1363,
"s": 1007,
"text": null
},
{
"code": "// C# program to print prime factors in// pairs.using System;public class GEE { static void printPFsInPairs(int n) { for (int i = 1; i * i <= n; i++) if (n % i == 0) Console.Write(i + \"*\" + n / i + \"\\n\"); } // Driver code public static void Main() { int n = 24; printPFsInPairs(n); }}",
"e": 1719,
"s": 1363,
"text": null
},
{
"code": "# Python 3 program to print prime factors in# pairs. def printPFsInPairs(n): for i in range(1, int(pow(n, 1 / 2))+1): if n % i == 0: print(str(i) +\"*\"+str(int(n / i))) # Driver coden = 24printPFsInPairs(n)",
"e": 1950,
"s": 1719,
"text": null
},
{
"code": "<?php// PHP program to print prime factors in// pairs. function printPFsInPairs($n){ for ($i = 1; $i*$i <= $n; $i++) if ($n % $i == 0) echo $i.\"*\". $n / $i .\"\\n\"; } // Driver code$n = 24;printPFsInPairs($n);return 0;?>",
"e": 2194,
"s": 1950,
"text": null
},
{
"code": "<script> // Javascript program to print prime factors in// pairs. function printPFsInPairs(n){ for (let i = 1; i * i <= n; i++) if (n % i == 0) document.write(i + \"*\" + parseInt(n / i) + \"<br>\");} // Driver codelet n = 24;printPFsInPairs(n); </script>",
"e": 2467,
"s": 2194,
"text": null
},
{
"code": null,
"e": 2485,
"s": 2467,
"text": "1*24\n2*12\n3*8\n4*6"
},
{
"code": null,
"e": 2493,
"s": 2487,
"text": "ukasp"
},
{
"code": null,
"e": 2503,
"s": 2493,
"text": "subham348"
},
{
"code": null,
"e": 2516,
"s": 2503,
"text": "prime-factor"
},
{
"code": null,
"e": 2529,
"s": 2516,
"text": "Mathematical"
},
{
"code": null,
"e": 2542,
"s": 2529,
"text": "Mathematical"
},
{
"code": null,
"e": 2640,
"s": 2542,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2672,
"s": 2640,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 2718,
"s": 2672,
"text": "Merge two sorted arrays with O(1) extra space"
},
{
"code": null,
"e": 2762,
"s": 2718,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 2824,
"s": 2762,
"text": "Sum of the series (1*2) + (2*3) + (3*4) + ...... upto n terms"
},
{
"code": null,
"e": 2866,
"s": 2824,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 2901,
"s": 2866,
"text": "Count ways to reach the n'th stair"
},
{
"code": null,
"e": 2933,
"s": 2901,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 2974,
"s": 2933,
"text": "Median of two sorted arrays of same size"
},
{
"code": null,
"e": 3005,
"s": 2974,
"text": "Product of Array except itself"
}
]
|
Flutter – Working with Callback Functions | 21 Jun, 2022
In this article, we will see how we can use callback functions in flutter. We will learn about different methods to implement callback functions in flutter. Callback is basically a function or a method that we pass as an argument into another function or a method to perform an action. In the simplest words, we can say that Callback or VoidCallback are used while sending data from one method to another and vice-versa. It is very important to maintain a continuous flow of data throughout the flutter app.
Let’s assume that you are working on an app. This app displays some sort of data. Now to alter the values in the application, there are 2 approaches that you can take, either change the state using various state-altering techniques or change the value using a Callback. If we are to work with the Callback function there are 2 possible methods that we can use as shown below:
In this approach, we just define the function that is supposed to trigger a callback when a specific event occurs.
Example:
Dart
import 'package:flutter/material.dart'; // function to trigger the app build processvoid main() { runApp(MaterialApp( home: Scaffold( // appbar appBar: AppBar( title: const Text('GeeksForGeeks'), backgroundColor: const Color.fromRGBO(15, 157, 88, 1), ), body: const MyApp(), ), ));} class MyApp extends StatefulWidget { const MyApp({Key? key}) : super(key: key); @override // ignore: library_private_types_in_public_api _MyAppState createState() => _MyAppState();} class _MyAppState extends State<MyApp> { int count = 0; @override Widget build(BuildContext context) { return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( '$count', style: const TextStyle(fontSize: 50.0), ), ElevatedButton( style: ButtonStyle( backgroundColor: MaterialStateProperty.all(Colors.green)), onPressed: () { setState(() { count++; }); }, child: const Text('' 'increase'), ), // RaisedButton is deprecated and shouldn't be used. // Use ElevatedButton insetad. // RaisedButton( // // callback function // // this increments the value // // by 1 each time the Raised button is pressed // onPressed: () { // setState(() { // count++; // }); // }, // child: const Text('' // 'increase'), // ) ], ), ); }}
Output:
In this approach, the callback is directly passed to the event. As shown in the below example, the onPressed action makes the direct callback function defined in the earlier part of the code.
Example:
Dart
import 'package:flutter/material.dart'; void main() { runApp(MaterialApp( home: Scaffold( // appbar appBar: AppBar( title: const Text('GeeksForGeeks'), backgroundColor: const Color.fromRGBO(15, 157, 88, 1), ), body: const MyApp(), ), ));} class MyApp extends StatefulWidget { const MyApp({Key? key}) : super(key: key); @override // ignore: library_private_types_in_public_api _MyAppState createState() => _MyAppState();} class _MyAppState extends State<MyApp> { int count = 0; // callback function callBack() { setState(() { count++; }); } @override Widget build(BuildContext context) { return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( '$count', style: const TextStyle(fontSize: 50.0), ), ElevatedButton( style: ButtonStyle( backgroundColor: MaterialStateProperty.all(Colors.green)), onPressed: callBack, child: const Text('increase'), ), // RaisedButton is deprecated and shouldn't be used. // Use ElevatedButton insetad. // RaisedButton( // // callback on Button press // onPressed: callBack, // child: Text('' // 'increase'), // ) ], ), ); }}
Output:
ankit_kumar_
android
Flutter
Picked
Dart
Flutter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n21 Jun, 2022"
},
{
"code": null,
"e": 562,
"s": 54,
"text": "In this article, we will see how we can use callback functions in flutter. We will learn about different methods to implement callback functions in flutter. Callback is basically a function or a method that we pass as an argument into another function or a method to perform an action. In the simplest words, we can say that Callback or VoidCallback are used while sending data from one method to another and vice-versa. It is very important to maintain a continuous flow of data throughout the flutter app."
},
{
"code": null,
"e": 940,
"s": 562,
"text": "Let’s assume that you are working on an app. This app displays some sort of data. Now to alter the values in the application, there are 2 approaches that you can take, either change the state using various state-altering techniques or change the value using a Callback. If we are to work with the Callback function there are 2 possible methods that we can use as shown below:"
},
{
"code": null,
"e": 1055,
"s": 940,
"text": "In this approach, we just define the function that is supposed to trigger a callback when a specific event occurs."
},
{
"code": null,
"e": 1064,
"s": 1055,
"text": "Example:"
},
{
"code": null,
"e": 1069,
"s": 1064,
"text": "Dart"
},
{
"code": "import 'package:flutter/material.dart'; // function to trigger the app build processvoid main() { runApp(MaterialApp( home: Scaffold( // appbar appBar: AppBar( title: const Text('GeeksForGeeks'), backgroundColor: const Color.fromRGBO(15, 157, 88, 1), ), body: const MyApp(), ), ));} class MyApp extends StatefulWidget { const MyApp({Key? key}) : super(key: key); @override // ignore: library_private_types_in_public_api _MyAppState createState() => _MyAppState();} class _MyAppState extends State<MyApp> { int count = 0; @override Widget build(BuildContext context) { return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( '$count', style: const TextStyle(fontSize: 50.0), ), ElevatedButton( style: ButtonStyle( backgroundColor: MaterialStateProperty.all(Colors.green)), onPressed: () { setState(() { count++; }); }, child: const Text('' 'increase'), ), // RaisedButton is deprecated and shouldn't be used. // Use ElevatedButton insetad. // RaisedButton( // // callback function // // this increments the value // // by 1 each time the Raised button is pressed // onPressed: () { // setState(() { // count++; // }); // }, // child: const Text('' // 'increase'), // ) ], ), ); }}",
"e": 2717,
"s": 1069,
"text": null
},
{
"code": null,
"e": 2725,
"s": 2717,
"text": "Output:"
},
{
"code": null,
"e": 2919,
"s": 2725,
"text": "In this approach, the callback is directly passed to the event. As shown in the below example, the onPressed action makes the direct callback function defined in the earlier part of the code. "
},
{
"code": null,
"e": 2929,
"s": 2919,
"text": "Example: "
},
{
"code": null,
"e": 2934,
"s": 2929,
"text": "Dart"
},
{
"code": "import 'package:flutter/material.dart'; void main() { runApp(MaterialApp( home: Scaffold( // appbar appBar: AppBar( title: const Text('GeeksForGeeks'), backgroundColor: const Color.fromRGBO(15, 157, 88, 1), ), body: const MyApp(), ), ));} class MyApp extends StatefulWidget { const MyApp({Key? key}) : super(key: key); @override // ignore: library_private_types_in_public_api _MyAppState createState() => _MyAppState();} class _MyAppState extends State<MyApp> { int count = 0; // callback function callBack() { setState(() { count++; }); } @override Widget build(BuildContext context) { return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( '$count', style: const TextStyle(fontSize: 50.0), ), ElevatedButton( style: ButtonStyle( backgroundColor: MaterialStateProperty.all(Colors.green)), onPressed: callBack, child: const Text('increase'), ), // RaisedButton is deprecated and shouldn't be used. // Use ElevatedButton insetad. // RaisedButton( // // callback on Button press // onPressed: callBack, // child: Text('' // 'increase'), // ) ], ), ); }}",
"e": 4320,
"s": 2934,
"text": null
},
{
"code": null,
"e": 4328,
"s": 4320,
"text": "Output:"
},
{
"code": null,
"e": 4341,
"s": 4328,
"text": "ankit_kumar_"
},
{
"code": null,
"e": 4349,
"s": 4341,
"text": "android"
},
{
"code": null,
"e": 4357,
"s": 4349,
"text": "Flutter"
},
{
"code": null,
"e": 4364,
"s": 4357,
"text": "Picked"
},
{
"code": null,
"e": 4369,
"s": 4364,
"text": "Dart"
},
{
"code": null,
"e": 4377,
"s": 4369,
"text": "Flutter"
}
]
|
Remove spaces from a given string | 27 Jun, 2022
Given a string, remove all spaces from the string and return it.
Input: "g eeks for ge eeks "
Output: "geeksforgeeks"
Expected time complexity is O(n) and only one traversal of string.
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Below is a Simple Solution
1) Iterate through all characters of given string, do following
a) If current character is a space, then move all subsequent
characters one position back and decrease length of the
result string.
Time complexity of above solution is O(n2).
A Better Solution can solve it in O(n) time. The idea is to keep track of count of non-space character seen so far.
1) Initialize 'count' = 0 (Count of non-space character seen so far)
2) Iterate through all characters of given string, do following
a) If current character is non-space, then put this character
at index 'count' and increment 'count'
3) Finally, put '\0' at index 'count'
Below is the implementation of above algorithm.
C++
Java
Python
C#
Javascript
// An efficient C++ program to remove all spaces// from a string#include <iostream>using namespace std; // Function to remove all spaces from a given stringvoid removeSpaces(char *str){ // To keep track of non-space character count int count = 0; // Traverse the given string. If current character // is not space, then place it at index 'count++' for (int i = 0; str[i]; i++) if (str[i] != ' ') str[count++] = str[i]; // here count is // incremented str[count] = '\0';} // Driver program to test above functionint main(){ char str[] = "g eeks for ge eeks "; removeSpaces(str); cout << str; return 0;}
// An efficient Java program to remove all spaces// from a stringclass GFG{ // Function to remove all spaces// from a given stringstatic int removeSpaces(char []str){ // To keep track of non-space character count int count = 0; // Traverse the given string. // If current character // is not space, then place // it at index 'count++' for (int i = 0; i<str.length; i++) if (str[i] != ' ') str[count++] = str[i]; // here count is // incremented return count;} // Driver codepublic static void main(String[] args){ char str[] = "g eeks for ge eeks ".toCharArray(); int i = removeSpaces(str); System.out.println(String.valueOf(str).subSequence(0, i));}} // This code is contributed by Rajput-Ji
# Python program to Remove spaces from a given string # Function to remove all spaces from a given stringdef removeSpaces(string): # To keep track of non-space character count count = 0 list = [] # Traverse the given string. If current character # is not space, then place it at index 'count++' for i in xrange(len(string)): if string[i] != ' ': list.append(string[i]) return toString(list) # Utility Functiondef toString(List): return ''.join(List) # Driver programstring = "g eeks for ge eeks "print removeSpaces(string) # This code is contributed by Bhavya Jain
// An efficient C# program to remove all// spaces from a stringusing System; class GFG{ // Function to remove all spaces// from a given stringstatic int removeSpaces(char []str){ // To keep track of non-space // character count int count = 0; // Traverse the given string. If current // character is not space, then place // it at index 'count++' for (int i = 0; i < str.Length; i++) if (str[i] != ' ') str[count++] = str[i]; // here count is // incremented return count;} // Driver codepublic static void Main(String[] args){ char []str = "g eeks for ge eeks ".ToCharArray(); int i = removeSpaces(str); Console.WriteLine(String.Join("", str).Substring(0, i));}} // This code is contributed by 29AjayKumar
<script> // An efficient JavaScript program to remove all // spaces from a string // Function to remove all spaces // from a given string function removeSpaces(str) { // To keep track of non-space // character count var count = 0; // Traverse the given string. If current // character is not space, then place // it at index 'count++' for (var i = 0; i < str.length; i++) if (str[i] !== " ") str[count++] = str[i]; // here count is // incremented return count; } // Driver code var str = "g eeks for ge eeks ".split(""); var i = removeSpaces(str); document.write(str.join("").substring(0, i)); </script>
geeksforgeeeks
Time complexity of above solution is O(n) and it does only one traversal of string. Another solution suggested by Divyam Madaan is to use predefined functions. Here is the implementation:
C++
Java
Python
C#
Javascript
// CPP program to Remove spaces// from a given string #include <iostream>#include <algorithm>using namespace std; // Function to remove all spaces from a given stringstring removeSpaces(string str){ str.erase(remove(str.begin(), str.end(), ' '), str.end()); return str;} // Driver program to test above functionint main(){ string str = "g eeks for ge eeks "; str = removeSpaces(str); cout << str; return 0;} // This code is contributed by Divyam Madaan
// Java program to remove// all spaces from a string class GFG { // Function to remove all // spaces from a given string static String removeSpace(String str) { str = str.replaceAll("\\s",""); return str; } // Driver Code public static void main(String args[]) { String str = "g eeks for ge eeks "; System.out.println(removeSpace(str)); }} // This code is contributed by Kanhaiya.
# Python program to Remove spaces from a given string # Function to remove all spaces from a given stringdef removeSpaces(string): string = string.replace(' ','') return string # Driver programstring = "g eeks for ge eeks "print(removeSpaces(string)) # This code is contributed by Divyam Madaan
// C# program to remove// all spaces from a stringusing System; class GFG{ // Function to remove all // spaces from a given string static String removeSpace(String str) { str = str.Replace(" ",""); return str; } // Driver Code public static void Main() { String str = "g eeks for ge eeks "; Console.WriteLine(removeSpace(str)); }} // This code is contributed by// PrinciRaj1992
<script>// javascript program to remove// all spaces from a string // Function to remove all // spaces from a given string function removeSpace( str) { str = str.replace(/\s/g,'') return str; } // Driver Code var str = "g eeks for ge eeks "; document.write(removeSpace(str)); // This code contributed by aashish1995</script>
geeksforgeeeks
Another method to solve this problem using predefined STL functions like count() ,remove() ,getline() and resize() is also present. Here is the implementation for the same :
C++
#include <bits/stdc++.h>using namespace std;int main(){ string s = "g e e k s f o r g e e k s"; cout << "string with spaces is " << s << endl; int l = s.length(); // storing the length of the string int c = count(s.begin(), s.end(), ' '); // counting the number of whitespaces remove(s.begin(), s.end(), ' '); // removing all the whitespaces s.resize(l - c); // resizing the string to l-c cout << "string without spaces is " << s << endl; return 0;}
string with spaces is g e e k s f o r g e e k s
string without spaces is geeksforgeeks
Thanks to Souravi Sarkar for suggesting this problem and initial solution. Java | Removing whitespaces using Regex
starklm1402
princiraj1992
Rajput-Ji
29AjayKumar
aashish1995
adityamutharia
rdtank
hardikkoriintern
Amazon
SAP Labs
Strings
Amazon
SAP Labs
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n27 Jun, 2022"
},
{
"code": null,
"e": 118,
"s": 52,
"text": "Given a string, remove all spaces from the string and return it. "
},
{
"code": null,
"e": 177,
"s": 118,
"text": "Input: \"g eeks for ge eeks \"\nOutput: \"geeksforgeeks\""
},
{
"code": null,
"e": 245,
"s": 177,
"text": "Expected time complexity is O(n) and only one traversal of string. "
},
{
"code": null,
"e": 254,
"s": 245,
"text": "Chapters"
},
{
"code": null,
"e": 281,
"s": 254,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 331,
"s": 281,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 354,
"s": 331,
"text": "captions off, selected"
},
{
"code": null,
"e": 362,
"s": 354,
"text": "English"
},
{
"code": null,
"e": 386,
"s": 362,
"text": "This is a modal window."
},
{
"code": null,
"e": 455,
"s": 386,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 477,
"s": 455,
"text": "End of dialog window."
},
{
"code": null,
"e": 505,
"s": 477,
"text": "Below is a Simple Solution "
},
{
"code": null,
"e": 717,
"s": 505,
"text": "1) Iterate through all characters of given string, do following\n a) If current character is a space, then move all subsequent\n characters one position back and decrease length of the \n result string."
},
{
"code": null,
"e": 761,
"s": 717,
"text": "Time complexity of above solution is O(n2)."
},
{
"code": null,
"e": 878,
"s": 761,
"text": "A Better Solution can solve it in O(n) time. The idea is to keep track of count of non-space character seen so far. "
},
{
"code": null,
"e": 1163,
"s": 878,
"text": "1) Initialize 'count' = 0 (Count of non-space character seen so far)\n2) Iterate through all characters of given string, do following\n a) If current character is non-space, then put this character\n at index 'count' and increment 'count'\n3) Finally, put '\\0' at index 'count'"
},
{
"code": null,
"e": 1212,
"s": 1163,
"text": "Below is the implementation of above algorithm. "
},
{
"code": null,
"e": 1216,
"s": 1212,
"text": "C++"
},
{
"code": null,
"e": 1221,
"s": 1216,
"text": "Java"
},
{
"code": null,
"e": 1228,
"s": 1221,
"text": "Python"
},
{
"code": null,
"e": 1231,
"s": 1228,
"text": "C#"
},
{
"code": null,
"e": 1242,
"s": 1231,
"text": "Javascript"
},
{
"code": "// An efficient C++ program to remove all spaces// from a string#include <iostream>using namespace std; // Function to remove all spaces from a given stringvoid removeSpaces(char *str){ // To keep track of non-space character count int count = 0; // Traverse the given string. If current character // is not space, then place it at index 'count++' for (int i = 0; str[i]; i++) if (str[i] != ' ') str[count++] = str[i]; // here count is // incremented str[count] = '\\0';} // Driver program to test above functionint main(){ char str[] = \"g eeks for ge eeks \"; removeSpaces(str); cout << str; return 0;}",
"e": 1932,
"s": 1242,
"text": null
},
{
"code": " // An efficient Java program to remove all spaces// from a stringclass GFG{ // Function to remove all spaces// from a given stringstatic int removeSpaces(char []str){ // To keep track of non-space character count int count = 0; // Traverse the given string. // If current character // is not space, then place // it at index 'count++' for (int i = 0; i<str.length; i++) if (str[i] != ' ') str[count++] = str[i]; // here count is // incremented return count;} // Driver codepublic static void main(String[] args){ char str[] = \"g eeks for ge eeks \".toCharArray(); int i = removeSpaces(str); System.out.println(String.valueOf(str).subSequence(0, i));}} // This code is contributed by Rajput-Ji",
"e": 2725,
"s": 1932,
"text": null
},
{
"code": "# Python program to Remove spaces from a given string # Function to remove all spaces from a given stringdef removeSpaces(string): # To keep track of non-space character count count = 0 list = [] # Traverse the given string. If current character # is not space, then place it at index 'count++' for i in xrange(len(string)): if string[i] != ' ': list.append(string[i]) return toString(list) # Utility Functiondef toString(List): return ''.join(List) # Driver programstring = \"g eeks for ge eeks \"print removeSpaces(string) # This code is contributed by Bhavya Jain",
"e": 3340,
"s": 2725,
"text": null
},
{
"code": "// An efficient C# program to remove all// spaces from a stringusing System; class GFG{ // Function to remove all spaces// from a given stringstatic int removeSpaces(char []str){ // To keep track of non-space // character count int count = 0; // Traverse the given string. If current // character is not space, then place // it at index 'count++' for (int i = 0; i < str.Length; i++) if (str[i] != ' ') str[count++] = str[i]; // here count is // incremented return count;} // Driver codepublic static void Main(String[] args){ char []str = \"g eeks for ge eeks \".ToCharArray(); int i = removeSpaces(str); Console.WriteLine(String.Join(\"\", str).Substring(0, i));}} // This code is contributed by 29AjayKumar",
"e": 4133,
"s": 3340,
"text": null
},
{
"code": "<script> // An efficient JavaScript program to remove all // spaces from a string // Function to remove all spaces // from a given string function removeSpaces(str) { // To keep track of non-space // character count var count = 0; // Traverse the given string. If current // character is not space, then place // it at index 'count++' for (var i = 0; i < str.length; i++) if (str[i] !== \" \") str[count++] = str[i]; // here count is // incremented return count; } // Driver code var str = \"g eeks for ge eeks \".split(\"\"); var i = removeSpaces(str); document.write(str.join(\"\").substring(0, i)); </script>",
"e": 4884,
"s": 4133,
"text": null
},
{
"code": null,
"e": 4899,
"s": 4884,
"text": "geeksforgeeeks"
},
{
"code": null,
"e": 5088,
"s": 4899,
"text": "Time complexity of above solution is O(n) and it does only one traversal of string. Another solution suggested by Divyam Madaan is to use predefined functions. Here is the implementation: "
},
{
"code": null,
"e": 5092,
"s": 5088,
"text": "C++"
},
{
"code": null,
"e": 5097,
"s": 5092,
"text": "Java"
},
{
"code": null,
"e": 5104,
"s": 5097,
"text": "Python"
},
{
"code": null,
"e": 5107,
"s": 5104,
"text": "C#"
},
{
"code": null,
"e": 5118,
"s": 5107,
"text": "Javascript"
},
{
"code": "// CPP program to Remove spaces// from a given string #include <iostream>#include <algorithm>using namespace std; // Function to remove all spaces from a given stringstring removeSpaces(string str){ str.erase(remove(str.begin(), str.end(), ' '), str.end()); return str;} // Driver program to test above functionint main(){ string str = \"g eeks for ge eeks \"; str = removeSpaces(str); cout << str; return 0;} // This code is contributed by Divyam Madaan",
"e": 5589,
"s": 5118,
"text": null
},
{
"code": "// Java program to remove// all spaces from a string class GFG { // Function to remove all // spaces from a given string static String removeSpace(String str) { str = str.replaceAll(\"\\\\s\",\"\"); return str; } // Driver Code public static void main(String args[]) { String str = \"g eeks for ge eeks \"; System.out.println(removeSpace(str)); }} // This code is contributed by Kanhaiya.",
"e": 6031,
"s": 5589,
"text": null
},
{
"code": "# Python program to Remove spaces from a given string # Function to remove all spaces from a given stringdef removeSpaces(string): string = string.replace(' ','') return string # Driver programstring = \"g eeks for ge eeks \"print(removeSpaces(string)) # This code is contributed by Divyam Madaan",
"e": 6341,
"s": 6031,
"text": null
},
{
"code": "// C# program to remove// all spaces from a stringusing System; class GFG{ // Function to remove all // spaces from a given string static String removeSpace(String str) { str = str.Replace(\" \",\"\"); return str; } // Driver Code public static void Main() { String str = \"g eeks for ge eeks \"; Console.WriteLine(removeSpace(str)); }} // This code is contributed by// PrinciRaj1992",
"e": 6780,
"s": 6341,
"text": null
},
{
"code": "<script>// javascript program to remove// all spaces from a string // Function to remove all // spaces from a given string function removeSpace( str) { str = str.replace(/\\s/g,'') return str; } // Driver Code var str = \"g eeks for ge eeks \"; document.write(removeSpace(str)); // This code contributed by aashish1995</script>",
"e": 7157,
"s": 6780,
"text": null
},
{
"code": null,
"e": 7172,
"s": 7157,
"text": "geeksforgeeeks"
},
{
"code": null,
"e": 7346,
"s": 7172,
"text": "Another method to solve this problem using predefined STL functions like count() ,remove() ,getline() and resize() is also present. Here is the implementation for the same :"
},
{
"code": null,
"e": 7350,
"s": 7346,
"text": "C++"
},
{
"code": "#include <bits/stdc++.h>using namespace std;int main(){ string s = \"g e e k s f o r g e e k s\"; cout << \"string with spaces is \" << s << endl; int l = s.length(); // storing the length of the string int c = count(s.begin(), s.end(), ' '); // counting the number of whitespaces remove(s.begin(), s.end(), ' '); // removing all the whitespaces s.resize(l - c); // resizing the string to l-c cout << \"string without spaces is \" << s << endl; return 0;}",
"e": 7863,
"s": 7350,
"text": null
},
{
"code": null,
"e": 7950,
"s": 7863,
"text": "string with spaces is g e e k s f o r g e e k s\nstring without spaces is geeksforgeeks"
},
{
"code": null,
"e": 8065,
"s": 7950,
"text": "Thanks to Souravi Sarkar for suggesting this problem and initial solution. Java | Removing whitespaces using Regex"
},
{
"code": null,
"e": 8077,
"s": 8065,
"text": "starklm1402"
},
{
"code": null,
"e": 8091,
"s": 8077,
"text": "princiraj1992"
},
{
"code": null,
"e": 8101,
"s": 8091,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 8113,
"s": 8101,
"text": "29AjayKumar"
},
{
"code": null,
"e": 8125,
"s": 8113,
"text": "aashish1995"
},
{
"code": null,
"e": 8140,
"s": 8125,
"text": "adityamutharia"
},
{
"code": null,
"e": 8147,
"s": 8140,
"text": "rdtank"
},
{
"code": null,
"e": 8164,
"s": 8147,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 8171,
"s": 8164,
"text": "Amazon"
},
{
"code": null,
"e": 8180,
"s": 8171,
"text": "SAP Labs"
},
{
"code": null,
"e": 8188,
"s": 8180,
"text": "Strings"
},
{
"code": null,
"e": 8195,
"s": 8188,
"text": "Amazon"
},
{
"code": null,
"e": 8204,
"s": 8195,
"text": "SAP Labs"
},
{
"code": null,
"e": 8212,
"s": 8204,
"text": "Strings"
}
]
|
Flutter – Changing App Icon | 29 Dec, 2020
Flutter SDK is an open-source software development kit for building beautiful UI which is natively compiled. When we create a Flutter Project, it comes with the default Flutter icon. In order to get the app published in stores like Google Play Store, Apple App Store, etc the default icon can be changed. In this article, we will look into a few possible approaches to achieve the same.
There are Two ways to change the App Icon:
Manually changing the files of Icon in Both Android and IOS folder by uploading all the required sizes of the icon.
Manually changing the files of Icon in Both Android and IOS folder by uploading all the required sizes of the icon.
2. Using Package which will add all the sizes of Icons in Android and IOS folders Automatically.
Go to https://appicon.co/ and upload the icon image and tick the iPhone and Android options and click on Generate. This site generates different sized Icons for both android and IOS at the same time.
It will Download the Zip file named AppIcons with the android and Assets.xcassets named folders along with images for appstore and playstore which can be directly uploaded as an icon in both the stores
Now, open your Project in Vs Code.
Navigate to android/app/src/main/res and right-click on res folder and click “reveal in Explorer”. Now delete all the mipmap folders in res folder and paste the mipmap folders from AppIcon/android folder which you have downloaded.
Icons changed in the res folder
Now navigate to the ios/Runner/Assets.xcassets. Now after you are in Runner folder, right-click on Runner folder and click “reveal in Explorer”. Now delete the Assets.xcassets folder and paste the Assets.xcassets folder from AppIcon/Assets.xcassets which you have downloaded.
Assets.xcassets Changed in Runner Folder
After manually changing the images in android and IOS folders now go to lib/main.dart and run the flutter project using the below command in the flutter console.
flutter run
By using the package we can generate the different sized Icons at a time for both android and IOS.
Open your Project in Vs Code and Go to pubspec.yaml file.
Go to dev_dependencies and add flutter_launcher_icons: “^0.8.0” dependency and save the file. It will get the dependency.
Adding dependency in dev_dependencies
Now add the flutter_icons: and save.
Now create assets folder -> create icon folder -> add icon.png file
Note: If you are not having .png image, then change the image format in image_path: as shown in the above image.
Open the Terminal in Vs Code and run
flutter pub get
After the command is executed successfully then run
flutter pub run flutter_launcher_icons:main
After both the commands are executed successfully then go to lib/main.dart file and run the app
flutter run
Output:
android
Flutter
Dart
Flutter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n29 Dec, 2020"
},
{
"code": null,
"e": 440,
"s": 52,
"text": "Flutter SDK is an open-source software development kit for building beautiful UI which is natively compiled. When we create a Flutter Project, it comes with the default Flutter icon. In order to get the app published in stores like Google Play Store, Apple App Store, etc the default icon can be changed. In this article, we will look into a few possible approaches to achieve the same."
},
{
"code": null,
"e": 483,
"s": 440,
"text": "There are Two ways to change the App Icon:"
},
{
"code": null,
"e": 599,
"s": 483,
"text": "Manually changing the files of Icon in Both Android and IOS folder by uploading all the required sizes of the icon."
},
{
"code": null,
"e": 715,
"s": 599,
"text": "Manually changing the files of Icon in Both Android and IOS folder by uploading all the required sizes of the icon."
},
{
"code": null,
"e": 818,
"s": 715,
"text": " 2. Using Package which will add all the sizes of Icons in Android and IOS folders Automatically."
},
{
"code": null,
"e": 1019,
"s": 818,
"text": "Go to https://appicon.co/ and upload the icon image and tick the iPhone and Android options and click on Generate. This site generates different sized Icons for both android and IOS at the same time."
},
{
"code": null,
"e": 1221,
"s": 1019,
"text": "It will Download the Zip file named AppIcons with the android and Assets.xcassets named folders along with images for appstore and playstore which can be directly uploaded as an icon in both the stores"
},
{
"code": null,
"e": 1256,
"s": 1221,
"text": "Now, open your Project in Vs Code."
},
{
"code": null,
"e": 1488,
"s": 1256,
"text": " Navigate to android/app/src/main/res and right-click on res folder and click “reveal in Explorer”. Now delete all the mipmap folders in res folder and paste the mipmap folders from AppIcon/android folder which you have downloaded."
},
{
"code": null,
"e": 1520,
"s": 1488,
"text": "Icons changed in the res folder"
},
{
"code": null,
"e": 1796,
"s": 1520,
"text": "Now navigate to the ios/Runner/Assets.xcassets. Now after you are in Runner folder, right-click on Runner folder and click “reveal in Explorer”. Now delete the Assets.xcassets folder and paste the Assets.xcassets folder from AppIcon/Assets.xcassets which you have downloaded."
},
{
"code": null,
"e": 1837,
"s": 1796,
"text": "Assets.xcassets Changed in Runner Folder"
},
{
"code": null,
"e": 1999,
"s": 1837,
"text": "After manually changing the images in android and IOS folders now go to lib/main.dart and run the flutter project using the below command in the flutter console."
},
{
"code": null,
"e": 2011,
"s": 1999,
"text": "flutter run"
},
{
"code": null,
"e": 2111,
"s": 2011,
"text": "By using the package we can generate the different sized Icons at a time for both android and IOS. "
},
{
"code": null,
"e": 2169,
"s": 2111,
"text": "Open your Project in Vs Code and Go to pubspec.yaml file."
},
{
"code": null,
"e": 2292,
"s": 2169,
"text": "Go to dev_dependencies and add flutter_launcher_icons: “^0.8.0” dependency and save the file. It will get the dependency. "
},
{
"code": null,
"e": 2331,
"s": 2292,
"text": "Adding dependency in dev_dependencies "
},
{
"code": null,
"e": 2368,
"s": 2331,
"text": "Now add the flutter_icons: and save."
},
{
"code": null,
"e": 2437,
"s": 2368,
"text": "Now create assets folder -> create icon folder -> add icon.png file "
},
{
"code": null,
"e": 2550,
"s": 2437,
"text": "Note: If you are not having .png image, then change the image format in image_path: as shown in the above image."
},
{
"code": null,
"e": 2588,
"s": 2550,
"text": "Open the Terminal in Vs Code and run "
},
{
"code": null,
"e": 2604,
"s": 2588,
"text": "flutter pub get"
},
{
"code": null,
"e": 2657,
"s": 2604,
"text": "After the command is executed successfully then run "
},
{
"code": null,
"e": 2701,
"s": 2657,
"text": "flutter pub run flutter_launcher_icons:main"
},
{
"code": null,
"e": 2797,
"s": 2701,
"text": "After both the commands are executed successfully then go to lib/main.dart file and run the app"
},
{
"code": null,
"e": 2809,
"s": 2797,
"text": "flutter run"
},
{
"code": null,
"e": 2818,
"s": 2809,
"text": "Output: "
},
{
"code": null,
"e": 2826,
"s": 2818,
"text": "android"
},
{
"code": null,
"e": 2834,
"s": 2826,
"text": "Flutter"
},
{
"code": null,
"e": 2839,
"s": 2834,
"text": "Dart"
},
{
"code": null,
"e": 2847,
"s": 2839,
"text": "Flutter"
}
]
|
How to open and close a file in Python | 07 Oct, 2021
There might rise a situation where one needs to interact with external files with Python.Python provides inbuilt functions for creating, writing and reading files. in this article, we will be discussing how to open an external file and close the same using Python.Opening a file in python:There are two types of files that can be handled in Python, normal text files and binary files (written in binary language, 0s, and 1s). Opening a file refers to getting the file ready either for reading or for writing. This can be done using the open() function. This function returns a file object and takes two arguments, one that accepts the file name and another that accepts the mode(Access Mode).Note: The file should exist in the same directory as the Python script, otherwise, full address of the file should be written.
Syntax: File_object = open(“File_Name”, “Access_Mode”)Parameters:
File_Name: It is the name of the file that needs to be opened.
Access_Mode: Access modes govern the type of operations possible in the opened file. The below table gives the list of all access mode available in python:
Example 1: In this example, we will be opening a file to read-only. The initial file looks like below:
Code:
Python3
# open the file using open() functionfile = open("sample.txt") # Reading from fileprint(file.read())
Here we have opened the file and printed its content.Output:
Hello Geek!
This is a sample text file for the example.
Example 2: In this example, we will be appending new content to the existing file. So the initial file looks like below:
Code:
Python3
# open the file using open() functionfile = open("sample.txt", 'a') # Add content in the filefile.write(" This text has been newly appended on the sample file")
Now if you open the file you will see the below result, Output:
Example 3: In this example, we will be overwriting the contents of the sample file with the below code:Code:
Python3
# open the file using open() functionfile = open("sample.txt", 'w') # Overwrite the filefile.write(" All content has been overwritten !")
The above code leads to the following result, Output:
Closing a file in Python:If you notice, we have not closed any of the files that we operated on in the above examples. Though Python automatically closes a file if the reference object of the file is allocated to another file, it is a standard practice to close an opened file as a closed file reduces the risk of being unwarrantedly modified or read.Python has a close() method to close a file. The close() method can be called more than once and if any operation is performed on a closed file it raises a ValueError. The below code shows a simple use of close() method to close an opened file.Example 1:
Python3
# open the file using open() functionfile = open("sample.txt") # Reading from fileprint(file.read()) # closing the filefile.close()
Now if we try to perform any operation on a closed file like shown below it raises a ValueError:
Python3
# open the file using open() functionfile = open("sample.txt") # Reading from fileprint(file.read()) # closing the filefile.close() # Attempt to write in the filefile.write(" Attempt to write on a closed file !")
Output:
ValueError: I/O operation on closed file.
anikaseth98
python-file-handling
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n07 Oct, 2021"
},
{
"code": null,
"e": 873,
"s": 53,
"text": "There might rise a situation where one needs to interact with external files with Python.Python provides inbuilt functions for creating, writing and reading files. in this article, we will be discussing how to open an external file and close the same using Python.Opening a file in python:There are two types of files that can be handled in Python, normal text files and binary files (written in binary language, 0s, and 1s). Opening a file refers to getting the file ready either for reading or for writing. This can be done using the open() function. This function returns a file object and takes two arguments, one that accepts the file name and another that accepts the mode(Access Mode).Note: The file should exist in the same directory as the Python script, otherwise, full address of the file should be written. "
},
{
"code": null,
"e": 941,
"s": 873,
"text": "Syntax: File_object = open(“File_Name”, “Access_Mode”)Parameters: "
},
{
"code": null,
"e": 1006,
"s": 941,
"text": "File_Name: It is the name of the file that needs to be opened. "
},
{
"code": null,
"e": 1164,
"s": 1006,
"text": "Access_Mode: Access modes govern the type of operations possible in the opened file. The below table gives the list of all access mode available in python: "
},
{
"code": null,
"e": 1269,
"s": 1164,
"text": "Example 1: In this example, we will be opening a file to read-only. The initial file looks like below: "
},
{
"code": null,
"e": 1277,
"s": 1269,
"text": "Code: "
},
{
"code": null,
"e": 1285,
"s": 1277,
"text": "Python3"
},
{
"code": "# open the file using open() functionfile = open(\"sample.txt\") # Reading from fileprint(file.read())",
"e": 1388,
"s": 1285,
"text": null
},
{
"code": null,
"e": 1451,
"s": 1388,
"text": "Here we have opened the file and printed its content.Output: "
},
{
"code": null,
"e": 1507,
"s": 1451,
"text": "Hello Geek!\nThis is a sample text file for the example."
},
{
"code": null,
"e": 1630,
"s": 1507,
"text": "Example 2: In this example, we will be appending new content to the existing file. So the initial file looks like below: "
},
{
"code": null,
"e": 1638,
"s": 1630,
"text": "Code: "
},
{
"code": null,
"e": 1646,
"s": 1638,
"text": "Python3"
},
{
"code": "# open the file using open() functionfile = open(\"sample.txt\", 'a') # Add content in the filefile.write(\" This text has been newly appended on the sample file\")",
"e": 1809,
"s": 1646,
"text": null
},
{
"code": null,
"e": 1875,
"s": 1809,
"text": "Now if you open the file you will see the below result, Output: "
},
{
"code": null,
"e": 1986,
"s": 1875,
"text": "Example 3: In this example, we will be overwriting the contents of the sample file with the below code:Code: "
},
{
"code": null,
"e": 1994,
"s": 1986,
"text": "Python3"
},
{
"code": "# open the file using open() functionfile = open(\"sample.txt\", 'w') # Overwrite the filefile.write(\" All content has been overwritten !\")",
"e": 2134,
"s": 1994,
"text": null
},
{
"code": null,
"e": 2190,
"s": 2134,
"text": "The above code leads to the following result, Output: "
},
{
"code": null,
"e": 2798,
"s": 2190,
"text": "Closing a file in Python:If you notice, we have not closed any of the files that we operated on in the above examples. Though Python automatically closes a file if the reference object of the file is allocated to another file, it is a standard practice to close an opened file as a closed file reduces the risk of being unwarrantedly modified or read.Python has a close() method to close a file. The close() method can be called more than once and if any operation is performed on a closed file it raises a ValueError. The below code shows a simple use of close() method to close an opened file.Example 1: "
},
{
"code": null,
"e": 2806,
"s": 2798,
"text": "Python3"
},
{
"code": "# open the file using open() functionfile = open(\"sample.txt\") # Reading from fileprint(file.read()) # closing the filefile.close()",
"e": 2940,
"s": 2806,
"text": null
},
{
"code": null,
"e": 3039,
"s": 2940,
"text": "Now if we try to perform any operation on a closed file like shown below it raises a ValueError: "
},
{
"code": null,
"e": 3047,
"s": 3039,
"text": "Python3"
},
{
"code": "# open the file using open() functionfile = open(\"sample.txt\") # Reading from fileprint(file.read()) # closing the filefile.close() # Attempt to write in the filefile.write(\" Attempt to write on a closed file !\")",
"e": 3262,
"s": 3047,
"text": null
},
{
"code": null,
"e": 3271,
"s": 3262,
"text": "Output: "
},
{
"code": null,
"e": 3313,
"s": 3271,
"text": "ValueError: I/O operation on closed file."
},
{
"code": null,
"e": 3327,
"s": 3315,
"text": "anikaseth98"
},
{
"code": null,
"e": 3348,
"s": 3327,
"text": "python-file-handling"
},
{
"code": null,
"e": 3355,
"s": 3348,
"text": "Python"
},
{
"code": null,
"e": 3371,
"s": 3355,
"text": "Write From Home"
}
]
|
Auto Image Slider in Android with Example | 28 Nov, 2021
Auto Image Slider is one of the most seen UI components in Android. This type of slider is mostly seen inside the apps of big E-commerce sites such as Flipkart, Amazon, and many more. Auto Image Slider is used to represent data in the form of slides that changes after a specific interval of time. In this article, we will take a look at How to Create Auto Image Slider on Android. We will use the SliderView library to add this type of UI component in our app.
Note: You may also refer to Image Slider in Android using ViewPager.
Now we will see the Implementation of this SliderView in Android.
A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Add dependency of Slider View in build.gradle file
Navigate to the Gradle scripts and then to build.gradle(Module) level. Add below line in build.gradle file in the dependencies section.
// dependency sor slider view
implementation ‘com.github.smarteist:autoimageslider:1.3.9’
// dependency for loading image from url
implementation “com.github.bumptech.glide:glide:4.11.0”
Step 3: Add internet permission in the AndroidManifest.xml file
Navigate to the app > Manifest to open the Manifest file and add below two lines.
<!–Permission for internet–>
<uses-permission android:name=”android.permission.INTERNET” />
<uses-permission android:name=”android.permission.ACCESS_NETWORK_STATE” />
Step 4: Working with the activity_main.xml file
Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!-- slideranimation duration is to set duration for transition between two slides sliderautocycledirection is to set animationbetween transition of your slides sliderindicator enables is used to display the indicators for slider slider indicator gravity is to set gravity for indicator gravity slider indicator margin is to set margin for indicator slider indicator orientation is used to add orientation for slider slider indicator padding is use to add padding to indicator slider indicator selected color is use to specify selected color and slider indicator unselected color is use to specify the color when the slider is unselected slider scroll time in sec is used to specify scrolling time in seconds --> <com.smarteist.autoimageslider.SliderView android:id="@+id/slider" android:layout_width="match_parent" android:layout_height="150dp" android:layout_centerInParent="true" app:sliderAnimationDuration="600" app:sliderAutoCycleDirection="back_and_forth" app:sliderIndicatorAnimationDuration="600" app:sliderIndicatorEnabled="true" app:sliderIndicatorGravity="center_horizontal|bottom" app:sliderIndicatorMargin="15dp" app:sliderIndicatorOrientation="horizontal" app:sliderIndicatorPadding="3dp" app:sliderIndicatorRadius="2dp" app:sliderIndicatorSelectedColor="#5A5A5A" app:sliderIndicatorUnselectedColor="#FFF" app:sliderScrollTimeInSec="1" /> </RelativeLayout>
Step 5: Create a new Modal class for storing data
Navigate to app > java > your app’s package name and then right-click on it and New > Java class and name your Model class as SliderData and below code inside that Java class. Below is the code for the SliderData.java file. Comments are added inside the code to understand the code in more detail.
Java
public class SliderData { // image url is used to // store the url of image private String imgUrl; // Constructor method. public SliderData(String imgUrl) { this.imgUrl = imgUrl; } // Getter method public String getImgUrl() { return imgUrl; } // Setter method public void setImgUrl(String imgUrl) { this.imgUrl = imgUrl; }}
Step 6: Create an XML file for the items of SliderView
Navigate to the app > res > layout > Right-click on it and select New > Layout Resource File and then name your XML file as slider_layout.xml. After creating this file add the below code to it.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <!--Image we will display is our slider view--> <ImageView android:id="@+id/myimage" android:layout_width="400dp" android:layout_height="300dp" android:layout_centerHorizontal="true" android:contentDescription="@string/app_name" /> </RelativeLayout>
Step 7: Create Adapter Class for setting data to each item of our SliderView
Navigate to app > java > your app’s package name and then right-click on it and New > Java class and name your class as SliderAdapter and below code inside that Java class. Below is the code for the SliderAdapter.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView; import com.bumptech.glide.Glide;import com.smarteist.autoimageslider.SliderViewAdapter; import java.util.ArrayList;import java.util.List; public class SliderAdapter extends SliderViewAdapter<SliderAdapter.SliderAdapterViewHolder> { // list for storing urls of images. private final List<SliderData> mSliderItems; // Constructor public SliderAdapter(Context context, ArrayList<SliderData> sliderDataArrayList) { this.mSliderItems = sliderDataArrayList; } // We are inflating the slider_layout // inside on Create View Holder method. @Override public SliderAdapterViewHolder onCreateViewHolder(ViewGroup parent) { View inflate = LayoutInflater.from(parent.getContext()).inflate(R.layout.slider_layout, null); return new SliderAdapterViewHolder(inflate); } // Inside on bind view holder we will // set data to item of Slider View. @Override public void onBindViewHolder(SliderAdapterViewHolder viewHolder, final int position) { final SliderData sliderItem = mSliderItems.get(position); // Glide is use to load image // from url in your imageview. Glide.with(viewHolder.itemView) .load(sliderItem.getImgUrl()) .fitCenter() .into(viewHolder.imageViewBackground); } // this method will return // the count of our list. @Override public int getCount() { return mSliderItems.size(); } static class SliderAdapterViewHolder extends SliderViewAdapter.ViewHolder { // Adapter class for initializing // the views of our slider view. View itemView; ImageView imageViewBackground; public SliderAdapterViewHolder(View itemView) { super(itemView); imageViewBackground = itemView.findViewById(R.id.myimage); this.itemView = itemView; } }}
Step 8: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.os.Bundle;import androidx.appcompat.app.AppCompatActivity;import com.smarteist.autoimageslider.SliderView;import java.util.ArrayList; public class MainActivity extends AppCompatActivity { // Urls of our images. String url1 = "https://www.geeksforgeeks.org/wp-content/uploads/gfg_200X200-1.png"; String url2 = "https://qphs.fs.quoracdn.net/main-qimg-8e203d34a6a56345f86f1a92570557ba.webp"; String url3 = "https://bizzbucket.co/wp-content/uploads/2020/08/Life-in-The-Metro-Blog-Title-22.png"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // we are creating array list for storing our image urls. ArrayList<SliderData> sliderDataArrayList = new ArrayList<>(); // initializing the slider view. SliderView sliderView = findViewById(R.id.slider); // adding the urls inside array list sliderDataArrayList.add(new SliderData(url1)); sliderDataArrayList.add(new SliderData(url2)); sliderDataArrayList.add(new SliderData(url3)); // passing this array list inside our adapter class. SliderAdapter adapter = new SliderAdapter(this, sliderDataArrayList); // below method is used to set auto cycle direction in left to // right direction you can change according to requirement. sliderView.setAutoCycleDirection(SliderView.LAYOUT_DIRECTION_LTR); // below method is used to // setadapter to sliderview. sliderView.setSliderAdapter(adapter); // below method is use to set // scroll time in seconds. sliderView.setScrollTimeInSec(3); // to set it scrollable automatically // we use below method. sliderView.setAutoCycle(true); // to start autocycle below method is used. sliderView.startAutoCycle(); }}
Check out the project on this link: https://github.com/ChaitanyaMunje/GFGImageSlider
kapoorsagar226
android
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Nov, 2021"
},
{
"code": null,
"e": 492,
"s": 28,
"text": "Auto Image Slider is one of the most seen UI components in Android. This type of slider is mostly seen inside the apps of big E-commerce sites such as Flipkart, Amazon, and many more. Auto Image Slider is used to represent data in the form of slides that changes after a specific interval of time. In this article, we will take a look at How to Create Auto Image Slider on Android. We will use the SliderView library to add this type of UI component in our app. "
},
{
"code": null,
"e": 561,
"s": 492,
"text": "Note: You may also refer to Image Slider in Android using ViewPager."
},
{
"code": null,
"e": 628,
"s": 561,
"text": "Now we will see the Implementation of this SliderView in Android. "
},
{
"code": null,
"e": 793,
"s": 628,
"text": "A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 822,
"s": 793,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 984,
"s": 822,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 1043,
"s": 984,
"text": "Step 2: Add dependency of Slider View in build.gradle file"
},
{
"code": null,
"e": 1179,
"s": 1043,
"text": "Navigate to the Gradle scripts and then to build.gradle(Module) level. Add below line in build.gradle file in the dependencies section."
},
{
"code": null,
"e": 1209,
"s": 1179,
"text": "// dependency sor slider view"
},
{
"code": null,
"e": 1269,
"s": 1209,
"text": "implementation ‘com.github.smarteist:autoimageslider:1.3.9’"
},
{
"code": null,
"e": 1310,
"s": 1269,
"text": "// dependency for loading image from url"
},
{
"code": null,
"e": 1366,
"s": 1310,
"text": "implementation “com.github.bumptech.glide:glide:4.11.0”"
},
{
"code": null,
"e": 1430,
"s": 1366,
"text": "Step 3: Add internet permission in the AndroidManifest.xml file"
},
{
"code": null,
"e": 1512,
"s": 1430,
"text": "Navigate to the app > Manifest to open the Manifest file and add below two lines."
},
{
"code": null,
"e": 1541,
"s": 1512,
"text": "<!–Permission for internet–>"
},
{
"code": null,
"e": 1604,
"s": 1541,
"text": "<uses-permission android:name=”android.permission.INTERNET” />"
},
{
"code": null,
"e": 1679,
"s": 1604,
"text": "<uses-permission android:name=”android.permission.ACCESS_NETWORK_STATE” />"
},
{
"code": null,
"e": 1727,
"s": 1679,
"text": "Step 4: Working with the activity_main.xml file"
},
{
"code": null,
"e": 1843,
"s": 1727,
"text": "Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file."
},
{
"code": null,
"e": 1847,
"s": 1843,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!-- slideranimation duration is to set duration for transition between two slides sliderautocycledirection is to set animationbetween transition of your slides sliderindicator enables is used to display the indicators for slider slider indicator gravity is to set gravity for indicator gravity slider indicator margin is to set margin for indicator slider indicator orientation is used to add orientation for slider slider indicator padding is use to add padding to indicator slider indicator selected color is use to specify selected color and slider indicator unselected color is use to specify the color when the slider is unselected slider scroll time in sec is used to specify scrolling time in seconds --> <com.smarteist.autoimageslider.SliderView android:id=\"@+id/slider\" android:layout_width=\"match_parent\" android:layout_height=\"150dp\" android:layout_centerInParent=\"true\" app:sliderAnimationDuration=\"600\" app:sliderAutoCycleDirection=\"back_and_forth\" app:sliderIndicatorAnimationDuration=\"600\" app:sliderIndicatorEnabled=\"true\" app:sliderIndicatorGravity=\"center_horizontal|bottom\" app:sliderIndicatorMargin=\"15dp\" app:sliderIndicatorOrientation=\"horizontal\" app:sliderIndicatorPadding=\"3dp\" app:sliderIndicatorRadius=\"2dp\" app:sliderIndicatorSelectedColor=\"#5A5A5A\" app:sliderIndicatorUnselectedColor=\"#FFF\" app:sliderScrollTimeInSec=\"1\" /> </RelativeLayout>",
"e": 3708,
"s": 1847,
"text": null
},
{
"code": null,
"e": 3758,
"s": 3708,
"text": "Step 5: Create a new Modal class for storing data"
},
{
"code": null,
"e": 4056,
"s": 3758,
"text": "Navigate to app > java > your app’s package name and then right-click on it and New > Java class and name your Model class as SliderData and below code inside that Java class. Below is the code for the SliderData.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 4061,
"s": 4056,
"text": "Java"
},
{
"code": "public class SliderData { // image url is used to // store the url of image private String imgUrl; // Constructor method. public SliderData(String imgUrl) { this.imgUrl = imgUrl; } // Getter method public String getImgUrl() { return imgUrl; } // Setter method public void setImgUrl(String imgUrl) { this.imgUrl = imgUrl; }}",
"e": 4451,
"s": 4061,
"text": null
},
{
"code": null,
"e": 4507,
"s": 4451,
"text": "Step 6: Create an XML file for the items of SliderView "
},
{
"code": null,
"e": 4703,
"s": 4507,
"text": "Navigate to the app > res > layout > Right-click on it and select New > Layout Resource File and then name your XML file as slider_layout.xml. After creating this file add the below code to it. "
},
{
"code": null,
"e": 4707,
"s": 4703,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"> <!--Image we will display is our slider view--> <ImageView android:id=\"@+id/myimage\" android:layout_width=\"400dp\" android:layout_height=\"300dp\" android:layout_centerHorizontal=\"true\" android:contentDescription=\"@string/app_name\" /> </RelativeLayout>",
"e": 5198,
"s": 4707,
"text": null
},
{
"code": null,
"e": 5275,
"s": 5198,
"text": "Step 7: Create Adapter Class for setting data to each item of our SliderView"
},
{
"code": null,
"e": 5573,
"s": 5275,
"text": "Navigate to app > java > your app’s package name and then right-click on it and New > Java class and name your class as SliderAdapter and below code inside that Java class. Below is the code for the SliderAdapter.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 5578,
"s": 5573,
"text": "Java"
},
{
"code": "import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView; import com.bumptech.glide.Glide;import com.smarteist.autoimageslider.SliderViewAdapter; import java.util.ArrayList;import java.util.List; public class SliderAdapter extends SliderViewAdapter<SliderAdapter.SliderAdapterViewHolder> { // list for storing urls of images. private final List<SliderData> mSliderItems; // Constructor public SliderAdapter(Context context, ArrayList<SliderData> sliderDataArrayList) { this.mSliderItems = sliderDataArrayList; } // We are inflating the slider_layout // inside on Create View Holder method. @Override public SliderAdapterViewHolder onCreateViewHolder(ViewGroup parent) { View inflate = LayoutInflater.from(parent.getContext()).inflate(R.layout.slider_layout, null); return new SliderAdapterViewHolder(inflate); } // Inside on bind view holder we will // set data to item of Slider View. @Override public void onBindViewHolder(SliderAdapterViewHolder viewHolder, final int position) { final SliderData sliderItem = mSliderItems.get(position); // Glide is use to load image // from url in your imageview. Glide.with(viewHolder.itemView) .load(sliderItem.getImgUrl()) .fitCenter() .into(viewHolder.imageViewBackground); } // this method will return // the count of our list. @Override public int getCount() { return mSliderItems.size(); } static class SliderAdapterViewHolder extends SliderViewAdapter.ViewHolder { // Adapter class for initializing // the views of our slider view. View itemView; ImageView imageViewBackground; public SliderAdapterViewHolder(View itemView) { super(itemView); imageViewBackground = itemView.findViewById(R.id.myimage); this.itemView = itemView; } }}",
"e": 7626,
"s": 5578,
"text": null
},
{
"code": null,
"e": 7674,
"s": 7626,
"text": "Step 8: Working with the MainActivity.java file"
},
{
"code": null,
"e": 7864,
"s": 7674,
"text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 7869,
"s": 7864,
"text": "Java"
},
{
"code": "import android.os.Bundle;import androidx.appcompat.app.AppCompatActivity;import com.smarteist.autoimageslider.SliderView;import java.util.ArrayList; public class MainActivity extends AppCompatActivity { // Urls of our images. String url1 = \"https://www.geeksforgeeks.org/wp-content/uploads/gfg_200X200-1.png\"; String url2 = \"https://qphs.fs.quoracdn.net/main-qimg-8e203d34a6a56345f86f1a92570557ba.webp\"; String url3 = \"https://bizzbucket.co/wp-content/uploads/2020/08/Life-in-The-Metro-Blog-Title-22.png\"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // we are creating array list for storing our image urls. ArrayList<SliderData> sliderDataArrayList = new ArrayList<>(); // initializing the slider view. SliderView sliderView = findViewById(R.id.slider); // adding the urls inside array list sliderDataArrayList.add(new SliderData(url1)); sliderDataArrayList.add(new SliderData(url2)); sliderDataArrayList.add(new SliderData(url3)); // passing this array list inside our adapter class. SliderAdapter adapter = new SliderAdapter(this, sliderDataArrayList); // below method is used to set auto cycle direction in left to // right direction you can change according to requirement. sliderView.setAutoCycleDirection(SliderView.LAYOUT_DIRECTION_LTR); // below method is used to // setadapter to sliderview. sliderView.setSliderAdapter(adapter); // below method is use to set // scroll time in seconds. sliderView.setScrollTimeInSec(3); // to set it scrollable automatically // we use below method. sliderView.setAutoCycle(true); // to start autocycle below method is used. sliderView.startAutoCycle(); }}",
"e": 9863,
"s": 7869,
"text": null
},
{
"code": null,
"e": 9948,
"s": 9863,
"text": "Check out the project on this link: https://github.com/ChaitanyaMunje/GFGImageSlider"
},
{
"code": null,
"e": 9963,
"s": 9948,
"text": "kapoorsagar226"
},
{
"code": null,
"e": 9971,
"s": 9963,
"text": "android"
},
{
"code": null,
"e": 9995,
"s": 9971,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 10003,
"s": 9995,
"text": "Android"
},
{
"code": null,
"e": 10008,
"s": 10003,
"text": "Java"
},
{
"code": null,
"e": 10027,
"s": 10008,
"text": "Technical Scripter"
},
{
"code": null,
"e": 10032,
"s": 10027,
"text": "Java"
},
{
"code": null,
"e": 10040,
"s": 10032,
"text": "Android"
}
]
|
How to redirect to a relative URL in JavaScript? | 31 Oct, 2019
This works in the same way as redirecting to any URL in javascript.
Approach 1: To redirect to a relative URL in JavaScript you can usewindow.location.href = '/path';window.location.href returns the href (URL) of the current pageExample 1: A simple redirecting program<!DOCTYPE html><html><head> <script> function newLocation() { window.location.href="page.html"; } </script></head><body> <input type="button" value="Go to new location" onclick="newLocation()"></body></html>Output:
window.location.href = '/path';
window.location.href returns the href (URL) of the current page
Example 1: A simple redirecting program
<!DOCTYPE html><html><head> <script> function newLocation() { window.location.href="page.html"; } </script></head><body> <input type="button" value="Go to new location" onclick="newLocation()"></body></html>
Output:
Approach 2: To redirect to a relative url you can usedocument.location.href = '../';Both windows.location.href and document.location.href are same.Example 2: A simple redirecting program<!DOCTYPE html><html><head> <script> function newLocation() { document.location.href="page.html"; } </script></head><body> <input type="button" value="Go to new location" onclick="newLocation()"></body></html>Output:NOTE: You can use both methods but for cross browser safety first one is preferred.
document.location.href = '../';
Both windows.location.href and document.location.href are same.
Example 2: A simple redirecting program
<!DOCTYPE html><html><head> <script> function newLocation() { document.location.href="page.html"; } </script></head><body> <input type="button" value="Go to new location" onclick="newLocation()"></body></html>
Output:
NOTE: You can use both methods but for cross browser safety first one is preferred.
JavaScript-Misc
Picked
JavaScript
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Roadmap to Learn JavaScript For Beginners
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Difference Between PUT and PATCH Request
How to Open URL in New Tab using JavaScript ?
How to get character array from string in JavaScript?
JavaScript | console.log() with Examples
How to filter object array based on attributes? | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n31 Oct, 2019"
},
{
"code": null,
"e": 122,
"s": 54,
"text": "This works in the same way as redirecting to any URL in javascript."
},
{
"code": null,
"e": 553,
"s": 122,
"text": "Approach 1: To redirect to a relative URL in JavaScript you can usewindow.location.href = '/path';window.location.href returns the href (URL) of the current pageExample 1: A simple redirecting program<!DOCTYPE html><html><head> <script> function newLocation() { window.location.href=\"page.html\"; } </script></head><body> <input type=\"button\" value=\"Go to new location\" onclick=\"newLocation()\"></body></html>Output:"
},
{
"code": null,
"e": 585,
"s": 553,
"text": "window.location.href = '/path';"
},
{
"code": null,
"e": 649,
"s": 585,
"text": "window.location.href returns the href (URL) of the current page"
},
{
"code": null,
"e": 689,
"s": 649,
"text": "Example 1: A simple redirecting program"
},
{
"code": "<!DOCTYPE html><html><head> <script> function newLocation() { window.location.href=\"page.html\"; } </script></head><body> <input type=\"button\" value=\"Go to new location\" onclick=\"newLocation()\"></body></html>",
"e": 913,
"s": 689,
"text": null
},
{
"code": null,
"e": 921,
"s": 913,
"text": "Output:"
},
{
"code": null,
"e": 1423,
"s": 921,
"text": "Approach 2: To redirect to a relative url you can usedocument.location.href = '../';Both windows.location.href and document.location.href are same.Example 2: A simple redirecting program<!DOCTYPE html><html><head> <script> function newLocation() { document.location.href=\"page.html\"; } </script></head><body> <input type=\"button\" value=\"Go to new location\" onclick=\"newLocation()\"></body></html>Output:NOTE: You can use both methods but for cross browser safety first one is preferred."
},
{
"code": null,
"e": 1455,
"s": 1423,
"text": "document.location.href = '../';"
},
{
"code": null,
"e": 1519,
"s": 1455,
"text": "Both windows.location.href and document.location.href are same."
},
{
"code": null,
"e": 1559,
"s": 1519,
"text": "Example 2: A simple redirecting program"
},
{
"code": "<!DOCTYPE html><html><head> <script> function newLocation() { document.location.href=\"page.html\"; } </script></head><body> <input type=\"button\" value=\"Go to new location\" onclick=\"newLocation()\"></body></html>",
"e": 1785,
"s": 1559,
"text": null
},
{
"code": null,
"e": 1793,
"s": 1785,
"text": "Output:"
},
{
"code": null,
"e": 1877,
"s": 1793,
"text": "NOTE: You can use both methods but for cross browser safety first one is preferred."
},
{
"code": null,
"e": 1893,
"s": 1877,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 1900,
"s": 1893,
"text": "Picked"
},
{
"code": null,
"e": 1911,
"s": 1900,
"text": "JavaScript"
},
{
"code": null,
"e": 1930,
"s": 1911,
"text": "Technical Scripter"
},
{
"code": null,
"e": 2028,
"s": 1930,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2070,
"s": 2028,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 2131,
"s": 2070,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2171,
"s": 2131,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2243,
"s": 2171,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 2295,
"s": 2243,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 2336,
"s": 2295,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 2382,
"s": 2336,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 2436,
"s": 2382,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 2477,
"s": 2436,
"text": "JavaScript | console.log() with Examples"
}
]
|
Find the Nth Pure number | 06 Apr, 2022
Given an integer N, the task is to find the Nth pure number.
A pure number has to satisfy three conditions: 1) It has an even number of digits. 2) All digits are either 4 or 5. 3) And the number is a palindrome.The Pure number series is: 44, 55, 4444, 4554, 5445, 5555, 444444, 445544, 454454, 455554 and so on.
Examples:
Input: 5
Output: 5445
Explanation:
5445 is the 5th pure number in the series.
Input: 19
Output: 45444454
Explanation:
45444454 is the 19th pure number in the series.
Approach: We will assume that 2 numbers make one single block. For each block, there is a 2block number of pure numbers. For pure numbers with 1 block, there are 21 pure numbers; for numbers with 2 blocks, there are 22 numbers, and so on.
Pure numbers starting with 4, start at position 2block – 1 for example, 4444 is at (22 -1 = 3) which means it is, at third position in the series.
Pure numbers starting with 5 starts at position 2block + 2(block-1) -1 for example, 5555 is at (2^2 + 2^1 -1 =5) which means it is at the fifth position in the series.
A pure number in a block is essentially sandwiched between two 4’s or 5’s and is a combination of all previous block numbers. To understand it better, let’s consider the example below:
The first pure number is 44 and the second pure number is 55.
4444 (“4′′+ “44” + “4”) 44 from previous block
4554 (“4′′+ “55” + “4”) 55 from previous block
5445 (“5′′+ “44” + “5”) 44 from previous block
5555 (“5′′+ “55” + “5”) 55 from previous block
This pattern repeats for all the numbers in the series.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
#include<bits/stdc++.h>using namespace std; // CPP program to find// the Nth pure num // Function to check if it// is a power of 2 or notbool isPowerOfTwo(int N){ double number = log(N)/log(2); int checker = int(number); return number - checker == 0;} // if a number belongs to 4 series// it should lie between 2^blocks -1 to// 2^blocks + 2^(blocks-1) -1bool isSeriesFour(int N, int digits){ int upperBound = int(pow(2, digits)+pow(2, digits - 1)-1); int lowerBound = int(pow(2, digits)-1); return (N >= lowerBound) && (N < upperBound);} // Method to find pure numberstring getPureNumber(int N){ string numbers[N + 1]; numbers[0] = ""; int blocks = 0; int displacement = 0; // Iterate from 1 to N for (int i = 1; i < N + 1; i++) { // Check if number is power of two if (isPowerOfTwo(i + 1)) { blocks = blocks + 1; } if (isSeriesFour(i, blocks)) { displacement = int(pow(2, blocks - 1)); // Distance to previous // block numbers numbers[i] = "4" + numbers[i - displacement] + "4"; } else { displacement = int(pow(2, blocks)); // Distance to previous // block numbers numbers[i] = "5" + numbers[i - displacement] + "5"; } } return numbers[N];} // Driver Codeint main(){ int N = 5; string pure = getPureNumber(N); cout << pure << endl;} // This code is contributed by Surendra_Gangwar
// Java program to find// the Nth pure number import java.io.*; class PureNumbers { // Function to check if it // is a power of 2 or not public boolean isPowerOfTwo(int N) { double number = Math.log(N) / Math.log(2); int checker = (int)number; return number - checker == 0; } // if a number belongs to 4 series // it should lie between 2^blocks -1 to // 2^blocks + 2^(blocks-1) -1 public boolean isSeriesFour( int N, int digits) { int upperBound = (int)(Math.pow(2, digits) + Math.pow(2, digits - 1) - 1); int lowerBound = (int)(Math.pow(2, digits) - 1); return (N >= lowerBound) && (N < upperBound); } // Method to find pure number public String getPureNumber(int N) { String[] numbers = new String[N + 1]; numbers[0] = ""; int blocks = 0; int displacement = 0; // Iterate from 1 to N for (int i = 1; i < N + 1; i++) { // Check if number is power of two if (isPowerOfTwo(i + 1)) { blocks = blocks + 1; } if (isSeriesFour(i, blocks)) { displacement = (int)Math.pow( 2, blocks - 1); // Distance to previous // block numbers numbers[i] = "4" + numbers[i - displacement] + "4"; } else { displacement = (int)Math.pow( 2, blocks); // Distance to previous // block numbers numbers[i] = "5" + numbers[i - displacement] + "5"; } } return numbers[N]; } // Driver Code public static void main(String[] args) throws Exception { int N = 5; // Create an object of the class PureNumbers ob = new PureNumbers(); // Function call to find the // Nth pure number String pure = ob.getPureNumber(N); System.out.println(pure); }}
# Python program to find# the Nth pure num # Function to check if it# is a power of 2 or notimport math def isPowerOfTwo(N): number = math.log(N)/math.log(2) checker = math.floor(number) return number - checker == 0 # if a number belongs to 4 series# it should lie between 2^blocks -1 to# 2^blocks + 2^(blocks-1) -1def isSeriesFour(N, digits): upperBound = math.floor(math.pow(2, digits) + math.pow(2, digits - 1)-1) lowerBound = math.floor(math.pow(2, digits)-1) return (N >= lowerBound) and (N < upperBound) # Method to find pure numberdef getPureNumber(N): numbers = ["" for i in range(N + 1)] numbers[0] = "" blocks = 0 displacement = 0 # Iterate from 1 to N for i in range(1,N + 1): # Check if number is power of two if (isPowerOfTwo(i + 1)): blocks = blocks + 1 if (isSeriesFour(i, blocks)): displacement = math.floor(math.pow(2, blocks - 1)) # Distance to previous # block numbers numbers[i] = f"4{numbers[i - displacement]}4" else: displacement = math.floor(math.pow(2, blocks)) # Distance to previous # block numbers numbers[i] = f"5{numbers[i - displacement]}5" return numbers[N] # Driver CodeN = 5pure = getPureNumber(N)print(pure) # This code is contributed by shinjanpatra
// C# program to find// the Nth pure numberusing System; class PureNumbers { // Function to check if it // is a power of 2 or not public bool isPowerOfTwo(int N) { double number = Math.Log(N) / Math.Log(2); int checker = (int)number; return number - checker == 0; } // if a number belongs to 4 series // it should lie between 2^blocks -1 to // 2^blocks + 2^(blocks-1) -1 public bool isSeriesFour( int N, int digits) { int upperBound = (int)(Math.Pow(2, digits) + Math.Pow(2, digits - 1) - 1); int lowerBound = (int)(Math.Pow(2, digits) - 1); return (N >= lowerBound) && (N < upperBound); } // Method to find pure number public string getPureNumber(int N) { string[] numbers = new string[N + 1]; numbers[0] = ""; int blocks = 0; int displacement = 0; // Iterate from 1 to N for (int i = 1; i < N + 1; i++) { // Check if number is power of two if (isPowerOfTwo(i + 1)) { blocks = blocks + 1; } if (isSeriesFour(i, blocks)) { displacement = (int)Math.Pow( 2, blocks - 1); // Distance to previous // block numbers numbers[i] = "4" + numbers[i - displacement] + "4"; } else { displacement = (int)Math.Pow( 2, blocks); // Distance to previous // block numbers numbers[i] = "5" + numbers[i - displacement] + "5"; } } return numbers[N]; } // Driver Code public static void Main() { int N = 5; // Create an object of the class PureNumbers ob = new PureNumbers(); // Function call to find the // Nth pure number string pure = ob.getPureNumber(N); Console.Write(pure); }} // This code is contributed by chitranayal
<script>// Javascript program to find// the Nth pure num // Function to check if it// is a power of 2 or notfunction isPowerOfTwo(N){ let number = Math.log(N)/Math.log(2); let checker = Math.floor(number); return number - checker == 0;} // if a number belongs to 4 series// it should lie between 2^blocks -1 to// 2^blocks + 2^(blocks-1) -1function isSeriesFour(N, digits){ let upperBound = Math.floor(Math.pow(2, digits) + Math.pow(2, digits - 1)-1); let lowerBound = Math.floor(Math.pow(2, digits)-1); return (N >= lowerBound) && (N < upperBound);} // Method to find pure numberfunction getPureNumber(N){ let numbers = new Array(N + 1); numbers[0] = ""; let blocks = 0; let displacement = 0; // Iterate from 1 to N for (let i = 1; i < N + 1; i++) { // Check if number is power of two if (isPowerOfTwo(i + 1)) { blocks = blocks + 1; } if (isSeriesFour(i, blocks)) { displacement = Math.floor(Math.pow(2, blocks - 1)); // Distance to previous // block numbers numbers[i] = "4" + numbers[i - displacement] + "4"; } else { displacement = Math.floor(Math.pow(2, blocks)); // Distance to previous // block numbers numbers[i] = "5" + numbers[i - displacement] + "5"; } } return numbers[N];} // Driver Code let N = 5; let pure = getPureNumber(N); document.write(pure + "<br>"); // This code is contributed by _saurabh_jaiswal</script>
5445
Time Complexity: O(N)
Auxiliary Space: O(N)
ukasp
SURENDRA_GANGWAR
_saurabh_jaiswal
souravmahato348
shinjanpatra
Numbers
series
Arrays
Dynamic Programming
Mathematical
Pattern Searching
Arrays
Dynamic Programming
Mathematical
series
Numbers
Pattern Searching
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
Linear Search
Stack Data Structure (Introduction and Program)
0-1 Knapsack Problem | DP-10
Program for Fibonacci numbers
Longest Common Subsequence | DP-4
Subset Sum Problem | DP-25
Floyd Warshall Algorithm | DP-16 | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n06 Apr, 2022"
},
{
"code": null,
"e": 117,
"s": 54,
"text": "Given an integer N, the task is to find the Nth pure number. "
},
{
"code": null,
"e": 368,
"s": 117,
"text": "A pure number has to satisfy three conditions: 1) It has an even number of digits. 2) All digits are either 4 or 5. 3) And the number is a palindrome.The Pure number series is: 44, 55, 4444, 4554, 5445, 5555, 444444, 445544, 454454, 455554 and so on."
},
{
"code": null,
"e": 379,
"s": 368,
"text": "Examples: "
},
{
"code": null,
"e": 549,
"s": 379,
"text": "Input: 5\nOutput: 5445\nExplanation: \n5445 is the 5th pure number in the series.\n\nInput: 19\nOutput: 45444454\nExplanation: \n45444454 is the 19th pure number in the series. "
},
{
"code": null,
"e": 789,
"s": 549,
"text": "Approach: We will assume that 2 numbers make one single block. For each block, there is a 2block number of pure numbers. For pure numbers with 1 block, there are 21 pure numbers; for numbers with 2 blocks, there are 22 numbers, and so on. "
},
{
"code": null,
"e": 936,
"s": 789,
"text": "Pure numbers starting with 4, start at position 2block – 1 for example, 4444 is at (22 -1 = 3) which means it is, at third position in the series."
},
{
"code": null,
"e": 1104,
"s": 936,
"text": "Pure numbers starting with 5 starts at position 2block + 2(block-1) -1 for example, 5555 is at (2^2 + 2^1 -1 =5) which means it is at the fifth position in the series."
},
{
"code": null,
"e": 1290,
"s": 1104,
"text": "A pure number in a block is essentially sandwiched between two 4’s or 5’s and is a combination of all previous block numbers. To understand it better, let’s consider the example below: "
},
{
"code": null,
"e": 1352,
"s": 1290,
"text": "The first pure number is 44 and the second pure number is 55."
},
{
"code": null,
"e": 1399,
"s": 1352,
"text": "4444 (“4′′+ “44” + “4”) 44 from previous block"
},
{
"code": null,
"e": 1446,
"s": 1399,
"text": "4554 (“4′′+ “55” + “4”) 55 from previous block"
},
{
"code": null,
"e": 1493,
"s": 1446,
"text": "5445 (“5′′+ “44” + “5”) 44 from previous block"
},
{
"code": null,
"e": 1540,
"s": 1493,
"text": "5555 (“5′′+ “55” + “5”) 55 from previous block"
},
{
"code": null,
"e": 1647,
"s": 1540,
"text": "This pattern repeats for all the numbers in the series.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1651,
"s": 1647,
"text": "C++"
},
{
"code": null,
"e": 1656,
"s": 1651,
"text": "Java"
},
{
"code": null,
"e": 1664,
"s": 1656,
"text": "Python3"
},
{
"code": null,
"e": 1667,
"s": 1664,
"text": "C#"
},
{
"code": null,
"e": 1678,
"s": 1667,
"text": "Javascript"
},
{
"code": "#include<bits/stdc++.h>using namespace std; // CPP program to find// the Nth pure num // Function to check if it// is a power of 2 or notbool isPowerOfTwo(int N){ double number = log(N)/log(2); int checker = int(number); return number - checker == 0;} // if a number belongs to 4 series// it should lie between 2^blocks -1 to// 2^blocks + 2^(blocks-1) -1bool isSeriesFour(int N, int digits){ int upperBound = int(pow(2, digits)+pow(2, digits - 1)-1); int lowerBound = int(pow(2, digits)-1); return (N >= lowerBound) && (N < upperBound);} // Method to find pure numberstring getPureNumber(int N){ string numbers[N + 1]; numbers[0] = \"\"; int blocks = 0; int displacement = 0; // Iterate from 1 to N for (int i = 1; i < N + 1; i++) { // Check if number is power of two if (isPowerOfTwo(i + 1)) { blocks = blocks + 1; } if (isSeriesFour(i, blocks)) { displacement = int(pow(2, blocks - 1)); // Distance to previous // block numbers numbers[i] = \"4\" + numbers[i - displacement] + \"4\"; } else { displacement = int(pow(2, blocks)); // Distance to previous // block numbers numbers[i] = \"5\" + numbers[i - displacement] + \"5\"; } } return numbers[N];} // Driver Codeint main(){ int N = 5; string pure = getPureNumber(N); cout << pure << endl;} // This code is contributed by Surendra_Gangwar",
"e": 3186,
"s": 1678,
"text": null
},
{
"code": "// Java program to find// the Nth pure number import java.io.*; class PureNumbers { // Function to check if it // is a power of 2 or not public boolean isPowerOfTwo(int N) { double number = Math.log(N) / Math.log(2); int checker = (int)number; return number - checker == 0; } // if a number belongs to 4 series // it should lie between 2^blocks -1 to // 2^blocks + 2^(blocks-1) -1 public boolean isSeriesFour( int N, int digits) { int upperBound = (int)(Math.pow(2, digits) + Math.pow(2, digits - 1) - 1); int lowerBound = (int)(Math.pow(2, digits) - 1); return (N >= lowerBound) && (N < upperBound); } // Method to find pure number public String getPureNumber(int N) { String[] numbers = new String[N + 1]; numbers[0] = \"\"; int blocks = 0; int displacement = 0; // Iterate from 1 to N for (int i = 1; i < N + 1; i++) { // Check if number is power of two if (isPowerOfTwo(i + 1)) { blocks = blocks + 1; } if (isSeriesFour(i, blocks)) { displacement = (int)Math.pow( 2, blocks - 1); // Distance to previous // block numbers numbers[i] = \"4\" + numbers[i - displacement] + \"4\"; } else { displacement = (int)Math.pow( 2, blocks); // Distance to previous // block numbers numbers[i] = \"5\" + numbers[i - displacement] + \"5\"; } } return numbers[N]; } // Driver Code public static void main(String[] args) throws Exception { int N = 5; // Create an object of the class PureNumbers ob = new PureNumbers(); // Function call to find the // Nth pure number String pure = ob.getPureNumber(N); System.out.println(pure); }}",
"e": 5459,
"s": 3186,
"text": null
},
{
"code": "# Python program to find# the Nth pure num # Function to check if it# is a power of 2 or notimport math def isPowerOfTwo(N): number = math.log(N)/math.log(2) checker = math.floor(number) return number - checker == 0 # if a number belongs to 4 series# it should lie between 2^blocks -1 to# 2^blocks + 2^(blocks-1) -1def isSeriesFour(N, digits): upperBound = math.floor(math.pow(2, digits) + math.pow(2, digits - 1)-1) lowerBound = math.floor(math.pow(2, digits)-1) return (N >= lowerBound) and (N < upperBound) # Method to find pure numberdef getPureNumber(N): numbers = [\"\" for i in range(N + 1)] numbers[0] = \"\" blocks = 0 displacement = 0 # Iterate from 1 to N for i in range(1,N + 1): # Check if number is power of two if (isPowerOfTwo(i + 1)): blocks = blocks + 1 if (isSeriesFour(i, blocks)): displacement = math.floor(math.pow(2, blocks - 1)) # Distance to previous # block numbers numbers[i] = f\"4{numbers[i - displacement]}4\" else: displacement = math.floor(math.pow(2, blocks)) # Distance to previous # block numbers numbers[i] = f\"5{numbers[i - displacement]}5\" return numbers[N] # Driver CodeN = 5pure = getPureNumber(N)print(pure) # This code is contributed by shinjanpatra",
"e": 6824,
"s": 5459,
"text": null
},
{
"code": "// C# program to find// the Nth pure numberusing System; class PureNumbers { // Function to check if it // is a power of 2 or not public bool isPowerOfTwo(int N) { double number = Math.Log(N) / Math.Log(2); int checker = (int)number; return number - checker == 0; } // if a number belongs to 4 series // it should lie between 2^blocks -1 to // 2^blocks + 2^(blocks-1) -1 public bool isSeriesFour( int N, int digits) { int upperBound = (int)(Math.Pow(2, digits) + Math.Pow(2, digits - 1) - 1); int lowerBound = (int)(Math.Pow(2, digits) - 1); return (N >= lowerBound) && (N < upperBound); } // Method to find pure number public string getPureNumber(int N) { string[] numbers = new string[N + 1]; numbers[0] = \"\"; int blocks = 0; int displacement = 0; // Iterate from 1 to N for (int i = 1; i < N + 1; i++) { // Check if number is power of two if (isPowerOfTwo(i + 1)) { blocks = blocks + 1; } if (isSeriesFour(i, blocks)) { displacement = (int)Math.Pow( 2, blocks - 1); // Distance to previous // block numbers numbers[i] = \"4\" + numbers[i - displacement] + \"4\"; } else { displacement = (int)Math.Pow( 2, blocks); // Distance to previous // block numbers numbers[i] = \"5\" + numbers[i - displacement] + \"5\"; } } return numbers[N]; } // Driver Code public static void Main() { int N = 5; // Create an object of the class PureNumbers ob = new PureNumbers(); // Function call to find the // Nth pure number string pure = ob.getPureNumber(N); Console.Write(pure); }} // This code is contributed by chitranayal",
"e": 9102,
"s": 6824,
"text": null
},
{
"code": "<script>// Javascript program to find// the Nth pure num // Function to check if it// is a power of 2 or notfunction isPowerOfTwo(N){ let number = Math.log(N)/Math.log(2); let checker = Math.floor(number); return number - checker == 0;} // if a number belongs to 4 series// it should lie between 2^blocks -1 to// 2^blocks + 2^(blocks-1) -1function isSeriesFour(N, digits){ let upperBound = Math.floor(Math.pow(2, digits) + Math.pow(2, digits - 1)-1); let lowerBound = Math.floor(Math.pow(2, digits)-1); return (N >= lowerBound) && (N < upperBound);} // Method to find pure numberfunction getPureNumber(N){ let numbers = new Array(N + 1); numbers[0] = \"\"; let blocks = 0; let displacement = 0; // Iterate from 1 to N for (let i = 1; i < N + 1; i++) { // Check if number is power of two if (isPowerOfTwo(i + 1)) { blocks = blocks + 1; } if (isSeriesFour(i, blocks)) { displacement = Math.floor(Math.pow(2, blocks - 1)); // Distance to previous // block numbers numbers[i] = \"4\" + numbers[i - displacement] + \"4\"; } else { displacement = Math.floor(Math.pow(2, blocks)); // Distance to previous // block numbers numbers[i] = \"5\" + numbers[i - displacement] + \"5\"; } } return numbers[N];} // Driver Code let N = 5; let pure = getPureNumber(N); document.write(pure + \"<br>\"); // This code is contributed by _saurabh_jaiswal</script>",
"e": 10645,
"s": 9102,
"text": null
},
{
"code": null,
"e": 10650,
"s": 10645,
"text": "5445"
},
{
"code": null,
"e": 10674,
"s": 10652,
"text": "Time Complexity: O(N)"
},
{
"code": null,
"e": 10696,
"s": 10674,
"text": "Auxiliary Space: O(N)"
},
{
"code": null,
"e": 10702,
"s": 10696,
"text": "ukasp"
},
{
"code": null,
"e": 10719,
"s": 10702,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 10736,
"s": 10719,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 10752,
"s": 10736,
"text": "souravmahato348"
},
{
"code": null,
"e": 10765,
"s": 10752,
"text": "shinjanpatra"
},
{
"code": null,
"e": 10773,
"s": 10765,
"text": "Numbers"
},
{
"code": null,
"e": 10780,
"s": 10773,
"text": "series"
},
{
"code": null,
"e": 10787,
"s": 10780,
"text": "Arrays"
},
{
"code": null,
"e": 10807,
"s": 10787,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 10820,
"s": 10807,
"text": "Mathematical"
},
{
"code": null,
"e": 10838,
"s": 10820,
"text": "Pattern Searching"
},
{
"code": null,
"e": 10845,
"s": 10838,
"text": "Arrays"
},
{
"code": null,
"e": 10865,
"s": 10845,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 10878,
"s": 10865,
"text": "Mathematical"
},
{
"code": null,
"e": 10885,
"s": 10878,
"text": "series"
},
{
"code": null,
"e": 10893,
"s": 10885,
"text": "Numbers"
},
{
"code": null,
"e": 10911,
"s": 10893,
"text": "Pattern Searching"
},
{
"code": null,
"e": 11009,
"s": 10911,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11077,
"s": 11009,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 11121,
"s": 11077,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 11153,
"s": 11121,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 11167,
"s": 11153,
"text": "Linear Search"
},
{
"code": null,
"e": 11215,
"s": 11167,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 11244,
"s": 11215,
"text": "0-1 Knapsack Problem | DP-10"
},
{
"code": null,
"e": 11274,
"s": 11244,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 11308,
"s": 11274,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 11335,
"s": 11308,
"text": "Subset Sum Problem | DP-25"
}
]
|
turtle.fillcolor() function in Python | 06 Aug, 2020
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This method is used to return or set the fillcolor. If turtleshape is a polygon, the interior of that polygon is drawn with the newly set fillcolor.
Syntax : turtle.fillcolor(*args)
fillcolor() : Return the current fillcolor as color specification string, possibly in hex-number format.
fillcolor(colorstring) : It is a Tk color specification string, such as “red” or “yellow”.
fillcolor((r, g, b)) : A tuple of r, g, and b, which represent, an RGB color, and each of r, g, and b are in the range 0 to colormode
fillcolor(r, g, b) : r, g, and b represent an RGB color, and each of r, g, and b are in the range 0 to colormode.
Below is the implementation of the above method with some examples :
Example 1 :
Python3
# importing packageimport turtle # set turtleturtle.shape("turtle")turtle.turtlesize(3,3,1) # check by default valueprint(turtle.fillcolor()) # set blue colorturtle.fillcolor("blue") # check fillcolor valueprint(turtle.fillcolor())
Output :
black
blue
Example 2 :
Python3
# importing packageimport turtle # method to draw a stardef star(): for i in range(5): turtle.forward(60) turtle.right(144) # method to set position# and fill color in stardef draw(x,y,col): turtle.up() turtle.setpos(x,y) turtle.down() turtle.fillcolor(col) turtle.begin_fill() star() turtle.end_fill() # Driver Codedraw(-100,0,"red")draw(-50,0,"yellow")draw(0,0,"blue")draw(50,0,"green") # hide the turtleturtle.hideturtle()
Output :
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n06 Aug, 2020"
},
{
"code": null,
"e": 269,
"s": 52,
"text": "The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support."
},
{
"code": null,
"e": 418,
"s": 269,
"text": "This method is used to return or set the fillcolor. If turtleshape is a polygon, the interior of that polygon is drawn with the newly set fillcolor."
},
{
"code": null,
"e": 451,
"s": 418,
"text": "Syntax : turtle.fillcolor(*args)"
},
{
"code": null,
"e": 556,
"s": 451,
"text": "fillcolor() : Return the current fillcolor as color specification string, possibly in hex-number format."
},
{
"code": null,
"e": 647,
"s": 556,
"text": "fillcolor(colorstring) : It is a Tk color specification string, such as “red” or “yellow”."
},
{
"code": null,
"e": 781,
"s": 647,
"text": "fillcolor((r, g, b)) : A tuple of r, g, and b, which represent, an RGB color, and each of r, g, and b are in the range 0 to colormode"
},
{
"code": null,
"e": 896,
"s": 781,
"text": "fillcolor(r, g, b) : r, g, and b represent an RGB color, and each of r, g, and b are in the range 0 to colormode."
},
{
"code": null,
"e": 965,
"s": 896,
"text": "Below is the implementation of the above method with some examples :"
},
{
"code": null,
"e": 977,
"s": 965,
"text": "Example 1 :"
},
{
"code": null,
"e": 985,
"s": 977,
"text": "Python3"
},
{
"code": "# importing packageimport turtle # set turtleturtle.shape(\"turtle\")turtle.turtlesize(3,3,1) # check by default valueprint(turtle.fillcolor()) # set blue colorturtle.fillcolor(\"blue\") # check fillcolor valueprint(turtle.fillcolor())",
"e": 1221,
"s": 985,
"text": null
},
{
"code": null,
"e": 1230,
"s": 1221,
"text": "Output :"
},
{
"code": null,
"e": 1242,
"s": 1230,
"text": "black\nblue\n"
},
{
"code": null,
"e": 1254,
"s": 1242,
"text": "Example 2 :"
},
{
"code": null,
"e": 1262,
"s": 1254,
"text": "Python3"
},
{
"code": "# importing packageimport turtle # method to draw a stardef star(): for i in range(5): turtle.forward(60) turtle.right(144) # method to set position# and fill color in stardef draw(x,y,col): turtle.up() turtle.setpos(x,y) turtle.down() turtle.fillcolor(col) turtle.begin_fill() star() turtle.end_fill() # Driver Codedraw(-100,0,\"red\")draw(-50,0,\"yellow\")draw(0,0,\"blue\")draw(50,0,\"green\") # hide the turtleturtle.hideturtle()",
"e": 1730,
"s": 1262,
"text": null
},
{
"code": null,
"e": 1739,
"s": 1730,
"text": "Output :"
},
{
"code": null,
"e": 1753,
"s": 1739,
"text": "Python-turtle"
},
{
"code": null,
"e": 1760,
"s": 1753,
"text": "Python"
}
]
|
Java Swing | JFileChooser | 01 Jun, 2022
JFileChooser is a part of java Swing package. The java Swing package is part of JavaTM Foundation Classes(JFC) . JFC contains many features that help in building graphical user interface in java . Java Swing provides components such as buttons, panels, dialogs, etc . JFileChooser is a easy and an effective way to prompt the user to choose a file or a directory . In this article we will see how to use JFileChooser in java swing .Constructors of JFileChooser are :
1. JFileChooser() – empty constructor that points to user’s default directory
Java
// Using this process to invoke the constructor,// JFileChooser points to user's default directoryJFileChooser j = new JFileChooser(); // Open the save dialogj.showSaveDialog(null);
Output of the code snippet:
2. JFileChooser(String) – uses the given path
Java
// Using this process to invoke the constructor,// JFileChooser points to the mentioned pathJFileChooser j = new JFileChooser("d:"); // Open the save dialogj.showSaveDialog(null);
Output of the code snippet:
3. JFileChooser(File) – uses the given File as the path
Java
// Using this process to invoke the constructor,// JFileChooser points to the mentioned path// of the file passedJFileChooser j = new JFileChooser(new File("C:\\Users\\pc\\Documents\\New folder\\")); // Open the save dialogj.showSaveDialog(null);
Output of the code snippet:
4. JFileChooser(FileSystemView) – uses the given FileSystemView
Java
// In this process argument passed// is an object of File System ViewJFileChooser j = new JFileChooser(FileSystemView.getFileSystemView()); // Open the save dialogj.showSaveDialog(null);
Output of the code snippet:
5. JFileChooser(String, FileSystemView) – uses the given path and the FileSystemView
Java
// In this process argument passed is an object// of File System View, and a pathJFileChooser j = new JFileChooser("d:", FileSystemView.getFileSystemView()); // Open the save dialogj.showSaveDialog(null);
Output of the code snippet:
6. JFileChooser(File, FileSystemView) – uses the given current directory and the FileSystemView
Java
// In this process argument passed is an object// of File System View and a object of// File classFile f = new File("C:\\Users\\pc\\Documents\\New folder\\");JFileChooser j = new JFileChooser(f, FileSystemView.getFileSystemView()); // Open the save dialogj.showSaveDialog(null);
Output of the code snippet:
Note : The code given above are code snippets not the full code, the code snippets given above should be used to invoke the constructor as per the need and discretion of the programmer, the paths mentioned above are arbitrary. User should set the path according to their need.
Practical Applications of JFileChooser
The following codes will not execute in an online compiler. Please use an offline IDE 1. Creating an open or save dialog using JFileChooser
Java
// Java program to create open or// save dialog using JFileChooserimport java.io.*;import javax.swing.*;import java.awt.event.*;import javax.swing.filechooser.*;class filechooser extends JFrame implements ActionListener { // Jlabel to show the files user selects static JLabel l; // a default constructor filechooser() { } public static void main(String args[]) { // frame to contains GUI elements JFrame f = new JFrame("file chooser"); // set the size of the frame f.setSize(400, 400); // set the frame's visibility f.setVisible(true); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // button to open save dialog JButton button1 = new JButton("save"); // button to open open dialog JButton button2 = new JButton("open"); // make an object of the class filechooser filechooser f1 = new filechooser(); // add action listener to the button to capture user // response on buttons button1.addActionListener(f1); button2.addActionListener(f1); // make a panel to add the buttons and labels JPanel p = new JPanel(); // add buttons to the frame p.add(button1); p.add(button2); // set the label to its initial value l = new JLabel("no file selected"); // add panel to the frame p.add(l); f.add(p); f.show(); } public void actionPerformed(ActionEvent evt) { // if the user presses the save button show the save dialog String com = evt.getActionCommand(); if (com.equals("save")) { // create an object of JFileChooser class JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory()); // invoke the showsSaveDialog function to show the save dialog int r = j.showSaveDialog(null); // if the user selects a file if (r == JFileChooser.APPROVE_OPTION) { // set the label to the path of the selected file l.setText(j.getSelectedFile().getAbsolutePath()); } // if the user cancelled the operation else l.setText("the user cancelled the operation"); } // if the user presses the open dialog show the open dialog else { // create an object of JFileChooser class JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory()); // invoke the showsOpenDialog function to show the save dialog int r = j.showOpenDialog(null); // if the user selects a file if (r == JFileChooser.APPROVE_OPTION) { // set the label to the path of the selected file l.setText(j.getSelectedFile().getAbsolutePath()); } // if the user cancelled the operation else l.setText("the user cancelled the operation"); } }}
2. Use JFileChooser to select directory only
Java
// Java program to use JFileChooser// to select directory onlyimport java.io.*;import javax.swing.*;import java.awt.event.*;import javax.swing.filechooser.*;class filechooser extends JFrame implements ActionListener { // Jlabel to show the files user selects static JLabel l; // a default constructor filechooser() { } public static void main(String args[]) { // frame to contains GUI elements JFrame f = new JFrame("file chooser to select directories"); // set the size of the frame f.setSize(400, 400); // set the frame's visibility f.setVisible(true); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // button to open save dialog JButton button1 = new JButton("save"); // button to open open dialog JButton button2 = new JButton("open"); // make an object of the class filechooser filechooser f1 = new filechooser(); // add action listener to the button to capture user // response on buttons button1.addActionListener(f1); button2.addActionListener(f1); // make a panel to add the buttons and labels JPanel p = new JPanel(); // add buttons to the frame p.add(button1); p.add(button2); // set the label to its initial value l = new JLabel("no file selected"); // add panel to the frame p.add(l); f.add(p); f.show(); } public void actionPerformed(ActionEvent evt) { // if the user presses the save button show the save dialog String com = evt.getActionCommand(); if (com.equals("save")) { // create an object of JFileChooser class JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory()); // set the selection mode to directories only j.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); // invoke the showsSaveDialog function to show the save dialog int r = j.showSaveDialog(null); if (r == JFileChooser.APPROVE_OPTION) { // set the label to the path of the selected directory l.setText(j.getSelectedFile().getAbsolutePath()); } // if the user cancelled the operation else l.setText("the user cancelled the operation"); } // if the user presses the open dialog show the open dialog else { // create an object of JFileChooser class JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory()); // set the selection mode to directories only j.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); // invoke the showsOpenDialog function to show the save dialog int r = j.showOpenDialog(null); if (r == JFileChooser.APPROVE_OPTION) { // set the label to the path of the selected directory l.setText(j.getSelectedFile().getAbsolutePath()); } // if the user cancelled the operation else l.setText("the user cancelled the operation"); } }}
3. Use JFileChooser to allow multiple selection of files
Java
// Java program to use JFileChooser to allow multiple selection of filesimport java.io.*;import javax.swing.*;import java.awt.event.*;import javax.swing.filechooser.*;class filechooser extends JFrame implements ActionListener { // Jlabel to show the files user selects static JLabel l; // a default constructor filechooser() { } public static void main(String args[]) { // frame to contains GUI elements JFrame f = new JFrame("file chooser to select multiple files at a time"); // set the size of the frame f.setSize(400, 400); // set the frame's visibility f.setVisible(true); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // button to open save dialog JButton button1 = new JButton("save"); // button to open open dialog JButton button2 = new JButton("open"); // make an object of the class filechooser filechooser f1 = new filechooser(); // add action listener to the button to capture user // response on buttons button1.addActionListener(f1); button2.addActionListener(f1); // make a panel to add the buttons and labels JPanel p = new JPanel(); // add buttons to the frame p.add(button1); p.add(button2); // set the label to its initial value l = new JLabel("no file selected"); // add panel to the frame p.add(l); f.add(p); f.show(); } public void actionPerformed(ActionEvent evt) { // if the user presses the save button show the save dialog String com = evt.getActionCommand(); if (com.equals("save")) { // create an object of JFileChooser class JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory()); // allow multiple file selection j.setMultiSelectionEnabled(true); // invoke the showsSaveDialog function to show the save dialog int r = j.showSaveDialog(null); if (r == JFileChooser.APPROVE_OPTION) { // get the Selected files File files[] = j.getSelectedFiles(); int t = 0; // set text to blank l.setText(""); // set the label to the path of the selected files while (t++ < files.length) l.setText(l.getText() + " " + files[t - 1].getName()); } // if the user cancelled the operation else l.setText("the user cancelled the operation"); } // if the user presses the open dialog show the open dialog else { // create an object of JFileChooser class JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory()); // allow multiple file selection j.setMultiSelectionEnabled(true); // invoke the showsOpenDialog function to show the save dialog int r = j.showOpenDialog(null); if (r == JFileChooser.APPROVE_OPTION) { // get the Selected files File files[] = j.getSelectedFiles(); // set text to blank l.setText(""); int t = 0; // set the label to the path of the selected files while (t++ < files.length) l.setText(l.getText() + " " + files[t - 1].getName()); } // if the user cancelled the operation else l.setText("the user cancelled the operation"); } }}
4. Use JFileChooser to restrict the type of files shown to the user
Java
// Java program to use JFileChooser to restrict// the type of files shown to the userimport java.io.*;import javax.swing.*;import java.awt.event.*;import javax.swing.filechooser.*;class filechooser extends JFrame implements ActionListener { // Jlabel to show the files user selects static JLabel l; // a default constructor filechooser() { } public static void main(String args[]) { // frame to contains GUI elements JFrame f = new JFrame("file chooser"); // set the size of the frame f.setSize(400, 400); // set the frame's visibility f.setVisible(true); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // button to open save dialog JButton button1 = new JButton("save"); // button to open open dialog JButton button2 = new JButton("open"); // make an object of the class filechooser filechooser f1 = new filechooser(); // add action listener to the button to capture user // response on buttons button1.addActionListener(f1); button2.addActionListener(f1); // make a panel to add the buttons and labels JPanel p = new JPanel(); // add buttons to the frame p.add(button1); p.add(button2); // set the label to its initial value l = new JLabel("no file selected"); // add panel to the frame p.add(l); f.add(p); f.show(); } public void actionPerformed(ActionEvent evt) { // if the user presses the save button show the save dialog String com = evt.getActionCommand(); if (com.equals("save")) { // create an object of JFileChooser class JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory()); // restrict the user to select files of all types j.setAcceptAllFileFilterUsed(false); // set a title for the dialog j.setDialogTitle("Select a .txt file"); // only allow files of .txt extension FileNameExtensionFilter restrict = new FileNameExtensionFilter("Only .txt files", "txt"); j.addChoosableFileFilter(restrict); // invoke the showsSaveDialog function to show the save dialog int r = j.showSaveDialog(null); // if the user selects a file if (r == JFileChooser.APPROVE_OPTION) { // set the label to the path of the selected file l.setText(j.getSelectedFile().getAbsolutePath()); } // if the user cancelled the operation else l.setText("the user cancelled the operation"); } // if the user presses the open dialog show the open dialog else { // create an object of JFileChooser class JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory()); // restrict the user to select files of all types j.setAcceptAllFileFilterUsed(false); // set a title for the dialog j.setDialogTitle("Select a .txt file"); // only allow files of .txt extension FileNameExtensionFilter restrict = new FileNameExtensionFilter("Only .txt files", "txt"); j.addChoosableFileFilter(restrict); // invoke the showsOpenDialog function to show the save dialog int r = j.showOpenDialog(null); // if the user selects a file if (r == JFileChooser.APPROVE_OPTION) { // set the label to the path of the selected file l.setText(j.getSelectedFile().getAbsolutePath()); } // if the user cancelled the operation else l.setText("the user cancelled the operation"); } }}
NOTE : you can also customize the approve button by using the function setApproveButtonText(String) . This will set the text of the approved button to the desired text.
sweetyty
surinderdawra388
Java
Programming Language
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Jun, 2022"
},
{
"code": null,
"e": 497,
"s": 28,
"text": "JFileChooser is a part of java Swing package. The java Swing package is part of JavaTM Foundation Classes(JFC) . JFC contains many features that help in building graphical user interface in java . Java Swing provides components such as buttons, panels, dialogs, etc . JFileChooser is a easy and an effective way to prompt the user to choose a file or a directory . In this article we will see how to use JFileChooser in java swing .Constructors of JFileChooser are : "
},
{
"code": null,
"e": 577,
"s": 497,
"text": "1. JFileChooser() – empty constructor that points to user’s default directory "
},
{
"code": null,
"e": 582,
"s": 577,
"text": "Java"
},
{
"code": "// Using this process to invoke the constructor,// JFileChooser points to user's default directoryJFileChooser j = new JFileChooser(); // Open the save dialogj.showSaveDialog(null);",
"e": 764,
"s": 582,
"text": null
},
{
"code": null,
"e": 794,
"s": 764,
"text": "Output of the code snippet: "
},
{
"code": null,
"e": 844,
"s": 796,
"text": "2. JFileChooser(String) – uses the given path "
},
{
"code": null,
"e": 849,
"s": 844,
"text": "Java"
},
{
"code": "// Using this process to invoke the constructor,// JFileChooser points to the mentioned pathJFileChooser j = new JFileChooser(\"d:\"); // Open the save dialogj.showSaveDialog(null);",
"e": 1029,
"s": 849,
"text": null
},
{
"code": null,
"e": 1059,
"s": 1029,
"text": "Output of the code snippet: "
},
{
"code": null,
"e": 1119,
"s": 1061,
"text": "3. JFileChooser(File) – uses the given File as the path "
},
{
"code": null,
"e": 1124,
"s": 1119,
"text": "Java"
},
{
"code": "// Using this process to invoke the constructor,// JFileChooser points to the mentioned path// of the file passedJFileChooser j = new JFileChooser(new File(\"C:\\\\Users\\\\pc\\\\Documents\\\\New folder\\\\\")); // Open the save dialogj.showSaveDialog(null);",
"e": 1371,
"s": 1124,
"text": null
},
{
"code": null,
"e": 1401,
"s": 1371,
"text": "Output of the code snippet: "
},
{
"code": null,
"e": 1467,
"s": 1401,
"text": "4. JFileChooser(FileSystemView) – uses the given FileSystemView "
},
{
"code": null,
"e": 1472,
"s": 1467,
"text": "Java"
},
{
"code": "// In this process argument passed// is an object of File System ViewJFileChooser j = new JFileChooser(FileSystemView.getFileSystemView()); // Open the save dialogj.showSaveDialog(null);",
"e": 1659,
"s": 1472,
"text": null
},
{
"code": null,
"e": 1689,
"s": 1659,
"text": "Output of the code snippet: "
},
{
"code": null,
"e": 1775,
"s": 1689,
"text": "5. JFileChooser(String, FileSystemView) – uses the given path and the FileSystemView "
},
{
"code": null,
"e": 1780,
"s": 1775,
"text": "Java"
},
{
"code": "// In this process argument passed is an object// of File System View, and a pathJFileChooser j = new JFileChooser(\"d:\", FileSystemView.getFileSystemView()); // Open the save dialogj.showSaveDialog(null);",
"e": 1985,
"s": 1780,
"text": null
},
{
"code": null,
"e": 2015,
"s": 1985,
"text": "Output of the code snippet: "
},
{
"code": null,
"e": 2113,
"s": 2015,
"text": "6. JFileChooser(File, FileSystemView) – uses the given current directory and the FileSystemView "
},
{
"code": null,
"e": 2118,
"s": 2113,
"text": "Java"
},
{
"code": "// In this process argument passed is an object// of File System View and a object of// File classFile f = new File(\"C:\\\\Users\\\\pc\\\\Documents\\\\New folder\\\\\");JFileChooser j = new JFileChooser(f, FileSystemView.getFileSystemView()); // Open the save dialogj.showSaveDialog(null);",
"e": 2397,
"s": 2118,
"text": null
},
{
"code": null,
"e": 2427,
"s": 2397,
"text": "Output of the code snippet: "
},
{
"code": null,
"e": 2705,
"s": 2427,
"text": "Note : The code given above are code snippets not the full code, the code snippets given above should be used to invoke the constructor as per the need and discretion of the programmer, the paths mentioned above are arbitrary. User should set the path according to their need. "
},
{
"code": null,
"e": 2744,
"s": 2705,
"text": "Practical Applications of JFileChooser"
},
{
"code": null,
"e": 2886,
"s": 2744,
"text": "The following codes will not execute in an online compiler. Please use an offline IDE 1. Creating an open or save dialog using JFileChooser "
},
{
"code": null,
"e": 2891,
"s": 2886,
"text": "Java"
},
{
"code": "// Java program to create open or// save dialog using JFileChooserimport java.io.*;import javax.swing.*;import java.awt.event.*;import javax.swing.filechooser.*;class filechooser extends JFrame implements ActionListener { // Jlabel to show the files user selects static JLabel l; // a default constructor filechooser() { } public static void main(String args[]) { // frame to contains GUI elements JFrame f = new JFrame(\"file chooser\"); // set the size of the frame f.setSize(400, 400); // set the frame's visibility f.setVisible(true); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // button to open save dialog JButton button1 = new JButton(\"save\"); // button to open open dialog JButton button2 = new JButton(\"open\"); // make an object of the class filechooser filechooser f1 = new filechooser(); // add action listener to the button to capture user // response on buttons button1.addActionListener(f1); button2.addActionListener(f1); // make a panel to add the buttons and labels JPanel p = new JPanel(); // add buttons to the frame p.add(button1); p.add(button2); // set the label to its initial value l = new JLabel(\"no file selected\"); // add panel to the frame p.add(l); f.add(p); f.show(); } public void actionPerformed(ActionEvent evt) { // if the user presses the save button show the save dialog String com = evt.getActionCommand(); if (com.equals(\"save\")) { // create an object of JFileChooser class JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory()); // invoke the showsSaveDialog function to show the save dialog int r = j.showSaveDialog(null); // if the user selects a file if (r == JFileChooser.APPROVE_OPTION) { // set the label to the path of the selected file l.setText(j.getSelectedFile().getAbsolutePath()); } // if the user cancelled the operation else l.setText(\"the user cancelled the operation\"); } // if the user presses the open dialog show the open dialog else { // create an object of JFileChooser class JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory()); // invoke the showsOpenDialog function to show the save dialog int r = j.showOpenDialog(null); // if the user selects a file if (r == JFileChooser.APPROVE_OPTION) { // set the label to the path of the selected file l.setText(j.getSelectedFile().getAbsolutePath()); } // if the user cancelled the operation else l.setText(\"the user cancelled the operation\"); } }}",
"e": 5934,
"s": 2891,
"text": null
},
{
"code": null,
"e": 5981,
"s": 5934,
"text": "2. Use JFileChooser to select directory only "
},
{
"code": null,
"e": 5986,
"s": 5981,
"text": "Java"
},
{
"code": "// Java program to use JFileChooser// to select directory onlyimport java.io.*;import javax.swing.*;import java.awt.event.*;import javax.swing.filechooser.*;class filechooser extends JFrame implements ActionListener { // Jlabel to show the files user selects static JLabel l; // a default constructor filechooser() { } public static void main(String args[]) { // frame to contains GUI elements JFrame f = new JFrame(\"file chooser to select directories\"); // set the size of the frame f.setSize(400, 400); // set the frame's visibility f.setVisible(true); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // button to open save dialog JButton button1 = new JButton(\"save\"); // button to open open dialog JButton button2 = new JButton(\"open\"); // make an object of the class filechooser filechooser f1 = new filechooser(); // add action listener to the button to capture user // response on buttons button1.addActionListener(f1); button2.addActionListener(f1); // make a panel to add the buttons and labels JPanel p = new JPanel(); // add buttons to the frame p.add(button1); p.add(button2); // set the label to its initial value l = new JLabel(\"no file selected\"); // add panel to the frame p.add(l); f.add(p); f.show(); } public void actionPerformed(ActionEvent evt) { // if the user presses the save button show the save dialog String com = evt.getActionCommand(); if (com.equals(\"save\")) { // create an object of JFileChooser class JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory()); // set the selection mode to directories only j.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); // invoke the showsSaveDialog function to show the save dialog int r = j.showSaveDialog(null); if (r == JFileChooser.APPROVE_OPTION) { // set the label to the path of the selected directory l.setText(j.getSelectedFile().getAbsolutePath()); } // if the user cancelled the operation else l.setText(\"the user cancelled the operation\"); } // if the user presses the open dialog show the open dialog else { // create an object of JFileChooser class JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory()); // set the selection mode to directories only j.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); // invoke the showsOpenDialog function to show the save dialog int r = j.showOpenDialog(null); if (r == JFileChooser.APPROVE_OPTION) { // set the label to the path of the selected directory l.setText(j.getSelectedFile().getAbsolutePath()); } // if the user cancelled the operation else l.setText(\"the user cancelled the operation\"); } }}",
"e": 9198,
"s": 5986,
"text": null
},
{
"code": null,
"e": 9257,
"s": 9198,
"text": "3. Use JFileChooser to allow multiple selection of files "
},
{
"code": null,
"e": 9262,
"s": 9257,
"text": "Java"
},
{
"code": "// Java program to use JFileChooser to allow multiple selection of filesimport java.io.*;import javax.swing.*;import java.awt.event.*;import javax.swing.filechooser.*;class filechooser extends JFrame implements ActionListener { // Jlabel to show the files user selects static JLabel l; // a default constructor filechooser() { } public static void main(String args[]) { // frame to contains GUI elements JFrame f = new JFrame(\"file chooser to select multiple files at a time\"); // set the size of the frame f.setSize(400, 400); // set the frame's visibility f.setVisible(true); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // button to open save dialog JButton button1 = new JButton(\"save\"); // button to open open dialog JButton button2 = new JButton(\"open\"); // make an object of the class filechooser filechooser f1 = new filechooser(); // add action listener to the button to capture user // response on buttons button1.addActionListener(f1); button2.addActionListener(f1); // make a panel to add the buttons and labels JPanel p = new JPanel(); // add buttons to the frame p.add(button1); p.add(button2); // set the label to its initial value l = new JLabel(\"no file selected\"); // add panel to the frame p.add(l); f.add(p); f.show(); } public void actionPerformed(ActionEvent evt) { // if the user presses the save button show the save dialog String com = evt.getActionCommand(); if (com.equals(\"save\")) { // create an object of JFileChooser class JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory()); // allow multiple file selection j.setMultiSelectionEnabled(true); // invoke the showsSaveDialog function to show the save dialog int r = j.showSaveDialog(null); if (r == JFileChooser.APPROVE_OPTION) { // get the Selected files File files[] = j.getSelectedFiles(); int t = 0; // set text to blank l.setText(\"\"); // set the label to the path of the selected files while (t++ < files.length) l.setText(l.getText() + \" \" + files[t - 1].getName()); } // if the user cancelled the operation else l.setText(\"the user cancelled the operation\"); } // if the user presses the open dialog show the open dialog else { // create an object of JFileChooser class JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory()); // allow multiple file selection j.setMultiSelectionEnabled(true); // invoke the showsOpenDialog function to show the save dialog int r = j.showOpenDialog(null); if (r == JFileChooser.APPROVE_OPTION) { // get the Selected files File files[] = j.getSelectedFiles(); // set text to blank l.setText(\"\"); int t = 0; // set the label to the path of the selected files while (t++ < files.length) l.setText(l.getText() + \" \" + files[t - 1].getName()); } // if the user cancelled the operation else l.setText(\"the user cancelled the operation\"); } }}",
"e": 12897,
"s": 9262,
"text": null
},
{
"code": null,
"e": 12967,
"s": 12897,
"text": "4. Use JFileChooser to restrict the type of files shown to the user "
},
{
"code": null,
"e": 12972,
"s": 12967,
"text": "Java"
},
{
"code": "// Java program to use JFileChooser to restrict// the type of files shown to the userimport java.io.*;import javax.swing.*;import java.awt.event.*;import javax.swing.filechooser.*;class filechooser extends JFrame implements ActionListener { // Jlabel to show the files user selects static JLabel l; // a default constructor filechooser() { } public static void main(String args[]) { // frame to contains GUI elements JFrame f = new JFrame(\"file chooser\"); // set the size of the frame f.setSize(400, 400); // set the frame's visibility f.setVisible(true); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // button to open save dialog JButton button1 = new JButton(\"save\"); // button to open open dialog JButton button2 = new JButton(\"open\"); // make an object of the class filechooser filechooser f1 = new filechooser(); // add action listener to the button to capture user // response on buttons button1.addActionListener(f1); button2.addActionListener(f1); // make a panel to add the buttons and labels JPanel p = new JPanel(); // add buttons to the frame p.add(button1); p.add(button2); // set the label to its initial value l = new JLabel(\"no file selected\"); // add panel to the frame p.add(l); f.add(p); f.show(); } public void actionPerformed(ActionEvent evt) { // if the user presses the save button show the save dialog String com = evt.getActionCommand(); if (com.equals(\"save\")) { // create an object of JFileChooser class JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory()); // restrict the user to select files of all types j.setAcceptAllFileFilterUsed(false); // set a title for the dialog j.setDialogTitle(\"Select a .txt file\"); // only allow files of .txt extension FileNameExtensionFilter restrict = new FileNameExtensionFilter(\"Only .txt files\", \"txt\"); j.addChoosableFileFilter(restrict); // invoke the showsSaveDialog function to show the save dialog int r = j.showSaveDialog(null); // if the user selects a file if (r == JFileChooser.APPROVE_OPTION) { // set the label to the path of the selected file l.setText(j.getSelectedFile().getAbsolutePath()); } // if the user cancelled the operation else l.setText(\"the user cancelled the operation\"); } // if the user presses the open dialog show the open dialog else { // create an object of JFileChooser class JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory()); // restrict the user to select files of all types j.setAcceptAllFileFilterUsed(false); // set a title for the dialog j.setDialogTitle(\"Select a .txt file\"); // only allow files of .txt extension FileNameExtensionFilter restrict = new FileNameExtensionFilter(\"Only .txt files\", \"txt\"); j.addChoosableFileFilter(restrict); // invoke the showsOpenDialog function to show the save dialog int r = j.showOpenDialog(null); // if the user selects a file if (r == JFileChooser.APPROVE_OPTION) { // set the label to the path of the selected file l.setText(j.getSelectedFile().getAbsolutePath()); } // if the user cancelled the operation else l.setText(\"the user cancelled the operation\"); } }}",
"e": 16823,
"s": 12972,
"text": null
},
{
"code": null,
"e": 16993,
"s": 16823,
"text": "NOTE : you can also customize the approve button by using the function setApproveButtonText(String) . This will set the text of the approved button to the desired text. "
},
{
"code": null,
"e": 17002,
"s": 16993,
"text": "sweetyty"
},
{
"code": null,
"e": 17019,
"s": 17002,
"text": "surinderdawra388"
},
{
"code": null,
"e": 17024,
"s": 17019,
"text": "Java"
},
{
"code": null,
"e": 17045,
"s": 17024,
"text": "Programming Language"
},
{
"code": null,
"e": 17050,
"s": 17045,
"text": "Java"
}
]
|
Lambda and filter in Python Examples | 09 Jul, 2021
Prerequisite : Lambda in Python
Given a list of numbers, find all numbers divisible by 13.
Input : my_list = [12, 65, 54, 39, 102,
339, 221, 50, 70]
Output : [65, 39, 221]
We can use Lambda function inside the filter() built-in function to find all the numbers divisible by 13 in the list. In Python, anonymous function means that a function is without a name.
The filter() function in Python takes in a function and a list as arguments. This offers an elegant way to filter out all the elements of a sequence “sequence”, for which the function returns True.
# Python Program to find numbers divisible # by thirteen from a list using anonymous # function # Take a list of numbers. my_list = [12, 65, 54, 39, 102, 339, 221, 50, 70, ] # use anonymous function to filter and comparing # if divisible or notresult = list(filter(lambda x: (x % 13 == 0), my_list)) # printing the resultprint(result)
Output:
[65, 39, 221]
Given a list of strings, find all palindromes.
# Python Program to find palindromes in # a list of strings. my_list = ["geeks", "geeg", "keek", "practice", "aa"] # use anonymous function to filter palindromes.# Please refer below article for details of reversed# https://www.geeksforgeeks.org/reverse-string-python-5-different-ways/result = list(filter(lambda x: (x == "".join(reversed(x))), my_list)) # printing the resultprint(result)
Output :
['geeg', 'keek', 'aa']
Given a list of strings and a string str, print all anagrams of str
# Python Program to find all anagrams of str in # a list of strings.from collections import Counter my_list = ["geeks", "geeg", "keegs", "practice", "aa"]str = "eegsk" # use anonymous function to filter anagrams of x.# Please refer below article for details of reversed# https://www.geeksforgeeks.org/anagram-checking-python-collections-counter/result = list(filter(lambda x: (Counter(str) == Counter(x)), my_list)) # printing the resultprint(result)
Output :
['geeks', 'keegs']
Python-Built-in-functions
python-lambda
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n09 Jul, 2021"
},
{
"code": null,
"e": 84,
"s": 52,
"text": "Prerequisite : Lambda in Python"
},
{
"code": null,
"e": 143,
"s": 84,
"text": "Given a list of numbers, find all numbers divisible by 13."
},
{
"code": null,
"e": 247,
"s": 143,
"text": "Input : my_list = [12, 65, 54, 39, 102, \n 339, 221, 50, 70]\nOutput : [65, 39, 221]\n"
},
{
"code": null,
"e": 436,
"s": 247,
"text": "We can use Lambda function inside the filter() built-in function to find all the numbers divisible by 13 in the list. In Python, anonymous function means that a function is without a name."
},
{
"code": null,
"e": 634,
"s": 436,
"text": "The filter() function in Python takes in a function and a list as arguments. This offers an elegant way to filter out all the elements of a sequence “sequence”, for which the function returns True."
},
{
"code": "# Python Program to find numbers divisible # by thirteen from a list using anonymous # function # Take a list of numbers. my_list = [12, 65, 54, 39, 102, 339, 221, 50, 70, ] # use anonymous function to filter and comparing # if divisible or notresult = list(filter(lambda x: (x % 13 == 0), my_list)) # printing the resultprint(result) ",
"e": 974,
"s": 634,
"text": null
},
{
"code": null,
"e": 982,
"s": 974,
"text": "Output:"
},
{
"code": null,
"e": 997,
"s": 982,
"text": "[65, 39, 221]\n"
},
{
"code": null,
"e": 1044,
"s": 997,
"text": "Given a list of strings, find all palindromes."
},
{
"code": "# Python Program to find palindromes in # a list of strings. my_list = [\"geeks\", \"geeg\", \"keek\", \"practice\", \"aa\"] # use anonymous function to filter palindromes.# Please refer below article for details of reversed# https://www.geeksforgeeks.org/reverse-string-python-5-different-ways/result = list(filter(lambda x: (x == \"\".join(reversed(x))), my_list)) # printing the resultprint(result) ",
"e": 1439,
"s": 1044,
"text": null
},
{
"code": null,
"e": 1448,
"s": 1439,
"text": "Output :"
},
{
"code": null,
"e": 1472,
"s": 1448,
"text": "['geeg', 'keek', 'aa']\n"
},
{
"code": null,
"e": 1540,
"s": 1472,
"text": "Given a list of strings and a string str, print all anagrams of str"
},
{
"code": "# Python Program to find all anagrams of str in # a list of strings.from collections import Counter my_list = [\"geeks\", \"geeg\", \"keegs\", \"practice\", \"aa\"]str = \"eegsk\" # use anonymous function to filter anagrams of x.# Please refer below article for details of reversed# https://www.geeksforgeeks.org/anagram-checking-python-collections-counter/result = list(filter(lambda x: (Counter(str) == Counter(x)), my_list)) # printing the resultprint(result) ",
"e": 1996,
"s": 1540,
"text": null
},
{
"code": null,
"e": 2005,
"s": 1996,
"text": "Output :"
},
{
"code": null,
"e": 2025,
"s": 2005,
"text": "['geeks', 'keegs']\n"
},
{
"code": null,
"e": 2051,
"s": 2025,
"text": "Python-Built-in-functions"
},
{
"code": null,
"e": 2065,
"s": 2051,
"text": "python-lambda"
},
{
"code": null,
"e": 2072,
"s": 2065,
"text": "Python"
}
]
|
Multiplication table till N rows where every Kth row is table of K upto Kth term | 30 Jan, 2022
Given a number N, the task is to print N rows where every Kth row consists of the multiplication table of K up to Kth term. Examples:
Input: N = 3 Output: 1 2 4 3 6 9 Explanation: In the above series, in every Kth row, multiplication table of K upto K terms is printed.Input: N = 5 Output: 1 2 4 3 6 9 4 8 12 16 5 10 15 20 25
Approach: The idea is to use two for loops to print the multiplication table. The outer loop in ‘i’ serves as the value of ‘K’ and the inner loop in ‘j’ serves as the terms of the multiplication table of every ‘i’. Each term in the table of ‘i’ can be obtained with the formula ‘i * j’. Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to print multiplication table// till N rows where every Kth row// is the table of K up to Kth term#include <iostream>using namespace std; // Function to print the multiplication table// upto K-th termvoid printMultiples(int N){ // For loop to iterate from 1 to N // where i serves as the value of K for (int i = 1; i <= N; i++) { // Inner loop which at every // iteration goes till i for (int j = 1; j <= i; j++) { // Printing the table value for i cout << (i * j) << " "; } // New line after every row cout << endl; }} // Driver codeint main(){ int N = 5; printMultiples(N); return 0;} // This code is contributed by Rajput-Ji
// Java program to print multiplication table// till N rows where every Kth row// is the table of K up to Kth term class GFG { // Function to print the multiplication table // upto K-th term public static void printMultiples(int N) { // For loop to iterate from 1 to N // where i serves as the value of K for (int i = 1; i <= N; i++) { // Inner loop which at every // iteration goes till i for (int j = 1; j <= i; j++) { // Printing the table value for i System.out.print((i * j) + " "); } // New line after every row System.out.println(); } } // Driver code public static void main(String args[]) { int N = 5; printMultiples(N); }}
# Python3 program to pr multiplication table# till N rows where every Kth row# is the table of K up to Kth term # Function to pr the multiplication table# upto K-th termdef prMultiples(N): # For loop to iterate from 1 to N # where i serves as the value of K for i in range(1, N + 1): # Inner loop which at every # iteration goes till i for j in range(1, i + 1): # Printing the table value for i print((i * j), end = " ") # New line after every row print() # Driver codeif __name__ == '__main__': N = 5 prMultiples(N) # This code is contributed by mohit kumar 29
// C# program to print multiplication table// till N rows where every Kth row// is the table of K up to Kth termusing System; class GFG{ // Function to print the multiplication table // upto K-th term public static void printMultiples(int N) { // For loop to iterate from 1 to N // where i serves as the value of K for (int i = 1; i <= N; i++) { // Inner loop which at every // iteration goes till i for (int j = 1; j <= i; j++) { // Printing the table value for i Console.Write((i * j) + " "); } // New line after every row Console.WriteLine(); } } // Driver code public static void Main(String []args) { int N = 5; printMultiples(N); }} // This code is contributed by Rajput-Ji
<script> // javascript program to print multiplication table// till N rows where every Kth row// is the table of K up to Kth term // Function to print the multiplication table// upto K-th termfunction printMultiples( N){ // For loop to iterate from 1 to N // where i serves as the value of K for (let i = 1; i <= N; i++) { // Inner loop which at every // iteration goes till i for (let j = 1; j <= i; j++) { // Printing the table value for i document.write((i * j) + " "); } // New line after every row document.write("<br/>"); }} // Driver code let N = 5; printMultiples(N); // This code is contributed by todaysgaurav </script>
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
Time Complexity: O(N2)
Auxiliary Space: O(1)
mohit kumar 29
Rajput-Ji
todaysgaurav
subhammahato348
Technical Scripter 2019
Mathematical
School Programming
Technical Scripter
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Jan, 2022"
},
{
"code": null,
"e": 164,
"s": 28,
"text": "Given a number N, the task is to print N rows where every Kth row consists of the multiplication table of K up to Kth term. Examples: "
},
{
"code": null,
"e": 358,
"s": 164,
"text": "Input: N = 3 Output: 1 2 4 3 6 9 Explanation: In the above series, in every Kth row, multiplication table of K upto K terms is printed.Input: N = 5 Output: 1 2 4 3 6 9 4 8 12 16 5 10 15 20 25 "
},
{
"code": null,
"e": 700,
"s": 360,
"text": "Approach: The idea is to use two for loops to print the multiplication table. The outer loop in ‘i’ serves as the value of ‘K’ and the inner loop in ‘j’ serves as the terms of the multiplication table of every ‘i’. Each term in the table of ‘i’ can be obtained with the formula ‘i * j’. Below is the implementation of the above approach: "
},
{
"code": null,
"e": 704,
"s": 700,
"text": "C++"
},
{
"code": null,
"e": 709,
"s": 704,
"text": "Java"
},
{
"code": null,
"e": 717,
"s": 709,
"text": "Python3"
},
{
"code": null,
"e": 720,
"s": 717,
"text": "C#"
},
{
"code": null,
"e": 731,
"s": 720,
"text": "Javascript"
},
{
"code": "// C++ program to print multiplication table// till N rows where every Kth row// is the table of K up to Kth term#include <iostream>using namespace std; // Function to print the multiplication table// upto K-th termvoid printMultiples(int N){ // For loop to iterate from 1 to N // where i serves as the value of K for (int i = 1; i <= N; i++) { // Inner loop which at every // iteration goes till i for (int j = 1; j <= i; j++) { // Printing the table value for i cout << (i * j) << \" \"; } // New line after every row cout << endl; }} // Driver codeint main(){ int N = 5; printMultiples(N); return 0;} // This code is contributed by Rajput-Ji",
"e": 1474,
"s": 731,
"text": null
},
{
"code": "// Java program to print multiplication table// till N rows where every Kth row// is the table of K up to Kth term class GFG { // Function to print the multiplication table // upto K-th term public static void printMultiples(int N) { // For loop to iterate from 1 to N // where i serves as the value of K for (int i = 1; i <= N; i++) { // Inner loop which at every // iteration goes till i for (int j = 1; j <= i; j++) { // Printing the table value for i System.out.print((i * j) + \" \"); } // New line after every row System.out.println(); } } // Driver code public static void main(String args[]) { int N = 5; printMultiples(N); }}",
"e": 2278,
"s": 1474,
"text": null
},
{
"code": "# Python3 program to pr multiplication table# till N rows where every Kth row# is the table of K up to Kth term # Function to pr the multiplication table# upto K-th termdef prMultiples(N): # For loop to iterate from 1 to N # where i serves as the value of K for i in range(1, N + 1): # Inner loop which at every # iteration goes till i for j in range(1, i + 1): # Printing the table value for i print((i * j), end = \" \") # New line after every row print() # Driver codeif __name__ == '__main__': N = 5 prMultiples(N) # This code is contributed by mohit kumar 29",
"e": 2917,
"s": 2278,
"text": null
},
{
"code": "// C# program to print multiplication table// till N rows where every Kth row// is the table of K up to Kth termusing System; class GFG{ // Function to print the multiplication table // upto K-th term public static void printMultiples(int N) { // For loop to iterate from 1 to N // where i serves as the value of K for (int i = 1; i <= N; i++) { // Inner loop which at every // iteration goes till i for (int j = 1; j <= i; j++) { // Printing the table value for i Console.Write((i * j) + \" \"); } // New line after every row Console.WriteLine(); } } // Driver code public static void Main(String []args) { int N = 5; printMultiples(N); }} // This code is contributed by Rajput-Ji",
"e": 3768,
"s": 2917,
"text": null
},
{
"code": "<script> // javascript program to print multiplication table// till N rows where every Kth row// is the table of K up to Kth term // Function to print the multiplication table// upto K-th termfunction printMultiples( N){ // For loop to iterate from 1 to N // where i serves as the value of K for (let i = 1; i <= N; i++) { // Inner loop which at every // iteration goes till i for (let j = 1; j <= i; j++) { // Printing the table value for i document.write((i * j) + \" \"); } // New line after every row document.write(\"<br/>\"); }} // Driver code let N = 5; printMultiples(N); // This code is contributed by todaysgaurav </script>",
"e": 4499,
"s": 3768,
"text": null
},
{
"code": null,
"e": 4539,
"s": 4499,
"text": "1 \n2 4 \n3 6 9 \n4 8 12 16 \n5 10 15 20 25"
},
{
"code": null,
"e": 4564,
"s": 4541,
"text": "Time Complexity: O(N2)"
},
{
"code": null,
"e": 4586,
"s": 4564,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 4601,
"s": 4586,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 4611,
"s": 4601,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 4624,
"s": 4611,
"text": "todaysgaurav"
},
{
"code": null,
"e": 4640,
"s": 4624,
"text": "subhammahato348"
},
{
"code": null,
"e": 4664,
"s": 4640,
"text": "Technical Scripter 2019"
},
{
"code": null,
"e": 4677,
"s": 4664,
"text": "Mathematical"
},
{
"code": null,
"e": 4696,
"s": 4677,
"text": "School Programming"
},
{
"code": null,
"e": 4715,
"s": 4696,
"text": "Technical Scripter"
},
{
"code": null,
"e": 4728,
"s": 4715,
"text": "Mathematical"
}
]
|
How to Sort a TreeMap By Value in Java? | 17 Dec, 2020
In Java Language, a TreeMap always stores key-value pairs which are in sorted order on the basis of the key. TreeMap implements the NavigableMap interface and extends AbstractMap class. TreeMap contains unique keys.
Sorting TreeMap by value in Java
The elements in TreeMap are sorted on the basis of keys.
So, we need to develop our own logic to sort it on the basis of value. We can do it using comparator class
Example 1:
Java
// Java program to Sort a TreeMap By Value import java.util.*;class GFG { public static <K, V extends Comparable<V> > Map<K, V> valueSort(final Map<K, V> map) { // Static Method with return type Map and // extending comparator class which compares values // associated with two keys Comparator<K> valueComparator = new Comparator<K>() { // return comparison results of values of // two keys public int compare(K k1, K k2) { int comp = map.get(k1).compareTo( map.get(k2)); if (comp == 0) return 1; else return comp; } }; // SortedMap created using the comparator Map<K, V> sorted = new TreeMap<K, V>(valueComparator); sorted.putAll(map); return sorted; } public static void main(String[] args) { TreeMap<String, Integer> map = new TreeMap<String, Integer>(); // Put elements to the map map.put("Anshu", 2); map.put("Rajiv", 4); map.put("Chhotu", 3); map.put("Golu", 5); map.put("Sita", 1); // Calling the method valueSort Map sortedMap = valueSort(map); // Get a set of the entries on the sorted map Set set = sortedMap.entrySet(); // Get an iterator Iterator i = set.iterator(); // Display elements while (i.hasNext()) { Map.Entry mp = (Map.Entry)i.next(); System.out.print(mp.getKey() + ": "); System.out.println(mp.getValue()); } }}
Sita: 1
Anshu: 2
Chhotu: 3
Rajiv: 4
Golu: 5
Example 2:
Java
// Java program to Sort a TreeMap By Value import java.util.*; class GFG { // Method for sorting the TreeMap based on values public static <K, V extends Comparable<V> > Map<K, V> valueSort(final Map<K, V> map) { // Static Method with return type Map and // extending comparator class which compares values // associated with two keys Comparator<K> valueComparator = new Comparator<K>() { public int compare(K k1, K k2) { int comp = map.get(k1).compareTo(map.get(k2)); if (comp == 0) return 1; else return comp; } }; // SortedMap created using the comparator Map<K, V> sorted = new TreeMap<K, V>(valueComparator); sorted.putAll(map); return sorted; } public static void main(String[] args) { TreeMap<Integer, String> map = new TreeMap<Integer, String>(); // Put elements to the map map.put(1, "Anshu"); map.put(5, "Rajiv"); map.put(3, "Chhotu"); map.put(2, "Golu"); map.put(4, "Sita"); // Calling the method valueSort Map sortedMap = valueSort(map); // Get a set of the entries on the sorted map Set set = sortedMap.entrySet(); // Get an iterator Iterator i = set.iterator(); while (i.hasNext()) { Map.Entry mp = (Map.Entry)i.next(); System.out.print(mp.getKey() + ": "); System.out.println(mp.getValue()); } }}
1: Anshu
3: Chhotu
2: Golu
5: Rajiv
4: Sita
java-TreeMap
Picked
Java
Java Programs
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
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n17 Dec, 2020"
},
{
"code": null,
"e": 270,
"s": 54,
"text": "In Java Language, a TreeMap always stores key-value pairs which are in sorted order on the basis of the key. TreeMap implements the NavigableMap interface and extends AbstractMap class. TreeMap contains unique keys."
},
{
"code": null,
"e": 303,
"s": 270,
"text": "Sorting TreeMap by value in Java"
},
{
"code": null,
"e": 360,
"s": 303,
"text": "The elements in TreeMap are sorted on the basis of keys."
},
{
"code": null,
"e": 468,
"s": 360,
"text": "So, we need to develop our own logic to sort it on the basis of value. We can do it using comparator class "
},
{
"code": null,
"e": 479,
"s": 468,
"text": "Example 1:"
},
{
"code": null,
"e": 484,
"s": 479,
"text": "Java"
},
{
"code": "// Java program to Sort a TreeMap By Value import java.util.*;class GFG { public static <K, V extends Comparable<V> > Map<K, V> valueSort(final Map<K, V> map) { // Static Method with return type Map and // extending comparator class which compares values // associated with two keys Comparator<K> valueComparator = new Comparator<K>() { // return comparison results of values of // two keys public int compare(K k1, K k2) { int comp = map.get(k1).compareTo( map.get(k2)); if (comp == 0) return 1; else return comp; } }; // SortedMap created using the comparator Map<K, V> sorted = new TreeMap<K, V>(valueComparator); sorted.putAll(map); return sorted; } public static void main(String[] args) { TreeMap<String, Integer> map = new TreeMap<String, Integer>(); // Put elements to the map map.put(\"Anshu\", 2); map.put(\"Rajiv\", 4); map.put(\"Chhotu\", 3); map.put(\"Golu\", 5); map.put(\"Sita\", 1); // Calling the method valueSort Map sortedMap = valueSort(map); // Get a set of the entries on the sorted map Set set = sortedMap.entrySet(); // Get an iterator Iterator i = set.iterator(); // Display elements while (i.hasNext()) { Map.Entry mp = (Map.Entry)i.next(); System.out.print(mp.getKey() + \": \"); System.out.println(mp.getValue()); } }}",
"e": 2269,
"s": 484,
"text": null
},
{
"code": null,
"e": 2313,
"s": 2269,
"text": "Sita: 1\nAnshu: 2\nChhotu: 3\nRajiv: 4\nGolu: 5"
},
{
"code": null,
"e": 2324,
"s": 2313,
"text": "Example 2:"
},
{
"code": null,
"e": 2329,
"s": 2324,
"text": "Java"
},
{
"code": "// Java program to Sort a TreeMap By Value import java.util.*; class GFG { // Method for sorting the TreeMap based on values public static <K, V extends Comparable<V> > Map<K, V> valueSort(final Map<K, V> map) { // Static Method with return type Map and // extending comparator class which compares values // associated with two keys Comparator<K> valueComparator = new Comparator<K>() { public int compare(K k1, K k2) { int comp = map.get(k1).compareTo(map.get(k2)); if (comp == 0) return 1; else return comp; } }; // SortedMap created using the comparator Map<K, V> sorted = new TreeMap<K, V>(valueComparator); sorted.putAll(map); return sorted; } public static void main(String[] args) { TreeMap<Integer, String> map = new TreeMap<Integer, String>(); // Put elements to the map map.put(1, \"Anshu\"); map.put(5, \"Rajiv\"); map.put(3, \"Chhotu\"); map.put(2, \"Golu\"); map.put(4, \"Sita\"); // Calling the method valueSort Map sortedMap = valueSort(map); // Get a set of the entries on the sorted map Set set = sortedMap.entrySet(); // Get an iterator Iterator i = set.iterator(); while (i.hasNext()) { Map.Entry mp = (Map.Entry)i.next(); System.out.print(mp.getKey() + \": \"); System.out.println(mp.getValue()); } }}",
"e": 3964,
"s": 2329,
"text": null
},
{
"code": null,
"e": 4008,
"s": 3964,
"text": "1: Anshu\n3: Chhotu\n2: Golu\n5: Rajiv\n4: Sita"
},
{
"code": null,
"e": 4021,
"s": 4008,
"text": "java-TreeMap"
},
{
"code": null,
"e": 4028,
"s": 4021,
"text": "Picked"
},
{
"code": null,
"e": 4033,
"s": 4028,
"text": "Java"
},
{
"code": null,
"e": 4047,
"s": 4033,
"text": "Java Programs"
},
{
"code": null,
"e": 4052,
"s": 4047,
"text": "Java"
},
{
"code": null,
"e": 4150,
"s": 4052,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4165,
"s": 4150,
"text": "Stream In Java"
},
{
"code": null,
"e": 4186,
"s": 4165,
"text": "Introduction to Java"
},
{
"code": null,
"e": 4207,
"s": 4186,
"text": "Constructors in Java"
},
{
"code": null,
"e": 4226,
"s": 4207,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 4243,
"s": 4226,
"text": "Generics in Java"
},
{
"code": null,
"e": 4269,
"s": 4243,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 4303,
"s": 4269,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 4350,
"s": 4303,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 4388,
"s": 4350,
"text": "Factory method design pattern in Java"
}
]
|
Print all permutations in sorted (lexicographic) order | 12 Jul, 2022
Given a string, print all permutations of it in sorted order. For example, if the input string is “ABC”, then output should be “ABC, ACB, BAC, BCA, CAB, CBA”.
We have discussed a program to print all permutations in this post, but here we must print the permutations in increasing order.
Algorithm to print the permutations lexicographic-ally:Step 1. Sort the given string in non-decreasing order and print it. The first permutation is always the string sorted in non-decreasing order.Step 2. Start generating next higher permutation. Do it until next higher permutation is not possible. If we reach a permutation where all characters are sorted and in non-increasing order, then that permutation is the last permutation.
Steps to generate the next higher permutation: Step 1. Take the previously printed permutation and find the rightmost character in it, which is smaller than its next character. Let us call this character as ‘first character’.Step 2. Now find the ceiling of the ‘first character’. Ceiling is the smallest character on right of ‘first character’, which is greater than ‘first character’. Let us call the ceil character as ‘second character’.Step 3. Swap the two characters found in above 2 steps.Step 4. Sort the substring (in non-decreasing order) after the original index of ‘first character’.
Approach:
1. Let us consider the string “ABCDEF”. Let the previously printed permutation be “DCFEBA”.
2. The next permutation in sorted order should be “DEABCF”.
3. Let us understand above steps to find next permutation. The ‘first character’ will be ‘C’. The ‘second character’ will be ‘E’. After swapping these two, we get “DEFCBA”.
4. The final step is to sort the substring after the character original index of ‘first character’. Finally, we get “DEABCF”.
Following is the implementation of the algorithm.
C++
C
Java
Python3
C#
Javascript
// C++ Program to print all permutations// of a string in sorted order.#include <bits/stdc++.h>using namespace std; /* Following function is needed for library function qsort(). Referhttp://www.cplusplus.com/reference/clibrary/cstdlib/qsort/ */int compare (const void *a, const void * b){ return ( *(char *)a - *(char *)b ); } // A utility function two swap two characters a and bvoid swap (char* a, char* b){ char t = *a; *a = *b; *b = t;} // This function finds the index of the smallest character// which is greater than 'first' and is present in str[l..h]int findCeil (char str[], char first, int l, int h){ // initialize index of ceiling element int ceilIndex = l; // Now iterate through rest of the elements and find // the smallest character greater than 'first' for (int i = l+1; i <= h; i++) if (str[i] > first && str[i] < str[ceilIndex]) ceilIndex = i; return ceilIndex;} // Print all permutations of str in sorted ordervoid sortedPermutations ( char str[] ){ // Get size of string int size = strlen(str); // Sort the string in increasing order qsort( str, size, sizeof( str[0] ), compare ); // Print permutations one by one bool isFinished = false; while ( ! isFinished ) { // print this permutation cout << str << endl; // Find the rightmost character which is // smaller than its next character. // Let us call it 'first char' int i; for ( i = size - 2; i >= 0; --i ) if (str[i] < str[i+1]) break; // If there is no such character, all are // sorted in decreasing order, means we // just printed the last permutation and we are done. if ( i == -1 ) isFinished = true; else { // Find the ceil of 'first char' in // right of first character. // Ceil of a character is the smallest // character greater than it int ceilIndex = findCeil( str, str[i], i + 1, size - 1 ); // Swap first and second characters swap( &str[i], &str[ceilIndex] ); // Sort the string on right of 'first char' qsort( str + i + 1, size - i - 1, sizeof(str[0]), compare ); } }} // Driver program to test above functionint main(){ char str[] = "ABCD"; sortedPermutations( str ); return 0;} // This is code is contributed by rathbhupendra
// Program to print all permutations of a string in sorted order.#include <stdio.h>#include <stdlib.h>#include <string.h> /* Following function is needed for library function qsort(). Referhttp://www.cplusplus.com/reference/clibrary/cstdlib/qsort/ */int compare (const void *a, const void * b){ return ( *(char *)a - *(char *)b ); } // A utility function two swap two characters a and bvoid swap (char* a, char* b){ char t = *a; *a = *b; *b = t;} // This function finds the index of the smallest character// which is greater than 'first' and is present in str[l..h]int findCeil (char str[], char first, int l, int h){ // initialize index of ceiling element int ceilIndex = l; // Now iterate through rest of the elements and find // the smallest character greater than 'first' for (int i = l+1; i <= h; i++) if (str[i] > first && str[i] < str[ceilIndex]) ceilIndex = i; return ceilIndex;} // Print all permutations of str in sorted ordervoid sortedPermutations ( char str[] ){ // Get size of string int size = strlen(str); // Sort the string in increasing order qsort( str, size, sizeof( str[0] ), compare ); // Print permutations one by one bool isFinished = false; while ( ! isFinished ) { // print this permutation printf ("%s \n", str); // Find the rightmost character which is smaller than its next // character. Let us call it 'first char' int i; for ( i = size - 2; i >= 0; --i ) if (str[i] < str[i+1]) break; // If there is no such character, all are sorted in decreasing order, // means we just printed the last permutation and we are done. if ( i == -1 ) isFinished = true; else { // Find the ceil of 'first char' in right of first character. // Ceil of a character is the smallest character greater than it int ceilIndex = findCeil( str, str[i], i + 1, size - 1 ); // Swap first and second characters swap( &str[i], &str[ceilIndex] ); // Sort the string on right of 'first char' qsort( str + i + 1, size - i - 1, sizeof(str[0]), compare ); } }} // Driver program to test above functionint main(){ char str[] = "ABCD"; sortedPermutations( str ); return 0;}
// Java Program to print all permutations// of a string in sorted order. import java.util.*; class GFG{ // This function finds the index of the smallest // character which is greater than 'first' and is // present in str[l..h] static int findCeil(char[] str, char first, int l, int h) { // initialize index of ceiling element int ceilIndex = l; // Now iterate through rest of the elements and find // the smallest character greater than 'first' for (int i = l + 1; i <= h; i++) if (str[i] > first && str[i] < str[ceilIndex]) ceilIndex = i; return ceilIndex; } // Print all permutations of str in sorted order static void sortedPermutations(char[] str) { // Get size of string int size = str.length; // Sort the string in increasing order Arrays.sort(str); // Print permutations one by one boolean isFinished = false; while (!isFinished) { // print this permutation System.out.println(String.valueOf(str)); // Find the rightmost character which is // smaller than its next character. // Let us call it 'first char' int i; for (i = size - 2; i >= 0; --i) if (str[i] < str[i + 1]) break; // If there is no such character, all are // sorted in decreasing order, means we // just printed the last permutation and we are // done. if (i == -1) isFinished = true; else { // Find the ceil of 'first char' in // right of first character. // Ceil of a character is the smallest // character greater than it int ceilIndex = findCeil(str, str[i], i + 1, size - 1); // Swap first and second characters char temp = str[i]; str[i] = str[ceilIndex]; str[ceilIndex] = temp; // Sort the string on right of 'first char' Arrays.sort(str, i + 1, size); } } } // Driver program to test above function public static void main(String[] args) { char[] str = { 'A', 'B', 'C', 'D' }; sortedPermutations(str); }} // This is code is contributed by phasing17
# Python3 Program to print all permutations# of a string in sorted order. # The following function is needed for the sort method # This function finds the index of the smallest character# which is greater than 'first' and is present in str[l..h]def findCeil(str_, first, l, h): # initialize index of ceiling element ceilIndex = l # Now iterate through rest of the elements and find # the smallest character greater than 'first' for i in range(l + 1, h + 1): if (str_[i] > first and str_[i] < str_[ceilIndex]): ceilIndex = i return ceilIndex # Print all permutations of str in sorted orderdef sortedPermutations(str_): # Get size of string size = len(str_) # Sort the string in increasing order str_ = sorted(str_) # Print permutations one by one isFinished = False while (isFinished is False): # print this permutation print("".join(str_)) # Find the rightmost character which is # smaller than its next character. # Let us call it 'first char' i = size - 2 while i >= 0: if (str_[i] < str_[i+1]): break i -= 1 # If there is no such character, all are # sorted in decreasing order, means we # just printed the last permutation and we are done. if (i == -1): isFinished = True else: # Find the ceil of 'first char' in # right of first character. # Ceil of a character is the smallest # character greater than it ceilIndex = findCeil(str_, str_[i], i + 1, size - 1) # Swap first and second characters temp = str_[i] str_[i] = str_[ceilIndex] str_[ceilIndex] = temp # Sort the string on right of 'first char' str_ = str_[:i + 1] + sorted(str_[i + 1:]) # Driver program to test above functionstr_ = "ABCD"sortedPermutations(str_) # This code is contributed by phasing17
// C# Program to print all permutations// of a string in sorted order. using System;using System.Collections.Generic; class GFG { // This function finds the index of the smallest // character which is greater than 'first' and is // present in str[l..h] static int findCeil(char[] str, char first, int l, int h) { // initialize index of ceiling element int ceilIndex = l; // Now iterate through rest of the elements and find // the smallest character greater than 'first' for (int i = l + 1; i <= h; i++) if (str[i] > first && str[i] < str[ceilIndex]) ceilIndex = i; return ceilIndex; } // Print all permutations of str in sorted order static void sortedPermutations(char[] str) { // Get size of string int size = str.Length; // Sort the string in increasing order Array.Sort(str); // Print permutations one by one bool isFinished = false; while (!isFinished) { // print this permutation Console.WriteLine(new string(str)); // Find the rightmost character which is // smaller than its next character. // Let us call it 'first char' int i; for (i = size - 2; i >= 0; --i) if (str[i] < str[i + 1]) break; // If there is no such character, all are // sorted in decreasing order, means we // just printed the last permutation and we are // done. if (i == -1) isFinished = true; else { // Find the ceil of 'first char' in // right of first character. // Ceil of a character is the smallest // character greater than it int ceilIndex = findCeil(str, str[i], i + 1, size - 1); // Swap first and second characters char temp = str[i]; str[i] = str[ceilIndex]; str[ceilIndex] = temp; // Sort the string on right of 'first char' Array.Sort(str, i + 1, size - i - 1); } } } // Driver program to test above function public static void Main(string[] args) { char[] str = { 'A', 'B', 'C', 'D' }; sortedPermutations(str); }} // This is code is contributed by phasing17
// JavaScript Program to print all permutations// of a string in sorted order. /* The following function is needed for the sort method */function compare (a, b){ return a.charCodeAt(0) - b.charCodeAt(0);} // This function finds the index of the smallest character// which is greater than 'first' and is present in str[l..h]function findCeil (str, first, l, h){ // initialize index of ceiling element let ceilIndex = l; // Now iterate through rest of the elements and find // the smallest character greater than 'first' for (let i = l+1; i <= h; i++) if (str[i] > first && str[i] < str[ceilIndex]) ceilIndex = i; return ceilIndex;} // Print all permutations of str in sorted orderfunction sortedPermutations ( str){ // Get size of string let size = str.length; // Sort the string in increasing order str = str.split(""); str.sort(compare); // Print permutations one by one let isFinished = false; while ( ! isFinished ) { // print this permutation console.log(str.join("")); // Find the rightmost character which is // smaller than its next character. // Let us call it 'first char' let i; for ( i = size - 2; i >= 0; --i ) if (str[i] < str[i+1]) break; // If there is no such character, all are // sorted in decreasing order, means we // just printed the last permutation and we are done. if ( i == -1 ) isFinished = true; else { // Find the ceil of 'first char' in // right of first character. // Ceil of a character is the smallest // character greater than it let ceilIndex = findCeil( str, str[i], i + 1, size - 1 ); // Swap first and second characters let temp = str[i]; str[i] = str[ceilIndex]; str[ceilIndex] = temp; // Sort the string on right of 'first char' str1 = str.slice(i + 1); str1.sort(); str = str.slice(0, i + 1); str.push(...str1); } }} // Driver program to test above functionlet str = "ABCD";sortedPermutations( str ); // This code is contributed by phasing17
Output:
ABCD
ABDC
....
....
DCAB
DCBA
Time Complexity: O(n2 x n!)
Auxiliary Space: O(n)
We can optimize step 4 of the above algorithm for finding next permutation. Instead of sorting the subarray after the ‘first character’, we can reverse the subarray, because the subarray we get after swapping is always sorted in non-increasing order. This optimization makes the time complexity as O(n x n!).
See following optimized code.
C++
C
Java
Python3
C#
Javascript
#include <bits/stdc++.h>using namespace std; // An optimized version that uses reverse instead of sort for// finding the next permutation // A utility function to reverse a string str[l..h]void reverse(char str[], int l, int h){ while (l < h) { swap(&str[l], &str[h]); l++; h--; }} // Print all permutations of str in sorted ordervoid sortedPermutations ( char str[] ){ // Get size of string int size = strlen(str); // Sort the string in increasing order qsort( str, size, sizeof( str[0] ), compare ); // Print permutations one by one bool isFinished = false; while ( ! isFinished ) { // print this permutation cout << str << endl; // Find the rightmost character which // is smaller than its next character. // Let us call it 'first char' int i; for ( i = size - 2; i >= 0; --i ) if (str[i] < str[i+1]) break; // If there is no such character, all // are sorted in decreasing order, // means we just printed the last // permutation and we are done. if ( i == -1 ) isFinished = true; else { // Find the ceil of 'first char' in // right of first character. // Ceil of a character is the // smallest character greater than it int ceilIndex = findCeil( str, str[i], i + 1, size - 1 ); // Swap first and second characters swap( &str[i], &str[ceilIndex] ); // reverse the string on right of 'first char' reverse( str, i + 1, size - 1 ); } }} // This code is contributed by rathbhupendra
// An optimized version that uses reverse instead of sort for// finding the next permutation // A utility function to reverse a string str[l..h]void reverse(char str[], int l, int h){ while (l < h) { swap(&str[l], &str[h]); l++; h--; }} // Print all permutations of str in sorted ordervoid sortedPermutations ( char str[] ){ // Get size of string int size = strlen(str); // Sort the string in increasing order qsort( str, size, sizeof( str[0] ), compare ); // Print permutations one by one bool isFinished = false; while ( ! isFinished ) { // print this permutation printf ("%s \n", str); // Find the rightmost character which is smaller than its next // character. Let us call it 'first char' int i; for ( i = size - 2; i >= 0; --i ) if (str[i] < str[i+1]) break; // If there is no such character, all are sorted in decreasing order, // means we just printed the last permutation and we are done. if ( i == -1 ) isFinished = true; else { // Find the ceil of 'first char' in right of first character. // Ceil of a character is the smallest character greater than it int ceilIndex = findCeil( str, str[i], i + 1, size - 1 ); // Swap first and second characters swap( &str[i], &str[ceilIndex] ); // reverse the string on right of 'first char' reverse( str, i + 1, size - 1 ); } }}
import java.util.*; // An optimized version that uses reverse instead of sort// for finding the next permutationclass GFG{ // A utility function two swap two characters a and b static void swap(char[] str, int i, int j) { char t = str[i]; str[i] = str[j]; str[j] = t; } // A utility function to reverse a string str[l..h] static void reverse(char str[], int l, int h) { while (l < h) { swap(str, l, h); l++; h--; } } // This function finds the index of the smallest // character which is greater than 'first' and is // present in str[l..h] static int findCeil(char str[], char first, int l, int h) { // initialize index of ceiling element int ceilIndex = l; // Now iterate through rest of the elements and find // the smallest character greater than 'first' for (int i = l + 1; i <= h; i++) if (str[i] > first && str[i] < str[ceilIndex]) ceilIndex = i; return ceilIndex; } // Print all permutations of str in sorted order static void sortedPermutations(char str[]) { // Get size of string int size = str.length; // Sort the string in increasing order Arrays.sort(str); // Print permutations one by one boolean isFinished = false; while (!isFinished) { // print this permutation System.out.println(str); // Find the rightmost character which is // smaller than its next character. // Let us call it 'first char' int i; for (i = size - 2; i >= 0; --i) if (str[i] < str[i + 1]) break; // If there is no such character, all are // sorted in decreasing order, means we // just printed the last permutation and we are // done. if (i == -1) isFinished = true; else { // Find the ceil of 'first char' in // right of first character. // Ceil of a character is the smallest // character greater than it int ceilIndex = findCeil(str, str[i], i + 1, size - 1); // Swap first and second characters swap(str, i, ceilIndex); // reverse the string on right of 'first // char' reverse(str, i + 1, size - 1); } } } // Driver program to test above function public static void main(String[] args) { char str[] = "ABCD".toCharArray(); sortedPermutations(str); }} // This code is contributed by Swarn Pallav Bhaskar
# An optimized version that uses reverse# instead of sort for finding the next# permutation # A utility function to reverse a# string str[l..h]def reverse(str, l, h): while (l < h) : str[l], str[h] = str[h], str[l] l += 1 h -= 1 return str def findCeil(str, c, k, n): ans = -1 val = c for i in range(k, n + 1): if str[i] > c and str[i] < val: val = str[i] ans = i return ans # Print all permutations of str in sorted orderdef sortedPermutations(str): # Get size of string size = len(str) # Sort the string in increasing order str = ''.join(sorted(str)) # Print permutations one by one isFinished = False while (not isFinished): # Print this permutation print(str) # Find the rightmost character which # is smaller than its next character. # Let us call it 'first char' for i in range(size - 2, -1, -1): if (str[i] < str[i + 1]): break # If there is no such character, all # are sorted in decreasing order, # means we just printed the last # permutation and we are done. if (i == -1): isFinished = True else: # Find the ceil of 'first char' in # right of first character. # Ceil of a character is the # smallest character greater than it ceilIndex = findCeil(str, str[i], i + 1, size - 1) # Swap first and second characters str[i], str[ceilIndex] = str[ceilIndex], str[i] # Reverse the string on right of 'first char' str = reverse(str, i + 1, size - 1) # This code is contributed by rohan07
using System; // An optimized version that uses reverse instead of sort// for finding the next permutationpublic class GFG { // A utility function two swap two characters a and b static void swap(char[] str, int i, int j) { char t = str[i]; str[i] = str[j]; str[j] = t; } // A utility function to reverse a string str[l..h] static void reverse(char []str, int l, int h) { while (l < h) { swap(str, l, h); l++; h--; } } // This function finds the index of the smallest // character which is greater than 'first' and is // present in str[l..h] static int findCeil(char []str, char first, int l, int h) { // initialize index of ceiling element int ceilIndex = l; // Now iterate through rest of the elements and find // the smallest character greater than 'first' for (int i = l + 1; i <= h; i++) if (str[i] > first && str[i] < str[ceilIndex]) ceilIndex = i; return ceilIndex; } // Print all permutations of str in sorted order static void sortedPermutations(char []str) { // Get size of string int size = str.Length; // Sort the string in increasing order Array.Sort(str); // Print permutations one by one bool isFinished = false; while (!isFinished) { // print this permutation Console.WriteLine(str); // Find the rightmost character which is // smaller than its next character. // Let us call it 'first char' int i; for (i = size - 2; i >= 0; --i) if (str[i] < str[i + 1]) break; // If there is no such character, all are // sorted in decreasing order, means we // just printed the last permutation and we are // done. if (i == -1) isFinished = true; else { // Find the ceil of 'first char' in // right of first character. // Ceil of a character is the smallest // character greater than it int ceilIndex = findCeil(str, str[i], i + 1, size - 1); // Swap first and second characters swap(str, i, ceilIndex); // reverse the string on right of 'first // char' reverse(str, i + 1, size - 1); } } } // Driver program to test above function public static void Main(String[] args) { char []str = "ABCD".ToCharArray(); sortedPermutations(str); }} // This code contributed by umadevi9616
<script> // An optimized version that uses reverse instead of sort// for finding the next permutation // A utility function two swap two characters a and b function swap( str , i , j) { var t = str[i]; str[i] = str[j]; str[j] = t; } // A utility function to reverse a string str[l..h] function reverse( str , l , h) { while (l < h) { swap(str, l, h); l++; h--; } } // This function finds the index of the smallest // character which is greater than 'first' and is // present in str[l..h] function findCeil( str, first , l , h) { // initialize index of ceiling element var ceilIndex = l; // Now iterate through rest of the elements and find // the smallest character greater than 'first' for (i = l + 1; i <= h; i++) if (str[i] > first && str[i] < str[ceilIndex]) ceilIndex = i; return ceilIndex; } // Print all permutations of str in sorted order function sortedPermutations(str) { // Get size of string var size = str.length; // Sort the string in increasing order str.sort(); // Print permutations one by one var isFinished = false; while (!isFinished) { // print this permutation var st = str.join(""); document.write(st+"</br>"); // Find the rightmost character which is // smaller than its next character. // Let us call it 'first char' var i; for (i = size - 2; i >= 0; --i) if (str[i] < str[i + 1]) break; // If there is no such character, all are // sorted in decreasing order, means we // just printed the last permutation and we are // done. if (i == -1) isFinished = true; else { // Find the ceil of 'first char' in // right of first character. // Ceil of a character is the smallest // character greater than it var ceilIndex = findCeil(str, str[i], i + 1, size - 1); // Swap first and second characters swap(str, i, ceilIndex); // reverse the string on right of 'first // char' reverse(str, i + 1, size - 1); } } } // Driver program to test above function var str = "ABCD"; str = str.split(""); sortedPermutations(str); // This code is contributed by umadevi9616</script>
Time Complexity: O(n*n!)
Auxiliary Space: O(n)
The above programs print duplicate permutation when characters are repeated. We can avoid it by keeping track of the previous permutation. While printing, if the current permutation is same as previous permutation, we won’t be printing it.This article is compiled by Aashish Barnwal and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
rathbhupendra
shubham_singh
rohan07
swarnpallav
umadevi9616
simranarora5sos
lucidcoder121
phasing17
lexicographic-ordering
permutation
Combinatorial
Mathematical
Strings
Strings
Mathematical
permutation
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n12 Jul, 2022"
},
{
"code": null,
"e": 211,
"s": 52,
"text": "Given a string, print all permutations of it in sorted order. For example, if the input string is “ABC”, then output should be “ABC, ACB, BAC, BCA, CAB, CBA”."
},
{
"code": null,
"e": 340,
"s": 211,
"text": "We have discussed a program to print all permutations in this post, but here we must print the permutations in increasing order."
},
{
"code": null,
"e": 774,
"s": 340,
"text": "Algorithm to print the permutations lexicographic-ally:Step 1. Sort the given string in non-decreasing order and print it. The first permutation is always the string sorted in non-decreasing order.Step 2. Start generating next higher permutation. Do it until next higher permutation is not possible. If we reach a permutation where all characters are sorted and in non-increasing order, then that permutation is the last permutation."
},
{
"code": null,
"e": 1368,
"s": 774,
"text": "Steps to generate the next higher permutation: Step 1. Take the previously printed permutation and find the rightmost character in it, which is smaller than its next character. Let us call this character as ‘first character’.Step 2. Now find the ceiling of the ‘first character’. Ceiling is the smallest character on right of ‘first character’, which is greater than ‘first character’. Let us call the ceil character as ‘second character’.Step 3. Swap the two characters found in above 2 steps.Step 4. Sort the substring (in non-decreasing order) after the original index of ‘first character’."
},
{
"code": null,
"e": 1378,
"s": 1368,
"text": "Approach:"
},
{
"code": null,
"e": 1471,
"s": 1378,
"text": "1. Let us consider the string “ABCDEF”. Let the previously printed permutation be “DCFEBA”. "
},
{
"code": null,
"e": 1532,
"s": 1471,
"text": "2. The next permutation in sorted order should be “DEABCF”. "
},
{
"code": null,
"e": 1706,
"s": 1532,
"text": "3. Let us understand above steps to find next permutation. The ‘first character’ will be ‘C’. The ‘second character’ will be ‘E’. After swapping these two, we get “DEFCBA”. "
},
{
"code": null,
"e": 1833,
"s": 1706,
"text": "4. The final step is to sort the substring after the character original index of ‘first character’. Finally, we get “DEABCF”. "
},
{
"code": null,
"e": 1883,
"s": 1833,
"text": "Following is the implementation of the algorithm."
},
{
"code": null,
"e": 1887,
"s": 1883,
"text": "C++"
},
{
"code": null,
"e": 1889,
"s": 1887,
"text": "C"
},
{
"code": null,
"e": 1894,
"s": 1889,
"text": "Java"
},
{
"code": null,
"e": 1902,
"s": 1894,
"text": "Python3"
},
{
"code": null,
"e": 1905,
"s": 1902,
"text": "C#"
},
{
"code": null,
"e": 1916,
"s": 1905,
"text": "Javascript"
},
{
"code": "// C++ Program to print all permutations// of a string in sorted order.#include <bits/stdc++.h>using namespace std; /* Following function is needed for library function qsort(). Referhttp://www.cplusplus.com/reference/clibrary/cstdlib/qsort/ */int compare (const void *a, const void * b){ return ( *(char *)a - *(char *)b ); } // A utility function two swap two characters a and bvoid swap (char* a, char* b){ char t = *a; *a = *b; *b = t;} // This function finds the index of the smallest character// which is greater than 'first' and is present in str[l..h]int findCeil (char str[], char first, int l, int h){ // initialize index of ceiling element int ceilIndex = l; // Now iterate through rest of the elements and find // the smallest character greater than 'first' for (int i = l+1; i <= h; i++) if (str[i] > first && str[i] < str[ceilIndex]) ceilIndex = i; return ceilIndex;} // Print all permutations of str in sorted ordervoid sortedPermutations ( char str[] ){ // Get size of string int size = strlen(str); // Sort the string in increasing order qsort( str, size, sizeof( str[0] ), compare ); // Print permutations one by one bool isFinished = false; while ( ! isFinished ) { // print this permutation cout << str << endl; // Find the rightmost character which is // smaller than its next character. // Let us call it 'first char' int i; for ( i = size - 2; i >= 0; --i ) if (str[i] < str[i+1]) break; // If there is no such character, all are // sorted in decreasing order, means we // just printed the last permutation and we are done. if ( i == -1 ) isFinished = true; else { // Find the ceil of 'first char' in // right of first character. // Ceil of a character is the smallest // character greater than it int ceilIndex = findCeil( str, str[i], i + 1, size - 1 ); // Swap first and second characters swap( &str[i], &str[ceilIndex] ); // Sort the string on right of 'first char' qsort( str + i + 1, size - i - 1, sizeof(str[0]), compare ); } }} // Driver program to test above functionint main(){ char str[] = \"ABCD\"; sortedPermutations( str ); return 0;} // This is code is contributed by rathbhupendra",
"e": 4345,
"s": 1916,
"text": null
},
{
"code": "// Program to print all permutations of a string in sorted order.#include <stdio.h>#include <stdlib.h>#include <string.h> /* Following function is needed for library function qsort(). Referhttp://www.cplusplus.com/reference/clibrary/cstdlib/qsort/ */int compare (const void *a, const void * b){ return ( *(char *)a - *(char *)b ); } // A utility function two swap two characters a and bvoid swap (char* a, char* b){ char t = *a; *a = *b; *b = t;} // This function finds the index of the smallest character// which is greater than 'first' and is present in str[l..h]int findCeil (char str[], char first, int l, int h){ // initialize index of ceiling element int ceilIndex = l; // Now iterate through rest of the elements and find // the smallest character greater than 'first' for (int i = l+1; i <= h; i++) if (str[i] > first && str[i] < str[ceilIndex]) ceilIndex = i; return ceilIndex;} // Print all permutations of str in sorted ordervoid sortedPermutations ( char str[] ){ // Get size of string int size = strlen(str); // Sort the string in increasing order qsort( str, size, sizeof( str[0] ), compare ); // Print permutations one by one bool isFinished = false; while ( ! isFinished ) { // print this permutation printf (\"%s \\n\", str); // Find the rightmost character which is smaller than its next // character. Let us call it 'first char' int i; for ( i = size - 2; i >= 0; --i ) if (str[i] < str[i+1]) break; // If there is no such character, all are sorted in decreasing order, // means we just printed the last permutation and we are done. if ( i == -1 ) isFinished = true; else { // Find the ceil of 'first char' in right of first character. // Ceil of a character is the smallest character greater than it int ceilIndex = findCeil( str, str[i], i + 1, size - 1 ); // Swap first and second characters swap( &str[i], &str[ceilIndex] ); // Sort the string on right of 'first char' qsort( str + i + 1, size - i - 1, sizeof(str[0]), compare ); } }} // Driver program to test above functionint main(){ char str[] = \"ABCD\"; sortedPermutations( str ); return 0;}",
"e": 6686,
"s": 4345,
"text": null
},
{
"code": "// Java Program to print all permutations// of a string in sorted order. import java.util.*; class GFG{ // This function finds the index of the smallest // character which is greater than 'first' and is // present in str[l..h] static int findCeil(char[] str, char first, int l, int h) { // initialize index of ceiling element int ceilIndex = l; // Now iterate through rest of the elements and find // the smallest character greater than 'first' for (int i = l + 1; i <= h; i++) if (str[i] > first && str[i] < str[ceilIndex]) ceilIndex = i; return ceilIndex; } // Print all permutations of str in sorted order static void sortedPermutations(char[] str) { // Get size of string int size = str.length; // Sort the string in increasing order Arrays.sort(str); // Print permutations one by one boolean isFinished = false; while (!isFinished) { // print this permutation System.out.println(String.valueOf(str)); // Find the rightmost character which is // smaller than its next character. // Let us call it 'first char' int i; for (i = size - 2; i >= 0; --i) if (str[i] < str[i + 1]) break; // If there is no such character, all are // sorted in decreasing order, means we // just printed the last permutation and we are // done. if (i == -1) isFinished = true; else { // Find the ceil of 'first char' in // right of first character. // Ceil of a character is the smallest // character greater than it int ceilIndex = findCeil(str, str[i], i + 1, size - 1); // Swap first and second characters char temp = str[i]; str[i] = str[ceilIndex]; str[ceilIndex] = temp; // Sort the string on right of 'first char' Arrays.sort(str, i + 1, size); } } } // Driver program to test above function public static void main(String[] args) { char[] str = { 'A', 'B', 'C', 'D' }; sortedPermutations(str); }} // This is code is contributed by phasing17",
"e": 8822,
"s": 6686,
"text": null
},
{
"code": "# Python3 Program to print all permutations# of a string in sorted order. # The following function is needed for the sort method # This function finds the index of the smallest character# which is greater than 'first' and is present in str[l..h]def findCeil(str_, first, l, h): # initialize index of ceiling element ceilIndex = l # Now iterate through rest of the elements and find # the smallest character greater than 'first' for i in range(l + 1, h + 1): if (str_[i] > first and str_[i] < str_[ceilIndex]): ceilIndex = i return ceilIndex # Print all permutations of str in sorted orderdef sortedPermutations(str_): # Get size of string size = len(str_) # Sort the string in increasing order str_ = sorted(str_) # Print permutations one by one isFinished = False while (isFinished is False): # print this permutation print(\"\".join(str_)) # Find the rightmost character which is # smaller than its next character. # Let us call it 'first char' i = size - 2 while i >= 0: if (str_[i] < str_[i+1]): break i -= 1 # If there is no such character, all are # sorted in decreasing order, means we # just printed the last permutation and we are done. if (i == -1): isFinished = True else: # Find the ceil of 'first char' in # right of first character. # Ceil of a character is the smallest # character greater than it ceilIndex = findCeil(str_, str_[i], i + 1, size - 1) # Swap first and second characters temp = str_[i] str_[i] = str_[ceilIndex] str_[ceilIndex] = temp # Sort the string on right of 'first char' str_ = str_[:i + 1] + sorted(str_[i + 1:]) # Driver program to test above functionstr_ = \"ABCD\"sortedPermutations(str_) # This code is contributed by phasing17",
"e": 10813,
"s": 8822,
"text": null
},
{
"code": "// C# Program to print all permutations// of a string in sorted order. using System;using System.Collections.Generic; class GFG { // This function finds the index of the smallest // character which is greater than 'first' and is // present in str[l..h] static int findCeil(char[] str, char first, int l, int h) { // initialize index of ceiling element int ceilIndex = l; // Now iterate through rest of the elements and find // the smallest character greater than 'first' for (int i = l + 1; i <= h; i++) if (str[i] > first && str[i] < str[ceilIndex]) ceilIndex = i; return ceilIndex; } // Print all permutations of str in sorted order static void sortedPermutations(char[] str) { // Get size of string int size = str.Length; // Sort the string in increasing order Array.Sort(str); // Print permutations one by one bool isFinished = false; while (!isFinished) { // print this permutation Console.WriteLine(new string(str)); // Find the rightmost character which is // smaller than its next character. // Let us call it 'first char' int i; for (i = size - 2; i >= 0; --i) if (str[i] < str[i + 1]) break; // If there is no such character, all are // sorted in decreasing order, means we // just printed the last permutation and we are // done. if (i == -1) isFinished = true; else { // Find the ceil of 'first char' in // right of first character. // Ceil of a character is the smallest // character greater than it int ceilIndex = findCeil(str, str[i], i + 1, size - 1); // Swap first and second characters char temp = str[i]; str[i] = str[ceilIndex]; str[ceilIndex] = temp; // Sort the string on right of 'first char' Array.Sort(str, i + 1, size - i - 1); } } } // Driver program to test above function public static void Main(string[] args) { char[] str = { 'A', 'B', 'C', 'D' }; sortedPermutations(str); }} // This is code is contributed by phasing17",
"e": 13286,
"s": 10813,
"text": null
},
{
"code": "// JavaScript Program to print all permutations// of a string in sorted order. /* The following function is needed for the sort method */function compare (a, b){ return a.charCodeAt(0) - b.charCodeAt(0);} // This function finds the index of the smallest character// which is greater than 'first' and is present in str[l..h]function findCeil (str, first, l, h){ // initialize index of ceiling element let ceilIndex = l; // Now iterate through rest of the elements and find // the smallest character greater than 'first' for (let i = l+1; i <= h; i++) if (str[i] > first && str[i] < str[ceilIndex]) ceilIndex = i; return ceilIndex;} // Print all permutations of str in sorted orderfunction sortedPermutations ( str){ // Get size of string let size = str.length; // Sort the string in increasing order str = str.split(\"\"); str.sort(compare); // Print permutations one by one let isFinished = false; while ( ! isFinished ) { // print this permutation console.log(str.join(\"\")); // Find the rightmost character which is // smaller than its next character. // Let us call it 'first char' let i; for ( i = size - 2; i >= 0; --i ) if (str[i] < str[i+1]) break; // If there is no such character, all are // sorted in decreasing order, means we // just printed the last permutation and we are done. if ( i == -1 ) isFinished = true; else { // Find the ceil of 'first char' in // right of first character. // Ceil of a character is the smallest // character greater than it let ceilIndex = findCeil( str, str[i], i + 1, size - 1 ); // Swap first and second characters let temp = str[i]; str[i] = str[ceilIndex]; str[ceilIndex] = temp; // Sort the string on right of 'first char' str1 = str.slice(i + 1); str1.sort(); str = str.slice(0, i + 1); str.push(...str1); } }} // Driver program to test above functionlet str = \"ABCD\";sortedPermutations( str ); // This code is contributed by phasing17",
"e": 15522,
"s": 13286,
"text": null
},
{
"code": null,
"e": 15531,
"s": 15522,
"text": "Output: "
},
{
"code": null,
"e": 15561,
"s": 15531,
"text": "ABCD\nABDC\n....\n....\nDCAB\nDCBA"
},
{
"code": null,
"e": 15591,
"s": 15561,
"text": "Time Complexity: O(n2 x n!) "
},
{
"code": null,
"e": 15613,
"s": 15591,
"text": "Auxiliary Space: O(n)"
},
{
"code": null,
"e": 15923,
"s": 15613,
"text": "We can optimize step 4 of the above algorithm for finding next permutation. Instead of sorting the subarray after the ‘first character’, we can reverse the subarray, because the subarray we get after swapping is always sorted in non-increasing order. This optimization makes the time complexity as O(n x n!). "
},
{
"code": null,
"e": 15954,
"s": 15923,
"text": "See following optimized code. "
},
{
"code": null,
"e": 15958,
"s": 15954,
"text": "C++"
},
{
"code": null,
"e": 15960,
"s": 15958,
"text": "C"
},
{
"code": null,
"e": 15965,
"s": 15960,
"text": "Java"
},
{
"code": null,
"e": 15973,
"s": 15965,
"text": "Python3"
},
{
"code": null,
"e": 15976,
"s": 15973,
"text": "C#"
},
{
"code": null,
"e": 15987,
"s": 15976,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std; // An optimized version that uses reverse instead of sort for// finding the next permutation // A utility function to reverse a string str[l..h]void reverse(char str[], int l, int h){ while (l < h) { swap(&str[l], &str[h]); l++; h--; }} // Print all permutations of str in sorted ordervoid sortedPermutations ( char str[] ){ // Get size of string int size = strlen(str); // Sort the string in increasing order qsort( str, size, sizeof( str[0] ), compare ); // Print permutations one by one bool isFinished = false; while ( ! isFinished ) { // print this permutation cout << str << endl; // Find the rightmost character which // is smaller than its next character. // Let us call it 'first char' int i; for ( i = size - 2; i >= 0; --i ) if (str[i] < str[i+1]) break; // If there is no such character, all // are sorted in decreasing order, // means we just printed the last // permutation and we are done. if ( i == -1 ) isFinished = true; else { // Find the ceil of 'first char' in // right of first character. // Ceil of a character is the // smallest character greater than it int ceilIndex = findCeil( str, str[i], i + 1, size - 1 ); // Swap first and second characters swap( &str[i], &str[ceilIndex] ); // reverse the string on right of 'first char' reverse( str, i + 1, size - 1 ); } }} // This code is contributed by rathbhupendra",
"e": 17665,
"s": 15987,
"text": null
},
{
"code": "// An optimized version that uses reverse instead of sort for// finding the next permutation // A utility function to reverse a string str[l..h]void reverse(char str[], int l, int h){ while (l < h) { swap(&str[l], &str[h]); l++; h--; }} // Print all permutations of str in sorted ordervoid sortedPermutations ( char str[] ){ // Get size of string int size = strlen(str); // Sort the string in increasing order qsort( str, size, sizeof( str[0] ), compare ); // Print permutations one by one bool isFinished = false; while ( ! isFinished ) { // print this permutation printf (\"%s \\n\", str); // Find the rightmost character which is smaller than its next // character. Let us call it 'first char' int i; for ( i = size - 2; i >= 0; --i ) if (str[i] < str[i+1]) break; // If there is no such character, all are sorted in decreasing order, // means we just printed the last permutation and we are done. if ( i == -1 ) isFinished = true; else { // Find the ceil of 'first char' in right of first character. // Ceil of a character is the smallest character greater than it int ceilIndex = findCeil( str, str[i], i + 1, size - 1 ); // Swap first and second characters swap( &str[i], &str[ceilIndex] ); // reverse the string on right of 'first char' reverse( str, i + 1, size - 1 ); } }}",
"e": 19196,
"s": 17665,
"text": null
},
{
"code": "import java.util.*; // An optimized version that uses reverse instead of sort// for finding the next permutationclass GFG{ // A utility function two swap two characters a and b static void swap(char[] str, int i, int j) { char t = str[i]; str[i] = str[j]; str[j] = t; } // A utility function to reverse a string str[l..h] static void reverse(char str[], int l, int h) { while (l < h) { swap(str, l, h); l++; h--; } } // This function finds the index of the smallest // character which is greater than 'first' and is // present in str[l..h] static int findCeil(char str[], char first, int l, int h) { // initialize index of ceiling element int ceilIndex = l; // Now iterate through rest of the elements and find // the smallest character greater than 'first' for (int i = l + 1; i <= h; i++) if (str[i] > first && str[i] < str[ceilIndex]) ceilIndex = i; return ceilIndex; } // Print all permutations of str in sorted order static void sortedPermutations(char str[]) { // Get size of string int size = str.length; // Sort the string in increasing order Arrays.sort(str); // Print permutations one by one boolean isFinished = false; while (!isFinished) { // print this permutation System.out.println(str); // Find the rightmost character which is // smaller than its next character. // Let us call it 'first char' int i; for (i = size - 2; i >= 0; --i) if (str[i] < str[i + 1]) break; // If there is no such character, all are // sorted in decreasing order, means we // just printed the last permutation and we are // done. if (i == -1) isFinished = true; else { // Find the ceil of 'first char' in // right of first character. // Ceil of a character is the smallest // character greater than it int ceilIndex = findCeil(str, str[i], i + 1, size - 1); // Swap first and second characters swap(str, i, ceilIndex); // reverse the string on right of 'first // char' reverse(str, i + 1, size - 1); } } } // Driver program to test above function public static void main(String[] args) { char str[] = \"ABCD\".toCharArray(); sortedPermutations(str); }} // This code is contributed by Swarn Pallav Bhaskar",
"e": 21993,
"s": 19196,
"text": null
},
{
"code": "# An optimized version that uses reverse# instead of sort for finding the next# permutation # A utility function to reverse a# string str[l..h]def reverse(str, l, h): while (l < h) : str[l], str[h] = str[h], str[l] l += 1 h -= 1 return str def findCeil(str, c, k, n): ans = -1 val = c for i in range(k, n + 1): if str[i] > c and str[i] < val: val = str[i] ans = i return ans # Print all permutations of str in sorted orderdef sortedPermutations(str): # Get size of string size = len(str) # Sort the string in increasing order str = ''.join(sorted(str)) # Print permutations one by one isFinished = False while (not isFinished): # Print this permutation print(str) # Find the rightmost character which # is smaller than its next character. # Let us call it 'first char' for i in range(size - 2, -1, -1): if (str[i] < str[i + 1]): break # If there is no such character, all # are sorted in decreasing order, # means we just printed the last # permutation and we are done. if (i == -1): isFinished = True else: # Find the ceil of 'first char' in # right of first character. # Ceil of a character is the # smallest character greater than it ceilIndex = findCeil(str, str[i], i + 1, size - 1) # Swap first and second characters str[i], str[ceilIndex] = str[ceilIndex], str[i] # Reverse the string on right of 'first char' str = reverse(str, i + 1, size - 1) # This code is contributed by rohan07",
"e": 23840,
"s": 21993,
"text": null
},
{
"code": "using System; // An optimized version that uses reverse instead of sort// for finding the next permutationpublic class GFG { // A utility function two swap two characters a and b static void swap(char[] str, int i, int j) { char t = str[i]; str[i] = str[j]; str[j] = t; } // A utility function to reverse a string str[l..h] static void reverse(char []str, int l, int h) { while (l < h) { swap(str, l, h); l++; h--; } } // This function finds the index of the smallest // character which is greater than 'first' and is // present in str[l..h] static int findCeil(char []str, char first, int l, int h) { // initialize index of ceiling element int ceilIndex = l; // Now iterate through rest of the elements and find // the smallest character greater than 'first' for (int i = l + 1; i <= h; i++) if (str[i] > first && str[i] < str[ceilIndex]) ceilIndex = i; return ceilIndex; } // Print all permutations of str in sorted order static void sortedPermutations(char []str) { // Get size of string int size = str.Length; // Sort the string in increasing order Array.Sort(str); // Print permutations one by one bool isFinished = false; while (!isFinished) { // print this permutation Console.WriteLine(str); // Find the rightmost character which is // smaller than its next character. // Let us call it 'first char' int i; for (i = size - 2; i >= 0; --i) if (str[i] < str[i + 1]) break; // If there is no such character, all are // sorted in decreasing order, means we // just printed the last permutation and we are // done. if (i == -1) isFinished = true; else { // Find the ceil of 'first char' in // right of first character. // Ceil of a character is the smallest // character greater than it int ceilIndex = findCeil(str, str[i], i + 1, size - 1); // Swap first and second characters swap(str, i, ceilIndex); // reverse the string on right of 'first // char' reverse(str, i + 1, size - 1); } } } // Driver program to test above function public static void Main(String[] args) { char []str = \"ABCD\".ToCharArray(); sortedPermutations(str); }} // This code contributed by umadevi9616",
"e": 26542,
"s": 23840,
"text": null
},
{
"code": "<script> // An optimized version that uses reverse instead of sort// for finding the next permutation // A utility function two swap two characters a and b function swap( str , i , j) { var t = str[i]; str[i] = str[j]; str[j] = t; } // A utility function to reverse a string str[l..h] function reverse( str , l , h) { while (l < h) { swap(str, l, h); l++; h--; } } // This function finds the index of the smallest // character which is greater than 'first' and is // present in str[l..h] function findCeil( str, first , l , h) { // initialize index of ceiling element var ceilIndex = l; // Now iterate through rest of the elements and find // the smallest character greater than 'first' for (i = l + 1; i <= h; i++) if (str[i] > first && str[i] < str[ceilIndex]) ceilIndex = i; return ceilIndex; } // Print all permutations of str in sorted order function sortedPermutations(str) { // Get size of string var size = str.length; // Sort the string in increasing order str.sort(); // Print permutations one by one var isFinished = false; while (!isFinished) { // print this permutation var st = str.join(\"\"); document.write(st+\"</br>\"); // Find the rightmost character which is // smaller than its next character. // Let us call it 'first char' var i; for (i = size - 2; i >= 0; --i) if (str[i] < str[i + 1]) break; // If there is no such character, all are // sorted in decreasing order, means we // just printed the last permutation and we are // done. if (i == -1) isFinished = true; else { // Find the ceil of 'first char' in // right of first character. // Ceil of a character is the smallest // character greater than it var ceilIndex = findCeil(str, str[i], i + 1, size - 1); // Swap first and second characters swap(str, i, ceilIndex); // reverse the string on right of 'first // char' reverse(str, i + 1, size - 1); } } } // Driver program to test above function var str = \"ABCD\"; str = str.split(\"\"); sortedPermutations(str); // This code is contributed by umadevi9616</script>",
"e": 29170,
"s": 26542,
"text": null
},
{
"code": null,
"e": 29195,
"s": 29170,
"text": "Time Complexity: O(n*n!)"
},
{
"code": null,
"e": 29217,
"s": 29195,
"text": "Auxiliary Space: O(n)"
},
{
"code": null,
"e": 29662,
"s": 29217,
"text": "The above programs print duplicate permutation when characters are repeated. We can avoid it by keeping track of the previous permutation. While printing, if the current permutation is same as previous permutation, we won’t be printing it.This article is compiled by Aashish Barnwal and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 29676,
"s": 29662,
"text": "rathbhupendra"
},
{
"code": null,
"e": 29690,
"s": 29676,
"text": "shubham_singh"
},
{
"code": null,
"e": 29698,
"s": 29690,
"text": "rohan07"
},
{
"code": null,
"e": 29710,
"s": 29698,
"text": "swarnpallav"
},
{
"code": null,
"e": 29722,
"s": 29710,
"text": "umadevi9616"
},
{
"code": null,
"e": 29738,
"s": 29722,
"text": "simranarora5sos"
},
{
"code": null,
"e": 29752,
"s": 29738,
"text": "lucidcoder121"
},
{
"code": null,
"e": 29762,
"s": 29752,
"text": "phasing17"
},
{
"code": null,
"e": 29785,
"s": 29762,
"text": "lexicographic-ordering"
},
{
"code": null,
"e": 29797,
"s": 29785,
"text": "permutation"
},
{
"code": null,
"e": 29811,
"s": 29797,
"text": "Combinatorial"
},
{
"code": null,
"e": 29824,
"s": 29811,
"text": "Mathematical"
},
{
"code": null,
"e": 29832,
"s": 29824,
"text": "Strings"
},
{
"code": null,
"e": 29840,
"s": 29832,
"text": "Strings"
},
{
"code": null,
"e": 29853,
"s": 29840,
"text": "Mathematical"
},
{
"code": null,
"e": 29865,
"s": 29853,
"text": "permutation"
},
{
"code": null,
"e": 29879,
"s": 29865,
"text": "Combinatorial"
}
]
|
numpy.true_divide() in Python | 29 Nov, 2018
(arr1, arr22, /, out=None, *, where=True, casting=’same_kind’, order=’K’, dtype=None, ufunc ‘true_divide’) :Array element from first array is divided by the elements from second array(all happens element-wise). Both arr1 and arr2 must have same shape. Returns true division element-wise.
Python traditionally follow ‘floor division’. Regardless of input type, true division adjusts answer to its best.“//” is floor division operator.“/” is true division operator.
Parameters :
arr1 : [array_like]Input array or object which works as numerator.
arr2 : [array_like]Input array or object which works as denominator.
out : [ndarray, None, optional]Output array with same dimensions as Input array,
placed with result.
**kwargs : allows you to pass keyword variable length of argument to a function.
It is used when we want to handle named argument in a function.
where : [array_like, optional]True value means to calculate the universal
functions(ufunc) at that position, False value means to leave the
value in the output alone.
Return :
If inputs are scalar then scalar; otherwise array with arr1 / arr2(element- wise)
i.e. true division
Code 1 : arr1 divided by arr2
# Python program explaining# true_divide() functionimport numpy as np # input_arrayarr1 = [6, 7, 2, 9, 1]arr2 = [2, 3, 4, 5, 6]print ("arr1 : ", arr1)print ("arr1 : ", arr2) # output_arrayout = np.true_divide(arr1, arr2)print ("\nOutput array : \n", out)
Output :
arr1 : [6, 7, 2, 9, 1]
arr1 : [2, 3, 4, 5, 6]
Output array :
[ 3. 2.33333333 0.5 1.8 0.16666667]
Code 2 : elements of arr1 divided by divisor
# Python program explaining# true_divide() functionimport numpy as np # input_arrayarr1 = [2, 7, 3, 11, 4]divisor = 3print ("arr1 : ", arr1) # output_arrayout = np.true_divide(arr1, divisor)print ("\nOutput array : ", out)
Output :
arr1 : [2, 7, 3, 11, 4]
Output array : [ 0.66666667 2.33333333 1. 3.66666667 1.33333333]
Code 3 : Comparison between floor_division(//) and true-division(/)
# Python program explaining# true_divide() functionimport numpy as np # input_arrayarr1 = np.arange(5)arr2 = [2, 3, 4, 5, 6]print ("arr1 : ", arr1)print ("arr1 : ", arr2) # output_arrayout = np.floor_divide(arr1, arr2)out_arr = np.true_divide(arr1, arr2) print ("\nOutput array with floor divide : \n", out)print ("\nOutput array with true divide : \n", out_arr) print ("\nOutput array with floor divide(//) : \n", arr1//arr2)print ("\nOutput array with true divide(/) : \n", arr1/arr2)
Output :
arr1 : [0 1 2 3 4]
arr1 : [2, 3, 4, 5, 6]
Output array with floor divide :
[0 0 0 0 0]
Output array with true divide :
[ 0. 0.33333333 0.5 0.6 0.66666667]
Output array with floor divide(//) :
[0 0 0 0 0]
Output array with true divide(/) :
[ 0. 0.33333333 0.5 0.6 0.66666667]
References :https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.floor_divide.html.
Python numpy-Mathematical Function
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 ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Nov, 2018"
},
{
"code": null,
"e": 316,
"s": 28,
"text": "(arr1, arr22, /, out=None, *, where=True, casting=’same_kind’, order=’K’, dtype=None, ufunc ‘true_divide’) :Array element from first array is divided by the elements from second array(all happens element-wise). Both arr1 and arr2 must have same shape. Returns true division element-wise."
},
{
"code": null,
"e": 492,
"s": 316,
"text": "Python traditionally follow ‘floor division’. Regardless of input type, true division adjusts answer to its best.“//” is floor division operator.“/” is true division operator."
},
{
"code": null,
"e": 505,
"s": 492,
"text": "Parameters :"
},
{
"code": null,
"e": 1121,
"s": 505,
"text": "arr1 : [array_like]Input array or object which works as numerator.\narr2 : [array_like]Input array or object which works as denominator. \nout : [ndarray, None, optional]Output array with same dimensions as Input array, \n placed with result.\n**kwargs : allows you to pass keyword variable length of argument to a function. \n It is used when we want to handle named argument in a function.\nwhere : [array_like, optional]True value means to calculate the universal \n functions(ufunc) at that position, False value means to leave the \n value in the output alone.\n"
},
{
"code": null,
"e": 1130,
"s": 1121,
"text": "Return :"
},
{
"code": null,
"e": 1233,
"s": 1130,
"text": "If inputs are scalar then scalar; otherwise array with arr1 / arr2(element- wise) \ni.e. true division\n"
},
{
"code": null,
"e": 1264,
"s": 1233,
"text": " Code 1 : arr1 divided by arr2"
},
{
"code": "# Python program explaining# true_divide() functionimport numpy as np # input_arrayarr1 = [6, 7, 2, 9, 1]arr2 = [2, 3, 4, 5, 6]print (\"arr1 : \", arr1)print (\"arr1 : \", arr2) # output_arrayout = np.true_divide(arr1, arr2)print (\"\\nOutput array : \\n\", out)",
"e": 1537,
"s": 1264,
"text": null
},
{
"code": null,
"e": 1546,
"s": 1537,
"text": "Output :"
},
{
"code": null,
"e": 1691,
"s": 1546,
"text": "arr1 : [6, 7, 2, 9, 1]\narr1 : [2, 3, 4, 5, 6]\n\nOutput array : \n [ 3. 2.33333333 0.5 1.8 0.16666667]\n"
},
{
"code": null,
"e": 1737,
"s": 1691,
"text": " Code 2 : elements of arr1 divided by divisor"
},
{
"code": "# Python program explaining# true_divide() functionimport numpy as np # input_arrayarr1 = [2, 7, 3, 11, 4]divisor = 3print (\"arr1 : \", arr1) # output_arrayout = np.true_divide(arr1, divisor)print (\"\\nOutput array : \", out)",
"e": 1970,
"s": 1737,
"text": null
},
{
"code": null,
"e": 1979,
"s": 1970,
"text": "Output :"
},
{
"code": null,
"e": 2091,
"s": 1979,
"text": "arr1 : [2, 7, 3, 11, 4]\n\nOutput array : [ 0.66666667 2.33333333 1. 3.66666667 1.33333333]"
},
{
"code": null,
"e": 2160,
"s": 2091,
"text": " Code 3 : Comparison between floor_division(//) and true-division(/)"
},
{
"code": "# Python program explaining# true_divide() functionimport numpy as np # input_arrayarr1 = np.arange(5)arr2 = [2, 3, 4, 5, 6]print (\"arr1 : \", arr1)print (\"arr1 : \", arr2) # output_arrayout = np.floor_divide(arr1, arr2)out_arr = np.true_divide(arr1, arr2) print (\"\\nOutput array with floor divide : \\n\", out)print (\"\\nOutput array with true divide : \\n\", out_arr) print (\"\\nOutput array with floor divide(//) : \\n\", arr1//arr2)print (\"\\nOutput array with true divide(/) : \\n\", arr1/arr2)",
"e": 2671,
"s": 2160,
"text": null
},
{
"code": null,
"e": 2680,
"s": 2671,
"text": "Output :"
},
{
"code": null,
"e": 3040,
"s": 2680,
"text": "arr1 : [0 1 2 3 4]\narr1 : [2, 3, 4, 5, 6]\n\nOutput array with floor divide : \n [0 0 0 0 0]\n\nOutput array with true divide : \n [ 0. 0.33333333 0.5 0.6 0.66666667]\n\nOutput array with floor divide(//) : \n [0 0 0 0 0]\n\nOutput array with true divide(/) : \n [ 0. 0.33333333 0.5 0.6 0.66666667]"
},
{
"code": null,
"e": 3137,
"s": 3040,
"text": "References :https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.floor_divide.html."
},
{
"code": null,
"e": 3172,
"s": 3137,
"text": "Python numpy-Mathematical Function"
},
{
"code": null,
"e": 3185,
"s": 3172,
"text": "Python-numpy"
},
{
"code": null,
"e": 3192,
"s": 3185,
"text": "Python"
},
{
"code": null,
"e": 3290,
"s": 3192,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3322,
"s": 3290,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3349,
"s": 3322,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3370,
"s": 3349,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3393,
"s": 3370,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3449,
"s": 3393,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 3480,
"s": 3449,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 3522,
"s": 3480,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 3564,
"s": 3522,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 3603,
"s": 3564,
"text": "Python | Get unique values from a list"
}
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.