title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
Progress Bars in Python - GeeksforGeeks
|
17 Aug, 2020
Understandably, we get a little impatient when we do not know how much time a process is going to take, for example, a for loop or a file downloading or an application starting up.
To distract us from that we were given the libraries tqdm and progressbar in Python language which allows us to give a visual illustration of the process completion time using a progress bar. Loading bars are often seen on game screens as the resources required for the game to run are being acquired to the main memory.
It wraps an iterable with the tqdm to decorate it with the methods built-in with tqdm and make a loading bar. This will take the users’ mind off of how long the process is taking to complete.
All we need to do is, install the tqdm package by typing this line in your terminal and start writing the code.
->pip install tqdm
And type this code in your editor.
from tqdm import tqdm for i in tqdm (range (100), desc="Loading..."): pass
Output:
This gives a very fast loading bar because there’s nothing in the loop., you can replace the pass keyword with whatever work you want to do in the for loop.
from tqdm import tqdmimport time for i in tqdm (range (101), desc="Loading...", ascii=False, ncols=75): time.sleep(0.01) print("Complete.")
Output:
For command-line interface
pip install progressbar
(or)
pip install progressbar2
It does everything the same as tqdm package, that is it decorates the iterable with the built-in widgets to make an animated progress bar or even a colorful one. Widgets are objects which display depending on the progress bar.
However, the progress bar and the progress bar 2 packages have a lot of extra, useful methods than the tqdm package. For example, we can make an animated loading bar.
import progressbarimport time # Function to create def animated_marker(): widgets = ['Loading: ', progressbar.AnimatedMarker()] bar = progressbar.ProgressBar(widgets=widgets).start() for i in range(50): time.sleep(0.1) bar.update(i) # Driver's codeanimated_marker()
Output:
In progressbar.AnimatedMarker(), we can pass any sequence of characters to animate. The default arguments are '|/-\|'
Here’s another example using some of the commonly used widgets of the ProgressBar class.
import timeimport progressbar widgets = [' [', progressbar.Timer(format= 'elapsed time: %(elapsed)s'), '] ', progressbar.Bar('*'),' (', progressbar.ETA(), ') ', ] bar = progressbar.ProgressBar(max_value=200, widgets=widgets).start() for i in range(200): time.sleep(0.1) bar.update(i)
Output:
Akanksha_Rai
Python-gui
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
How To Convert Python Dictionary To JSON?
Convert integer to string in Python
|
[
{
"code": null,
"e": 25683,
"s": 25655,
"text": "\n17 Aug, 2020"
},
{
"code": null,
"e": 25864,
"s": 25683,
"text": "Understandably, we get a little impatient when we do not know how much time a process is going to take, for example, a for loop or a file downloading or an application starting up."
},
{
"code": null,
"e": 26185,
"s": 25864,
"text": "To distract us from that we were given the libraries tqdm and progressbar in Python language which allows us to give a visual illustration of the process completion time using a progress bar. Loading bars are often seen on game screens as the resources required for the game to run are being acquired to the main memory."
},
{
"code": null,
"e": 26377,
"s": 26185,
"text": "It wraps an iterable with the tqdm to decorate it with the methods built-in with tqdm and make a loading bar. This will take the users’ mind off of how long the process is taking to complete."
},
{
"code": null,
"e": 26489,
"s": 26377,
"text": "All we need to do is, install the tqdm package by typing this line in your terminal and start writing the code."
},
{
"code": null,
"e": 26508,
"s": 26489,
"text": "->pip install tqdm"
},
{
"code": null,
"e": 26543,
"s": 26508,
"text": "And type this code in your editor."
},
{
"code": "from tqdm import tqdm for i in tqdm (range (100), desc=\"Loading...\"): pass",
"e": 26622,
"s": 26543,
"text": null
},
{
"code": null,
"e": 26630,
"s": 26622,
"text": "Output:"
},
{
"code": null,
"e": 26787,
"s": 26630,
"text": "This gives a very fast loading bar because there’s nothing in the loop., you can replace the pass keyword with whatever work you want to do in the for loop."
},
{
"code": "from tqdm import tqdmimport time for i in tqdm (range (101), desc=\"Loading...\", ascii=False, ncols=75): time.sleep(0.01) print(\"Complete.\")",
"e": 26968,
"s": 26787,
"text": null
},
{
"code": null,
"e": 26976,
"s": 26968,
"text": "Output:"
},
{
"code": null,
"e": 27003,
"s": 26976,
"text": "For command-line interface"
},
{
"code": null,
"e": 27058,
"s": 27003,
"text": "pip install progressbar \n(or)\npip install progressbar2"
},
{
"code": null,
"e": 27285,
"s": 27058,
"text": "It does everything the same as tqdm package, that is it decorates the iterable with the built-in widgets to make an animated progress bar or even a colorful one. Widgets are objects which display depending on the progress bar."
},
{
"code": null,
"e": 27452,
"s": 27285,
"text": "However, the progress bar and the progress bar 2 packages have a lot of extra, useful methods than the tqdm package. For example, we can make an animated loading bar."
},
{
"code": "import progressbarimport time # Function to create def animated_marker(): widgets = ['Loading: ', progressbar.AnimatedMarker()] bar = progressbar.ProgressBar(widgets=widgets).start() for i in range(50): time.sleep(0.1) bar.update(i) # Driver's codeanimated_marker()",
"e": 27765,
"s": 27452,
"text": null
},
{
"code": null,
"e": 27773,
"s": 27765,
"text": "Output:"
},
{
"code": null,
"e": 27891,
"s": 27773,
"text": "In progressbar.AnimatedMarker(), we can pass any sequence of characters to animate. The default arguments are '|/-\\|'"
},
{
"code": null,
"e": 27980,
"s": 27891,
"text": "Here’s another example using some of the commonly used widgets of the ProgressBar class."
},
{
"code": "import timeimport progressbar widgets = [' [', progressbar.Timer(format= 'elapsed time: %(elapsed)s'), '] ', progressbar.Bar('*'),' (', progressbar.ETA(), ') ', ] bar = progressbar.ProgressBar(max_value=200, widgets=widgets).start() for i in range(200): time.sleep(0.1) bar.update(i)",
"e": 28348,
"s": 27980,
"text": null
},
{
"code": null,
"e": 28356,
"s": 28348,
"text": "Output:"
},
{
"code": null,
"e": 28369,
"s": 28356,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 28380,
"s": 28369,
"text": "Python-gui"
},
{
"code": null,
"e": 28387,
"s": 28380,
"text": "Python"
},
{
"code": null,
"e": 28485,
"s": 28387,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28503,
"s": 28485,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28535,
"s": 28503,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28557,
"s": 28535,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28599,
"s": 28557,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28625,
"s": 28599,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28669,
"s": 28625,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 28698,
"s": 28669,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 28735,
"s": 28698,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 28777,
"s": 28735,
"text": "How To Convert Python Dictionary To JSON?"
}
] |
Playit
|
You can change the text-align by clicking on one of the properties on the left.
This text is where you will see the result of the selected text-align property.
|
[] |
UUID getLeastSignificantBits() Method in Java with Examples - GeeksforGeeks
|
27 Dec, 2018
The UUIDs are 128-bit values. The getLeastSignificantBits() Method of UUID class in Java is used to get the least significant 64 bits of this UUID.
Syntax:
public long getLeastSignificantBits()
Parameters: The method does not take any parameters.
Return Value: The method returns an integer value which is the least significant 64 bit of this 128 valued UUID.
Below programs illustrate the working of getLeastSignificantBits() method:
Program 1:
// Java code to illustrate// getLeastSignificantBits() method import java.util.*; public class UUID_Demo { public static void main(String[] args) { // Creating two UUIDs UUID UUID_1 = UUID .fromString( "58e0a7d7-eebc-11d8-9669-0800200c9a66"); // Displaying the UUID System.out.println("UUID: " + UUID_1); // Displaying the value of UUID System.out.println("The value is: " + UUID_1.clockSequence()); // Getting the least significant 64 bit System.out.println("The least significant 64 bit: " + UUID_1 .getLeastSignificantBits()); }}
UUID: 58e0a7d7-eebc-11d8-9669-0800200c9a66
The value is: 5737
The least significant 64 bit: -7608541298835023258
Program 2:
// Java code to illustrate// getLeastSignificantBits() method import java.util.*; public class UUID_Demo { public static void main(String[] args) { // Creating two UUIDs UUID UUID_1 = UUID .fromString( "58e0a7d7-eebc-11d8-9669-0800200c9a66"); // Displaying the UUID System.out.println("UUID: " + UUID_1); // Displaying the value of UUID System.out.println("The value is: " + UUID_1.clockSequence()); // Getting the least significant 64 bit System.out.println("The least significant 64 bit: " + UUID_1.getLeastSignificantBits()); }}
UUID: 58e0a7d7-eebc-11d8-9669-0800200c9a66
The value is: 5737
The least significant 64 bit: -7608541298835023258
Java - util package
Java-Functions
Java-UUID
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Interfaces in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
Multithreading in Java
Collections in Java
|
[
{
"code": null,
"e": 26093,
"s": 26065,
"text": "\n27 Dec, 2018"
},
{
"code": null,
"e": 26241,
"s": 26093,
"text": "The UUIDs are 128-bit values. The getLeastSignificantBits() Method of UUID class in Java is used to get the least significant 64 bits of this UUID."
},
{
"code": null,
"e": 26249,
"s": 26241,
"text": "Syntax:"
},
{
"code": null,
"e": 26287,
"s": 26249,
"text": "public long getLeastSignificantBits()"
},
{
"code": null,
"e": 26340,
"s": 26287,
"text": "Parameters: The method does not take any parameters."
},
{
"code": null,
"e": 26453,
"s": 26340,
"text": "Return Value: The method returns an integer value which is the least significant 64 bit of this 128 valued UUID."
},
{
"code": null,
"e": 26528,
"s": 26453,
"text": "Below programs illustrate the working of getLeastSignificantBits() method:"
},
{
"code": null,
"e": 26539,
"s": 26528,
"text": "Program 1:"
},
{
"code": "// Java code to illustrate// getLeastSignificantBits() method import java.util.*; public class UUID_Demo { public static void main(String[] args) { // Creating two UUIDs UUID UUID_1 = UUID .fromString( \"58e0a7d7-eebc-11d8-9669-0800200c9a66\"); // Displaying the UUID System.out.println(\"UUID: \" + UUID_1); // Displaying the value of UUID System.out.println(\"The value is: \" + UUID_1.clockSequence()); // Getting the least significant 64 bit System.out.println(\"The least significant 64 bit: \" + UUID_1 .getLeastSignificantBits()); }}",
"e": 27304,
"s": 26539,
"text": null
},
{
"code": null,
"e": 27418,
"s": 27304,
"text": "UUID: 58e0a7d7-eebc-11d8-9669-0800200c9a66\nThe value is: 5737\nThe least significant 64 bit: -7608541298835023258\n"
},
{
"code": null,
"e": 27429,
"s": 27418,
"text": "Program 2:"
},
{
"code": "// Java code to illustrate// getLeastSignificantBits() method import java.util.*; public class UUID_Demo { public static void main(String[] args) { // Creating two UUIDs UUID UUID_1 = UUID .fromString( \"58e0a7d7-eebc-11d8-9669-0800200c9a66\"); // Displaying the UUID System.out.println(\"UUID: \" + UUID_1); // Displaying the value of UUID System.out.println(\"The value is: \" + UUID_1.clockSequence()); // Getting the least significant 64 bit System.out.println(\"The least significant 64 bit: \" + UUID_1.getLeastSignificantBits()); }}",
"e": 28163,
"s": 27429,
"text": null
},
{
"code": null,
"e": 28277,
"s": 28163,
"text": "UUID: 58e0a7d7-eebc-11d8-9669-0800200c9a66\nThe value is: 5737\nThe least significant 64 bit: -7608541298835023258\n"
},
{
"code": null,
"e": 28297,
"s": 28277,
"text": "Java - util package"
},
{
"code": null,
"e": 28312,
"s": 28297,
"text": "Java-Functions"
},
{
"code": null,
"e": 28322,
"s": 28312,
"text": "Java-UUID"
},
{
"code": null,
"e": 28327,
"s": 28322,
"text": "Java"
},
{
"code": null,
"e": 28332,
"s": 28327,
"text": "Java"
},
{
"code": null,
"e": 28430,
"s": 28332,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28445,
"s": 28430,
"text": "Stream In Java"
},
{
"code": null,
"e": 28464,
"s": 28445,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 28482,
"s": 28464,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 28514,
"s": 28482,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 28534,
"s": 28514,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 28558,
"s": 28534,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 28590,
"s": 28558,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 28602,
"s": 28590,
"text": "Set in Java"
},
{
"code": null,
"e": 28625,
"s": 28602,
"text": "Multithreading in Java"
}
] |
Counting number of repeating words in a Golang String - GeeksforGeeks
|
04 May, 2020
Given a string, the task is to count the number of words being repeated in that particular string in Golang.
Example:
Input: s = "She is mother of my mother."
Output: She = 1
is = 1
mother = 2
of = 1
my = 1
To count the number of repeating words, first, the string is taken as input and then strings.Fields() function is used to split the string. A function “repetition” is defined to count the number of words getting repeated.
Below is the program in Golang to count the number of repeating words in a given string.
// Golang program to count the number of// repeating words in given Golang Stringpackage main import ( "fmt" "strings") func repetition(st string) map[string]int { // using strings.Field Function input := strings.Fields(st) wc := make(map[string]int) for _, word := range input { _, matched := wc[word] if matched { wc[word] += 1 } else { wc[word] = 1 } } return wc} // Main functionfunc main() { input := "betty bought the butter , the butter was bitter , " + "betty bought more butter to make the bitter butter better " for index, element := range repetition(input) { fmt.Println(index, "=", element) }}
Output:
the = 3
, = 2
bitter = 2
to = 1
make = 1
better = 1
betty = 2
bought = 2
butter = 4
was = 1
more = 1
Explanation: In the above program, we first take a string as an input and then split that string using strings.Fields() function. If the same word has occurred, the count increases by one else value 1 is returned that implies that word occurs only once in the string.
Golang-Program
Golang-String
Picked
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Parse JSON in Golang?
Defer Keyword in Golang
time.Parse() Function in Golang With Examples
Anonymous function in Go Language
Time Durations in Golang
Structures in Golang
Strings in Golang
Class and Object in Golang
How to convert a string in uppercase in Golang?
Rune in Golang
|
[
{
"code": null,
"e": 24380,
"s": 24352,
"text": "\n04 May, 2020"
},
{
"code": null,
"e": 24489,
"s": 24380,
"text": "Given a string, the task is to count the number of words being repeated in that particular string in Golang."
},
{
"code": null,
"e": 24498,
"s": 24489,
"text": "Example:"
},
{
"code": null,
"e": 24629,
"s": 24498,
"text": "Input: s = \"She is mother of my mother.\"\nOutput: She = 1 \n is = 1\n mother = 2\n of = 1\n my = 1\n"
},
{
"code": null,
"e": 24851,
"s": 24629,
"text": "To count the number of repeating words, first, the string is taken as input and then strings.Fields() function is used to split the string. A function “repetition” is defined to count the number of words getting repeated."
},
{
"code": null,
"e": 24940,
"s": 24851,
"text": "Below is the program in Golang to count the number of repeating words in a given string."
},
{
"code": "// Golang program to count the number of// repeating words in given Golang Stringpackage main import ( \"fmt\" \"strings\") func repetition(st string) map[string]int { // using strings.Field Function input := strings.Fields(st) wc := make(map[string]int) for _, word := range input { _, matched := wc[word] if matched { wc[word] += 1 } else { wc[word] = 1 } } return wc} // Main functionfunc main() { input := \"betty bought the butter , the butter was bitter , \" + \"betty bought more butter to make the bitter butter better \" for index, element := range repetition(input) { fmt.Println(index, \"=\", element) }}",
"e": 25648,
"s": 24940,
"text": null
},
{
"code": null,
"e": 25656,
"s": 25648,
"text": "Output:"
},
{
"code": null,
"e": 25758,
"s": 25656,
"text": "the = 3\n, = 2\nbitter = 2\nto = 1\nmake = 1\nbetter = 1\nbetty = 2\nbought = 2\nbutter = 4\nwas = 1\nmore = 1\n"
},
{
"code": null,
"e": 26026,
"s": 25758,
"text": "Explanation: In the above program, we first take a string as an input and then split that string using strings.Fields() function. If the same word has occurred, the count increases by one else value 1 is returned that implies that word occurs only once in the string."
},
{
"code": null,
"e": 26041,
"s": 26026,
"text": "Golang-Program"
},
{
"code": null,
"e": 26055,
"s": 26041,
"text": "Golang-String"
},
{
"code": null,
"e": 26062,
"s": 26055,
"text": "Picked"
},
{
"code": null,
"e": 26074,
"s": 26062,
"text": "Go Language"
},
{
"code": null,
"e": 26172,
"s": 26074,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26181,
"s": 26172,
"text": "Comments"
},
{
"code": null,
"e": 26194,
"s": 26181,
"text": "Old Comments"
},
{
"code": null,
"e": 26223,
"s": 26194,
"text": "How to Parse JSON in Golang?"
},
{
"code": null,
"e": 26247,
"s": 26223,
"text": "Defer Keyword in Golang"
},
{
"code": null,
"e": 26293,
"s": 26247,
"text": "time.Parse() Function in Golang With Examples"
},
{
"code": null,
"e": 26327,
"s": 26293,
"text": "Anonymous function in Go Language"
},
{
"code": null,
"e": 26352,
"s": 26327,
"text": "Time Durations in Golang"
},
{
"code": null,
"e": 26373,
"s": 26352,
"text": "Structures in Golang"
},
{
"code": null,
"e": 26391,
"s": 26373,
"text": "Strings in Golang"
},
{
"code": null,
"e": 26418,
"s": 26391,
"text": "Class and Object in Golang"
},
{
"code": null,
"e": 26466,
"s": 26418,
"text": "How to convert a string in uppercase in Golang?"
}
] |
C# | How to change the Output Encoding Scheme of the Console - GeeksforGeeks
|
28 Jan, 2019
Given the normal Console in C#, the task is to change the Output Encoding Scheme of the Console.
Approach: This can be done using the OutputEncoding property in the Console class of the System package in C#.
Program 1: Getting the value of Output Encoding Scheme
// C# program to illustrate the// Console.OutputEncoding Propertyusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace GFG { class Program { static void Main(string[] args) { // Get the Output Encoding Scheme Console.WriteLine("Current Output Encoding Scheme: {0}", Console.OutputEncoding); }}}
Output:
Program 2: Setting the value of Output Encoding Scheme
// C# program to illustrate the// Console.OutputEncoding Propertyusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace GFG { class Program { static void Main(string[] args) { // Get the Output Encoding Scheme Console.WriteLine("Current Output Encoding Scheme: {0}", Console.OutputEncoding); // Set the Output Encoding Scheme to ASCII Console.OutputEncoding = Encoding.ASCII; // Get the Output Encoding Scheme Console.WriteLine("Current Output Encoding Scheme: {0}", Console.OutputEncoding); }}}
Output:
CSharp-Console-Class
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Delegates
C# | Method Overriding
C# | Abstract Classes
Difference between Ref and Out keywords in C#
Extension Method in C#
C# | Replace() Method
C# | Class and Object
C# | String.IndexOf( ) Method | Set - 1
C# | Constructors
|
[
{
"code": null,
"e": 26389,
"s": 26361,
"text": "\n28 Jan, 2019"
},
{
"code": null,
"e": 26486,
"s": 26389,
"text": "Given the normal Console in C#, the task is to change the Output Encoding Scheme of the Console."
},
{
"code": null,
"e": 26597,
"s": 26486,
"text": "Approach: This can be done using the OutputEncoding property in the Console class of the System package in C#."
},
{
"code": null,
"e": 26652,
"s": 26597,
"text": "Program 1: Getting the value of Output Encoding Scheme"
},
{
"code": "// C# program to illustrate the// Console.OutputEncoding Propertyusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace GFG { class Program { static void Main(string[] args) { // Get the Output Encoding Scheme Console.WriteLine(\"Current Output Encoding Scheme: {0}\", Console.OutputEncoding); }}}",
"e": 27083,
"s": 26652,
"text": null
},
{
"code": null,
"e": 27091,
"s": 27083,
"text": "Output:"
},
{
"code": null,
"e": 27146,
"s": 27091,
"text": "Program 2: Setting the value of Output Encoding Scheme"
},
{
"code": "// C# program to illustrate the// Console.OutputEncoding Propertyusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace GFG { class Program { static void Main(string[] args) { // Get the Output Encoding Scheme Console.WriteLine(\"Current Output Encoding Scheme: {0}\", Console.OutputEncoding); // Set the Output Encoding Scheme to ASCII Console.OutputEncoding = Encoding.ASCII; // Get the Output Encoding Scheme Console.WriteLine(\"Current Output Encoding Scheme: {0}\", Console.OutputEncoding); }}}",
"e": 27848,
"s": 27146,
"text": null
},
{
"code": null,
"e": 27856,
"s": 27848,
"text": "Output:"
},
{
"code": null,
"e": 27877,
"s": 27856,
"text": "CSharp-Console-Class"
},
{
"code": null,
"e": 27880,
"s": 27877,
"text": "C#"
},
{
"code": null,
"e": 27978,
"s": 27880,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28006,
"s": 27978,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 28021,
"s": 28006,
"text": "C# | Delegates"
},
{
"code": null,
"e": 28044,
"s": 28021,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 28066,
"s": 28044,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 28112,
"s": 28066,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 28135,
"s": 28112,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 28157,
"s": 28135,
"text": "C# | Replace() Method"
},
{
"code": null,
"e": 28179,
"s": 28157,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 28219,
"s": 28179,
"text": "C# | String.IndexOf( ) Method | Set - 1"
}
] |
PyQt5 QDateEdit - Setting Date Programmatically - GeeksforGeeks
|
25 May, 2021
In this article, we will see how we can date programmatically to the QDateEdit. User can set date to the date edit with the help of cursor and the keyboard but sometimes there is a need of setting initial date or date programmatically for showing date in the records.In order to do this we use setDate method with the QDateEdit object
Syntax : date.setDate(d)Argument : It takes QDate object as argumentReturn : It returns None
Below is the implementation
Python3
# importing librariesfrom PyQt5.QtWidgets import *from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import *from PyQt5.QtCore import *import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QDateEdit widget date = QDateEdit(self) # setting geometry of the date edit date.setGeometry(100, 100, 150, 40) # date d = QDate(2020, 6, 10) # setting date to the date edit date.setDate(d) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
sweetyty
Python PyQt-QDateEdit
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
|
[
{
"code": null,
"e": 25729,
"s": 25701,
"text": "\n25 May, 2021"
},
{
"code": null,
"e": 26066,
"s": 25729,
"text": "In this article, we will see how we can date programmatically to the QDateEdit. User can set date to the date edit with the help of cursor and the keyboard but sometimes there is a need of setting initial date or date programmatically for showing date in the records.In order to do this we use setDate method with the QDateEdit object "
},
{
"code": null,
"e": 26161,
"s": 26066,
"text": "Syntax : date.setDate(d)Argument : It takes QDate object as argumentReturn : It returns None "
},
{
"code": null,
"e": 26191,
"s": 26161,
"text": "Below is the implementation "
},
{
"code": null,
"e": 26199,
"s": 26191,
"text": "Python3"
},
{
"code": "# importing librariesfrom PyQt5.QtWidgets import *from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import *from PyQt5.QtCore import *import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QDateEdit widget date = QDateEdit(self) # setting geometry of the date edit date.setGeometry(100, 100, 150, 40) # date d = QDate(2020, 6, 10) # setting date to the date edit date.setDate(d) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 27123,
"s": 26199,
"text": null
},
{
"code": null,
"e": 27134,
"s": 27123,
"text": "Output : "
},
{
"code": null,
"e": 27145,
"s": 27136,
"text": "sweetyty"
},
{
"code": null,
"e": 27167,
"s": 27145,
"text": "Python PyQt-QDateEdit"
},
{
"code": null,
"e": 27178,
"s": 27167,
"text": "Python-gui"
},
{
"code": null,
"e": 27190,
"s": 27178,
"text": "Python-PyQt"
},
{
"code": null,
"e": 27197,
"s": 27190,
"text": "Python"
},
{
"code": null,
"e": 27295,
"s": 27197,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27313,
"s": 27295,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27345,
"s": 27313,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27367,
"s": 27345,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27409,
"s": 27367,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27439,
"s": 27409,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27465,
"s": 27439,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27494,
"s": 27465,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27538,
"s": 27494,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 27575,
"s": 27538,
"text": "Create a Pandas DataFrame from Lists"
}
] |
ReactJS UNSAFE_componentWillMount() Method - GeeksforGeeks
|
17 Dec, 2021
The componentWillMount() method invokes right before our React component gets loaded or mounted in the DOM (Document Object Model). It is called during the mounting phase of the React Life-cycle, i.e., before render(). It is used to fetch data from outside the component by executing the React code synchronously which causes our component to render with empty data at first because this method doesn’t return anything before our component renders for the first time. As the fetch calls are asynchronous, our component doesn’t wait for this method to finish and continues to get rendered.
The componentWillMount() method has been deprecated in the latest releases of React as per this issue. It is recommended to use componentDidMount() method in its place but if we still want to use componentWillMount() we can do it by calling it as UNSAFE_componentWillMount(). It’s not suggested using this method according to React, that’s why the UNSAFE keyword comes at the beginning to give a gentle message to all the React developers to stop using this method. This method can be used to perform an action just before our React component gets mounted in the DOM.
Syntax:
class App extends Component {
UNSAFE_componentWillMount() {
//action you want to execute
}
}
Creating React Application:
Step 1: Create a React application using the following command.
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.
cd foldername
Project Structure: It will look like the following.
Example: In this example, we are going to build an application that gives an alert message before our React component loads in the DOM. Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Filename: App.js
Javascript
import React from 'react';class App extends React.Component { UNSAFE_componentWillMount() { // Performing an action alert(`Welcome to GeeksForGeeks portal`); } render() { return <h1>GeeksForGeeks</h1>; } } export default App;
Step to Run Application: Run the application using the following command from the root directory of the project.
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output.
Explanation: We receive an alert message through UNSAFE_componentWillMount() method before our component gets mounted in the DOM and then our component loads after rendering. This way, we can perform any action just before our component loads. As you can see a warning message also appears at the console when our component loads which clearly tells us that this method is not recommended for the use which we already discussed above.
sagartomar9927
Picked
React.js-Methods
ReactJS-Basics
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ReactJS useNavigate() Hook
How to set background images in ReactJS ?
Axios in React: A Guide for Beginners
How to create a table in ReactJS ?
How to navigate on path by button click in react router ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26071,
"s": 26043,
"text": "\n17 Dec, 2021"
},
{
"code": null,
"e": 26660,
"s": 26071,
"text": "The componentWillMount() method invokes right before our React component gets loaded or mounted in the DOM (Document Object Model). It is called during the mounting phase of the React Life-cycle, i.e., before render(). It is used to fetch data from outside the component by executing the React code synchronously which causes our component to render with empty data at first because this method doesn’t return anything before our component renders for the first time. As the fetch calls are asynchronous, our component doesn’t wait for this method to finish and continues to get rendered."
},
{
"code": null,
"e": 27228,
"s": 26660,
"text": "The componentWillMount() method has been deprecated in the latest releases of React as per this issue. It is recommended to use componentDidMount() method in its place but if we still want to use componentWillMount() we can do it by calling it as UNSAFE_componentWillMount(). It’s not suggested using this method according to React, that’s why the UNSAFE keyword comes at the beginning to give a gentle message to all the React developers to stop using this method. This method can be used to perform an action just before our React component gets mounted in the DOM."
},
{
"code": null,
"e": 27236,
"s": 27228,
"text": "Syntax:"
},
{
"code": null,
"e": 27347,
"s": 27236,
"text": "class App extends Component {\n\n UNSAFE_componentWillMount() {\n \n //action you want to execute\n \n }\n}"
},
{
"code": null,
"e": 27375,
"s": 27347,
"text": "Creating React Application:"
},
{
"code": null,
"e": 27439,
"s": 27375,
"text": "Step 1: Create a React application using the following command."
},
{
"code": null,
"e": 27471,
"s": 27439,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 27571,
"s": 27471,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command."
},
{
"code": null,
"e": 27585,
"s": 27571,
"text": "cd foldername"
},
{
"code": null,
"e": 27637,
"s": 27585,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 27894,
"s": 27637,
"text": "Example: In this example, we are going to build an application that gives an alert message before our React component loads in the DOM. Now write down the following code in the App.js file. Here, App is our default component where we have written our code."
},
{
"code": null,
"e": 27911,
"s": 27894,
"text": "Filename: App.js"
},
{
"code": null,
"e": 27922,
"s": 27911,
"text": "Javascript"
},
{
"code": "import React from 'react';class App extends React.Component { UNSAFE_componentWillMount() { // Performing an action alert(`Welcome to GeeksForGeeks portal`); } render() { return <h1>GeeksForGeeks</h1>; } } export default App;",
"e": 28166,
"s": 27922,
"text": null
},
{
"code": null,
"e": 28279,
"s": 28166,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project."
},
{
"code": null,
"e": 28289,
"s": 28279,
"text": "npm start"
},
{
"code": null,
"e": 28388,
"s": 28289,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output."
},
{
"code": null,
"e": 28823,
"s": 28388,
"text": "Explanation: We receive an alert message through UNSAFE_componentWillMount() method before our component gets mounted in the DOM and then our component loads after rendering. This way, we can perform any action just before our component loads. As you can see a warning message also appears at the console when our component loads which clearly tells us that this method is not recommended for the use which we already discussed above."
},
{
"code": null,
"e": 28838,
"s": 28823,
"text": "sagartomar9927"
},
{
"code": null,
"e": 28845,
"s": 28838,
"text": "Picked"
},
{
"code": null,
"e": 28862,
"s": 28845,
"text": "React.js-Methods"
},
{
"code": null,
"e": 28877,
"s": 28862,
"text": "ReactJS-Basics"
},
{
"code": null,
"e": 28885,
"s": 28877,
"text": "ReactJS"
},
{
"code": null,
"e": 28902,
"s": 28885,
"text": "Web Technologies"
},
{
"code": null,
"e": 29000,
"s": 28902,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29027,
"s": 29000,
"text": "ReactJS useNavigate() Hook"
},
{
"code": null,
"e": 29069,
"s": 29027,
"text": "How to set background images in ReactJS ?"
},
{
"code": null,
"e": 29107,
"s": 29069,
"text": "Axios in React: A Guide for Beginners"
},
{
"code": null,
"e": 29142,
"s": 29107,
"text": "How to create a table in ReactJS ?"
},
{
"code": null,
"e": 29200,
"s": 29142,
"text": "How to navigate on path by button click in react router ?"
},
{
"code": null,
"e": 29240,
"s": 29200,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29273,
"s": 29240,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29318,
"s": 29273,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29368,
"s": 29318,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Building a Machine Learning Model Using J48 Classifier - GeeksforGeeks
|
22 Sep, 2021
What is the J48 Classifier?
J48 is a machine learning decision tree classification algorithm based on Iterative Dichotomiser 3. It is very helpful in examine the data categorically and continuously.
Note: To build our J48 machine learning model we’ll use the weka tool.
What is Weka?
Weka is an open-source tool developed by the University of Waikato, New Zealand licensed under GNU public license. You can download weka on any operating system. Weka has GUI and APIs available to use.
Steps to follow:
Step 1: Create a model using GUI
Step 2: After opening Weka click on the “Explorer” Tab
Step 3: In the “Preprocess” Tab Click on “Open File” and select the “breast-cancer.arff” file which will be located in the installation path, inside the data folder.
In this tab, you can view all the attributes and play with them.
Step 4: In the “Classify” tab click on the choose button. Now under weka/classifiers/trees/ select J48
Step 5: Now one can click on the J48 Classifier selection and play around with it like changing batch size, confidence factor, etc. There under “Test Options” we’ll use the default cross-validation option as folds 10 and click on start.
Implementation:
Now we are done with discussing that Weka has Java API that you can use to create machine learning models so di now let us create a model using API
Example
Java
// Java Program for Creating a Model Based on J48 Classifier // 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 classpublic class BreastCancer { // Main driver method public static void main(String args[]) { // Try bloc kto check for exceptions try { // Creating J48 classifier J48 j48Classifier = new J48(); // Dataset path String breastCancerDataset = "/home/droid/Tools/weka-3-8-5/data/breast-cancer.arff"; // Create 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); // Evaluation 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 check fo rexceptions catch (Exception e) { // Print and display the display message // using getMessage() method System.out.println("Error Occured!!!! \n" + e.getMessage()); } // Display message to be printed ion console // when program is successfully executed System.out.print("Successfully executed."); }}
Output:
Successfully executed.
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
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Naive Bayes Classifiers
Linear Regression (Python Implementation)
ML | Linear Regression
Reinforcement learning
Removing stop words with NLTK in Python
|
[
{
"code": null,
"e": 25225,
"s": 25197,
"text": "\n22 Sep, 2021"
},
{
"code": null,
"e": 25253,
"s": 25225,
"text": "What is the J48 Classifier?"
},
{
"code": null,
"e": 25424,
"s": 25253,
"text": "J48 is a machine learning decision tree classification algorithm based on Iterative Dichotomiser 3. It is very helpful in examine the data categorically and continuously."
},
{
"code": null,
"e": 25495,
"s": 25424,
"text": "Note: To build our J48 machine learning model we’ll use the weka tool."
},
{
"code": null,
"e": 25509,
"s": 25495,
"text": "What is Weka?"
},
{
"code": null,
"e": 25711,
"s": 25509,
"text": "Weka is an open-source tool developed by the University of Waikato, New Zealand licensed under GNU public license. You can download weka on any operating system. Weka has GUI and APIs available to use."
},
{
"code": null,
"e": 25728,
"s": 25711,
"text": "Steps to follow:"
},
{
"code": null,
"e": 25761,
"s": 25728,
"text": "Step 1: Create a model using GUI"
},
{
"code": null,
"e": 25816,
"s": 25761,
"text": "Step 2: After opening Weka click on the “Explorer” Tab"
},
{
"code": null,
"e": 25982,
"s": 25816,
"text": "Step 3: In the “Preprocess” Tab Click on “Open File” and select the “breast-cancer.arff” file which will be located in the installation path, inside the data folder."
},
{
"code": null,
"e": 26047,
"s": 25982,
"text": "In this tab, you can view all the attributes and play with them."
},
{
"code": null,
"e": 26150,
"s": 26047,
"text": "Step 4: In the “Classify” tab click on the choose button. Now under weka/classifiers/trees/ select J48"
},
{
"code": null,
"e": 26387,
"s": 26150,
"text": "Step 5: Now one can click on the J48 Classifier selection and play around with it like changing batch size, confidence factor, etc. There under “Test Options” we’ll use the default cross-validation option as folds 10 and click on start."
},
{
"code": null,
"e": 26403,
"s": 26387,
"text": "Implementation:"
},
{
"code": null,
"e": 26551,
"s": 26403,
"text": "Now we are done with discussing that Weka has Java API that you can use to create machine learning models so di now let us create a model using API"
},
{
"code": null,
"e": 26559,
"s": 26551,
"text": "Example"
},
{
"code": null,
"e": 26564,
"s": 26559,
"text": "Java"
},
{
"code": "// Java Program for Creating a Model Based on J48 Classifier // 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 classpublic class BreastCancer { // Main driver method public static void main(String args[]) { // Try bloc kto check for exceptions try { // Creating J48 classifier J48 j48Classifier = new J48(); // Dataset path String breastCancerDataset = \"/home/droid/Tools/weka-3-8-5/data/breast-cancer.arff\"; // Create 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); // Evaluation 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 check fo rexceptions catch (Exception e) { // Print and display the display message // using getMessage() method System.out.println(\"Error Occured!!!! \\n\" + e.getMessage()); } // Display message to be printed ion console // when program is successfully executed System.out.print(\"Successfully executed.\"); }}",
"e": 28511,
"s": 26564,
"text": null
},
{
"code": null,
"e": 28519,
"s": 28511,
"text": "Output:"
},
{
"code": null,
"e": 28542,
"s": 28519,
"text": "Successfully executed."
},
{
"code": null,
"e": 28547,
"s": 28542,
"text": "Java"
},
{
"code": null,
"e": 28564,
"s": 28547,
"text": "Machine Learning"
},
{
"code": null,
"e": 28569,
"s": 28564,
"text": "Java"
},
{
"code": null,
"e": 28586,
"s": 28569,
"text": "Machine Learning"
},
{
"code": null,
"e": 28684,
"s": 28586,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28699,
"s": 28684,
"text": "Stream In Java"
},
{
"code": null,
"e": 28720,
"s": 28699,
"text": "Constructors in Java"
},
{
"code": null,
"e": 28739,
"s": 28720,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 28769,
"s": 28739,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 28815,
"s": 28769,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 28839,
"s": 28815,
"text": "Naive Bayes Classifiers"
},
{
"code": null,
"e": 28881,
"s": 28839,
"text": "Linear Regression (Python Implementation)"
},
{
"code": null,
"e": 28904,
"s": 28881,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 28927,
"s": 28904,
"text": "Reinforcement learning"
}
] |
Getting Started with TensorFlow.js | by Venelin Valkov | Towards Data Science
|
TL;DR Learn about the basics of Machine Learning with TensorFlow.js — Tensors, basic visualizations and train a simple model that converts kilograms to pounds
So what is this thing TensorFlow.js?
TensorFlow.js is a library for developing and training ML models in JavaScript, and deploying in browser or on Node.js
For our purposes, TensorFlow.js will allow you to build Machine Learning models (especially Deep Neural Networks) that you can easily integrate with existing or new web apps. Think of your ReactJs, Vue, or Angular app enhanced with the power of Machine Learning models.
Run the complete source code for this tutorial right in your browser:
codesandbox.io
Tensors are the main building blocks of TensorFlow. They are n-dimensional data containers. You can think of them as multidimensional arrays in languages like PHP, JavaScript, and others. What that means is that you can use tensors as a scalar, vector, and matrix values, since they are a generalization of those.
Each Tensor contains the following properties
rank - number of dimensions
shape - size of each dimension
dtype - data type of the values
Let’s start by creating your first Tensor:
Check it’s rank:
1
That confirms that your Tensor is 1-dimensional. Let’s check the shape:
[3]
1-dimensional with 3 values. But how can you see the contents of this thing?
Tensor {kept: false, isDisposedInternal: false ...}
Not what you’ve expected, right? Tensors are custom objects and have a print()method that output their values:
Tensor [1, 2, 3]
Of course, the values don’t have to be just numeric. You can create tensors of strings:
You can use tensor2d() to create matrices (or 2-dimensional tensors):
[2, 3]
There are some utility methods that will be handy when we start developing models. Let’s start with ones():
Tensor [[1, 1, 1], [1, 1, 1], [1, 1, 1]]
You can use reshape() to change the dimensionality of a Tensor:
Tensor [[1, 2, 3], [4, 5, 6]]
You can use add() to do element-wise addition:
Tensor [5, 7, 9]
and dot() to compute the dot product of two tensors:
Tensor [[9, 12], [9, 12]]
Finally, let’s have a look at transpose():
Tensor [[1, 3], [2, 4]]
You can think of the transpose as a flipped-axis version of the input Tensor.
Have a look at all arithmetic operations
tfjs-vis is a small library for in browser visualization intended for use with TensorFlow.js.
Let’s start by creating a simple bar chart. Here’s what our data looks like:
Now, let’s render the data using barchart():
Note that we provide a DOM element to the renderer as a container for our chart, which might be handy when you want to embed the charts in your apps.
Let’s have a look at histogram() and create a sample chart:
The API is pretty consistent for those 2 charts. Let’s do a scatter plot:
Have a look at the complete tfjs-vis API
Time to put what you’ve learned into practice and build your first model. To make it somewhat realistic, we’ll try to approximate the conversion of kgs to lbs, which is described by this function:
Let’s use it to prepare our data and create 2000 training examples:
We’re going to use a style of Machine Learning known as Supervised Learning. In a nutshell, we need to provide 2 arrays to our model — X is the training features (kilograms), and y is the training labels (corresponding pounds).
TensorFlow.js allows you to build layered models using sequential(). We’re going to go extremely simple: 1 layer, input size of 1, and 1 learning parameter:
and teach it to convert kilograms to pounds:
Your model needs a metric to know how well is doing. In our case that is Mean Squared Error (MSE). Once you know how to measure the error, you need something to know how to minimize it using the data. In our case, that is the Adam optimizer.
Finally, we use the data to train our model for 100 epochs (number of times our model sees the data) and request to shuffle it. Why shuffle? We don’t want our model to learn the ordering of the data, just the relationship between different examples.
After the training is complete (might take some time) you can use your model to predict what amount of pounds correspond to 10 kg:
10 kg to lbs: 22.481597900390625
Seems to be doing good, right?
Congratulation on finishing the first part of your journey to Machine Learning understanding. You learned about:
Tensors: n-dimensional data containers
tfjs-vis: visualization library integrated with TensorFlow.js
predict pounds from kilograms using a simple model
Run the complete source code for this tutorial right in your browser:
codesandbox.io
I hope that this tutorial just made you thirsty for knowledge about what is possible with Machine Learning and JavaScript. Ready for the next one?
Originally published at https://www.curiousily.com.
Build Machine Learning models (especially Deep Neural Networks) that you can easily integrate with existing or new web apps. Think of your ReactJs, Vue, or Angular app enhanced with the power of Machine Learning models:
leanpub.com
Develop a deeper understanding of Machine Learning models, tools and concepts by building them from scratch with Python
|
[
{
"code": null,
"e": 330,
"s": 171,
"text": "TL;DR Learn about the basics of Machine Learning with TensorFlow.js — Tensors, basic visualizations and train a simple model that converts kilograms to pounds"
},
{
"code": null,
"e": 367,
"s": 330,
"text": "So what is this thing TensorFlow.js?"
},
{
"code": null,
"e": 486,
"s": 367,
"text": "TensorFlow.js is a library for developing and training ML models in JavaScript, and deploying in browser or on Node.js"
},
{
"code": null,
"e": 756,
"s": 486,
"text": "For our purposes, TensorFlow.js will allow you to build Machine Learning models (especially Deep Neural Networks) that you can easily integrate with existing or new web apps. Think of your ReactJs, Vue, or Angular app enhanced with the power of Machine Learning models."
},
{
"code": null,
"e": 826,
"s": 756,
"text": "Run the complete source code for this tutorial right in your browser:"
},
{
"code": null,
"e": 841,
"s": 826,
"text": "codesandbox.io"
},
{
"code": null,
"e": 1155,
"s": 841,
"text": "Tensors are the main building blocks of TensorFlow. They are n-dimensional data containers. You can think of them as multidimensional arrays in languages like PHP, JavaScript, and others. What that means is that you can use tensors as a scalar, vector, and matrix values, since they are a generalization of those."
},
{
"code": null,
"e": 1201,
"s": 1155,
"text": "Each Tensor contains the following properties"
},
{
"code": null,
"e": 1229,
"s": 1201,
"text": "rank - number of dimensions"
},
{
"code": null,
"e": 1260,
"s": 1229,
"text": "shape - size of each dimension"
},
{
"code": null,
"e": 1292,
"s": 1260,
"text": "dtype - data type of the values"
},
{
"code": null,
"e": 1335,
"s": 1292,
"text": "Let’s start by creating your first Tensor:"
},
{
"code": null,
"e": 1352,
"s": 1335,
"text": "Check it’s rank:"
},
{
"code": null,
"e": 1354,
"s": 1352,
"text": "1"
},
{
"code": null,
"e": 1426,
"s": 1354,
"text": "That confirms that your Tensor is 1-dimensional. Let’s check the shape:"
},
{
"code": null,
"e": 1430,
"s": 1426,
"text": "[3]"
},
{
"code": null,
"e": 1507,
"s": 1430,
"text": "1-dimensional with 3 values. But how can you see the contents of this thing?"
},
{
"code": null,
"e": 1559,
"s": 1507,
"text": "Tensor {kept: false, isDisposedInternal: false ...}"
},
{
"code": null,
"e": 1670,
"s": 1559,
"text": "Not what you’ve expected, right? Tensors are custom objects and have a print()method that output their values:"
},
{
"code": null,
"e": 1690,
"s": 1670,
"text": "Tensor [1, 2, 3]"
},
{
"code": null,
"e": 1778,
"s": 1690,
"text": "Of course, the values don’t have to be just numeric. You can create tensors of strings:"
},
{
"code": null,
"e": 1848,
"s": 1778,
"text": "You can use tensor2d() to create matrices (or 2-dimensional tensors):"
},
{
"code": null,
"e": 1855,
"s": 1848,
"text": "[2, 3]"
},
{
"code": null,
"e": 1963,
"s": 1855,
"text": "There are some utility methods that will be handy when we start developing models. Let’s start with ones():"
},
{
"code": null,
"e": 2015,
"s": 1963,
"text": "Tensor [[1, 1, 1], [1, 1, 1], [1, 1, 1]]"
},
{
"code": null,
"e": 2079,
"s": 2015,
"text": "You can use reshape() to change the dimensionality of a Tensor:"
},
{
"code": null,
"e": 2116,
"s": 2079,
"text": "Tensor [[1, 2, 3], [4, 5, 6]]"
},
{
"code": null,
"e": 2163,
"s": 2116,
"text": "You can use add() to do element-wise addition:"
},
{
"code": null,
"e": 2183,
"s": 2163,
"text": "Tensor [5, 7, 9]"
},
{
"code": null,
"e": 2236,
"s": 2183,
"text": "and dot() to compute the dot product of two tensors:"
},
{
"code": null,
"e": 2269,
"s": 2236,
"text": "Tensor [[9, 12], [9, 12]]"
},
{
"code": null,
"e": 2312,
"s": 2269,
"text": "Finally, let’s have a look at transpose():"
},
{
"code": null,
"e": 2343,
"s": 2312,
"text": "Tensor [[1, 3], [2, 4]]"
},
{
"code": null,
"e": 2421,
"s": 2343,
"text": "You can think of the transpose as a flipped-axis version of the input Tensor."
},
{
"code": null,
"e": 2462,
"s": 2421,
"text": "Have a look at all arithmetic operations"
},
{
"code": null,
"e": 2556,
"s": 2462,
"text": "tfjs-vis is a small library for in browser visualization intended for use with TensorFlow.js."
},
{
"code": null,
"e": 2633,
"s": 2556,
"text": "Let’s start by creating a simple bar chart. Here’s what our data looks like:"
},
{
"code": null,
"e": 2678,
"s": 2633,
"text": "Now, let’s render the data using barchart():"
},
{
"code": null,
"e": 2828,
"s": 2678,
"text": "Note that we provide a DOM element to the renderer as a container for our chart, which might be handy when you want to embed the charts in your apps."
},
{
"code": null,
"e": 2888,
"s": 2828,
"text": "Let’s have a look at histogram() and create a sample chart:"
},
{
"code": null,
"e": 2962,
"s": 2888,
"text": "The API is pretty consistent for those 2 charts. Let’s do a scatter plot:"
},
{
"code": null,
"e": 3003,
"s": 2962,
"text": "Have a look at the complete tfjs-vis API"
},
{
"code": null,
"e": 3200,
"s": 3003,
"text": "Time to put what you’ve learned into practice and build your first model. To make it somewhat realistic, we’ll try to approximate the conversion of kgs to lbs, which is described by this function:"
},
{
"code": null,
"e": 3268,
"s": 3200,
"text": "Let’s use it to prepare our data and create 2000 training examples:"
},
{
"code": null,
"e": 3496,
"s": 3268,
"text": "We’re going to use a style of Machine Learning known as Supervised Learning. In a nutshell, we need to provide 2 arrays to our model — X is the training features (kilograms), and y is the training labels (corresponding pounds)."
},
{
"code": null,
"e": 3653,
"s": 3496,
"text": "TensorFlow.js allows you to build layered models using sequential(). We’re going to go extremely simple: 1 layer, input size of 1, and 1 learning parameter:"
},
{
"code": null,
"e": 3698,
"s": 3653,
"text": "and teach it to convert kilograms to pounds:"
},
{
"code": null,
"e": 3940,
"s": 3698,
"text": "Your model needs a metric to know how well is doing. In our case that is Mean Squared Error (MSE). Once you know how to measure the error, you need something to know how to minimize it using the data. In our case, that is the Adam optimizer."
},
{
"code": null,
"e": 4190,
"s": 3940,
"text": "Finally, we use the data to train our model for 100 epochs (number of times our model sees the data) and request to shuffle it. Why shuffle? We don’t want our model to learn the ordering of the data, just the relationship between different examples."
},
{
"code": null,
"e": 4321,
"s": 4190,
"text": "After the training is complete (might take some time) you can use your model to predict what amount of pounds correspond to 10 kg:"
},
{
"code": null,
"e": 4354,
"s": 4321,
"text": "10 kg to lbs: 22.481597900390625"
},
{
"code": null,
"e": 4385,
"s": 4354,
"text": "Seems to be doing good, right?"
},
{
"code": null,
"e": 4498,
"s": 4385,
"text": "Congratulation on finishing the first part of your journey to Machine Learning understanding. You learned about:"
},
{
"code": null,
"e": 4537,
"s": 4498,
"text": "Tensors: n-dimensional data containers"
},
{
"code": null,
"e": 4599,
"s": 4537,
"text": "tfjs-vis: visualization library integrated with TensorFlow.js"
},
{
"code": null,
"e": 4650,
"s": 4599,
"text": "predict pounds from kilograms using a simple model"
},
{
"code": null,
"e": 4720,
"s": 4650,
"text": "Run the complete source code for this tutorial right in your browser:"
},
{
"code": null,
"e": 4735,
"s": 4720,
"text": "codesandbox.io"
},
{
"code": null,
"e": 4882,
"s": 4735,
"text": "I hope that this tutorial just made you thirsty for knowledge about what is possible with Machine Learning and JavaScript. Ready for the next one?"
},
{
"code": null,
"e": 4934,
"s": 4882,
"text": "Originally published at https://www.curiousily.com."
},
{
"code": null,
"e": 5154,
"s": 4934,
"text": "Build Machine Learning models (especially Deep Neural Networks) that you can easily integrate with existing or new web apps. Think of your ReactJs, Vue, or Angular app enhanced with the power of Machine Learning models:"
},
{
"code": null,
"e": 5166,
"s": 5154,
"text": "leanpub.com"
}
] |
How to fine-tune BERT with pytorch-lightning | by sobamchan | Towards Data Science
|
How to fine-tune BERT with pytorch-lightning
What’s up world!
I hope you are enjoying fine-tuning transformer-based language models on tasks of your interest and achieving cool results.
I assume quite many of you use this amazing transformers library from huggingface to fine-tune pre-trained language models. This is a library that lets you use state-of-the-art general-purpose (pre-trained) language models for PyTorch and Tensorflow. This library makes the process of downloading pretraining models very easy, plus the library also provides a set of python scripts so you can fine-tune the models on the task that you’re interested in.
Running provided scripts is very easy. However, when we want to add some changes to those scripts may get a bit tricky.
But don’t worry, we are lucky that there are other amazing libraries out there that help you to implement clean and pretty script for fine-tuning.
pytorch-lightning is a lightweight PyTorch wrapper which frees you from writing boring training loops. We will see the minimal functions we need in this tutorial later. To learn detail of this, I will refer you to its documents.
For the data pipeline, we will use tofunlp/lineflow, a dataloader library for deep learning frameworks. This library provides a bunch of functions to ease data handling for NLP datasets. Additionally, it gives us common NLP dataset downloaders. So we don’t need to download datasets by ourselves anymore!
Using these tools, we will go through the following items in this tutorial.
Preprocess one famous paraphrase detection dataset.
Prepare one pre-trained strong language model (BERT).
Finally, fine-tune the BERT on paraphrase dataset with pytorch-lightning.
So let’s get started then!
If you don’t have time to read this article through, you can directly go to my GitHub repository, clone it, set up for it, run it.
First, we will take a look at the task that we are tackling today, Microsoft Research Paraphrase Corpus, a task that given two documents, models are asked to predict if they have the same meanings. For instance, two sentences like following, “It is an excellent day for a picnic!” and “In a day like this, I want to go for a picnic!”, have different surfaces but conceptually the same meanings. So we want our models to predict “TRUE” with this pair.
To use this dataset, all we have to do is use lineflow library I mentioned above.
import lineflow.datasets as lfds
train = lfds.MsrParaphrase('train')
test = lfds.MsrParaphrase('test')
The item in this dataset as follows:
>>> import lineflow.datasets as lfds
>>> train = lfds.MsrParaphrase('train')
>>> train.first()
{'quality': '1',
'id1': '702876',
'id2': '702977',
'string1': 'Amrozi accused his brother, whom he called "the witness", of deliberately distorting his evidence.',
'string2': 'Referring to him as only "the witness", Amrozi accused his brother of deliberately distorting his evidence.'
}
Calling MsrParphrase class in lineflow.datasets module, it downloads data from the web and gives you an iterator. In the sample above, you can see two sentences “sentence1” and “sentence2”, and quality (i.e., label). When quality is “1”, the pair is a paraphrase. If it’s “0”, the pair isn’t a paraphrase.
After we got this raw dataset, we want to convert this dataset into the format that BERT can process. Since BERT requires texts to be processed by BPE, we need to use the same tokenizer that BERT uses when it was pre-trained. But don’t worry, the transformers also provides it with a simple interface.
from transformers import BertTokenizertokenizer = BertTokenizer.from_pretrained("bert-base-uncased", do_lower_case=True)text = "Hello NLP lovers!"inputs = tokenizer.encode_plus(text, add_special_tokens=True, max_length=MAX_LEN)input_ids, token_type_ids = inputs["input_ids"], inputs["token_type_ids"]
By using tokenizer’s encode_plus function, we can do 1) tokenize a raw text, 2) replace tokens with corresponding ids, 3) insert special tokens for BERT. Cool! We can also pass this function a pair of texts so that it can be converted into the perfect format for our task, paraphrase identification.
sent1 = "It is an excellent day for a picnic!"sent2 = "In a day like this, I want to go for a picnic!"inputs = tokenizer.encode_plus(sent1, sent2, add_special_token=True, max_length=MAX_LEN)input_ids, token_type_ids = inputs["input_ids"], inputs["token_type_ids"]
So now we know how to encode input strings into BERT ready format. Next, let’s look at an actual code I wrote for this article.
In this, there are two main functions. First, preprocess: takes a data instance, and encode it to BERT format and pad the sequences. Second, get_dataloader: applies preprocess to all the instances in the dataset and make PyTorch DataLoader. This gist is a bit long, but it is just because I added some comment lines.
To get your BERT ready is very easy with transformers. You just need to choose which transformer-baed language model you want.
from transformers import BertForSequenceClassificationNUM_LABELS = 2 # For paraphrase identification, labels are binary, "paraphrase" or "not paraphrase".model = BertForSequenceClassification.from_pretrained("bert-base-uncased", num_labels=NUM_LABELS)
transformers provides BertModel, which is just a pre-trained BERT, here we can use BertForSequenceClassification instead. This is a PyTorch’s nn.Module class which contains pre-trained BERT plus initialized classification layer on top.
Yeah, this is it! Very easy, isn’t it?
We now have the data and model prepared, let’s put them together into a pytorch-lightning format so that we can run the fine-tuning process easy and simple.
As shown in the official document, there at least three methods you need implement to utilize pytorch-lightning’s LightningModule class, 1) train_dataloader, 2) training_step and 3) configure_optimizers. Let’s check how to write these methods for fine-tuning one by one.
In this function, we simply need to return the pytorch dataloader we implemented in the preprocessing section. I will skip the code here, check the repository if you don’t understand.
As it is shown in the pytorch-lighting docs, this function takes batch generated by dataloader we implemented. Then, pass the inputs in batch to the BertForSequenceClassification instance. Since we pass the correct labels with inputs, this model can just return the loss value. We do not even care about calculating the loss in this setting. After we obtained the loss from the model, we just follow the pytorch-lightning format, make a dictionary that contains the loss to be used for updating the model’s parameters.
This is pretty straightforward to implement too. As we can see in the official document, we just need to initialize PyTorch's optimizer and return. For optimizer’s configuration, we simply use the one from huggingface/transformers’s sample script. The actual code block would look like this.
Now, we have everything prepared. For the entire codes, you can check my GitHub repository here. In here, there are actually two scripts, one for Paraphrase detection we just went through, another one for CommonsenseQA.
In this article, we check how to use lineflow to download and preprocess the dataset. Then, use pytorch-lightning to fine-tune pre-trained BERT which is provided from transformers. I hope you enjoyed reading this article, and actually try to run the codes!
|
[
{
"code": null,
"e": 217,
"s": 172,
"text": "How to fine-tune BERT with pytorch-lightning"
},
{
"code": null,
"e": 234,
"s": 217,
"text": "What’s up world!"
},
{
"code": null,
"e": 358,
"s": 234,
"text": "I hope you are enjoying fine-tuning transformer-based language models on tasks of your interest and achieving cool results."
},
{
"code": null,
"e": 811,
"s": 358,
"text": "I assume quite many of you use this amazing transformers library from huggingface to fine-tune pre-trained language models. This is a library that lets you use state-of-the-art general-purpose (pre-trained) language models for PyTorch and Tensorflow. This library makes the process of downloading pretraining models very easy, plus the library also provides a set of python scripts so you can fine-tune the models on the task that you’re interested in."
},
{
"code": null,
"e": 931,
"s": 811,
"text": "Running provided scripts is very easy. However, when we want to add some changes to those scripts may get a bit tricky."
},
{
"code": null,
"e": 1078,
"s": 931,
"text": "But don’t worry, we are lucky that there are other amazing libraries out there that help you to implement clean and pretty script for fine-tuning."
},
{
"code": null,
"e": 1307,
"s": 1078,
"text": "pytorch-lightning is a lightweight PyTorch wrapper which frees you from writing boring training loops. We will see the minimal functions we need in this tutorial later. To learn detail of this, I will refer you to its documents."
},
{
"code": null,
"e": 1612,
"s": 1307,
"text": "For the data pipeline, we will use tofunlp/lineflow, a dataloader library for deep learning frameworks. This library provides a bunch of functions to ease data handling for NLP datasets. Additionally, it gives us common NLP dataset downloaders. So we don’t need to download datasets by ourselves anymore!"
},
{
"code": null,
"e": 1688,
"s": 1612,
"text": "Using these tools, we will go through the following items in this tutorial."
},
{
"code": null,
"e": 1740,
"s": 1688,
"text": "Preprocess one famous paraphrase detection dataset."
},
{
"code": null,
"e": 1794,
"s": 1740,
"text": "Prepare one pre-trained strong language model (BERT)."
},
{
"code": null,
"e": 1868,
"s": 1794,
"text": "Finally, fine-tune the BERT on paraphrase dataset with pytorch-lightning."
},
{
"code": null,
"e": 1895,
"s": 1868,
"text": "So let’s get started then!"
},
{
"code": null,
"e": 2026,
"s": 1895,
"text": "If you don’t have time to read this article through, you can directly go to my GitHub repository, clone it, set up for it, run it."
},
{
"code": null,
"e": 2477,
"s": 2026,
"text": "First, we will take a look at the task that we are tackling today, Microsoft Research Paraphrase Corpus, a task that given two documents, models are asked to predict if they have the same meanings. For instance, two sentences like following, “It is an excellent day for a picnic!” and “In a day like this, I want to go for a picnic!”, have different surfaces but conceptually the same meanings. So we want our models to predict “TRUE” with this pair."
},
{
"code": null,
"e": 2559,
"s": 2477,
"text": "To use this dataset, all we have to do is use lineflow library I mentioned above."
},
{
"code": null,
"e": 2663,
"s": 2559,
"text": "import lineflow.datasets as lfds\n\ntrain = lfds.MsrParaphrase('train')\ntest = lfds.MsrParaphrase('test')"
},
{
"code": null,
"e": 2700,
"s": 2663,
"text": "The item in this dataset as follows:"
},
{
"code": null,
"e": 3086,
"s": 2700,
"text": ">>> import lineflow.datasets as lfds\n>>> train = lfds.MsrParaphrase('train')\n>>> train.first()\n{'quality': '1',\n 'id1': '702876',\n 'id2': '702977',\n 'string1': 'Amrozi accused his brother, whom he called \"the witness\", of deliberately distorting his evidence.',\n 'string2': 'Referring to him as only \"the witness\", Amrozi accused his brother of deliberately distorting his evidence.'\n}"
},
{
"code": null,
"e": 3392,
"s": 3086,
"text": "Calling MsrParphrase class in lineflow.datasets module, it downloads data from the web and gives you an iterator. In the sample above, you can see two sentences “sentence1” and “sentence2”, and quality (i.e., label). When quality is “1”, the pair is a paraphrase. If it’s “0”, the pair isn’t a paraphrase."
},
{
"code": null,
"e": 3694,
"s": 3392,
"text": "After we got this raw dataset, we want to convert this dataset into the format that BERT can process. Since BERT requires texts to be processed by BPE, we need to use the same tokenizer that BERT uses when it was pre-trained. But don’t worry, the transformers also provides it with a simple interface."
},
{
"code": null,
"e": 3995,
"s": 3694,
"text": "from transformers import BertTokenizertokenizer = BertTokenizer.from_pretrained(\"bert-base-uncased\", do_lower_case=True)text = \"Hello NLP lovers!\"inputs = tokenizer.encode_plus(text, add_special_tokens=True, max_length=MAX_LEN)input_ids, token_type_ids = inputs[\"input_ids\"], inputs[\"token_type_ids\"]"
},
{
"code": null,
"e": 4295,
"s": 3995,
"text": "By using tokenizer’s encode_plus function, we can do 1) tokenize a raw text, 2) replace tokens with corresponding ids, 3) insert special tokens for BERT. Cool! We can also pass this function a pair of texts so that it can be converted into the perfect format for our task, paraphrase identification."
},
{
"code": null,
"e": 4559,
"s": 4295,
"text": "sent1 = \"It is an excellent day for a picnic!\"sent2 = \"In a day like this, I want to go for a picnic!\"inputs = tokenizer.encode_plus(sent1, sent2, add_special_token=True, max_length=MAX_LEN)input_ids, token_type_ids = inputs[\"input_ids\"], inputs[\"token_type_ids\"]"
},
{
"code": null,
"e": 4687,
"s": 4559,
"text": "So now we know how to encode input strings into BERT ready format. Next, let’s look at an actual code I wrote for this article."
},
{
"code": null,
"e": 5004,
"s": 4687,
"text": "In this, there are two main functions. First, preprocess: takes a data instance, and encode it to BERT format and pad the sequences. Second, get_dataloader: applies preprocess to all the instances in the dataset and make PyTorch DataLoader. This gist is a bit long, but it is just because I added some comment lines."
},
{
"code": null,
"e": 5131,
"s": 5004,
"text": "To get your BERT ready is very easy with transformers. You just need to choose which transformer-baed language model you want."
},
{
"code": null,
"e": 5384,
"s": 5131,
"text": "from transformers import BertForSequenceClassificationNUM_LABELS = 2 # For paraphrase identification, labels are binary, \"paraphrase\" or \"not paraphrase\".model = BertForSequenceClassification.from_pretrained(\"bert-base-uncased\", num_labels=NUM_LABELS)"
},
{
"code": null,
"e": 5620,
"s": 5384,
"text": "transformers provides BertModel, which is just a pre-trained BERT, here we can use BertForSequenceClassification instead. This is a PyTorch’s nn.Module class which contains pre-trained BERT plus initialized classification layer on top."
},
{
"code": null,
"e": 5659,
"s": 5620,
"text": "Yeah, this is it! Very easy, isn’t it?"
},
{
"code": null,
"e": 5816,
"s": 5659,
"text": "We now have the data and model prepared, let’s put them together into a pytorch-lightning format so that we can run the fine-tuning process easy and simple."
},
{
"code": null,
"e": 6087,
"s": 5816,
"text": "As shown in the official document, there at least three methods you need implement to utilize pytorch-lightning’s LightningModule class, 1) train_dataloader, 2) training_step and 3) configure_optimizers. Let’s check how to write these methods for fine-tuning one by one."
},
{
"code": null,
"e": 6271,
"s": 6087,
"text": "In this function, we simply need to return the pytorch dataloader we implemented in the preprocessing section. I will skip the code here, check the repository if you don’t understand."
},
{
"code": null,
"e": 6790,
"s": 6271,
"text": "As it is shown in the pytorch-lighting docs, this function takes batch generated by dataloader we implemented. Then, pass the inputs in batch to the BertForSequenceClassification instance. Since we pass the correct labels with inputs, this model can just return the loss value. We do not even care about calculating the loss in this setting. After we obtained the loss from the model, we just follow the pytorch-lightning format, make a dictionary that contains the loss to be used for updating the model’s parameters."
},
{
"code": null,
"e": 7082,
"s": 6790,
"text": "This is pretty straightforward to implement too. As we can see in the official document, we just need to initialize PyTorch's optimizer and return. For optimizer’s configuration, we simply use the one from huggingface/transformers’s sample script. The actual code block would look like this."
},
{
"code": null,
"e": 7302,
"s": 7082,
"text": "Now, we have everything prepared. For the entire codes, you can check my GitHub repository here. In here, there are actually two scripts, one for Paraphrase detection we just went through, another one for CommonsenseQA."
}
] |
clock() function in C/C++ - GeeksforGeeks
|
28 Sep, 2018
The clock() function is defined in the ctime header file. The clock() function returns the approximate processor time that is consumed by the program. The clock() time depends upon how the operating system allocate resources to the process that’s why clock() time may be slower or faster than the actual clock.
Syntax:
clock_t clock( void );
Parameters: This function does not accept any parameter.
Return Value: This function returns the approximate processor time that is consumed by the program and on failure function returns -1.
Below program illustrates the implementation of clock() function:
// C++ program to demonstrate// example of clock() function. #include<bits/stdc++.h>using namespace std; int main (){ float a; clock_t time_req; // Without using pow function time_req = clock(); for(int i=0; i<200000; i++) { a = log(i*i*i*i); } time_req = clock()- time_req; cout << "Processor time taken for multiplication: " << (float)time_req/CLOCKS_PER_SEC << " seconds" << endl; // Using pow function time_req = clock(); for(int i=0; i<200000; i++) { a = log(pow(i, 4)); } time_req = clock() - time_req; cout << "Processor time taken in pow function: " << (float)time_req/CLOCKS_PER_SEC << " seconds" << endl; return 0;}
Processor time taken for multiplication: 0.006485 seconds
Processor time taken in pow function: 0.022251 seconds
C-Functions
CPP-Functions
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Function Pointer in C
Core Dump (Segmentation fault) in C/C++
Substring in C++
Vector in C++ STL
Inheritance in C++
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
|
[
{
"code": null,
"e": 26131,
"s": 26103,
"text": "\n28 Sep, 2018"
},
{
"code": null,
"e": 26442,
"s": 26131,
"text": "The clock() function is defined in the ctime header file. The clock() function returns the approximate processor time that is consumed by the program. The clock() time depends upon how the operating system allocate resources to the process that’s why clock() time may be slower or faster than the actual clock."
},
{
"code": null,
"e": 26450,
"s": 26442,
"text": "Syntax:"
},
{
"code": null,
"e": 26473,
"s": 26450,
"text": "clock_t clock( void );"
},
{
"code": null,
"e": 26530,
"s": 26473,
"text": "Parameters: This function does not accept any parameter."
},
{
"code": null,
"e": 26665,
"s": 26530,
"text": "Return Value: This function returns the approximate processor time that is consumed by the program and on failure function returns -1."
},
{
"code": null,
"e": 26731,
"s": 26665,
"text": "Below program illustrates the implementation of clock() function:"
},
{
"code": "// C++ program to demonstrate// example of clock() function. #include<bits/stdc++.h>using namespace std; int main (){ float a; clock_t time_req; // Without using pow function time_req = clock(); for(int i=0; i<200000; i++) { a = log(i*i*i*i); } time_req = clock()- time_req; cout << \"Processor time taken for multiplication: \" << (float)time_req/CLOCKS_PER_SEC << \" seconds\" << endl; // Using pow function time_req = clock(); for(int i=0; i<200000; i++) { a = log(pow(i, 4)); } time_req = clock() - time_req; cout << \"Processor time taken in pow function: \" << (float)time_req/CLOCKS_PER_SEC << \" seconds\" << endl; return 0;}",
"e": 27444,
"s": 26731,
"text": null
},
{
"code": null,
"e": 27558,
"s": 27444,
"text": "Processor time taken for multiplication: 0.006485 seconds\nProcessor time taken in pow function: 0.022251 seconds\n"
},
{
"code": null,
"e": 27570,
"s": 27558,
"text": "C-Functions"
},
{
"code": null,
"e": 27584,
"s": 27570,
"text": "CPP-Functions"
},
{
"code": null,
"e": 27595,
"s": 27584,
"text": "C Language"
},
{
"code": null,
"e": 27599,
"s": 27595,
"text": "C++"
},
{
"code": null,
"e": 27603,
"s": 27599,
"text": "CPP"
},
{
"code": null,
"e": 27701,
"s": 27603,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27736,
"s": 27701,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 27782,
"s": 27736,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 27804,
"s": 27782,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 27844,
"s": 27804,
"text": "Core Dump (Segmentation fault) in C/C++"
},
{
"code": null,
"e": 27861,
"s": 27844,
"text": "Substring in C++"
},
{
"code": null,
"e": 27879,
"s": 27861,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 27898,
"s": 27879,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 27944,
"s": 27898,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 27987,
"s": 27944,
"text": "Map in C++ Standard Template Library (STL)"
}
] |
Ant Design Introduction and Installation for Angular - GeeksforGeeks
|
21 Aug, 2020
Ant Design is a design pattern for enterprise-level products that can be integrated with other front-end frameworks such as Angular, React, or Vue. Ant Design official implementation is released with React but it can be used with other JavaScript frameworks. It is an open-source tool with approximately 50.4K GitHub stars, it is the world’s second most used React UI library. Many companies are using this design pattern like Alibaba, Tencent, Didi, etc.
Features of Ant Design:
Supports internationalization.
Rich and interactive user interface.
Powerful theme customization.
High-quality components are present.
High performance.
Prerequisite:
A code editor like VSCode, Sublime, Brackets, etc.
NodeJS should be installed in the system
For Windows
https://www.geeksforgeeks.org/installation-of-node-js-on-windows/
For Linux
https://www.geeksforgeeks.org/installation-of-node-js-on-linux/
Knowledge of setting up an Angular Projecthttps://www.geeksforgeeks.org/angular-7-installation/Installation of Ant Design of AngularIn the terminal, go to that folder of the angular project which you have created, then install Ant Design of Angular by using the following command:npm install ng-zorro-antdIn “angular.json” file add Ant Design .css file in styles array as given below:{ "$schema": "./node_modules/@angular/cli/lib/config/schema.json", "version": 1, "newProjectRoot": "projects", "projects": { "myAntApp": { "projectType": "application", "schematics": { "@schematics/angular:component": { "style": "scss" } }, "root": "", "sourceRoot": "src", "prefix": "app", "architect": { "build": { "builder": "@angular-devkit/build-angular:browser", "options": { "outputPath": "dist/myAntApp", "index": "src/index.html", "main": "src/main.ts", "polyfills": "src/polyfills.ts", "tsConfig": "tsconfig.app.json", "aot": true, "assets": [ "src/favicon.ico", "src/assets" ], "styles": ["node_modules/ng-zorro-antd/src/ng-zorro-antd.min.css", "src/styles.scss" ], "scripts": [] }, "configurations": { "production": { "fileReplacements": [ { "replace": "src/environments/environment.ts", "with": "src/environments/environment.prod.ts" } ], "optimization": true, "outputHashing": "all", "sourceMap": false, "extractCss": true, "namedChunks": false, "extractLicenses": true, "vendorChunk": false, "buildOptimizer": true, "budgets": [ { "type": "initial", "maximumWarning": "2mb", "maximumError": "5mb" }, { "type": "anyComponentStyle", "maximumWarning": "6kb", "maximumError": "10kb" } ] } } }, "serve": { "builder": "@angular-devkit/build-angular:dev-server", "options": { "browserTarget": "myAntApp:build" }, "configurations": { "production": { "browserTarget": "myAntApp:build:production" } } }, "extract-i18n": { "builder": "@angular-devkit/build-angular:extract-i18n", "options": { "browserTarget": "myAntApp:build" } }, "test": { "builder": "@angular-devkit/build-angular:karma", "options": { "main": "src/test.ts", "polyfills": "src/polyfills.ts", "tsConfig": "tsconfig.spec.json", "karmaConfig": "karma.conf.js", "assets": [ "src/favicon.ico", "src/assets" ], "styles": [ "src/styles.scss" ], "scripts": [] } }, "lint": { "builder": "@angular-devkit/build-angular:tslint", "options": { "tsConfig": [ "tsconfig.app.json", "tsconfig.spec.json", "e2e/tsconfig.json" ], "exclude": [ "**/node_modules/**" ] } }, "e2e": { "builder": "@angular-devkit/build-angular:protractor", "options": { "protractorConfig": "e2e/protractor.conf.js", "devServerTarget": "myAntApp:serve" }, "configurations": { "production": { "devServerTarget": "myAntApp:serve:production" } } } } }}, "defaultProject": "myAntApp"}In “app.module.ts” import the Ant Design button module, so that we can access it in .html file as given below:import { BrowserModule } from '@angular/platform-browser';import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module';import { AppComponent } from './app.component';import { NzButtonModule } from 'ng-zorro-antd/button'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule, NzButtonModule ], providers: [], bootstrap: [AppComponent]})export class AppModule { }In “app.component.html” file add the following code as given below:<button nz-button nzType="primary">Primary</button><button nz-button nzType="default">Default</button><button nz-button nzType="dashed">Dashed</button>Add some CSS in “app.component.scss” to show the buttons at the center as given below:[nz-button] { margin-left: 50%; margin-top: 3%;}In the terminal, run the application in the browser by using the following command:ng serve -oOutput:Final Output in the browserMy Personal Notes
arrow_drop_upSave
https://www.geeksforgeeks.org/angular-7-installation/
Installation of Ant Design of Angular
In the terminal, go to that folder of the angular project which you have created, then install Ant Design of Angular by using the following command:
npm install ng-zorro-antd
In “angular.json” file add Ant Design .css file in styles array as given below:{ "$schema": "./node_modules/@angular/cli/lib/config/schema.json", "version": 1, "newProjectRoot": "projects", "projects": { "myAntApp": { "projectType": "application", "schematics": { "@schematics/angular:component": { "style": "scss" } }, "root": "", "sourceRoot": "src", "prefix": "app", "architect": { "build": { "builder": "@angular-devkit/build-angular:browser", "options": { "outputPath": "dist/myAntApp", "index": "src/index.html", "main": "src/main.ts", "polyfills": "src/polyfills.ts", "tsConfig": "tsconfig.app.json", "aot": true, "assets": [ "src/favicon.ico", "src/assets" ], "styles": ["node_modules/ng-zorro-antd/src/ng-zorro-antd.min.css", "src/styles.scss" ], "scripts": [] }, "configurations": { "production": { "fileReplacements": [ { "replace": "src/environments/environment.ts", "with": "src/environments/environment.prod.ts" } ], "optimization": true, "outputHashing": "all", "sourceMap": false, "extractCss": true, "namedChunks": false, "extractLicenses": true, "vendorChunk": false, "buildOptimizer": true, "budgets": [ { "type": "initial", "maximumWarning": "2mb", "maximumError": "5mb" }, { "type": "anyComponentStyle", "maximumWarning": "6kb", "maximumError": "10kb" } ] } } }, "serve": { "builder": "@angular-devkit/build-angular:dev-server", "options": { "browserTarget": "myAntApp:build" }, "configurations": { "production": { "browserTarget": "myAntApp:build:production" } } }, "extract-i18n": { "builder": "@angular-devkit/build-angular:extract-i18n", "options": { "browserTarget": "myAntApp:build" } }, "test": { "builder": "@angular-devkit/build-angular:karma", "options": { "main": "src/test.ts", "polyfills": "src/polyfills.ts", "tsConfig": "tsconfig.spec.json", "karmaConfig": "karma.conf.js", "assets": [ "src/favicon.ico", "src/assets" ], "styles": [ "src/styles.scss" ], "scripts": [] } }, "lint": { "builder": "@angular-devkit/build-angular:tslint", "options": { "tsConfig": [ "tsconfig.app.json", "tsconfig.spec.json", "e2e/tsconfig.json" ], "exclude": [ "**/node_modules/**" ] } }, "e2e": { "builder": "@angular-devkit/build-angular:protractor", "options": { "protractorConfig": "e2e/protractor.conf.js", "devServerTarget": "myAntApp:serve" }, "configurations": { "production": { "devServerTarget": "myAntApp:serve:production" } } } } }}, "defaultProject": "myAntApp"}
{ "$schema": "./node_modules/@angular/cli/lib/config/schema.json", "version": 1, "newProjectRoot": "projects", "projects": { "myAntApp": { "projectType": "application", "schematics": { "@schematics/angular:component": { "style": "scss" } }, "root": "", "sourceRoot": "src", "prefix": "app", "architect": { "build": { "builder": "@angular-devkit/build-angular:browser", "options": { "outputPath": "dist/myAntApp", "index": "src/index.html", "main": "src/main.ts", "polyfills": "src/polyfills.ts", "tsConfig": "tsconfig.app.json", "aot": true, "assets": [ "src/favicon.ico", "src/assets" ], "styles": ["node_modules/ng-zorro-antd/src/ng-zorro-antd.min.css", "src/styles.scss" ], "scripts": [] }, "configurations": { "production": { "fileReplacements": [ { "replace": "src/environments/environment.ts", "with": "src/environments/environment.prod.ts" } ], "optimization": true, "outputHashing": "all", "sourceMap": false, "extractCss": true, "namedChunks": false, "extractLicenses": true, "vendorChunk": false, "buildOptimizer": true, "budgets": [ { "type": "initial", "maximumWarning": "2mb", "maximumError": "5mb" }, { "type": "anyComponentStyle", "maximumWarning": "6kb", "maximumError": "10kb" } ] } } }, "serve": { "builder": "@angular-devkit/build-angular:dev-server", "options": { "browserTarget": "myAntApp:build" }, "configurations": { "production": { "browserTarget": "myAntApp:build:production" } } }, "extract-i18n": { "builder": "@angular-devkit/build-angular:extract-i18n", "options": { "browserTarget": "myAntApp:build" } }, "test": { "builder": "@angular-devkit/build-angular:karma", "options": { "main": "src/test.ts", "polyfills": "src/polyfills.ts", "tsConfig": "tsconfig.spec.json", "karmaConfig": "karma.conf.js", "assets": [ "src/favicon.ico", "src/assets" ], "styles": [ "src/styles.scss" ], "scripts": [] } }, "lint": { "builder": "@angular-devkit/build-angular:tslint", "options": { "tsConfig": [ "tsconfig.app.json", "tsconfig.spec.json", "e2e/tsconfig.json" ], "exclude": [ "**/node_modules/**" ] } }, "e2e": { "builder": "@angular-devkit/build-angular:protractor", "options": { "protractorConfig": "e2e/protractor.conf.js", "devServerTarget": "myAntApp:serve" }, "configurations": { "production": { "devServerTarget": "myAntApp:serve:production" } } } } }}, "defaultProject": "myAntApp"}
In “app.module.ts” import the Ant Design button module, so that we can access it in .html file as given below:import { BrowserModule } from '@angular/platform-browser';import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module';import { AppComponent } from './app.component';import { NzButtonModule } from 'ng-zorro-antd/button'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule, NzButtonModule ], providers: [], bootstrap: [AppComponent]})export class AppModule { }
import { BrowserModule } from '@angular/platform-browser';import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module';import { AppComponent } from './app.component';import { NzButtonModule } from 'ng-zorro-antd/button'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule, NzButtonModule ], providers: [], bootstrap: [AppComponent]})export class AppModule { }
In “app.component.html” file add the following code as given below:<button nz-button nzType="primary">Primary</button><button nz-button nzType="default">Default</button><button nz-button nzType="dashed">Dashed</button>
<button nz-button nzType="primary">Primary</button><button nz-button nzType="default">Default</button><button nz-button nzType="dashed">Dashed</button>
Add some CSS in “app.component.scss” to show the buttons at the center as given below:[nz-button] { margin-left: 50%; margin-top: 3%;}In the terminal, run the application in the browser by using the following command:ng serve -oOutput:Final Output in the browserMy Personal Notes
arrow_drop_upSave
[nz-button] { margin-left: 50%; margin-top: 3%;}
In the terminal, run the application in the browser by using the following command:ng serve -o
ng serve -o
Output:
Final Output in the browser
AngularJS-Misc
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Angular Libraries For Web Developers
How to use <mat-chip-list> and <mat-chip> in Angular Material ?
Angular 10 (blur) Event
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Angular PrimeNG Dropdown Component
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 25029,
"s": 25001,
"text": "\n21 Aug, 2020"
},
{
"code": null,
"e": 25485,
"s": 25029,
"text": "Ant Design is a design pattern for enterprise-level products that can be integrated with other front-end frameworks such as Angular, React, or Vue. Ant Design official implementation is released with React but it can be used with other JavaScript frameworks. It is an open-source tool with approximately 50.4K GitHub stars, it is the world’s second most used React UI library. Many companies are using this design pattern like Alibaba, Tencent, Didi, etc."
},
{
"code": null,
"e": 25509,
"s": 25485,
"text": "Features of Ant Design:"
},
{
"code": null,
"e": 25540,
"s": 25509,
"text": "Supports internationalization."
},
{
"code": null,
"e": 25577,
"s": 25540,
"text": "Rich and interactive user interface."
},
{
"code": null,
"e": 25607,
"s": 25577,
"text": "Powerful theme customization."
},
{
"code": null,
"e": 25644,
"s": 25607,
"text": "High-quality components are present."
},
{
"code": null,
"e": 25662,
"s": 25644,
"text": "High performance."
},
{
"code": null,
"e": 25676,
"s": 25662,
"text": "Prerequisite:"
},
{
"code": null,
"e": 25727,
"s": 25676,
"text": "A code editor like VSCode, Sublime, Brackets, etc."
},
{
"code": null,
"e": 25768,
"s": 25727,
"text": "NodeJS should be installed in the system"
},
{
"code": null,
"e": 25780,
"s": 25768,
"text": "For Windows"
},
{
"code": null,
"e": 25846,
"s": 25780,
"text": "https://www.geeksforgeeks.org/installation-of-node-js-on-windows/"
},
{
"code": null,
"e": 25856,
"s": 25846,
"text": "For Linux"
},
{
"code": null,
"e": 25920,
"s": 25856,
"text": "https://www.geeksforgeeks.org/installation-of-node-js-on-linux/"
},
{
"code": null,
"e": 30977,
"s": 25920,
"text": "Knowledge of setting up an Angular Projecthttps://www.geeksforgeeks.org/angular-7-installation/Installation of Ant Design of AngularIn the terminal, go to that folder of the angular project which you have created, then install Ant Design of Angular by using the following command:npm install ng-zorro-antdIn “angular.json” file add Ant Design .css file in styles array as given below:{ \"$schema\": \"./node_modules/@angular/cli/lib/config/schema.json\", \"version\": 1, \"newProjectRoot\": \"projects\", \"projects\": { \"myAntApp\": { \"projectType\": \"application\", \"schematics\": { \"@schematics/angular:component\": { \"style\": \"scss\" } }, \"root\": \"\", \"sourceRoot\": \"src\", \"prefix\": \"app\", \"architect\": { \"build\": { \"builder\": \"@angular-devkit/build-angular:browser\", \"options\": { \"outputPath\": \"dist/myAntApp\", \"index\": \"src/index.html\", \"main\": \"src/main.ts\", \"polyfills\": \"src/polyfills.ts\", \"tsConfig\": \"tsconfig.app.json\", \"aot\": true, \"assets\": [ \"src/favicon.ico\", \"src/assets\" ], \"styles\": [\"node_modules/ng-zorro-antd/src/ng-zorro-antd.min.css\", \"src/styles.scss\" ], \"scripts\": [] }, \"configurations\": { \"production\": { \"fileReplacements\": [ { \"replace\": \"src/environments/environment.ts\", \"with\": \"src/environments/environment.prod.ts\" } ], \"optimization\": true, \"outputHashing\": \"all\", \"sourceMap\": false, \"extractCss\": true, \"namedChunks\": false, \"extractLicenses\": true, \"vendorChunk\": false, \"buildOptimizer\": true, \"budgets\": [ { \"type\": \"initial\", \"maximumWarning\": \"2mb\", \"maximumError\": \"5mb\" }, { \"type\": \"anyComponentStyle\", \"maximumWarning\": \"6kb\", \"maximumError\": \"10kb\" } ] } } }, \"serve\": { \"builder\": \"@angular-devkit/build-angular:dev-server\", \"options\": { \"browserTarget\": \"myAntApp:build\" }, \"configurations\": { \"production\": { \"browserTarget\": \"myAntApp:build:production\" } } }, \"extract-i18n\": { \"builder\": \"@angular-devkit/build-angular:extract-i18n\", \"options\": { \"browserTarget\": \"myAntApp:build\" } }, \"test\": { \"builder\": \"@angular-devkit/build-angular:karma\", \"options\": { \"main\": \"src/test.ts\", \"polyfills\": \"src/polyfills.ts\", \"tsConfig\": \"tsconfig.spec.json\", \"karmaConfig\": \"karma.conf.js\", \"assets\": [ \"src/favicon.ico\", \"src/assets\" ], \"styles\": [ \"src/styles.scss\" ], \"scripts\": [] } }, \"lint\": { \"builder\": \"@angular-devkit/build-angular:tslint\", \"options\": { \"tsConfig\": [ \"tsconfig.app.json\", \"tsconfig.spec.json\", \"e2e/tsconfig.json\" ], \"exclude\": [ \"**/node_modules/**\" ] } }, \"e2e\": { \"builder\": \"@angular-devkit/build-angular:protractor\", \"options\": { \"protractorConfig\": \"e2e/protractor.conf.js\", \"devServerTarget\": \"myAntApp:serve\" }, \"configurations\": { \"production\": { \"devServerTarget\": \"myAntApp:serve:production\" } } } } }}, \"defaultProject\": \"myAntApp\"}In “app.module.ts” import the Ant Design button module, so that we can access it in .html file as given below:import { BrowserModule } from '@angular/platform-browser';import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module';import { AppComponent } from './app.component';import { NzButtonModule } from 'ng-zorro-antd/button'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule, NzButtonModule ], providers: [], bootstrap: [AppComponent]})export class AppModule { }In “app.component.html” file add the following code as given below:<button nz-button nzType=\"primary\">Primary</button><button nz-button nzType=\"default\">Default</button><button nz-button nzType=\"dashed\">Dashed</button>Add some CSS in “app.component.scss” to show the buttons at the center as given below:[nz-button] { margin-left: 50%; margin-top: 3%;}In the terminal, run the application in the browser by using the following command:ng serve -oOutput:Final Output in the browserMy Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 31031,
"s": 30977,
"text": "https://www.geeksforgeeks.org/angular-7-installation/"
},
{
"code": null,
"e": 31069,
"s": 31031,
"text": "Installation of Ant Design of Angular"
},
{
"code": null,
"e": 31218,
"s": 31069,
"text": "In the terminal, go to that folder of the angular project which you have created, then install Ant Design of Angular by using the following command:"
},
{
"code": null,
"e": 31244,
"s": 31218,
"text": "npm install ng-zorro-antd"
},
{
"code": null,
"e": 34917,
"s": 31244,
"text": "In “angular.json” file add Ant Design .css file in styles array as given below:{ \"$schema\": \"./node_modules/@angular/cli/lib/config/schema.json\", \"version\": 1, \"newProjectRoot\": \"projects\", \"projects\": { \"myAntApp\": { \"projectType\": \"application\", \"schematics\": { \"@schematics/angular:component\": { \"style\": \"scss\" } }, \"root\": \"\", \"sourceRoot\": \"src\", \"prefix\": \"app\", \"architect\": { \"build\": { \"builder\": \"@angular-devkit/build-angular:browser\", \"options\": { \"outputPath\": \"dist/myAntApp\", \"index\": \"src/index.html\", \"main\": \"src/main.ts\", \"polyfills\": \"src/polyfills.ts\", \"tsConfig\": \"tsconfig.app.json\", \"aot\": true, \"assets\": [ \"src/favicon.ico\", \"src/assets\" ], \"styles\": [\"node_modules/ng-zorro-antd/src/ng-zorro-antd.min.css\", \"src/styles.scss\" ], \"scripts\": [] }, \"configurations\": { \"production\": { \"fileReplacements\": [ { \"replace\": \"src/environments/environment.ts\", \"with\": \"src/environments/environment.prod.ts\" } ], \"optimization\": true, \"outputHashing\": \"all\", \"sourceMap\": false, \"extractCss\": true, \"namedChunks\": false, \"extractLicenses\": true, \"vendorChunk\": false, \"buildOptimizer\": true, \"budgets\": [ { \"type\": \"initial\", \"maximumWarning\": \"2mb\", \"maximumError\": \"5mb\" }, { \"type\": \"anyComponentStyle\", \"maximumWarning\": \"6kb\", \"maximumError\": \"10kb\" } ] } } }, \"serve\": { \"builder\": \"@angular-devkit/build-angular:dev-server\", \"options\": { \"browserTarget\": \"myAntApp:build\" }, \"configurations\": { \"production\": { \"browserTarget\": \"myAntApp:build:production\" } } }, \"extract-i18n\": { \"builder\": \"@angular-devkit/build-angular:extract-i18n\", \"options\": { \"browserTarget\": \"myAntApp:build\" } }, \"test\": { \"builder\": \"@angular-devkit/build-angular:karma\", \"options\": { \"main\": \"src/test.ts\", \"polyfills\": \"src/polyfills.ts\", \"tsConfig\": \"tsconfig.spec.json\", \"karmaConfig\": \"karma.conf.js\", \"assets\": [ \"src/favicon.ico\", \"src/assets\" ], \"styles\": [ \"src/styles.scss\" ], \"scripts\": [] } }, \"lint\": { \"builder\": \"@angular-devkit/build-angular:tslint\", \"options\": { \"tsConfig\": [ \"tsconfig.app.json\", \"tsconfig.spec.json\", \"e2e/tsconfig.json\" ], \"exclude\": [ \"**/node_modules/**\" ] } }, \"e2e\": { \"builder\": \"@angular-devkit/build-angular:protractor\", \"options\": { \"protractorConfig\": \"e2e/protractor.conf.js\", \"devServerTarget\": \"myAntApp:serve\" }, \"configurations\": { \"production\": { \"devServerTarget\": \"myAntApp:serve:production\" } } } } }}, \"defaultProject\": \"myAntApp\"}"
},
{
"code": "{ \"$schema\": \"./node_modules/@angular/cli/lib/config/schema.json\", \"version\": 1, \"newProjectRoot\": \"projects\", \"projects\": { \"myAntApp\": { \"projectType\": \"application\", \"schematics\": { \"@schematics/angular:component\": { \"style\": \"scss\" } }, \"root\": \"\", \"sourceRoot\": \"src\", \"prefix\": \"app\", \"architect\": { \"build\": { \"builder\": \"@angular-devkit/build-angular:browser\", \"options\": { \"outputPath\": \"dist/myAntApp\", \"index\": \"src/index.html\", \"main\": \"src/main.ts\", \"polyfills\": \"src/polyfills.ts\", \"tsConfig\": \"tsconfig.app.json\", \"aot\": true, \"assets\": [ \"src/favicon.ico\", \"src/assets\" ], \"styles\": [\"node_modules/ng-zorro-antd/src/ng-zorro-antd.min.css\", \"src/styles.scss\" ], \"scripts\": [] }, \"configurations\": { \"production\": { \"fileReplacements\": [ { \"replace\": \"src/environments/environment.ts\", \"with\": \"src/environments/environment.prod.ts\" } ], \"optimization\": true, \"outputHashing\": \"all\", \"sourceMap\": false, \"extractCss\": true, \"namedChunks\": false, \"extractLicenses\": true, \"vendorChunk\": false, \"buildOptimizer\": true, \"budgets\": [ { \"type\": \"initial\", \"maximumWarning\": \"2mb\", \"maximumError\": \"5mb\" }, { \"type\": \"anyComponentStyle\", \"maximumWarning\": \"6kb\", \"maximumError\": \"10kb\" } ] } } }, \"serve\": { \"builder\": \"@angular-devkit/build-angular:dev-server\", \"options\": { \"browserTarget\": \"myAntApp:build\" }, \"configurations\": { \"production\": { \"browserTarget\": \"myAntApp:build:production\" } } }, \"extract-i18n\": { \"builder\": \"@angular-devkit/build-angular:extract-i18n\", \"options\": { \"browserTarget\": \"myAntApp:build\" } }, \"test\": { \"builder\": \"@angular-devkit/build-angular:karma\", \"options\": { \"main\": \"src/test.ts\", \"polyfills\": \"src/polyfills.ts\", \"tsConfig\": \"tsconfig.spec.json\", \"karmaConfig\": \"karma.conf.js\", \"assets\": [ \"src/favicon.ico\", \"src/assets\" ], \"styles\": [ \"src/styles.scss\" ], \"scripts\": [] } }, \"lint\": { \"builder\": \"@angular-devkit/build-angular:tslint\", \"options\": { \"tsConfig\": [ \"tsconfig.app.json\", \"tsconfig.spec.json\", \"e2e/tsconfig.json\" ], \"exclude\": [ \"**/node_modules/**\" ] } }, \"e2e\": { \"builder\": \"@angular-devkit/build-angular:protractor\", \"options\": { \"protractorConfig\": \"e2e/protractor.conf.js\", \"devServerTarget\": \"myAntApp:serve\" }, \"configurations\": { \"production\": { \"devServerTarget\": \"myAntApp:serve:production\" } } } } }}, \"defaultProject\": \"myAntApp\"}",
"e": 38511,
"s": 34917,
"text": null
},
{
"code": null,
"e": 39074,
"s": 38511,
"text": "In “app.module.ts” import the Ant Design button module, so that we can access it in .html file as given below:import { BrowserModule } from '@angular/platform-browser';import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module';import { AppComponent } from './app.component';import { NzButtonModule } from 'ng-zorro-antd/button'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule, NzButtonModule ], providers: [], bootstrap: [AppComponent]})export class AppModule { }"
},
{
"code": "import { BrowserModule } from '@angular/platform-browser';import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module';import { AppComponent } from './app.component';import { NzButtonModule } from 'ng-zorro-antd/button'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule, NzButtonModule ], providers: [], bootstrap: [AppComponent]})export class AppModule { }",
"e": 39527,
"s": 39074,
"text": null
},
{
"code": null,
"e": 39746,
"s": 39527,
"text": "In “app.component.html” file add the following code as given below:<button nz-button nzType=\"primary\">Primary</button><button nz-button nzType=\"default\">Default</button><button nz-button nzType=\"dashed\">Dashed</button>"
},
{
"code": "<button nz-button nzType=\"primary\">Primary</button><button nz-button nzType=\"default\">Default</button><button nz-button nzType=\"dashed\">Dashed</button>",
"e": 39898,
"s": 39746,
"text": null
},
{
"code": null,
"e": 40198,
"s": 39898,
"text": "Add some CSS in “app.component.scss” to show the buttons at the center as given below:[nz-button] { margin-left: 50%; margin-top: 3%;}In the terminal, run the application in the browser by using the following command:ng serve -oOutput:Final Output in the browserMy Personal Notes\narrow_drop_upSave"
},
{
"code": "[nz-button] { margin-left: 50%; margin-top: 3%;}",
"e": 40249,
"s": 40198,
"text": null
},
{
"code": null,
"e": 40344,
"s": 40249,
"text": "In the terminal, run the application in the browser by using the following command:ng serve -o"
},
{
"code": null,
"e": 40356,
"s": 40344,
"text": "ng serve -o"
},
{
"code": null,
"e": 40364,
"s": 40356,
"text": "Output:"
},
{
"code": null,
"e": 40392,
"s": 40364,
"text": "Final Output in the browser"
},
{
"code": null,
"e": 40407,
"s": 40392,
"text": "AngularJS-Misc"
},
{
"code": null,
"e": 40417,
"s": 40407,
"text": "AngularJS"
},
{
"code": null,
"e": 40434,
"s": 40417,
"text": "Web Technologies"
},
{
"code": null,
"e": 40532,
"s": 40434,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40541,
"s": 40532,
"text": "Comments"
},
{
"code": null,
"e": 40554,
"s": 40541,
"text": "Old Comments"
},
{
"code": null,
"e": 40598,
"s": 40554,
"text": "Top 10 Angular Libraries For Web Developers"
},
{
"code": null,
"e": 40662,
"s": 40598,
"text": "How to use <mat-chip-list> and <mat-chip> in Angular Material ?"
},
{
"code": null,
"e": 40686,
"s": 40662,
"text": "Angular 10 (blur) Event"
},
{
"code": null,
"e": 40739,
"s": 40686,
"text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?"
},
{
"code": null,
"e": 40774,
"s": 40739,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 40816,
"s": 40774,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 40849,
"s": 40816,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 40911,
"s": 40849,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 40954,
"s": 40911,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Check if all array elements are pairwise co-prime or not - GeeksforGeeks
|
02 Jun, 2021
Given an array A[] consisting of N positive integers, the task is to check if all the array elements are pairwise co-prime, i.e. for all pairs (Ai , Aj), such that 1<=i<j<=N, GCD(Ai, Aj) = 1.
Examples:
Input : A[] = {2, 3, 5}Output : YesExplanation : All the pairs, (2, 3), (3, 5), (2, 5) are pairwise co-prime.
Input : A[] = {5, 10}Output : NoExplanation : GCD(5, 10)=5 so they are not co-prime.
Naive Approach: The simplest approach to solve the problem is to generate all possible pairs from a given array and for each pair, check if it is coprime or not. If any pair is found to be non-coprime, print “No“. Otherwise, print “Yes“.Time Complexity: O(N2)Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized based on the following observation:
If any two numbers have a common prime factor, then their GCD can never be 1.
This can also be interpreted as:
The LCM of the array must be equal to the product of the elements in the array.
Therefore, the solution boils down to calculating the LCM of the given array and check if it is equal to the product of all the array elements or not.
Below is the implementation of the above approach :
C++
Java
Python3
C#
Javascript
// C++ Program for the above approach#include <bits/stdc++.h>using namespace std;#define ll long long int // Function to calculate GCDll GCD(ll a, ll b){ if (a == 0) return b; return GCD(b % a, a);} // Function to calculate LCMll LCM(ll a, ll b){ return (a * b) / GCD(a, b);} // Function to check if all elements// in the array are pairwise coprimevoid checkPairwiseCoPrime(int A[], int n){ // Initialize variables ll prod = 1; ll lcm = 1; // Iterate over the array for (int i = 0; i < n; i++) { // Calculate product of // array elements prod *= A[i]; // Calculate LCM of // array elements lcm = LCM(A[i], lcm); } // If the product of array elements // is equal to LCM of the array if (prod == lcm) cout << "Yes" << endl; else cout << "No" << endl;}// Driver Codeint main(){ int A[] = { 2, 3, 5 }; int n = sizeof(A) / sizeof(A[0]); // Function call checkPairwiseCoPrime(A, n);}
// Java program for the above approachimport java.util.*;import java.lang.*; class GFG{ // Function to calculate GCDstatic long GCD(long a, long b){ if (a == 0) return b; return GCD(b % a, a);} // Function to calculate LCMstatic long LCM(long a, long b){ return (a * b) / GCD(a, b);} // Function to check if all elements// in the array are pairwise coprimestatic void checkPairwiseCoPrime(int A[], int n){ // Initialize variables long prod = 1; long lcm = 1; // Iterate over the array for(int i = 0; i < n; i++) { // Calculate product of // array elements prod *= A[i]; // Calculate LCM of // array elements lcm = LCM(A[i], lcm); } // If the product of array elements // is equal to LCM of the array if (prod == lcm) System.out.println("Yes"); else System.out.println("No");} // Driver Codepublic static void main (String[] args){ int A[] = { 2, 3, 5 }; int n = A.length; // Function call checkPairwiseCoPrime(A, n);}} // This code is contributed by offbeat
# Python3 program for the above approach # Function to calculate GCDdef GCD(a, b): if (a == 0): return b return GCD(b % a, a) # Function to calculate LCMdef LCM(a, b): return (a * b) // GCD(a, b) # Function to check if aelements# in the array are pairwise coprimedef checkPairwiseCoPrime(A, n): # Initialize variables prod = 1 lcm = 1 # Iterate over the array for i in range(n): # Calculate product of # array elements prod *= A[i] # Calculate LCM of # array elements lcm = LCM(A[i], lcm) # If the product of array elements # is equal to LCM of the array if (prod == lcm): print("Yes") else: print("No") # Driver Codeif __name__ == '__main__': A = [ 2, 3, 5 ] n = len(A) # Function call checkPairwiseCoPrime(A, n) # This code is contributed by mohit kumar 29
// C# program for// the above approachusing System;using System.Collections.Generic;class GFG{ // Function to calculate GCDstatic long GCD(long a, long b){ if (a == 0) return b; return GCD(b % a, a);} // Function to calculate LCMstatic long LCM(long a, long b){ return (a * b) / GCD(a, b);} // Function to check if all elements// in the array are pairwise coprimestatic void checkPairwiseCoPrime(int []A, int n){ // Initialize variables long prod = 1; long lcm = 1; // Iterate over the array for(int i = 0; i < n; i++) { // Calculate product of // array elements prod *= A[i]; // Calculate LCM of // array elements lcm = LCM(A[i], lcm); } // If the product of array elements // is equal to LCM of the array if (prod == lcm) Console.WriteLine("Yes"); else Console.WriteLine("No");} // Driver Codepublic static void Main(String[] args){ int []A = {2, 3, 5}; int n = A.Length; // Function call checkPairwiseCoPrime(A, n);}} // This code is contributed by Rajput-Ji
<script>// javascript program for the above approach // Function to calculate GCD function GCD(a , b) { if (a == 0) return b; return GCD(b % a, a); } // Function to calculate LCM function LCM(a , b) { return (a * b) / GCD(a, b); } // Function to check if all elements // in the array are pairwise coprime function checkPairwiseCoPrime(A , n) { // Initialize variables var prod = 1; var lcm = 1; // Iterate over the array for (i = 0; i < n; i++) { // Calculate product of // array elements prod *= A[i]; // Calculate LCM of // array elements lcm = LCM(A[i], lcm); } // If the product of array elements // is equal to LCM of the array if (prod == lcm) document.write("Yes"); else document.write("No"); } // Driver Code var A = [ 2, 3, 5 ]; var n = A.length; // Function call checkPairwiseCoPrime(A, n); // This code contributed by umadevi9616</script>
Yes
Time Complexity: O(N log (min(A[i])))Auxiliary Space: O(1)
mohit kumar 29
offbeat
Rajput-Ji
umadevi9616
arorakashish0911
surinderdawra388
GCD-LCM
prime-factor
Arrays
Greedy
Mathematical
Searching
Arrays
Searching
Greedy
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Introduction to Arrays
Multidimensional Arrays in Java
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
Write a program to print all permutations of a given string
Huffman Coding | Greedy Algo-3
|
[
{
"code": null,
"e": 26025,
"s": 25997,
"text": "\n02 Jun, 2021"
},
{
"code": null,
"e": 26217,
"s": 26025,
"text": "Given an array A[] consisting of N positive integers, the task is to check if all the array elements are pairwise co-prime, i.e. for all pairs (Ai , Aj), such that 1<=i<j<=N, GCD(Ai, Aj) = 1."
},
{
"code": null,
"e": 26228,
"s": 26217,
"text": "Examples: "
},
{
"code": null,
"e": 26338,
"s": 26228,
"text": "Input : A[] = {2, 3, 5}Output : YesExplanation : All the pairs, (2, 3), (3, 5), (2, 5) are pairwise co-prime."
},
{
"code": null,
"e": 26423,
"s": 26338,
"text": "Input : A[] = {5, 10}Output : NoExplanation : GCD(5, 10)=5 so they are not co-prime."
},
{
"code": null,
"e": 26704,
"s": 26423,
"text": "Naive Approach: The simplest approach to solve the problem is to generate all possible pairs from a given array and for each pair, check if it is coprime or not. If any pair is found to be non-coprime, print “No“. Otherwise, print “Yes“.Time Complexity: O(N2)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 26797,
"s": 26704,
"text": "Efficient Approach: The above approach can be optimized based on the following observation: "
},
{
"code": null,
"e": 26877,
"s": 26797,
"text": "If any two numbers have a common prime factor, then their GCD can never be 1. "
},
{
"code": null,
"e": 26911,
"s": 26877,
"text": "This can also be interpreted as: "
},
{
"code": null,
"e": 26991,
"s": 26911,
"text": "The LCM of the array must be equal to the product of the elements in the array."
},
{
"code": null,
"e": 27142,
"s": 26991,
"text": "Therefore, the solution boils down to calculating the LCM of the given array and check if it is equal to the product of all the array elements or not."
},
{
"code": null,
"e": 27194,
"s": 27142,
"text": "Below is the implementation of the above approach :"
},
{
"code": null,
"e": 27198,
"s": 27194,
"text": "C++"
},
{
"code": null,
"e": 27203,
"s": 27198,
"text": "Java"
},
{
"code": null,
"e": 27211,
"s": 27203,
"text": "Python3"
},
{
"code": null,
"e": 27214,
"s": 27211,
"text": "C#"
},
{
"code": null,
"e": 27225,
"s": 27214,
"text": "Javascript"
},
{
"code": "// C++ Program for the above approach#include <bits/stdc++.h>using namespace std;#define ll long long int // Function to calculate GCDll GCD(ll a, ll b){ if (a == 0) return b; return GCD(b % a, a);} // Function to calculate LCMll LCM(ll a, ll b){ return (a * b) / GCD(a, b);} // Function to check if all elements// in the array are pairwise coprimevoid checkPairwiseCoPrime(int A[], int n){ // Initialize variables ll prod = 1; ll lcm = 1; // Iterate over the array for (int i = 0; i < n; i++) { // Calculate product of // array elements prod *= A[i]; // Calculate LCM of // array elements lcm = LCM(A[i], lcm); } // If the product of array elements // is equal to LCM of the array if (prod == lcm) cout << \"Yes\" << endl; else cout << \"No\" << endl;}// Driver Codeint main(){ int A[] = { 2, 3, 5 }; int n = sizeof(A) / sizeof(A[0]); // Function call checkPairwiseCoPrime(A, n);}",
"e": 28229,
"s": 27225,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*;import java.lang.*; class GFG{ // Function to calculate GCDstatic long GCD(long a, long b){ if (a == 0) return b; return GCD(b % a, a);} // Function to calculate LCMstatic long LCM(long a, long b){ return (a * b) / GCD(a, b);} // Function to check if all elements// in the array are pairwise coprimestatic void checkPairwiseCoPrime(int A[], int n){ // Initialize variables long prod = 1; long lcm = 1; // Iterate over the array for(int i = 0; i < n; i++) { // Calculate product of // array elements prod *= A[i]; // Calculate LCM of // array elements lcm = LCM(A[i], lcm); } // If the product of array elements // is equal to LCM of the array if (prod == lcm) System.out.println(\"Yes\"); else System.out.println(\"No\");} // Driver Codepublic static void main (String[] args){ int A[] = { 2, 3, 5 }; int n = A.length; // Function call checkPairwiseCoPrime(A, n);}} // This code is contributed by offbeat",
"e": 29339,
"s": 28229,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to calculate GCDdef GCD(a, b): if (a == 0): return b return GCD(b % a, a) # Function to calculate LCMdef LCM(a, b): return (a * b) // GCD(a, b) # Function to check if aelements# in the array are pairwise coprimedef checkPairwiseCoPrime(A, n): # Initialize variables prod = 1 lcm = 1 # Iterate over the array for i in range(n): # Calculate product of # array elements prod *= A[i] # Calculate LCM of # array elements lcm = LCM(A[i], lcm) # If the product of array elements # is equal to LCM of the array if (prod == lcm): print(\"Yes\") else: print(\"No\") # Driver Codeif __name__ == '__main__': A = [ 2, 3, 5 ] n = len(A) # Function call checkPairwiseCoPrime(A, n) # This code is contributed by mohit kumar 29",
"e": 30243,
"s": 29339,
"text": null
},
{
"code": "// C# program for// the above approachusing System;using System.Collections.Generic;class GFG{ // Function to calculate GCDstatic long GCD(long a, long b){ if (a == 0) return b; return GCD(b % a, a);} // Function to calculate LCMstatic long LCM(long a, long b){ return (a * b) / GCD(a, b);} // Function to check if all elements// in the array are pairwise coprimestatic void checkPairwiseCoPrime(int []A, int n){ // Initialize variables long prod = 1; long lcm = 1; // Iterate over the array for(int i = 0; i < n; i++) { // Calculate product of // array elements prod *= A[i]; // Calculate LCM of // array elements lcm = LCM(A[i], lcm); } // If the product of array elements // is equal to LCM of the array if (prod == lcm) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\");} // Driver Codepublic static void Main(String[] args){ int []A = {2, 3, 5}; int n = A.Length; // Function call checkPairwiseCoPrime(A, n);}} // This code is contributed by Rajput-Ji",
"e": 31320,
"s": 30243,
"text": null
},
{
"code": "<script>// javascript program for the above approach // Function to calculate GCD function GCD(a , b) { if (a == 0) return b; return GCD(b % a, a); } // Function to calculate LCM function LCM(a , b) { return (a * b) / GCD(a, b); } // Function to check if all elements // in the array are pairwise coprime function checkPairwiseCoPrime(A , n) { // Initialize variables var prod = 1; var lcm = 1; // Iterate over the array for (i = 0; i < n; i++) { // Calculate product of // array elements prod *= A[i]; // Calculate LCM of // array elements lcm = LCM(A[i], lcm); } // If the product of array elements // is equal to LCM of the array if (prod == lcm) document.write(\"Yes\"); else document.write(\"No\"); } // Driver Code var A = [ 2, 3, 5 ]; var n = A.length; // Function call checkPairwiseCoPrime(A, n); // This code contributed by umadevi9616</script>",
"e": 32435,
"s": 31320,
"text": null
},
{
"code": null,
"e": 32439,
"s": 32435,
"text": "Yes"
},
{
"code": null,
"e": 32498,
"s": 32439,
"text": "Time Complexity: O(N log (min(A[i])))Auxiliary Space: O(1)"
},
{
"code": null,
"e": 32513,
"s": 32498,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 32521,
"s": 32513,
"text": "offbeat"
},
{
"code": null,
"e": 32531,
"s": 32521,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 32543,
"s": 32531,
"text": "umadevi9616"
},
{
"code": null,
"e": 32560,
"s": 32543,
"text": "arorakashish0911"
},
{
"code": null,
"e": 32577,
"s": 32560,
"text": "surinderdawra388"
},
{
"code": null,
"e": 32585,
"s": 32577,
"text": "GCD-LCM"
},
{
"code": null,
"e": 32598,
"s": 32585,
"text": "prime-factor"
},
{
"code": null,
"e": 32605,
"s": 32598,
"text": "Arrays"
},
{
"code": null,
"e": 32612,
"s": 32605,
"text": "Greedy"
},
{
"code": null,
"e": 32625,
"s": 32612,
"text": "Mathematical"
},
{
"code": null,
"e": 32635,
"s": 32625,
"text": "Searching"
},
{
"code": null,
"e": 32642,
"s": 32635,
"text": "Arrays"
},
{
"code": null,
"e": 32652,
"s": 32642,
"text": "Searching"
},
{
"code": null,
"e": 32659,
"s": 32652,
"text": "Greedy"
},
{
"code": null,
"e": 32672,
"s": 32659,
"text": "Mathematical"
},
{
"code": null,
"e": 32770,
"s": 32672,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32838,
"s": 32770,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 32882,
"s": 32838,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 32930,
"s": 32882,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 32953,
"s": 32930,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 32985,
"s": 32953,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 33036,
"s": 32985,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 33094,
"s": 33036,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 33145,
"s": 33094,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
},
{
"code": null,
"e": 33205,
"s": 33145,
"text": "Write a program to print all permutations of a given string"
}
] |
Check if a given string is Even-Odd Palindrome or not - GeeksforGeeks
|
07 Apr, 2021
Given a string str, the task is to check if the given string is Even-Odd Palindrome or not.
An Even-Odd Palindrome string is defined to be a string whose characters at even indices form a Palindrome while the characters at odd indices also form a Palindrome separately.
Examples:
Input: str=”abzzab” Output:YES Explanation: String formed by characters at odd indices: bzb, which is a Palindrome. String formed by characters at even indices: aza, which is a Palindrome. Hence, the given string is an Even-Odd Palindrome.Input: str=”daccad” Output: NO
Approach: To solve the problem, create a new String by appending the Odd Indexed Characters of the given string and check if the strings formed are palindromic or not. Similarly, check for Even Indexed Characters. If both the strings are palindromic, then print “Yes”. Otherwise, print “No”.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to check if the string// str is palindromic or notbool isPalindrome(string str){ // Pointers to iterate the // string from both ends int l = 0; int h = str.size() - 1; while (h > l) { // If characters are found // to be distinct if (str[l++] != str[h--]) { return false; } } // Return true if the // string is palindromic return true;} // Function to generate string// from characters at odd indicesstring makeOddString(string str){ string odd = ""; for (int i = 1; i < str.size(); i += 2) { odd += str[i]; } return odd;} // Function to generate string// from characters at even indicesstring makeevenString(string str){ string even = ""; for (int i = 0; i < str.size(); i += 2) { even += str[i]; } return even;} // Functions to checks if string// is Even-Odd Palindrome or notvoid checkevenOddPalindrome(string str){ // Generate odd indexed string string odd = makeOddString(str); // Generate even indexed string string even = makeevenString(str); // Check for Palindrome if (isPalindrome(odd) && isPalindrome(even)) cout << "Yes" << endl; else cout << "No" << endl;} // Driver Codeint main(){ string str = "abzzab"; checkevenOddPalindrome(str); return 0;}
// Java program implementation// of the approachimport java.util.*;import java.io.*; class GFG{ // Function to check if the string// str is palindromic or notstatic boolean isPalindrome(String str){ // Pointers to iterate the // string from both ends int l = 0; int h = str.length() - 1; while (h > l) { // If characters are found // to be distinct if (str.charAt(l++) != str.charAt(h--)) return false; } // Return true if the // string is palindromic return true;} // Function to generate string// from characters at odd indicesstatic String makeOddString(String str){ String odd = ""; for(int i = 1; i < str.length(); i += 2) { odd += str.charAt(i); } return odd;} // Function to generate string// from characters at even indicesstatic String makeevenString(String str){ String even = ""; for(int i = 0; i < str.length(); i += 2) { even += str.charAt(i); } return even;} // Functions to checks if string// is Even-Odd Palindrome or notstatic void checkevenOddPalindrome(String str){ // Generate odd indexed string String odd = makeOddString(str); // Generate even indexed string String even = makeevenString(str); // Check for Palindrome if (isPalindrome(odd) && isPalindrome(even)) System.out.println("Yes"); else System.out.println("No");} // Driver codepublic static void main(String[] args){ String str = "abzzab"; checkevenOddPalindrome(str);}} // This code is contributed by sanjoy_62
# Python3 program to implement# the above approach # Function to check if the string# str is palindromic or notdef isPalindrome(Str): # Pointers to iterate the # string from both ends l = 0 h = len(Str) - 1 while (h > l): # If characters are found # to be distinct if (Str[l] != Str[h]): return False l += 1 h -= 1 # Return true if the # string is palindromic return True # Function to generate string# from characters at odd indicesdef makeOddString(Str): odd = "" for i in range(1, len(Str), 2): odd += Str[i] return odd # Function to generate string# from characters at even indicesdef makeevenString(Str): even = "" for i in range(0, len(Str), 2): even += Str[i] return even # Functions to checks if string# is Even-Odd Palindrome or notdef checkevenOddPalindrome(Str): # Generate odd indexed string odd = makeOddString(Str) # Generate even indexed string even = makeevenString(Str) # Check for Palindrome if (isPalindrome(odd) and isPalindrome(even)): print("Yes") else: print("No") # Driver codeStr = "abzzab" checkevenOddPalindrome(Str) # This code is contributed by himanshu77
// C# program implementation// of the approachusing System; class GFG{ // Function to check if the string// str is palindromic or notstatic bool isPalindrome(string str){ // Pointers to iterate the // string from both ends int l = 0; int h = str.Length - 1; while (h > l) { // If characters are found // to be distinct if (str[l++] != str[h--]) return false; } // Return true if the // string is palindromic return true;} // Function to generate string// from characters at odd indicesstatic string makeOddString(string str){ string odd = ""; for(int i = 1; i < str.Length; i += 2) { odd += str[i]; } return odd;} // Function to generate string// from characters at even indicesstatic string makeevenString(string str){ string even = ""; for(int i = 0; i < str.Length; i += 2) { even += str[i]; } return even;} // Functions to checks if string// is Even-Odd Palindrome or notstatic void checkevenOddPalindrome(string str){ // Generate odd indexed string string odd = makeOddString(str); // Generate even indexed string string even = makeevenString(str); // Check for Palindrome if (isPalindrome(odd) && isPalindrome(even)) Console.WriteLine("Yes"); else Console.WriteLine("No");} // Driver codepublic static void Main(){ string str = "abzzab"; checkevenOddPalindrome(str);}} // This code is contributed by sanjoy_62
<script> // Javascript program implementation// of the approach // Function to check if the string// str is palindromic or notfunction isPalindrome(str){ // Pointers to iterate the // string from both ends var l = 0; var h = str.length - 1; while (h > l) { // If characters are found // to be distinct if (str.charAt(l++) != str.charAt(h--)) return false; } // Return true if the // string is palindromic return true;} // Function to generate string// from characters at odd indicesfunction makeOddString(str){ var odd = ""; for(var i = 1; i < str.length; i += 2) { odd += str.charAt(i); } return odd;} // Function to generate string// from characters at even indicesfunction makeevenString(str){ var even = ""; for(var i = 0; i < str.length; i += 2) { even += str.charAt(i); } return even;} // Functions to checks if string// is Even-Odd Palindrome or notfunction checkevenOddPalindrome(str){ // Generate odd indexed string var odd = makeOddString(str); // Generate even indexed string var even = makeevenString(str); // Check for Palindrome if (isPalindrome(odd) && isPalindrome(even)) document.write("Yes"); else document.write("No");} // Driver codevar str = "abzzab"; checkevenOddPalindrome(str); // This code is contributed by Khushboogoyal499 </script>
Yes
sanjoy_62
himanshu77
khushboogoyal499
palindrome
Competitive Programming
School Programming
Strings
Strings
palindrome
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multistage Graph (Shortest Path)
Breadth First Traversal ( BFS ) on a 2D array
Difference between Backtracking and Branch-N-Bound technique
5 Best Languages for Competitive Programming
Minimum changes required to make all Array elements Prime
Python Dictionary
Arrays in C/C++
Inheritance in C++
Reverse a string in Java
C++ Classes and Objects
|
[
{
"code": null,
"e": 26365,
"s": 26337,
"text": "\n07 Apr, 2021"
},
{
"code": null,
"e": 26458,
"s": 26365,
"text": "Given a string str, the task is to check if the given string is Even-Odd Palindrome or not. "
},
{
"code": null,
"e": 26637,
"s": 26458,
"text": "An Even-Odd Palindrome string is defined to be a string whose characters at even indices form a Palindrome while the characters at odd indices also form a Palindrome separately. "
},
{
"code": null,
"e": 26649,
"s": 26637,
"text": "Examples: "
},
{
"code": null,
"e": 26921,
"s": 26649,
"text": "Input: str=”abzzab” Output:YES Explanation: String formed by characters at odd indices: bzb, which is a Palindrome. String formed by characters at even indices: aza, which is a Palindrome. Hence, the given string is an Even-Odd Palindrome.Input: str=”daccad” Output: NO "
},
{
"code": null,
"e": 27265,
"s": 26921,
"text": "Approach: To solve the problem, create a new String by appending the Odd Indexed Characters of the given string and check if the strings formed are palindromic or not. Similarly, check for Even Indexed Characters. If both the strings are palindromic, then print “Yes”. Otherwise, print “No”.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27269,
"s": 27265,
"text": "C++"
},
{
"code": null,
"e": 27274,
"s": 27269,
"text": "Java"
},
{
"code": null,
"e": 27282,
"s": 27274,
"text": "Python3"
},
{
"code": null,
"e": 27285,
"s": 27282,
"text": "C#"
},
{
"code": null,
"e": 27296,
"s": 27285,
"text": "Javascript"
},
{
"code": "// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to check if the string// str is palindromic or notbool isPalindrome(string str){ // Pointers to iterate the // string from both ends int l = 0; int h = str.size() - 1; while (h > l) { // If characters are found // to be distinct if (str[l++] != str[h--]) { return false; } } // Return true if the // string is palindromic return true;} // Function to generate string// from characters at odd indicesstring makeOddString(string str){ string odd = \"\"; for (int i = 1; i < str.size(); i += 2) { odd += str[i]; } return odd;} // Function to generate string// from characters at even indicesstring makeevenString(string str){ string even = \"\"; for (int i = 0; i < str.size(); i += 2) { even += str[i]; } return even;} // Functions to checks if string// is Even-Odd Palindrome or notvoid checkevenOddPalindrome(string str){ // Generate odd indexed string string odd = makeOddString(str); // Generate even indexed string string even = makeevenString(str); // Check for Palindrome if (isPalindrome(odd) && isPalindrome(even)) cout << \"Yes\" << endl; else cout << \"No\" << endl;} // Driver Codeint main(){ string str = \"abzzab\"; checkevenOddPalindrome(str); return 0;}",
"e": 28740,
"s": 27296,
"text": null
},
{
"code": "// Java program implementation// of the approachimport java.util.*;import java.io.*; class GFG{ // Function to check if the string// str is palindromic or notstatic boolean isPalindrome(String str){ // Pointers to iterate the // string from both ends int l = 0; int h = str.length() - 1; while (h > l) { // If characters are found // to be distinct if (str.charAt(l++) != str.charAt(h--)) return false; } // Return true if the // string is palindromic return true;} // Function to generate string// from characters at odd indicesstatic String makeOddString(String str){ String odd = \"\"; for(int i = 1; i < str.length(); i += 2) { odd += str.charAt(i); } return odd;} // Function to generate string// from characters at even indicesstatic String makeevenString(String str){ String even = \"\"; for(int i = 0; i < str.length(); i += 2) { even += str.charAt(i); } return even;} // Functions to checks if string// is Even-Odd Palindrome or notstatic void checkevenOddPalindrome(String str){ // Generate odd indexed string String odd = makeOddString(str); // Generate even indexed string String even = makeevenString(str); // Check for Palindrome if (isPalindrome(odd) && isPalindrome(even)) System.out.println(\"Yes\"); else System.out.println(\"No\");} // Driver codepublic static void main(String[] args){ String str = \"abzzab\"; checkevenOddPalindrome(str);}} // This code is contributed by sanjoy_62",
"e": 30319,
"s": 28740,
"text": null
},
{
"code": "# Python3 program to implement# the above approach # Function to check if the string# str is palindromic or notdef isPalindrome(Str): # Pointers to iterate the # string from both ends l = 0 h = len(Str) - 1 while (h > l): # If characters are found # to be distinct if (Str[l] != Str[h]): return False l += 1 h -= 1 # Return true if the # string is palindromic return True # Function to generate string# from characters at odd indicesdef makeOddString(Str): odd = \"\" for i in range(1, len(Str), 2): odd += Str[i] return odd # Function to generate string# from characters at even indicesdef makeevenString(Str): even = \"\" for i in range(0, len(Str), 2): even += Str[i] return even # Functions to checks if string# is Even-Odd Palindrome or notdef checkevenOddPalindrome(Str): # Generate odd indexed string odd = makeOddString(Str) # Generate even indexed string even = makeevenString(Str) # Check for Palindrome if (isPalindrome(odd) and isPalindrome(even)): print(\"Yes\") else: print(\"No\") # Driver codeStr = \"abzzab\" checkevenOddPalindrome(Str) # This code is contributed by himanshu77",
"e": 31560,
"s": 30319,
"text": null
},
{
"code": "// C# program implementation// of the approachusing System; class GFG{ // Function to check if the string// str is palindromic or notstatic bool isPalindrome(string str){ // Pointers to iterate the // string from both ends int l = 0; int h = str.Length - 1; while (h > l) { // If characters are found // to be distinct if (str[l++] != str[h--]) return false; } // Return true if the // string is palindromic return true;} // Function to generate string// from characters at odd indicesstatic string makeOddString(string str){ string odd = \"\"; for(int i = 1; i < str.Length; i += 2) { odd += str[i]; } return odd;} // Function to generate string// from characters at even indicesstatic string makeevenString(string str){ string even = \"\"; for(int i = 0; i < str.Length; i += 2) { even += str[i]; } return even;} // Functions to checks if string// is Even-Odd Palindrome or notstatic void checkevenOddPalindrome(string str){ // Generate odd indexed string string odd = makeOddString(str); // Generate even indexed string string even = makeevenString(str); // Check for Palindrome if (isPalindrome(odd) && isPalindrome(even)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\");} // Driver codepublic static void Main(){ string str = \"abzzab\"; checkevenOddPalindrome(str);}} // This code is contributed by sanjoy_62",
"e": 33050,
"s": 31560,
"text": null
},
{
"code": "<script> // Javascript program implementation// of the approach // Function to check if the string// str is palindromic or notfunction isPalindrome(str){ // Pointers to iterate the // string from both ends var l = 0; var h = str.length - 1; while (h > l) { // If characters are found // to be distinct if (str.charAt(l++) != str.charAt(h--)) return false; } // Return true if the // string is palindromic return true;} // Function to generate string// from characters at odd indicesfunction makeOddString(str){ var odd = \"\"; for(var i = 1; i < str.length; i += 2) { odd += str.charAt(i); } return odd;} // Function to generate string// from characters at even indicesfunction makeevenString(str){ var even = \"\"; for(var i = 0; i < str.length; i += 2) { even += str.charAt(i); } return even;} // Functions to checks if string// is Even-Odd Palindrome or notfunction checkevenOddPalindrome(str){ // Generate odd indexed string var odd = makeOddString(str); // Generate even indexed string var even = makeevenString(str); // Check for Palindrome if (isPalindrome(odd) && isPalindrome(even)) document.write(\"Yes\"); else document.write(\"No\");} // Driver codevar str = \"abzzab\"; checkevenOddPalindrome(str); // This code is contributed by Khushboogoyal499 </script>",
"e": 34499,
"s": 33050,
"text": null
},
{
"code": null,
"e": 34503,
"s": 34499,
"text": "Yes"
},
{
"code": null,
"e": 34515,
"s": 34505,
"text": "sanjoy_62"
},
{
"code": null,
"e": 34526,
"s": 34515,
"text": "himanshu77"
},
{
"code": null,
"e": 34543,
"s": 34526,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 34554,
"s": 34543,
"text": "palindrome"
},
{
"code": null,
"e": 34578,
"s": 34554,
"text": "Competitive Programming"
},
{
"code": null,
"e": 34597,
"s": 34578,
"text": "School Programming"
},
{
"code": null,
"e": 34605,
"s": 34597,
"text": "Strings"
},
{
"code": null,
"e": 34613,
"s": 34605,
"text": "Strings"
},
{
"code": null,
"e": 34624,
"s": 34613,
"text": "palindrome"
},
{
"code": null,
"e": 34722,
"s": 34624,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34755,
"s": 34722,
"text": "Multistage Graph (Shortest Path)"
},
{
"code": null,
"e": 34801,
"s": 34755,
"text": "Breadth First Traversal ( BFS ) on a 2D array"
},
{
"code": null,
"e": 34862,
"s": 34801,
"text": "Difference between Backtracking and Branch-N-Bound technique"
},
{
"code": null,
"e": 34907,
"s": 34862,
"text": "5 Best Languages for Competitive Programming"
},
{
"code": null,
"e": 34965,
"s": 34907,
"text": "Minimum changes required to make all Array elements Prime"
},
{
"code": null,
"e": 34983,
"s": 34965,
"text": "Python Dictionary"
},
{
"code": null,
"e": 34999,
"s": 34983,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 35018,
"s": 34999,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 35043,
"s": 35018,
"text": "Reverse a string in Java"
}
] |
Printing the correct number of decimal points with cout in C++
|
Here we will see how to print some floating point numbers up to some pre-defined decimal places. In C++, we can use setprecision with the cout to do this word. This is present under the iomanip header file in C++.
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double x = 2.3654789d;
cout << "Print up to 3 decimal places: " << setprecision(3) << x << endl;
cout << "Print up to 2 decimal places: " << setprecision(2) << x << endl;
cout << "Print up to 7 decimal places: " << setprecision(7) << x << endl;
}
Print up to 3 decimal places: 2.365
Print up to 2 decimal places: 2.37
Print up to 7 decimal places: 2.3654789
|
[
{
"code": null,
"e": 1401,
"s": 1187,
"text": "Here we will see how to print some floating point numbers up to some pre-defined decimal places. In C++, we can use setprecision with the cout to do this word. This is present under the iomanip header file in C++."
},
{
"code": null,
"e": 1733,
"s": 1401,
"text": "#include <iostream>\n#include <iomanip>\nusing namespace std;\nint main() {\n double x = 2.3654789d;\n cout << \"Print up to 3 decimal places: \" << setprecision(3) << x << endl;\n cout << \"Print up to 2 decimal places: \" << setprecision(2) << x << endl;\n cout << \"Print up to 7 decimal places: \" << setprecision(7) << x << endl;\n}"
},
{
"code": null,
"e": 1844,
"s": 1733,
"text": "Print up to 3 decimal places: 2.365\nPrint up to 2 decimal places: 2.37\nPrint up to 7 decimal places: 2.3654789"
}
] |
Create a correlation Matrix using Python
|
27 Jan, 2022
A correlation matrix is a table containing correlation coefficients between variables. Each cell in the table represents the correlation between two variables. The value lies between -1 and 1. A correlation matrix is used to summarize data, as a diagnostic for advanced analyses and as an input into a more advanced analysis. The two key components of the correlation are:
Magnitude: larger the magnitude, stronger the correlation.
Sign: if positive, there is a regular correlation. If negative, there is an inverse correlation.
A correlation matrix has been created using the following two libraries:
Numpy LibraryPandas Library
Numpy Library
Pandas Library
Method 1: Creating a correlation matrix using Numpy library
Numpy library make use of corrcoef() function that returns a matrix of 2×2. The matrix consists of correlations of x with x (0,0), x with y (0,1), y with x (1,0) and y with y (1,1). We are only concerned with the correlation of x with y i.e. cell (0,1) or (1,0). See below for an example.
Example 1: Suppose an ice cream shop keeps track of total sales of ice creams versus the temperature on that day.
Python3
import numpy as np # x represents the total sale in# dollarsx = [215, 325, 185, 332, 406, 522, 412, 614, 544, 421, 445, 408], # y represents the temperature on# each day of saley = [14.2, 16.4, 11.9, 15.2, 18.5, 22.1, 19.4, 25.1, 23.4, 18.1, 22.6, 17.2] # create correlation matrixmatrix = np.corrcoef(x, y) # print matrixprint(matrix)
Output
[[1. 0.95750662]
[0.95750662 1. ]]
From the above matrix, if we see cell (0,1) and (1,0) both have the same value equal to 0.95750662 which lead us to conclude that whenever the temperature is high we have more sales.
Example 2: Suppose we are given glucose level in boy respective to age. Find correlation between age(x) and glucose level in body(y).
Python3
import numpy as np # x represents the agex = [43, 21, 25, 42, 57, 59] # y represents the glucose level# corresponding to that agey = [99, 65, 79, 75, 87, 81] # correlation matrixmatrix = np.corrcoef(x, y)print(matrix)
Output
[[1. 0.5298089]
[0.5298089 1. ]]
From the above correlation matrix, 0.5298089 or 52.98% that means the variable has a moderate positive correlation.
Method 2: Creating correlation matrix using Pandas library
In order to create a correlation matrix for a given dataset, we use corr() method on dataframes.
Example 1:
Python3
import pandas as pd # collect datadata = { 'x': [45, 37, 42, 35, 39], 'y': [38, 31, 26, 28, 33], 'z': [10, 15, 17, 21, 12]} # form dataframedataframe = pd.DataFrame(data, columns=['x', 'y', 'z'])print("Dataframe is : ")print(dataframe) # form correlation matrixmatrix = dataframe.corr()print("Correlation matrix is : ")print(matrix)
Output:
Dataframe is :
x y z
0 45 38 10
1 37 31 15
2 42 26 17
3 35 28 21
4 39 33 12
Correlation matrix is :
x y z
x 1.000000 0.518457 -0.701886
y 0.518457 1.000000 -0.860941
z -0.701886 -0.860941 1.000000
Example 2:
CSV File used:
Python3
import pandas as pd # create dataframe from filedataframe = pd.read_csv("C:\\GFG\\sample.csv") # show dataframeprint(dataframe) # use corr() method on dataframe to# make correlation matrixmatrix = dataframe.corr() # print correlation matrixprint("Correlation Matrix is : ")print(matrix)
Output:
Correlation Matrix is :
AVG temp C Ice Cream production
AVG temp C 1.000000 0.718032
Ice Cream production 0.718032 1.000000
as5853535
clintra
Python-numpy
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Jan, 2022"
},
{
"code": null,
"e": 401,
"s": 28,
"text": "A correlation matrix is a table containing correlation coefficients between variables. Each cell in the table represents the correlation between two variables. The value lies between -1 and 1. A correlation matrix is used to summarize data, as a diagnostic for advanced analyses and as an input into a more advanced analysis. The two key components of the correlation are:"
},
{
"code": null,
"e": 460,
"s": 401,
"text": "Magnitude: larger the magnitude, stronger the correlation."
},
{
"code": null,
"e": 557,
"s": 460,
"text": "Sign: if positive, there is a regular correlation. If negative, there is an inverse correlation."
},
{
"code": null,
"e": 630,
"s": 557,
"text": "A correlation matrix has been created using the following two libraries:"
},
{
"code": null,
"e": 658,
"s": 630,
"text": "Numpy LibraryPandas Library"
},
{
"code": null,
"e": 672,
"s": 658,
"text": "Numpy Library"
},
{
"code": null,
"e": 687,
"s": 672,
"text": "Pandas Library"
},
{
"code": null,
"e": 747,
"s": 687,
"text": "Method 1: Creating a correlation matrix using Numpy library"
},
{
"code": null,
"e": 1036,
"s": 747,
"text": "Numpy library make use of corrcoef() function that returns a matrix of 2×2. The matrix consists of correlations of x with x (0,0), x with y (0,1), y with x (1,0) and y with y (1,1). We are only concerned with the correlation of x with y i.e. cell (0,1) or (1,0). See below for an example."
},
{
"code": null,
"e": 1150,
"s": 1036,
"text": "Example 1: Suppose an ice cream shop keeps track of total sales of ice creams versus the temperature on that day."
},
{
"code": null,
"e": 1158,
"s": 1150,
"text": "Python3"
},
{
"code": "import numpy as np # x represents the total sale in# dollarsx = [215, 325, 185, 332, 406, 522, 412, 614, 544, 421, 445, 408], # y represents the temperature on# each day of saley = [14.2, 16.4, 11.9, 15.2, 18.5, 22.1, 19.4, 25.1, 23.4, 18.1, 22.6, 17.2] # create correlation matrixmatrix = np.corrcoef(x, y) # print matrixprint(matrix)",
"e": 1503,
"s": 1158,
"text": null
},
{
"code": null,
"e": 1510,
"s": 1503,
"text": "Output"
},
{
"code": null,
"e": 1561,
"s": 1510,
"text": "[[1. 0.95750662]\n [0.95750662 1. ]]"
},
{
"code": null,
"e": 1744,
"s": 1561,
"text": "From the above matrix, if we see cell (0,1) and (1,0) both have the same value equal to 0.95750662 which lead us to conclude that whenever the temperature is high we have more sales."
},
{
"code": null,
"e": 1878,
"s": 1744,
"text": "Example 2: Suppose we are given glucose level in boy respective to age. Find correlation between age(x) and glucose level in body(y)."
},
{
"code": null,
"e": 1886,
"s": 1878,
"text": "Python3"
},
{
"code": "import numpy as np # x represents the agex = [43, 21, 25, 42, 57, 59] # y represents the glucose level# corresponding to that agey = [99, 65, 79, 75, 87, 81] # correlation matrixmatrix = np.corrcoef(x, y)print(matrix)",
"e": 2105,
"s": 1886,
"text": null
},
{
"code": null,
"e": 2112,
"s": 2105,
"text": "Output"
},
{
"code": null,
"e": 2159,
"s": 2112,
"text": "[[1. 0.5298089]\n [0.5298089 1. ]]"
},
{
"code": null,
"e": 2275,
"s": 2159,
"text": "From the above correlation matrix, 0.5298089 or 52.98% that means the variable has a moderate positive correlation."
},
{
"code": null,
"e": 2335,
"s": 2275,
"text": "Method 2: Creating correlation matrix using Pandas library "
},
{
"code": null,
"e": 2432,
"s": 2335,
"text": "In order to create a correlation matrix for a given dataset, we use corr() method on dataframes."
},
{
"code": null,
"e": 2443,
"s": 2432,
"text": "Example 1:"
},
{
"code": null,
"e": 2451,
"s": 2443,
"text": "Python3"
},
{
"code": "import pandas as pd # collect datadata = { 'x': [45, 37, 42, 35, 39], 'y': [38, 31, 26, 28, 33], 'z': [10, 15, 17, 21, 12]} # form dataframedataframe = pd.DataFrame(data, columns=['x', 'y', 'z'])print(\"Dataframe is : \")print(dataframe) # form correlation matrixmatrix = dataframe.corr()print(\"Correlation matrix is : \")print(matrix)",
"e": 2794,
"s": 2451,
"text": null
},
{
"code": null,
"e": 2803,
"s": 2794,
"text": " Output:"
},
{
"code": null,
"e": 3055,
"s": 2803,
"text": "Dataframe is : \n x y z\n0 45 38 10\n1 37 31 15\n2 42 26 17\n3 35 28 21\n4 39 33 12\nCorrelation matrix is :\n x y z\nx 1.000000 0.518457 -0.701886\ny 0.518457 1.000000 -0.860941\nz -0.701886 -0.860941 1.000000"
},
{
"code": null,
"e": 3066,
"s": 3055,
"text": "Example 2:"
},
{
"code": null,
"e": 3081,
"s": 3066,
"text": "CSV File used:"
},
{
"code": null,
"e": 3089,
"s": 3081,
"text": "Python3"
},
{
"code": "import pandas as pd # create dataframe from filedataframe = pd.read_csv(\"C:\\\\GFG\\\\sample.csv\") # show dataframeprint(dataframe) # use corr() method on dataframe to# make correlation matrixmatrix = dataframe.corr() # print correlation matrixprint(\"Correlation Matrix is : \")print(matrix)",
"e": 3377,
"s": 3089,
"text": null
},
{
"code": null,
"e": 3385,
"s": 3377,
"text": "Output:"
},
{
"code": null,
"e": 3574,
"s": 3385,
"text": "Correlation Matrix is : \n AVG temp C Ice Cream production\nAVG temp C 1.000000 0.718032\nIce Cream production 0.718032 1.000000"
},
{
"code": null,
"e": 3584,
"s": 3574,
"text": "as5853535"
},
{
"code": null,
"e": 3592,
"s": 3584,
"text": "clintra"
},
{
"code": null,
"e": 3605,
"s": 3592,
"text": "Python-numpy"
},
{
"code": null,
"e": 3619,
"s": 3605,
"text": "Python-pandas"
},
{
"code": null,
"e": 3626,
"s": 3619,
"text": "Python"
},
{
"code": null,
"e": 3724,
"s": 3626,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3742,
"s": 3724,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3784,
"s": 3742,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3806,
"s": 3784,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3841,
"s": 3806,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 3867,
"s": 3841,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3899,
"s": 3867,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3928,
"s": 3899,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3955,
"s": 3928,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3985,
"s": 3955,
"text": "Iterate over a list in Python"
}
] |
Number of integral solutions of the equation x1 + x2 +.... + xN = k
|
30 Jun, 2022
Given N and K. The task is to count the number of the integral solutions of a linear equation having N variable as given below:
x1 + x2+ x3...+ xN-1+...+xN = K
Examples:
Input: N = 3, K = 3
Output: 10
Explaination: Possible solutions are: (1,1,1),(1,0,2),(2,0,1),(1,2,0),(2,1,0),(0,1,2)
(0,2,1),(3,0,0),(0,3,0),(0,0,3).
Input: N = 2, K = 2
Output: 3
Approach: This problem can be solved using the concept of Permutation and Combination. Below are the direct formulas for finding non-negative and positive integral solutions respectively.
Number of non-negative integral solutions of equation x1 + x2 + ...... + xn = k is given by (n+k-1)! / (n-1)!*k!. Number of positive integral solutions of equation x1 + x2 + ..... + xn = k is given by (k-1)! / (n-1)! * (k-n)!.
Note here that the non-negative integral solutions already include the positive integral solutions. Therefore, there is no need to add the number of positive integral solutions to the answer.Below is the implementation of above approach:
c++
Java
Python3
C#
PHP
Javascript
// C++ program for above implementation#include<iostream> using namespace std ; int nCr(int n, int r){ int fac[100] = {1} ; for (int i = 1 ; i < n + 1 ; i++) { fac[i] = fac[i - 1] * i ; } int ans = fac[n] / (fac[n - r] * fac[r]) ; return ans ;} // Driver Codeint main(){ int n = 3 ; int k = 3 ; int ans = nCr(n + k - 1 , k); cout << ans ; return 0 ;} // This code is contributed// by ANKITRAI1
// Java program for above implementationimport java.io.*; class GFG{static int nCr(int n, int r){ int fac[] = new int[100] ; for(int i = 0; i < n; i++) fac[i] = 1; for (int i = 1 ; i < n + 1 ; i++) { fac[i] = fac[i - 1] * i ; } int ans = fac[n] / (fac[n - r] * fac[r]); return ans ;} // Driver Codepublic static void main (String[] args){ int n = 3 ; int k = 3 ; int ans = nCr(n + k - 1 , k); System.out.println(ans) ;}} // This code is contributed// by anuj_67
# Python implementation of# above approach # Calculate nCr i.e binomial# cofficent nCr = n !/(r !*(n-r)!)def nCr(n, r): # first find factorial # upto n fac = list() fac.append(1) for i in range(1, n + 1): fac.append(fac[i - 1] * i) # use nCr formula ans = fac[n] / (fac[n - r] * fac[r]) return ans # n = number of variablesn = 3 # sum of n variables = kk = 3 # find number of solutionsans = nCr(n + k - 1, k) print(ans) # This code is contributed# by ChitraNayal
// C# program for above implementationusing System; class GFG{static int nCr(int n, int r){ int[] fac = new int[100] ; for(int i = 0; i < n; i++) fac[i] = 1; for (int i = 1 ; i < n + 1 ; i++) { fac[i] = fac[i - 1] * i ; } int ans = fac[n] / (fac[n - r] * fac[r]); return ans ;} // Driver Codepublic static void Main (){ int n = 3 ; int k = 3 ; int ans = nCr(n + k - 1 , k); Console.Write(ans) ;}} // This code is contributed// by ChitraNayal
<?php// PHP implementation of above approach // Calculate nCr i.e binomial// cofficent nCr = n !/(r !*(n-r)!)function nCr($n, $r){ // first find factorial // upto n $fac = array(); array_push($fac, 1); for($i = 1; $i < $n + 1; $i++) array_push($fac, $fac[$i - 1] * $i); // use nCr formula $ans = $fac[$n] / ($fac[$n - $r] * $fac[$r]); return $ans;} // Driver Code // n = number of variables$n = 3; // sum of n variables = k$k = 3; // find number of solutions$ans = nCr($n + $k - 1, $k); print($ans); // This code is contributed// by mits?>
<script> // Javascript program for above implementationfunction nCr(n, r){ var fac = Array(100).fill(1); for (var i = 1 ; i < n + 1 ; i++) { fac[i] = fac[i - 1] * i ; } var ans = fac[n] / (fac[n - r] * fac[r]) ; return ans ;} // Driver Codevar n = 3 ;var k = 3 ; var ans = nCr(n + k - 1 , k); document.write(ans ); // This code is contributed by noob2000.</script>
10
Applications of the above concepts:
Number of non-negative integral solutions of equation x1 + x2 +...+ xn = k is equal to the number of ways in which k identical balls can be distributed into N unique boxes.Number of positive integral solutions of equation x1 + x2 + ... + xn = k is equal to the number of ways in which k identical balls can be distributed into N unique boxes such that each box must contain at-least 1 ball.
Number of non-negative integral solutions of equation x1 + x2 +...+ xn = k is equal to the number of ways in which k identical balls can be distributed into N unique boxes.
Number of positive integral solutions of equation x1 + x2 + ... + xn = k is equal to the number of ways in which k identical balls can be distributed into N unique boxes such that each box must contain at-least 1 ball.
ankthon
vt_m
ukasp
Mithun Kumar
noob2000
jatingrg2399
factorial
Permutation and Combination
Mathematical
Mathematical
factorial
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
Program to find GCD or HCF of two numbers
Minimum number of jumps to reach end
Algorithm to solve Rubik's Cube
The Knight's tour problem | Backtracking-1
Program for Decimal to Binary Conversion
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n30 Jun, 2022"
},
{
"code": null,
"e": 182,
"s": 52,
"text": "Given N and K. The task is to count the number of the integral solutions of a linear equation having N variable as given below: "
},
{
"code": null,
"e": 214,
"s": 182,
"text": "x1 + x2+ x3...+ xN-1+...+xN = K"
},
{
"code": null,
"e": 226,
"s": 214,
"text": "Examples: "
},
{
"code": null,
"e": 407,
"s": 226,
"text": "Input: N = 3, K = 3\nOutput: 10\nExplaination: Possible solutions are: (1,1,1),(1,0,2),(2,0,1),(1,2,0),(2,1,0),(0,1,2)\n(0,2,1),(3,0,0),(0,3,0),(0,0,3).\n\nInput: N = 2, K = 2\nOutput: 3"
},
{
"code": null,
"e": 598,
"s": 409,
"text": "Approach: This problem can be solved using the concept of Permutation and Combination. Below are the direct formulas for finding non-negative and positive integral solutions respectively. "
},
{
"code": null,
"e": 827,
"s": 598,
"text": "Number of non-negative integral solutions of equation x1 + x2 + ...... + xn = k is given by (n+k-1)! / (n-1)!*k!. Number of positive integral solutions of equation x1 + x2 + ..... + xn = k is given by (k-1)! / (n-1)! * (k-n)!. "
},
{
"code": null,
"e": 1067,
"s": 827,
"text": "Note here that the non-negative integral solutions already include the positive integral solutions. Therefore, there is no need to add the number of positive integral solutions to the answer.Below is the implementation of above approach: "
},
{
"code": null,
"e": 1071,
"s": 1067,
"text": "c++"
},
{
"code": null,
"e": 1076,
"s": 1071,
"text": "Java"
},
{
"code": null,
"e": 1084,
"s": 1076,
"text": "Python3"
},
{
"code": null,
"e": 1087,
"s": 1084,
"text": "C#"
},
{
"code": null,
"e": 1091,
"s": 1087,
"text": "PHP"
},
{
"code": null,
"e": 1102,
"s": 1091,
"text": "Javascript"
},
{
"code": "// C++ program for above implementation#include<iostream> using namespace std ; int nCr(int n, int r){ int fac[100] = {1} ; for (int i = 1 ; i < n + 1 ; i++) { fac[i] = fac[i - 1] * i ; } int ans = fac[n] / (fac[n - r] * fac[r]) ; return ans ;} // Driver Codeint main(){ int n = 3 ; int k = 3 ; int ans = nCr(n + k - 1 , k); cout << ans ; return 0 ;} // This code is contributed// by ANKITRAI1",
"e": 1579,
"s": 1102,
"text": null
},
{
"code": "// Java program for above implementationimport java.io.*; class GFG{static int nCr(int n, int r){ int fac[] = new int[100] ; for(int i = 0; i < n; i++) fac[i] = 1; for (int i = 1 ; i < n + 1 ; i++) { fac[i] = fac[i - 1] * i ; } int ans = fac[n] / (fac[n - r] * fac[r]); return ans ;} // Driver Codepublic static void main (String[] args){ int n = 3 ; int k = 3 ; int ans = nCr(n + k - 1 , k); System.out.println(ans) ;}} // This code is contributed// by anuj_67",
"e": 2127,
"s": 1579,
"text": null
},
{
"code": "# Python implementation of# above approach # Calculate nCr i.e binomial# cofficent nCr = n !/(r !*(n-r)!)def nCr(n, r): # first find factorial # upto n fac = list() fac.append(1) for i in range(1, n + 1): fac.append(fac[i - 1] * i) # use nCr formula ans = fac[n] / (fac[n - r] * fac[r]) return ans # n = number of variablesn = 3 # sum of n variables = kk = 3 # find number of solutionsans = nCr(n + k - 1, k) print(ans) # This code is contributed# by ChitraNayal",
"e": 2623,
"s": 2127,
"text": null
},
{
"code": "// C# program for above implementationusing System; class GFG{static int nCr(int n, int r){ int[] fac = new int[100] ; for(int i = 0; i < n; i++) fac[i] = 1; for (int i = 1 ; i < n + 1 ; i++) { fac[i] = fac[i - 1] * i ; } int ans = fac[n] / (fac[n - r] * fac[r]); return ans ;} // Driver Codepublic static void Main (){ int n = 3 ; int k = 3 ; int ans = nCr(n + k - 1 , k); Console.Write(ans) ;}} // This code is contributed// by ChitraNayal",
"e": 3151,
"s": 2623,
"text": null
},
{
"code": "<?php// PHP implementation of above approach // Calculate nCr i.e binomial// cofficent nCr = n !/(r !*(n-r)!)function nCr($n, $r){ // first find factorial // upto n $fac = array(); array_push($fac, 1); for($i = 1; $i < $n + 1; $i++) array_push($fac, $fac[$i - 1] * $i); // use nCr formula $ans = $fac[$n] / ($fac[$n - $r] * $fac[$r]); return $ans;} // Driver Code // n = number of variables$n = 3; // sum of n variables = k$k = 3; // find number of solutions$ans = nCr($n + $k - 1, $k); print($ans); // This code is contributed// by mits?>",
"e": 3745,
"s": 3151,
"text": null
},
{
"code": "<script> // Javascript program for above implementationfunction nCr(n, r){ var fac = Array(100).fill(1); for (var i = 1 ; i < n + 1 ; i++) { fac[i] = fac[i - 1] * i ; } var ans = fac[n] / (fac[n - r] * fac[r]) ; return ans ;} // Driver Codevar n = 3 ;var k = 3 ; var ans = nCr(n + k - 1 , k); document.write(ans ); // This code is contributed by noob2000.</script>",
"e": 4168,
"s": 3745,
"text": null
},
{
"code": null,
"e": 4171,
"s": 4168,
"text": "10"
},
{
"code": null,
"e": 4209,
"s": 4171,
"text": "Applications of the above concepts: "
},
{
"code": null,
"e": 4600,
"s": 4209,
"text": "Number of non-negative integral solutions of equation x1 + x2 +...+ xn = k is equal to the number of ways in which k identical balls can be distributed into N unique boxes.Number of positive integral solutions of equation x1 + x2 + ... + xn = k is equal to the number of ways in which k identical balls can be distributed into N unique boxes such that each box must contain at-least 1 ball."
},
{
"code": null,
"e": 4773,
"s": 4600,
"text": "Number of non-negative integral solutions of equation x1 + x2 +...+ xn = k is equal to the number of ways in which k identical balls can be distributed into N unique boxes."
},
{
"code": null,
"e": 4992,
"s": 4773,
"text": "Number of positive integral solutions of equation x1 + x2 + ... + xn = k is equal to the number of ways in which k identical balls can be distributed into N unique boxes such that each box must contain at-least 1 ball."
},
{
"code": null,
"e": 5002,
"s": 4994,
"text": "ankthon"
},
{
"code": null,
"e": 5007,
"s": 5002,
"text": "vt_m"
},
{
"code": null,
"e": 5013,
"s": 5007,
"text": "ukasp"
},
{
"code": null,
"e": 5026,
"s": 5013,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 5035,
"s": 5026,
"text": "noob2000"
},
{
"code": null,
"e": 5048,
"s": 5035,
"text": "jatingrg2399"
},
{
"code": null,
"e": 5058,
"s": 5048,
"text": "factorial"
},
{
"code": null,
"e": 5086,
"s": 5058,
"text": "Permutation and Combination"
},
{
"code": null,
"e": 5099,
"s": 5086,
"text": "Mathematical"
},
{
"code": null,
"e": 5112,
"s": 5099,
"text": "Mathematical"
},
{
"code": null,
"e": 5122,
"s": 5112,
"text": "factorial"
},
{
"code": null,
"e": 5220,
"s": 5122,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5244,
"s": 5220,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 5265,
"s": 5244,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 5287,
"s": 5265,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 5301,
"s": 5287,
"text": "Prime Numbers"
},
{
"code": null,
"e": 5354,
"s": 5301,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 5396,
"s": 5354,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 5433,
"s": 5396,
"text": "Minimum number of jumps to reach end"
},
{
"code": null,
"e": 5465,
"s": 5433,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 5508,
"s": 5465,
"text": "The Knight's tour problem | Backtracking-1"
}
] |
Variable Names in MATLAB
|
22 Sep, 2021
A variable is a named-memory location that stores different types of data which can be used to perform a specific set of operations. It can be thought of as a container that holds some value in memory. The Matlab workspace store all the variables being used during a session. This workspace not only deals with the creation of new variables but also supports the reusing of existing variables in the execution of the command. Each variable in the Matlab environment is treated as a matrix or an array of different data types. In Matlab, variables are assigned using the assignment ‘=’ operator.
Note:
After the creation of a variable, we can use it later in our program.
There must have values assigned to variables before they are used.
If an expression returns a result without being assigned to any variable, the system implicitly assigns and stores the value to a special variable named ‘ans’. But ans variable is specific to the current workspace and the value of ans can change frequently, that is why the use of ans in a script or function is not recommended.
Example 1:
Matlab
% MATLAB code for defining a and initializing % it with a value 10 using assignment operator '='a = 10
Output:
a = 10
Example 2:
Matlab
% MATLAB code for calculates an expression% and stores value 13 in variable bb = sqrt(169)
Output:
b = 13
Example 3:
Matlab
% MATLAB code to stores the expression % in special variable 'ans'sqrt(169)
Output:
ans = 13
A variable name is the name of the memory location where we can store our values. Some of the rules for naming a variable are:
A variable name should start with a letter followed by digits, underscores, or letters.
Don’t use Matlab keywords as variable names.
Matlab is case sensitive, i.e., small letters and capital letters are treated differently. For example, variable names ‘PRICE’ and Price are different.
A variable name cannot contain letters more than name length max characters.
Special symbols anywhere in a variable name are syntactically invalid in Matlab.
Avoid naming variable names as provided by pre-defined Matlab’s variable names.
To check whether a variable name is a MATLAB keyword or not, MATLAB provides a built-in function iskeyword( ). This keyword determines whether the input is MATLAB keyword or not.
Syntax:
v = iskeyword(txt)iskeyword
Example 1:
Matlab
% MATLAB code for check variable% is keyword or notTest=iskeyword('if') % this statement returns % logical True (1) as a result as 'if' is a keyword % in the Matlab otherwise returns false. iskeyword if % this statement uses the Matlab % command format and results in ans=1.
Test = logical
1
ans = logical
1
Example 2:
Matlab
% MATLAB code for print all keywordiskeyword % returns a list of all Matlab keywords.
Output:
To check whether the input is a valid variable name isvarname( ) is used. This function determines if the input is a valid variable name. If it is a valid MATLAB variable name the isvarname function returns logical 1 (true). Otherwise, it returns logical 0 (false).
Syntax:
t = isvarname(s)
isvarname s
Example 1:
Matlab
% MATLAB code for isvarnameisvarname Number_1
Output:
ans = logical
1
Example 2:
Matlab
% MATLAB code for isvarname()Test= isvarname(Digit_1)
Output:
Test = logical
1
Matlab provides some predefined functions such as pi, ans, i, j, clock, date, eps which cannot be used as variable names as they can create confliction between variable name and functions name. Usually, variable names take precedence over function names that result in unexpected results.
To check whether a variable name is already used with function:
Example:
Matlab
% MATLAB code for check if there is no% existing variables or functions name. In case it exists, % remove the variable from the memory with the clear() function. exist varname
Output:
ans=0
This function (generate variable name) is used to construct a valid and unique variable name. It returns an array of strings or characters that can be used as a legal variable name. Argument str can be a string, a string array, a character array, or a cell array containing character vectors. All the returned elements are unique.
Syntax:
varname = genvarname(str)
varname = genvarname(str, exclusions)
here genvarname(str, exclusions) returns a legal variable name that is different from any name listed in the exclusions input. The argument exclusions can be a string, a string array, a character array, a cell array of character vectors.
Example 1:
Matlab
% MATLAB code for gemvarname()var_name = genvarname({'Pen', 'Pen', 'Pen', 'Pen'})
Output:
var_name = 1X4 cell
'Pen_1' 'Pen_2' 'Pen_3' 'Pen_4'
Example 2:
Matlab
% MATLAB code for genvarname() with different parametersa = ["Pen", "Eraser", "Pencil", "Box" ]var_name=genvarname(a,"Box")
Output:
var_name= 1x4 string
"Pen" "Eraser" "Pencil" "Box1"
MATLAB-Basic
Picked
MATLAB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Convert Three Channels of Colored Image into Grayscale Image in MATLAB?
How to Solve Histogram Equalization Numerical Problem in MATLAB?
Adaptive Histogram Equalization in Image Processing Using MATLAB
MRI Image Segmentation in MATLAB
How to detect duplicate values and its indices within an array in MATLAB?
Double Integral in MATLAB
Classes and Object in MATLAB
How to remove space in a string in MATLAB?
How to Normalize a Histogram in MATLAB?
Forward and Inverse Fourier Transform of an Image in MATLAB
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Sep, 2021"
},
{
"code": null,
"e": 648,
"s": 52,
"text": "A variable is a named-memory location that stores different types of data which can be used to perform a specific set of operations. It can be thought of as a container that holds some value in memory. The Matlab workspace store all the variables being used during a session. This workspace not only deals with the creation of new variables but also supports the reusing of existing variables in the execution of the command. Each variable in the Matlab environment is treated as a matrix or an array of different data types. In Matlab, variables are assigned using the assignment ‘=’ operator. "
},
{
"code": null,
"e": 654,
"s": 648,
"text": "Note:"
},
{
"code": null,
"e": 724,
"s": 654,
"text": "After the creation of a variable, we can use it later in our program."
},
{
"code": null,
"e": 791,
"s": 724,
"text": "There must have values assigned to variables before they are used."
},
{
"code": null,
"e": 1120,
"s": 791,
"text": "If an expression returns a result without being assigned to any variable, the system implicitly assigns and stores the value to a special variable named ‘ans’. But ans variable is specific to the current workspace and the value of ans can change frequently, that is why the use of ans in a script or function is not recommended."
},
{
"code": null,
"e": 1132,
"s": 1120,
"text": "Example 1: "
},
{
"code": null,
"e": 1139,
"s": 1132,
"text": "Matlab"
},
{
"code": "% MATLAB code for defining a and initializing % it with a value 10 using assignment operator '='a = 10",
"e": 1242,
"s": 1139,
"text": null
},
{
"code": null,
"e": 1250,
"s": 1242,
"text": "Output:"
},
{
"code": null,
"e": 1257,
"s": 1250,
"text": "a = 10"
},
{
"code": null,
"e": 1268,
"s": 1257,
"text": "Example 2:"
},
{
"code": null,
"e": 1275,
"s": 1268,
"text": "Matlab"
},
{
"code": "% MATLAB code for calculates an expression% and stores value 13 in variable bb = sqrt(169)",
"e": 1366,
"s": 1275,
"text": null
},
{
"code": null,
"e": 1374,
"s": 1366,
"text": "Output:"
},
{
"code": null,
"e": 1381,
"s": 1374,
"text": "b = 13"
},
{
"code": null,
"e": 1392,
"s": 1381,
"text": "Example 3:"
},
{
"code": null,
"e": 1399,
"s": 1392,
"text": "Matlab"
},
{
"code": "% MATLAB code to stores the expression % in special variable 'ans'sqrt(169)",
"e": 1475,
"s": 1399,
"text": null
},
{
"code": null,
"e": 1483,
"s": 1475,
"text": "Output:"
},
{
"code": null,
"e": 1492,
"s": 1483,
"text": "ans = 13"
},
{
"code": null,
"e": 1619,
"s": 1492,
"text": "A variable name is the name of the memory location where we can store our values. Some of the rules for naming a variable are:"
},
{
"code": null,
"e": 1707,
"s": 1619,
"text": "A variable name should start with a letter followed by digits, underscores, or letters."
},
{
"code": null,
"e": 1752,
"s": 1707,
"text": "Don’t use Matlab keywords as variable names."
},
{
"code": null,
"e": 1904,
"s": 1752,
"text": "Matlab is case sensitive, i.e., small letters and capital letters are treated differently. For example, variable names ‘PRICE’ and Price are different."
},
{
"code": null,
"e": 1981,
"s": 1904,
"text": "A variable name cannot contain letters more than name length max characters."
},
{
"code": null,
"e": 2062,
"s": 1981,
"text": "Special symbols anywhere in a variable name are syntactically invalid in Matlab."
},
{
"code": null,
"e": 2142,
"s": 2062,
"text": "Avoid naming variable names as provided by pre-defined Matlab’s variable names."
},
{
"code": null,
"e": 2321,
"s": 2142,
"text": "To check whether a variable name is a MATLAB keyword or not, MATLAB provides a built-in function iskeyword( ). This keyword determines whether the input is MATLAB keyword or not."
},
{
"code": null,
"e": 2329,
"s": 2321,
"text": "Syntax:"
},
{
"code": null,
"e": 2357,
"s": 2329,
"text": "v = iskeyword(txt)iskeyword"
},
{
"code": null,
"e": 2368,
"s": 2357,
"text": "Example 1:"
},
{
"code": null,
"e": 2375,
"s": 2368,
"text": "Matlab"
},
{
"code": "% MATLAB code for check variable% is keyword or notTest=iskeyword('if') % this statement returns % logical True (1) as a result as 'if' is a keyword % in the Matlab otherwise returns false. iskeyword if % this statement uses the Matlab % command format and results in ans=1. ",
"e": 2668,
"s": 2375,
"text": null
},
{
"code": null,
"e": 2715,
"s": 2668,
"text": "Test = logical\n 1\n\nans = logical\n 1"
},
{
"code": null,
"e": 2726,
"s": 2715,
"text": "Example 2:"
},
{
"code": null,
"e": 2733,
"s": 2726,
"text": "Matlab"
},
{
"code": "% MATLAB code for print all keywordiskeyword % returns a list of all Matlab keywords.",
"e": 2819,
"s": 2733,
"text": null
},
{
"code": null,
"e": 2831,
"s": 2819,
"text": " Output: "
},
{
"code": null,
"e": 3097,
"s": 2831,
"text": "To check whether the input is a valid variable name isvarname( ) is used. This function determines if the input is a valid variable name. If it is a valid MATLAB variable name the isvarname function returns logical 1 (true). Otherwise, it returns logical 0 (false)."
},
{
"code": null,
"e": 3105,
"s": 3097,
"text": "Syntax:"
},
{
"code": null,
"e": 3122,
"s": 3105,
"text": "t = isvarname(s)"
},
{
"code": null,
"e": 3134,
"s": 3122,
"text": "isvarname s"
},
{
"code": null,
"e": 3145,
"s": 3134,
"text": "Example 1:"
},
{
"code": null,
"e": 3152,
"s": 3145,
"text": "Matlab"
},
{
"code": "% MATLAB code for isvarnameisvarname Number_1",
"e": 3198,
"s": 3152,
"text": null
},
{
"code": null,
"e": 3206,
"s": 3198,
"text": "Output:"
},
{
"code": null,
"e": 3226,
"s": 3206,
"text": "ans = logical\n 1"
},
{
"code": null,
"e": 3237,
"s": 3226,
"text": "Example 2:"
},
{
"code": null,
"e": 3244,
"s": 3237,
"text": "Matlab"
},
{
"code": "% MATLAB code for isvarname()Test= isvarname(Digit_1)",
"e": 3298,
"s": 3244,
"text": null
},
{
"code": null,
"e": 3306,
"s": 3298,
"text": "Output:"
},
{
"code": null,
"e": 3329,
"s": 3306,
"text": "Test = logical\n 1"
},
{
"code": null,
"e": 3619,
"s": 3329,
"text": "Matlab provides some predefined functions such as pi, ans, i, j, clock, date, eps which cannot be used as variable names as they can create confliction between variable name and functions name. Usually, variable names take precedence over function names that result in unexpected results."
},
{
"code": null,
"e": 3683,
"s": 3619,
"text": "To check whether a variable name is already used with function:"
},
{
"code": null,
"e": 3692,
"s": 3683,
"text": "Example:"
},
{
"code": null,
"e": 3699,
"s": 3692,
"text": "Matlab"
},
{
"code": "% MATLAB code for check if there is no% existing variables or functions name. In case it exists, % remove the variable from the memory with the clear() function. exist varname ",
"e": 3876,
"s": 3699,
"text": null
},
{
"code": null,
"e": 3884,
"s": 3876,
"text": "Output:"
},
{
"code": null,
"e": 3890,
"s": 3884,
"text": "ans=0"
},
{
"code": null,
"e": 4223,
"s": 3890,
"text": "This function (generate variable name) is used to construct a valid and unique variable name. It returns an array of strings or characters that can be used as a legal variable name. Argument str can be a string, a string array, a character array, or a cell array containing character vectors. All the returned elements are unique. "
},
{
"code": null,
"e": 4231,
"s": 4223,
"text": "Syntax:"
},
{
"code": null,
"e": 4257,
"s": 4231,
"text": "varname = genvarname(str)"
},
{
"code": null,
"e": 4295,
"s": 4257,
"text": "varname = genvarname(str, exclusions)"
},
{
"code": null,
"e": 4533,
"s": 4295,
"text": "here genvarname(str, exclusions) returns a legal variable name that is different from any name listed in the exclusions input. The argument exclusions can be a string, a string array, a character array, a cell array of character vectors."
},
{
"code": null,
"e": 4544,
"s": 4533,
"text": "Example 1:"
},
{
"code": null,
"e": 4551,
"s": 4544,
"text": "Matlab"
},
{
"code": "% MATLAB code for gemvarname()var_name = genvarname({'Pen', 'Pen', 'Pen', 'Pen'})",
"e": 4633,
"s": 4551,
"text": null
},
{
"code": null,
"e": 4641,
"s": 4633,
"text": "Output:"
},
{
"code": null,
"e": 4702,
"s": 4641,
"text": "var_name = 1X4 cell\n 'Pen_1' 'Pen_2' 'Pen_3' 'Pen_4'"
},
{
"code": null,
"e": 4713,
"s": 4702,
"text": "Example 2:"
},
{
"code": null,
"e": 4720,
"s": 4713,
"text": "Matlab"
},
{
"code": "% MATLAB code for genvarname() with different parametersa = [\"Pen\", \"Eraser\", \"Pencil\", \"Box\" ]var_name=genvarname(a,\"Box\")",
"e": 4844,
"s": 4720,
"text": null
},
{
"code": null,
"e": 4852,
"s": 4844,
"text": "Output:"
},
{
"code": null,
"e": 4909,
"s": 4852,
"text": "var_name= 1x4 string\n\"Pen\" \"Eraser\" \"Pencil\" \"Box1\""
},
{
"code": null,
"e": 4926,
"s": 4913,
"text": "MATLAB-Basic"
},
{
"code": null,
"e": 4933,
"s": 4926,
"text": "Picked"
},
{
"code": null,
"e": 4940,
"s": 4933,
"text": "MATLAB"
},
{
"code": null,
"e": 5038,
"s": 4940,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5117,
"s": 5038,
"text": "How to Convert Three Channels of Colored Image into Grayscale Image in MATLAB?"
},
{
"code": null,
"e": 5182,
"s": 5117,
"text": "How to Solve Histogram Equalization Numerical Problem in MATLAB?"
},
{
"code": null,
"e": 5247,
"s": 5182,
"text": "Adaptive Histogram Equalization in Image Processing Using MATLAB"
},
{
"code": null,
"e": 5280,
"s": 5247,
"text": "MRI Image Segmentation in MATLAB"
},
{
"code": null,
"e": 5354,
"s": 5280,
"text": "How to detect duplicate values and its indices within an array in MATLAB?"
},
{
"code": null,
"e": 5380,
"s": 5354,
"text": "Double Integral in MATLAB"
},
{
"code": null,
"e": 5409,
"s": 5380,
"text": "Classes and Object in MATLAB"
},
{
"code": null,
"e": 5452,
"s": 5409,
"text": "How to remove space in a string in MATLAB?"
},
{
"code": null,
"e": 5492,
"s": 5452,
"text": "How to Normalize a Histogram in MATLAB?"
}
] |
JavaScript | Trigger a button on ENTER key
|
27 Jul, 2021
To trigger a click button on ENTER key, We can use any of the keyup(), keydown() and keypress() events of jQuery.
keyup(): This event occurs when a keyboard key is released. The method either triggers the keyup event, or to run a function when a keyup event occurs.Syntax:It triggers the keyup event for selected element.$(selector).keyup()It Attaches a function to the keyup event.$(selector).keyup(function)
Syntax:
It triggers the keyup event for selected element.$(selector).keyup()
$(selector).keyup()
It Attaches a function to the keyup event.$(selector).keyup(function)
$(selector).keyup(function)
keydown(): This event occurs when a keyboard key is pressed. The method either triggers the keydown event, or to run a function when a keydown event occurs.Syntax:It triggers the keydown event for selected element.$(selector).keydown()It Attaches a function to the keydown event.$(selector).keydown(function)
It triggers the keydown event for selected element.$(selector).keydown()
$(selector).keydown()
It Attaches a function to the keydown event.$(selector).keydown(function)
$(selector).keydown(function)
keypress(): This event is similar to keydown event. This event occurs when a keyboard key is released. The method either triggers the keypress event or to run a function when a keypress event occurs.Note: This event is not fired for all keys (e.g. ALT, CTRL, SHIFT, ESC).Syntax:It triggers the keypress event for selected element.$(selector).keypress()It Attaches a function to the keypress event.$(selector).keypress(function)
It triggers the keypress event for selected element.$(selector).keypress()
$(selector).keypress()
It Attaches a function to the keypress event.$(selector).keypress(function)
$(selector).keypress(function)
Example 1: This Example uses keypress() event to trigger enter key as a button.
<!DOCTYPE html> <html> <head> <title> JavaScript | Trigger a button on ENTER key </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script></head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> Username: <input id="uname" type="text"><br> Password: <input id="pass" type="password"><br> <button id="GFG_Button">Submit</button> <script> $("#pass").keypress(function(event) { if (event.keyCode === 13) { $("#GFG_Button").click(); } }); $("#GFG_Button").click(function() { alert("Button clicked"); }); </script> </body> </html>
Output:
Before pressing on the button:
After pressing on the button:
Example 2: This example uses keyup() event to trigger enter key as a button.
<!DOCTYPE html> <html> <head> <title> JavaScript | Trigger a button on ENTER key </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script></head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> Username: <input id="uname" type="text"><br> Password: <input id="pass" type="password"><br> <button id="GFG_Button">Submit</button> <script> $("#pass").keyup(function(event) { if (event.keyCode === 13) { $("#GFG_Button").click(); } }); $("#GFG_Button").click(function() { alert("Button clicked"); }); </script> </body> </html>
Output:
Before releasing the button:
After releasing the button:
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
JavaScript-Misc
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Jul, 2021"
},
{
"code": null,
"e": 142,
"s": 28,
"text": "To trigger a click button on ENTER key, We can use any of the keyup(), keydown() and keypress() events of jQuery."
},
{
"code": null,
"e": 438,
"s": 142,
"text": "keyup(): This event occurs when a keyboard key is released. The method either triggers the keyup event, or to run a function when a keyup event occurs.Syntax:It triggers the keyup event for selected element.$(selector).keyup()It Attaches a function to the keyup event.$(selector).keyup(function)"
},
{
"code": null,
"e": 446,
"s": 438,
"text": "Syntax:"
},
{
"code": null,
"e": 515,
"s": 446,
"text": "It triggers the keyup event for selected element.$(selector).keyup()"
},
{
"code": null,
"e": 535,
"s": 515,
"text": "$(selector).keyup()"
},
{
"code": null,
"e": 605,
"s": 535,
"text": "It Attaches a function to the keyup event.$(selector).keyup(function)"
},
{
"code": null,
"e": 633,
"s": 605,
"text": "$(selector).keyup(function)"
},
{
"code": null,
"e": 942,
"s": 633,
"text": "keydown(): This event occurs when a keyboard key is pressed. The method either triggers the keydown event, or to run a function when a keydown event occurs.Syntax:It triggers the keydown event for selected element.$(selector).keydown()It Attaches a function to the keydown event.$(selector).keydown(function)"
},
{
"code": null,
"e": 1015,
"s": 942,
"text": "It triggers the keydown event for selected element.$(selector).keydown()"
},
{
"code": null,
"e": 1037,
"s": 1015,
"text": "$(selector).keydown()"
},
{
"code": null,
"e": 1111,
"s": 1037,
"text": "It Attaches a function to the keydown event.$(selector).keydown(function)"
},
{
"code": null,
"e": 1141,
"s": 1111,
"text": "$(selector).keydown(function)"
},
{
"code": null,
"e": 1569,
"s": 1141,
"text": "keypress(): This event is similar to keydown event. This event occurs when a keyboard key is released. The method either triggers the keypress event or to run a function when a keypress event occurs.Note: This event is not fired for all keys (e.g. ALT, CTRL, SHIFT, ESC).Syntax:It triggers the keypress event for selected element.$(selector).keypress()It Attaches a function to the keypress event.$(selector).keypress(function)"
},
{
"code": null,
"e": 1644,
"s": 1569,
"text": "It triggers the keypress event for selected element.$(selector).keypress()"
},
{
"code": null,
"e": 1667,
"s": 1644,
"text": "$(selector).keypress()"
},
{
"code": null,
"e": 1743,
"s": 1667,
"text": "It Attaches a function to the keypress event.$(selector).keypress(function)"
},
{
"code": null,
"e": 1774,
"s": 1743,
"text": "$(selector).keypress(function)"
},
{
"code": null,
"e": 1854,
"s": 1774,
"text": "Example 1: This Example uses keypress() event to trigger enter key as a button."
},
{
"code": "<!DOCTYPE html> <html> <head> <title> JavaScript | Trigger a button on ENTER key </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"> </script></head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> Username: <input id=\"uname\" type=\"text\"><br> Password: <input id=\"pass\" type=\"password\"><br> <button id=\"GFG_Button\">Submit</button> <script> $(\"#pass\").keypress(function(event) { if (event.keyCode === 13) { $(\"#GFG_Button\").click(); } }); $(\"#GFG_Button\").click(function() { alert(\"Button clicked\"); }); </script> </body> </html> ",
"e": 2640,
"s": 1854,
"text": null
},
{
"code": null,
"e": 2648,
"s": 2640,
"text": "Output:"
},
{
"code": null,
"e": 2679,
"s": 2648,
"text": "Before pressing on the button:"
},
{
"code": null,
"e": 2709,
"s": 2679,
"text": "After pressing on the button:"
},
{
"code": null,
"e": 2786,
"s": 2709,
"text": "Example 2: This example uses keyup() event to trigger enter key as a button."
},
{
"code": "<!DOCTYPE html> <html> <head> <title> JavaScript | Trigger a button on ENTER key </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"> </script></head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> Username: <input id=\"uname\" type=\"text\"><br> Password: <input id=\"pass\" type=\"password\"><br> <button id=\"GFG_Button\">Submit</button> <script> $(\"#pass\").keyup(function(event) { if (event.keyCode === 13) { $(\"#GFG_Button\").click(); } }); $(\"#GFG_Button\").click(function() { alert(\"Button clicked\"); }); </script> </body> </html> ",
"e": 3570,
"s": 2786,
"text": null
},
{
"code": null,
"e": 3578,
"s": 3570,
"text": "Output:"
},
{
"code": null,
"e": 3607,
"s": 3578,
"text": "Before releasing the button:"
},
{
"code": null,
"e": 3635,
"s": 3607,
"text": "After releasing the button:"
},
{
"code": null,
"e": 3854,
"s": 3635,
"text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples."
},
{
"code": null,
"e": 3870,
"s": 3854,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 3881,
"s": 3870,
"text": "JavaScript"
},
{
"code": null,
"e": 3898,
"s": 3881,
"text": "Web Technologies"
},
{
"code": null,
"e": 3925,
"s": 3898,
"text": "Web technologies Questions"
}
] |
How to use relative xpath for locating a web-element by particular Attribute in Selenium?
|
We can use relative xpath for locating web-element by particular attribute value. A relative xpath begins from the element to be located and not from the root.
It begins with the // symbol. It’s advantage is that even if an element is deleted or added in the DOM, the relative xpath for a specific element remains unaffected. To obtain a relative path by an attribute, the xpath expression is //tagname[@attribute='value'].
Let us identify the below highlighted element on the page with the help of the alt attribute.
l = driver.find_element_by_xpath("//img[@alt='tutorialspoint']")
from selenium import webdriver
#set chromodriver.exe path
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
driver.implicitly_wait(0.5)
#launch URL
driver.get("https://www.tutorialspoint.com/about/about_careers.htm")
#identify element with an attribute using xpath
l = driver.find_element_by_xpath("//img[@alt='tutorialspoint']")
#get src attribute
s = l.get_attribute('src')
print('Src attribute value is: ')
print(s)
#browser quit
driver.quit()
|
[
{
"code": null,
"e": 1347,
"s": 1187,
"text": "We can use relative xpath for locating web-element by particular attribute value. A relative xpath begins from the element to be located and not from the root."
},
{
"code": null,
"e": 1611,
"s": 1347,
"text": "It begins with the // symbol. It’s advantage is that even if an element is deleted or added in the DOM, the relative xpath for a specific element remains unaffected. To obtain a relative path by an attribute, the xpath expression is //tagname[@attribute='value']."
},
{
"code": null,
"e": 1705,
"s": 1611,
"text": "Let us identify the below highlighted element on the page with the help of the alt attribute."
},
{
"code": null,
"e": 1770,
"s": 1705,
"text": "l = driver.find_element_by_xpath(\"//img[@alt='tutorialspoint']\")"
},
{
"code": null,
"e": 2233,
"s": 1770,
"text": "from selenium import webdriver\n#set chromodriver.exe path\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\ndriver.implicitly_wait(0.5)\n#launch URL\ndriver.get(\"https://www.tutorialspoint.com/about/about_careers.htm\")\n#identify element with an attribute using xpath\nl = driver.find_element_by_xpath(\"//img[@alt='tutorialspoint']\")\n#get src attribute\ns = l.get_attribute('src')\nprint('Src attribute value is: ')\nprint(s)\n#browser quit\ndriver.quit()"
}
] |
JavaFX | How to set padding between nodes of a GridPane - GeeksforGeeks
|
06 Jun, 2019
In most cases, we look forward to seeing objects organized and well arranged, especially when we want efficiencywhile using them. In the case of object nodes of JavaFX GridPane, there will always be a need to make these objects look smart and organized.
Example: Let us see these four buttons on GridPane
// Java Program to show the four // buttons on the GridPaneimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.GridPane;import javafx.stage.Stage; public class GridpaneExamplePadding extends Application { public void start(Stage primaryStage) { primaryStage.setTitle("GridPane Example"); // creating buttons Button button1 = new Button("Button A"); Button button2 = new Button("Button B"); Button button3 = new Button("Button C"); Button button4 = new Button("Button D"); // creating Gridpane object GridPane gridPane = new GridPane(); // adding buttons to the Gridpane gridPane.add(button1, 0, 0); gridPane.add(button2, 1, 0); gridPane.add(button3, 1, 1); gridPane.add(button4, 0, 1); // Adding Gridpane to the scene // and showing the primary stage Scene scene = new Scene(gridPane, 200, 100); primaryStage.setScene(scene); primaryStage.show(); } // main to run our javaFx application public static void main(String[] args) { Application.launch(args); }}
Output:
You may need to add some spacing between buttons to make things look nice.
Adding space between columns of the Gridpane:
gridpane.setHgap(5) // set gap in pixels
Adding space between rows of the Gridpane:
gridpane.setVgap(5) // set gap in pixels
// Java program to add some spacing // between the buttons of the GridPaneimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.GridPane;import javafx.stage.Stage; public class GridpaneExamplePadding extends Application { public void start(Stage primaryStage) { primaryStage.setTitle("GridPane Example"); // creating buttons Button button1 = new Button("Button A"); Button button2 = new Button("Button B"); Button button3 = new Button("Button C"); Button button4 = new Button("Button D"); // creating Gridpane object GridPane gridPane = new GridPane(); // adding buttons to the Gridpane gridPane.add(button1, 0, 0); gridPane.add(button2, 1, 0); gridPane.add(button3, 1, 1); gridPane.add(button4, 0, 1); // spacing the buttons gridPane.setHgap(10); gridPane.setVgap(10); // Adding Gridpane to the scene // and showing the primary stage Scene scene = new Scene(gridPane, 200, 100); primaryStage.setScene(scene); primaryStage.show(); } // main to run our javaFx application public static void main(String[] args) { Application.launch(args); }}
Output:
JavaFX
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
Stream In Java
Set in Java
Multithreading in Java
Collections in Java
Queue Interface In Java
Constructors in Java
Initializing a List in Java
Exceptions in Java
Inheritance in Java
|
[
{
"code": null,
"e": 25309,
"s": 25281,
"text": "\n06 Jun, 2019"
},
{
"code": null,
"e": 25563,
"s": 25309,
"text": "In most cases, we look forward to seeing objects organized and well arranged, especially when we want efficiencywhile using them. In the case of object nodes of JavaFX GridPane, there will always be a need to make these objects look smart and organized."
},
{
"code": null,
"e": 25614,
"s": 25563,
"text": "Example: Let us see these four buttons on GridPane"
},
{
"code": "// Java Program to show the four // buttons on the GridPaneimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.GridPane;import javafx.stage.Stage; public class GridpaneExamplePadding extends Application { public void start(Stage primaryStage) { primaryStage.setTitle(\"GridPane Example\"); // creating buttons Button button1 = new Button(\"Button A\"); Button button2 = new Button(\"Button B\"); Button button3 = new Button(\"Button C\"); Button button4 = new Button(\"Button D\"); // creating Gridpane object GridPane gridPane = new GridPane(); // adding buttons to the Gridpane gridPane.add(button1, 0, 0); gridPane.add(button2, 1, 0); gridPane.add(button3, 1, 1); gridPane.add(button4, 0, 1); // Adding Gridpane to the scene // and showing the primary stage Scene scene = new Scene(gridPane, 200, 100); primaryStage.setScene(scene); primaryStage.show(); } // main to run our javaFx application public static void main(String[] args) { Application.launch(args); }}",
"e": 26813,
"s": 25614,
"text": null
},
{
"code": null,
"e": 26821,
"s": 26813,
"text": "Output:"
},
{
"code": null,
"e": 26896,
"s": 26821,
"text": "You may need to add some spacing between buttons to make things look nice."
},
{
"code": null,
"e": 27071,
"s": 26896,
"text": "Adding space between columns of the Gridpane:\ngridpane.setHgap(5) // set gap in pixels \n\nAdding space between rows of the Gridpane:\ngridpane.setVgap(5) // set gap in pixels \n"
},
{
"code": "// Java program to add some spacing // between the buttons of the GridPaneimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.GridPane;import javafx.stage.Stage; public class GridpaneExamplePadding extends Application { public void start(Stage primaryStage) { primaryStage.setTitle(\"GridPane Example\"); // creating buttons Button button1 = new Button(\"Button A\"); Button button2 = new Button(\"Button B\"); Button button3 = new Button(\"Button C\"); Button button4 = new Button(\"Button D\"); // creating Gridpane object GridPane gridPane = new GridPane(); // adding buttons to the Gridpane gridPane.add(button1, 0, 0); gridPane.add(button2, 1, 0); gridPane.add(button3, 1, 1); gridPane.add(button4, 0, 1); // spacing the buttons gridPane.setHgap(10); gridPane.setVgap(10); // Adding Gridpane to the scene // and showing the primary stage Scene scene = new Scene(gridPane, 200, 100); primaryStage.setScene(scene); primaryStage.show(); } // main to run our javaFx application public static void main(String[] args) { Application.launch(args); }}",
"e": 28374,
"s": 27071,
"text": null
},
{
"code": null,
"e": 28382,
"s": 28374,
"text": "Output:"
},
{
"code": null,
"e": 28389,
"s": 28382,
"text": "JavaFX"
},
{
"code": null,
"e": 28394,
"s": 28389,
"text": "Java"
},
{
"code": null,
"e": 28399,
"s": 28394,
"text": "Java"
},
{
"code": null,
"e": 28497,
"s": 28399,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28516,
"s": 28497,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 28531,
"s": 28516,
"text": "Stream In Java"
},
{
"code": null,
"e": 28543,
"s": 28531,
"text": "Set in Java"
},
{
"code": null,
"e": 28566,
"s": 28543,
"text": "Multithreading in Java"
},
{
"code": null,
"e": 28586,
"s": 28566,
"text": "Collections in Java"
},
{
"code": null,
"e": 28610,
"s": 28586,
"text": "Queue Interface In Java"
},
{
"code": null,
"e": 28631,
"s": 28610,
"text": "Constructors in Java"
},
{
"code": null,
"e": 28659,
"s": 28631,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 28678,
"s": 28659,
"text": "Exceptions in Java"
}
] |
Building a Simple Neural Network in R Programming - GeeksforGeeks
|
20 Aug, 2020
The term Neural Networks refers to the system of neurons either organic or artificial in nature. In artificial intelligence reference, neural networks are a set of algorithms that are designed to recognize a pattern like a human brain. They interpret sensory data through a kind of machine perception, labeling, or clustering raw input. The recognition is numerical, which is stored in vectors, into which all real-world data, be it images, sound, text, or time series, must be translated. A neural network can be pictured as a system that consists of a number of highly interconnected nodes, called ‘neurons’, which are organized in layers that process information using dynamic state responses to external inputs. Before understanding the working and architecture of neural networks, let us try to understand what artificial neurons actually are.
Perceptron: Perceptrons are a type of artificial neurons developed in the 1950s and 1960s by the scientist Frank Rosenbalt, inspired by earlier work by Warren McCulloch and Walter Pitts. So, how do perceptron works? A perceptron takes several binary outputs x1, x2, ...., and produces a single binary output.
It could have more or fewer inputs. To calculate/compute the output weights play an important role. Weights w1, w2, ...., are real numbers expressing the importance of the respective inputs to the outputs. The neuron’s output(o or 1) totally depends upon a threshold value and is computed according to the function:
Here t0 is the threshold value. It is a real number which is a parameter of the neuron. That’s the basic mathematical model. The perceptron is that it’s a device that makes decisions by weighing up the evidence. By varying the weights and the threshold, we can get different models of decision-making.
Sigmoid Neurons: Sigmoid neurons are very much closer to perceptrons, but modified so that small changes in their weights and bias cause only a small change in their output. It will allow a network of sigmoid neurons to learn more efficiently. Just like a perceptron, the sigmoid neuron has inputs, x1, x2, .... But instead of being just 0 or 1, these inputs can also be any value between 0 and 1. So, for instance, 0.567... is a valid input for a sigmoid neuron. A sigmoid neuron also has weights for each input, w1, w2, ..., and an overall bias, b. But the output is not 0 or 1. Instead, it’s σ(w.x + b), where σ is called the sigmoid function:
The output of a sigmoid neuron with inputs x1, x2, ..., weights w1, w2, ..., and bias b is:
A neural network consists of three layers:
Input Layer: Layers that take inputs based on existing data.Hidden Layer: Layers that use backpropagation to optimise the weights of the input variables in order to improve the predictive power of the model.Output Layer: Output of predictions based on the data from the input and hidden layers.
Input Layer: Layers that take inputs based on existing data.
Hidden Layer: Layers that use backpropagation to optimise the weights of the input variables in order to improve the predictive power of the model.
Output Layer: Output of predictions based on the data from the input and hidden layers.
The input data is introduced to the neural network through the input layer that has one neuron for each component present in the input data and is communicated to hidden layers(one or more) present in the network. It is called ‘hidden’ only because they do not constitute the input or output layer. In the hidden layers, all the processing actually happens through a system of connections characterized by weights and biases(as discussed earlier). Once the input is received, the neuron calculates a weighted sum adding also the bias and according to the result and an activation function (the most common one is sigmoid), it decides whether it should be ‘fired’ or ‘activated’. Then, the neuron transmits the information downstream to other connected neurons in a process called ‘forward pass’. At the end of this process, the last hidden layer is linked to the output layer which has one neuron for each possible desired output.
It is very much easier to implement a neural network by using the R language because of its excellent libraries inside it. Before implementing a neural network in R let’s understand the structure of the data first.
Understanding the structure of the data
Here let’s use the binary datasets. The objective is to predict whether a candidate will get admitted to a university with variables such as gre, gpa, and rank. The R script is provided side by side and is commented for better understanding of the user. The data is in .csv format. We will get the working directory with getwd() function and place out datasets binary.csv inside it to proceed further. Please download the csv file here.
# preparing the datasetgetwd()data <- read.csv("binary.csv" )str(data)
Output:
'data.frame': 400 obs. of 4 variables:
$ admit: int 0 1 1 1 0 1 1 0 1 0 ...
$ gre : int 380 660 800 640 520 760 560 400 540 700 ...
$ gpa : num 3.61 3.67 4 3.19 2.93 3 2.98 3.08 3.39 3.92 ...
$ rank : int 3 3 1 4 4 2 1 2 3 2 ...
Looking at the structure of the datasets we can observe that it has 4 variables, where admit tells whether a candidate will get admitted or not admitted (1 if admitted and 0 if not admitted) gre, gpa and rank give the candidates gre score, his/her gpa in the previous college and previous college rank respectively. We use admit as the dependent variable and gre, gpa, and rank as the independent variables. Now understand the whole process in a stepwise manner
Step 1: Scaling of the data
To set up a neural network to a dataset it is very important that we ensure a proper scaling of data. The scaling of data is essential because otherwise, a variable may have a large impact on the prediction variable only because of its scale. Using unscaled data may lead to meaningless results. The common techniques to scale data are min-max normalization, Z-score normalization, median and MAD, and tan-h estimators. The min-max normalization transforms the data into a common range, thus removing the scaling effect from all the variables. Here we are using min-max normalization for scaling data.
# Draw a histogram for gre datahist(data$gre)
Output:
From the above histogram of gre we can see that the gre varies from 200 to 800. We invoke the following function to normalize our data:
normalize <- function(x) {
return ((x - min(x)) / (max(x) - min(x)))
}
# Min-Max Normalizationdata$gre <- (data$gre - min(data$gre)) / (max(data$gre) - min(data$gre))hist(data$gre)
Output:
From the above representation we can see that gre data is scaled in the range of 0 to 1. Similar we do for gpa and rank.
# Min-Max Normalizationdata$gpa <- (data$gpa - min(data$gpa)) / (max(data$gpa) - min(data$gpa))hist(data$gpa)data$rank <- (data$rank - min(data$rank)) / (max(data$rank) - min(data$rank))hist(data$rank)
Output:
It can be seen from the above two histogram representation that gpa and rank are also scaled in the range of 0 to 1. The scaled data is used to fit the neural network.
Step 2: Sampling of the data
Now divide the data into a training set and test set. The training set is used to find the relationship between dependent and independent variables while the test set analyses the performance of the model. We use 60% of the dataset as a training set. The assignment of the data to training and test set is done using random sampling. We perform random sampling on R using sample() function. Use set.seed()to generate same random sample every time and maintain consistency. Use the index variable while fitting neural network to create training and test data sets. The R script is as follows:
set.seed(222)inp <- sample(2, nrow(data), replace = TRUE, prob = c(0.7, 0.3))training_data <- data[inp==1, ]test_data <- data[inp==2, ]
Step 3: Fitting a Neural Network
Now fit a neural network on our data. We use neuralnet library for the same. neuralnet() function helps us to establish a neural network for our data. The neuralnet() function we are using here has the following syntax.
Syntax:neuralnet(formula, data, hidden = 1, stepmax = 1e+05, rep = 1, lifesign = “none”, algorithm = “rprop+”, err.fct = “sse”, linear.output = TRUE)
Parameters:
library(neuralnet)set.seed(333)n <- neuralnet(admit~gre + gpa + rank, data = training_data, hidden = 5, err.fct = "ce", linear.output = FALSE, lifesign = 'full', rep = 2, algorithm = "rprop+", stepmax = 100000)
hidden: 5 thresh: 0.01 rep: 1/2 steps: 1000 min thresh: 0.092244246452834
2000 min thresh: 0.092244246452834
3000 min thresh: 0.092244246452834
4000 min thresh: 0.092244246452834
5000 min thresh: 0.092244246452834
6000 min thresh: 0.092244246452834
7000 min thresh: 0.092244246452834
8000 min thresh: 0.0657773918077728
9000 min thresh: 0.0492128119805471
10000 min thresh: 0.0350341801886022
11000 min thresh: 0.0257113452845989
12000 min thresh: 0.0175961794629306
13000 min thresh: 0.0108791716102531
13253 error: 139.80883 time: 7.51 secs
hidden: 5 thresh: 0.01 rep: 2/2 steps: 1000 min thresh: 0.147257381292693
2000 min thresh: 0.147257381292693
3000 min thresh: 0.091389043508166
4000 min thresh: 0.0648814957085886
5000 min thresh: 0.0472858320232246
6000 min thresh: 0.0359632940146351
7000 min thresh: 0.0328699898176084
8000 min thresh: 0.0305035254157369
9000 min thresh: 0.0305035254157369
10000 min thresh: 0.0241743801258625
11000 min thresh: 0.0182557959333173
12000 min thresh: 0.0136844933371039
13000 min thresh: 0.0120885410813301
14000 min thresh: 0.0109156031403791
14601 error: 147.41304 time: 8.25 secs
From the above output we conclude that both of the repetitions converge. But we will use the output-driven in the first repetition because it gives less error(139.80883) than the error(147.41304) the second repetition derives. Now, lets plot our neural network and visualize the computed neural network.
# plot our neural network plot(n, rep = 1)
Output:
The model has 5 neurons in its hidden layer. The black lines show the connections with weights. The weights are calculated using the backpropagation algorithm. The blue line is displays the bias term (constant in a regression equation). Now generate the error of the neural network model, along with the weights between the inputs, hidden layers, and outputs:
# errorn$result.matrix
Output:
[, 1] [, 2]
error 1.398088e+02 1.474130e+02
reached.threshold 9.143429e-03 9.970574e-03
steps 1.325300e+04 1.460100e+04
Intercept.to.1layhid1 -6.713132e+01 -1.136151e+02
gre.to.1layhid1 -2.448706e+01 1.469138e+02
gpa.to.1layhid1 8.326628e+01 1.290251e+02
rank.to.1layhid1 2.974782e+01 -5.733805e+01
Intercept.to.1layhid2 -2.582341e+01 2.508958e-01
gre.to.1layhid2 -5.800955e+01 1.302115e+00
gpa.to.1layhid2 3.206933e+01 -4.856419e+00
rank.to.1layhid2 6.723053e+01 1.540390e+01
Intercept.to.1layhid3 3.174853e+01 -3.495968e+01
gre.to.1layhid3 1.050214e+01 1.325498e+02
gpa.to.1layhid3 -6.478704e+01 -4.536649e+01
rank.to.1layhid3 -7.706895e+01 -1.844943e+02
Intercept.to.1layhid4 1.625662e+01 2.188646e+01
gre.to.1layhid4 -3.552645e+01 1.956271e+01
gpa.to.1layhid4 -1.151684e+01 2.052294e+01
rank.to.1layhid4 -2.263859e+01 1.347474e+01
Intercept.to.1layhid5 2.448949e+00 -3.978068e+01
gre.to.1layhid5 -2.924269e+00 -1.569897e+02
gpa.to.1layhid5 -7.773543e+00 1.500767e+02
rank.to.1layhid5 -1.107282e+03 4.045248e+02
Intercept.to.admit -5.480278e-01 -3.622384e+00
1layhid1.to.admit 1.580944e+00 1.717584e+00
1layhid2.to.admit -1.943969e+00 -6.195182e+00
1layhid3.to.admit -5.137650e+01 6.731498e+00
1layhid4.to.admit -1.112174e+03 -4.245278e+00
1layhid5.to.admit 7.259237e+02 1.156083e+01
Step 4: Prediction
Let’s predict the rating using the neural network model. We must remember that the predicted rating will be scaled and it must be transformed in order to make a comparison with the real rating. Also compare the predicted rating with real rating.
# Predictionoutput <- compute(n, rep = 1, training_data[, -1])head(output$net.result)
Output:
[, 1]
2 0.34405929
3 0.41148373
4 0.07642387
7 0.98152454
8 0.26230256
9 0.07660906
head(training_data[1, ])
Output:
admit gre gpa rank
2 1 0.7586207 0.8103448 0.6666667
Step 5: Confusion Matrix and Misclassification error
Then, we round up our results using compute() method and create a confusion matrix to compare the number of true/false positives and negatives. We will form a confusion matrix with training data
# confusion Matrix $Misclassification error -Training dataoutput <- compute(n, rep = 1, training_data[, -1])p1 <- output$net.resultpred1 <- ifelse(p1 > 0.5, 1, 0)tab1 <- table(pred1, training_data$admit)tab1
Output:
pred1 0 1
0 177 58
1 12 34
The model generates 177 true negatives (0’s), 34 true positives (1’s), while there are 12 false negatives and 58 false positives. Now, lets calculate the misclassification error (for training data) which {1 – classification error}
1 - sum(diag(tab1)) / sum(tab1)
Output:
[1] 0.2491103
The misclassification error comes out to be 24.9%. We can further increase the accuracy and efficiency of our model by increasing of decreasing nodes and bias in hidden layers .
The strength of machine learning algorithms lies in their ability to learn and improve every time in predicting an output. In the context of neural networks, it implies that the weights and biases that define the connection between neurons become more precise. This is why the weights and biases are selected such as the output from the network approximates the real value for all the training inputs. Similarly, we can make more efficient neural network models in R to predict and drive decisions.
Picked
R Data-science
R Machine-Learning
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
R - if statement
Time Series Analysis in R
Plot mean and standard deviation using ggplot2 in R
|
[
{
"code": null,
"e": 26487,
"s": 26459,
"text": "\n20 Aug, 2020"
},
{
"code": null,
"e": 27336,
"s": 26487,
"text": "The term Neural Networks refers to the system of neurons either organic or artificial in nature. In artificial intelligence reference, neural networks are a set of algorithms that are designed to recognize a pattern like a human brain. They interpret sensory data through a kind of machine perception, labeling, or clustering raw input. The recognition is numerical, which is stored in vectors, into which all real-world data, be it images, sound, text, or time series, must be translated. A neural network can be pictured as a system that consists of a number of highly interconnected nodes, called ‘neurons’, which are organized in layers that process information using dynamic state responses to external inputs. Before understanding the working and architecture of neural networks, let us try to understand what artificial neurons actually are."
},
{
"code": null,
"e": 27645,
"s": 27336,
"text": "Perceptron: Perceptrons are a type of artificial neurons developed in the 1950s and 1960s by the scientist Frank Rosenbalt, inspired by earlier work by Warren McCulloch and Walter Pitts. So, how do perceptron works? A perceptron takes several binary outputs x1, x2, ...., and produces a single binary output."
},
{
"code": null,
"e": 27961,
"s": 27645,
"text": "It could have more or fewer inputs. To calculate/compute the output weights play an important role. Weights w1, w2, ...., are real numbers expressing the importance of the respective inputs to the outputs. The neuron’s output(o or 1) totally depends upon a threshold value and is computed according to the function:"
},
{
"code": null,
"e": 28263,
"s": 27961,
"text": "Here t0 is the threshold value. It is a real number which is a parameter of the neuron. That’s the basic mathematical model. The perceptron is that it’s a device that makes decisions by weighing up the evidence. By varying the weights and the threshold, we can get different models of decision-making."
},
{
"code": null,
"e": 28910,
"s": 28263,
"text": "Sigmoid Neurons: Sigmoid neurons are very much closer to perceptrons, but modified so that small changes in their weights and bias cause only a small change in their output. It will allow a network of sigmoid neurons to learn more efficiently. Just like a perceptron, the sigmoid neuron has inputs, x1, x2, .... But instead of being just 0 or 1, these inputs can also be any value between 0 and 1. So, for instance, 0.567... is a valid input for a sigmoid neuron. A sigmoid neuron also has weights for each input, w1, w2, ..., and an overall bias, b. But the output is not 0 or 1. Instead, it’s σ(w.x + b), where σ is called the sigmoid function:"
},
{
"code": null,
"e": 29002,
"s": 28910,
"text": "The output of a sigmoid neuron with inputs x1, x2, ..., weights w1, w2, ..., and bias b is:"
},
{
"code": null,
"e": 29045,
"s": 29002,
"text": "A neural network consists of three layers:"
},
{
"code": null,
"e": 29340,
"s": 29045,
"text": "Input Layer: Layers that take inputs based on existing data.Hidden Layer: Layers that use backpropagation to optimise the weights of the input variables in order to improve the predictive power of the model.Output Layer: Output of predictions based on the data from the input and hidden layers."
},
{
"code": null,
"e": 29401,
"s": 29340,
"text": "Input Layer: Layers that take inputs based on existing data."
},
{
"code": null,
"e": 29549,
"s": 29401,
"text": "Hidden Layer: Layers that use backpropagation to optimise the weights of the input variables in order to improve the predictive power of the model."
},
{
"code": null,
"e": 29637,
"s": 29549,
"text": "Output Layer: Output of predictions based on the data from the input and hidden layers."
},
{
"code": null,
"e": 30568,
"s": 29637,
"text": "The input data is introduced to the neural network through the input layer that has one neuron for each component present in the input data and is communicated to hidden layers(one or more) present in the network. It is called ‘hidden’ only because they do not constitute the input or output layer. In the hidden layers, all the processing actually happens through a system of connections characterized by weights and biases(as discussed earlier). Once the input is received, the neuron calculates a weighted sum adding also the bias and according to the result and an activation function (the most common one is sigmoid), it decides whether it should be ‘fired’ or ‘activated’. Then, the neuron transmits the information downstream to other connected neurons in a process called ‘forward pass’. At the end of this process, the last hidden layer is linked to the output layer which has one neuron for each possible desired output."
},
{
"code": null,
"e": 30783,
"s": 30568,
"text": "It is very much easier to implement a neural network by using the R language because of its excellent libraries inside it. Before implementing a neural network in R let’s understand the structure of the data first."
},
{
"code": null,
"e": 30823,
"s": 30783,
"text": "Understanding the structure of the data"
},
{
"code": null,
"e": 31260,
"s": 30823,
"text": "Here let’s use the binary datasets. The objective is to predict whether a candidate will get admitted to a university with variables such as gre, gpa, and rank. The R script is provided side by side and is commented for better understanding of the user. The data is in .csv format. We will get the working directory with getwd() function and place out datasets binary.csv inside it to proceed further. Please download the csv file here."
},
{
"code": "# preparing the datasetgetwd()data <- read.csv(\"binary.csv\" )str(data)",
"e": 31331,
"s": 31260,
"text": null
},
{
"code": null,
"e": 31339,
"s": 31331,
"text": "Output:"
},
{
"code": null,
"e": 31582,
"s": 31339,
"text": "'data.frame': 400 obs. of 4 variables:\n $ admit: int 0 1 1 1 0 1 1 0 1 0 ...\n $ gre : int 380 660 800 640 520 760 560 400 540 700 ...\n $ gpa : num 3.61 3.67 4 3.19 2.93 3 2.98 3.08 3.39 3.92 ...\n $ rank : int 3 3 1 4 4 2 1 2 3 2 ...\n"
},
{
"code": null,
"e": 32046,
"s": 31582,
"text": "Looking at the structure of the datasets we can observe that it has 4 variables, where admit tells whether a candidate will get admitted or not admitted (1 if admitted and 0 if not admitted) gre, gpa and rank give the candidates gre score, his/her gpa in the previous college and previous college rank respectively. We use admit as the dependent variable and gre, gpa, and rank as the independent variables. Now understand the whole process in a stepwise manner"
},
{
"code": null,
"e": 32074,
"s": 32046,
"text": "Step 1: Scaling of the data"
},
{
"code": null,
"e": 32676,
"s": 32074,
"text": "To set up a neural network to a dataset it is very important that we ensure a proper scaling of data. The scaling of data is essential because otherwise, a variable may have a large impact on the prediction variable only because of its scale. Using unscaled data may lead to meaningless results. The common techniques to scale data are min-max normalization, Z-score normalization, median and MAD, and tan-h estimators. The min-max normalization transforms the data into a common range, thus removing the scaling effect from all the variables. Here we are using min-max normalization for scaling data."
},
{
"code": "# Draw a histogram for gre datahist(data$gre)",
"e": 32722,
"s": 32676,
"text": null
},
{
"code": null,
"e": 32730,
"s": 32722,
"text": "Output:"
},
{
"code": null,
"e": 32867,
"s": 32730,
"text": "From the above histogram of gre we can see that the gre varies from 200 to 800. We invoke the following function to normalize our data:"
},
{
"code": null,
"e": 32947,
"s": 32867,
"text": "normalize <- function(x) {\n return ((x - min(x)) / (max(x) - min(x)))\n}\n"
},
{
"code": "# Min-Max Normalizationdata$gre <- (data$gre - min(data$gre)) / (max(data$gre) - min(data$gre))hist(data$gre)",
"e": 33057,
"s": 32947,
"text": null
},
{
"code": null,
"e": 33065,
"s": 33057,
"text": "Output:"
},
{
"code": null,
"e": 33186,
"s": 33065,
"text": "From the above representation we can see that gre data is scaled in the range of 0 to 1. Similar we do for gpa and rank."
},
{
"code": "# Min-Max Normalizationdata$gpa <- (data$gpa - min(data$gpa)) / (max(data$gpa) - min(data$gpa))hist(data$gpa)data$rank <- (data$rank - min(data$rank)) / (max(data$rank) - min(data$rank))hist(data$rank)",
"e": 33388,
"s": 33186,
"text": null
},
{
"code": null,
"e": 33396,
"s": 33388,
"text": "Output:"
},
{
"code": null,
"e": 33564,
"s": 33396,
"text": "It can be seen from the above two histogram representation that gpa and rank are also scaled in the range of 0 to 1. The scaled data is used to fit the neural network."
},
{
"code": null,
"e": 33593,
"s": 33564,
"text": "Step 2: Sampling of the data"
},
{
"code": null,
"e": 34186,
"s": 33593,
"text": "Now divide the data into a training set and test set. The training set is used to find the relationship between dependent and independent variables while the test set analyses the performance of the model. We use 60% of the dataset as a training set. The assignment of the data to training and test set is done using random sampling. We perform random sampling on R using sample() function. Use set.seed()to generate same random sample every time and maintain consistency. Use the index variable while fitting neural network to create training and test data sets. The R script is as follows:"
},
{
"code": "set.seed(222)inp <- sample(2, nrow(data), replace = TRUE, prob = c(0.7, 0.3))training_data <- data[inp==1, ]test_data <- data[inp==2, ]",
"e": 34322,
"s": 34186,
"text": null
},
{
"code": null,
"e": 34355,
"s": 34322,
"text": "Step 3: Fitting a Neural Network"
},
{
"code": null,
"e": 34575,
"s": 34355,
"text": "Now fit a neural network on our data. We use neuralnet library for the same. neuralnet() function helps us to establish a neural network for our data. The neuralnet() function we are using here has the following syntax."
},
{
"code": null,
"e": 34725,
"s": 34575,
"text": "Syntax:neuralnet(formula, data, hidden = 1, stepmax = 1e+05, rep = 1, lifesign = “none”, algorithm = “rprop+”, err.fct = “sse”, linear.output = TRUE)"
},
{
"code": null,
"e": 34737,
"s": 34725,
"text": "Parameters:"
},
{
"code": "library(neuralnet)set.seed(333)n <- neuralnet(admit~gre + gpa + rank, data = training_data, hidden = 5, err.fct = \"ce\", linear.output = FALSE, lifesign = 'full', rep = 2, algorithm = \"rprop+\", stepmax = 100000)",
"e": 35060,
"s": 34737,
"text": null
},
{
"code": null,
"e": 37592,
"s": 35060,
"text": "hidden: 5 thresh: 0.01 rep: 1/2 steps: 1000 min thresh: 0.092244246452834\n 2000 min thresh: 0.092244246452834\n 3000 min thresh: 0.092244246452834\n 4000 min thresh: 0.092244246452834\n 5000 min thresh: 0.092244246452834\n 6000 min thresh: 0.092244246452834\n 7000 min thresh: 0.092244246452834\n 8000 min thresh: 0.0657773918077728\n 9000 min thresh: 0.0492128119805471\n 10000 min thresh: 0.0350341801886022\n 11000 min thresh: 0.0257113452845989\n 12000 min thresh: 0.0175961794629306\n 13000 min thresh: 0.0108791716102531\n 13253 error: 139.80883 time: 7.51 secs\nhidden: 5 thresh: 0.01 rep: 2/2 steps: 1000 min thresh: 0.147257381292693\n 2000 min thresh: 0.147257381292693\n 3000 min thresh: 0.091389043508166\n 4000 min thresh: 0.0648814957085886\n 5000 min thresh: 0.0472858320232246\n 6000 min thresh: 0.0359632940146351\n 7000 min thresh: 0.0328699898176084\n 8000 min thresh: 0.0305035254157369\n 9000 min thresh: 0.0305035254157369\n 10000 min thresh: 0.0241743801258625\n 11000 min thresh: 0.0182557959333173\n 12000 min thresh: 0.0136844933371039\n 13000 min thresh: 0.0120885410813301\n 14000 min thresh: 0.0109156031403791\n 14601 error: 147.41304 time: 8.25 secs\n"
},
{
"code": null,
"e": 37899,
"s": 37592,
"text": "From the above output we conclude that both of the repetitions converge. But we will use the output-driven in the first repetition because it gives less error(139.80883) than the error(147.41304) the second repetition derives. Now, lets plot our neural network and visualize the computed neural network. "
},
{
"code": "# plot our neural network plot(n, rep = 1)",
"e": 37942,
"s": 37899,
"text": null
},
{
"code": null,
"e": 37950,
"s": 37942,
"text": "Output:"
},
{
"code": null,
"e": 38310,
"s": 37950,
"text": "The model has 5 neurons in its hidden layer. The black lines show the connections with weights. The weights are calculated using the backpropagation algorithm. The blue line is displays the bias term (constant in a regression equation). Now generate the error of the neural network model, along with the weights between the inputs, hidden layers, and outputs:"
},
{
"code": "# errorn$result.matrix",
"e": 38333,
"s": 38310,
"text": null
},
{
"code": null,
"e": 38341,
"s": 38333,
"text": "Output:"
},
{
"code": null,
"e": 39844,
"s": 38341,
"text": " [, 1] [, 2]\nerror 1.398088e+02 1.474130e+02\nreached.threshold 9.143429e-03 9.970574e-03\nsteps 1.325300e+04 1.460100e+04\nIntercept.to.1layhid1 -6.713132e+01 -1.136151e+02\ngre.to.1layhid1 -2.448706e+01 1.469138e+02\ngpa.to.1layhid1 8.326628e+01 1.290251e+02\nrank.to.1layhid1 2.974782e+01 -5.733805e+01\nIntercept.to.1layhid2 -2.582341e+01 2.508958e-01\ngre.to.1layhid2 -5.800955e+01 1.302115e+00\ngpa.to.1layhid2 3.206933e+01 -4.856419e+00\nrank.to.1layhid2 6.723053e+01 1.540390e+01\nIntercept.to.1layhid3 3.174853e+01 -3.495968e+01\ngre.to.1layhid3 1.050214e+01 1.325498e+02\ngpa.to.1layhid3 -6.478704e+01 -4.536649e+01\nrank.to.1layhid3 -7.706895e+01 -1.844943e+02\nIntercept.to.1layhid4 1.625662e+01 2.188646e+01\ngre.to.1layhid4 -3.552645e+01 1.956271e+01\ngpa.to.1layhid4 -1.151684e+01 2.052294e+01\nrank.to.1layhid4 -2.263859e+01 1.347474e+01\nIntercept.to.1layhid5 2.448949e+00 -3.978068e+01\ngre.to.1layhid5 -2.924269e+00 -1.569897e+02\ngpa.to.1layhid5 -7.773543e+00 1.500767e+02\nrank.to.1layhid5 -1.107282e+03 4.045248e+02\nIntercept.to.admit -5.480278e-01 -3.622384e+00\n1layhid1.to.admit 1.580944e+00 1.717584e+00\n1layhid2.to.admit -1.943969e+00 -6.195182e+00\n1layhid3.to.admit -5.137650e+01 6.731498e+00\n1layhid4.to.admit -1.112174e+03 -4.245278e+00\n1layhid5.to.admit 7.259237e+02 1.156083e+01\n"
},
{
"code": null,
"e": 39863,
"s": 39844,
"text": "Step 4: Prediction"
},
{
"code": null,
"e": 40109,
"s": 39863,
"text": "Let’s predict the rating using the neural network model. We must remember that the predicted rating will be scaled and it must be transformed in order to make a comparison with the real rating. Also compare the predicted rating with real rating."
},
{
"code": "# Predictionoutput <- compute(n, rep = 1, training_data[, -1])head(output$net.result)",
"e": 40195,
"s": 40109,
"text": null
},
{
"code": null,
"e": 40203,
"s": 40195,
"text": "Output:"
},
{
"code": null,
"e": 40301,
"s": 40203,
"text": " \n [, 1]\n2 0.34405929\n3 0.41148373\n4 0.07642387\n7 0.98152454\n8 0.26230256\n9 0.07660906\n"
},
{
"code": "head(training_data[1, ])",
"e": 40326,
"s": 40301,
"text": null
},
{
"code": null,
"e": 40334,
"s": 40326,
"text": "Output:"
},
{
"code": null,
"e": 40409,
"s": 40334,
"text": " \n admit gre gpa rank\n2 1 0.7586207 0.8103448 0.6666667\n"
},
{
"code": null,
"e": 40462,
"s": 40409,
"text": "Step 5: Confusion Matrix and Misclassification error"
},
{
"code": null,
"e": 40657,
"s": 40462,
"text": "Then, we round up our results using compute() method and create a confusion matrix to compare the number of true/false positives and negatives. We will form a confusion matrix with training data"
},
{
"code": "# confusion Matrix $Misclassification error -Training dataoutput <- compute(n, rep = 1, training_data[, -1])p1 <- output$net.resultpred1 <- ifelse(p1 > 0.5, 1, 0)tab1 <- table(pred1, training_data$admit)tab1",
"e": 40865,
"s": 40657,
"text": null
},
{
"code": null,
"e": 40873,
"s": 40865,
"text": "Output:"
},
{
"code": null,
"e": 40915,
"s": 40873,
"text": " pred1 0 1\n 0 177 58\n 1 12 34\n"
},
{
"code": null,
"e": 41147,
"s": 40915,
"text": "The model generates 177 true negatives (0’s), 34 true positives (1’s), while there are 12 false negatives and 58 false positives. Now, lets calculate the misclassification error (for training data) which {1 – classification error}"
},
{
"code": "1 - sum(diag(tab1)) / sum(tab1)",
"e": 41179,
"s": 41147,
"text": null
},
{
"code": null,
"e": 41187,
"s": 41179,
"text": "Output:"
},
{
"code": null,
"e": 41202,
"s": 41187,
"text": "[1] 0.2491103\n"
},
{
"code": null,
"e": 41380,
"s": 41202,
"text": "The misclassification error comes out to be 24.9%. We can further increase the accuracy and efficiency of our model by increasing of decreasing nodes and bias in hidden layers ."
},
{
"code": null,
"e": 41879,
"s": 41380,
"text": "The strength of machine learning algorithms lies in their ability to learn and improve every time in predicting an output. In the context of neural networks, it implies that the weights and biases that define the connection between neurons become more precise. This is why the weights and biases are selected such as the output from the network approximates the real value for all the training inputs. Similarly, we can make more efficient neural network models in R to predict and drive decisions."
},
{
"code": null,
"e": 41886,
"s": 41879,
"text": "Picked"
},
{
"code": null,
"e": 41901,
"s": 41886,
"text": "R Data-science"
},
{
"code": null,
"e": 41920,
"s": 41901,
"text": "R Machine-Learning"
},
{
"code": null,
"e": 41931,
"s": 41920,
"text": "R Language"
},
{
"code": null,
"e": 42029,
"s": 41931,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 42081,
"s": 42029,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 42116,
"s": 42081,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 42154,
"s": 42116,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 42212,
"s": 42154,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 42255,
"s": 42212,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 42304,
"s": 42255,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 42341,
"s": 42304,
"text": "How to import an Excel File into R ?"
},
{
"code": null,
"e": 42358,
"s": 42341,
"text": "R - if statement"
},
{
"code": null,
"e": 42384,
"s": 42358,
"text": "Time Series Analysis in R"
}
] |
Group multiple occurrence of array elements ordered by first occurrence - GeeksforGeeks
|
28 Apr, 2022
Given an unsorted array with repetitions, the task is to group multiple occurrence of individual elements. The grouping should happen in a way that the order of first occurrences of all elements is maintained.Examples:
Input: arr[] = {5, 3, 5, 1, 3, 3}
Output: {5, 5, 3, 3, 3, 1}
Input: arr[] = {4, 6, 9, 2, 3, 4, 9, 6, 10, 4}
Output: {4, 4, 4, 6, 6, 9, 9, 2, 3, 10}
Simple Solution is to use nested loops. The outer loop traverses array elements one by one. The inner loop checks if this is first occurrence, if yes, then the inner loop prints it and all other occurrences.
C++
Java
Python3
C#
Javascript
// A simple C++ program to group multiple occurrences of individual// array elements#include<bits/stdc++.h>using namespace std; // A simple method to group all occurrences of individual elementsvoid groupElements(int arr[], int n){ // Initialize all elements as not visited bool *visited = new bool[n]; for (int i=0; i<n; i++) visited[i] = false; // Traverse all elements for (int i=0; i<n; i++) { // Check if this is first occurrence if (!visited[i]) { // If yes, print it and all subsequent occurrences cout << arr[i] << " "; for (int j=i+1; j<n; j++) { if (arr[i] == arr[j]) { cout << arr[i] << " "; visited[j] = true; } } } } delete [] visited; } /* Driver program to test above function */int main(){ int arr[] = {4, 6, 9, 2, 3, 4, 9, 6, 10, 4}; int n = sizeof(arr)/sizeof(arr[0]); groupElements(arr, n); return 0;}
// A simple Java program to group// multiple occurrences of individual// array elements class GFG{ // A simple method to group all occurrences // of individual elements static void groupElements(int arr[], int n) { // Initialize all elements as not visited boolean visited[] = new boolean[n]; for (int i = 0; i < n; i++) { visited[i] = false; } // Traverse all elements for (int i = 0; i < n; i++) { // Check if this is first occurrence if (!visited[i]) { // If yes, print it and all // subsequent occurrences System.out.print(arr[i] + " "); for (int j = i + 1; j < n; j++) { if (arr[i] == arr[j]) { System.out.print(arr[i] + " "); visited[j] = true; } } } } } /* Driver code */ public static void main(String[] args) { int arr[] = {4, 6, 9, 2, 3, 4, 9, 6, 10, 4}; int n = arr.length; groupElements(arr, n); }} // This code is contributed by Rajput-JI
# A simple Python 3 program to# group multiple occurrences of# individual array elements # A simple method to group all# occurrences of individual elementsdef groupElements(arr, n): # Initialize all elements # as not visited visited = [False] * n for i in range(0, n): visited[i] = False # Traverse all elements for i in range(0, n): # Check if this is # first occurrence if (visited[i] == False): # If yes, print it and # all subsequent occurrences print(arr[i], end = " ") for j in range(i + 1, n): if (arr[i] == arr[j]): print(arr[i], end = " ") visited[j] = True # Driver Codearr = [4, 6, 9, 2, 3, 4, 9, 6, 10, 4]n = len(arr)groupElements(arr, n) # This code is contributed# by Smitha
// A simple C# program to group// multiple occurrences of individual// array elementsusing System; class GFG{ // A simple method to group all occurrences // of individual elements static void groupElements(int []arr, int n) { // Initialize all elements as not visited bool []visited = new bool[n]; for (int i = 0; i < n; i++) { visited[i] = false; } // Traverse all elements for (int i = 0; i < n; i++) { // Check if this is first occurrence if (!visited[i]) { // If yes, print it and all // subsequent occurrences Console.Write(arr[i] + " "); for (int j = i + 1; j < n; j++) { if (arr[i] == arr[j]) { Console.Write(arr[i] + " "); visited[j] = true; } } } } } /* Driver code */ public static void Main(String[] args) { int []arr = {4, 6, 9, 2, 3, 4, 9, 6, 10, 4}; int n = arr.Length; groupElements(arr, n); }} // This code is contributed by PrinciRaj1992
<script> // Javascript program to group// multiple occurrences of individual// array elements // A simple method to group all occurrences // of individual elements function groupElements(arr, n) { // Initialize all elements as not visited let visited = Array(n).fill(0); for (let i = 0; i < n; i++) { visited[i] = false; } // Traverse all elements for (let i = 0; i < n; i++) { // Check if this is first occurrence if (!visited[i]) { // If yes, print it and all // subsequent occurrences document.write(arr[i] + " "); for (let j = i + 1; j < n; j++) { if (arr[i] == arr[j]) { document.write(arr[i] + " "); visited[j] = true; } } } } } // Driver program let arr = [ 4, 6, 9, 2, 3, 4, 9, 6, 10, 4]; let n = arr.length; groupElements(arr, n); </script>
Output:
4 4 4 6 6 9 9 2 3 10
Time complexity of the above method is O(n2). Binary Search Tree based Method: The time complexity can be improved to O(nLogn) using self-balancing binary search tree like Red-Black Tree or AVL tree. Following is complete algorithm. 1) Create an empty Binary Search Tree (BST). Every BST node is going to contain an array element and its count. 2) Traverse the input array and do following for every element. ........a) If element is not present in BST, then insert it with count as 0. ........b) If element is present, then increment count in corresponding BST node. 3) Traverse the array again and do following for every element. ........ If element is present in BST, then do following ..........a) Get its count and print the element ‘count’ times. ..........b) Delete the element from BST.Time Complexity of the above solution is O(nLogn).Hashing based Method: We can also use hashing. The idea is to replace Binary Search Tree with a Hash Map in above algorithm. Below is Implementation of hashing based solution.
C++
Java
Python3
C#
Javascript
#include<bits/stdc++.h>using namespace std; // C++ program to group multiple// occurrences of individual array elements // A hashing based method to group// all occurrences of individual elementsvoid orderedGroup(vector<int>&arr){ // Creates an empty hashmap map<int,int>hM; // Traverse the array elements, and store // count for every element in HashMap for(int i=0;i<arr.size();i++){ // Increment count of elements // in HashMap hM[arr[i]]++; } // Traverse array again for(int i=0;i<arr.size();i++){ // Check if this is first occurrence int count = (hM.find(arr[i]) == hM.end())? 0 : hM[arr[i]]; if(hM.find(arr[i]) != hM.end()){ // If yes, then print // the element 'count' times for(int j=0;j<count;j++){ cout<<arr[i]<<" "; } // And remove the element from HashMap. hM.erase(arr[i]); } }} // Driver Codeint main(){ vector<int>arr = {10, 5, 3, 10, 10, 4, 1, 3};orderedGroup(arr); } // This code is contributed by shinjanpatra
/* Java program to group multiple occurrences of individual array elements */import java.util.HashMap; class Main{ // A hashing based method to group all occurrences of individual elements static void orderedGroup(int arr[]) { // Creates an empty hashmap HashMap<Integer, Integer> hM = new HashMap<Integer, Integer>(); // Traverse the array elements, and store count for every element // in HashMap for (int i=0; i<arr.length; i++) { // Check if element is already in HashMap Integer prevCount = hM.get(arr[i]); if (prevCount == null) prevCount = 0; // Increment count of element element in HashMap hM.put(arr[i], prevCount + 1); } // Traverse array again for (int i=0; i<arr.length; i++) { // Check if this is first occurrence Integer count = hM.get(arr[i]); if (count != null) { // If yes, then print the element 'count' times for (int j=0; j<count; j++) System.out.print(arr[i] + " "); // And remove the element from HashMap. hM.remove(arr[i]); } } } // Driver method to test above method public static void main (String[] args) { int arr[] = {10, 5, 3, 10, 10, 4, 1, 3}; orderedGroup(arr); }}
# Python3 program to group multiple# occurrences of individual array elements # A hashing based method to group# all occurrences of individual elementsdef orderedGroup(arr): # Creates an empty hashmap hM = {} # Traverse the array elements, and store # count for every element in HashMap for i in range(0, len(arr)): # Increment count of elements # in HashMap hM[arr[i]] = hM.get(arr[i], 0) + 1 # Traverse array again for i in range(0, len(arr)): # Check if this is first occurrence count = hM.get(arr[i], None) if count != None: # If yes, then print # the element 'count' times for j in range(0, count): print(arr[i], end = " ") # And remove the element from HashMap. del hM[arr[i]] # Driver Codeif __name__ == "__main__": arr = [10, 5, 3, 10, 10, 4, 1, 3] orderedGroup(arr) # This code is contributed by Rituraj Jain
// C# program to group multiple occurrences// of individual array elementsusing System;using System.Collections.Generic; class GFG{ // A hashing based method to group// all occurrences of individual elementsstatic void orderedGroup(int []arr){ // Creates an empty hashmap Dictionary<int, int> hM = new Dictionary<int, int>(); // Traverse the array elements, // and store count for every element in HashMap for (int i = 0; i < arr.Length; i++) { // Check if element is already in HashMap int prevCount = 0; if (hM.ContainsKey(arr[i])) prevCount = hM[arr[i]]; // Increment count of element element in HashMap if (hM.ContainsKey(arr[i])) hM[arr[i]] = prevCount + 1; else hM.Add(arr[i], prevCount + 1); } // Traverse array again for (int i = 0; i < arr.Length; i++) { // Check if this is first occurrence int count = 0; if (hM.ContainsKey(arr[i])) count = hM[arr[i]]; if (count != 0) { // If yes, then print the // element 'count' times for (int j = 0; j < count; j++) Console.Write(arr[i] + " "); // And remove the element from HashMap. hM.Remove(arr[i]); } }} // Driver Codepublic static void Main (String[] args){ int []arr = {10, 5, 3, 10, 10, 4, 1, 3}; orderedGroup(arr);}} // This code is contributed by Princi Singh
<script> // JavaScript program to group multiple occurrences // of individual array elements // A hashing based method to group // all occurrences of individual elements function orderedGroup(arr) { // Creates an empty hashmap var hM = {}; // Traverse the array elements, // and store count for every element in HashMap for (var i = 0; i < arr.length; i++) { // Check if element is already in HashMap var prevCount = 0; if (hM.hasOwnProperty(arr[i])) prevCount = hM[arr[i]]; // Increment count of element element in HashMap if (hM.hasOwnProperty(arr[i])) hM[arr[i]] = prevCount + 1; else hM[arr[i]] = prevCount + 1; } // Traverse array again for (var i = 0; i < arr.length; i++) { // Check if this is first occurrence var count = 0; if (hM.hasOwnProperty(arr[i])) count = hM[arr[i]]; if (count !== 0) { // If yes, then print the // element 'count' times for (var j = 0; j < count; j++) document.write(arr[i] + " "); // And remove the element from HashMap. delete hM[arr[i]]; } } } // Driver Code var arr = [10, 5, 3, 10, 10, 4, 1, 3]; orderedGroup(arr); </script>
Output:
10 10 10 5 3 3 4 1
Time Complexity of the above hashing based solution is Θ(n) under the assumption that insert, search and delete operations on HashMap take O(1) time.Below is a related problem for strings. Group all occurrences of characters according to first appearanceThis article is contributed by Himanshu Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Smitha Dinesh Semwal
Rajput-Ji
princiraj1992
rituraj_jain
princi singh
chinmoy1997pal
rdtank
khushboogoyal499
shinjanpatra
Hash
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Hashing | Set 2 (Separate Chaining)
Sort string of characters
Counting frequencies of array elements
Most frequent element in an array
Sorting a Map by value in C++ STL
Longest Consecutive Subsequence
Return maximum occurring character in an input string
C++ program for hashing with chaining
Double Hashing
Rearrange an array such that arr[i] = i
|
[
{
"code": null,
"e": 25975,
"s": 25947,
"text": "\n28 Apr, 2022"
},
{
"code": null,
"e": 26196,
"s": 25975,
"text": "Given an unsorted array with repetitions, the task is to group multiple occurrence of individual elements. The grouping should happen in a way that the order of first occurrences of all elements is maintained.Examples: "
},
{
"code": null,
"e": 26359,
"s": 26196,
"text": "Input: arr[] = {5, 3, 5, 1, 3, 3}\nOutput: {5, 5, 3, 3, 3, 1}\n\nInput: arr[] = {4, 6, 9, 2, 3, 4, 9, 6, 10, 4}\nOutput: {4, 4, 4, 6, 6, 9, 9, 2, 3, 10}"
},
{
"code": null,
"e": 26571,
"s": 26361,
"text": "Simple Solution is to use nested loops. The outer loop traverses array elements one by one. The inner loop checks if this is first occurrence, if yes, then the inner loop prints it and all other occurrences. "
},
{
"code": null,
"e": 26575,
"s": 26571,
"text": "C++"
},
{
"code": null,
"e": 26580,
"s": 26575,
"text": "Java"
},
{
"code": null,
"e": 26588,
"s": 26580,
"text": "Python3"
},
{
"code": null,
"e": 26591,
"s": 26588,
"text": "C#"
},
{
"code": null,
"e": 26602,
"s": 26591,
"text": "Javascript"
},
{
"code": "// A simple C++ program to group multiple occurrences of individual// array elements#include<bits/stdc++.h>using namespace std; // A simple method to group all occurrences of individual elementsvoid groupElements(int arr[], int n){ // Initialize all elements as not visited bool *visited = new bool[n]; for (int i=0; i<n; i++) visited[i] = false; // Traverse all elements for (int i=0; i<n; i++) { // Check if this is first occurrence if (!visited[i]) { // If yes, print it and all subsequent occurrences cout << arr[i] << \" \"; for (int j=i+1; j<n; j++) { if (arr[i] == arr[j]) { cout << arr[i] << \" \"; visited[j] = true; } } } } delete [] visited; } /* Driver program to test above function */int main(){ int arr[] = {4, 6, 9, 2, 3, 4, 9, 6, 10, 4}; int n = sizeof(arr)/sizeof(arr[0]); groupElements(arr, n); return 0;}",
"e": 27634,
"s": 26602,
"text": null
},
{
"code": "// A simple Java program to group// multiple occurrences of individual// array elements class GFG{ // A simple method to group all occurrences // of individual elements static void groupElements(int arr[], int n) { // Initialize all elements as not visited boolean visited[] = new boolean[n]; for (int i = 0; i < n; i++) { visited[i] = false; } // Traverse all elements for (int i = 0; i < n; i++) { // Check if this is first occurrence if (!visited[i]) { // If yes, print it and all // subsequent occurrences System.out.print(arr[i] + \" \"); for (int j = i + 1; j < n; j++) { if (arr[i] == arr[j]) { System.out.print(arr[i] + \" \"); visited[j] = true; } } } } } /* Driver code */ public static void main(String[] args) { int arr[] = {4, 6, 9, 2, 3, 4, 9, 6, 10, 4}; int n = arr.length; groupElements(arr, n); }} // This code is contributed by Rajput-JI",
"e": 28910,
"s": 27634,
"text": null
},
{
"code": "# A simple Python 3 program to# group multiple occurrences of# individual array elements # A simple method to group all# occurrences of individual elementsdef groupElements(arr, n): # Initialize all elements # as not visited visited = [False] * n for i in range(0, n): visited[i] = False # Traverse all elements for i in range(0, n): # Check if this is # first occurrence if (visited[i] == False): # If yes, print it and # all subsequent occurrences print(arr[i], end = \" \") for j in range(i + 1, n): if (arr[i] == arr[j]): print(arr[i], end = \" \") visited[j] = True # Driver Codearr = [4, 6, 9, 2, 3, 4, 9, 6, 10, 4]n = len(arr)groupElements(arr, n) # This code is contributed# by Smitha",
"e": 29806,
"s": 28910,
"text": null
},
{
"code": "// A simple C# program to group// multiple occurrences of individual// array elementsusing System; class GFG{ // A simple method to group all occurrences // of individual elements static void groupElements(int []arr, int n) { // Initialize all elements as not visited bool []visited = new bool[n]; for (int i = 0; i < n; i++) { visited[i] = false; } // Traverse all elements for (int i = 0; i < n; i++) { // Check if this is first occurrence if (!visited[i]) { // If yes, print it and all // subsequent occurrences Console.Write(arr[i] + \" \"); for (int j = i + 1; j < n; j++) { if (arr[i] == arr[j]) { Console.Write(arr[i] + \" \"); visited[j] = true; } } } } } /* Driver code */ public static void Main(String[] args) { int []arr = {4, 6, 9, 2, 3, 4, 9, 6, 10, 4}; int n = arr.Length; groupElements(arr, n); }} // This code is contributed by PrinciRaj1992",
"e": 31085,
"s": 29806,
"text": null
},
{
"code": "<script> // Javascript program to group// multiple occurrences of individual// array elements // A simple method to group all occurrences // of individual elements function groupElements(arr, n) { // Initialize all elements as not visited let visited = Array(n).fill(0); for (let i = 0; i < n; i++) { visited[i] = false; } // Traverse all elements for (let i = 0; i < n; i++) { // Check if this is first occurrence if (!visited[i]) { // If yes, print it and all // subsequent occurrences document.write(arr[i] + \" \"); for (let j = i + 1; j < n; j++) { if (arr[i] == arr[j]) { document.write(arr[i] + \" \"); visited[j] = true; } } } } } // Driver program let arr = [ 4, 6, 9, 2, 3, 4, 9, 6, 10, 4]; let n = arr.length; groupElements(arr, n); </script>",
"e": 32260,
"s": 31085,
"text": null
},
{
"code": null,
"e": 32269,
"s": 32260,
"text": "Output: "
},
{
"code": null,
"e": 32290,
"s": 32269,
"text": "4 4 4 6 6 9 9 2 3 10"
},
{
"code": null,
"e": 33312,
"s": 32290,
"text": "Time complexity of the above method is O(n2). Binary Search Tree based Method: The time complexity can be improved to O(nLogn) using self-balancing binary search tree like Red-Black Tree or AVL tree. Following is complete algorithm. 1) Create an empty Binary Search Tree (BST). Every BST node is going to contain an array element and its count. 2) Traverse the input array and do following for every element. ........a) If element is not present in BST, then insert it with count as 0. ........b) If element is present, then increment count in corresponding BST node. 3) Traverse the array again and do following for every element. ........ If element is present in BST, then do following ..........a) Get its count and print the element ‘count’ times. ..........b) Delete the element from BST.Time Complexity of the above solution is O(nLogn).Hashing based Method: We can also use hashing. The idea is to replace Binary Search Tree with a Hash Map in above algorithm. Below is Implementation of hashing based solution. "
},
{
"code": null,
"e": 33316,
"s": 33312,
"text": "C++"
},
{
"code": null,
"e": 33321,
"s": 33316,
"text": "Java"
},
{
"code": null,
"e": 33329,
"s": 33321,
"text": "Python3"
},
{
"code": null,
"e": 33332,
"s": 33329,
"text": "C#"
},
{
"code": null,
"e": 33343,
"s": 33332,
"text": "Javascript"
},
{
"code": "#include<bits/stdc++.h>using namespace std; // C++ program to group multiple// occurrences of individual array elements // A hashing based method to group// all occurrences of individual elementsvoid orderedGroup(vector<int>&arr){ // Creates an empty hashmap map<int,int>hM; // Traverse the array elements, and store // count for every element in HashMap for(int i=0;i<arr.size();i++){ // Increment count of elements // in HashMap hM[arr[i]]++; } // Traverse array again for(int i=0;i<arr.size();i++){ // Check if this is first occurrence int count = (hM.find(arr[i]) == hM.end())? 0 : hM[arr[i]]; if(hM.find(arr[i]) != hM.end()){ // If yes, then print // the element 'count' times for(int j=0;j<count;j++){ cout<<arr[i]<<\" \"; } // And remove the element from HashMap. hM.erase(arr[i]); } }} // Driver Codeint main(){ vector<int>arr = {10, 5, 3, 10, 10, 4, 1, 3};orderedGroup(arr); } // This code is contributed by shinjanpatra",
"e": 34501,
"s": 33343,
"text": null
},
{
"code": "/* Java program to group multiple occurrences of individual array elements */import java.util.HashMap; class Main{ // A hashing based method to group all occurrences of individual elements static void orderedGroup(int arr[]) { // Creates an empty hashmap HashMap<Integer, Integer> hM = new HashMap<Integer, Integer>(); // Traverse the array elements, and store count for every element // in HashMap for (int i=0; i<arr.length; i++) { // Check if element is already in HashMap Integer prevCount = hM.get(arr[i]); if (prevCount == null) prevCount = 0; // Increment count of element element in HashMap hM.put(arr[i], prevCount + 1); } // Traverse array again for (int i=0; i<arr.length; i++) { // Check if this is first occurrence Integer count = hM.get(arr[i]); if (count != null) { // If yes, then print the element 'count' times for (int j=0; j<count; j++) System.out.print(arr[i] + \" \"); // And remove the element from HashMap. hM.remove(arr[i]); } } } // Driver method to test above method public static void main (String[] args) { int arr[] = {10, 5, 3, 10, 10, 4, 1, 3}; orderedGroup(arr); }}",
"e": 35948,
"s": 34501,
"text": null
},
{
"code": "# Python3 program to group multiple# occurrences of individual array elements # A hashing based method to group# all occurrences of individual elementsdef orderedGroup(arr): # Creates an empty hashmap hM = {} # Traverse the array elements, and store # count for every element in HashMap for i in range(0, len(arr)): # Increment count of elements # in HashMap hM[arr[i]] = hM.get(arr[i], 0) + 1 # Traverse array again for i in range(0, len(arr)): # Check if this is first occurrence count = hM.get(arr[i], None) if count != None: # If yes, then print # the element 'count' times for j in range(0, count): print(arr[i], end = \" \") # And remove the element from HashMap. del hM[arr[i]] # Driver Codeif __name__ == \"__main__\": arr = [10, 5, 3, 10, 10, 4, 1, 3] orderedGroup(arr) # This code is contributed by Rituraj Jain",
"e": 36981,
"s": 35948,
"text": null
},
{
"code": "// C# program to group multiple occurrences// of individual array elementsusing System;using System.Collections.Generic; class GFG{ // A hashing based method to group// all occurrences of individual elementsstatic void orderedGroup(int []arr){ // Creates an empty hashmap Dictionary<int, int> hM = new Dictionary<int, int>(); // Traverse the array elements, // and store count for every element in HashMap for (int i = 0; i < arr.Length; i++) { // Check if element is already in HashMap int prevCount = 0; if (hM.ContainsKey(arr[i])) prevCount = hM[arr[i]]; // Increment count of element element in HashMap if (hM.ContainsKey(arr[i])) hM[arr[i]] = prevCount + 1; else hM.Add(arr[i], prevCount + 1); } // Traverse array again for (int i = 0; i < arr.Length; i++) { // Check if this is first occurrence int count = 0; if (hM.ContainsKey(arr[i])) count = hM[arr[i]]; if (count != 0) { // If yes, then print the // element 'count' times for (int j = 0; j < count; j++) Console.Write(arr[i] + \" \"); // And remove the element from HashMap. hM.Remove(arr[i]); } }} // Driver Codepublic static void Main (String[] args){ int []arr = {10, 5, 3, 10, 10, 4, 1, 3}; orderedGroup(arr);}} // This code is contributed by Princi Singh",
"e": 38518,
"s": 36981,
"text": null
},
{
"code": "<script> // JavaScript program to group multiple occurrences // of individual array elements // A hashing based method to group // all occurrences of individual elements function orderedGroup(arr) { // Creates an empty hashmap var hM = {}; // Traverse the array elements, // and store count for every element in HashMap for (var i = 0; i < arr.length; i++) { // Check if element is already in HashMap var prevCount = 0; if (hM.hasOwnProperty(arr[i])) prevCount = hM[arr[i]]; // Increment count of element element in HashMap if (hM.hasOwnProperty(arr[i])) hM[arr[i]] = prevCount + 1; else hM[arr[i]] = prevCount + 1; } // Traverse array again for (var i = 0; i < arr.length; i++) { // Check if this is first occurrence var count = 0; if (hM.hasOwnProperty(arr[i])) count = hM[arr[i]]; if (count !== 0) { // If yes, then print the // element 'count' times for (var j = 0; j < count; j++) document.write(arr[i] + \" \"); // And remove the element from HashMap. delete hM[arr[i]]; } } } // Driver Code var arr = [10, 5, 3, 10, 10, 4, 1, 3]; orderedGroup(arr); </script>",
"e": 39867,
"s": 38518,
"text": null
},
{
"code": null,
"e": 39876,
"s": 39867,
"text": "Output: "
},
{
"code": null,
"e": 39896,
"s": 39876,
"text": "10 10 10 5 3 3 4 1 "
},
{
"code": null,
"e": 40323,
"s": 39896,
"text": "Time Complexity of the above hashing based solution is Θ(n) under the assumption that insert, search and delete operations on HashMap take O(1) time.Below is a related problem for strings. Group all occurrences of characters according to first appearanceThis article is contributed by Himanshu Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 40344,
"s": 40323,
"text": "Smitha Dinesh Semwal"
},
{
"code": null,
"e": 40354,
"s": 40344,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 40368,
"s": 40354,
"text": "princiraj1992"
},
{
"code": null,
"e": 40381,
"s": 40368,
"text": "rituraj_jain"
},
{
"code": null,
"e": 40394,
"s": 40381,
"text": "princi singh"
},
{
"code": null,
"e": 40409,
"s": 40394,
"text": "chinmoy1997pal"
},
{
"code": null,
"e": 40416,
"s": 40409,
"text": "rdtank"
},
{
"code": null,
"e": 40433,
"s": 40416,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 40446,
"s": 40433,
"text": "shinjanpatra"
},
{
"code": null,
"e": 40451,
"s": 40446,
"text": "Hash"
},
{
"code": null,
"e": 40456,
"s": 40451,
"text": "Hash"
},
{
"code": null,
"e": 40554,
"s": 40456,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40590,
"s": 40554,
"text": "Hashing | Set 2 (Separate Chaining)"
},
{
"code": null,
"e": 40616,
"s": 40590,
"text": "Sort string of characters"
},
{
"code": null,
"e": 40655,
"s": 40616,
"text": "Counting frequencies of array elements"
},
{
"code": null,
"e": 40689,
"s": 40655,
"text": "Most frequent element in an array"
},
{
"code": null,
"e": 40723,
"s": 40689,
"text": "Sorting a Map by value in C++ STL"
},
{
"code": null,
"e": 40755,
"s": 40723,
"text": "Longest Consecutive Subsequence"
},
{
"code": null,
"e": 40809,
"s": 40755,
"text": "Return maximum occurring character in an input string"
},
{
"code": null,
"e": 40847,
"s": 40809,
"text": "C++ program for hashing with chaining"
},
{
"code": null,
"e": 40862,
"s": 40847,
"text": "Double Hashing"
}
] |
Python: Passing Dictionary as Arguments to Function - GeeksforGeeks
|
30 Jan, 2020
A dictionary in Python is a collection of data which is unordered and mutable. Unlike, numeric indices used by lists, a dictionary uses the key as an index for a specific value. It can be used to store unrelated data types but data that is related as a real-world entity. The keys themselves are employed for using a specific value.
Refer to the below article to get the idea about Python Dictionary.
Python Dictionary
In Python, everything is an object, so the dictionary can be passed as an argument to a function like other variables are passed.
Example:
# Python program to demonstrate# passing dictionary as argument # A function that takes dictionary# as an argumentdef func(d): for key in d: print("key:", key, "Value:", d[key]) # Driver's codeD = {'a':1, 'b':2, 'c':3}func(D)
Output:
key: b Value: 2
key: a Value: 1
key: c Value: 3
Passing Dictionary as kwargs
“kwargs” stands for keyword arguments. It is used for passing advanced data objects like dictionaries to a function because in such functions one doesn’t have a clue about the number of arguments, hence data passed is be dealt properly by adding “**” to the passing type.
Example 1:
# Python program to demonstrate# passing dictionary as kwargs def display(**name): print (name["fname"]+" "+name["mname"]+" "+name["lname"]) def main(): # passing dictionary key-value # pair as arguments display(fname ="John", mname ="F.", lname ="Kennedy")# Driver's codemain()
Output:
John F. Kennedy
Example 2:
# Python program to demonstrate# passing dictionary as kwargs def display(x = 0, y = 0, **name): print (name["fname"]+" "+name["mname"]+" "+name["lname"]) print ("x =", x) print ("y =", y) def main(): # passing dictionary key-value # pair with other arguments display(2, fname ="John", mname ="F.", lname ="Kennedy") # Driver's codemain()
Output:
John F. Kennedy
x = 2
y = 0
Python dictionary-programs
python-dict
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
|
[
{
"code": null,
"e": 25553,
"s": 25525,
"text": "\n30 Jan, 2020"
},
{
"code": null,
"e": 25886,
"s": 25553,
"text": "A dictionary in Python is a collection of data which is unordered and mutable. Unlike, numeric indices used by lists, a dictionary uses the key as an index for a specific value. It can be used to store unrelated data types but data that is related as a real-world entity. The keys themselves are employed for using a specific value."
},
{
"code": null,
"e": 25954,
"s": 25886,
"text": "Refer to the below article to get the idea about Python Dictionary."
},
{
"code": null,
"e": 25972,
"s": 25954,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26102,
"s": 25972,
"text": "In Python, everything is an object, so the dictionary can be passed as an argument to a function like other variables are passed."
},
{
"code": null,
"e": 26111,
"s": 26102,
"text": "Example:"
},
{
"code": "# Python program to demonstrate# passing dictionary as argument # A function that takes dictionary# as an argumentdef func(d): for key in d: print(\"key:\", key, \"Value:\", d[key]) # Driver's codeD = {'a':1, 'b':2, 'c':3}func(D)",
"e": 26365,
"s": 26111,
"text": null
},
{
"code": null,
"e": 26373,
"s": 26365,
"text": "Output:"
},
{
"code": null,
"e": 26422,
"s": 26373,
"text": "key: b Value: 2\nkey: a Value: 1\nkey: c Value: 3\n"
},
{
"code": null,
"e": 26451,
"s": 26422,
"text": "Passing Dictionary as kwargs"
},
{
"code": null,
"e": 26723,
"s": 26451,
"text": "“kwargs” stands for keyword arguments. It is used for passing advanced data objects like dictionaries to a function because in such functions one doesn’t have a clue about the number of arguments, hence data passed is be dealt properly by adding “**” to the passing type."
},
{
"code": null,
"e": 26734,
"s": 26723,
"text": "Example 1:"
},
{
"code": "# Python program to demonstrate# passing dictionary as kwargs def display(**name): print (name[\"fname\"]+\" \"+name[\"mname\"]+\" \"+name[\"lname\"]) def main(): # passing dictionary key-value # pair as arguments display(fname =\"John\", mname =\"F.\", lname =\"Kennedy\")# Driver's codemain()",
"e": 27065,
"s": 26734,
"text": null
},
{
"code": null,
"e": 27073,
"s": 27065,
"text": "Output:"
},
{
"code": null,
"e": 27090,
"s": 27073,
"text": "John F. Kennedy\n"
},
{
"code": null,
"e": 27101,
"s": 27090,
"text": "Example 2:"
},
{
"code": "# Python program to demonstrate# passing dictionary as kwargs def display(x = 0, y = 0, **name): print (name[\"fname\"]+\" \"+name[\"mname\"]+\" \"+name[\"lname\"]) print (\"x =\", x) print (\"y =\", y) def main(): # passing dictionary key-value # pair with other arguments display(2, fname =\"John\", mname =\"F.\", lname =\"Kennedy\") # Driver's codemain()",
"e": 27474,
"s": 27101,
"text": null
},
{
"code": null,
"e": 27482,
"s": 27474,
"text": "Output:"
},
{
"code": null,
"e": 27511,
"s": 27482,
"text": "John F. Kennedy\nx = 2\ny = 0\n"
},
{
"code": null,
"e": 27538,
"s": 27511,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 27550,
"s": 27538,
"text": "python-dict"
},
{
"code": null,
"e": 27557,
"s": 27550,
"text": "Python"
},
{
"code": null,
"e": 27569,
"s": 27557,
"text": "python-dict"
},
{
"code": null,
"e": 27667,
"s": 27569,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27685,
"s": 27667,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27717,
"s": 27685,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27739,
"s": 27717,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27781,
"s": 27739,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27811,
"s": 27781,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27837,
"s": 27811,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27866,
"s": 27837,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27903,
"s": 27866,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 27939,
"s": 27903,
"text": "Convert integer to string in Python"
}
] |
NseTools - Getting Stock Quote of Given Company - GeeksforGeeks
|
18 Aug, 2020
In this article we will see how we can get the stock quote of given company using nsetools. Nsetools is a library for collecting real time data from National Stock Exchange of India. A stock quote is the price of a stock as quoted on an exchange. A basic quote for a specific stock provides information, such as its bid and ask price, last traded price, and volume traded.
Steps to get the Stock Quote1. Import the Nse from nsetools2. Create a Nse object3. From the Nse object get the stock quote with the help of get_quote method with the NSE Stock code of the company4. Print the stock quote
Below is the implementation
# importing nse from nse toolsfrom nsetools import Nse # creating a Nse objectnse = Nse() # nse stock code for wiprocode = "wipro" # getting stock quote quote = nse.get_quote(code) # printing quoteprint(quote)
Output :
{'pricebandupper': 309.15, 'symbol': 'WIPRO', 'applicableMargin': 19.23, 'bcEndDate': '13-JUL-20', 'totalSellQuantity': None, 'adhocMargin': None, 'companyName': 'Wipro Limited', 'marketType': 'N', 'exDate': '08-JUL-20', 'bcStartDate': '10-JUL-20', 'css_status_desc': 'Listed', 'dayHigh': 284.45, 'basePrice': 281.05, 'securityVar': 15.73, 'pricebandlower': 252.95, 'sellQuantity5': None, 'sellQuantity4': None, 'sellQuantity3': None, 'cm_adj_high_dt': '31-JUL-20', 'sellQuantity2': None, 'dayLow': 277.4, 'sellQuantity1': None, 'quantityTraded': 7345555.0, 'pChange': '-1.05', 'totalTradedValue': 20596.94, 'deliveryToTradedQuantity': 21.36, 'totalBuyQuantity': 610.0, 'averagePrice': 280.4, 'indexVar': None, 'cm_ffm': 41333.68, 'purpose': 'ANNUAL GENERAL MEETING', 'buyPrice2': None, 'secDate': '05-Aug-2020 00:00:00', 'buyPrice1': 278.2, 'high52': 290.8, 'previousClose': 281.05, 'ndEndDate': None, 'low52': 159.4, 'buyPrice4': None, 'buyPrice3': None, 'recordDate': None, 'deliveryQuantity': 1569237.0, 'buyPrice5': None, 'priceBand': 'No Band', 'extremeLossMargin': 3.5, 'cm_adj_low_dt': '19-MAR-20', 'varMargin': 15.73, 'sellPrice1': None, 'sellPrice2': None, 'totalTradedVolume': 7345555.0, 'sellPrice3': None, 'sellPrice4': None, 'sellPrice5': None, 'change': '-2.95', 'surv_indicator': None, 'ndStartDate': None, 'buyQuantity4': None, 'isExDateFlag': False, 'buyQuantity3': None, 'buyQuantity2': None, 'buyQuantity1': 610.0, 'series': 'EQ', 'faceValue': 2.0, 'buyQuantity5': None, 'closePrice': 278.2, 'open': 281.25, 'isinCode': 'INE075A01022', 'lastPrice': 278.1}
Another example
# importing nse from nse toolsfrom nsetools import Nse # creating a Nse objectnse = Nse() # nse stock code for hdfccode = "hdfcbank" # getting stock quote quote = nse.get_quote(code) # printing quoteprint(quote)
Output :
{'pricebandupper': 1145.8, 'symbol': 'HDFCBANK', 'applicableMargin': 18.2, 'bcEndDate': None, 'totalSellQuantity': None, 'adhocMargin': None, 'companyName': 'HDFC Bank Limited', 'marketType': 'N', 'exDate': '19-SEP-19', 'bcStartDate': None, 'css_status_desc': 'Listed', 'dayHigh': 1055.8, 'basePrice': 1041.65, 'securityVar': 14.7, 'pricebandlower': 937.5, 'sellQuantity5': None, 'sellQuantity4': None, 'sellQuantity3': None, 'cm_adj_high_dt': '19-DEC-19', 'sellQuantity2': None, 'dayLow': 1020.0, 'sellQuantity1': None, 'quantityTraded': 16610696.0, 'pChange': '-1.03', 'totalTradedValue': 172025.35, 'deliveryToTradedQuantity': 26.31, 'totalBuyQuantity': 7009.0, 'averagePrice': 1035.63, 'indexVar': None, 'cm_ffm': 445360.08, 'purpose': 'FACE VALUE SPLIT (SUB-DIVISION) - FROM RS 2 PER SHARE TO RS 1 PER SHARE', 'buyPrice2': None, 'secDate': '05-Aug-2020 00:00:00', 'buyPrice1': 1027.55, 'high52': 1305.5, 'previousClose': 1041.65, 'ndEndDate': None, 'low52': 738.75, 'buyPrice4': None, 'buyPrice3': None, 'recordDate': '20-SEP-19', 'deliveryQuantity': 4369897.0, 'buyPrice5': None, 'priceBand': 'No Band', 'extremeLossMargin': 3.5, 'cm_adj_low_dt': '24-MAR-20', 'varMargin': 14.7, 'sellPrice1': None, 'sellPrice2': None, 'totalTradedVolume': 16610696.0, 'sellPrice3': None, 'sellPrice4': None, 'sellPrice5': None, 'change': '-10.70', 'surv_indicator': None, 'ndStartDate': None, 'buyQuantity4': None, 'isExDateFlag': False, 'buyQuantity3': None, 'buyQuantity2': None, 'buyQuantity1': 7009.0, 'series': 'EQ', 'faceValue': 1.0, 'buyQuantity5': None, 'closePrice': 1027.55, 'open': 1047.95, 'isinCode': 'INE040A01034', 'lastPrice': 1030.95}
Python NseTools-library
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Convert integer to string in Python
Check if element exists in list in Python
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 26175,
"s": 26147,
"text": "\n18 Aug, 2020"
},
{
"code": null,
"e": 26548,
"s": 26175,
"text": "In this article we will see how we can get the stock quote of given company using nsetools. Nsetools is a library for collecting real time data from National Stock Exchange of India. A stock quote is the price of a stock as quoted on an exchange. A basic quote for a specific stock provides information, such as its bid and ask price, last traded price, and volume traded."
},
{
"code": null,
"e": 26769,
"s": 26548,
"text": "Steps to get the Stock Quote1. Import the Nse from nsetools2. Create a Nse object3. From the Nse object get the stock quote with the help of get_quote method with the NSE Stock code of the company4. Print the stock quote"
},
{
"code": null,
"e": 26797,
"s": 26769,
"text": "Below is the implementation"
},
{
"code": "# importing nse from nse toolsfrom nsetools import Nse # creating a Nse objectnse = Nse() # nse stock code for wiprocode = \"wipro\" # getting stock quote quote = nse.get_quote(code) # printing quoteprint(quote)",
"e": 27011,
"s": 26797,
"text": null
},
{
"code": null,
"e": 27020,
"s": 27011,
"text": "Output :"
},
{
"code": null,
"e": 28597,
"s": 27020,
"text": "{'pricebandupper': 309.15, 'symbol': 'WIPRO', 'applicableMargin': 19.23, 'bcEndDate': '13-JUL-20', 'totalSellQuantity': None, 'adhocMargin': None, 'companyName': 'Wipro Limited', 'marketType': 'N', 'exDate': '08-JUL-20', 'bcStartDate': '10-JUL-20', 'css_status_desc': 'Listed', 'dayHigh': 284.45, 'basePrice': 281.05, 'securityVar': 15.73, 'pricebandlower': 252.95, 'sellQuantity5': None, 'sellQuantity4': None, 'sellQuantity3': None, 'cm_adj_high_dt': '31-JUL-20', 'sellQuantity2': None, 'dayLow': 277.4, 'sellQuantity1': None, 'quantityTraded': 7345555.0, 'pChange': '-1.05', 'totalTradedValue': 20596.94, 'deliveryToTradedQuantity': 21.36, 'totalBuyQuantity': 610.0, 'averagePrice': 280.4, 'indexVar': None, 'cm_ffm': 41333.68, 'purpose': 'ANNUAL GENERAL MEETING', 'buyPrice2': None, 'secDate': '05-Aug-2020 00:00:00', 'buyPrice1': 278.2, 'high52': 290.8, 'previousClose': 281.05, 'ndEndDate': None, 'low52': 159.4, 'buyPrice4': None, 'buyPrice3': None, 'recordDate': None, 'deliveryQuantity': 1569237.0, 'buyPrice5': None, 'priceBand': 'No Band', 'extremeLossMargin': 3.5, 'cm_adj_low_dt': '19-MAR-20', 'varMargin': 15.73, 'sellPrice1': None, 'sellPrice2': None, 'totalTradedVolume': 7345555.0, 'sellPrice3': None, 'sellPrice4': None, 'sellPrice5': None, 'change': '-2.95', 'surv_indicator': None, 'ndStartDate': None, 'buyQuantity4': None, 'isExDateFlag': False, 'buyQuantity3': None, 'buyQuantity2': None, 'buyQuantity1': 610.0, 'series': 'EQ', 'faceValue': 2.0, 'buyQuantity5': None, 'closePrice': 278.2, 'open': 281.25, 'isinCode': 'INE075A01022', 'lastPrice': 278.1}\n"
},
{
"code": null,
"e": 28613,
"s": 28597,
"text": "Another example"
},
{
"code": "# importing nse from nse toolsfrom nsetools import Nse # creating a Nse objectnse = Nse() # nse stock code for hdfccode = \"hdfcbank\" # getting stock quote quote = nse.get_quote(code) # printing quoteprint(quote)",
"e": 28829,
"s": 28613,
"text": null
},
{
"code": null,
"e": 28838,
"s": 28829,
"text": "Output :"
},
{
"code": null,
"e": 30482,
"s": 28838,
"text": "{'pricebandupper': 1145.8, 'symbol': 'HDFCBANK', 'applicableMargin': 18.2, 'bcEndDate': None, 'totalSellQuantity': None, 'adhocMargin': None, 'companyName': 'HDFC Bank Limited', 'marketType': 'N', 'exDate': '19-SEP-19', 'bcStartDate': None, 'css_status_desc': 'Listed', 'dayHigh': 1055.8, 'basePrice': 1041.65, 'securityVar': 14.7, 'pricebandlower': 937.5, 'sellQuantity5': None, 'sellQuantity4': None, 'sellQuantity3': None, 'cm_adj_high_dt': '19-DEC-19', 'sellQuantity2': None, 'dayLow': 1020.0, 'sellQuantity1': None, 'quantityTraded': 16610696.0, 'pChange': '-1.03', 'totalTradedValue': 172025.35, 'deliveryToTradedQuantity': 26.31, 'totalBuyQuantity': 7009.0, 'averagePrice': 1035.63, 'indexVar': None, 'cm_ffm': 445360.08, 'purpose': 'FACE VALUE SPLIT (SUB-DIVISION) - FROM RS 2 PER SHARE TO RS 1 PER SHARE', 'buyPrice2': None, 'secDate': '05-Aug-2020 00:00:00', 'buyPrice1': 1027.55, 'high52': 1305.5, 'previousClose': 1041.65, 'ndEndDate': None, 'low52': 738.75, 'buyPrice4': None, 'buyPrice3': None, 'recordDate': '20-SEP-19', 'deliveryQuantity': 4369897.0, 'buyPrice5': None, 'priceBand': 'No Band', 'extremeLossMargin': 3.5, 'cm_adj_low_dt': '24-MAR-20', 'varMargin': 14.7, 'sellPrice1': None, 'sellPrice2': None, 'totalTradedVolume': 16610696.0, 'sellPrice3': None, 'sellPrice4': None, 'sellPrice5': None, 'change': '-10.70', 'surv_indicator': None, 'ndStartDate': None, 'buyQuantity4': None, 'isExDateFlag': False, 'buyQuantity3': None, 'buyQuantity2': None, 'buyQuantity1': 7009.0, 'series': 'EQ', 'faceValue': 1.0, 'buyQuantity5': None, 'closePrice': 1027.55, 'open': 1047.95, 'isinCode': 'INE040A01034', 'lastPrice': 1030.95}\n\n"
},
{
"code": null,
"e": 30506,
"s": 30482,
"text": "Python NseTools-library"
},
{
"code": null,
"e": 30513,
"s": 30506,
"text": "Python"
},
{
"code": null,
"e": 30611,
"s": 30513,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30629,
"s": 30611,
"text": "Python Dictionary"
},
{
"code": null,
"e": 30661,
"s": 30629,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30683,
"s": 30661,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 30725,
"s": 30683,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 30751,
"s": 30725,
"text": "Python String | replace()"
},
{
"code": null,
"e": 30795,
"s": 30751,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 30824,
"s": 30795,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 30860,
"s": 30824,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 30902,
"s": 30860,
"text": "Check if element exists in list in Python"
}
] |
HTML content modification using Javascript - GeeksforGeeks
|
23 Apr, 2019
JavaScript is the dynamic, lightweight and most commonly computer programming language used to create a web pages. It interact with client side and make dynamic pages.
JavaScript Can Change Content of HTML page: The getElementById() method is used to get the id of element and change the HTML content.
Example:
<!DOCTYPE html><html> <head> <title> Change HTML Content using Javascript </title></head> <body> <h1> GeeksforGeeks </h1> <h2> Change HTML Content using Javascript </h2> <p id="GFG"> GeeksforGeeks: A computer science portal </p> <button type="button" onclick= 'document.getElementById("GFG").innerHTML ="Welcome to GeeksforGeeks"'> Click Here! </button></body> </html>
Output:
Before Clicking the button:
After Clicking the button:
JavaScript Can Change Styles of HTML page: JavaScript can be used to change the CSS property of HTML page.
Example:
<!DOCTYPE html><html> <head> <title> Change HTML Content using Javascript </title></head> <body> <h1> GeeksforGeeks </h1> <h2> Change HTML Content using Javascript </h2> <p id="GFG"> GeeksforGeeks: A computer science portal </p> <button type="button" onclick= "document.getElementById('GFG').style.fontSize= '25px'"> Click Here! </button></body> </html>
Output:
Before Clicking the button:
After Clicking the button:
JavaScript Can Hide or Show HTML Elements: JavaScript can be used to change the display property to hide or show element content.
Example:
<!DOCTYPE html><html> <head> <title> Change HTML Content using Javascript </title></head> <body> <h1> GeeksforGeeks </h1> <h2> Change HTML Content using Javascript </h2> <p id="GFG"> GeeksforGeeks: A computer science portal </p> <button type="button" onclick= "document.getElementById('GFG').style.display= 'none'"> Click Here! </button></body> </html>
Output before clicking:
Output after clicking:
HTML-Misc
JavaScript-Misc
Picked
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Difference Between PUT and PATCH Request
JavaScript | console.log() with Examples
How to read a local text file using JavaScript?
How to Use the JavaScript Fetch API to Get Data?
|
[
{
"code": null,
"e": 26435,
"s": 26407,
"text": "\n23 Apr, 2019"
},
{
"code": null,
"e": 26603,
"s": 26435,
"text": "JavaScript is the dynamic, lightweight and most commonly computer programming language used to create a web pages. It interact with client side and make dynamic pages."
},
{
"code": null,
"e": 26737,
"s": 26603,
"text": "JavaScript Can Change Content of HTML page: The getElementById() method is used to get the id of element and change the HTML content."
},
{
"code": null,
"e": 26746,
"s": 26737,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> Change HTML Content using Javascript </title></head> <body> <h1> GeeksforGeeks </h1> <h2> Change HTML Content using Javascript </h2> <p id=\"GFG\"> GeeksforGeeks: A computer science portal </p> <button type=\"button\" onclick= 'document.getElementById(\"GFG\").innerHTML =\"Welcome to GeeksforGeeks\"'> Click Here! </button></body> </html>",
"e": 27224,
"s": 26746,
"text": null
},
{
"code": null,
"e": 27232,
"s": 27224,
"text": "Output:"
},
{
"code": null,
"e": 27260,
"s": 27232,
"text": "Before Clicking the button:"
},
{
"code": null,
"e": 27287,
"s": 27260,
"text": "After Clicking the button:"
},
{
"code": null,
"e": 27394,
"s": 27287,
"text": "JavaScript Can Change Styles of HTML page: JavaScript can be used to change the CSS property of HTML page."
},
{
"code": null,
"e": 27403,
"s": 27394,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> Change HTML Content using Javascript </title></head> <body> <h1> GeeksforGeeks </h1> <h2> Change HTML Content using Javascript </h2> <p id=\"GFG\"> GeeksforGeeks: A computer science portal </p> <button type=\"button\" onclick= \"document.getElementById('GFG').style.fontSize= '25px'\"> Click Here! </button></body> </html>",
"e": 27865,
"s": 27403,
"text": null
},
{
"code": null,
"e": 27873,
"s": 27865,
"text": "Output:"
},
{
"code": null,
"e": 27901,
"s": 27873,
"text": "Before Clicking the button:"
},
{
"code": null,
"e": 27928,
"s": 27901,
"text": "After Clicking the button:"
},
{
"code": null,
"e": 28058,
"s": 27928,
"text": "JavaScript Can Hide or Show HTML Elements: JavaScript can be used to change the display property to hide or show element content."
},
{
"code": null,
"e": 28067,
"s": 28058,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> Change HTML Content using Javascript </title></head> <body> <h1> GeeksforGeeks </h1> <h2> Change HTML Content using Javascript </h2> <p id=\"GFG\"> GeeksforGeeks: A computer science portal </p> <button type=\"button\" onclick= \"document.getElementById('GFG').style.display= 'none'\"> Click Here! </button></body> </html>",
"e": 28528,
"s": 28067,
"text": null
},
{
"code": null,
"e": 28552,
"s": 28528,
"text": "Output before clicking:"
},
{
"code": null,
"e": 28575,
"s": 28552,
"text": "Output after clicking:"
},
{
"code": null,
"e": 28585,
"s": 28575,
"text": "HTML-Misc"
},
{
"code": null,
"e": 28601,
"s": 28585,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 28608,
"s": 28601,
"text": "Picked"
},
{
"code": null,
"e": 28619,
"s": 28608,
"text": "JavaScript"
},
{
"code": null,
"e": 28717,
"s": 28619,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28757,
"s": 28717,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28802,
"s": 28757,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28863,
"s": 28802,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28935,
"s": 28863,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 28987,
"s": 28935,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 29033,
"s": 28987,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 29074,
"s": 29033,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 29115,
"s": 29074,
"text": "JavaScript | console.log() with Examples"
},
{
"code": null,
"e": 29163,
"s": 29115,
"text": "How to read a local text file using JavaScript?"
}
] |
Making SOAP API calls using Python - GeeksforGeeks
|
18 Jul, 2021
SOAP stands for Simple Object Access Protocol, as the name suggests nothing but a protocol for exchanging structured data between nodes. It uses XML instead of JSON.
In this article, we are going to see how to make SOAP API calls using python. If you want to test out what exactly the payload and response would look like, you can use the below curl command:
CURL Output
First, we import requests library, then we define the SOAP URL.
The next and the most important step is to format the XML body according to the structure provided in the SOAP URL. To know the format, simply visit the SOAP URL and click on CountryISOCode link and format the XML accordingly.
Then you simply prepare the headers and make the POST call.
Code:
Python3
import requests# SOAP request URLurl = "http://webservices.oorsprong.org/websamples.countryinfo/CountryInfoService.wso" # structured XMLpayload = """<?xml version=\"1.0\" encoding=\"utf-8\"?> <soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"> <soap:Body> <CountryIntPhoneCode xmlns=\"http://www.oorsprong.org/websamples.countryinfo\"> <sCountryISOCode>IN</sCountryISOCode> </CountryIntPhoneCode> </soap:Body> </soap:Envelope>"""# headersheaders = { 'Content-Type': 'text/xml; charset=utf-8'}# POST requestresponse = requests.request("POST", url, headers=headers, data=payload) # prints the responseprint(response.text)print(response)
Output:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<m:CountryIntPhoneCodeResponse xmlns:m="http://www.oorsprong.org/websamples.countryinfo">
<m:CountryIntPhoneCodeResult>91</m:CountryIntPhoneCodeResult>
</m:CountryIntPhoneCodeResponse>
</soap:Body>
</soap:Envelope>
<Response [200]>
Now that we have seen how to make SOAP calls with requests, we are going to see how easy it is to make it through Zeep. First, you need to install zeep.
pip3 install zeep
Approach:
First, set the WSDL URL. You can get the WSDL URL simply by visiting the base URL and click on Service Description. That will take you to the WSDL URL. The base URL will be service_url and append the service name after the base URL.
Next, you need to create a header element. Now, you need to set the header element with method_url and service_url.
Now, initialize a zeep client with the WSDL URL.
All the setup is done, now you just need to call the zeep service with the service name, here the service name is CountryIntPhoneCode. You need to pass the parameters with the country_code and also pass the header to _soapheaders as a list.
Now, this would directly return the phone code of the country.
Code:
Python3
import zeep # set the WSDL URLwsdl_url = "http://webservices.oorsprong.org/websamples.countryinfo/CountryInfoService.wso?WSDL" # set method URLmethod_url = "http://webservices.oorsprong.org/websamples.countryinfo/CountryIntPhoneCode" # set service URLservice_url = "http://webservices.oorsprong.org/websamples.countryinfo/CountryInfoService.wso" # create the header elementheader = zeep.xsd.Element( "Header", zeep.xsd.ComplexType( [ zeep.xsd.Element( "{http://www.w3.org/2005/08/addressing}Action", zeep.xsd.String() ), zeep.xsd.Element( "{http://www.w3.org/2005/08/addressing}To", zeep.xsd.String() ), ] ),)# set the header value from header elementheader_value = header(Action=method_url, To=service_url) # initialize zeep clientclient = zeep.Client(wsdl=wsdl_url) # set country code for Indiacountry_code = "IN" # make the service callresult = client.service.CountryIntPhoneCode( sCountryISOCode=country_code, _soapheaders=[header_value])# print the resultprint(f"Phone Code for {country_code} is {result}") # set country code for United Statescountry_code = "US" # make the service callresult = client.service.CountryIntPhoneCode( sCountryISOCode=country_code, _soapheaders=[header_value]) # print the resultprint(f"Phone Code for {country_code} is {result}")print(response)
Output:
Phone Code for IN is 91
Phone Code for US is 1
<Response [200]>
Python-requests
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n18 Jul, 2021"
},
{
"code": null,
"e": 25703,
"s": 25537,
"text": "SOAP stands for Simple Object Access Protocol, as the name suggests nothing but a protocol for exchanging structured data between nodes. It uses XML instead of JSON."
},
{
"code": null,
"e": 25896,
"s": 25703,
"text": "In this article, we are going to see how to make SOAP API calls using python. If you want to test out what exactly the payload and response would look like, you can use the below curl command:"
},
{
"code": null,
"e": 25908,
"s": 25896,
"text": "CURL Output"
},
{
"code": null,
"e": 25973,
"s": 25908,
"text": "First, we import requests library, then we define the SOAP URL. "
},
{
"code": null,
"e": 26200,
"s": 25973,
"text": "The next and the most important step is to format the XML body according to the structure provided in the SOAP URL. To know the format, simply visit the SOAP URL and click on CountryISOCode link and format the XML accordingly."
},
{
"code": null,
"e": 26260,
"s": 26200,
"text": "Then you simply prepare the headers and make the POST call."
},
{
"code": null,
"e": 26266,
"s": 26260,
"text": "Code:"
},
{
"code": null,
"e": 26274,
"s": 26266,
"text": "Python3"
},
{
"code": "import requests# SOAP request URLurl = \"http://webservices.oorsprong.org/websamples.countryinfo/CountryInfoService.wso\" # structured XMLpayload = \"\"\"<?xml version=\\\"1.0\\\" encoding=\\\"utf-8\\\"?> <soap:Envelope xmlns:soap=\\\"http://schemas.xmlsoap.org/soap/envelope/\\\"> <soap:Body> <CountryIntPhoneCode xmlns=\\\"http://www.oorsprong.org/websamples.countryinfo\\\"> <sCountryISOCode>IN</sCountryISOCode> </CountryIntPhoneCode> </soap:Body> </soap:Envelope>\"\"\"# headersheaders = { 'Content-Type': 'text/xml; charset=utf-8'}# POST requestresponse = requests.request(\"POST\", url, headers=headers, data=payload) # prints the responseprint(response.text)print(response)",
"e": 27048,
"s": 26274,
"text": null
},
{
"code": null,
"e": 27056,
"s": 27048,
"text": "Output:"
},
{
"code": null,
"e": 27428,
"s": 27056,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n <soap:Body>\n <m:CountryIntPhoneCodeResponse xmlns:m=\"http://www.oorsprong.org/websamples.countryinfo\">\n <m:CountryIntPhoneCodeResult>91</m:CountryIntPhoneCodeResult>\n </m:CountryIntPhoneCodeResponse>\n </soap:Body>\n</soap:Envelope>\n<Response [200]>"
},
{
"code": null,
"e": 27581,
"s": 27428,
"text": "Now that we have seen how to make SOAP calls with requests, we are going to see how easy it is to make it through Zeep. First, you need to install zeep."
},
{
"code": null,
"e": 27599,
"s": 27581,
"text": "pip3 install zeep"
},
{
"code": null,
"e": 27609,
"s": 27599,
"text": "Approach:"
},
{
"code": null,
"e": 27842,
"s": 27609,
"text": "First, set the WSDL URL. You can get the WSDL URL simply by visiting the base URL and click on Service Description. That will take you to the WSDL URL. The base URL will be service_url and append the service name after the base URL."
},
{
"code": null,
"e": 27958,
"s": 27842,
"text": "Next, you need to create a header element. Now, you need to set the header element with method_url and service_url."
},
{
"code": null,
"e": 28007,
"s": 27958,
"text": "Now, initialize a zeep client with the WSDL URL."
},
{
"code": null,
"e": 28248,
"s": 28007,
"text": "All the setup is done, now you just need to call the zeep service with the service name, here the service name is CountryIntPhoneCode. You need to pass the parameters with the country_code and also pass the header to _soapheaders as a list."
},
{
"code": null,
"e": 28311,
"s": 28248,
"text": "Now, this would directly return the phone code of the country."
},
{
"code": null,
"e": 28317,
"s": 28311,
"text": "Code:"
},
{
"code": null,
"e": 28325,
"s": 28317,
"text": "Python3"
},
{
"code": "import zeep # set the WSDL URLwsdl_url = \"http://webservices.oorsprong.org/websamples.countryinfo/CountryInfoService.wso?WSDL\" # set method URLmethod_url = \"http://webservices.oorsprong.org/websamples.countryinfo/CountryIntPhoneCode\" # set service URLservice_url = \"http://webservices.oorsprong.org/websamples.countryinfo/CountryInfoService.wso\" # create the header elementheader = zeep.xsd.Element( \"Header\", zeep.xsd.ComplexType( [ zeep.xsd.Element( \"{http://www.w3.org/2005/08/addressing}Action\", zeep.xsd.String() ), zeep.xsd.Element( \"{http://www.w3.org/2005/08/addressing}To\", zeep.xsd.String() ), ] ),)# set the header value from header elementheader_value = header(Action=method_url, To=service_url) # initialize zeep clientclient = zeep.Client(wsdl=wsdl_url) # set country code for Indiacountry_code = \"IN\" # make the service callresult = client.service.CountryIntPhoneCode( sCountryISOCode=country_code, _soapheaders=[header_value])# print the resultprint(f\"Phone Code for {country_code} is {result}\") # set country code for United Statescountry_code = \"US\" # make the service callresult = client.service.CountryIntPhoneCode( sCountryISOCode=country_code, _soapheaders=[header_value]) # print the resultprint(f\"Phone Code for {country_code} is {result}\")print(response)",
"e": 29724,
"s": 28325,
"text": null
},
{
"code": null,
"e": 29732,
"s": 29724,
"text": "Output:"
},
{
"code": null,
"e": 29796,
"s": 29732,
"text": "Phone Code for IN is 91\nPhone Code for US is 1\n<Response [200]>"
},
{
"code": null,
"e": 29812,
"s": 29796,
"text": "Python-requests"
},
{
"code": null,
"e": 29827,
"s": 29812,
"text": "python-utility"
},
{
"code": null,
"e": 29834,
"s": 29827,
"text": "Python"
},
{
"code": null,
"e": 29932,
"s": 29834,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29964,
"s": 29932,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30006,
"s": 29964,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 30048,
"s": 30006,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 30104,
"s": 30048,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 30131,
"s": 30104,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 30170,
"s": 30131,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 30201,
"s": 30170,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 30230,
"s": 30201,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 30252,
"s": 30230,
"text": "Defaultdict in Python"
}
] |
ALTER SCHEMA in SQL Server - GeeksforGeeks
|
04 Sep, 2020
The ALTER SCHEMA statement used to transfer a object from a schema to another schema in the same database.
Syntax :
ALTER SCHEMA target_schema_name
TRANSFER [ object_type :: ] object_name;
Parameters :
target_schema_name is the schema in the database, into which the object will be moved.
object_type represents the type of the object for which the owner schema will be changed.
object_name is the name of the object that will be moved to the target_schema_name.
Note : SYS or INFORMATION_SCHEMA cannot be altered.
Example :Let us create table named geektab in the dbo schema :
CREATE TABLE dbo.geektab
(id INT PRIMARY KEY IDENTITY,
name NVARCHAR(40) NOT NULL,
address NVARCHAR(255) NOT NULL);
Now, insert some rows into the dbo.geektab table :
INSERT INTO dbo.geektab (id, name, address)
VALUES (1, 'Neha', 'B-Wing, Delhi'), (2, 'Vineet', 'D-Wing, Noida');
Lets us create a stored procedure that finds id :
CREATE PROCEDURE sp_get_id(@id INT
) AS
BEGIN
SELECT *
FROM dbo.geektab
WHERE id = @id;
END;
Let us move this dbo.geektab table to the geek schema :
ALTER SCHEMA geek TRANSFER OBJECT::dbo.geektabs;
Run the sp_get_id stored procedure :
EXEC sp_get_id;
SQL Server will throw an error similar to mentioned below :
strong>Msg 208, Level 16, State 1, Procedure sp_get_id, Line 3
Invalid object name 'dbo.geektab'
Now, let us manually alter the stored procedure to reflect the geek schema :
ALTER PROCEDURE sp_get_id( @id INT
) AS
BEGIN SELECT *
FROM geek.geektab
WHERE id = @id;
END;
Run the sp_get_id stored procedure :
EXEC sp_get_id 1;
Output –
DBMS-SQL
SQL-Server
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Deadlock in DBMS
Types of Functional dependencies in DBMS
KDD Process in Data Mining
Conflict Serializability in DBMS
Two Phase Locking Protocol
SQL | DDL, DQL, DML, DCL and TCL Commands
How to find Nth highest salary from a table
SQL | ALTER (RENAME)
How to Update Multiple Columns in Single Update Statement in SQL?
MySQL | Group_CONCAT() Function
|
[
{
"code": null,
"e": 25549,
"s": 25521,
"text": "\n04 Sep, 2020"
},
{
"code": null,
"e": 25656,
"s": 25549,
"text": "The ALTER SCHEMA statement used to transfer a object from a schema to another schema in the same database."
},
{
"code": null,
"e": 25665,
"s": 25656,
"text": "Syntax :"
},
{
"code": null,
"e": 25746,
"s": 25665,
"text": "ALTER SCHEMA target_schema_name \n TRANSFER [ object_type :: ] object_name;\n"
},
{
"code": null,
"e": 25759,
"s": 25746,
"text": "Parameters :"
},
{
"code": null,
"e": 25846,
"s": 25759,
"text": "target_schema_name is the schema in the database, into which the object will be moved."
},
{
"code": null,
"e": 25936,
"s": 25846,
"text": "object_type represents the type of the object for which the owner schema will be changed."
},
{
"code": null,
"e": 26020,
"s": 25936,
"text": "object_name is the name of the object that will be moved to the target_schema_name."
},
{
"code": null,
"e": 26072,
"s": 26020,
"text": "Note : SYS or INFORMATION_SCHEMA cannot be altered."
},
{
"code": null,
"e": 26135,
"s": 26072,
"text": "Example :Let us create table named geektab in the dbo schema :"
},
{
"code": null,
"e": 26252,
"s": 26135,
"text": "CREATE TABLE dbo.geektab\n(id INT PRIMARY KEY IDENTITY,\nname NVARCHAR(40) NOT NULL,\naddress NVARCHAR(255) NOT NULL);\n"
},
{
"code": null,
"e": 26303,
"s": 26252,
"text": "Now, insert some rows into the dbo.geektab table :"
},
{
"code": null,
"e": 26347,
"s": 26303,
"text": "INSERT INTO dbo.geektab (id, name, address)"
},
{
"code": null,
"e": 26417,
"s": 26347,
"text": "VALUES (1, 'Neha', 'B-Wing, Delhi'), (2, 'Vineet', 'D-Wing, Noida');\n"
},
{
"code": null,
"e": 26467,
"s": 26417,
"text": "Lets us create a stored procedure that finds id :"
},
{
"code": null,
"e": 26561,
"s": 26467,
"text": "CREATE PROCEDURE sp_get_id(@id INT\n) AS\nBEGIN\nSELECT *\nFROM dbo.geektab\nWHERE id = @id;\nEND;\n"
},
{
"code": null,
"e": 26617,
"s": 26561,
"text": "Let us move this dbo.geektab table to the geek schema :"
},
{
"code": null,
"e": 26666,
"s": 26617,
"text": "ALTER SCHEMA geek TRANSFER OBJECT::dbo.geektabs;"
},
{
"code": null,
"e": 26703,
"s": 26666,
"text": "Run the sp_get_id stored procedure :"
},
{
"code": null,
"e": 26719,
"s": 26703,
"text": "EXEC sp_get_id;"
},
{
"code": null,
"e": 26779,
"s": 26719,
"text": "SQL Server will throw an error similar to mentioned below :"
},
{
"code": null,
"e": 26877,
"s": 26779,
"text": "strong>Msg 208, Level 16, State 1, Procedure sp_get_id, Line 3\nInvalid object name 'dbo.geektab'\n"
},
{
"code": null,
"e": 26954,
"s": 26877,
"text": "Now, let us manually alter the stored procedure to reflect the geek schema :"
},
{
"code": null,
"e": 27049,
"s": 26954,
"text": "ALTER PROCEDURE sp_get_id( @id INT\n) AS\nBEGIN SELECT *\nFROM geek.geektab\nWHERE id = @id;\nEND;\n"
},
{
"code": null,
"e": 27086,
"s": 27049,
"text": "Run the sp_get_id stored procedure :"
},
{
"code": null,
"e": 27105,
"s": 27086,
"text": "EXEC sp_get_id 1; "
},
{
"code": null,
"e": 27114,
"s": 27105,
"text": "Output –"
},
{
"code": null,
"e": 27123,
"s": 27114,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 27134,
"s": 27123,
"text": "SQL-Server"
},
{
"code": null,
"e": 27139,
"s": 27134,
"text": "DBMS"
},
{
"code": null,
"e": 27143,
"s": 27139,
"text": "SQL"
},
{
"code": null,
"e": 27148,
"s": 27143,
"text": "DBMS"
},
{
"code": null,
"e": 27152,
"s": 27148,
"text": "SQL"
},
{
"code": null,
"e": 27250,
"s": 27152,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27267,
"s": 27250,
"text": "Deadlock in DBMS"
},
{
"code": null,
"e": 27308,
"s": 27267,
"text": "Types of Functional dependencies in DBMS"
},
{
"code": null,
"e": 27335,
"s": 27308,
"text": "KDD Process in Data Mining"
},
{
"code": null,
"e": 27368,
"s": 27335,
"text": "Conflict Serializability in DBMS"
},
{
"code": null,
"e": 27395,
"s": 27368,
"text": "Two Phase Locking Protocol"
},
{
"code": null,
"e": 27437,
"s": 27395,
"text": "SQL | DDL, DQL, DML, DCL and TCL Commands"
},
{
"code": null,
"e": 27481,
"s": 27437,
"text": "How to find Nth highest salary from a table"
},
{
"code": null,
"e": 27502,
"s": 27481,
"text": "SQL | ALTER (RENAME)"
},
{
"code": null,
"e": 27568,
"s": 27502,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
}
] |
Find if array has an element whose value is half of array sum - GeeksforGeeks
|
23 Jul, 2021
Given a sorted array (with unique entries), we have to find whether there exist an element(say X) which is exactly half the sum of all the elements of the array including X.
Examples:
Input : A = {1, 2, 3}
Output : YES
Sum of all the elements is 6 = 3*2;
Input : A = {2, 4}
Output : NO
Sum of all the elements is 6, and 3 is not present in the array.
1. Calculate the sum of all the elements of the array. 2. There can be two cases ....a. Sum is Odd, implies we cannot find such X, since all entries are integer. ....b. Sum is Even, if half the value of sum exist in array then answer is YES else NO. 3. We can use Binary Search to find if sum/2 exist in array or not (Since it does not have duplicate entries)
Below is the implementation of above approach:
C++
Java
Python3
C#
PHP
Javascript
// CPP program to check if array has an// element whose value is half of array// sum.#include <bits/stdc++.h>using namespace std; // Function to check if answer existsbool checkForElement(int array[], int n){ // Sum of all array elements int sum = 0; for (int i = 0; i < n; i++) sum += array[i]; // If sum is odd if (sum % 2) return false; sum /= 2; // If sum is Even // Do binary search for the required element int start = 0; int end = n - 1; while (start <= end) { int mid = start + (end - start) / 2; if (array[mid] == sum) return true; else if (array[mid] > sum) end = mid - 1; else start = mid + 1; } return false;} // Driver codeint main(){ int array[] = { 1, 2, 3 }; int n = sizeof(array) / sizeof(array[0]); if (checkForElement(array, n)) cout << "Yes"; else cout << "No"; return 0;}
// Java program to check if array has an// element whose value is half of array// sum. import java.io.*; class GFG { // Function to check if answer existsstatic boolean checkForElement(int array[], int n){ // Sum of all array elements int sum = 0; for (int i = 0; i < n; i++) sum += array[i]; // If sum is odd if (sum % 2>0) return false; sum /= 2; // If sum is Even // Do binary search for the required element int start = 0; int end = n - 1; while (start <= end) { int mid = start + (end - start) / 2; if (array[mid] == sum) return true; else if (array[mid] > sum) end = mid - 1; else start = mid + 1; } return false;} // Driver code public static void main (String[] args) { int array[] = { 1, 2, 3 }; int n = array.length; if (checkForElement(array, n)) System.out.println( "Yes"); else System.out.println( "No"); }}// This code is contributed by anuj_67..
# Python 3 program to check if array# has an element whose value is half# of array sum. # Function to check if answer existsdef checkForElement(array, n): # Sum of all array elements sum = 0 for i in range(n): sum += array[i] # If sum is odd if (sum % 2): return False sum //= 2 # If sum is Even # Do binary search for the # required element start = 0 end = n - 1 while (start <= end) : mid = start + (end - start) // 2 if (array[mid] == sum): return True elif (array[mid] > sum) : end = mid - 1; else: start = mid + 1 return False # Driver codeif __name__ == "__main__": array = [ 1, 2, 3 ] n = len(array) if (checkForElement(array, n)): print("Yes") else: print("No") # This code is contributed# by ChitraNayal
// C# program to check if array has// an element whose value is half// of array sum.using System; class GFG{// Function to check if answer existsstatic bool checkForElement(int[] array, int n){ // Sum of all array elements int sum = 0; for (int i = 0; i < n; i++) sum += array[i]; // If sum is odd if (sum % 2 > 0) return false; sum /= 2; // If sum is Even // Do binary search for the // required element int start = 0; int end = n - 1; while (start <= end) { int mid = start + (end - start) / 2; if (array[mid] == sum) return true; else if (array[mid] > sum) end = mid - 1; else start = mid + 1; } return false;} // Driver Codestatic void Main(){ int []array = { 1, 2, 3 }; int n = array.Length; if (checkForElement(array, n)) Console.WriteLine("Yes"); else Console.WriteLine("No");}} // This code is contributed by ANKITRAI1
<?php// PHP program to check if array has an// element whose value is half of array// sum. // Function to check if answer existsfunction checkForElement(&$array, $n){ // Sum of all array elements $sum = 0; for ($i = 0; $i < $n; $i++) $sum += $array[$i]; // If sum is odd if ($sum % 2) return false; $sum /= 2; // If sum is Even // Do binary search for the // required element $start = 0; $end = $n - 1; while ($start <= $end) { $mid = $start + ($end - $start) / 2; if ($array[$mid] == $sum) return true; else if ($array[$mid] > $sum) $end = $mid - 1; else $start = $mid + 1; } return false;} // Driver code$array = array(1, 2, 3 );$n = sizeof($array);if (checkForElement($array, $n)) echo "Yes";else echo "No"; // This code is contributed// by Shivi_Aggarwal?>
<script>// Javascript program to check if array has an// element whose value is half of array// sum. // Function to check if answer existsfunction checkForElement(array, n){ // Sum of all array elements let sum = 0; for (let i = 0; i < n; i++) sum += array[i]; // If sum is odd if (sum % 2) return false; sum = Math.floor(sum / 2); // If sum is Even // Do binary search for the // required element let start = 0; let end = n - 1; while (start <= end) { let mid = Math.floor(start + (end - start) / 2); if (array[mid] == sum) return true; else if (array[mid] > sum) end = mid - 1; else start = mid + 1; } return false;} // Driver codelet array = new Array(1, 2, 3 );let n = array.length;if (checkForElement(array, n)) document.write("Yes");else document.write("No"); // This code is contributed by _saurabh_jaiswal</script>
Yes
Time Complexity: O(n) Auxiliary Space: O(1)
Another efficient solution that works for unsorted arrays also The idea is to use hashing.
C++
Java
Python3
C#
Javascript
// CPP program to check if array has an// element whose value is half of array// sum.#include <bits/stdc++.h>using namespace std; // Function to check if answer existsbool checkForElement(int array[], int n){ // Sum of all array elements // and storing in a hash table unordered_set<int> s; int sum = 0; for (int i = 0; i < n; i++) { sum += array[i]; s.insert(array[i]); } // If sum/2 is present in hash table if (sum % 2 == 0 && s.find(sum/2) != s.end()) return true; else return false;} // Driver codeint main(){ int array[] = { 1, 2, 3 }; int n = sizeof(array) / sizeof(array[0]); if (checkForElement(array, n)) cout << "Yes"; else cout << "No"; return 0;}
// Java program to check if array has an// element whose value is half of array// sum. import java.util.*; class GFG { // Function to check if answer exists static boolean checkForElement(int array[], int n) { // Sum of all array elements // and storing in a hash table Set<Integer> s = new LinkedHashSet<>(); int sum = 0; for (int i = 0; i < n; i++) { sum += array[i]; s.add(array[i]); } // If sum/2 is present in hash table if (sum % 2 == 0 && s.contains(sum / 2) && (sum / 2 )== s.stream().skip(s.size() - 1).findFirst().get()) { return true; } else { return false; } } // Driver code public static void main(String[] args) { int array[] = {1, 2, 3}; int n = array.length; System.out.println(checkForElement(array, n) ? "Yes" : "No"); }}// This code is contributed by 29AjayKumar
# Python 3 program to check if array has an# element whose value is half of array# sum. # Function to check if answer existsdef checkForElement(array, n): # Sum of all array elements # and storing in a hash table s = set() sum = 0 for i in range(n): sum += array[i] s.add(array[i]) # If sum/2 is present in hash table f = int(sum / 2) if (sum % 2 == 0 and f in s): return True else: return False # Driver codeif __name__ == '__main__': array = [1, 2, 3] n = len(array) if (checkForElement(array, n)): print("Yes") else: print("No") # This code is contributed by# Surendra_Gangwar
// C# program to check if array has an// element whose value is half of array// sum.using System;using System.Collections.Generic; class GFG{ // Function to check if answer exists static Boolean checkForElement(int []array, int n) { // Sum of all array elements // and storing in a hash table HashSet<int> s = new HashSet<int>(); int sum = 0; for (int i = 0; i < n; i++) { sum += array[i]; s.Add(array[i]); } // If sum/2 is present in hash table if (sum % 2 == 0 && s.Contains(sum / 2)) { return true; } else { return false; } } // Driver code public static void Main(String[] args) { int []array = {1, 2, 3}; int n = array.Length; Console.WriteLine(checkForElement(array, n) ? "Yes" : "No"); }} // This code is contributed by Princi Singh
<script> // Javascript program to check if array has an// element whose value is half of array// sum. // Function to check if answer existsfunction checkForElement(array, n){ // Sum of all array elements // and storing in a hash table let s = new Set(); let sum = 0; for(let i = 0; i < n; i++) { sum += array[i]; s.add(array[i]); } // If sum/2 is present in hash table if (sum % 2 == 0 && s.has(sum / 2)) { return true; } else { return false; }} // Driver codelet array = [ 1, 2, 3 ];let n = array.length; document.write( checkForElement(array, n) ? "Yes" : "No"); // This code is contributed by rag2127 </script>
Yes
Time Complexity : O(n) Auxiliary Space : O(n)
vt_m
ankthon
ukasp
Shivi_Aggarwal
29AjayKumar
SURENDRA_GANGWAR
princi singh
_saurabh_jaiswal
rag2127
Binary Search
cpp-unordered_set
Arrays
Hash
Arrays
Hash
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Linked List vs Array
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Internal Working of HashMap in Java
Count pairs with given sum
Hashing | Set 1 (Introduction)
Hashing | Set 3 (Open Addressing)
|
[
{
"code": null,
"e": 26444,
"s": 26416,
"text": "\n23 Jul, 2021"
},
{
"code": null,
"e": 26618,
"s": 26444,
"text": "Given a sorted array (with unique entries), we have to find whether there exist an element(say X) which is exactly half the sum of all the elements of the array including X."
},
{
"code": null,
"e": 26630,
"s": 26618,
"text": "Examples: "
},
{
"code": null,
"e": 26798,
"s": 26630,
"text": "Input : A = {1, 2, 3}\nOutput : YES\nSum of all the elements is 6 = 3*2;\n\nInput : A = {2, 4}\nOutput : NO\nSum of all the elements is 6, and 3 is not present in the array."
},
{
"code": null,
"e": 27158,
"s": 26798,
"text": "1. Calculate the sum of all the elements of the array. 2. There can be two cases ....a. Sum is Odd, implies we cannot find such X, since all entries are integer. ....b. Sum is Even, if half the value of sum exist in array then answer is YES else NO. 3. We can use Binary Search to find if sum/2 exist in array or not (Since it does not have duplicate entries)"
},
{
"code": null,
"e": 27207,
"s": 27158,
"text": "Below is the implementation of above approach: "
},
{
"code": null,
"e": 27211,
"s": 27207,
"text": "C++"
},
{
"code": null,
"e": 27216,
"s": 27211,
"text": "Java"
},
{
"code": null,
"e": 27224,
"s": 27216,
"text": "Python3"
},
{
"code": null,
"e": 27227,
"s": 27224,
"text": "C#"
},
{
"code": null,
"e": 27231,
"s": 27227,
"text": "PHP"
},
{
"code": null,
"e": 27242,
"s": 27231,
"text": "Javascript"
},
{
"code": "// CPP program to check if array has an// element whose value is half of array// sum.#include <bits/stdc++.h>using namespace std; // Function to check if answer existsbool checkForElement(int array[], int n){ // Sum of all array elements int sum = 0; for (int i = 0; i < n; i++) sum += array[i]; // If sum is odd if (sum % 2) return false; sum /= 2; // If sum is Even // Do binary search for the required element int start = 0; int end = n - 1; while (start <= end) { int mid = start + (end - start) / 2; if (array[mid] == sum) return true; else if (array[mid] > sum) end = mid - 1; else start = mid + 1; } return false;} // Driver codeint main(){ int array[] = { 1, 2, 3 }; int n = sizeof(array) / sizeof(array[0]); if (checkForElement(array, n)) cout << \"Yes\"; else cout << \"No\"; return 0;}",
"e": 28191,
"s": 27242,
"text": null
},
{
"code": "// Java program to check if array has an// element whose value is half of array// sum. import java.io.*; class GFG { // Function to check if answer existsstatic boolean checkForElement(int array[], int n){ // Sum of all array elements int sum = 0; for (int i = 0; i < n; i++) sum += array[i]; // If sum is odd if (sum % 2>0) return false; sum /= 2; // If sum is Even // Do binary search for the required element int start = 0; int end = n - 1; while (start <= end) { int mid = start + (end - start) / 2; if (array[mid] == sum) return true; else if (array[mid] > sum) end = mid - 1; else start = mid + 1; } return false;} // Driver code public static void main (String[] args) { int array[] = { 1, 2, 3 }; int n = array.length; if (checkForElement(array, n)) System.out.println( \"Yes\"); else System.out.println( \"No\"); }}// This code is contributed by anuj_67..",
"e": 29199,
"s": 28191,
"text": null
},
{
"code": "# Python 3 program to check if array# has an element whose value is half# of array sum. # Function to check if answer existsdef checkForElement(array, n): # Sum of all array elements sum = 0 for i in range(n): sum += array[i] # If sum is odd if (sum % 2): return False sum //= 2 # If sum is Even # Do binary search for the # required element start = 0 end = n - 1 while (start <= end) : mid = start + (end - start) // 2 if (array[mid] == sum): return True elif (array[mid] > sum) : end = mid - 1; else: start = mid + 1 return False # Driver codeif __name__ == \"__main__\": array = [ 1, 2, 3 ] n = len(array) if (checkForElement(array, n)): print(\"Yes\") else: print(\"No\") # This code is contributed# by ChitraNayal",
"e": 30069,
"s": 29199,
"text": null
},
{
"code": "// C# program to check if array has// an element whose value is half// of array sum.using System; class GFG{// Function to check if answer existsstatic bool checkForElement(int[] array, int n){ // Sum of all array elements int sum = 0; for (int i = 0; i < n; i++) sum += array[i]; // If sum is odd if (sum % 2 > 0) return false; sum /= 2; // If sum is Even // Do binary search for the // required element int start = 0; int end = n - 1; while (start <= end) { int mid = start + (end - start) / 2; if (array[mid] == sum) return true; else if (array[mid] > sum) end = mid - 1; else start = mid + 1; } return false;} // Driver Codestatic void Main(){ int []array = { 1, 2, 3 }; int n = array.Length; if (checkForElement(array, n)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\");}} // This code is contributed by ANKITRAI1",
"e": 31074,
"s": 30069,
"text": null
},
{
"code": "<?php// PHP program to check if array has an// element whose value is half of array// sum. // Function to check if answer existsfunction checkForElement(&$array, $n){ // Sum of all array elements $sum = 0; for ($i = 0; $i < $n; $i++) $sum += $array[$i]; // If sum is odd if ($sum % 2) return false; $sum /= 2; // If sum is Even // Do binary search for the // required element $start = 0; $end = $n - 1; while ($start <= $end) { $mid = $start + ($end - $start) / 2; if ($array[$mid] == $sum) return true; else if ($array[$mid] > $sum) $end = $mid - 1; else $start = $mid + 1; } return false;} // Driver code$array = array(1, 2, 3 );$n = sizeof($array);if (checkForElement($array, $n)) echo \"Yes\";else echo \"No\"; // This code is contributed// by Shivi_Aggarwal?>",
"e": 31970,
"s": 31074,
"text": null
},
{
"code": "<script>// Javascript program to check if array has an// element whose value is half of array// sum. // Function to check if answer existsfunction checkForElement(array, n){ // Sum of all array elements let sum = 0; for (let i = 0; i < n; i++) sum += array[i]; // If sum is odd if (sum % 2) return false; sum = Math.floor(sum / 2); // If sum is Even // Do binary search for the // required element let start = 0; let end = n - 1; while (start <= end) { let mid = Math.floor(start + (end - start) / 2); if (array[mid] == sum) return true; else if (array[mid] > sum) end = mid - 1; else start = mid + 1; } return false;} // Driver codelet array = new Array(1, 2, 3 );let n = array.length;if (checkForElement(array, n)) document.write(\"Yes\");else document.write(\"No\"); // This code is contributed by _saurabh_jaiswal</script>",
"e": 32929,
"s": 31970,
"text": null
},
{
"code": null,
"e": 32933,
"s": 32929,
"text": "Yes"
},
{
"code": null,
"e": 32979,
"s": 32935,
"text": "Time Complexity: O(n) Auxiliary Space: O(1)"
},
{
"code": null,
"e": 33072,
"s": 32979,
"text": "Another efficient solution that works for unsorted arrays also The idea is to use hashing. "
},
{
"code": null,
"e": 33076,
"s": 33072,
"text": "C++"
},
{
"code": null,
"e": 33081,
"s": 33076,
"text": "Java"
},
{
"code": null,
"e": 33089,
"s": 33081,
"text": "Python3"
},
{
"code": null,
"e": 33092,
"s": 33089,
"text": "C#"
},
{
"code": null,
"e": 33103,
"s": 33092,
"text": "Javascript"
},
{
"code": "// CPP program to check if array has an// element whose value is half of array// sum.#include <bits/stdc++.h>using namespace std; // Function to check if answer existsbool checkForElement(int array[], int n){ // Sum of all array elements // and storing in a hash table unordered_set<int> s; int sum = 0; for (int i = 0; i < n; i++) { sum += array[i]; s.insert(array[i]); } // If sum/2 is present in hash table if (sum % 2 == 0 && s.find(sum/2) != s.end()) return true; else return false;} // Driver codeint main(){ int array[] = { 1, 2, 3 }; int n = sizeof(array) / sizeof(array[0]); if (checkForElement(array, n)) cout << \"Yes\"; else cout << \"No\"; return 0;}",
"e": 33846,
"s": 33103,
"text": null
},
{
"code": "// Java program to check if array has an// element whose value is half of array// sum. import java.util.*; class GFG { // Function to check if answer exists static boolean checkForElement(int array[], int n) { // Sum of all array elements // and storing in a hash table Set<Integer> s = new LinkedHashSet<>(); int sum = 0; for (int i = 0; i < n; i++) { sum += array[i]; s.add(array[i]); } // If sum/2 is present in hash table if (sum % 2 == 0 && s.contains(sum / 2) && (sum / 2 )== s.stream().skip(s.size() - 1).findFirst().get()) { return true; } else { return false; } } // Driver code public static void main(String[] args) { int array[] = {1, 2, 3}; int n = array.length; System.out.println(checkForElement(array, n) ? \"Yes\" : \"No\"); }}// This code is contributed by 29AjayKumar",
"e": 34791,
"s": 33846,
"text": null
},
{
"code": "# Python 3 program to check if array has an# element whose value is half of array# sum. # Function to check if answer existsdef checkForElement(array, n): # Sum of all array elements # and storing in a hash table s = set() sum = 0 for i in range(n): sum += array[i] s.add(array[i]) # If sum/2 is present in hash table f = int(sum / 2) if (sum % 2 == 0 and f in s): return True else: return False # Driver codeif __name__ == '__main__': array = [1, 2, 3] n = len(array) if (checkForElement(array, n)): print(\"Yes\") else: print(\"No\") # This code is contributed by# Surendra_Gangwar",
"e": 35454,
"s": 34791,
"text": null
},
{
"code": "// C# program to check if array has an// element whose value is half of array// sum.using System;using System.Collections.Generic; class GFG{ // Function to check if answer exists static Boolean checkForElement(int []array, int n) { // Sum of all array elements // and storing in a hash table HashSet<int> s = new HashSet<int>(); int sum = 0; for (int i = 0; i < n; i++) { sum += array[i]; s.Add(array[i]); } // If sum/2 is present in hash table if (sum % 2 == 0 && s.Contains(sum / 2)) { return true; } else { return false; } } // Driver code public static void Main(String[] args) { int []array = {1, 2, 3}; int n = array.Length; Console.WriteLine(checkForElement(array, n) ? \"Yes\" : \"No\"); }} // This code is contributed by Princi Singh",
"e": 36392,
"s": 35454,
"text": null
},
{
"code": "<script> // Javascript program to check if array has an// element whose value is half of array// sum. // Function to check if answer existsfunction checkForElement(array, n){ // Sum of all array elements // and storing in a hash table let s = new Set(); let sum = 0; for(let i = 0; i < n; i++) { sum += array[i]; s.add(array[i]); } // If sum/2 is present in hash table if (sum % 2 == 0 && s.has(sum / 2)) { return true; } else { return false; }} // Driver codelet array = [ 1, 2, 3 ];let n = array.length; document.write( checkForElement(array, n) ? \"Yes\" : \"No\"); // This code is contributed by rag2127 </script>",
"e": 37095,
"s": 36392,
"text": null
},
{
"code": null,
"e": 37099,
"s": 37095,
"text": "Yes"
},
{
"code": null,
"e": 37148,
"s": 37101,
"text": "Time Complexity : O(n) Auxiliary Space : O(n) "
},
{
"code": null,
"e": 37153,
"s": 37148,
"text": "vt_m"
},
{
"code": null,
"e": 37161,
"s": 37153,
"text": "ankthon"
},
{
"code": null,
"e": 37167,
"s": 37161,
"text": "ukasp"
},
{
"code": null,
"e": 37182,
"s": 37167,
"text": "Shivi_Aggarwal"
},
{
"code": null,
"e": 37194,
"s": 37182,
"text": "29AjayKumar"
},
{
"code": null,
"e": 37211,
"s": 37194,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 37224,
"s": 37211,
"text": "princi singh"
},
{
"code": null,
"e": 37241,
"s": 37224,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 37249,
"s": 37241,
"text": "rag2127"
},
{
"code": null,
"e": 37263,
"s": 37249,
"text": "Binary Search"
},
{
"code": null,
"e": 37281,
"s": 37263,
"text": "cpp-unordered_set"
},
{
"code": null,
"e": 37288,
"s": 37281,
"text": "Arrays"
},
{
"code": null,
"e": 37293,
"s": 37288,
"text": "Hash"
},
{
"code": null,
"e": 37300,
"s": 37293,
"text": "Arrays"
},
{
"code": null,
"e": 37305,
"s": 37300,
"text": "Hash"
},
{
"code": null,
"e": 37319,
"s": 37305,
"text": "Binary Search"
},
{
"code": null,
"e": 37417,
"s": 37319,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37440,
"s": 37417,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 37472,
"s": 37440,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 37486,
"s": 37472,
"text": "Linear Search"
},
{
"code": null,
"e": 37507,
"s": 37486,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 37592,
"s": 37507,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 37677,
"s": 37592,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 37713,
"s": 37677,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 37740,
"s": 37713,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 37771,
"s": 37740,
"text": "Hashing | Set 1 (Introduction)"
}
] |
C++ Mathematical Functions - GeeksforGeeks
|
25 Nov, 2021
C++ being superset of C, supports large number of useful mathematical functions. These functions are available in standard C++ and C to support various mathematical calculations. Instead of focusing on implementation, these functions can be directly used to simplify code and programs. C++ provides large set of mathematical functions which are stated below – In order to use these functions you need to include header file- <math.h> or <cmath>.
double sin(double) : This function takes angle (in degree) as an argument and return its sine value that could be verified using sine curve.double cos(double) : This function takes angle (in degree) as an argument and return its cosine value that could be verified using cosine curve.double tan(double) : This function takes angle (in degree) as an argument and return its tangent value. This could also be verified using Trigonometry as Tan(x) = Sin(x)/Cos(x).double sqrt(double) : This function takes number as an argument and return its square root value. Number can not be negative value.int abs(int) : This function takes integer number as an argument and return its absolute value. It means, the output will always be positive regardless of sign of input.double pow(double, double) : This function takes one argument as base and other as exponent.double hypot(double, double) : This function requires two sides of the right angled triangle to give output as its hypotenuse.double floor(double) : This functions returns the integer value lesser or equal to argument passed in the function.double fabs(double) : This function returns the absolute value of any number.double acos(double) : This function returns the arc cosine of argument. The argument to acos() must be in the range -1 to 1 ; otherwise, a domain error occurs.double asin(double) : This function returns the arc sine of argument. The argument to asin() must be in the range -1 to 1 ; otherwise, a domain error occurs.double atan(double) : This function returns the arc tangent of arg.double atan2(double, double) : This function returns the arc tangent of (double a)/(double b).double ceil(double) : This function returns the smallest integer as double not less than the argument provided.double cosh(double) : This function returns the hyperbolic cosine of argument provided. The value of argument provided must be in radians.double tanh(double) : This function returns the hyperbolic tangent of argument provided. The value of argument provided must be in radians.double log(double) : This function takes a number and returns the natural log of that number.
double sin(double) : This function takes angle (in degree) as an argument and return its sine value that could be verified using sine curve.
double cos(double) : This function takes angle (in degree) as an argument and return its cosine value that could be verified using cosine curve.
double tan(double) : This function takes angle (in degree) as an argument and return its tangent value. This could also be verified using Trigonometry as Tan(x) = Sin(x)/Cos(x).
double sqrt(double) : This function takes number as an argument and return its square root value. Number can not be negative value.
int abs(int) : This function takes integer number as an argument and return its absolute value. It means, the output will always be positive regardless of sign of input.
double pow(double, double) : This function takes one argument as base and other as exponent.
double hypot(double, double) : This function requires two sides of the right angled triangle to give output as its hypotenuse.
double floor(double) : This functions returns the integer value lesser or equal to argument passed in the function.
double fabs(double) : This function returns the absolute value of any number.
double acos(double) : This function returns the arc cosine of argument. The argument to acos() must be in the range -1 to 1 ; otherwise, a domain error occurs.
double asin(double) : This function returns the arc sine of argument. The argument to asin() must be in the range -1 to 1 ; otherwise, a domain error occurs.
double atan(double) : This function returns the arc tangent of arg.
double atan2(double, double) : This function returns the arc tangent of (double a)/(double b).
double ceil(double) : This function returns the smallest integer as double not less than the argument provided.
double cosh(double) : This function returns the hyperbolic cosine of argument provided. The value of argument provided must be in radians.
double tanh(double) : This function returns the hyperbolic tangent of argument provided. The value of argument provided must be in radians.
double log(double) : This function takes a number and returns the natural log of that number.
CPP
// C++ program to illustrate some of the// above mentioned functions #include <iostream>#include <math.h>using namespace std; int main(){ double x = 2.3; cout << "Sine value of x=2.3 : " << sin(x) << endl; cout << "Cosine value of x=2.3 : " << cos(x) << endl; cout << "Tangent value of x=2.3 : " << tan(x) << endl; double y = 0.25; cout << "Square root value of y=0.25 : " << sqrt(y) << endl; int z = -10; cout << "Absolute value of z=-10 : " << abs(z) << endl; cout << "Power value: x^y = (2.3^0.25) : " << pow(x, y) << endl; x = 3.0; y = 4.0; cout << "Hypotenuse having other two sides as x=3.0 and" << " y=4.0 : " << hypot(x, y) << endl; x = 4.56; cout << "Floor value of x=4.56 is : " << floor(x) << endl; x = -4.57; cout << "Absolute value of x=-4.57 is : " << fabs(x) << endl; x = 1.0; cout << "Arc Cosine value of x=1.0 : " << acos(x) << endl; cout << "Arc Sine value of x=1.0 : " << asin(x) << endl; cout << "Arc Tangent value of x=1.0 : " << atan(x) << endl; y = 12.3; cout << "Ceiling value of y=12.3 : " << ceil(y) << endl; x = 57.3; // in degrees cout << "Hyperbolic Cosine of x=57.3 : " << cosh(x) << endl; cout << "Hyperbolic tangent of x=57.3 : " << tanh(x) << endl; y = 100.0; // Natural base with 'e' cout << "Log value of y=100.0 is : " << log(y) << endl; return 0;}
Sine value of x=2.3 : 0.745705
Cosine value of x=2.3 : -0.666276
Tangent value of x=2.3 : -1.11921
Square root value of y=0.25 : 0.5
Absolute value of z=-10 : 10
Power value: x^y = (2.3^0.25) : 1.23149
Hypotenuse having other two sides as x=3.0 and y=4.0 : 5
Floor value of x=4.56 is : 4
Absolute value of x=-4.57 is : 4.57
Arc Cosine value of x=1.0 : 0
Arc Sine value of x=1.0 : 1.5708
Arc Tangent value of x=1.0 : 0.785398
Ceiling value of y=12.3 : 13
Hyperbolic Cosine of x=57.3 : 3.83746e+24
Hyperbolic tangent of x=57.3 : 1
Log value of y=100.0 is : 4.60517
rkbhola5
CPP-Functions
cpp-math
C++
C++ Programs
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
std::string class in C++
Header files in C/C++ and its uses
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
C++ Program for QuickSort
Sorting a Map by value in C++ STL
|
[
{
"code": null,
"e": 25368,
"s": 25340,
"text": "\n25 Nov, 2021"
},
{
"code": null,
"e": 25816,
"s": 25368,
"text": "C++ being superset of C, supports large number of useful mathematical functions. These functions are available in standard C++ and C to support various mathematical calculations. Instead of focusing on implementation, these functions can be directly used to simplify code and programs. C++ provides large set of mathematical functions which are stated below – In order to use these functions you need to include header file- <math.h> or <cmath>. "
},
{
"code": null,
"e": 27946,
"s": 25816,
"text": "double sin(double) : This function takes angle (in degree) as an argument and return its sine value that could be verified using sine curve.double cos(double) : This function takes angle (in degree) as an argument and return its cosine value that could be verified using cosine curve.double tan(double) : This function takes angle (in degree) as an argument and return its tangent value. This could also be verified using Trigonometry as Tan(x) = Sin(x)/Cos(x).double sqrt(double) : This function takes number as an argument and return its square root value. Number can not be negative value.int abs(int) : This function takes integer number as an argument and return its absolute value. It means, the output will always be positive regardless of sign of input.double pow(double, double) : This function takes one argument as base and other as exponent.double hypot(double, double) : This function requires two sides of the right angled triangle to give output as its hypotenuse.double floor(double) : This functions returns the integer value lesser or equal to argument passed in the function.double fabs(double) : This function returns the absolute value of any number.double acos(double) : This function returns the arc cosine of argument. The argument to acos() must be in the range -1 to 1 ; otherwise, a domain error occurs.double asin(double) : This function returns the arc sine of argument. The argument to asin() must be in the range -1 to 1 ; otherwise, a domain error occurs.double atan(double) : This function returns the arc tangent of arg.double atan2(double, double) : This function returns the arc tangent of (double a)/(double b).double ceil(double) : This function returns the smallest integer as double not less than the argument provided.double cosh(double) : This function returns the hyperbolic cosine of argument provided. The value of argument provided must be in radians.double tanh(double) : This function returns the hyperbolic tangent of argument provided. The value of argument provided must be in radians.double log(double) : This function takes a number and returns the natural log of that number."
},
{
"code": null,
"e": 28087,
"s": 27946,
"text": "double sin(double) : This function takes angle (in degree) as an argument and return its sine value that could be verified using sine curve."
},
{
"code": null,
"e": 28232,
"s": 28087,
"text": "double cos(double) : This function takes angle (in degree) as an argument and return its cosine value that could be verified using cosine curve."
},
{
"code": null,
"e": 28410,
"s": 28232,
"text": "double tan(double) : This function takes angle (in degree) as an argument and return its tangent value. This could also be verified using Trigonometry as Tan(x) = Sin(x)/Cos(x)."
},
{
"code": null,
"e": 28542,
"s": 28410,
"text": "double sqrt(double) : This function takes number as an argument and return its square root value. Number can not be negative value."
},
{
"code": null,
"e": 28712,
"s": 28542,
"text": "int abs(int) : This function takes integer number as an argument and return its absolute value. It means, the output will always be positive regardless of sign of input."
},
{
"code": null,
"e": 28805,
"s": 28712,
"text": "double pow(double, double) : This function takes one argument as base and other as exponent."
},
{
"code": null,
"e": 28932,
"s": 28805,
"text": "double hypot(double, double) : This function requires two sides of the right angled triangle to give output as its hypotenuse."
},
{
"code": null,
"e": 29048,
"s": 28932,
"text": "double floor(double) : This functions returns the integer value lesser or equal to argument passed in the function."
},
{
"code": null,
"e": 29126,
"s": 29048,
"text": "double fabs(double) : This function returns the absolute value of any number."
},
{
"code": null,
"e": 29286,
"s": 29126,
"text": "double acos(double) : This function returns the arc cosine of argument. The argument to acos() must be in the range -1 to 1 ; otherwise, a domain error occurs."
},
{
"code": null,
"e": 29444,
"s": 29286,
"text": "double asin(double) : This function returns the arc sine of argument. The argument to asin() must be in the range -1 to 1 ; otherwise, a domain error occurs."
},
{
"code": null,
"e": 29512,
"s": 29444,
"text": "double atan(double) : This function returns the arc tangent of arg."
},
{
"code": null,
"e": 29607,
"s": 29512,
"text": "double atan2(double, double) : This function returns the arc tangent of (double a)/(double b)."
},
{
"code": null,
"e": 29719,
"s": 29607,
"text": "double ceil(double) : This function returns the smallest integer as double not less than the argument provided."
},
{
"code": null,
"e": 29858,
"s": 29719,
"text": "double cosh(double) : This function returns the hyperbolic cosine of argument provided. The value of argument provided must be in radians."
},
{
"code": null,
"e": 29998,
"s": 29858,
"text": "double tanh(double) : This function returns the hyperbolic tangent of argument provided. The value of argument provided must be in radians."
},
{
"code": null,
"e": 30092,
"s": 29998,
"text": "double log(double) : This function takes a number and returns the natural log of that number."
},
{
"code": null,
"e": 30098,
"s": 30094,
"text": "CPP"
},
{
"code": "// C++ program to illustrate some of the// above mentioned functions #include <iostream>#include <math.h>using namespace std; int main(){ double x = 2.3; cout << \"Sine value of x=2.3 : \" << sin(x) << endl; cout << \"Cosine value of x=2.3 : \" << cos(x) << endl; cout << \"Tangent value of x=2.3 : \" << tan(x) << endl; double y = 0.25; cout << \"Square root value of y=0.25 : \" << sqrt(y) << endl; int z = -10; cout << \"Absolute value of z=-10 : \" << abs(z) << endl; cout << \"Power value: x^y = (2.3^0.25) : \" << pow(x, y) << endl; x = 3.0; y = 4.0; cout << \"Hypotenuse having other two sides as x=3.0 and\" << \" y=4.0 : \" << hypot(x, y) << endl; x = 4.56; cout << \"Floor value of x=4.56 is : \" << floor(x) << endl; x = -4.57; cout << \"Absolute value of x=-4.57 is : \" << fabs(x) << endl; x = 1.0; cout << \"Arc Cosine value of x=1.0 : \" << acos(x) << endl; cout << \"Arc Sine value of x=1.0 : \" << asin(x) << endl; cout << \"Arc Tangent value of x=1.0 : \" << atan(x) << endl; y = 12.3; cout << \"Ceiling value of y=12.3 : \" << ceil(y) << endl; x = 57.3; // in degrees cout << \"Hyperbolic Cosine of x=57.3 : \" << cosh(x) << endl; cout << \"Hyperbolic tangent of x=57.3 : \" << tanh(x) << endl; y = 100.0; // Natural base with 'e' cout << \"Log value of y=100.0 is : \" << log(y) << endl; return 0;}",
"e": 31488,
"s": 30098,
"text": null
},
{
"code": null,
"e": 32051,
"s": 31488,
"text": "Sine value of x=2.3 : 0.745705\nCosine value of x=2.3 : -0.666276\nTangent value of x=2.3 : -1.11921\nSquare root value of y=0.25 : 0.5\nAbsolute value of z=-10 : 10\nPower value: x^y = (2.3^0.25) : 1.23149\nHypotenuse having other two sides as x=3.0 and y=4.0 : 5\nFloor value of x=4.56 is : 4\nAbsolute value of x=-4.57 is : 4.57\nArc Cosine value of x=1.0 : 0\nArc Sine value of x=1.0 : 1.5708\nArc Tangent value of x=1.0 : 0.785398\nCeiling value of y=12.3 : 13\nHyperbolic Cosine of x=57.3 : 3.83746e+24\nHyperbolic tangent of x=57.3 : 1\nLog value of y=100.0 is : 4.60517"
},
{
"code": null,
"e": 32062,
"s": 32053,
"text": "rkbhola5"
},
{
"code": null,
"e": 32076,
"s": 32062,
"text": "CPP-Functions"
},
{
"code": null,
"e": 32085,
"s": 32076,
"text": "cpp-math"
},
{
"code": null,
"e": 32089,
"s": 32085,
"text": "C++"
},
{
"code": null,
"e": 32102,
"s": 32089,
"text": "C++ Programs"
},
{
"code": null,
"e": 32106,
"s": 32102,
"text": "CPP"
},
{
"code": null,
"e": 32204,
"s": 32106,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32232,
"s": 32204,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 32252,
"s": 32232,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 32285,
"s": 32252,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 32309,
"s": 32285,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 32334,
"s": 32309,
"text": "std::string class in C++"
},
{
"code": null,
"e": 32369,
"s": 32334,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 32413,
"s": 32369,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 32472,
"s": 32413,
"text": "How to return multiple values from a function in C or C++?"
},
{
"code": null,
"e": 32498,
"s": 32472,
"text": "C++ Program for QuickSort"
}
] |
PostgreSQL - RANK Function - GeeksforGeeks
|
10 Feb, 2021
In PostgreSQL, the RANK() function is used to assign a rank to each row of the query result set within the specified partition. The rank of the first row within each partition is 1.
The following illustrates the syntax of the RANK() function:
Syntax:
RANK() OVER (
[PARTITION BY partition_expression, ... ]
ORDER BY sort_expression [ASC | DESC], ...
)
Let’s analyze the above syntax:
First, the PARTITION BY clause creates partition in the query result where the RANK() function is applied.
The ORDER BY clause sets the order in which the query results are displayed.
Example 1:
First, create a table named Rankings that contains one column:
CREATE TABLE Rankings(
g VARCHAR(100)
);
Now add some data to it:
INSERT INTO Rankings(g)
VALUES('Ram'), ('Ravi'), ('Bhola'), ('Bhagat'), ('Bhushan'), ('Chintu'), ('Isha');
Now, use the RANK() function to assign ranks to the rows in the result set of ranks table:
SELECT
g,
RANK () OVER (
ORDER BY g
) rank
FROM
Rankings;
Output:
Example 2:
First, create two tables named Mammals and Animal_groups:
CREATE TABLE Animal_groups (
animal_id serial PRIMARY KEY,
animal_name VARCHAR (255) NOT NULL
);
CREATE TABLE Mammals (
mammal_id serial PRIMARY KEY,
mammal_name VARCHAR (255) NOT NULL,
lifespan DECIMAL (11, 2),
animal_id INT NOT NULL,
FOREIGN KEY (animal_id) REFERENCES Animal_groups (animal_id)
);
Now add some data to it:
INSERT INTO Animal_groups (animal_name)
VALUES
('Terrestrial'),
('Aquatic'),
('Winged');
INSERT INTO Mammals(mammal_name, animal_id, lifespan)
VALUES
('Cow', 1, 10),
('Dog', 1, 7),
('Ox', 1, 13),
('Wolf', 1, 11),
('Blue Whale', 2, 80),
('Dolphin', 2, 5),
('Sea Horse', 2, 3),
('Octopus', 2, 8),
('Bat', 3, 4),
('Flying Squirrels', 3, 1),
('Petaurus', 3, 2);
The below statement uses the RANK() function to assign a rank to each mammals by its lifespan:
SELECT
mammal_id,
mammal_name,
lifespan,
RANK () OVER (
ORDER BY lifespan DESC
) long_life
FROM
Mammals;
Output:
PostgreSQL-function
PostgreSQL-Window-function
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - Create Auto-increment Column using SERIAL
PostgreSQL - CREATE PROCEDURE
PostgreSQL - GROUP BY clause
PostgreSQL - DROP INDEX
PostgreSQL - TIME Data Type
PostgreSQL - REPLACE Function
PostgreSQL - Copy Table
PostgreSQL - CREATE SCHEMA
PostgreSQL - Rename Table
PostgreSQL - Identity Column
|
[
{
"code": null,
"e": 25177,
"s": 25149,
"text": "\n10 Feb, 2021"
},
{
"code": null,
"e": 25359,
"s": 25177,
"text": "In PostgreSQL, the RANK() function is used to assign a rank to each row of the query result set within the specified partition. The rank of the first row within each partition is 1."
},
{
"code": null,
"e": 25420,
"s": 25359,
"text": "The following illustrates the syntax of the RANK() function:"
},
{
"code": null,
"e": 25537,
"s": 25420,
"text": "Syntax:\nRANK() OVER (\n [PARTITION BY partition_expression, ... ]\n ORDER BY sort_expression [ASC | DESC], ...\n)"
},
{
"code": null,
"e": 25569,
"s": 25537,
"text": "Let’s analyze the above syntax:"
},
{
"code": null,
"e": 25676,
"s": 25569,
"text": "First, the PARTITION BY clause creates partition in the query result where the RANK() function is applied."
},
{
"code": null,
"e": 25753,
"s": 25676,
"text": "The ORDER BY clause sets the order in which the query results are displayed."
},
{
"code": null,
"e": 25764,
"s": 25753,
"text": "Example 1:"
},
{
"code": null,
"e": 25827,
"s": 25764,
"text": "First, create a table named Rankings that contains one column:"
},
{
"code": null,
"e": 25872,
"s": 25827,
"text": "CREATE TABLE Rankings(\n g VARCHAR(100)\n);"
},
{
"code": null,
"e": 25897,
"s": 25872,
"text": "Now add some data to it:"
},
{
"code": null,
"e": 26004,
"s": 25897,
"text": "INSERT INTO Rankings(g)\nVALUES('Ram'), ('Ravi'), ('Bhola'), ('Bhagat'), ('Bhushan'), ('Chintu'), ('Isha');"
},
{
"code": null,
"e": 26095,
"s": 26004,
"text": "Now, use the RANK() function to assign ranks to the rows in the result set of ranks table:"
},
{
"code": null,
"e": 26179,
"s": 26095,
"text": "SELECT\n g,\n RANK () OVER ( \n ORDER BY g \n ) rank\nFROM\n Rankings;"
},
{
"code": null,
"e": 26187,
"s": 26179,
"text": "Output:"
},
{
"code": null,
"e": 26198,
"s": 26187,
"text": "Example 2:"
},
{
"code": null,
"e": 26256,
"s": 26198,
"text": "First, create two tables named Mammals and Animal_groups:"
},
{
"code": null,
"e": 26587,
"s": 26256,
"text": "CREATE TABLE Animal_groups (\n animal_id serial PRIMARY KEY,\n animal_name VARCHAR (255) NOT NULL\n);\n\nCREATE TABLE Mammals (\n mammal_id serial PRIMARY KEY,\n mammal_name VARCHAR (255) NOT NULL,\n lifespan DECIMAL (11, 2),\n animal_id INT NOT NULL,\n FOREIGN KEY (animal_id) REFERENCES Animal_groups (animal_id)\n);\n\n"
},
{
"code": null,
"e": 26612,
"s": 26587,
"text": "Now add some data to it:"
},
{
"code": null,
"e": 27027,
"s": 26612,
"text": "INSERT INTO Animal_groups (animal_name)\nVALUES\n ('Terrestrial'),\n ('Aquatic'),\n ('Winged');\n\nINSERT INTO Mammals(mammal_name, animal_id, lifespan)\nVALUES\n ('Cow', 1, 10),\n ('Dog', 1, 7),\n ('Ox', 1, 13),\n ('Wolf', 1, 11),\n ('Blue Whale', 2, 80),\n ('Dolphin', 2, 5),\n ('Sea Horse', 2, 3),\n ('Octopus', 2, 8),\n ('Bat', 3, 4),\n ('Flying Squirrels', 3, 1),\n ('Petaurus', 3, 2);"
},
{
"code": null,
"e": 27122,
"s": 27027,
"text": "The below statement uses the RANK() function to assign a rank to each mammals by its lifespan:"
},
{
"code": null,
"e": 27261,
"s": 27122,
"text": "SELECT\n mammal_id,\n mammal_name,\n lifespan,\n RANK () OVER ( \n ORDER BY lifespan DESC\n ) long_life \nFROM\n Mammals;"
},
{
"code": null,
"e": 27269,
"s": 27261,
"text": "Output:"
},
{
"code": null,
"e": 27289,
"s": 27269,
"text": "PostgreSQL-function"
},
{
"code": null,
"e": 27316,
"s": 27289,
"text": "PostgreSQL-Window-function"
},
{
"code": null,
"e": 27327,
"s": 27316,
"text": "PostgreSQL"
},
{
"code": null,
"e": 27425,
"s": 27327,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27480,
"s": 27425,
"text": "PostgreSQL - Create Auto-increment Column using SERIAL"
},
{
"code": null,
"e": 27510,
"s": 27480,
"text": "PostgreSQL - CREATE PROCEDURE"
},
{
"code": null,
"e": 27539,
"s": 27510,
"text": "PostgreSQL - GROUP BY clause"
},
{
"code": null,
"e": 27563,
"s": 27539,
"text": "PostgreSQL - DROP INDEX"
},
{
"code": null,
"e": 27591,
"s": 27563,
"text": "PostgreSQL - TIME Data Type"
},
{
"code": null,
"e": 27621,
"s": 27591,
"text": "PostgreSQL - REPLACE Function"
},
{
"code": null,
"e": 27645,
"s": 27621,
"text": "PostgreSQL - Copy Table"
},
{
"code": null,
"e": 27672,
"s": 27645,
"text": "PostgreSQL - CREATE SCHEMA"
},
{
"code": null,
"e": 27698,
"s": 27672,
"text": "PostgreSQL - Rename Table"
}
] |
Opening tif file using GDAL in Python - GeeksforGeeks
|
12 Nov, 2020
To open a raster file we need to register drivers. In python, GDALAllRegister() is implicitly called whenever gdal is imported. The tiff file to be opened can be downloaded here.
Importing the modules: Import the gdal and ogr modules from osgeo.
Python3
from osgeo import gdal, ogr
Opening the file: The raster dataset can be opened using gdal.open() by passing the filename and path.
Python3
dataset = gdal.Open(r'land_shallow_topo_2048.tif')
Getting the metadata: We can fetch the metadata of the tif file using the GetMetadata() method.
Python3
print(dataset.GetMetadata())
Output:
{‘TIFFTAG_RESOLUTIONUNIT’: ‘2 (pixels/inch)’, ‘TIFFTAG_XRESOLUTION’: ’72’, ‘TIFFTAG_YRESOLUTION’: ’72’}
Getting other information: We can get the number of bands(represents the RGB channels) using the RasterCount() method, width of the image using RasterXSize() method and the height using RasterYSize() method.
Python3
print(dataset.RasterCount) # width print(dataset.RasterXSize) # heightprint(dataset.RasterYSize)
Output:
3
2048
1024
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 25551,
"s": 25523,
"text": "\n12 Nov, 2020"
},
{
"code": null,
"e": 25730,
"s": 25551,
"text": "To open a raster file we need to register drivers. In python, GDALAllRegister() is implicitly called whenever gdal is imported. The tiff file to be opened can be downloaded here."
},
{
"code": null,
"e": 25797,
"s": 25730,
"text": "Importing the modules: Import the gdal and ogr modules from osgeo."
},
{
"code": null,
"e": 25805,
"s": 25797,
"text": "Python3"
},
{
"code": "from osgeo import gdal, ogr",
"e": 25833,
"s": 25805,
"text": null
},
{
"code": null,
"e": 25937,
"s": 25833,
"text": "Opening the file: The raster dataset can be opened using gdal.open() by passing the filename and path. "
},
{
"code": null,
"e": 25945,
"s": 25937,
"text": "Python3"
},
{
"code": "dataset = gdal.Open(r'land_shallow_topo_2048.tif')",
"e": 25996,
"s": 25945,
"text": null
},
{
"code": null,
"e": 26092,
"s": 25996,
"text": "Getting the metadata: We can fetch the metadata of the tif file using the GetMetadata() method."
},
{
"code": null,
"e": 26100,
"s": 26092,
"text": "Python3"
},
{
"code": "print(dataset.GetMetadata())",
"e": 26129,
"s": 26100,
"text": null
},
{
"code": null,
"e": 26137,
"s": 26129,
"text": "Output:"
},
{
"code": null,
"e": 26241,
"s": 26137,
"text": "{‘TIFFTAG_RESOLUTIONUNIT’: ‘2 (pixels/inch)’, ‘TIFFTAG_XRESOLUTION’: ’72’, ‘TIFFTAG_YRESOLUTION’: ’72’}"
},
{
"code": null,
"e": 26449,
"s": 26241,
"text": "Getting other information: We can get the number of bands(represents the RGB channels) using the RasterCount() method, width of the image using RasterXSize() method and the height using RasterYSize() method."
},
{
"code": null,
"e": 26457,
"s": 26449,
"text": "Python3"
},
{
"code": "print(dataset.RasterCount) # width print(dataset.RasterXSize) # heightprint(dataset.RasterYSize)",
"e": 26556,
"s": 26457,
"text": null
},
{
"code": null,
"e": 26564,
"s": 26556,
"text": "Output:"
},
{
"code": null,
"e": 26577,
"s": 26564,
"text": "3\n2048\n1024\n"
},
{
"code": null,
"e": 26592,
"s": 26577,
"text": "python-modules"
},
{
"code": null,
"e": 26599,
"s": 26592,
"text": "Python"
},
{
"code": null,
"e": 26697,
"s": 26599,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26715,
"s": 26697,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26750,
"s": 26715,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26782,
"s": 26750,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26804,
"s": 26782,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26846,
"s": 26804,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26876,
"s": 26846,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26902,
"s": 26876,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26931,
"s": 26902,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 26975,
"s": 26931,
"text": "Reading and Writing to text files in Python"
}
] |
Function Overloading and Default Arguments in C++ - GeeksQuiz
|
07 Mar, 2018
#include <iostream>
using namespace std;
int fun(int x, int y = 0, int z = 0)
{ return (x + y + z); }
int main()
{
cout << fun(10);
return 0;
}
int fun(int x, int y);
void fun(int x, int y);
int fun(int x, int y);
static int fun(int x, int y);
int fun(int *ptr, int n);
int fun(int ptr[], int n);
int fun( int x, int y);
int fun( int x, int y = 10);
#include
using namespace std;
void square (int *x)
{
*x = (*x)++ * (*x);
}
void square (int *x, int *y)
{
*x = (*x) * --(*y);
}
int main ( )
{
int number = 30;
square(&number, &number);
cout << number;
return 0;
}
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Product Based Companies
C Program For Finding Length Of A Linked List
How to calculate MOVING AVERAGE in a Pandas DataFrame?
How to Convert Categorical Variable to Numeric in Pandas?
How to Replace Values in Column Based on Condition in Pandas?
How to Fix: SyntaxError: positional argument follows keyword argument in Python
How to Fix: KeyError in Pandas
C Program to read contents of Whole File
How to Append Pandas DataFrame to Existing CSV File?
How to Replace Values in a List in Python?
|
[
{
"code": null,
"e": 28855,
"s": 28827,
"text": "\n07 Mar, 2018"
},
{
"code": null,
"e": 29009,
"s": 28855,
"text": "#include <iostream>\nusing namespace std;\n\nint fun(int x, int y = 0, int z = 0)\n{ return (x + y + z); }\n\nint main()\n{\n cout << fun(10);\n return 0;\n}\n"
},
{
"code": null,
"e": 29070,
"s": 29009,
"text": " int fun(int x, int y);\n void fun(int x, int y); "
},
{
"code": null,
"e": 29137,
"s": 29070,
"text": " int fun(int x, int y);\n static int fun(int x, int y); "
},
{
"code": null,
"e": 29191,
"s": 29137,
"text": "int fun(int *ptr, int n);\nint fun(int ptr[], int n); "
},
{
"code": null,
"e": 29246,
"s": 29191,
"text": "int fun( int x, int y); \nint fun( int x, int y = 10); "
},
{
"code": null,
"e": 29461,
"s": 29246,
"text": "#include \nusing namespace std;\nvoid square (int *x)\n{\n*x = (*x)++ * (*x);\n}\nvoid square (int *x, int *y)\n{\n*x = (*x) * --(*y);\n}\nint main ( )\n{\nint number = 30;\nsquare(&number, &number);\ncout << number;\nreturn 0;\n}"
},
{
"code": null,
"e": 29559,
"s": 29461,
"text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here."
},
{
"code": null,
"e": 29612,
"s": 29559,
"text": "Must Do Coding Questions for Product Based Companies"
},
{
"code": null,
"e": 29658,
"s": 29612,
"text": "C Program For Finding Length Of A Linked List"
},
{
"code": null,
"e": 29713,
"s": 29658,
"text": "How to calculate MOVING AVERAGE in a Pandas DataFrame?"
},
{
"code": null,
"e": 29771,
"s": 29713,
"text": "How to Convert Categorical Variable to Numeric in Pandas?"
},
{
"code": null,
"e": 29833,
"s": 29771,
"text": "How to Replace Values in Column Based on Condition in Pandas?"
},
{
"code": null,
"e": 29913,
"s": 29833,
"text": "How to Fix: SyntaxError: positional argument follows keyword argument in Python"
},
{
"code": null,
"e": 29944,
"s": 29913,
"text": "How to Fix: KeyError in Pandas"
},
{
"code": null,
"e": 29985,
"s": 29944,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 30038,
"s": 29985,
"text": "How to Append Pandas DataFrame to Existing CSV File?"
}
] |
Downloading gists from Github made simple - GeeksforGeeks
|
04 Sep, 2017
GithubGist is a place where you can create a private or a public gist i.e store your files either privately or publicly. Let us assume a scenario where you have written a good number of gists for your project and you want to download a set of them. The only way you can do it using GithubGist is to open each and every individual gist to download ZIP or clone via HTTP or SSH.This article is all about making the above task simpler. Using the commands below, you can even download gists from other github users excluding the private ones until you know their password.
We will be using requests package for this propose. It is an awesome package to send HTTP requests with minimal code.
Installation
1. Download the package from PyPI via terminal using pip3Syntax:
pip3 install requests
Note: To become a root user, run the following command:
sudo pip3 install requests
Python3 scriptThe script can not run on an online IDE and therefore you can click here to see how it works.
import requestsimport os def create_directory(dirname): #Creates a new directory if a directory with dirname does not exist try: os.stat(dirname) except: os.mkdir(dirname) def show(obj): #Displays the items in the obj for i in range(len(obj)): print(str(i)+': '+str(obj[i])) def auth(): #Asks for the user details ask_auth = input("Do you want to download gists from your account ? Type 'yes' or 'no': ") if(ask_auth=="yes"): user = input("Enter your username: ") password = input("Enter your password: ") request = requests.get('https://api.github.com/users/'+user+'/gists' , auth=(user, password)) elif(ask_auth=="no"): user = input("Enter username: ") request = requests.get('https://api.github.com/users/' +user+'/gists') return [ask_auth, user, request] def load(request): #Loads the files and the gist urls output = request.text.split(",") gist_urls = [] files = [] for item in output: if "raw_url" in item: gist_urls.append(str(item[11:-1])) if "filename" in item: files.append(str(item.split(":")[1][2:-1])) return [gist_urls, files] def write_gist(filename, text): #Writes text(gist) to filename fp = open(filename, 'w') fp.write(text) fp.close() def download(permission, user, request, fileno): #Loads and writes all the gists to <em>dirname</em> if(permission == "yes" or permission == "no"): gist_urls, files = load(request) dirname = user+"'s_gists/" create_directory(dirname) if(fileno[1] == "all"): for i in range(len(gist_urls)): gist = requests.get(gist_urls[i]) write_gist(dirname+files[i], gist.text) else: for i in range(1,len(fileno)): gist = requests.get(gist_urls[int(fileno[i])]) write_gist(dirname+files[int(fileno[i])], gist.text) def detailed(urls, pos): #Prints out the contents of a file gist = requests.get(urls[int(pos)]) print(gist.text) def main(): #Authenticates and downloads gists according to user's choice #Commands: #show: To show all the available gists with their assigned gistno #download all: To download all the available gists #download gistno(s): To download gist(s) assigned to gistno(s) #detailed gistno: To print content of gist assigned to gistno #exit: To exit the script ask_auth, user, request = auth() urls, files = load(request) try: while(1): command = input("Enter your command: ") if("download" in command): download(ask_auth, user, request, command.split(" ")) elif("detailed" in command): detailed(urls, command.split(" ")[1]) elif(command == "show"): show(files) elif(command == "exit"): return except: pass if(__name__ == '__main__'): main()
ExplanationGithubGist API stores information about each user at http://api.github.com/users/username/gists.
Send a HTTP request to the above url to retrieve information about the user.
Search for the raw_url of every available gist and sent HTTP requests to retrieve the information about them.
Manipulated the information to your needs.
This article is contributed by Sri Sanketh Uppalapati. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
GitHub
GBlog
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
How to Start Learning DSA?
Introduction to Recurrent Neural Network
12 pip Commands For Python Developers
A Freshers Guide To Programming
ML | Underfitting and Overfitting
What is web socket and how it is different from the HTTP?
Virtualization In Cloud Computing and Types
Software Testing | Basics
Top 10 Programming Languages to Learn in 2022
|
[
{
"code": null,
"e": 26299,
"s": 26271,
"text": "\n04 Sep, 2017"
},
{
"code": null,
"e": 26868,
"s": 26299,
"text": "GithubGist is a place where you can create a private or a public gist i.e store your files either privately or publicly. Let us assume a scenario where you have written a good number of gists for your project and you want to download a set of them. The only way you can do it using GithubGist is to open each and every individual gist to download ZIP or clone via HTTP or SSH.This article is all about making the above task simpler. Using the commands below, you can even download gists from other github users excluding the private ones until you know their password."
},
{
"code": null,
"e": 26986,
"s": 26868,
"text": "We will be using requests package for this propose. It is an awesome package to send HTTP requests with minimal code."
},
{
"code": null,
"e": 26999,
"s": 26986,
"text": "Installation"
},
{
"code": null,
"e": 27064,
"s": 26999,
"text": "1. Download the package from PyPI via terminal using pip3Syntax:"
},
{
"code": null,
"e": 27086,
"s": 27064,
"text": "pip3 install requests"
},
{
"code": null,
"e": 27142,
"s": 27086,
"text": "Note: To become a root user, run the following command:"
},
{
"code": null,
"e": 27169,
"s": 27142,
"text": "sudo pip3 install requests"
},
{
"code": null,
"e": 27277,
"s": 27169,
"text": "Python3 scriptThe script can not run on an online IDE and therefore you can click here to see how it works."
},
{
"code": "import requestsimport os def create_directory(dirname): #Creates a new directory if a directory with dirname does not exist try: os.stat(dirname) except: os.mkdir(dirname) def show(obj): #Displays the items in the obj for i in range(len(obj)): print(str(i)+': '+str(obj[i])) def auth(): #Asks for the user details ask_auth = input(\"Do you want to download gists from your account ? Type 'yes' or 'no': \") if(ask_auth==\"yes\"): user = input(\"Enter your username: \") password = input(\"Enter your password: \") request = requests.get('https://api.github.com/users/'+user+'/gists' , auth=(user, password)) elif(ask_auth==\"no\"): user = input(\"Enter username: \") request = requests.get('https://api.github.com/users/' +user+'/gists') return [ask_auth, user, request] def load(request): #Loads the files and the gist urls output = request.text.split(\",\") gist_urls = [] files = [] for item in output: if \"raw_url\" in item: gist_urls.append(str(item[11:-1])) if \"filename\" in item: files.append(str(item.split(\":\")[1][2:-1])) return [gist_urls, files] def write_gist(filename, text): #Writes text(gist) to filename fp = open(filename, 'w') fp.write(text) fp.close() def download(permission, user, request, fileno): #Loads and writes all the gists to <em>dirname</em> if(permission == \"yes\" or permission == \"no\"): gist_urls, files = load(request) dirname = user+\"'s_gists/\" create_directory(dirname) if(fileno[1] == \"all\"): for i in range(len(gist_urls)): gist = requests.get(gist_urls[i]) write_gist(dirname+files[i], gist.text) else: for i in range(1,len(fileno)): gist = requests.get(gist_urls[int(fileno[i])]) write_gist(dirname+files[int(fileno[i])], gist.text) def detailed(urls, pos): #Prints out the contents of a file gist = requests.get(urls[int(pos)]) print(gist.text) def main(): #Authenticates and downloads gists according to user's choice #Commands: #show: To show all the available gists with their assigned gistno #download all: To download all the available gists #download gistno(s): To download gist(s) assigned to gistno(s) #detailed gistno: To print content of gist assigned to gistno #exit: To exit the script ask_auth, user, request = auth() urls, files = load(request) try: while(1): command = input(\"Enter your command: \") if(\"download\" in command): download(ask_auth, user, request, command.split(\" \")) elif(\"detailed\" in command): detailed(urls, command.split(\" \")[1]) elif(command == \"show\"): show(files) elif(command == \"exit\"): return except: pass if(__name__ == '__main__'): main()",
"e": 30373,
"s": 27277,
"text": null
},
{
"code": null,
"e": 30481,
"s": 30373,
"text": "ExplanationGithubGist API stores information about each user at http://api.github.com/users/username/gists."
},
{
"code": null,
"e": 30558,
"s": 30481,
"text": "Send a HTTP request to the above url to retrieve information about the user."
},
{
"code": null,
"e": 30668,
"s": 30558,
"text": "Search for the raw_url of every available gist and sent HTTP requests to retrieve the information about them."
},
{
"code": null,
"e": 30711,
"s": 30668,
"text": "Manipulated the information to your needs."
},
{
"code": null,
"e": 31021,
"s": 30711,
"text": "This article is contributed by Sri Sanketh Uppalapati. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 31146,
"s": 31021,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 31153,
"s": 31146,
"text": "GitHub"
},
{
"code": null,
"e": 31159,
"s": 31153,
"text": "GBlog"
},
{
"code": null,
"e": 31178,
"s": 31159,
"text": "Technical Scripter"
},
{
"code": null,
"e": 31276,
"s": 31178,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31301,
"s": 31276,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 31328,
"s": 31301,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 31369,
"s": 31328,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 31407,
"s": 31369,
"text": "12 pip Commands For Python Developers"
},
{
"code": null,
"e": 31439,
"s": 31407,
"text": "A Freshers Guide To Programming"
},
{
"code": null,
"e": 31473,
"s": 31439,
"text": "ML | Underfitting and Overfitting"
},
{
"code": null,
"e": 31531,
"s": 31473,
"text": "What is web socket and how it is different from the HTTP?"
},
{
"code": null,
"e": 31575,
"s": 31531,
"text": "Virtualization In Cloud Computing and Types"
},
{
"code": null,
"e": 31601,
"s": 31575,
"text": "Software Testing | Basics"
}
] |
Python - Unique values count of each Key - GeeksforGeeks
|
24 Jan, 2021
Given a Dictionaries list, the task is to write a Python program to count the unique values of each key.
Example:
Input : test_list = [{“gfg” : 1, “is” : 3, “best”: 2}, {“gfg” : 1, “is” : 3, “best” : 6},
{“gfg” : 7, “is” : 3, “best” : 10}]
Output : {‘gfg’: 2, ‘is’: 1, ‘best’: 3}
Explanation : gfg has 1 and 7 as unique elements, hence 2.
Input : test_list = [{“gfg” : 1, “is” : 3, “best”: 2}, {“gfg” : 1, “is” : 3, “best” : 6},
{“gfg” : 1, “is” : 3, “best” : 10}]
Output : {‘gfg’: 1, ‘is’: 1, ‘best’: 3}
Explanation : gfg has only 1 as unique element, hence 1.
Method #1 : Using len() + set() + loop
In this, unique values is extracted using set(), len() is used to get its count, and then the result is mapped to each key extracted using keys(). Iterating over keys occur in loop.
Python3
# Python3 code to demonstrate working of# Unique values count of each Key# Using len() + set() # initializing liststest_list = [{"gfg": 1, "is": 3, "best": 2}, { "gfg": 1, "is": 3, "best": 6}, {"gfg": 7, "is": 3, "best": 10}] # printing original listprint("The original list is : " + str(test_list)) res = dict()for key in test_list[0].keys(): # mapping unique values. res[key] = len(set([sub[key] for sub in test_list])) # printing resultprint("Unique count of keys : " + str(res))
Output:
The original list is : [{‘gfg’: 1, ‘is’: 3, ‘best’: 2}, {‘gfg’: 1, ‘is’: 3, ‘best’: 6},
{‘gfg’: 7, ‘is’: 3, ‘best’: 10}]
Unique count of keys : {‘gfg’: 2, ‘is’: 1, ‘best’: 3}
Method #2 : Using dictionary comprehension + len() + set()
Similar to above method, difference being dictionary comprehension is used as one liner alternative for shorthand.
Python3
# Python3 code to demonstrate working of# Unique values count of each Key# Using len() + set() + dictionary comprehension # initializing liststest_list = [{"gfg": 1, "is": 3, "best": 2}, { "gfg": 1, "is": 3, "best": 6}, {"gfg": 7, "is": 3, "best": 10}] # printing original listprint("The original list is : " + str(test_list)) # dictionary comprehension for compact solutionres = {key: len(set([sub[key] for sub in test_list])) for key in test_list[0].keys()} # printing resultprint("Unique count of keys : " + str(res))
Output:
The original list is : [{‘gfg’: 1, ‘is’: 3, ‘best’: 2}, {‘gfg’: 1, ‘is’: 3, ‘best’: 6},
{‘gfg’: 7, ‘is’: 3, ‘best’: 10}]
Unique count of keys : {‘gfg’: 2, ‘is’: 1, ‘best’: 3}
Python dictionary-programs
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n24 Jan, 2021"
},
{
"code": null,
"e": 25642,
"s": 25537,
"text": "Given a Dictionaries list, the task is to write a Python program to count the unique values of each key."
},
{
"code": null,
"e": 25651,
"s": 25642,
"text": "Example:"
},
{
"code": null,
"e": 25742,
"s": 25651,
"text": "Input : test_list = [{“gfg” : 1, “is” : 3, “best”: 2}, {“gfg” : 1, “is” : 3, “best” : 6}, "
},
{
"code": null,
"e": 25778,
"s": 25742,
"text": "{“gfg” : 7, “is” : 3, “best” : 10}]"
},
{
"code": null,
"e": 25818,
"s": 25778,
"text": "Output : {‘gfg’: 2, ‘is’: 1, ‘best’: 3}"
},
{
"code": null,
"e": 25877,
"s": 25818,
"text": "Explanation : gfg has 1 and 7 as unique elements, hence 2."
},
{
"code": null,
"e": 25967,
"s": 25877,
"text": "Input : test_list = [{“gfg” : 1, “is” : 3, “best”: 2}, {“gfg” : 1, “is” : 3, “best” : 6},"
},
{
"code": null,
"e": 26004,
"s": 25967,
"text": " {“gfg” : 1, “is” : 3, “best” : 10}]"
},
{
"code": null,
"e": 26044,
"s": 26004,
"text": "Output : {‘gfg’: 1, ‘is’: 1, ‘best’: 3}"
},
{
"code": null,
"e": 26101,
"s": 26044,
"text": "Explanation : gfg has only 1 as unique element, hence 1."
},
{
"code": null,
"e": 26140,
"s": 26101,
"text": "Method #1 : Using len() + set() + loop"
},
{
"code": null,
"e": 26322,
"s": 26140,
"text": "In this, unique values is extracted using set(), len() is used to get its count, and then the result is mapped to each key extracted using keys(). Iterating over keys occur in loop."
},
{
"code": null,
"e": 26330,
"s": 26322,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Unique values count of each Key# Using len() + set() # initializing liststest_list = [{\"gfg\": 1, \"is\": 3, \"best\": 2}, { \"gfg\": 1, \"is\": 3, \"best\": 6}, {\"gfg\": 7, \"is\": 3, \"best\": 10}] # printing original listprint(\"The original list is : \" + str(test_list)) res = dict()for key in test_list[0].keys(): # mapping unique values. res[key] = len(set([sub[key] for sub in test_list])) # printing resultprint(\"Unique count of keys : \" + str(res))",
"e": 26828,
"s": 26330,
"text": null
},
{
"code": null,
"e": 26836,
"s": 26828,
"text": "Output:"
},
{
"code": null,
"e": 26924,
"s": 26836,
"text": "The original list is : [{‘gfg’: 1, ‘is’: 3, ‘best’: 2}, {‘gfg’: 1, ‘is’: 3, ‘best’: 6},"
},
{
"code": null,
"e": 26958,
"s": 26924,
"text": " {‘gfg’: 7, ‘is’: 3, ‘best’: 10}]"
},
{
"code": null,
"e": 27012,
"s": 26958,
"text": "Unique count of keys : {‘gfg’: 2, ‘is’: 1, ‘best’: 3}"
},
{
"code": null,
"e": 27071,
"s": 27012,
"text": "Method #2 : Using dictionary comprehension + len() + set()"
},
{
"code": null,
"e": 27186,
"s": 27071,
"text": "Similar to above method, difference being dictionary comprehension is used as one liner alternative for shorthand."
},
{
"code": null,
"e": 27194,
"s": 27186,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Unique values count of each Key# Using len() + set() + dictionary comprehension # initializing liststest_list = [{\"gfg\": 1, \"is\": 3, \"best\": 2}, { \"gfg\": 1, \"is\": 3, \"best\": 6}, {\"gfg\": 7, \"is\": 3, \"best\": 10}] # printing original listprint(\"The original list is : \" + str(test_list)) # dictionary comprehension for compact solutionres = {key: len(set([sub[key] for sub in test_list])) for key in test_list[0].keys()} # printing resultprint(\"Unique count of keys : \" + str(res))",
"e": 27728,
"s": 27194,
"text": null
},
{
"code": null,
"e": 27736,
"s": 27728,
"text": "Output:"
},
{
"code": null,
"e": 27824,
"s": 27736,
"text": "The original list is : [{‘gfg’: 1, ‘is’: 3, ‘best’: 2}, {‘gfg’: 1, ‘is’: 3, ‘best’: 6},"
},
{
"code": null,
"e": 27858,
"s": 27824,
"text": " {‘gfg’: 7, ‘is’: 3, ‘best’: 10}]"
},
{
"code": null,
"e": 27912,
"s": 27858,
"text": "Unique count of keys : {‘gfg’: 2, ‘is’: 1, ‘best’: 3}"
},
{
"code": null,
"e": 27939,
"s": 27912,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 27960,
"s": 27939,
"text": "Python list-programs"
},
{
"code": null,
"e": 27967,
"s": 27960,
"text": "Python"
},
{
"code": null,
"e": 27983,
"s": 27967,
"text": "Python Programs"
},
{
"code": null,
"e": 28081,
"s": 27983,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28113,
"s": 28081,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28155,
"s": 28113,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28197,
"s": 28155,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28224,
"s": 28197,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28280,
"s": 28224,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28302,
"s": 28280,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28341,
"s": 28302,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 28387,
"s": 28341,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 28425,
"s": 28387,
"text": "Python | Convert a list to dictionary"
}
] |
Minimum operations to transform given string to another by moving characters to front or end - GeeksforGeeks
|
19 May, 2021
Given two Strings S and T of length N consisting of lowercase alphabets, which are permutations of each other, the task is to print the minimum number of operations to convert S to T. In one operation, pick any character of the string S and move it either to the start or end of the string S.
Examples:
Input: S = “abcde”, T = “edacb”Output: 3Explanation:We can convert S to T in 3 moves:1. move ‘d’ to start: “dabce” 2. move ‘e’ to start: “edabc” 3. move ‘b’ to end: “edacb”
Input: S = “dcdb”, T = “ddbc”Output: 1Explanation:Move ‘c’ to end
Naive Approach: The naive approach is to try all possibilities of swapping a character. One can put some character to the front, to the end, or can leave it in the same position. The above three operations can be solved using recursion and print the minimum number of steps required after all the steps.Time Complexity: O(3N), where N is the length of the given string.Auxiliary Space: O(1)
Efficient Approach: To optimize the above approach, the idea is to observe that after moving the characters of the string S, the unchanged characters come together to form a contiguous substring in T. So, if we can maximize the length of this subsequence, then the count of operations to convert string S to T is:
N – length of the longest contiguous substring of T that is a subsequence of S
Therefore, to find the length of the longest contiguous substring of T that is a subsequence of string S, find the longest common subsequence of S and T. Let dp[][] stores the length of the longest contiguous substring of T that is a subsequence of string S, . Now dp[i][j] will store the length of the longest suffix of T[0, ..., j] that is also a subsequence of S[0, ..., i]. The recurrence relation is given by:
If i is greater than 0, dp[i][j] = max(dp[i-1][j], dp[i][j]).
If S[i] is equals to T[i] then, dp[i][j] = 1 + dp[i-1][j-1].
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; int dp[1010][1010]; // Function that finds the minimum number// of steps to find the minimum characters// must be moved to convert string s to tint solve(string s, string t){ int n = s.size(); // r = maximum value over all // dp[i][j] computed so far int r = 0; // dp[i][j] stores the longest // contiguous suffix of T[0..j] // that is subsequence of S[0..i] for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { dp[i][j] = 0; if (i > 0) { dp[i][j] = max(dp[i - 1][j], dp[i][j]); } if (s[i] == t[j]) { int ans = 1; if (i > 0 && j > 0) { ans = 1 + dp[i - 1][j - 1]; } // Update the maximum length dp[i][j] = max(dp[i][j], ans); r = max(r, dp[i][j]); } } } // Return the resulting length return (n - r);} // Driver Codeint main(){ // Given string s, t string s = "abcde"; string t = "edacb"; // Function Call cout << solve(s, t); return 0;}
// Java program for the above approachclass GFG{ static int[][] dp = new int[1010][1010]; // Function that finds the minimum number // of steps to find the minimum characters // must be moved to convert String s to t static int solve(String s, String t) { int n = s.length(); // r = maximum value over all // dp[i][j] computed so far int r = 0; // dp[i][j] stores the longest // contiguous suffix of T[0..j] // that is subsequence of S[0..i] for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { dp[i][j] = 0; if (i > 0) { dp[i][j] = Math.max(dp[i - 1][j], dp[i][j]); } if (s.charAt(i) == t.charAt(j)) { int ans = 1; if (i > 0 && j > 0) { ans = 1 + dp[i - 1][j - 1]; } // Update the maximum length dp[i][j] = Math.max(dp[i][j], ans); r = Math.max(r, dp[i][j]); } } } // Return the resulting length return (n - r); } // Driver Code public static void main(String[] args) { // Given String s, t String s = "abcde"; String t = "edacb"; // Function Call System.out.print(solve(s, t)); }} // This code is contributed by shikhasingrajput
# Python3 program for the above approachdp = [[0] * 1010] * 1010 # Function that finds the minimum number# of steps to find the minimum characters# must be moved to convert string s to tdef solve(s, t): n = len(s) # r = maximum value over all # dp[i][j] computed so far r = 0 # dp[i][j] stores the longest # contiguous suffix of T[0..j] # that is subsequence of S[0..i] for j in range(0, n): for i in range(0, n): dp[i][j] = 0 if (i > 0): dp[i][j] = max(dp[i - 1][j], dp[i][j]) if (s[i] == t[j]): ans = 1 if (i > 0 and j > 0): ans = 1 + dp[i - 1][j - 1] # Update the maximum length dp[i][j] = max(dp[i][j], ans) r = max(r, dp[i][j]) # Return the resulting length return (n - r) # Driver Code # Given string s, ts = "abcde"t = "edacb" # Function callprint(solve(s, t)) # This code is contributed by code_hunt
// C# program for the above approachusing System;class GFG{static int[, ] dp = new int[1010, 1010]; // Function that finds the minimum number// of steps to find the minimum characters// must be moved to convert String s to tstatic int solve(String s, String t){ int n = s.Length; // r = maximum value over all // dp[i, j] computed so far int r = 0; // dp[i, j] stores the longest // contiguous suffix of T[0..j] // that is subsequence of S[0..i] for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { dp[i, j] = 0; if (i > 0) { dp[i, j] = Math.Max(dp[i - 1, j], dp[i, j]); } if (s[i] == t[j]) { int ans = 1; if (i > 0 && j > 0) { ans = 1 + dp[i - 1, j - 1]; } // Update the maximum length dp[i, j] = Math.Max(dp[i, j], ans); r = Math.Max(r, dp[i, j]); } } } // Return the resulting length return (n - r);} // Driver Codepublic static void Main(String[] args){ // Given String s, t String s = "abcde"; String t = "edacb"; // Function Call Console.Write(solve(s, t));}} // This code is contributed by shikhasingrajput
<script> // Javascript program for the above approach var dp = Array.from(Array(1010), ()=> Array(1010)); // Function that finds the minimum number// of steps to find the minimum characters// must be moved to convert string s to tfunction solve(s, t){ var n = s.length; // r = maximum value over all // dp[i][j] computed so far var r = 0; // dp[i][j] stores the longest // contiguous suffix of T[0..j] // that is subsequence of S[0..i] for (var i = 0; i < n; i++) { for (var j = 0; j < n; j++) { dp[i][j] = 0; if (i > 0) { dp[i][j] = Math.max(dp[i - 1][j], dp[i][j]); } if (s[i] == t[j]) { var ans = 1; if (i > 0 && j > 0) { ans = 1 + dp[i - 1][j - 1]; } // Update the maximum length dp[i][j] = Math.max(dp[i][j], ans); r = Math.max(r, dp[i][j]); } } } // Return the resulting length return (n - r);} // Driver Code// Given string s, tvar s = "abcde";var t = "edacb";// Function Calldocument.write( solve(s, t)); </script>
3
Time Complexity: O(N2), where N is the length of the given stringAuxiliary Space: O(N2)
Note: The above naive approach is efficient for smaller strings whereas, the above efficient approach is efficient for larger strings.
shikhasingrajput
code_hunt
rutvik_56
LCS
substring
Dynamic Programming
Strings
Strings
Dynamic Programming
LCS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
Subset Sum Problem | DP-25
Coin Change | DP-7
Matrix Chain Multiplication | DP-8
Write a program to reverse an array or string
Reverse a string in Java
C++ Data Types
Check for Balanced Brackets in an expression (well-formedness) using Stack
Python program to check if a string is palindrome or not
|
[
{
"code": null,
"e": 26235,
"s": 26207,
"text": "\n19 May, 2021"
},
{
"code": null,
"e": 26528,
"s": 26235,
"text": "Given two Strings S and T of length N consisting of lowercase alphabets, which are permutations of each other, the task is to print the minimum number of operations to convert S to T. In one operation, pick any character of the string S and move it either to the start or end of the string S."
},
{
"code": null,
"e": 26538,
"s": 26528,
"text": "Examples:"
},
{
"code": null,
"e": 26711,
"s": 26538,
"text": "Input: S = “abcde”, T = “edacb”Output: 3Explanation:We can convert S to T in 3 moves:1. move ‘d’ to start: “dabce” 2. move ‘e’ to start: “edabc” 3. move ‘b’ to end: “edacb”"
},
{
"code": null,
"e": 26777,
"s": 26711,
"text": "Input: S = “dcdb”, T = “ddbc”Output: 1Explanation:Move ‘c’ to end"
},
{
"code": null,
"e": 27168,
"s": 26777,
"text": "Naive Approach: The naive approach is to try all possibilities of swapping a character. One can put some character to the front, to the end, or can leave it in the same position. The above three operations can be solved using recursion and print the minimum number of steps required after all the steps.Time Complexity: O(3N), where N is the length of the given string.Auxiliary Space: O(1)"
},
{
"code": null,
"e": 27482,
"s": 27168,
"text": "Efficient Approach: To optimize the above approach, the idea is to observe that after moving the characters of the string S, the unchanged characters come together to form a contiguous substring in T. So, if we can maximize the length of this subsequence, then the count of operations to convert string S to T is:"
},
{
"code": null,
"e": 27561,
"s": 27482,
"text": "N – length of the longest contiguous substring of T that is a subsequence of S"
},
{
"code": null,
"e": 27977,
"s": 27561,
"text": "Therefore, to find the length of the longest contiguous substring of T that is a subsequence of string S, find the longest common subsequence of S and T. Let dp[][] stores the length of the longest contiguous substring of T that is a subsequence of string S, . Now dp[i][j] will store the length of the longest suffix of T[0, ..., j] that is also a subsequence of S[0, ..., i]. The recurrence relation is given by: "
},
{
"code": null,
"e": 28039,
"s": 27977,
"text": "If i is greater than 0, dp[i][j] = max(dp[i-1][j], dp[i][j])."
},
{
"code": null,
"e": 28100,
"s": 28039,
"text": "If S[i] is equals to T[i] then, dp[i][j] = 1 + dp[i-1][j-1]."
},
{
"code": null,
"e": 28151,
"s": 28100,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 28155,
"s": 28151,
"text": "C++"
},
{
"code": null,
"e": 28160,
"s": 28155,
"text": "Java"
},
{
"code": null,
"e": 28168,
"s": 28160,
"text": "Python3"
},
{
"code": null,
"e": 28171,
"s": 28168,
"text": "C#"
},
{
"code": null,
"e": 28182,
"s": 28171,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; int dp[1010][1010]; // Function that finds the minimum number// of steps to find the minimum characters// must be moved to convert string s to tint solve(string s, string t){ int n = s.size(); // r = maximum value over all // dp[i][j] computed so far int r = 0; // dp[i][j] stores the longest // contiguous suffix of T[0..j] // that is subsequence of S[0..i] for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { dp[i][j] = 0; if (i > 0) { dp[i][j] = max(dp[i - 1][j], dp[i][j]); } if (s[i] == t[j]) { int ans = 1; if (i > 0 && j > 0) { ans = 1 + dp[i - 1][j - 1]; } // Update the maximum length dp[i][j] = max(dp[i][j], ans); r = max(r, dp[i][j]); } } } // Return the resulting length return (n - r);} // Driver Codeint main(){ // Given string s, t string s = \"abcde\"; string t = \"edacb\"; // Function Call cout << solve(s, t); return 0;}",
"e": 29394,
"s": 28182,
"text": null
},
{
"code": "// Java program for the above approachclass GFG{ static int[][] dp = new int[1010][1010]; // Function that finds the minimum number // of steps to find the minimum characters // must be moved to convert String s to t static int solve(String s, String t) { int n = s.length(); // r = maximum value over all // dp[i][j] computed so far int r = 0; // dp[i][j] stores the longest // contiguous suffix of T[0..j] // that is subsequence of S[0..i] for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { dp[i][j] = 0; if (i > 0) { dp[i][j] = Math.max(dp[i - 1][j], dp[i][j]); } if (s.charAt(i) == t.charAt(j)) { int ans = 1; if (i > 0 && j > 0) { ans = 1 + dp[i - 1][j - 1]; } // Update the maximum length dp[i][j] = Math.max(dp[i][j], ans); r = Math.max(r, dp[i][j]); } } } // Return the resulting length return (n - r); } // Driver Code public static void main(String[] args) { // Given String s, t String s = \"abcde\"; String t = \"edacb\"; // Function Call System.out.print(solve(s, t)); }} // This code is contributed by shikhasingrajput",
"e": 30943,
"s": 29394,
"text": null
},
{
"code": "# Python3 program for the above approachdp = [[0] * 1010] * 1010 # Function that finds the minimum number# of steps to find the minimum characters# must be moved to convert string s to tdef solve(s, t): n = len(s) # r = maximum value over all # dp[i][j] computed so far r = 0 # dp[i][j] stores the longest # contiguous suffix of T[0..j] # that is subsequence of S[0..i] for j in range(0, n): for i in range(0, n): dp[i][j] = 0 if (i > 0): dp[i][j] = max(dp[i - 1][j], dp[i][j]) if (s[i] == t[j]): ans = 1 if (i > 0 and j > 0): ans = 1 + dp[i - 1][j - 1] # Update the maximum length dp[i][j] = max(dp[i][j], ans) r = max(r, dp[i][j]) # Return the resulting length return (n - r) # Driver Code # Given string s, ts = \"abcde\"t = \"edacb\" # Function callprint(solve(s, t)) # This code is contributed by code_hunt",
"e": 32023,
"s": 30943,
"text": null
},
{
"code": "// C# program for the above approachusing System;class GFG{static int[, ] dp = new int[1010, 1010]; // Function that finds the minimum number// of steps to find the minimum characters// must be moved to convert String s to tstatic int solve(String s, String t){ int n = s.Length; // r = maximum value over all // dp[i, j] computed so far int r = 0; // dp[i, j] stores the longest // contiguous suffix of T[0..j] // that is subsequence of S[0..i] for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { dp[i, j] = 0; if (i > 0) { dp[i, j] = Math.Max(dp[i - 1, j], dp[i, j]); } if (s[i] == t[j]) { int ans = 1; if (i > 0 && j > 0) { ans = 1 + dp[i - 1, j - 1]; } // Update the maximum length dp[i, j] = Math.Max(dp[i, j], ans); r = Math.Max(r, dp[i, j]); } } } // Return the resulting length return (n - r);} // Driver Codepublic static void Main(String[] args){ // Given String s, t String s = \"abcde\"; String t = \"edacb\"; // Function Call Console.Write(solve(s, t));}} // This code is contributed by shikhasingrajput",
"e": 33380,
"s": 32023,
"text": null
},
{
"code": "<script> // Javascript program for the above approach var dp = Array.from(Array(1010), ()=> Array(1010)); // Function that finds the minimum number// of steps to find the minimum characters// must be moved to convert string s to tfunction solve(s, t){ var n = s.length; // r = maximum value over all // dp[i][j] computed so far var r = 0; // dp[i][j] stores the longest // contiguous suffix of T[0..j] // that is subsequence of S[0..i] for (var i = 0; i < n; i++) { for (var j = 0; j < n; j++) { dp[i][j] = 0; if (i > 0) { dp[i][j] = Math.max(dp[i - 1][j], dp[i][j]); } if (s[i] == t[j]) { var ans = 1; if (i > 0 && j > 0) { ans = 1 + dp[i - 1][j - 1]; } // Update the maximum length dp[i][j] = Math.max(dp[i][j], ans); r = Math.max(r, dp[i][j]); } } } // Return the resulting length return (n - r);} // Driver Code// Given string s, tvar s = \"abcde\";var t = \"edacb\";// Function Calldocument.write( solve(s, t)); </script>",
"e": 34569,
"s": 33380,
"text": null
},
{
"code": null,
"e": 34571,
"s": 34569,
"text": "3"
},
{
"code": null,
"e": 34659,
"s": 34571,
"text": "Time Complexity: O(N2), where N is the length of the given stringAuxiliary Space: O(N2)"
},
{
"code": null,
"e": 34795,
"s": 34659,
"text": "Note: The above naive approach is efficient for smaller strings whereas, the above efficient approach is efficient for larger strings. "
},
{
"code": null,
"e": 34812,
"s": 34795,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 34822,
"s": 34812,
"text": "code_hunt"
},
{
"code": null,
"e": 34832,
"s": 34822,
"text": "rutvik_56"
},
{
"code": null,
"e": 34836,
"s": 34832,
"text": "LCS"
},
{
"code": null,
"e": 34846,
"s": 34836,
"text": "substring"
},
{
"code": null,
"e": 34866,
"s": 34846,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 34874,
"s": 34866,
"text": "Strings"
},
{
"code": null,
"e": 34882,
"s": 34874,
"text": "Strings"
},
{
"code": null,
"e": 34902,
"s": 34882,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 34906,
"s": 34902,
"text": "LCS"
},
{
"code": null,
"e": 35004,
"s": 34906,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35035,
"s": 35004,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 35068,
"s": 35035,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 35095,
"s": 35068,
"text": "Subset Sum Problem | DP-25"
},
{
"code": null,
"e": 35114,
"s": 35095,
"text": "Coin Change | DP-7"
},
{
"code": null,
"e": 35149,
"s": 35114,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 35195,
"s": 35149,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 35220,
"s": 35195,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 35235,
"s": 35220,
"text": "C++ Data Types"
},
{
"code": null,
"e": 35310,
"s": 35235,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
}
] |
Count of integers from the range [0, N] whose digit sum is a multiple of K - GeeksforGeeks
|
15 Jun, 2021
Given two integers N and K, the task is to calculate the number of integers in the range [0, N] whose digit sum is a multiple of K. The answer could be large, so print the answer modulo 109 +7.
Examples:
Input: N = 10, K = 5 Output: 2 0 and 5 are the only possible integers.
Input: N = 30, K = 4 Output: 7
Naive Approach: For small value of N, loop through the range [0, N] and check if the sum of the digits of the numbers are multiples of K or not.
Efficient Approach: The idea is to use digit dp to solve this problem. Subproblems iterating through all index values from the left or most significant digit(MSD) in the given integer will be solved and for each index, store the number of ways such that (sum of digits upto current index) mod K to be zero. The dp states will be:
dp[idx][sum][tight] idx = position, it tells about the index value from left in the given integer sum = sum of digits mod k, This parameter will store the (sum of digits mod k) in the generated integer from most significant digit(MSD) to p tight = flag if the current value is crossing the range (1, n) or not For unrestricted range tight = 0 For restricted range tight = 1
Let’s say we are at the MSD having index idx. So initially the sum will be 0. At every position, set a limit that is always in the range [0, 9]. Therefore, fill the digit at index by the digits in its range from 0 to limit and fetch the answer from the next state having index = idx + 1 and new_tight for next state is calculated separately. The dp state definition will be:
dp[idx][sum][tight] += dp[idx + 1][(sum + d) % k][new_tight] for d in [0, limit]
Below is the implementation of the above approach:
C++
Java
Python 3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; #define MAX 100005#define MOD 1000000007 // To store the states of the dpint dp[MAX][101][2]; // Function to return the count of numbers// from the range [0, n] whose digit sum// is a multiple of k using bottom-up dpint countNum(int idx, int sum, int tight, vector<int> num, int len, int k){ if (len == idx) { if (sum == 0) return 1; else return 0; } if (dp[idx][sum][tight] != -1) return dp[idx][sum][tight]; int res = 0, limit; // The digit in this index can // only be from [0, num[idx]] if (tight == 0) { limit = num[idx]; } // The digit in this index can // be anything from [0, 9] else { limit = 9; } for (int i = 0; i <= limit; i++) { // new_tight is the flag value // for the next position int new_tight = tight; if (tight == 0 && i < limit) new_tight = 1; res += countNum(idx + 1, (sum + i) % k, new_tight, num, len, k); res %= MOD; } // res can't be negative if (res < 0) res += MOD; return dp[idx][sum][tight] = res;} // Function to process the string to// a vector of digits from MSD to LSDvector<int> process(string s){ vector<int> num; for (int i = 0; i < s.length(); i++) { num.push_back(s[i] - '0'); } return num;} // Driver codeint main(){ // For large input number n string n = "98765432109876543210"; // Total number of digits in n int len = n.length(); int k = 58; // Clean dp table memset(dp, -1, sizeof(dp)); // Process the string to a vector // of digits from MSD to LSD vector<int> num = process(n); cout << countNum(0, 0, 0, num, len, k); return 0;}
// Java implementation of the approachimport java.util.*; class GFG{ static final int MAX = 100005;static final int MOD = 1000000007; // To store the states of the dpstatic int [][][]dp = new int[MAX][101][2]; // Function to return the count of numbers// from the range [0, n] whose digit sum// is a multiple of k using bottom-up dpstatic int countNum(int idx, int sum, int tight, Vector<Integer> num, int len, int k){ if (len == idx) { if (sum == 0) return 1; else return 0; } if (dp[idx][sum][tight] != -1) return dp[idx][sum][tight]; int res = 0, limit; // The digit in this index can // only be from [0, num[idx]] if (tight == 0) { limit = num.get(idx); } // The digit in this index can // be anything from [0, 9] else { limit = 9; } for (int i = 0; i <= limit; i++) { // new_tight is the flag value // for the next position int new_tight = tight; if (tight == 0 && i < limit) new_tight = 1; res += countNum(idx + 1, (sum + i) % k, new_tight, num, len, k); res %= MOD; } // res can't be negative if (res < 0) res += MOD; return dp[idx][sum][tight] = res;} // Function to process the String to// a vector of digits from MSD to LSDstatic Vector<Integer> process(String s){ Vector<Integer> num = new Vector<Integer>(); for (int i = 0; i < s.length(); i++) { num.add(s.charAt(i) - '0'); } return num;} // Driver codepublic static void main(String[] args){ // For large input number n String n = "98765432109876543210"; // Total number of digits in n int len = n.length(); int k = 58; // Clean dp table for(int i = 0; i < MAX; i++) { for(int j = 0; j < 101; j++) { for(int l = 0; l < 2; l++) dp[i][j][l] = -1; } } // Process the String to a vector // of digits from MSD to LSD Vector<Integer> num = process(n); System.out.print(countNum(0, 0, 0, num, len, k)); }} // This code is contributed by 29AjayKumar
# Python 3 implementation of the approachMAX = 10005MOD = 1000000007 # Function to return the count of numbers# from the range [0, n] whose digit sum# is a multiple of k using bottom-up dpdef countNum(idx, sum, tight, num, len1, k): if (len1 == idx): if (sum == 0): return 1 else: return 0 if (dp[idx][sum][tight] != -1): return dp[idx][sum][tight] res = 0 # The digit in this index can # only be from [0, num[idx]] if (tight == 0): limit = num[idx] # The digit in this index can # be anything from [0, 9] else: limit = 9 for i in range(limit + 1): # new_tight is the flag value # for the next position new_tight = tight if (tight == 0 and i < limit): new_tight = 1 res += countNum(idx + 1,(sum + i) % k, new_tight, num, len1, k) res %= MOD # res can't be negative if (res < 0): res += MOD dp[idx][sum][tight] = res return dp[idx][sum][tight] # Function to process the string to# a vector of digits from MSD to LSDdef process(s): num = [] for i in range(len(s)): num.append(ord(s[i]) - ord('0')) return num # Driver codeif __name__ == '__main__': # For large input number n n = "98765432109876543210" # Total number of digits in n len1 = len(n) k = 58 # To store the states of the dp dp = [[[-1 for i in range(2)] for j in range(101)] for k in range(MAX)] # Process the string to a vector # of digits from MSD to LSD num = process(n) print(countNum(0, 0, 0, num, len1, k)) # This code is contributed by Surendra_Gangwar
// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{static readonly int MAX = 10005;static readonly int MOD = 1000000007; // To store the states of the dpstatic int [,,]dp = new int[MAX, 101, 2]; // Function to return the count of numbers// from the range [0, n] whose digit sum// is a multiple of k using bottom-up dpstatic int countNum(int idx, int sum, int tight, List<int> num, int len, int k){ if (len == idx) { if (sum == 0) return 1; else return 0; } if (dp[idx, sum, tight] != -1) return dp[idx, sum, tight]; int res = 0, limit; // The digit in this index can // only be from [0, num[idx]] if (tight == 0) { limit = num[idx]; } // The digit in this index can // be anything from [0, 9] else { limit = 9; } for (int i = 0; i <= limit; i++) { // new_tight is the flag value // for the next position int new_tight = tight; if (tight == 0 && i < limit) new_tight = 1; res += countNum(idx + 1, (sum + i) % k, new_tight, num, len, k); res %= MOD; } // res can't be negative if (res < 0) res += MOD; return dp[idx, sum, tight] = res;} // Function to process the String to// a vector of digits from MSD to LSDstatic List<int> process(String s){ List<int> num = new List<int>(); for (int i = 0; i < s.Length; i++) { num.Add(s[i] - '0'); } return num;} // Driver codepublic static void Main(String[] args){ // For large input number n String n = "98765432109876543210"; // Total number of digits in n int len = n.Length; int k = 58; // Clean dp table for(int i = 0; i < MAX; i++) { for(int j = 0; j < 101; j++) { for(int l = 0; l < 2; l++) dp[i, j, l] = -1; } } // Process the String to a vector // of digits from MSD to LSD List<int> num = process(n); Console.Write(countNum(0, 0, 0, num, len, k));}} // This code is contributed by Rajput-Ji
<script> // Javascript implementation of the approach var MAX = 100005;var MOD = 1000000007; // To store the states of the dpvar dp = Array.from(Array(MAX), () => Array(101));for(var i =0; i<MAX; i++) for(var j =0; j<101; j++) dp[i][j] = new Array(2).fill(-1); // Function to return the count of numbers// from the range [0, n] whose digit sum// is a multiple of k using bottom-up dpfunction countNum(idx, sum, tight, num, len, k){ if (len == idx) { if (sum == 0) return 1; else return 0; } if (dp[idx][sum][tight] != -1) return dp[idx][sum][tight]; var res = 0, limit; // The digit in this index can // only be from [0, num[idx]] if (tight == 0) { limit = num[idx]; } // The digit in this index can // be anything from [0, 9] else { limit = 9; } for (var i = 0; i <= limit; i++) { // new_tight is the flag value // for the next position var new_tight = tight; if (tight == 0 && i < limit) new_tight = 1; res += countNum(idx + 1, (sum + i) % k, new_tight, num, len, k); res %= MOD; } // res can't be negative if (res < 0) res += MOD; return dp[idx][sum][tight] = res;} // Function to process the string to// a vector of digits from MSD to LSDfunction process(s){ var num = []; for (var i = 0; i < s.length; i++) { num.push(s[i].charCodeAt(0) - '0'.charCodeAt(0)); } return num;} // Driver code// For large input number nvar n = "98765432109876543210";// Total number of digits in nvar len = n.length;var k = 58;// Process the string to a vector// of digits from MSD to LSDvar num = process(n);document.write( countNum(0, 0, 0, num, len, k)); </script>
635270835
SURENDRA_GANGWAR
29AjayKumar
Rajput-Ji
importantly
digit-DP
Dynamic Programming
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum size square sub-matrix with all 1s
Optimal Substructure Property in Dynamic Programming | DP-2
Optimal Binary Search Tree | DP-24
Min Cost Path | DP-6
Maximum Subarray Sum using Divide and Conquer algorithm
Greedy approach vs Dynamic programming
Maximum sum such that no two elements are adjacent
Word Break Problem | DP-32
3 Different ways to print Fibonacci series in Java
Top 50 Dynamic Programming Coding Problems for Interviews
|
[
{
"code": null,
"e": 25917,
"s": 25889,
"text": "\n15 Jun, 2021"
},
{
"code": null,
"e": 26111,
"s": 25917,
"text": "Given two integers N and K, the task is to calculate the number of integers in the range [0, N] whose digit sum is a multiple of K. The answer could be large, so print the answer modulo 109 +7."
},
{
"code": null,
"e": 26123,
"s": 26111,
"text": "Examples: "
},
{
"code": null,
"e": 26194,
"s": 26123,
"text": "Input: N = 10, K = 5 Output: 2 0 and 5 are the only possible integers."
},
{
"code": null,
"e": 26227,
"s": 26194,
"text": "Input: N = 30, K = 4 Output: 7 "
},
{
"code": null,
"e": 26373,
"s": 26227,
"text": "Naive Approach: For small value of N, loop through the range [0, N] and check if the sum of the digits of the numbers are multiples of K or not. "
},
{
"code": null,
"e": 26704,
"s": 26373,
"text": "Efficient Approach: The idea is to use digit dp to solve this problem. Subproblems iterating through all index values from the left or most significant digit(MSD) in the given integer will be solved and for each index, store the number of ways such that (sum of digits upto current index) mod K to be zero. The dp states will be: "
},
{
"code": null,
"e": 27079,
"s": 26704,
"text": "dp[idx][sum][tight] idx = position, it tells about the index value from left in the given integer sum = sum of digits mod k, This parameter will store the (sum of digits mod k) in the generated integer from most significant digit(MSD) to p tight = flag if the current value is crossing the range (1, n) or not For unrestricted range tight = 0 For restricted range tight = 1 "
},
{
"code": null,
"e": 27455,
"s": 27079,
"text": "Let’s say we are at the MSD having index idx. So initially the sum will be 0. At every position, set a limit that is always in the range [0, 9]. Therefore, fill the digit at index by the digits in its range from 0 to limit and fetch the answer from the next state having index = idx + 1 and new_tight for next state is calculated separately. The dp state definition will be: "
},
{
"code": null,
"e": 27538,
"s": 27455,
"text": "dp[idx][sum][tight] += dp[idx + 1][(sum + d) % k][new_tight] for d in [0, limit] "
},
{
"code": null,
"e": 27590,
"s": 27538,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27594,
"s": 27590,
"text": "C++"
},
{
"code": null,
"e": 27599,
"s": 27594,
"text": "Java"
},
{
"code": null,
"e": 27608,
"s": 27599,
"text": "Python 3"
},
{
"code": null,
"e": 27611,
"s": 27608,
"text": "C#"
},
{
"code": null,
"e": 27622,
"s": 27611,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; #define MAX 100005#define MOD 1000000007 // To store the states of the dpint dp[MAX][101][2]; // Function to return the count of numbers// from the range [0, n] whose digit sum// is a multiple of k using bottom-up dpint countNum(int idx, int sum, int tight, vector<int> num, int len, int k){ if (len == idx) { if (sum == 0) return 1; else return 0; } if (dp[idx][sum][tight] != -1) return dp[idx][sum][tight]; int res = 0, limit; // The digit in this index can // only be from [0, num[idx]] if (tight == 0) { limit = num[idx]; } // The digit in this index can // be anything from [0, 9] else { limit = 9; } for (int i = 0; i <= limit; i++) { // new_tight is the flag value // for the next position int new_tight = tight; if (tight == 0 && i < limit) new_tight = 1; res += countNum(idx + 1, (sum + i) % k, new_tight, num, len, k); res %= MOD; } // res can't be negative if (res < 0) res += MOD; return dp[idx][sum][tight] = res;} // Function to process the string to// a vector of digits from MSD to LSDvector<int> process(string s){ vector<int> num; for (int i = 0; i < s.length(); i++) { num.push_back(s[i] - '0'); } return num;} // Driver codeint main(){ // For large input number n string n = \"98765432109876543210\"; // Total number of digits in n int len = n.length(); int k = 58; // Clean dp table memset(dp, -1, sizeof(dp)); // Process the string to a vector // of digits from MSD to LSD vector<int> num = process(n); cout << countNum(0, 0, 0, num, len, k); return 0;}",
"e": 29471,
"s": 27622,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*; class GFG{ static final int MAX = 100005;static final int MOD = 1000000007; // To store the states of the dpstatic int [][][]dp = new int[MAX][101][2]; // Function to return the count of numbers// from the range [0, n] whose digit sum// is a multiple of k using bottom-up dpstatic int countNum(int idx, int sum, int tight, Vector<Integer> num, int len, int k){ if (len == idx) { if (sum == 0) return 1; else return 0; } if (dp[idx][sum][tight] != -1) return dp[idx][sum][tight]; int res = 0, limit; // The digit in this index can // only be from [0, num[idx]] if (tight == 0) { limit = num.get(idx); } // The digit in this index can // be anything from [0, 9] else { limit = 9; } for (int i = 0; i <= limit; i++) { // new_tight is the flag value // for the next position int new_tight = tight; if (tight == 0 && i < limit) new_tight = 1; res += countNum(idx + 1, (sum + i) % k, new_tight, num, len, k); res %= MOD; } // res can't be negative if (res < 0) res += MOD; return dp[idx][sum][tight] = res;} // Function to process the String to// a vector of digits from MSD to LSDstatic Vector<Integer> process(String s){ Vector<Integer> num = new Vector<Integer>(); for (int i = 0; i < s.length(); i++) { num.add(s.charAt(i) - '0'); } return num;} // Driver codepublic static void main(String[] args){ // For large input number n String n = \"98765432109876543210\"; // Total number of digits in n int len = n.length(); int k = 58; // Clean dp table for(int i = 0; i < MAX; i++) { for(int j = 0; j < 101; j++) { for(int l = 0; l < 2; l++) dp[i][j][l] = -1; } } // Process the String to a vector // of digits from MSD to LSD Vector<Integer> num = process(n); System.out.print(countNum(0, 0, 0, num, len, k)); }} // This code is contributed by 29AjayKumar",
"e": 31628,
"s": 29471,
"text": null
},
{
"code": "# Python 3 implementation of the approachMAX = 10005MOD = 1000000007 # Function to return the count of numbers# from the range [0, n] whose digit sum# is a multiple of k using bottom-up dpdef countNum(idx, sum, tight, num, len1, k): if (len1 == idx): if (sum == 0): return 1 else: return 0 if (dp[idx][sum][tight] != -1): return dp[idx][sum][tight] res = 0 # The digit in this index can # only be from [0, num[idx]] if (tight == 0): limit = num[idx] # The digit in this index can # be anything from [0, 9] else: limit = 9 for i in range(limit + 1): # new_tight is the flag value # for the next position new_tight = tight if (tight == 0 and i < limit): new_tight = 1 res += countNum(idx + 1,(sum + i) % k, new_tight, num, len1, k) res %= MOD # res can't be negative if (res < 0): res += MOD dp[idx][sum][tight] = res return dp[idx][sum][tight] # Function to process the string to# a vector of digits from MSD to LSDdef process(s): num = [] for i in range(len(s)): num.append(ord(s[i]) - ord('0')) return num # Driver codeif __name__ == '__main__': # For large input number n n = \"98765432109876543210\" # Total number of digits in n len1 = len(n) k = 58 # To store the states of the dp dp = [[[-1 for i in range(2)] for j in range(101)] for k in range(MAX)] # Process the string to a vector # of digits from MSD to LSD num = process(n) print(countNum(0, 0, 0, num, len1, k)) # This code is contributed by Surendra_Gangwar",
"e": 33331,
"s": 31628,
"text": null
},
{
"code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{static readonly int MAX = 10005;static readonly int MOD = 1000000007; // To store the states of the dpstatic int [,,]dp = new int[MAX, 101, 2]; // Function to return the count of numbers// from the range [0, n] whose digit sum// is a multiple of k using bottom-up dpstatic int countNum(int idx, int sum, int tight, List<int> num, int len, int k){ if (len == idx) { if (sum == 0) return 1; else return 0; } if (dp[idx, sum, tight] != -1) return dp[idx, sum, tight]; int res = 0, limit; // The digit in this index can // only be from [0, num[idx]] if (tight == 0) { limit = num[idx]; } // The digit in this index can // be anything from [0, 9] else { limit = 9; } for (int i = 0; i <= limit; i++) { // new_tight is the flag value // for the next position int new_tight = tight; if (tight == 0 && i < limit) new_tight = 1; res += countNum(idx + 1, (sum + i) % k, new_tight, num, len, k); res %= MOD; } // res can't be negative if (res < 0) res += MOD; return dp[idx, sum, tight] = res;} // Function to process the String to// a vector of digits from MSD to LSDstatic List<int> process(String s){ List<int> num = new List<int>(); for (int i = 0; i < s.Length; i++) { num.Add(s[i] - '0'); } return num;} // Driver codepublic static void Main(String[] args){ // For large input number n String n = \"98765432109876543210\"; // Total number of digits in n int len = n.Length; int k = 58; // Clean dp table for(int i = 0; i < MAX; i++) { for(int j = 0; j < 101; j++) { for(int l = 0; l < 2; l++) dp[i, j, l] = -1; } } // Process the String to a vector // of digits from MSD to LSD List<int> num = process(n); Console.Write(countNum(0, 0, 0, num, len, k));}} // This code is contributed by Rajput-Ji",
"e": 35470,
"s": 33331,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach var MAX = 100005;var MOD = 1000000007; // To store the states of the dpvar dp = Array.from(Array(MAX), () => Array(101));for(var i =0; i<MAX; i++) for(var j =0; j<101; j++) dp[i][j] = new Array(2).fill(-1); // Function to return the count of numbers// from the range [0, n] whose digit sum// is a multiple of k using bottom-up dpfunction countNum(idx, sum, tight, num, len, k){ if (len == idx) { if (sum == 0) return 1; else return 0; } if (dp[idx][sum][tight] != -1) return dp[idx][sum][tight]; var res = 0, limit; // The digit in this index can // only be from [0, num[idx]] if (tight == 0) { limit = num[idx]; } // The digit in this index can // be anything from [0, 9] else { limit = 9; } for (var i = 0; i <= limit; i++) { // new_tight is the flag value // for the next position var new_tight = tight; if (tight == 0 && i < limit) new_tight = 1; res += countNum(idx + 1, (sum + i) % k, new_tight, num, len, k); res %= MOD; } // res can't be negative if (res < 0) res += MOD; return dp[idx][sum][tight] = res;} // Function to process the string to// a vector of digits from MSD to LSDfunction process(s){ var num = []; for (var i = 0; i < s.length; i++) { num.push(s[i].charCodeAt(0) - '0'.charCodeAt(0)); } return num;} // Driver code// For large input number nvar n = \"98765432109876543210\";// Total number of digits in nvar len = n.length;var k = 58;// Process the string to a vector// of digits from MSD to LSDvar num = process(n);document.write( countNum(0, 0, 0, num, len, k)); </script>",
"e": 37277,
"s": 35470,
"text": null
},
{
"code": null,
"e": 37287,
"s": 37277,
"text": "635270835"
},
{
"code": null,
"e": 37306,
"s": 37289,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 37318,
"s": 37306,
"text": "29AjayKumar"
},
{
"code": null,
"e": 37328,
"s": 37318,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 37340,
"s": 37328,
"text": "importantly"
},
{
"code": null,
"e": 37349,
"s": 37340,
"text": "digit-DP"
},
{
"code": null,
"e": 37369,
"s": 37349,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 37389,
"s": 37369,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 37487,
"s": 37389,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37530,
"s": 37487,
"text": "Maximum size square sub-matrix with all 1s"
},
{
"code": null,
"e": 37590,
"s": 37530,
"text": "Optimal Substructure Property in Dynamic Programming | DP-2"
},
{
"code": null,
"e": 37625,
"s": 37590,
"text": "Optimal Binary Search Tree | DP-24"
},
{
"code": null,
"e": 37646,
"s": 37625,
"text": "Min Cost Path | DP-6"
},
{
"code": null,
"e": 37702,
"s": 37646,
"text": "Maximum Subarray Sum using Divide and Conquer algorithm"
},
{
"code": null,
"e": 37741,
"s": 37702,
"text": "Greedy approach vs Dynamic programming"
},
{
"code": null,
"e": 37792,
"s": 37741,
"text": "Maximum sum such that no two elements are adjacent"
},
{
"code": null,
"e": 37819,
"s": 37792,
"text": "Word Break Problem | DP-32"
},
{
"code": null,
"e": 37870,
"s": 37819,
"text": "3 Different ways to print Fibonacci series in Java"
}
] |
Push Relabel Algorithm | Set 1 (Introduction and Illustration) - GeeksforGeeks
|
08 Apr, 2022
Given a graph which represents a flow network where every edge has a capacity. Also given two vertices source ‘s’ and sink ‘t’ in the graph, find the maximum possible flow from s to t with following constraints: a) Flow on an edge doesn’t exceed the given capacity of the edge. b) Incoming flow is equal to outgoing flow for every vertex except s and t. For example, consider the following graph from CLRS book. The maximum possible flow in the above graph is 23. We have discussed Ford Fulkerson Algorithm that uses augmenting path for computing maximum flow.
Push-Relabel approach is the more efficient than Ford-Fulkerson algorithm. In this post, Goldberg’s “generic” maximum-flow algorithm is discussed that runs in O(V2E) time. This time complexity is better than O(E2V) which is time complexity of Edmond-Karp algorithm (a BFS based implementation of Ford-Fulkerson). There exist a push-relabel approach based algorithm that works in O(V3) which is even better than the one discussed here. Similarities with Ford Fulkerson
Like Ford-Fulkerson, Push-Relabel also works on Residual Graph (Residual Graph of a flow network is a graph which indicates additional possible flow. If there is a path from source to sink in residual graph, then it is possible to add flow).
Differences with Ford Fulkerson
Push-relabel algorithm works in a more localized. Rather than examining the entire residual network to find an augmenting path, push-relabel algorithms work on one vertex at a time (Source : CLRS Book).
In Ford-Fulkerson, net difference between total outflow and total inflow for every vertex (Except source and sink) is maintained 0. Push-Relabel algorithm allows inflow to exceed the outflow before reaching the final flow. In final flow, the net difference is 0 for all except source and sink.
Time complexity wise more efficient.
The intuition behind the push-relabel algorithm (considering a fluid flow problem) is that we consider edges as water pipes and nodes are joints. The source is considered to be at the highest level and it sends water to all adjacent nodes. Once a node has excess water, it pushes water to a smaller height node. If water gets locally trapped at a vertex, the vertex is Relabeled which means its height is increased. Following are some useful facts to consider before we proceed to algorithm.
Each vertex has associated to it a height variable and a Excess Flow. Height is used to determine whether a vertex can push flow to an adjacent or not (A vertex can push flow only to a smaller height vertex). Excess flow is the difference of total flow coming into the vertex minus the total flow going out of the vertex.
Excess Flow of u = Total Inflow to u -
Total Outflow from u
Like Ford Fulkerson. each edge has associated to it a flow (which indicates current flow) and a capacity
Following are abstract steps of complete algorithm.
Push-Relabel Algorithm
1) Initialize PreFlow : Initialize Flows
and Heights
2) While it is possible to perform a Push() or
Relabel() on a vertex
// Or while there is a vertex that has excess flow
Do Push() or Relabel()
// At this point all vertices have Excess Flow as 0 (Except source
// and sink)
3) Return flow.
There are three main operations in Push-Relabel Algorithm
Initialize PreFlow() It initializes heights and flows of all vertices.
Initialize PreFlow() It initializes heights and flows of all vertices.
Preflow()
1) Initialize height and flow of every vertex as 0.
2) Initialize height of source vertex equal to total
number of vertices in graph.
3) Initialize flow of every edge as 0.
4) For all vertices adjacent to source s, flow and
excess flow is equal to capacity initially.
Push() is used to make the flow from a node which has excess flow. If a vertex has excess flow and there is an adjacent with smaller height (in residual graph), we push the flow from the vertex to the adjacent with lower height. The amount of pushed flow through the pipe (edge) is equal to the minimum of excess flow and capacity of edge.Relabel() operation is used when a vertex has excess flow and none of its adjacent is at lower height. We basically increase height of the vertex so that we can perform push(). To increase height, we pick the minimum height adjacent (in residual graph, i.e., an adjacent to whom we can add flow) and add 1 to it.
Push() is used to make the flow from a node which has excess flow. If a vertex has excess flow and there is an adjacent with smaller height (in residual graph), we push the flow from the vertex to the adjacent with lower height. The amount of pushed flow through the pipe (edge) is equal to the minimum of excess flow and capacity of edge.
Relabel() operation is used when a vertex has excess flow and none of its adjacent is at lower height. We basically increase height of the vertex so that we can perform push(). To increase height, we pick the minimum height adjacent (in residual graph, i.e., an adjacent to whom we can add flow) and add 1 to it.
Note that above operations are performed on residual graph (like Ford-Fulkerson). Illustration:Before we proceed to below example, we need to make sure that we understand residual graph (See this for more details of residual graph). Residual graph is different from graphs shown. Whenever we push or add a flow from a vertex u to v, we do following updates in residual graph : 1) We subtract the flow from capacity of edge from u to v. If capacity of an edge becomes 0, then the edge no longer exists in residual graph. 2) We add flow to the capacity of edge from v to u.
For example, consider two vertices u an v.
In original graph
3/10
u ---------> v
3 is current flow from u to v and
10 is capacity of edge from u to v.
In residual Graph, there are two edges corresponding
to one edge shown above.
7
u ---------> v
3
u <--------- v
Initial given flow graph. After PreFlow operation. In residual graph, there is an edge from A to S with capacity 3 and no edge from S to A. The highlighted vertex is relabeled (height becomes 1) as it has excess flow and there is no adjacent with smaller height. The new height is equal to minimum of heights of adjacent plus 1. In residual graph, there are two adjacent of vertex A, one is S and other is B. Height of S is 4 and height of B is 0. Minimum of these two heights is 0. We take the minimum and add 1 to it. The highlighted vertex has excess flow and there is an adjacent with lower height, so push() happens. Excess flow of vertex A is 2 and capacity of edge (A, B) is 1. Therefore, the amount of pushed flow is 1 (minimum of two values). The highlighted vertex is relabeled (height becomes 1) as it has excess flow and there is no adjacent with smaller height. The highlighted vertex has excess flow and there is an adjacent with lower height, so flow() is pushed from B to T. The highlighted vertex is relabeled (height becomes 5) as it has excess flow and there is no adjacent with smaller height. The highlighted vertex has excess flow and there is an adjacent with lower height, so push() happens. The highlighted vertex is relabeled (height is increased by 1) as it has excess flow and there is no adjacent with smaller height.
Initial given flow graph.
After PreFlow operation. In residual graph, there is an edge from A to S with capacity 3 and no edge from S to A.
The highlighted vertex is relabeled (height becomes 1) as it has excess flow and there is no adjacent with smaller height. The new height is equal to minimum of heights of adjacent plus 1. In residual graph, there are two adjacent of vertex A, one is S and other is B. Height of S is 4 and height of B is 0. Minimum of these two heights is 0. We take the minimum and add 1 to it.
The highlighted vertex has excess flow and there is an adjacent with lower height, so push() happens. Excess flow of vertex A is 2 and capacity of edge (A, B) is 1. Therefore, the amount of pushed flow is 1 (minimum of two values).
The highlighted vertex is relabeled (height becomes 1) as it has excess flow and there is no adjacent with smaller height.
The highlighted vertex has excess flow and there is an adjacent with lower height, so flow() is pushed from B to T.
The highlighted vertex is relabeled (height becomes 5) as it has excess flow and there is no adjacent with smaller height.
The highlighted vertex has excess flow and there is an adjacent with lower height, so push() happens.
The highlighted vertex is relabeled (height is increased by 1) as it has excess flow and there is no adjacent with smaller height.
surinderdawra388
Graph
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Topological Sorting
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
Detect Cycle in a Directed Graph
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)
Traveling Salesman Problem (TSP) Implementation
Strongly Connected Components
Detect cycle in an undirected graph
|
[
{
"code": null,
"e": 26295,
"s": 26267,
"text": "\n08 Apr, 2022"
},
{
"code": null,
"e": 26860,
"s": 26295,
"text": "Given a graph which represents a flow network where every edge has a capacity. Also given two vertices source ‘s’ and sink ‘t’ in the graph, find the maximum possible flow from s to t with following constraints: a) Flow on an edge doesn’t exceed the given capacity of the edge. b) Incoming flow is equal to outgoing flow for every vertex except s and t. For example, consider the following graph from CLRS book. The maximum possible flow in the above graph is 23. We have discussed Ford Fulkerson Algorithm that uses augmenting path for computing maximum flow. "
},
{
"code": null,
"e": 27328,
"s": 26860,
"text": "Push-Relabel approach is the more efficient than Ford-Fulkerson algorithm. In this post, Goldberg’s “generic” maximum-flow algorithm is discussed that runs in O(V2E) time. This time complexity is better than O(E2V) which is time complexity of Edmond-Karp algorithm (a BFS based implementation of Ford-Fulkerson). There exist a push-relabel approach based algorithm that works in O(V3) which is even better than the one discussed here. Similarities with Ford Fulkerson"
},
{
"code": null,
"e": 27570,
"s": 27328,
"text": "Like Ford-Fulkerson, Push-Relabel also works on Residual Graph (Residual Graph of a flow network is a graph which indicates additional possible flow. If there is a path from source to sink in residual graph, then it is possible to add flow)."
},
{
"code": null,
"e": 27602,
"s": 27570,
"text": "Differences with Ford Fulkerson"
},
{
"code": null,
"e": 27805,
"s": 27602,
"text": "Push-relabel algorithm works in a more localized. Rather than examining the entire residual network to find an augmenting path, push-relabel algorithms work on one vertex at a time (Source : CLRS Book)."
},
{
"code": null,
"e": 28099,
"s": 27805,
"text": "In Ford-Fulkerson, net difference between total outflow and total inflow for every vertex (Except source and sink) is maintained 0. Push-Relabel algorithm allows inflow to exceed the outflow before reaching the final flow. In final flow, the net difference is 0 for all except source and sink."
},
{
"code": null,
"e": 28136,
"s": 28099,
"text": "Time complexity wise more efficient."
},
{
"code": null,
"e": 28628,
"s": 28136,
"text": "The intuition behind the push-relabel algorithm (considering a fluid flow problem) is that we consider edges as water pipes and nodes are joints. The source is considered to be at the highest level and it sends water to all adjacent nodes. Once a node has excess water, it pushes water to a smaller height node. If water gets locally trapped at a vertex, the vertex is Relabeled which means its height is increased. Following are some useful facts to consider before we proceed to algorithm."
},
{
"code": null,
"e": 28950,
"s": 28628,
"text": "Each vertex has associated to it a height variable and a Excess Flow. Height is used to determine whether a vertex can push flow to an adjacent or not (A vertex can push flow only to a smaller height vertex). Excess flow is the difference of total flow coming into the vertex minus the total flow going out of the vertex."
},
{
"code": null,
"e": 29040,
"s": 28950,
"text": " Excess Flow of u = Total Inflow to u - \n Total Outflow from u"
},
{
"code": null,
"e": 29145,
"s": 29040,
"text": "Like Ford Fulkerson. each edge has associated to it a flow (which indicates current flow) and a capacity"
},
{
"code": null,
"e": 29197,
"s": 29145,
"text": "Following are abstract steps of complete algorithm."
},
{
"code": null,
"e": 29538,
"s": 29197,
"text": "Push-Relabel Algorithm \n1) Initialize PreFlow : Initialize Flows \n and Heights \n\n2) While it is possible to perform a Push() or \n Relabel() on a vertex\n // Or while there is a vertex that has excess flow\n Do Push() or Relabel()\n\n// At this point all vertices have Excess Flow as 0 (Except source\n// and sink)\n3) Return flow."
},
{
"code": null,
"e": 29598,
"s": 29538,
"text": " There are three main operations in Push-Relabel Algorithm"
},
{
"code": null,
"e": 29669,
"s": 29598,
"text": "Initialize PreFlow() It initializes heights and flows of all vertices."
},
{
"code": null,
"e": 29740,
"s": 29669,
"text": "Initialize PreFlow() It initializes heights and flows of all vertices."
},
{
"code": null,
"e": 30028,
"s": 29740,
"text": "Preflow() \n1) Initialize height and flow of every vertex as 0.\n2) Initialize height of source vertex equal to total \n number of vertices in graph.\n3) Initialize flow of every edge as 0.\n4) For all vertices adjacent to source s, flow and \n excess flow is equal to capacity initially."
},
{
"code": null,
"e": 30680,
"s": 30028,
"text": "Push() is used to make the flow from a node which has excess flow. If a vertex has excess flow and there is an adjacent with smaller height (in residual graph), we push the flow from the vertex to the adjacent with lower height. The amount of pushed flow through the pipe (edge) is equal to the minimum of excess flow and capacity of edge.Relabel() operation is used when a vertex has excess flow and none of its adjacent is at lower height. We basically increase height of the vertex so that we can perform push(). To increase height, we pick the minimum height adjacent (in residual graph, i.e., an adjacent to whom we can add flow) and add 1 to it."
},
{
"code": null,
"e": 31020,
"s": 30680,
"text": "Push() is used to make the flow from a node which has excess flow. If a vertex has excess flow and there is an adjacent with smaller height (in residual graph), we push the flow from the vertex to the adjacent with lower height. The amount of pushed flow through the pipe (edge) is equal to the minimum of excess flow and capacity of edge."
},
{
"code": null,
"e": 31333,
"s": 31020,
"text": "Relabel() operation is used when a vertex has excess flow and none of its adjacent is at lower height. We basically increase height of the vertex so that we can perform push(). To increase height, we pick the minimum height adjacent (in residual graph, i.e., an adjacent to whom we can add flow) and add 1 to it."
},
{
"code": null,
"e": 31906,
"s": 31333,
"text": "Note that above operations are performed on residual graph (like Ford-Fulkerson). Illustration:Before we proceed to below example, we need to make sure that we understand residual graph (See this for more details of residual graph). Residual graph is different from graphs shown. Whenever we push or add a flow from a vertex u to v, we do following updates in residual graph : 1) We subtract the flow from capacity of edge from u to v. If capacity of an edge becomes 0, then the edge no longer exists in residual graph. 2) We add flow to the capacity of edge from v to u."
},
{
"code": null,
"e": 32216,
"s": 31906,
"text": "For example, consider two vertices u an v.\n\nIn original graph\n 3/10\n u ---------> v\n 3 is current flow from u to v and\n 10 is capacity of edge from u to v.\n\nIn residual Graph, there are two edges corresponding\nto one edge shown above.\n 7\n u ---------> v\n\n 3\n u <--------- v "
},
{
"code": null,
"e": 33567,
"s": 32216,
"text": "Initial given flow graph. After PreFlow operation. In residual graph, there is an edge from A to S with capacity 3 and no edge from S to A. The highlighted vertex is relabeled (height becomes 1) as it has excess flow and there is no adjacent with smaller height. The new height is equal to minimum of heights of adjacent plus 1. In residual graph, there are two adjacent of vertex A, one is S and other is B. Height of S is 4 and height of B is 0. Minimum of these two heights is 0. We take the minimum and add 1 to it. The highlighted vertex has excess flow and there is an adjacent with lower height, so push() happens. Excess flow of vertex A is 2 and capacity of edge (A, B) is 1. Therefore, the amount of pushed flow is 1 (minimum of two values). The highlighted vertex is relabeled (height becomes 1) as it has excess flow and there is no adjacent with smaller height. The highlighted vertex has excess flow and there is an adjacent with lower height, so flow() is pushed from B to T. The highlighted vertex is relabeled (height becomes 5) as it has excess flow and there is no adjacent with smaller height. The highlighted vertex has excess flow and there is an adjacent with lower height, so push() happens. The highlighted vertex is relabeled (height is increased by 1) as it has excess flow and there is no adjacent with smaller height. "
},
{
"code": null,
"e": 33594,
"s": 33567,
"text": "Initial given flow graph. "
},
{
"code": null,
"e": 33709,
"s": 33594,
"text": "After PreFlow operation. In residual graph, there is an edge from A to S with capacity 3 and no edge from S to A. "
},
{
"code": null,
"e": 34093,
"s": 33709,
"text": "The highlighted vertex is relabeled (height becomes 1) as it has excess flow and there is no adjacent with smaller height. The new height is equal to minimum of heights of adjacent plus 1. In residual graph, there are two adjacent of vertex A, one is S and other is B. Height of S is 4 and height of B is 0. Minimum of these two heights is 0. We take the minimum and add 1 to it. "
},
{
"code": null,
"e": 34326,
"s": 34093,
"text": "The highlighted vertex has excess flow and there is an adjacent with lower height, so push() happens. Excess flow of vertex A is 2 and capacity of edge (A, B) is 1. Therefore, the amount of pushed flow is 1 (minimum of two values). "
},
{
"code": null,
"e": 34450,
"s": 34326,
"text": "The highlighted vertex is relabeled (height becomes 1) as it has excess flow and there is no adjacent with smaller height. "
},
{
"code": null,
"e": 34567,
"s": 34450,
"text": "The highlighted vertex has excess flow and there is an adjacent with lower height, so flow() is pushed from B to T. "
},
{
"code": null,
"e": 34691,
"s": 34567,
"text": "The highlighted vertex is relabeled (height becomes 5) as it has excess flow and there is no adjacent with smaller height. "
},
{
"code": null,
"e": 34794,
"s": 34691,
"text": "The highlighted vertex has excess flow and there is an adjacent with lower height, so push() happens. "
},
{
"code": null,
"e": 34926,
"s": 34794,
"text": "The highlighted vertex is relabeled (height is increased by 1) as it has excess flow and there is no adjacent with smaller height. "
},
{
"code": null,
"e": 34943,
"s": 34926,
"text": "surinderdawra388"
},
{
"code": null,
"e": 34949,
"s": 34943,
"text": "Graph"
},
{
"code": null,
"e": 34955,
"s": 34949,
"text": "Graph"
},
{
"code": null,
"e": 35053,
"s": 34955,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35111,
"s": 35053,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 35131,
"s": 35111,
"text": "Topological Sorting"
},
{
"code": null,
"e": 35162,
"s": 35131,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 35195,
"s": 35162,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 35228,
"s": 35195,
"text": "Detect Cycle in a Directed Graph"
},
{
"code": null,
"e": 35296,
"s": 35228,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 35371,
"s": 35296,
"text": "Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)"
},
{
"code": null,
"e": 35419,
"s": 35371,
"text": "Traveling Salesman Problem (TSP) Implementation"
},
{
"code": null,
"e": 35449,
"s": 35419,
"text": "Strongly Connected Components"
}
] |
Insert a given column at a specific position in a Pandas DataFrame - GeeksforGeeks
|
26 Jul, 2020
In this article, we will use Dataframe.insert() method of Pandas to insert a new column at a specific column index in a dataframe.
Syntax: DataFrame.insert(loc, column, value, allow_duplicates = False)
Return: None
Code: Let’s create a Dataframe.
Python3
# Importing pandas libraryimport pandas as pd # dictionaryvalues = {'col2': [6, 7, 8, 9, 10], 'col3': [11, 12, 13, 14, 15]} # Creating dataframedf = pd.DataFrame(values) # show the dataframedf
Output:
Example 1: Inserting column at the beginning of the dataframe.
Python3
# Importing pandas libraryimport pandas as pd # dictionaryvalues = {'col2': [6, 7, 8, 9, 10], 'col3': [11, 12, 13, 14, 15]} # Creating dataframedf = pd.DataFrame(values) # New column to be addednew_col = [1, 2, 3, 4, 5] # Inserting the column at the# beginning in the DataFramedf.insert(loc = 0, column = 'col1', value = new_col)# show the dataframedf
Output:
Example 2: Inserting column in the middle of the dataframe
Python3
# Importing pandas libraryimport pandas as pd # dictionaryvalues = {'col2': [6, 7, 8, 9, 10], 'col3': [11, 12, 13, 14, 15]} # Creating dataframedf = pd.DataFrame(values) # New column to be addednew_col = [1, 2, 3, 4, 5] # Inserting the column at the# middle of the DataFramedf.insert(loc = 1, column = 'col1', value = new_col)# show the dataframedf
Output:
Example 3: Inserting column at the end of the dataframe
Python3
# Importing pandas libraryimport pandas as pd # dictionaryvalues = {'col2': [6, 7, 8, 9, 10], 'col3': [11, 12, 13, 14, 15]} # Creating dataframedf = pd.DataFrame(values) # New column to be addednew_col = [1, 2, 3, 4, 5] # Inserting the column at the# end of the DataFrame# df.columns gives index array # of column namesdf.insert(loc = len(df.columns), column = 'col1', value = new_col)# show the dataframedf
Output:
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n26 Jul, 2020"
},
{
"code": null,
"e": 25668,
"s": 25537,
"text": "In this article, we will use Dataframe.insert() method of Pandas to insert a new column at a specific column index in a dataframe."
},
{
"code": null,
"e": 25739,
"s": 25668,
"text": "Syntax: DataFrame.insert(loc, column, value, allow_duplicates = False)"
},
{
"code": null,
"e": 25752,
"s": 25739,
"text": "Return: None"
},
{
"code": null,
"e": 25784,
"s": 25752,
"text": "Code: Let’s create a Dataframe."
},
{
"code": null,
"e": 25792,
"s": 25784,
"text": "Python3"
},
{
"code": "# Importing pandas libraryimport pandas as pd # dictionaryvalues = {'col2': [6, 7, 8, 9, 10], 'col3': [11, 12, 13, 14, 15]} # Creating dataframedf = pd.DataFrame(values) # show the dataframedf",
"e": 26034,
"s": 25792,
"text": null
},
{
"code": null,
"e": 26042,
"s": 26034,
"text": "Output:"
},
{
"code": null,
"e": 26105,
"s": 26042,
"text": "Example 1: Inserting column at the beginning of the dataframe."
},
{
"code": null,
"e": 26113,
"s": 26105,
"text": "Python3"
},
{
"code": "# Importing pandas libraryimport pandas as pd # dictionaryvalues = {'col2': [6, 7, 8, 9, 10], 'col3': [11, 12, 13, 14, 15]} # Creating dataframedf = pd.DataFrame(values) # New column to be addednew_col = [1, 2, 3, 4, 5] # Inserting the column at the# beginning in the DataFramedf.insert(loc = 0, column = 'col1', value = new_col)# show the dataframedf",
"e": 26535,
"s": 26113,
"text": null
},
{
"code": null,
"e": 26544,
"s": 26535,
"text": "Output: "
},
{
"code": null,
"e": 26603,
"s": 26544,
"text": "Example 2: Inserting column in the middle of the dataframe"
},
{
"code": null,
"e": 26611,
"s": 26603,
"text": "Python3"
},
{
"code": "# Importing pandas libraryimport pandas as pd # dictionaryvalues = {'col2': [6, 7, 8, 9, 10], 'col3': [11, 12, 13, 14, 15]} # Creating dataframedf = pd.DataFrame(values) # New column to be addednew_col = [1, 2, 3, 4, 5] # Inserting the column at the# middle of the DataFramedf.insert(loc = 1, column = 'col1', value = new_col)# show the dataframedf",
"e": 27030,
"s": 26611,
"text": null
},
{
"code": null,
"e": 27039,
"s": 27030,
"text": "Output: "
},
{
"code": null,
"e": 27095,
"s": 27039,
"text": "Example 3: Inserting column at the end of the dataframe"
},
{
"code": null,
"e": 27103,
"s": 27095,
"text": "Python3"
},
{
"code": "# Importing pandas libraryimport pandas as pd # dictionaryvalues = {'col2': [6, 7, 8, 9, 10], 'col3': [11, 12, 13, 14, 15]} # Creating dataframedf = pd.DataFrame(values) # New column to be addednew_col = [1, 2, 3, 4, 5] # Inserting the column at the# end of the DataFrame# df.columns gives index array # of column namesdf.insert(loc = len(df.columns), column = 'col1', value = new_col)# show the dataframedf",
"e": 27581,
"s": 27103,
"text": null
},
{
"code": null,
"e": 27591,
"s": 27581,
"text": "Output: "
},
{
"code": null,
"e": 27615,
"s": 27591,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 27629,
"s": 27615,
"text": "Python-pandas"
},
{
"code": null,
"e": 27636,
"s": 27629,
"text": "Python"
},
{
"code": null,
"e": 27734,
"s": 27636,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27766,
"s": 27734,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27808,
"s": 27766,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27850,
"s": 27808,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27877,
"s": 27850,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27933,
"s": 27877,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27955,
"s": 27933,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27994,
"s": 27955,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28025,
"s": 27994,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28054,
"s": 28025,
"text": "Create a directory in Python"
}
] |
D3.js schemePaired Method - GeeksforGeeks
|
23 Aug, 2020
The d3.schemePaired method in D3.js is used to return an array of twelve categorical colors which is returned as RGB hexadecimal strings.
Syntax:
d3.schemePaired
Parameters: This function does not accept any parameter.
Return Value: It returns an RGB hexadecimal string.
Example 1:
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" path1tent="width=device-width, initial-scale=1.0"/> <script src= " https://d3js.org/d3.v4.min.js"> </script> <script src= " https://d3js.org/d3-color.v1.min.js"> </script> <script src= " https://d3js.org/d3-interpolate.v1.min.js"> </script> <script src= " https://d3js.org/d3-scale-chromatic.v1.min.js"> </script> </head> <body> <center> <h1 style="color:green;">GeeksForGeeks</h1> <h3>D3.js schemePaired Method</h3> <script> document.write(d3.schemePaired[0]+"<br>"); document.write(d3.schemePaired[1]+"<br>"); document.write(d3.schemePaired[2]+"<br>"); document.write(d3.schemePaired[3]+"<br>"); document.write(d3.schemePaired[4]+"<br>"); document.write(d3.schemePaired[5]+"<br>"); document.write(d3.schemePaired[6]+"<br>"); document.write(d3.schemePaired[7]+"<br>"); document.write(d3.schemePaired[8]+"<br>"); document.write(d3.schemePaired[9]+"<br>"); document.write(d3.schemePaired[10]+"<br>"); document.write(d3.schemePaired[11]+"<br>"); </script> </center></body> </html>
Output:
Example 2:
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" path1tent="width=device-width, initial-scale=1.0"/> <script src= " https://d3js.org/d3.v4.min.js"> </script> <script src= " https://d3js.org/d3-color.v1.min.js"> </script> <script src= " https://d3js.org/d3-interpolate.v1.min.js"> </script> <script src= " https://d3js.org/d3-scale-chromatic.v1.min.js"> </script> <style> div { padding: 3px; width: fit-content; height: 20px; width: 250px; } </style> </head> <body> <center> <h1 style="color:green;">GeeksForGeeks</h1> <h3>D3.js schemePaired Method</h3> <div class="b1"> <span> D3.schemePaired[0] </span> </div> <div class="b2"> <span> D3.schemePaired[1] </span> </div> <div class="b3"> <span> D3.schemePaired[2] </span> </div> <div class="b4"> <span> D3.schemePaired[3] </span> </div> <div class="b5"> <span> D3.schemePaired[4] </span> </div> <div class="b6"> <span> D3.schemePaired[5] </span> </div> <div class="b7"> <span> D3.schemePaired[6] </span> </div> <div class="b8"> <span> D3.schemePaired[7] </span> </div> <div class="b9"> <span> D3.schemePaired[8] </span> </div> <div class="b10"> <span> D3.schemePaired[9] </span> </div> <div class="b11"> <span> D3.schemePaired[10] </span> </div> <div class="b12"> <span> D3.schemePaired[11] </span> </div> <script> // Array of colors is given let color1 = d3.schemePaired[0]; let color2 = d3.schemePaired[1]; let color3 = d3.schemePaired[2]; let color4 = d3.schemePaired[3]; let color5 = d3.schemePaired[4]; let color6 = d3.schemePaired[5]; let color7 = d3.schemePaired[6]; let color8 = d3.schemePaired[7]; let color9 = d3.schemePaired[8]; let color10 = d3.schemePaired[9]; let color11 = d3.schemePaired[10]; let color12 = d3.schemePaired[11]; let b1 = document.querySelector(".b1"); let b2 = document.querySelector(".b2"); let b3 = document.querySelector(".b3"); let b4 = document.querySelector(".b4"); let b5 = document.querySelector(".b5"); let b6 = document.querySelector(".b6"); let b7 = document.querySelector(".b7"); let b8 = document.querySelector(".b8"); let b9 = document.querySelector(".b9"); let b10 = document.querySelector(".b10"); let b11 = document.querySelector(".b11"); let b12 = document.querySelector(".b12"); b1.style.backgroundColor = color1; b2.style.backgroundColor = color2; b3.style.backgroundColor = color3; b4.style.backgroundColor = color4; b5.style.backgroundColor = color5; b6.style.backgroundColor = color6; b7.style.backgroundColor = color7; b8.style.backgroundColor = color8; b9.style.backgroundColor = color9; b10.style.backgroundColor = color10; b11.style.backgroundColor = color11; b12.style.backgroundColor = color12; </script> </center></body> </html>
Output:
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26545,
"s": 26517,
"text": "\n23 Aug, 2020"
},
{
"code": null,
"e": 26683,
"s": 26545,
"text": "The d3.schemePaired method in D3.js is used to return an array of twelve categorical colors which is returned as RGB hexadecimal strings."
},
{
"code": null,
"e": 26691,
"s": 26683,
"text": "Syntax:"
},
{
"code": null,
"e": 26707,
"s": 26691,
"text": "d3.schemePaired"
},
{
"code": null,
"e": 26764,
"s": 26707,
"text": "Parameters: This function does not accept any parameter."
},
{
"code": null,
"e": 26816,
"s": 26764,
"text": "Return Value: It returns an RGB hexadecimal string."
},
{
"code": null,
"e": 26827,
"s": 26816,
"text": "Example 1:"
},
{
"code": null,
"e": 26832,
"s": 26827,
"text": "HTML"
},
{
"code": "<!DOCTYPE html> <html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" path1tent=\"width=device-width, initial-scale=1.0\"/> <script src= \" https://d3js.org/d3.v4.min.js\"> </script> <script src= \" https://d3js.org/d3-color.v1.min.js\"> </script> <script src= \" https://d3js.org/d3-interpolate.v1.min.js\"> </script> <script src= \" https://d3js.org/d3-scale-chromatic.v1.min.js\"> </script> </head> <body> <center> <h1 style=\"color:green;\">GeeksForGeeks</h1> <h3>D3.js schemePaired Method</h3> <script> document.write(d3.schemePaired[0]+\"<br>\"); document.write(d3.schemePaired[1]+\"<br>\"); document.write(d3.schemePaired[2]+\"<br>\"); document.write(d3.schemePaired[3]+\"<br>\"); document.write(d3.schemePaired[4]+\"<br>\"); document.write(d3.schemePaired[5]+\"<br>\"); document.write(d3.schemePaired[6]+\"<br>\"); document.write(d3.schemePaired[7]+\"<br>\"); document.write(d3.schemePaired[8]+\"<br>\"); document.write(d3.schemePaired[9]+\"<br>\"); document.write(d3.schemePaired[10]+\"<br>\"); document.write(d3.schemePaired[11]+\"<br>\"); </script> </center></body> </html>",
"e": 28089,
"s": 26832,
"text": null
},
{
"code": null,
"e": 28097,
"s": 28089,
"text": "Output:"
},
{
"code": null,
"e": 28108,
"s": 28097,
"text": "Example 2:"
},
{
"code": null,
"e": 28113,
"s": 28108,
"text": "HTML"
},
{
"code": "<!DOCTYPE html> <html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" path1tent=\"width=device-width, initial-scale=1.0\"/> <script src= \" https://d3js.org/d3.v4.min.js\"> </script> <script src= \" https://d3js.org/d3-color.v1.min.js\"> </script> <script src= \" https://d3js.org/d3-interpolate.v1.min.js\"> </script> <script src= \" https://d3js.org/d3-scale-chromatic.v1.min.js\"> </script> <style> div { padding: 3px; width: fit-content; height: 20px; width: 250px; } </style> </head> <body> <center> <h1 style=\"color:green;\">GeeksForGeeks</h1> <h3>D3.js schemePaired Method</h3> <div class=\"b1\"> <span> D3.schemePaired[0] </span> </div> <div class=\"b2\"> <span> D3.schemePaired[1] </span> </div> <div class=\"b3\"> <span> D3.schemePaired[2] </span> </div> <div class=\"b4\"> <span> D3.schemePaired[3] </span> </div> <div class=\"b5\"> <span> D3.schemePaired[4] </span> </div> <div class=\"b6\"> <span> D3.schemePaired[5] </span> </div> <div class=\"b7\"> <span> D3.schemePaired[6] </span> </div> <div class=\"b8\"> <span> D3.schemePaired[7] </span> </div> <div class=\"b9\"> <span> D3.schemePaired[8] </span> </div> <div class=\"b10\"> <span> D3.schemePaired[9] </span> </div> <div class=\"b11\"> <span> D3.schemePaired[10] </span> </div> <div class=\"b12\"> <span> D3.schemePaired[11] </span> </div> <script> // Array of colors is given let color1 = d3.schemePaired[0]; let color2 = d3.schemePaired[1]; let color3 = d3.schemePaired[2]; let color4 = d3.schemePaired[3]; let color5 = d3.schemePaired[4]; let color6 = d3.schemePaired[5]; let color7 = d3.schemePaired[6]; let color8 = d3.schemePaired[7]; let color9 = d3.schemePaired[8]; let color10 = d3.schemePaired[9]; let color11 = d3.schemePaired[10]; let color12 = d3.schemePaired[11]; let b1 = document.querySelector(\".b1\"); let b2 = document.querySelector(\".b2\"); let b3 = document.querySelector(\".b3\"); let b4 = document.querySelector(\".b4\"); let b5 = document.querySelector(\".b5\"); let b6 = document.querySelector(\".b6\"); let b7 = document.querySelector(\".b7\"); let b8 = document.querySelector(\".b8\"); let b9 = document.querySelector(\".b9\"); let b10 = document.querySelector(\".b10\"); let b11 = document.querySelector(\".b11\"); let b12 = document.querySelector(\".b12\"); b1.style.backgroundColor = color1; b2.style.backgroundColor = color2; b3.style.backgroundColor = color3; b4.style.backgroundColor = color4; b5.style.backgroundColor = color5; b6.style.backgroundColor = color6; b7.style.backgroundColor = color7; b8.style.backgroundColor = color8; b9.style.backgroundColor = color9; b10.style.backgroundColor = color10; b11.style.backgroundColor = color11; b12.style.backgroundColor = color12; </script> </center></body> </html>",
"e": 31721,
"s": 28113,
"text": null
},
{
"code": null,
"e": 31729,
"s": 31721,
"text": "Output:"
},
{
"code": null,
"e": 31735,
"s": 31729,
"text": "D3.js"
},
{
"code": null,
"e": 31746,
"s": 31735,
"text": "JavaScript"
},
{
"code": null,
"e": 31763,
"s": 31746,
"text": "Web Technologies"
},
{
"code": null,
"e": 31861,
"s": 31763,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31901,
"s": 31861,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 31962,
"s": 31901,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 32003,
"s": 31962,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 32025,
"s": 32003,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 32079,
"s": 32025,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 32119,
"s": 32079,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 32152,
"s": 32119,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 32195,
"s": 32152,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 32245,
"s": 32195,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Hexadecimal equivalents in Binary Valued Graph - GeeksforGeeks
|
24 Nov, 2021
Given a binary valued undirected graph with V vertices and E edges, the task is to find the hexadecimal equivalents of all the connected components of the graph. A binary valued graph can be considered as having only binary numbers (0 or 1) as the vertex values.
Examples:
Input: E = 4, V = 7
Output: Chain = 0 1 Hexadecimal equivalent = 1 Chain = 0 0 0 Hexadecimal equivalent = 0 Chain = 1 1 Hexadecimal equivalent = 3 Explanation: In case of the first connected component, the binary chain is [0, 1] Hence, the binary string = “01” and binary number = 01 So, the hexadecimal equivalent = 1
Input: E = 6, V = 10
Output: Chain = 1 Hexadecimal equivalent = 1 Chain = 0 0 1 0 Hexadecimal equivalent = 2 Chain = 1 1 0 Hexadecimal equivalent = 6 Chain = 1 0 Hexadecimal equivalent = 2
Approach: The idea is to use Depth First Search Traversal to keep track of the connected components in the undirected graph as explained in this article. For each connected component, the binary string is displayed and the equivalent hexadecimal value is calculated from the binary value as explained in this article and printed.
Below is the implementation of the above approach:
C++
Java
Python3
// C++ implementation to find// hexadecimal equivalents of// all connected components#include <bits/stdc++.h>using namespace std; // Function to traverse the undirected// graph using the Depth first traversalvoid depthFirst(int v, vector<int> graph[], vector<bool>& visited, vector<int>& storeChain){ // Marking the visited // vertex as true visited[v] = true; // Store the connected chain storeChain.push_back(v); for (auto i : graph[v]) { if (visited[i] == false) { // Recursive call to // the DFS algorithm depthFirst(i, graph, visited, storeChain); } }} // Function to create map between binary// number and its equivalent hexadecimalvoid createMap(unordered_map<string, char>* um){ (*um)["0000"] = '0'; (*um)["0001"] = '1'; (*um)["0010"] = '2'; (*um)["0011"] = '3'; (*um)["0100"] = '4'; (*um)["0101"] = '5'; (*um)["0110"] = '6'; (*um)["0111"] = '7'; (*um)["1000"] = '8'; (*um)["1001"] = '9'; (*um)["1010"] = 'A'; (*um)["1011"] = 'B'; (*um)["1100"] = 'C'; (*um)["1101"] = 'D'; (*um)["1110"] = 'E'; (*um)["1111"] = 'F';} // Function to return hexadecimal// equivalent of each connected// componentstring hexaDecimal(string bin){ int l = bin.size(); int t = bin.find_first_of('.'); // Length of string before '.' int len_left = t != -1 ? t : l; // Add min 0's in the beginning // to make left substring length // divisible by 4 for (int i = 1; i <= (4 - len_left % 4) % 4; i++) bin = '0' + bin; // If decimal point exists if (t != -1) { // Length of string after '.' int len_right = l - len_left - 1; // Add min 0's in the end to // make right substring length // divisible by 4 for (int i = 1; i <= (4 - len_right % 4) % 4; i++) bin = bin + '0'; } // Create map between binary // and its equivalent hex code unordered_map<string, char> bin_hex_map; createMap(&bin_hex_map); int i = 0; string hex = ""; while (1) { // Extract from left, // substring of size 4 and add // its hex code hex += bin_hex_map[bin.substr(i, 4)]; i += 4; if (i == bin.size()) break; // If '.' is encountered add it // to result if (bin.at(i) == '.') { hex += '.'; i++; } } // Required hexadecimal number return hex;} // Function to find the hexadecimal// equivalents of all connected// componentsvoid hexValue( vector<int> graph[], int vertices, vector<int> values){ // Initializing boolean array // to mark visited vertices vector<bool> visited(10001, false); // Following loop invokes // DFS algorithm for (int i = 1; i <= vertices; i++) { if (visited[i] == false) { // Variable to hold // temporary length int sizeChain; // Container to store // each chain vector<int> storeChain; // DFS algorithm depthFirst(i, graph, visited, storeChain); // Variable to hold each // chain size sizeChain = storeChain.size(); // Container to store // values of vertices of // individual chains int chainValues[sizeChain + 1]; // Storing the values of // each chain for (int i = 0; i < sizeChain; i++) { int temp = values[storeChain[i] - 1]; chainValues[i] = temp; } // Printing binary chain cout << "Chain = "; for (int i = 0; i < sizeChain; i++) { cout << chainValues[i] << " "; } cout << "\t"; // Converting the array // with vertex // values to a binary string // using string stream stringstream ss; ss << chainValues[0]; string s = ss.str(); for (int i = 1; i < sizeChain; i++) { stringstream ss1; ss1 << chainValues[i]; string s1 = ss1.str(); s.append(s1); } // Printing the hexadecimal // values cout << "Hexadecimal " << "equivalent = "; cout << hexaDecimal(s) << endl; } }} // Driver Programint main(){ // Initializing graph in the // form of adjacency list vector<int> graph[1001]; // Defining the number of // edges and vertices int E, V; E = 4; V = 7; // Assigning the values // for each vertex of the // undirected graph vector<int> values; values.push_back(0); values.push_back(1); values.push_back(1); values.push_back(1); values.push_back(0); values.push_back(1); values.push_back(1); // Constructing the // undirected graph graph[1].push_back(2); graph[2].push_back(1); graph[3].push_back(4); graph[4].push_back(3); graph[4].push_back(5); graph[5].push_back(4); graph[6].push_back(5); graph[5].push_back(6); graph[6].push_back(7); graph[7].push_back(6); hexValue(graph, V, values); return 0;}
// Java implementation to find // hexadecimal equivalents of // all connected components import java.io.*;import java.util.*; class GFG{ // Function to traverse the undirected// graph using the Depth first traversalstatic void depthFirst(int v, List<List<Integer>> graph, boolean[] visited, List<Integer> storeChain){ // Marking the visited // vertex as true visited[v] = true; // Store the connected chain storeChain.add(v); for(int i : graph.get(v)) { if (visited[i] == false) { // Recursive call to // the DFS algorithm depthFirst(i, graph, visited, storeChain); } }} // Function to create map between binary// number and its equivalent hexadecimalstatic void createMap(Map<String, Character> um){ um.put("0000", '0'); um.put("0001", '1'); um.put("0010", '2'); um.put("0011", '3'); um.put("0100", '4'); um.put("0101", '5'); um.put("0110", '6'); um.put("0111", '7'); um.put("1000", '8'); um.put("1001", '9'); um.put("1010", 'A'); um.put("1011", 'B'); um.put("1100", 'C'); um.put("1101", 'D'); um.put("1110", 'E'); um.put("1111", 'F');} // Function to return hexadecimal// equivalent of each connected// componentstatic String hexaDecimal(String bin){ int l = bin.length(); int t = bin.indexOf('.'); // Length of string before '.' int len_left = t != -1 ? t : l; // Add min 0's in the beginning to make // left substring length divisible by 4 for(int i = 1; i <= (4 - len_left % 4) % 4; i++) bin = '0' + bin; // If decimal point exists if (t != -1) { // Length of string after '.' int len_right = l - len_left - 1; // Add min 0's in the end to make right // substring length divisible by 4 for(int i = 1; i <= (4 - len_right % 4) % 4; i++) bin = bin + '0'; } // Create map between binary and its // equivalent hex code Map<String, Character> bin_hex_map = new HashMap<String, Character>(); createMap(bin_hex_map); int i = 0; String hex = ""; while (true) { // One by one extract from left, substring // of size 4 and add its hex code hex += bin_hex_map.get(bin.substring(i, i + 4)); i += 4; if (i == bin.length()) break; // If '.' is encountered add it // to result if (bin.charAt(i) == '.') { hex += '.'; i++; } } // Required hexadecimal number return hex;} // Function to find the hexadecimal// equivalents of all connected// componentsstatic void hexValue(List<List<Integer>> graph, int vertices, List<Integer> values){ // Initializing boolean array // to mark visited vertices boolean[] visited = new boolean[1001]; // Following loop invokes DFS algorithm for(int i = 1; i <= vertices; i++) { if (visited[i] == false) { // Variable to hold // temporary length int sizeChain; // Container to store each chain List<Integer> storeChain = new ArrayList<Integer>(); // DFS algorithm depthFirst(i, graph, visited, storeChain); // Variable to hold each chain size sizeChain = storeChain.size(); // Container to store values // of vertices of individual chains int[] chainValues = new int[sizeChain + 1]; // Storing the values of each chain for(int j = 0; j < sizeChain; j++) { int temp = values.get( storeChain.get(j) - 1); chainValues[j] = temp; } // Printing binary chain System.out.print("Chain = "); for(int j = 0; j < sizeChain; j++) { System.out.print(chainValues[j] + " "); } System.out.println(); System.out.print("\t"); // Converting the array with // vertex values to a binary // string String s = ""; for(int j = 0; j < sizeChain; j++) { String s1 = String.valueOf( chainValues[j]); s += s1; } // Printing the hexadecimal // values System.out.println("Hexadecimal " + "equivalent = " + hexaDecimal(s)); } }} // Driver codepublic static void main(String[] args){ // Initializing graph in the // form of adjacency list @SuppressWarnings("unchecked") List<List<Integer>> graph = new ArrayList(); for(int i = 0; i < 1001; i++) graph.add(new ArrayList<Integer>()); // Defining the number // of edges and vertices int E = 4, V = 7; // Assigning the values for each // vertex of the undirected graph List<Integer> values = new ArrayList<Integer>(); values.add(0); values.add(1); values.add(1); values.add(1); values.add(0); values.add(1); values.add(1); // Constructing the undirected graph graph.get(1).add(2); graph.get(2).add(1); graph.get(3).add(4); graph.get(4).add(3); graph.get(4).add(5); graph.get(5).add(4); graph.get(6).add(5); graph.get(5).add(6); graph.get(6).add(7); graph.get(7).add(6); hexValue(graph, V, values);}} // This code is contributed by jithin
# Python3 implementation to find# hexadecimal equivalents of# all connected components # Function to traverse the undirected# graph using the Depth first traversaldef depthFirst(v, graph, visited, storeChain): # Marking the visited # vertex as true visited[v] = True # Store the connected chain storeChain.append(v) for i in graph[v] : if not visited[i] : # Recursive call to # the DFS algorithm depthFirst(i, graph, visited, storeChain) # Function to create map between binary# number and its equivalent hexadecimaldef createMap(um): um["0000"] = '0' um["0001"] = '1' um["0010"] = '2' um["0011"] = '3' um["0100"] = '4' um["0101"] = '5' um["0110"] = '6' um["0111"] = '7' um["1000"] = '8' um["1001"] = '9' um["1010"] = 'A' um["1011"] = 'B' um["1100"] = 'C' um["1101"] = 'D' um["1110"] = 'E' um["1111"] = 'F' # Function to return hexadecimal# equivalent of each connected# componentdef hexaDecimal(bn): l = len(bn) t = bn.find('.') # Length of string before '.' len_left = t if t != -1 else l # Add min 0's in the beginning # to make left substring length # divisible by 4 for i in range(1,((4 - len_left % 4) % 4)+1): bn = '0' + bn # If decimal point exists if (t != -1) : # Length of string after '.' len_right = l - len_left - 1 # Add min 0's in the end to # make right substring length # divisible by 4 for i in range(1,((4 - len_right % 4) % 4)+1): bn = bn + '0' # Create map between binary # and its equivalent hx code bin_hex_map=dict() createMap(bin_hex_map) i = 0 hx = "" while (True) : # Extract from left, # substring of size 4 and add # its hx code hx += bin_hex_map[bn[i: i+4]] i += 4 if (i == len(bn)): break # If '.' is encountered add it # to result if (bn[i] == '.') : hx += '.' i+=1 # Required hexadecimal number return hx # Function to find the hexadecimal# equivalents of all connected# componentsdef hexValue(graph, vertices, values): # Initializing boolean array # to mark visited vertices visited=[False]*10001 # Following loop invokes # DFS algorithm for i in range(1,vertices+1): if not visited[i]: # Variable to hold # temporary length sizeChain=0 # Container to store # each chain storeChain=[] # DFS algorithm depthFirst(i, graph, visited, storeChain) # Variable to hold each # chain size sizeChain = len(storeChain) # Container to store # values of vertices of # individual chains chainValues=[-1]*(sizeChain + 1) # Storing the values of # each chain for i in range(sizeChain): temp = values[storeChain[i] - 1] chainValues[i] = temp # Printing binary chain print("Chain =",end=" ") for i in range(sizeChain) : print(chainValues[i],end=" ") print("\t",end="") # Converting the array # with vertex # values to a binary string s=[] for i in range(sizeChain): s.append(str(chainValues[i])) s=''.join(s) # Printing the hexadecimal # values print("Hexadecimal equivalent =",hexaDecimal(s)) # Driver Programif __name__=='__main__': # Initializing graph in the # form of adjacency list graph=[[] for _ in range(1001)] # Defining the number of # edges and vertices E = 4 V = 7 # Assigning the values # for each vertex of the # undirected graph values=[] values.append(0) values.append(1) values.append(1) values.append(1) values.append(0) values.append(1) values.append(1) # Constructing the # undirected graph graph[1].append(2) graph[2].append(1) graph[3].append(4) graph[4].append(3) graph[4].append(5) graph[5].append(4) graph[6].append(5) graph[5].append(6) graph[6].append(7) graph[7].append(6) hexValue(graph, V, values)
Chain = 0 1
Hexadecimal equivalent = 1
Chain = 1 1 0 1 1
Hexadecimal equivalent = 1B
Time Complexity: O(V2) The DFS algorithm requires O(V + E) complexity, where V, E are the vertices and edges of the undirected graph. Further, the hexadecimal equivalent is obtained at each iteration which requires an additional O(V) complexity to compute. Hence, the overall complexity is O(V2).
Auxiliary Space: O(V)
jithin
pankajsharmagfg
amartyaghoshgfg
base-conversion
binary-representation
connected-components
Data Structures
DFS
Algorithms
Competitive Programming
Data Structures
Graph
Strings
Data Structures
Strings
DFS
Graph
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
How to Start Learning DSA?
Difference between Algorithm, Pseudocode and Program
K means Clustering - Introduction
Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
Competitive Programming - A Complete Guide
Practice for cracking any coding interview
Arrow operator -> in C/C++ with Examples
Prefix Sum Array - Implementation and Applications in Competitive Programming
Fast I/O for Competitive Programming
|
[
{
"code": null,
"e": 25917,
"s": 25889,
"text": "\n24 Nov, 2021"
},
{
"code": null,
"e": 26180,
"s": 25917,
"text": "Given a binary valued undirected graph with V vertices and E edges, the task is to find the hexadecimal equivalents of all the connected components of the graph. A binary valued graph can be considered as having only binary numbers (0 or 1) as the vertex values."
},
{
"code": null,
"e": 26192,
"s": 26180,
"text": "Examples: "
},
{
"code": null,
"e": 26213,
"s": 26192,
"text": "Input: E = 4, V = 7 "
},
{
"code": null,
"e": 26527,
"s": 26213,
"text": "Output: Chain = 0 1 Hexadecimal equivalent = 1 Chain = 0 0 0 Hexadecimal equivalent = 0 Chain = 1 1 Hexadecimal equivalent = 3 Explanation: In case of the first connected component, the binary chain is [0, 1] Hence, the binary string = “01” and binary number = 01 So, the hexadecimal equivalent = 1"
},
{
"code": null,
"e": 26549,
"s": 26527,
"text": "Input: E = 6, V = 10 "
},
{
"code": null,
"e": 26738,
"s": 26549,
"text": "Output: Chain = 1 Hexadecimal equivalent = 1 Chain = 0 0 1 0 Hexadecimal equivalent = 2 Chain = 1 1 0 Hexadecimal equivalent = 6 Chain = 1 0 Hexadecimal equivalent = 2 "
},
{
"code": null,
"e": 27069,
"s": 26738,
"text": "Approach: The idea is to use Depth First Search Traversal to keep track of the connected components in the undirected graph as explained in this article. For each connected component, the binary string is displayed and the equivalent hexadecimal value is calculated from the binary value as explained in this article and printed. "
},
{
"code": null,
"e": 27122,
"s": 27069,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27126,
"s": 27122,
"text": "C++"
},
{
"code": null,
"e": 27131,
"s": 27126,
"text": "Java"
},
{
"code": null,
"e": 27139,
"s": 27131,
"text": "Python3"
},
{
"code": "// C++ implementation to find// hexadecimal equivalents of// all connected components#include <bits/stdc++.h>using namespace std; // Function to traverse the undirected// graph using the Depth first traversalvoid depthFirst(int v, vector<int> graph[], vector<bool>& visited, vector<int>& storeChain){ // Marking the visited // vertex as true visited[v] = true; // Store the connected chain storeChain.push_back(v); for (auto i : graph[v]) { if (visited[i] == false) { // Recursive call to // the DFS algorithm depthFirst(i, graph, visited, storeChain); } }} // Function to create map between binary// number and its equivalent hexadecimalvoid createMap(unordered_map<string, char>* um){ (*um)[\"0000\"] = '0'; (*um)[\"0001\"] = '1'; (*um)[\"0010\"] = '2'; (*um)[\"0011\"] = '3'; (*um)[\"0100\"] = '4'; (*um)[\"0101\"] = '5'; (*um)[\"0110\"] = '6'; (*um)[\"0111\"] = '7'; (*um)[\"1000\"] = '8'; (*um)[\"1001\"] = '9'; (*um)[\"1010\"] = 'A'; (*um)[\"1011\"] = 'B'; (*um)[\"1100\"] = 'C'; (*um)[\"1101\"] = 'D'; (*um)[\"1110\"] = 'E'; (*um)[\"1111\"] = 'F';} // Function to return hexadecimal// equivalent of each connected// componentstring hexaDecimal(string bin){ int l = bin.size(); int t = bin.find_first_of('.'); // Length of string before '.' int len_left = t != -1 ? t : l; // Add min 0's in the beginning // to make left substring length // divisible by 4 for (int i = 1; i <= (4 - len_left % 4) % 4; i++) bin = '0' + bin; // If decimal point exists if (t != -1) { // Length of string after '.' int len_right = l - len_left - 1; // Add min 0's in the end to // make right substring length // divisible by 4 for (int i = 1; i <= (4 - len_right % 4) % 4; i++) bin = bin + '0'; } // Create map between binary // and its equivalent hex code unordered_map<string, char> bin_hex_map; createMap(&bin_hex_map); int i = 0; string hex = \"\"; while (1) { // Extract from left, // substring of size 4 and add // its hex code hex += bin_hex_map[bin.substr(i, 4)]; i += 4; if (i == bin.size()) break; // If '.' is encountered add it // to result if (bin.at(i) == '.') { hex += '.'; i++; } } // Required hexadecimal number return hex;} // Function to find the hexadecimal// equivalents of all connected// componentsvoid hexValue( vector<int> graph[], int vertices, vector<int> values){ // Initializing boolean array // to mark visited vertices vector<bool> visited(10001, false); // Following loop invokes // DFS algorithm for (int i = 1; i <= vertices; i++) { if (visited[i] == false) { // Variable to hold // temporary length int sizeChain; // Container to store // each chain vector<int> storeChain; // DFS algorithm depthFirst(i, graph, visited, storeChain); // Variable to hold each // chain size sizeChain = storeChain.size(); // Container to store // values of vertices of // individual chains int chainValues[sizeChain + 1]; // Storing the values of // each chain for (int i = 0; i < sizeChain; i++) { int temp = values[storeChain[i] - 1]; chainValues[i] = temp; } // Printing binary chain cout << \"Chain = \"; for (int i = 0; i < sizeChain; i++) { cout << chainValues[i] << \" \"; } cout << \"\\t\"; // Converting the array // with vertex // values to a binary string // using string stream stringstream ss; ss << chainValues[0]; string s = ss.str(); for (int i = 1; i < sizeChain; i++) { stringstream ss1; ss1 << chainValues[i]; string s1 = ss1.str(); s.append(s1); } // Printing the hexadecimal // values cout << \"Hexadecimal \" << \"equivalent = \"; cout << hexaDecimal(s) << endl; } }} // Driver Programint main(){ // Initializing graph in the // form of adjacency list vector<int> graph[1001]; // Defining the number of // edges and vertices int E, V; E = 4; V = 7; // Assigning the values // for each vertex of the // undirected graph vector<int> values; values.push_back(0); values.push_back(1); values.push_back(1); values.push_back(1); values.push_back(0); values.push_back(1); values.push_back(1); // Constructing the // undirected graph graph[1].push_back(2); graph[2].push_back(1); graph[3].push_back(4); graph[4].push_back(3); graph[4].push_back(5); graph[5].push_back(4); graph[6].push_back(5); graph[5].push_back(6); graph[6].push_back(7); graph[7].push_back(6); hexValue(graph, V, values); return 0;}",
"e": 32708,
"s": 27139,
"text": null
},
{
"code": "// Java implementation to find // hexadecimal equivalents of // all connected components import java.io.*;import java.util.*; class GFG{ // Function to traverse the undirected// graph using the Depth first traversalstatic void depthFirst(int v, List<List<Integer>> graph, boolean[] visited, List<Integer> storeChain){ // Marking the visited // vertex as true visited[v] = true; // Store the connected chain storeChain.add(v); for(int i : graph.get(v)) { if (visited[i] == false) { // Recursive call to // the DFS algorithm depthFirst(i, graph, visited, storeChain); } }} // Function to create map between binary// number and its equivalent hexadecimalstatic void createMap(Map<String, Character> um){ um.put(\"0000\", '0'); um.put(\"0001\", '1'); um.put(\"0010\", '2'); um.put(\"0011\", '3'); um.put(\"0100\", '4'); um.put(\"0101\", '5'); um.put(\"0110\", '6'); um.put(\"0111\", '7'); um.put(\"1000\", '8'); um.put(\"1001\", '9'); um.put(\"1010\", 'A'); um.put(\"1011\", 'B'); um.put(\"1100\", 'C'); um.put(\"1101\", 'D'); um.put(\"1110\", 'E'); um.put(\"1111\", 'F');} // Function to return hexadecimal// equivalent of each connected// componentstatic String hexaDecimal(String bin){ int l = bin.length(); int t = bin.indexOf('.'); // Length of string before '.' int len_left = t != -1 ? t : l; // Add min 0's in the beginning to make // left substring length divisible by 4 for(int i = 1; i <= (4 - len_left % 4) % 4; i++) bin = '0' + bin; // If decimal point exists if (t != -1) { // Length of string after '.' int len_right = l - len_left - 1; // Add min 0's in the end to make right // substring length divisible by 4 for(int i = 1; i <= (4 - len_right % 4) % 4; i++) bin = bin + '0'; } // Create map between binary and its // equivalent hex code Map<String, Character> bin_hex_map = new HashMap<String, Character>(); createMap(bin_hex_map); int i = 0; String hex = \"\"; while (true) { // One by one extract from left, substring // of size 4 and add its hex code hex += bin_hex_map.get(bin.substring(i, i + 4)); i += 4; if (i == bin.length()) break; // If '.' is encountered add it // to result if (bin.charAt(i) == '.') { hex += '.'; i++; } } // Required hexadecimal number return hex;} // Function to find the hexadecimal// equivalents of all connected// componentsstatic void hexValue(List<List<Integer>> graph, int vertices, List<Integer> values){ // Initializing boolean array // to mark visited vertices boolean[] visited = new boolean[1001]; // Following loop invokes DFS algorithm for(int i = 1; i <= vertices; i++) { if (visited[i] == false) { // Variable to hold // temporary length int sizeChain; // Container to store each chain List<Integer> storeChain = new ArrayList<Integer>(); // DFS algorithm depthFirst(i, graph, visited, storeChain); // Variable to hold each chain size sizeChain = storeChain.size(); // Container to store values // of vertices of individual chains int[] chainValues = new int[sizeChain + 1]; // Storing the values of each chain for(int j = 0; j < sizeChain; j++) { int temp = values.get( storeChain.get(j) - 1); chainValues[j] = temp; } // Printing binary chain System.out.print(\"Chain = \"); for(int j = 0; j < sizeChain; j++) { System.out.print(chainValues[j] + \" \"); } System.out.println(); System.out.print(\"\\t\"); // Converting the array with // vertex values to a binary // string String s = \"\"; for(int j = 0; j < sizeChain; j++) { String s1 = String.valueOf( chainValues[j]); s += s1; } // Printing the hexadecimal // values System.out.println(\"Hexadecimal \" + \"equivalent = \" + hexaDecimal(s)); } }} // Driver codepublic static void main(String[] args){ // Initializing graph in the // form of adjacency list @SuppressWarnings(\"unchecked\") List<List<Integer>> graph = new ArrayList(); for(int i = 0; i < 1001; i++) graph.add(new ArrayList<Integer>()); // Defining the number // of edges and vertices int E = 4, V = 7; // Assigning the values for each // vertex of the undirected graph List<Integer> values = new ArrayList<Integer>(); values.add(0); values.add(1); values.add(1); values.add(1); values.add(0); values.add(1); values.add(1); // Constructing the undirected graph graph.get(1).add(2); graph.get(2).add(1); graph.get(3).add(4); graph.get(4).add(3); graph.get(4).add(5); graph.get(5).add(4); graph.get(6).add(5); graph.get(5).add(6); graph.get(6).add(7); graph.get(7).add(6); hexValue(graph, V, values);}} // This code is contributed by jithin",
"e": 38460,
"s": 32708,
"text": null
},
{
"code": "# Python3 implementation to find# hexadecimal equivalents of# all connected components # Function to traverse the undirected# graph using the Depth first traversaldef depthFirst(v, graph, visited, storeChain): # Marking the visited # vertex as true visited[v] = True # Store the connected chain storeChain.append(v) for i in graph[v] : if not visited[i] : # Recursive call to # the DFS algorithm depthFirst(i, graph, visited, storeChain) # Function to create map between binary# number and its equivalent hexadecimaldef createMap(um): um[\"0000\"] = '0' um[\"0001\"] = '1' um[\"0010\"] = '2' um[\"0011\"] = '3' um[\"0100\"] = '4' um[\"0101\"] = '5' um[\"0110\"] = '6' um[\"0111\"] = '7' um[\"1000\"] = '8' um[\"1001\"] = '9' um[\"1010\"] = 'A' um[\"1011\"] = 'B' um[\"1100\"] = 'C' um[\"1101\"] = 'D' um[\"1110\"] = 'E' um[\"1111\"] = 'F' # Function to return hexadecimal# equivalent of each connected# componentdef hexaDecimal(bn): l = len(bn) t = bn.find('.') # Length of string before '.' len_left = t if t != -1 else l # Add min 0's in the beginning # to make left substring length # divisible by 4 for i in range(1,((4 - len_left % 4) % 4)+1): bn = '0' + bn # If decimal point exists if (t != -1) : # Length of string after '.' len_right = l - len_left - 1 # Add min 0's in the end to # make right substring length # divisible by 4 for i in range(1,((4 - len_right % 4) % 4)+1): bn = bn + '0' # Create map between binary # and its equivalent hx code bin_hex_map=dict() createMap(bin_hex_map) i = 0 hx = \"\" while (True) : # Extract from left, # substring of size 4 and add # its hx code hx += bin_hex_map[bn[i: i+4]] i += 4 if (i == len(bn)): break # If '.' is encountered add it # to result if (bn[i] == '.') : hx += '.' i+=1 # Required hexadecimal number return hx # Function to find the hexadecimal# equivalents of all connected# componentsdef hexValue(graph, vertices, values): # Initializing boolean array # to mark visited vertices visited=[False]*10001 # Following loop invokes # DFS algorithm for i in range(1,vertices+1): if not visited[i]: # Variable to hold # temporary length sizeChain=0 # Container to store # each chain storeChain=[] # DFS algorithm depthFirst(i, graph, visited, storeChain) # Variable to hold each # chain size sizeChain = len(storeChain) # Container to store # values of vertices of # individual chains chainValues=[-1]*(sizeChain + 1) # Storing the values of # each chain for i in range(sizeChain): temp = values[storeChain[i] - 1] chainValues[i] = temp # Printing binary chain print(\"Chain =\",end=\" \") for i in range(sizeChain) : print(chainValues[i],end=\" \") print(\"\\t\",end=\"\") # Converting the array # with vertex # values to a binary string s=[] for i in range(sizeChain): s.append(str(chainValues[i])) s=''.join(s) # Printing the hexadecimal # values print(\"Hexadecimal equivalent =\",hexaDecimal(s)) # Driver Programif __name__=='__main__': # Initializing graph in the # form of adjacency list graph=[[] for _ in range(1001)] # Defining the number of # edges and vertices E = 4 V = 7 # Assigning the values # for each vertex of the # undirected graph values=[] values.append(0) values.append(1) values.append(1) values.append(1) values.append(0) values.append(1) values.append(1) # Constructing the # undirected graph graph[1].append(2) graph[2].append(1) graph[3].append(4) graph[4].append(3) graph[4].append(5) graph[5].append(4) graph[6].append(5) graph[5].append(6) graph[6].append(7) graph[7].append(6) hexValue(graph, V, values)",
"e": 42921,
"s": 38460,
"text": null
},
{
"code": null,
"e": 43016,
"s": 42921,
"text": "Chain = 0 1\n Hexadecimal equivalent = 1\nChain = 1 1 0 1 1\n Hexadecimal equivalent = 1B"
},
{
"code": null,
"e": 43316,
"s": 43018,
"text": "Time Complexity: O(V2) The DFS algorithm requires O(V + E) complexity, where V, E are the vertices and edges of the undirected graph. Further, the hexadecimal equivalent is obtained at each iteration which requires an additional O(V) complexity to compute. Hence, the overall complexity is O(V2). "
},
{
"code": null,
"e": 43339,
"s": 43316,
"text": "Auxiliary Space: O(V) "
},
{
"code": null,
"e": 43346,
"s": 43339,
"text": "jithin"
},
{
"code": null,
"e": 43362,
"s": 43346,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 43378,
"s": 43362,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 43394,
"s": 43378,
"text": "base-conversion"
},
{
"code": null,
"e": 43416,
"s": 43394,
"text": "binary-representation"
},
{
"code": null,
"e": 43437,
"s": 43416,
"text": "connected-components"
},
{
"code": null,
"e": 43453,
"s": 43437,
"text": "Data Structures"
},
{
"code": null,
"e": 43457,
"s": 43453,
"text": "DFS"
},
{
"code": null,
"e": 43468,
"s": 43457,
"text": "Algorithms"
},
{
"code": null,
"e": 43492,
"s": 43468,
"text": "Competitive Programming"
},
{
"code": null,
"e": 43508,
"s": 43492,
"text": "Data Structures"
},
{
"code": null,
"e": 43514,
"s": 43508,
"text": "Graph"
},
{
"code": null,
"e": 43522,
"s": 43514,
"text": "Strings"
},
{
"code": null,
"e": 43538,
"s": 43522,
"text": "Data Structures"
},
{
"code": null,
"e": 43546,
"s": 43538,
"text": "Strings"
},
{
"code": null,
"e": 43550,
"s": 43546,
"text": "DFS"
},
{
"code": null,
"e": 43556,
"s": 43550,
"text": "Graph"
},
{
"code": null,
"e": 43567,
"s": 43556,
"text": "Algorithms"
},
{
"code": null,
"e": 43665,
"s": 43567,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 43690,
"s": 43665,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 43717,
"s": 43690,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 43770,
"s": 43717,
"text": "Difference between Algorithm, Pseudocode and Program"
},
{
"code": null,
"e": 43804,
"s": 43770,
"text": "K means Clustering - Introduction"
},
{
"code": null,
"e": 43871,
"s": 43804,
"text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete"
},
{
"code": null,
"e": 43914,
"s": 43871,
"text": "Competitive Programming - A Complete Guide"
},
{
"code": null,
"e": 43957,
"s": 43914,
"text": "Practice for cracking any coding interview"
},
{
"code": null,
"e": 43998,
"s": 43957,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 44076,
"s": 43998,
"text": "Prefix Sum Array - Implementation and Applications in Competitive Programming"
}
] |
Perl system Function
|
This function executes the command specified by PROGRAM, passing LIST as arguments to the command.
The return value is the exit status of the program as returned by the wait function. To obtain the actual exit value, divide by 256.
Following is the simple syntax for this function −
system PROGRAM, LIST
system PROGRAM
This function returns exit status of program as returned by wai
Following is the example code showing its basic usage −
#!/usr/bin/perl -w
system("ls -F /var > /tmp/t.tmp");
When above code is executed, it produces the following result −
A file in /tmp directory, check it out.
46 Lectures
4.5 hours
Devi Killada
11 Lectures
1.5 hours
Harshit Srivastava
30 Lectures
6 hours
TELCOMA Global
24 Lectures
2 hours
Mohammad Nauman
68 Lectures
7 hours
Stone River ELearning
58 Lectures
6.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2319,
"s": 2220,
"text": "This function executes the command specified by PROGRAM, passing LIST as arguments to the command."
},
{
"code": null,
"e": 2452,
"s": 2319,
"text": "The return value is the exit status of the program as returned by the wait function. To obtain the actual exit value, divide by 256."
},
{
"code": null,
"e": 2503,
"s": 2452,
"text": "Following is the simple syntax for this function −"
},
{
"code": null,
"e": 2541,
"s": 2503,
"text": "system PROGRAM, LIST\n\nsystem PROGRAM\n"
},
{
"code": null,
"e": 2605,
"s": 2541,
"text": "This function returns exit status of program as returned by wai"
},
{
"code": null,
"e": 2661,
"s": 2605,
"text": "Following is the example code showing its basic usage −"
},
{
"code": null,
"e": 2716,
"s": 2661,
"text": "#!/usr/bin/perl -w\n\nsystem(\"ls -F /var > /tmp/t.tmp\");"
},
{
"code": null,
"e": 2780,
"s": 2716,
"text": "When above code is executed, it produces the following result −"
},
{
"code": null,
"e": 2821,
"s": 2780,
"text": "A file in /tmp directory, check it out.\n"
},
{
"code": null,
"e": 2856,
"s": 2821,
"text": "\n 46 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 2870,
"s": 2856,
"text": " Devi Killada"
},
{
"code": null,
"e": 2905,
"s": 2870,
"text": "\n 11 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 2925,
"s": 2905,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 2958,
"s": 2925,
"text": "\n 30 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 2974,
"s": 2958,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 3007,
"s": 2974,
"text": "\n 24 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3024,
"s": 3007,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 3057,
"s": 3024,
"text": "\n 68 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3080,
"s": 3057,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 3115,
"s": 3080,
"text": "\n 58 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3138,
"s": 3115,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 3145,
"s": 3138,
"text": " Print"
},
{
"code": null,
"e": 3156,
"s": 3145,
"text": " Add Notes"
}
] |
Longest Repeating Subsequence | Practice | GeeksforGeeks
|
Given a string str, find the length of the longest repeating subsequence such that it can be found twice in the given string. The two identified subsequences A and B can use the same ith character from string str if and only if that ith character has different indices in A and B.
Example 1:
Input:
str = "axxzxy"
Output: 2
Explanation:
The given array with indexes looks like
a x x z x y
0 1 2 3 4 5
The longest subsequence is "xx".
It appears twice as explained below.
subsequence A
x x
0 1 <-- index of subsequence A
------
1 2 <-- index of str
subsequence B
x x
0 1 <-- index of subsequence B
------
2 4 <-- index of str
We are able to use character 'x'
(at index 2 in str) in both subsequences
as it appears on index 1 in subsequence A
and index 0 in subsequence B.
Example 2:
Input:
str = "axxxy"
Output: 2
Explanation:
The given array with indexes looks like
a x x x y
0 1 2 3 4
The longest subsequence is "xx".
It appears twice as explained below.
subsequence A
x x
0 1 <-- index of subsequence A
------
1 2 <-- index of str
subsequence B
x x
0 1 <-- index of subsequence B
------
2 3 <-- index of str
We are able to use character 'x'
(at index 2 in str) in both subsequences
as it appears on index 1 in subsequence A
and index 0 in subsequence B.
Your Task:
You don't need to read or print anything. Your task is to complete the LongestRepeatingSubsequence() which takes str as input parameter and returns the length of the longest repeating subsequnece.
Expected Time Complexity: O(n2)
Expected Space Complexity: O(n2)
Constraints:
1 <= |str| <= 103
-129
eeshagoyal2Admin7 months ago
The problem statement has been updated to avoid any ambiguity.
0
shishir17pandey2 weeks ago
int call(string a,string b,int n){ int dp[1001][1001]; for(int i=0;i<n;i++){ dp[i][0]=0; } for(int j=0;j<n;j++){ dp[0][j]=0; } for(int i=1;i<=n;i++){ for(int j=1;j<=n;j++){ if(a[i-1]==b[j-1] && i!=j){ dp[i][j]=1+dp[i-1][j-1]; } else{ dp[i][j]=max(dp[i-1][j],dp[i][j-1]); } } } return dp[n][n]; }int LongestRepeatingSubsequence(string str){ string a=str; int n=str.length(); return call(a,str,n)}
;}
0
amannawal72 weeks ago
int lcs(string str1,string str2,int sz1,int sz2) { if(sz1<0 || sz2<0) { return 1; } if(str1[sz1]==str2[sz2] && sz1!=sz2) { return lcs(str1,str2,sz1-1,sz2-1)+1; } else { return max(lcs(str1,str2,sz1-1,sz2),lcs(str1,str2,sz1,sz2-1)); } //how to improve TC for this code }
+2
vr095802 weeks ago
//Not a easy level question shrm kro gfg :(
int LongestRepeatingSubsequence(string str){ // Code here int n=str.length(),dp[n+1][n+1]; for(int i=0;i<=n;i++){ for(int j=0;j<=n;j++){ if(i==0||j==0){ dp[i][j]=0; } else if(str[i-1]==str[j-1]&&i!=j) dp[i][j]=dp[i-1][j-1]+1; else{ dp[i][j]=max(dp[i-1][j],dp[i][j-1]); } } } return dp[n][n]; }
+2
gajendrasonare3 weeks ago
Giving TLE error but why
int solve(string str, int i, int j, vector<vector<int>>dp){
if(i<0 || j<0) return 0;
if(dp[i][j] != -1) return dp[i][j];
if(str[i] == str[j] && i!=j) return dp[i][j] = 1 + solve(str,i-1,j-1,dp);
return dp[i][j] = max(solve(str,i-1,j,dp), solve(str,i,j-1,dp));
}
int LongestRepeatingSubsequence(string str){
int n = str.length();
vector<vector<int>>dp(n,vector<int>(n,-1));
return solve(str,n-1,n-1,dp);
}
0
jainmuskan5654 weeks ago
int dp[1001][1001]; int helper(string str1, string str2, int n,int m){ if(dp[n][m]!=-1){ return dp[n][m]; } for(int i=0;i<=n;i++){ for(int j=0;j<=m;j++){ if(i==0 || j==0){ dp[i][j]=0; } } } for(int i=1;i<=n;i++){ for(int j=1;j<=m;j++){ if(str1[i-1]==str2[j-1] && i!=j){ dp[i][j]= 1+ dp[i-1][j-1]; } else{ dp[i][j]= max(dp[i-1][j],dp[i][j-1]); } } } return dp[n][m]; } int LongestRepeatingSubsequence(string str){ memset(dp,-1,sizeof(dp)); return helper(str,str,str.size(),str.size()); }
0
f2017084811 month ago
Can anyone tell me what is wrong in this code? it is failing for the this test case- “agcsorvauz”. It is working in my machine but not working here? why is it so. Please help me!
class Solution:def LongestRepeatingSubsequence(self,str): # Code here arr1=[] count=0 maxcount=0 maxlength=0 for i in range(len(str)): for j in range(i,len(str)): arr1.append(str[i:j+1]) for k in range(len(arr1)): for l in range(k+1,len(arr1)): if arr1[k]==arr1[l]: length=len(arr1[k]) if length<maxlength: break else: maxlength=length count=1 count=count+1 if count>maxcount: maxcount=count count=0 return maxcount
+1
officialshivaji0071 month ago
class Solution { int dp[1001][1001]; int lcs(int x,int y,string s){ if(dp[x][y]!=-1) return dp[x][y]; if(x==0||y==0) return dp[x][y]=0; if(s[x-1]== s[y-1] && x!=y){ return dp[x][y]=1+lcs(x-1,y-1,s); } return dp[x][y]=max(lcs(x-1,y,s),lcs(x,y-1,s)); }public: Solution(){ memset(dp,-1,sizeof(dp)); } int LongestRepeatingSubsequence(string str){ // Code here int n = str.size(); return lcs(n,n,str); }
};
0
vijayadurga2781 month ago
python solution:
This is one way of solution :
class Solution:
def LongestRepeatingSubsequence(self, str):
# Code here
m=len(str)
l=[[0 for i in range(m+1)]for j in range(m+1)]
for i in range(1,m+1):
for j in range(1,m+1):
if(str[i-1]==str[j-1] and i!=j):
l[i][j]=l[i-1][j-1]+1
else:
l[i][j]=max(l[i][j-1],l[i-1][j])
s=''
i=m
j=m
while(i>0 and j>0):
if(l[i][j]==l[i-1][j-1]+1):
s+=str[i-1]
i-=1
j-=1
elif(l[i][j]==l[i-1][j]):
i-=1
else:
j-=1
s=''.join(reversed(s))
return len(s)
------------------------------------------------------
2)The other way is :
class Solution:
def LongestRepeatingSubsequence(self, str):
n=len(str)
p=str
m=[[0 for i in range(n+1)]for i in range(n+1)]
for i in range(n+1):
for j in range(n+1):
if(i==0 or j==0):
m[i][j]=0
for i in range(1,n+1):
for j in range(1,n+1):
if(str[i-1]==p[j-1] and i!=j):
m[i][j]=m[i-1][j-1]+1
else:
m[i][j]=max(m[i-1][j],m[i][j-1])
return m[n][n]
0
ram210320011 month ago
class Solution {
public:
int lcs(string A,string s){
int n=A.size();
int m=s.size();
int t[n+1][m+1];
for(int i=0;i<n+1;i++)
t[i][0]=0;
for(int j=0;j<m+1;j++)
t[0][j]=0;
for(int i=1;i<n+1;i++){
for(int j=1;j<m+1;j++){
if(A[i-1]==s[j-1] && (i!=j))
t[i][j]=1+t[i-1][j-1];
else
t[i][j]=max(t[i][j-1],t[i-1][j]);
}
}
return t[n][m];
}
int LongestRepeatingSubsequence(string str){
// Code here
string A=str;
string s=str;
return lcs(A,s);
}};
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": 519,
"s": 238,
"text": "Given a string str, find the length of the longest repeating subsequence such that it can be found twice in the given string. The two identified subsequences A and B can use the same ith character from string str if and only if that ith character has different indices in A and B."
},
{
"code": null,
"e": 530,
"s": 519,
"text": "Example 1:"
},
{
"code": null,
"e": 1024,
"s": 530,
"text": "Input:\nstr = \"axxzxy\"\nOutput: 2\nExplanation:\nThe given array with indexes looks like\na x x z x y \n0 1 2 3 4 5\n\nThe longest subsequence is \"xx\". \nIt appears twice as explained below.\n\nsubsequence A\nx x\n0 1 <-- index of subsequence A\n------\n1 2 <-- index of str \n\n\nsubsequence B\nx x\n0 1 <-- index of subsequence B\n------\n2 4 <-- index of str \n\nWe are able to use character 'x' \n(at index 2 in str) in both subsequences\nas it appears on index 1 in subsequence A \nand index 0 in subsequence B."
},
{
"code": null,
"e": 1035,
"s": 1024,
"text": "Example 2:"
},
{
"code": null,
"e": 1524,
"s": 1035,
"text": "Input:\nstr = \"axxxy\"\nOutput: 2\nExplanation:\nThe given array with indexes looks like\na x x x y \n0 1 2 3 4\n\nThe longest subsequence is \"xx\". \nIt appears twice as explained below.\n\nsubsequence A\nx x\n0 1 <-- index of subsequence A\n------\n1 2 <-- index of str \n\n\nsubsequence B\nx x\n0 1 <-- index of subsequence B\n------\n2 3 <-- index of str \n\nWe are able to use character 'x' \n(at index 2 in str) in both subsequences\nas it appears on index 1 in subsequence A \nand index 0 in subsequence B."
},
{
"code": null,
"e": 1733,
"s": 1524,
"text": "\nYour Task:\nYou don't need to read or print anything. Your task is to complete the LongestRepeatingSubsequence() which takes str as input parameter and returns the length of the longest repeating subsequnece."
},
{
"code": null,
"e": 1799,
"s": 1733,
"text": "\nExpected Time Complexity: O(n2)\nExpected Space Complexity: O(n2)"
},
{
"code": null,
"e": 1831,
"s": 1799,
"text": "\nConstraints:\n1 <= |str| <= 103"
},
{
"code": null,
"e": 1836,
"s": 1831,
"text": "-129"
},
{
"code": null,
"e": 1865,
"s": 1836,
"text": "eeshagoyal2Admin7 months ago"
},
{
"code": null,
"e": 1929,
"s": 1865,
"text": "The problem statement has been updated to avoid any ambiguity. "
},
{
"code": null,
"e": 1931,
"s": 1929,
"text": "0"
},
{
"code": null,
"e": 1958,
"s": 1931,
"text": "shishir17pandey2 weeks ago"
},
{
"code": null,
"e": 2532,
"s": 1958,
"text": " int call(string a,string b,int n){ int dp[1001][1001]; for(int i=0;i<n;i++){ dp[i][0]=0; } for(int j=0;j<n;j++){ dp[0][j]=0; } for(int i=1;i<=n;i++){ for(int j=1;j<=n;j++){ if(a[i-1]==b[j-1] && i!=j){ dp[i][j]=1+dp[i-1][j-1]; } else{ dp[i][j]=max(dp[i-1][j],dp[i][j-1]); } } } return dp[n][n]; }int LongestRepeatingSubsequence(string str){ string a=str; int n=str.length(); return call(a,str,n)}"
},
{
"code": null,
"e": 2535,
"s": 2532,
"text": ";}"
},
{
"code": null,
"e": 2537,
"s": 2535,
"text": "0"
},
{
"code": null,
"e": 2559,
"s": 2537,
"text": "amannawal72 weeks ago"
},
{
"code": null,
"e": 2978,
"s": 2559,
"text": "int lcs(string str1,string str2,int sz1,int sz2) { if(sz1<0 || sz2<0) { return 1; } if(str1[sz1]==str2[sz2] && sz1!=sz2) { return lcs(str1,str2,sz1-1,sz2-1)+1; } else { return max(lcs(str1,str2,sz1-1,sz2),lcs(str1,str2,sz1,sz2-1)); } //how to improve TC for this code }"
},
{
"code": null,
"e": 2981,
"s": 2978,
"text": "+2"
},
{
"code": null,
"e": 3000,
"s": 2981,
"text": "vr095802 weeks ago"
},
{
"code": null,
"e": 3044,
"s": 3000,
"text": "//Not a easy level question shrm kro gfg :("
},
{
"code": null,
"e": 3444,
"s": 3044,
"text": " int LongestRepeatingSubsequence(string str){ // Code here int n=str.length(),dp[n+1][n+1]; for(int i=0;i<=n;i++){ for(int j=0;j<=n;j++){ if(i==0||j==0){ dp[i][j]=0; } else if(str[i-1]==str[j-1]&&i!=j) dp[i][j]=dp[i-1][j-1]+1; else{ dp[i][j]=max(dp[i-1][j],dp[i][j-1]); } } } return dp[n][n]; }"
},
{
"code": null,
"e": 3447,
"s": 3444,
"text": "+2"
},
{
"code": null,
"e": 3473,
"s": 3447,
"text": "gajendrasonare3 weeks ago"
},
{
"code": null,
"e": 3498,
"s": 3473,
"text": "Giving TLE error but why"
},
{
"code": null,
"e": 4006,
"s": 3498,
"text": "int solve(string str, int i, int j, vector<vector<int>>dp){\n\t if(i<0 || j<0) return 0;\n\t \n\t if(dp[i][j] != -1) return dp[i][j];\n\t \n\t if(str[i] == str[j] && i!=j) return dp[i][j] = 1 + solve(str,i-1,j-1,dp); \n\t \n\t return dp[i][j] = max(solve(str,i-1,j,dp), solve(str,i,j-1,dp)); \n\t }\n\t\tint LongestRepeatingSubsequence(string str){\n\t\t int n = str.length();\n\t\t vector<vector<int>>dp(n,vector<int>(n,-1));\n return solve(str,n-1,n-1,dp); \n\t\t}"
},
{
"code": null,
"e": 4008,
"s": 4006,
"text": "0"
},
{
"code": null,
"e": 4033,
"s": 4008,
"text": "jainmuskan5654 weeks ago"
},
{
"code": null,
"e": 4785,
"s": 4033,
"text": "int dp[1001][1001]; int helper(string str1, string str2, int n,int m){ if(dp[n][m]!=-1){ return dp[n][m]; } for(int i=0;i<=n;i++){ for(int j=0;j<=m;j++){ if(i==0 || j==0){ dp[i][j]=0; } } } for(int i=1;i<=n;i++){ for(int j=1;j<=m;j++){ if(str1[i-1]==str2[j-1] && i!=j){ dp[i][j]= 1+ dp[i-1][j-1]; } else{ dp[i][j]= max(dp[i-1][j],dp[i][j-1]); } } } return dp[n][m]; } int LongestRepeatingSubsequence(string str){ memset(dp,-1,sizeof(dp)); return helper(str,str,str.size(),str.size()); }"
},
{
"code": null,
"e": 4787,
"s": 4785,
"text": "0"
},
{
"code": null,
"e": 4809,
"s": 4787,
"text": "f2017084811 month ago"
},
{
"code": null,
"e": 4988,
"s": 4809,
"text": "Can anyone tell me what is wrong in this code? it is failing for the this test case- “agcsorvauz”. It is working in my machine but not working here? why is it so. Please help me!"
},
{
"code": null,
"e": 5699,
"s": 4988,
"text": "class Solution:def LongestRepeatingSubsequence(self,str): # Code here arr1=[] count=0 maxcount=0 maxlength=0 for i in range(len(str)): for j in range(i,len(str)): arr1.append(str[i:j+1]) for k in range(len(arr1)): for l in range(k+1,len(arr1)): if arr1[k]==arr1[l]: length=len(arr1[k]) if length<maxlength: break else: maxlength=length count=1 count=count+1 if count>maxcount: maxcount=count count=0 return maxcount"
},
{
"code": null,
"e": 5702,
"s": 5699,
"text": "+1"
},
{
"code": null,
"e": 5732,
"s": 5702,
"text": "officialshivaji0071 month ago"
},
{
"code": null,
"e": 6301,
"s": 5732,
"text": "class Solution { int dp[1001][1001]; int lcs(int x,int y,string s){ if(dp[x][y]!=-1) return dp[x][y]; if(x==0||y==0) return dp[x][y]=0; if(s[x-1]== s[y-1] && x!=y){ return dp[x][y]=1+lcs(x-1,y-1,s); } return dp[x][y]=max(lcs(x-1,y,s),lcs(x,y-1,s)); }public: Solution(){ memset(dp,-1,sizeof(dp)); } int LongestRepeatingSubsequence(string str){ // Code here int n = str.size(); return lcs(n,n,str); }"
},
{
"code": null,
"e": 6304,
"s": 6301,
"text": "};"
},
{
"code": null,
"e": 6306,
"s": 6304,
"text": "0"
},
{
"code": null,
"e": 6332,
"s": 6306,
"text": "vijayadurga2781 month ago"
},
{
"code": null,
"e": 7633,
"s": 6332,
"text": "python solution:\nThis is one way of solution :\n\nclass Solution:\n\tdef LongestRepeatingSubsequence(self, str):\n\t\t# Code here\n\t\tm=len(str)\n l=[[0 for i in range(m+1)]for j in range(m+1)]\n for i in range(1,m+1):\n for j in range(1,m+1):\n if(str[i-1]==str[j-1] and i!=j):\n l[i][j]=l[i-1][j-1]+1\n else:\n l[i][j]=max(l[i][j-1],l[i-1][j])\n s=''\n i=m\n j=m\n while(i>0 and j>0):\n if(l[i][j]==l[i-1][j-1]+1):\n s+=str[i-1]\n i-=1\n j-=1\n elif(l[i][j]==l[i-1][j]):\n i-=1\n else:\n j-=1\n s=''.join(reversed(s))\n return len(s)\n ------------------------------------------------------\n 2)The other way is :\n class Solution:\n\tdef LongestRepeatingSubsequence(self, str):\n n=len(str)\n\t\tp=str \n\t\tm=[[0 for i in range(n+1)]for i in range(n+1)]\n\t\tfor i in range(n+1):\n\t\t for j in range(n+1):\n\t\t if(i==0 or j==0):\n\t\t m[i][j]=0\n\t\tfor i in range(1,n+1):\n\t\t for j in range(1,n+1):\n\t\t \n\t\t if(str[i-1]==p[j-1] and i!=j):\n\t\t m[i][j]=m[i-1][j-1]+1\n\t\t else:\n\t\t m[i][j]=max(m[i-1][j],m[i][j-1])\n\t\treturn m[n][n]"
},
{
"code": null,
"e": 7639,
"s": 7637,
"text": "0"
},
{
"code": null,
"e": 7662,
"s": 7639,
"text": "ram210320011 month ago"
},
{
"code": null,
"e": 8263,
"s": 7662,
"text": "\nclass Solution {\npublic:\n\nint lcs(string A,string s){\n int n=A.size();\n int m=s.size();\n int t[n+1][m+1];\n for(int i=0;i<n+1;i++)\n t[i][0]=0;\n for(int j=0;j<m+1;j++)\n t[0][j]=0;\n \n for(int i=1;i<n+1;i++){\n for(int j=1;j<m+1;j++){\n if(A[i-1]==s[j-1] && (i!=j))\n t[i][j]=1+t[i-1][j-1];\n else\n t[i][j]=max(t[i][j-1],t[i-1][j]);\n }\n }\n return t[n][m];\n}\n int LongestRepeatingSubsequence(string str){\n // Code here\n string A=str;\n string s=str;\n return lcs(A,s);\n }};"
},
{
"code": null,
"e": 8409,
"s": 8263,
"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": 8445,
"s": 8409,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 8455,
"s": 8445,
"text": "\nProblem\n"
},
{
"code": null,
"e": 8465,
"s": 8455,
"text": "\nContest\n"
},
{
"code": null,
"e": 8528,
"s": 8465,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 8676,
"s": 8528,
"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": 8884,
"s": 8676,
"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": 8990,
"s": 8884,
"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 Export the Azure VMs using PowerShell?
|
To export the azure VMs using PowerShell, we first need to get their desired properties. The cmdlet Get-AZVM will get all the VMs connected to the particular subscription. To export them to the CSV file we can use the below command.
Get-AzVM | Export-Csv .\AZVMs.csv -NoTypeInformation
Once you run the above command, you will notice that you get all the properties of the VM, and sometimes they are not needed. To get the particular properties of the VM use the Select-Object (alias Select) command.
Get-AzVM | Select Name, ResourceGroupName, Location, @{N='VMSize';E={$_.HardwareProfile.VmSize}} | Export-Csv .\AzureVms.csv -NoTypeInformation
If you want to export the VMs from a particular Resource group,
Get-AZVM -ResourceGroupName TestRG | Export-CSV .\TestRGVMs.csv -NoTypeInformation
When you add -Status Parameter in the Get-AzVM command, it shows the power state of the virtual machine.
Get-AzVM -Status | Export-Csv .\AZVMs.csv -NoTypeInformation
If you need VMs from another subscription, you can use Set-AZContext or Select-AZSubscription command to switch the subscription and then use any of the above commands to get the VM details in the CSV file.
|
[
{
"code": null,
"e": 1295,
"s": 1062,
"text": "To export the azure VMs using PowerShell, we first need to get their desired properties. The cmdlet Get-AZVM will get all the VMs connected to the particular subscription. To export them to the CSV file we can use the below command."
},
{
"code": null,
"e": 1348,
"s": 1295,
"text": "Get-AzVM | Export-Csv .\\AZVMs.csv -NoTypeInformation"
},
{
"code": null,
"e": 1563,
"s": 1348,
"text": "Once you run the above command, you will notice that you get all the properties of the VM, and sometimes they are not needed. To get the particular properties of the VM use the Select-Object (alias Select) command."
},
{
"code": null,
"e": 1707,
"s": 1563,
"text": "Get-AzVM | Select Name, ResourceGroupName, Location, @{N='VMSize';E={$_.HardwareProfile.VmSize}} | Export-Csv .\\AzureVms.csv -NoTypeInformation"
},
{
"code": null,
"e": 1771,
"s": 1707,
"text": "If you want to export the VMs from a particular Resource group,"
},
{
"code": null,
"e": 1854,
"s": 1771,
"text": "Get-AZVM -ResourceGroupName TestRG | Export-CSV .\\TestRGVMs.csv -NoTypeInformation"
},
{
"code": null,
"e": 1959,
"s": 1854,
"text": "When you add -Status Parameter in the Get-AzVM command, it shows the power state of the virtual machine."
},
{
"code": null,
"e": 2020,
"s": 1959,
"text": "Get-AzVM -Status | Export-Csv .\\AZVMs.csv -NoTypeInformation"
},
{
"code": null,
"e": 2227,
"s": 2020,
"text": "If you need VMs from another subscription, you can use Set-AZContext or Select-AZSubscription command to switch the subscription and then use any of the above commands to get the VM details in the CSV file."
}
] |
CSS Rounded Corners
|
With the CSS border-radius property, you can give any element "rounded corners".
The CSS
border-radius property defines the radius of an
element's corners.
Tip: This property allows you to add rounded corners to
elements!
Here are three examples:
1. Rounded corners for an element with a specified background color:
Rounded corners!
2. Rounded corners for an element with a border:
Rounded corners!
3. Rounded corners for an element with a background image:
Rounded corners!
Here is the code:
Tip: The border-radius property is actually a shorthand property for the
border-top-left-radius, border-top-right-radius, border-bottom-right-radius
and border-bottom-left-radius properties.
The border-radius property can have from one
to four values. Here are the rules:
Four values - border-radius: 15px 50px 30px 5px; (first
value applies to top-left corner, second value applies to top-right corner,
third value applies to bottom-right corner, and fourth value applies to
bottom-left corner):
Three values - border-radius: 15px 50px 30px; (first value
applies to top-left corner, second value applies to top-right and bottom-left
corners, and third value applies to bottom-right corner):
Two values - border-radius: 15px 50px; (first value applies
to top-left and bottom-right corners, and the second value applies to top-right
and bottom-left corners):
One value - border-radius: 15px; (the value applies to all
four corners, which are rounded equally:
Here is the code:
You could also create elliptical corners:
Give the div element rounded corners.
<style>
div {
background: red;
: 10px;
}
</style>
<body>
<div>This is a div element. It has some text.</div>
</body>
Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 81,
"s": 0,
"text": "With the CSS border-radius property, you can give any element \"rounded corners\"."
},
{
"code": null,
"e": 158,
"s": 81,
"text": "The CSS \nborder-radius property defines the radius of an \nelement's corners."
},
{
"code": null,
"e": 225,
"s": 158,
"text": "Tip: This property allows you to add rounded corners to \nelements!"
},
{
"code": null,
"e": 250,
"s": 225,
"text": "Here are three examples:"
},
{
"code": null,
"e": 319,
"s": 250,
"text": "1. Rounded corners for an element with a specified background color:"
},
{
"code": null,
"e": 336,
"s": 319,
"text": "Rounded corners!"
},
{
"code": null,
"e": 385,
"s": 336,
"text": "2. Rounded corners for an element with a border:"
},
{
"code": null,
"e": 402,
"s": 385,
"text": "Rounded corners!"
},
{
"code": null,
"e": 461,
"s": 402,
"text": "3. Rounded corners for an element with a background image:"
},
{
"code": null,
"e": 478,
"s": 461,
"text": "Rounded corners!"
},
{
"code": null,
"e": 496,
"s": 478,
"text": "Here is the code:"
},
{
"code": null,
"e": 689,
"s": 496,
"text": "Tip: The border-radius property is actually a shorthand property for the \nborder-top-left-radius, border-top-right-radius, border-bottom-right-radius \nand border-bottom-left-radius properties."
},
{
"code": null,
"e": 771,
"s": 689,
"text": "The border-radius property can have from one \nto four values. Here are the rules:"
},
{
"code": null,
"e": 1000,
"s": 771,
"text": "Four values - border-radius: 15px 50px 30px 5px; (first \nvalue applies to top-left corner, second value applies to top-right corner, \nthird value applies to bottom-right corner, and fourth value applies to \nbottom-left corner): "
},
{
"code": null,
"e": 1197,
"s": 1000,
"text": "Three values - border-radius: 15px 50px 30px; (first value \napplies to top-left corner, second value applies to top-right and bottom-left \ncorners, and third value applies to bottom-right corner):"
},
{
"code": null,
"e": 1365,
"s": 1197,
"text": "Two values - border-radius: 15px 50px; (first value applies \nto top-left and bottom-right corners, and the second value applies to top-right \nand bottom-left corners):"
},
{
"code": null,
"e": 1466,
"s": 1365,
"text": "One value - border-radius: 15px; (the value applies to all \nfour corners, which are rounded equally:"
},
{
"code": null,
"e": 1484,
"s": 1466,
"text": "Here is the code:"
},
{
"code": null,
"e": 1526,
"s": 1484,
"text": "You could also create elliptical corners:"
},
{
"code": null,
"e": 1564,
"s": 1526,
"text": "Give the div element rounded corners."
},
{
"code": null,
"e": 1691,
"s": 1564,
"text": "<style>\ndiv {\n background: red;\n : 10px; \n}\n</style>\n\n<body>\n <div>This is a div element. It has some text.</div>\n</body>\n"
},
{
"code": null,
"e": 1710,
"s": 1691,
"text": "Start the Exercise"
},
{
"code": null,
"e": 1743,
"s": 1710,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 1785,
"s": 1743,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 1892,
"s": 1785,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 1911,
"s": 1892,
"text": "help@w3schools.com"
}
] |
NLP Metrics Made Simple: The BLEU Score | by Boaz Shmueli | Towards Data Science
|
Natural language processing (NLP) has become a super-hot topic. One of the most successful applications of NLP is Machine Translation (MT) — the ability to automatically translate text from one language to another. Perhaps the most well-known MT application is the very useful Google Translate, with its ability to translate from and to 100+ languages.
How can we evaluate the performance of an MT system? One obvious way is to use human evaluation: we can show the original sentence with its machine translation side-by-side, and ask humans to rate the accuracy of the translation. Human evaluation usually requires experts who are fluent in both the source and the target languages. This is expensive and time-consuming. Moreover, every time you tweak your model, you need to re-run the evaluation. Wouldn’t it be nice if we had an automatic way to evaluate the performance of an MT system?
That’s where BLEU, which stands for Bi-Lingual Evaluation Understudy, kicks in. It’s a popular and inexpensive way to automatically measure the performance of your MT model. In a nutshell, BLEU compares the machine’s translation — what’s known as the candidate translation — with existing human-generated translations, known as the reference translations.
The easiest way to explain BLEU is by example. And for that we’ll look at a classic maxim from the Hebrew Bible — וְאָהַבְתָּ לְרֵעֲךָ כָּמוֹךָ — which depicts in three words the principle known as the Golden Rule: treat others as you would like others to treat you 🤗. We use the Bible because it’s been translated many times and to many languages, so it’s easy to find reference translations. Also, most of the translations are in the public domain. The Bible is in fact the most translated book in history (even more than Harry Potter!). In our case, we chose the following three reference translations among the many English translations for our maxim:
R1: but thou shalt love thy neighbor as thyself
R2: but have love for your neighbor as for yourself
R3: but love your neighbors as you love yourself
And here is our candidate translation for which we want to compute the BLEU score:
D: but love other love friend for love yourself
As you can see, our MT system is not very good 😔...
BLEU works by computing the precision — the fraction of tokens from the candidate that appear, or are “covered”, by the references— but with a twist. Like any precision-based metric, the value of the BLEU score is always a number between 0 (worst) and 1 (best). Let’s compute BLEU for our candidate translation. In our example, the candidate consist of 8 words: but love other love friend for love yourself. Had none of the words appeared in any of the references, the precision would have been be 0/8=0. Luckily most of them appear in the references. It’s easy to see that 6 of the 8 words, but love love for love yourself — that is, all words except other and friend — appear in at least one of the references. One is thus tempted to compute the precision as 6/8 = 0.75. But if you look carefully, you will see that the word love appears 3 times in the candidate, yet it appears at most twice in any single reference (it appears twice in R3 and once in R1 and R2 ). BLEU takes this into account — it penalizes words that appear in the candidate more times than it appears in any of the references. Why? Well, the rationale is: since love appeared at most twice in any reference translation, it’s reasonable for it to appear up to 2 times also in the candidate. Thus, up to 2 love words are covered. Any excess usage of love in the candidate doesn’t make sense and so it is not considered as covered. And because the 3rd love is not covered, only 5 of the tokens are covered — but love love for yourself — and we get a BLEU score of 5/8=0.675.
Imagine for a moment that we didn’t have this correction; an 8-word candidate translation like love love love love love love love love would then get a perfect BLEU score of 1, since love appears in a reference translation. With BLEU, we would consider only the first 2 love’s as covered and discard the other 6. The BLEU score, in this case, is just 2/8 = 0.25, indeed indicating very low precision (albeit lots of love!).
Let’s look at the calculation more formally. For each unique word w in the candidate, we count how many times it appears in the candidate. Let’s call this number D(w). In our example:
D(but)=1D(love)=3D(other)=1D(friend)=1D(for)=1D(yourself)=1
For each unique word w, we also define R(w) to be the largest number of times the word appears in any of the references. We calculate this by looking at how many times w appears in each reference, and taking the maximum value. In our example:
R(but)=1 R(love)=2 [appears twice in R3]R(other)=0 R(friend)=0R(for)=2 [appears twice in R2]R(yourself)=1
Our very naïve and basic BLEU score — we will call it BLEU* — can be computed as the ratio of Covered candidate words out of the Total number of candidate words:
BLEU*=Covered/Total
Let’s start with the denominator Total, which is super simple to compute. It’s the number of words in the candidate. A fancy way to write it is:
Total = D(W1)+D(W2)+...
In our case
Total=D(but)+D(love)+D(other)+D(friend)+D(for)+D(yourself)=1+3+1+1+1+1=8
Now for the numerator Covered, which is the total number of covered words. For each unique word w, the number of words in the candidate is D(w), but the coverage is limited by R(w). So if D(w)≤R(w), all D(w) words are covered. Otherwise only R(w) words are covered. The number of covered words for each unique word w can simply be written as MIN(R(w), D(w)) where MIN is the minimum of the two values.
Let’s see how this works out for our example:
MIN(D(but), R(but))=MIN(1, 1)=1MIN(D(love), R(love))=MIN(3, 2)=2MIN(D(other), R(other))=MIN(1, 0)=0MIN(D(friend), R(friend))=MIN(1,0)=0MIN(D(for), R(for))=MIN(1, 2)=1MIN(D(yourself), R(yourself))=MIN(1,1)=1
The total coverage is the sum of the above values:
Covered=1+2+0+0+1+1=5
We can finally calculate our BLEU* score for our candidate:
BLEU*(but love other love friend for love yourself)=Covered/Total=5/8=0.625
The naïve BLEU* score that I described above is not used in practice because it has many issues that render it highly inaccurate and not practical. I’ve simply introduced it to give the idea behind the “true” BLEU score.
Here are some of the problems with the naïve BLEU*.
First, very short translations —i.e., candidates with very few words— can do absurdly well although they are likely to be horrible translations. Imagine the candidate is simply the 1-word love or even the two-word but for. These candidates get a perfect BLEU* score of 1 because the tokens are nicely covered by the references.
In addition, the BLEU* metric is completely oblivious to word order. The BLEU* score for but love other love friend for love yourself is exactly the same as other love love love for friend yourself but. In languages where word order is important (English and many others) this doesn’t really make sense.
Lastly, we only calculated the BLEU* score for a single sentence. To measure the performance of our MT model, it makes sense not to rely on a single instance, but to check the performance on many sentences, and combine the scores for a more comprehensive and accurate evaluation of the model.
To rectify these issues, the true BLEU score incorporates several corrections to my naïve BLEU* calculations. I explain how the true BLEU score is calculated in a follow up story.
Finally, I wrote some simple Python code that computes the BLEU* score. Note that this is for educational purposes only — do not use it for industrial or academic purposes! The code includes two versions for the score — they are functionally equivalent and so they calculate identical scores. The first (BLUE_star) is longer but is hopefully easier to understand. The shorter version (BLUE_star_compact) uses (or perhaps even abuses) Python’s list comprehension and is hence more compact.
from collections import Counter
# compute a very naïve BLEU score -- for educational purposes only
def BLEU_star(refs, candidate):
# tokenize the references and the candidate
refs = [ref.split() for ref in refs]
candidate = candidate.split()
# compute word frequencies for the references and the candidate
refs_counts = [Counter(ref) for ref in refs]
candidate_counts = Counter(candidate)
covered = 0
total = 0
# compute the coverage for each word
for word, count in candidate_counts.items():
covered += min(count, max([ref[word] for ref in refs_counts]))
total += count
# note: we can also use len(candidate) instead of total :)
return covered / total
# a more "pythonic" way to compute BLUE_star
def BLEU_star_compact(refs, candidate):
refs = [ref.split() for ref in refs]
candidate = candidate.split()
return sum([min(count, max([ref[word] for ref in [Counter(ref) for ref in refs]])) for word, count in Counter(candidate).items()])/len(candidate)
refs=['but thou shalt love thy neighbor as thyself',
'but have love for your neighbour as for yourself',
'but love your neighbors as you love yourself']
candidate = 'but love other love friend for love yourself'
print(BLEU_star(refs, candidate))
print(BLEU_star_compact(refs, candidate))
I hope you liked this beginner’s BLEU tutorial.
Feel free to leave feedback below. Thank you!
|
[
{
"code": null,
"e": 524,
"s": 171,
"text": "Natural language processing (NLP) has become a super-hot topic. One of the most successful applications of NLP is Machine Translation (MT) — the ability to automatically translate text from one language to another. Perhaps the most well-known MT application is the very useful Google Translate, with its ability to translate from and to 100+ languages."
},
{
"code": null,
"e": 1064,
"s": 524,
"text": "How can we evaluate the performance of an MT system? One obvious way is to use human evaluation: we can show the original sentence with its machine translation side-by-side, and ask humans to rate the accuracy of the translation. Human evaluation usually requires experts who are fluent in both the source and the target languages. This is expensive and time-consuming. Moreover, every time you tweak your model, you need to re-run the evaluation. Wouldn’t it be nice if we had an automatic way to evaluate the performance of an MT system?"
},
{
"code": null,
"e": 1420,
"s": 1064,
"text": "That’s where BLEU, which stands for Bi-Lingual Evaluation Understudy, kicks in. It’s a popular and inexpensive way to automatically measure the performance of your MT model. In a nutshell, BLEU compares the machine’s translation — what’s known as the candidate translation — with existing human-generated translations, known as the reference translations."
},
{
"code": null,
"e": 2076,
"s": 1420,
"text": "The easiest way to explain BLEU is by example. And for that we’ll look at a classic maxim from the Hebrew Bible — וְאָהַבְתָּ לְרֵעֲךָ כָּמוֹךָ — which depicts in three words the principle known as the Golden Rule: treat others as you would like others to treat you 🤗. We use the Bible because it’s been translated many times and to many languages, so it’s easy to find reference translations. Also, most of the translations are in the public domain. The Bible is in fact the most translated book in history (even more than Harry Potter!). In our case, we chose the following three reference translations among the many English translations for our maxim:"
},
{
"code": null,
"e": 2124,
"s": 2076,
"text": "R1: but thou shalt love thy neighbor as thyself"
},
{
"code": null,
"e": 2176,
"s": 2124,
"text": "R2: but have love for your neighbor as for yourself"
},
{
"code": null,
"e": 2225,
"s": 2176,
"text": "R3: but love your neighbors as you love yourself"
},
{
"code": null,
"e": 2308,
"s": 2225,
"text": "And here is our candidate translation for which we want to compute the BLEU score:"
},
{
"code": null,
"e": 2356,
"s": 2308,
"text": "D: but love other love friend for love yourself"
},
{
"code": null,
"e": 2408,
"s": 2356,
"text": "As you can see, our MT system is not very good 😔..."
},
{
"code": null,
"e": 3953,
"s": 2408,
"text": "BLEU works by computing the precision — the fraction of tokens from the candidate that appear, or are “covered”, by the references— but with a twist. Like any precision-based metric, the value of the BLEU score is always a number between 0 (worst) and 1 (best). Let’s compute BLEU for our candidate translation. In our example, the candidate consist of 8 words: but love other love friend for love yourself. Had none of the words appeared in any of the references, the precision would have been be 0/8=0. Luckily most of them appear in the references. It’s easy to see that 6 of the 8 words, but love love for love yourself — that is, all words except other and friend — appear in at least one of the references. One is thus tempted to compute the precision as 6/8 = 0.75. But if you look carefully, you will see that the word love appears 3 times in the candidate, yet it appears at most twice in any single reference (it appears twice in R3 and once in R1 and R2 ). BLEU takes this into account — it penalizes words that appear in the candidate more times than it appears in any of the references. Why? Well, the rationale is: since love appeared at most twice in any reference translation, it’s reasonable for it to appear up to 2 times also in the candidate. Thus, up to 2 love words are covered. Any excess usage of love in the candidate doesn’t make sense and so it is not considered as covered. And because the 3rd love is not covered, only 5 of the tokens are covered — but love love for yourself — and we get a BLEU score of 5/8=0.675."
},
{
"code": null,
"e": 4377,
"s": 3953,
"text": "Imagine for a moment that we didn’t have this correction; an 8-word candidate translation like love love love love love love love love would then get a perfect BLEU score of 1, since love appears in a reference translation. With BLEU, we would consider only the first 2 love’s as covered and discard the other 6. The BLEU score, in this case, is just 2/8 = 0.25, indeed indicating very low precision (albeit lots of love!)."
},
{
"code": null,
"e": 4561,
"s": 4377,
"text": "Let’s look at the calculation more formally. For each unique word w in the candidate, we count how many times it appears in the candidate. Let’s call this number D(w). In our example:"
},
{
"code": null,
"e": 4621,
"s": 4561,
"text": "D(but)=1D(love)=3D(other)=1D(friend)=1D(for)=1D(yourself)=1"
},
{
"code": null,
"e": 4864,
"s": 4621,
"text": "For each unique word w, we also define R(w) to be the largest number of times the word appears in any of the references. We calculate this by looking at how many times w appears in each reference, and taking the maximum value. In our example:"
},
{
"code": null,
"e": 4970,
"s": 4864,
"text": "R(but)=1 R(love)=2 [appears twice in R3]R(other)=0 R(friend)=0R(for)=2 [appears twice in R2]R(yourself)=1"
},
{
"code": null,
"e": 5133,
"s": 4970,
"text": "Our very naïve and basic BLEU score — we will call it BLEU* — can be computed as the ratio of Covered candidate words out of the Total number of candidate words:"
},
{
"code": null,
"e": 5153,
"s": 5133,
"text": "BLEU*=Covered/Total"
},
{
"code": null,
"e": 5298,
"s": 5153,
"text": "Let’s start with the denominator Total, which is super simple to compute. It’s the number of words in the candidate. A fancy way to write it is:"
},
{
"code": null,
"e": 5322,
"s": 5298,
"text": "Total = D(W1)+D(W2)+..."
},
{
"code": null,
"e": 5334,
"s": 5322,
"text": "In our case"
},
{
"code": null,
"e": 5407,
"s": 5334,
"text": "Total=D(but)+D(love)+D(other)+D(friend)+D(for)+D(yourself)=1+3+1+1+1+1=8"
},
{
"code": null,
"e": 5809,
"s": 5407,
"text": "Now for the numerator Covered, which is the total number of covered words. For each unique word w, the number of words in the candidate is D(w), but the coverage is limited by R(w). So if D(w)≤R(w), all D(w) words are covered. Otherwise only R(w) words are covered. The number of covered words for each unique word w can simply be written as MIN(R(w), D(w)) where MIN is the minimum of the two values."
},
{
"code": null,
"e": 5855,
"s": 5809,
"text": "Let’s see how this works out for our example:"
},
{
"code": null,
"e": 6062,
"s": 5855,
"text": "MIN(D(but), R(but))=MIN(1, 1)=1MIN(D(love), R(love))=MIN(3, 2)=2MIN(D(other), R(other))=MIN(1, 0)=0MIN(D(friend), R(friend))=MIN(1,0)=0MIN(D(for), R(for))=MIN(1, 2)=1MIN(D(yourself), R(yourself))=MIN(1,1)=1"
},
{
"code": null,
"e": 6113,
"s": 6062,
"text": "The total coverage is the sum of the above values:"
},
{
"code": null,
"e": 6135,
"s": 6113,
"text": "Covered=1+2+0+0+1+1=5"
},
{
"code": null,
"e": 6195,
"s": 6135,
"text": "We can finally calculate our BLEU* score for our candidate:"
},
{
"code": null,
"e": 6271,
"s": 6195,
"text": "BLEU*(but love other love friend for love yourself)=Covered/Total=5/8=0.625"
},
{
"code": null,
"e": 6493,
"s": 6271,
"text": "The naïve BLEU* score that I described above is not used in practice because it has many issues that render it highly inaccurate and not practical. I’ve simply introduced it to give the idea behind the “true” BLEU score."
},
{
"code": null,
"e": 6546,
"s": 6493,
"text": "Here are some of the problems with the naïve BLEU*."
},
{
"code": null,
"e": 6874,
"s": 6546,
"text": "First, very short translations —i.e., candidates with very few words— can do absurdly well although they are likely to be horrible translations. Imagine the candidate is simply the 1-word love or even the two-word but for. These candidates get a perfect BLEU* score of 1 because the tokens are nicely covered by the references."
},
{
"code": null,
"e": 7178,
"s": 6874,
"text": "In addition, the BLEU* metric is completely oblivious to word order. The BLEU* score for but love other love friend for love yourself is exactly the same as other love love love for friend yourself but. In languages where word order is important (English and many others) this doesn’t really make sense."
},
{
"code": null,
"e": 7471,
"s": 7178,
"text": "Lastly, we only calculated the BLEU* score for a single sentence. To measure the performance of our MT model, it makes sense not to rely on a single instance, but to check the performance on many sentences, and combine the scores for a more comprehensive and accurate evaluation of the model."
},
{
"code": null,
"e": 7652,
"s": 7471,
"text": "To rectify these issues, the true BLEU score incorporates several corrections to my naïve BLEU* calculations. I explain how the true BLEU score is calculated in a follow up story."
},
{
"code": null,
"e": 8141,
"s": 7652,
"text": "Finally, I wrote some simple Python code that computes the BLEU* score. Note that this is for educational purposes only — do not use it for industrial or academic purposes! The code includes two versions for the score — they are functionally equivalent and so they calculate identical scores. The first (BLUE_star) is longer but is hopefully easier to understand. The shorter version (BLUE_star_compact) uses (or perhaps even abuses) Python’s list comprehension and is hence more compact."
},
{
"code": null,
"e": 9193,
"s": 8141,
"text": "from collections import Counter\n\n# compute a very naïve BLEU score -- for educational purposes only\n\ndef BLEU_star(refs, candidate):\n \n # tokenize the references and the candidate\n refs = [ref.split() for ref in refs]\n candidate = candidate.split()\n\n # compute word frequencies for the references and the candidate\n refs_counts = [Counter(ref) for ref in refs]\n candidate_counts = Counter(candidate)\n\n covered = 0\n total = 0\n \n # compute the coverage for each word\n for word, count in candidate_counts.items():\n covered += min(count, max([ref[word] for ref in refs_counts]))\n total += count\n \n # note: we can also use len(candidate) instead of total :)\n return covered / total\n\n# a more \"pythonic\" way to compute BLUE_star \n\ndef BLEU_star_compact(refs, candidate):\n refs = [ref.split() for ref in refs]\n candidate = candidate.split()\n\n return sum([min(count, max([ref[word] for ref in [Counter(ref) for ref in refs]])) for word, count in Counter(candidate).items()])/len(candidate)\n"
},
{
"code": null,
"e": 9500,
"s": 9193,
"text": "refs=['but thou shalt love thy neighbor as thyself',\n 'but have love for your neighbour as for yourself',\n 'but love your neighbors as you love yourself']\n\ncandidate = 'but love other love friend for love yourself'\n\nprint(BLEU_star(refs, candidate))\nprint(BLEU_star_compact(refs, candidate))\n"
},
{
"code": null,
"e": 9548,
"s": 9500,
"text": "I hope you liked this beginner’s BLEU tutorial."
}
] |
Microprocessor - Quick Guide
|
Microprocessor is a controlling unit of a micro-computer, fabricated on a small chip capable of performing ALU (Arithmetic Logical Unit) operations and communicating with the other devices connected to it.
Microprocessor consists of an ALU, register array, and a control unit. ALU performs arithmetical and logical operations on the data received from the memory or an input device. Register array consists of registers identified by letters like B, C, D, E, H, L and accumulator. The control unit controls the flow of data and instructions within the computer.
The microprocessor follows a sequence: Fetch, Decode, and then Execute.
Initially, the instructions are stored in the memory in a sequential order. The microprocessor fetches those instructions from the memory, then decodes it and executes those instructions till STOP instruction is reached. Later, it sends the result in binary to the output port. Between these processes, the register stores the temporarily data and ALU performs the computing functions.
Here is a list of some of the frequently used terms in a microprocessor −
Instruction Set − It is the set of instructions that the microprocessor can understand.
Instruction Set − It is the set of instructions that the microprocessor can understand.
Bandwidth − It is the number of bits processed in a single instruction.
Bandwidth − It is the number of bits processed in a single instruction.
Clock Speed − It determines the number of operations per second the processor can perform. It is expressed in megahertz (MHz) or gigahertz (GHz).It is also known as Clock Rate.
Clock Speed − It determines the number of operations per second the processor can perform. It is expressed in megahertz (MHz) or gigahertz (GHz).It is also known as Clock Rate.
Word Length − It depends upon the width of internal data bus, registers, ALU, etc. An 8-bit microprocessor can process 8-bit data at a time. The word length ranges from 4 bits to 64 bits depending upon the type of the microcomputer.
Word Length − It depends upon the width of internal data bus, registers, ALU, etc. An 8-bit microprocessor can process 8-bit data at a time. The word length ranges from 4 bits to 64 bits depending upon the type of the microcomputer.
Data Types − The microprocessor has multiple data type formats like binary, BCD, ASCII, signed and unsigned numbers.
Data Types − The microprocessor has multiple data type formats like binary, BCD, ASCII, signed and unsigned numbers.
Here is a list of some of the most prominent features of any microprocessor −
Cost-effective − The microprocessor chips are available at low prices and results its low cost.
Cost-effective − The microprocessor chips are available at low prices and results its low cost.
Size − The microprocessor is of small size chip, hence is portable.
Size − The microprocessor is of small size chip, hence is portable.
Low Power Consumption − Microprocessors are manufactured by using metaloxide semiconductor technology, which has low power consumption.
Low Power Consumption − Microprocessors are manufactured by using metaloxide semiconductor technology, which has low power consumption.
Versatility − The microprocessors are versatile as we can use the same chip in a number of applications by configuring the software program.
Versatility − The microprocessors are versatile as we can use the same chip in a number of applications by configuring the software program.
Reliability − The failure rate of an IC in microprocessors is very low, hence it is reliable.
Reliability − The failure rate of an IC in microprocessors is very low, hence it is reliable.
A microprocessor can be classified into three categories −
RISC stands for Reduced Instruction Set Computer. It is designed to reduce the execution time by simplifying the instruction set of the computer. Using RISC processors, each instruction requires only one clock cycle to execute results in uniform execution time. This reduces the efficiency as there are more lines of code, hence more RAM is needed to store the instructions. The compiler also has to work more to convert high-level language instructions into machine code.
Some of the RISC processors are −
Power PC: 601, 604, 615, 620
DEC Alpha: 210642, 211066, 21068, 21164
MIPS: TS (R10000) RISC Processor
PA-RISC: HP 7100LC
RISC microprocessor architecture uses highly-optimized set of instructions. It is used in portable devices like Apple iPod due to its power efficiency.
The major characteristics of a RISC processor are as follows −
It consists of simple instructions.
It consists of simple instructions.
It supports various data-type formats.
It supports various data-type formats.
It utilizes simple addressing modes and fixed length instructions for pipelining.
It utilizes simple addressing modes and fixed length instructions for pipelining.
It supports register to use in any context.
It supports register to use in any context.
One cycle execution time.
One cycle execution time.
“LOAD” and “STORE” instructions are used to access the memory location.
“LOAD” and “STORE” instructions are used to access the memory location.
It consists of larger number of registers.
It consists of larger number of registers.
It consists of less number of transistors.
It consists of less number of transistors.
CISC stands for Complex Instruction Set Computer. It is designed to minimize the number of instructions per program, ignoring the number of cycles per instruction. The emphasis is on building complex instructions directly into the hardware.
The compiler has to do very little work to translate a high-level language into assembly level language/machine code because the length of the code is relatively short, so very little RAM is required to store the instructions.
Some of the CISC Processors are −
IBM 370/168
VAX 11/780
Intel 80486
Its architecture is designed to decrease the memory cost because more storage is needed in larger programs resulting in higher memory cost. To resolve this, the number of instructions per program can be reduced by embedding the number of operations in a single instruction.
Variety of addressing modes.
Larger number of instructions.
Variable length of instruction formats.
Several cycles may be required to execute one instruction.
Instruction-decoding logic is complex.
One instruction is required to support multiple addressing modes.
These are the processors which are designed for some special purposes. Few of the special processors are briefly discussed −
A coprocessor is a specially designed microprocessor, which can handle its particular function many times faster than the ordinary microprocessor.
For example − Math Coprocessor.
Some Intel math-coprocessors are −
8087-used with 8086
80287-used with 80286
80387-used with 80386
It is a specially designed microprocessor having a local memory of its own, which is used to control I/O devices with minimum CPU involvement.
For example −
DMA (direct Memory Access) controller
Keyboard/mouse controller
Graphic display controller
SCSI port controller
A transputer is a specially designed microprocessor with its own local memory and having links to connect one transputer to another transputer for inter-processor communications. It was first designed in 1980 by Inmos and is targeted to the utilization of VLSI technology.
A transputer can be used as a single processor system or can be connected to external links, which reduces the construction cost and increases the performance.
For example − 16-bit T212, 32-bit T425, the floating point (T800, T805 & T9000) processors.
This processor is specially designed to process the analog signals into a digital form. This is done by sampling the voltage level at regular time intervals and converting the voltage at that instant into a digital form. This process is performed by a circuit called an analogue to digital converter, A to D converter or ADC.
A DSP contains the following components −
Program Memory − It stores the programs that DSP will use to process data.
Program Memory − It stores the programs that DSP will use to process data.
Data Memory − It stores the information to be processed.
Data Memory − It stores the information to be processed.
Compute Engine − It performs the mathematical processing, accessing the program from the program memory and the data from the data memory.
Compute Engine − It performs the mathematical processing, accessing the program from the program memory and the data from the data memory.
Input/Output − It connects to the outside world.
Input/Output − It connects to the outside world.
Its applications are −
Sound and music synthesis
Audio and video compression
Video signal processing
2D and 3d graphics acceleration.
For example − Texas Instrument’s TMS 320 series, e.g., TMS 320C40, TMS320C50.
8085 is pronounced as "eighty-eighty-five" microprocessor. It is an 8-bit microprocessor designed by Intel in 1977 using NMOS technology.
It has the following configuration −
8-bit data bus
16-bit address bus, which can address upto 64KB
A 16-bit program counter
A 16-bit stack pointer
Six 8-bit registers arranged in pairs: BC, DE, HL
Requires +5V supply to operate at 3.2 MHZ single phase clock
It is used in washing machines, microwave ovens, mobile phones, etc.
8085 consists of the following functional units −
It is an 8-bit register used to perform arithmetic, logical, I/O & LOAD/STORE operations. It is connected to internal data bus & ALU.
As the name suggests, it performs arithmetic and logical operations like Addition, Subtraction, AND, OR, etc. on 8-bit data.
There are 6 general purpose registers in 8085 processor, i.e. B, C, D, E, H & L. Each register can hold 8-bit data.
These registers can work in pair to hold 16-bit data and their pairing combination is like B-C, D-E & H-L.
It is a 16-bit register used to store the memory address location of the next instruction to be executed. Microprocessor increments the program whenever an instruction is being executed, so that the program counter points to the memory address of the next instruction that is going to be executed.
It is also a 16-bit register works like stack, which is always incremented/decremented by 2 during push & pop operations.
It is an 8-bit register, which holds the temporary data of arithmetic and logical operations.
It is an 8-bit register having five 1-bit flip-flops, which holds either 0 or 1 depending upon the result stored in the accumulator.
These are the set of 5 flip-flops −
Sign (S)
Zero (Z)
Auxiliary Carry (AC)
Parity (P)
Carry (C)
Its bit position is shown in the following table −
It is an 8-bit register. When an instruction is fetched from memory then it is stored in the Instruction register. Instruction decoder decodes the information present in the Instruction register.
It provides timing and control signal to the microprocessor to perform operations. Following are the timing and control signals, which control external and internal circuits −
Control Signals: READY, RD’, WR’, ALE
Status Signals: S0, S1, IO/M’
DMA Signals: HOLD, HLDA
RESET Signals: RESET IN, RESET OUT
As the name suggests it controls the interrupts during a process. When a microprocessor is executing a main program and whenever an interrupt occurs, the microprocessor shifts the control from the main program to process the incoming request. After the request is completed, the control goes back to the main program.
There are 5 interrupt signals in 8085 microprocessor: INTR, RST 7.5, RST 6.5, RST 5.5, TRAP.
It controls the serial data communication by using these two instructions: SID (Serial input data) and SOD (Serial output data).
The content stored in the stack pointer and program counter is loaded into the address buffer and address-data buffer to communicate with the CPU. The memory and I/O chips are connected to these buses; the CPU can exchange the desired data with the memory and I/O chips.
Data bus carries the data to be stored. It is bidirectional, whereas address bus carries the location to where it should be stored and it is unidirectional. It is used to transfer the data & Address I/O devices.
We have tried to depict the architecture of 8085 with this following image −
The following image depicts the pin diagram of 8085 Microprocessor −
The pins of a 8085 microprocessor can be classified into seven groups −
A15-A8, it carries the most significant 8-bits of memory/IO address.
AD7-AD0, it carries the least significant 8-bit address and data bus.
These signals are used to identify the nature of operation. There are 3 control signal and 3 status signals.
Three control signals are RD, WR & ALE.
RD − This signal indicates that the selected IO or memory device is to be read and is ready for accepting data available on the data bus.
RD − This signal indicates that the selected IO or memory device is to be read and is ready for accepting data available on the data bus.
WR − This signal indicates that the data on the data bus is to be written into a selected memory or IO location.
WR − This signal indicates that the data on the data bus is to be written into a selected memory or IO location.
ALE − It is a positive going pulse generated when a new operation is started by the microprocessor. When the pulse goes high, it indicates address. When the pulse goes down it indicates data.
ALE − It is a positive going pulse generated when a new operation is started by the microprocessor. When the pulse goes high, it indicates address. When the pulse goes down it indicates data.
Three status signals are IO/M, S0 & S1.
This signal is used to differentiate between IO and Memory operations, i.e. when it is high indicates IO operation and when it is low then it indicates memory operation.
These signals are used to identify the type of current operation.
There are 2 power supply signals − VCC & VSS. VCC indicates +5v power supply and VSS indicates ground signal.
There are 3 clock signals, i.e. X1, X2, CLK OUT.
X1, X2 − A crystal (RC, LC N/W) is connected at these two pins and is used to set frequency of the internal clock generator. This frequency is internally divided by 2.
X1, X2 − A crystal (RC, LC N/W) is connected at these two pins and is used to set frequency of the internal clock generator. This frequency is internally divided by 2.
CLK OUT − This signal is used as the system clock for devices connected with the microprocessor.
CLK OUT − This signal is used as the system clock for devices connected with the microprocessor.
Interrupts are the signals generated by external devices to request the microprocessor to perform a task. There are 5 interrupt signals, i.e. TRAP, RST 7.5, RST 6.5, RST 5.5, and INTR. We will discuss interrupts in detail in interrupts section.
INTA − It is an interrupt acknowledgment signal.
INTA − It is an interrupt acknowledgment signal.
RESET IN − This signal is used to reset the microprocessor by setting the program counter to zero.
RESET IN − This signal is used to reset the microprocessor by setting the program counter to zero.
RESET OUT − This signal is used to reset all the connected devices when the microprocessor is reset.
RESET OUT − This signal is used to reset all the connected devices when the microprocessor is reset.
READY − This signal indicates that the device is ready to send or receive data. If READY is low, then the CPU has to wait for READY to go high.
READY − This signal indicates that the device is ready to send or receive data. If READY is low, then the CPU has to wait for READY to go high.
HOLD − This signal indicates that another master is requesting the use of the address and data buses.
HOLD − This signal indicates that another master is requesting the use of the address and data buses.
HLDA (HOLD Acknowledge) − It indicates that the CPU has received the HOLD request and it will relinquish the bus in the next clock cycle. HLDA is set to low after the HOLD signal is removed.
HLDA (HOLD Acknowledge) − It indicates that the CPU has received the HOLD request and it will relinquish the bus in the next clock cycle. HLDA is set to low after the HOLD signal is removed.
There are 2 serial signals, i.e. SID and SOD and these signals are used for serial communication.
SOD (Serial output data line) − The output SOD is set/reset as specified by the SIM instruction.
SOD (Serial output data line) − The output SOD is set/reset as specified by the SIM instruction.
SID (Serial input data line) − The data on this line is loaded into accumulator whenever a RIM instruction is executed.
SID (Serial input data line) − The data on this line is loaded into accumulator whenever a RIM instruction is executed.
Now let us discuss the addressing modes in 8085 Microprocessor.
These are the instructions used to transfer the data from one register to another register, from the memory to the register, and from the register to the memory without any alteration in the content. Addressing modes in 8085 is classified into 5 groups −
In this mode, the 8/16-bit data is specified in the instruction itself as one of its operand. For example: MVI K, 20F: means 20F is copied into register K.
In this mode, the data is copied from one register to another. For example: MOV K, B: means data in register B is copied to register K.
In this mode, the data is directly copied from the given address to the register. For example: LDB 5000K: means the data at address 5000K is copied to register B.
In this mode, the data is transferred from one register to another by using the address pointed by the register. For example: MOV K, B: means data is transferred from the memory address pointed by the register to the register K.
This mode doesn’t require any operand; the data is specified by the opcode itself. For example: CMP.
Interrupts are the signals generated by the external devices to request the microprocessor to perform a task. There are 5 interrupt signals, i.e. TRAP, RST 7.5, RST 6.5, RST 5.5, and INTR.
Interrupt are classified into following groups based on their parameter −
Vector interrupt − In this type of interrupt, the interrupt address is known to the processor. For example: RST7.5, RST6.5, RST5.5, TRAP.
Vector interrupt − In this type of interrupt, the interrupt address is known to the processor. For example: RST7.5, RST6.5, RST5.5, TRAP.
Non-Vector interrupt − In this type of interrupt, the interrupt address is not known to the processor so, the interrupt address needs to be sent externally by the device to perform interrupts. For example: INTR.
Non-Vector interrupt − In this type of interrupt, the interrupt address is not known to the processor so, the interrupt address needs to be sent externally by the device to perform interrupts. For example: INTR.
Maskable interrupt − In this type of interrupt, we can disable the interrupt by writing some instructions into the program. For example: RST7.5, RST6.5, RST5.5.
Maskable interrupt − In this type of interrupt, we can disable the interrupt by writing some instructions into the program. For example: RST7.5, RST6.5, RST5.5.
Non-Maskable interrupt − In this type of interrupt, we cannot disable the interrupt by writing some instructions into the program. For example: TRAP.
Non-Maskable interrupt − In this type of interrupt, we cannot disable the interrupt by writing some instructions into the program. For example: TRAP.
Software interrupt − In this type of interrupt, the programmer has to add the instructions into the program to execute the interrupt. There are 8 software interrupts in 8085, i.e. RST0, RST1, RST2, RST3, RST4, RST5, RST6, and RST7.
Software interrupt − In this type of interrupt, the programmer has to add the instructions into the program to execute the interrupt. There are 8 software interrupts in 8085, i.e. RST0, RST1, RST2, RST3, RST4, RST5, RST6, and RST7.
Hardware interrupt − There are 5 interrupt pins in 8085 used as hardware interrupts, i.e. TRAP, RST7.5, RST6.5, RST5.5, INTA.
Hardware interrupt − There are 5 interrupt pins in 8085 used as hardware interrupts, i.e. TRAP, RST7.5, RST6.5, RST5.5, INTA.
Note − NTA is not an interrupt, it is used by the microprocessor for sending acknowledgement. TRAP has the highest priority, then RST7.5 and so on.
A small program or a routine that when executed, services the corresponding interrupting source is called an ISR.
It is a non-maskable interrupt, having the highest priority among all interrupts. Bydefault, it is enabled until it gets acknowledged. In case of failure, it executes as ISR and sends the data to backup memory. This interrupt transfers the control to the location 0024H.
It is a maskable interrupt, having the second highest priority among all interrupts. When this interrupt is executed, the processor saves the content of the PC register into the stack and branches to 003CH address.
It is a maskable interrupt, having the third highest priority among all interrupts. When this interrupt is executed, the processor saves the content of the PC register into the stack and branches to 0034H address.
It is a maskable interrupt. When this interrupt is executed, the processor saves the content of the PC register into the stack and branches to 002CH address.
It is a maskable interrupt, having the lowest priority among all interrupts. It can be disabled by resetting the microprocessor.
When INTR signal goes high, the following events can occur −
The microprocessor checks the status of INTR signal during the execution of each instruction.
The microprocessor checks the status of INTR signal during the execution of each instruction.
When the INTR signal is high, then the microprocessor completes its current instruction and sends active low interrupt acknowledge signal.
When the INTR signal is high, then the microprocessor completes its current instruction and sends active low interrupt acknowledge signal.
When instructions are received, then the microprocessor saves the address of the next instruction on stack and executes the received instruction.
When instructions are received, then the microprocessor saves the address of the next instruction on stack and executes the received instruction.
Let us take a look at the programming of 8085 Microprocessor.
Instruction sets are instruction codes to perform some task. It is classified into five categories.
Following is the table showing the list of Control instructions with their meanings.
Following is the table showing the list of Logical instructions with their meanings.
Following is the table showing the list of Branching instructions with their meanings.
Following is the table showing the list of Arithmetic instructions with their meanings.
Following is the table showing the list of Data-transfer instructions with their meanings.
Now, let us take a look at some program demonstrations using the above instructions −
Write a program to add data at 3005H & 3006H memory location and store the result at 3007H memory location.
Problem demo −
(3005H) = 14H
(3006H) = 89H
Result −
14H + 89H = 9DH
The program code can be written like this −
LXI H 3005H : "HL points 3005H"
MOV A, M : "Getting first operand"
INX H : "HL points 3006H"
ADD M : "Add second operand"
INX H : "HL points 3007H"
MOV M, A : "Store result at 3007H"
HLT : "Exit program"
Write a program to exchange the data at 5000M& 6000M memory location.
LDA 5000M : "Getting the contents at5000M location into accumulator"
MOV B, A : "Save the contents into B register"
LDA 6000M : "Getting the contents at 6000M location into accumulator"
STA 5000M : "Store the contents of accumulator at address 5000M"
MOV A, B : "Get the saved contents back into A register"
STA 6000M : "Store the contents of accumulator at address 6000M"
Write a program to arrange first 10 numbers from memory address 3000H in an ascending order.
MVI B, 09 :"Initialize counter"
START :"LXI H, 3000H: Initialize memory pointer"
MVI C, 09H :"Initialize counter 2"
BACK: MOV A, M :"Get the number"
INX H :"Increment memory pointer"
CMP M :"Compare number with next number"
JC SKIP :"If less, don’t interchange"
JZ SKIP :"If equal, don’t interchange"
MOV D, M
MOV M, A
DCX H
MOV M, D
INX H :"Interchange two numbers"
SKIP:DCR C :"Decrement counter 2"
JNZ BACK :"If not zero, repeat"
DCR B :"Decrement counter 1"
JNZ START
HLT :"Terminate program execution"
8086 Microprocessor is an enhanced version of 8085Microprocessor that was designed by Intel in 1976. It is a 16-bit Microprocessor having 20 address lines and16 data lines that provides up to 1MB storage. It consists of powerful instruction set, which provides operations like multiplication and division easily.
It supports two modes of operation, i.e. Maximum mode and Minimum mode. Maximum mode is suitable for system having multiple processors and Minimum mode is suitable for system having a single processor.
The most prominent features of a 8086 microprocessor are as follows −
It has an instruction queue, which is capable of storing six instruction bytes from the memory resulting in faster processing.
It has an instruction queue, which is capable of storing six instruction bytes from the memory resulting in faster processing.
It was the first 16-bit processor having 16-bit ALU, 16-bit registers, internal data bus, and 16-bit external data bus resulting in faster processing.
It was the first 16-bit processor having 16-bit ALU, 16-bit registers, internal data bus, and 16-bit external data bus resulting in faster processing.
It is available in 3 versions based on the frequency of operation −
8086 → 5MHz
8086-2 → 8MHz
(c)8086-1 → 10 MHz
It is available in 3 versions based on the frequency of operation −
8086 → 5MHz
8086 → 5MHz
8086-2 → 8MHz
8086-2 → 8MHz
(c)8086-1 → 10 MHz
(c)8086-1 → 10 MHz
It uses two stages of pipelining, i.e. Fetch Stage and Execute Stage, which improves performance.
It uses two stages of pipelining, i.e. Fetch Stage and Execute Stage, which improves performance.
Fetch stage can prefetch up to 6 bytes of instructions and stores them in the queue.
Fetch stage can prefetch up to 6 bytes of instructions and stores them in the queue.
Execute stage executes these instructions.
Execute stage executes these instructions.
It has 256 vectored interrupts.
It has 256 vectored interrupts.
It consists of 29,000 transistors.
It consists of 29,000 transistors.
Size − 8085 is 8-bit microprocessor, whereas 8086 is 16-bit microprocessor.
Size − 8085 is 8-bit microprocessor, whereas 8086 is 16-bit microprocessor.
Address Bus − 8085 has 16-bit address bus while 8086 has 20-bit address bus.
Address Bus − 8085 has 16-bit address bus while 8086 has 20-bit address bus.
Memory − 8085 can access up to 64Kb, whereas 8086 can access up to 1 Mb of memory.
Memory − 8085 can access up to 64Kb, whereas 8086 can access up to 1 Mb of memory.
Instruction − 8085 doesn’t have an instruction queue, whereas 8086 has an instruction queue.
Instruction − 8085 doesn’t have an instruction queue, whereas 8086 has an instruction queue.
Pipelining − 8085 doesn’t support a pipelined architecture while 8086 supports a pipelined architecture.
Pipelining − 8085 doesn’t support a pipelined architecture while 8086 supports a pipelined architecture.
I/O − 8085 can address 2^8 = 256 I/O's, whereas 8086 can access 2^16 = 65,536 I/O's.
I/O − 8085 can address 2^8 = 256 I/O's, whereas 8086 can access 2^16 = 65,536 I/O's.
Cost − The cost of 8085 is low whereas that of 8086 is high.
Cost − The cost of 8085 is low whereas that of 8086 is high.
The following diagram depicts the architecture of a 8086 Microprocessor −
8086 Microprocessor is divided into two functional units, i.e., EU (Execution Unit) and BIU (Bus Interface Unit).
Execution unit gives instructions to BIU stating from where to fetch the data and then decode and execute those instructions. Its function is to control operations on data using the instruction decoder & ALU. EU has no direct connection with system buses as shown in the above figure, it performs operations over data through BIU.
Let us now discuss the functional parts of 8086 microprocessors.
It handles all arithmetic and logical operations, like +, −, ×, /, OR, AND, NOT operations.
It is a 16-bit register that behaves like a flip-flop, i.e. it changes its status according to the result stored in the accumulator. It has 9 flags and they are divided into 2 groups − Conditional Flags and Control Flags.
It represents the result of the last arithmetic or logical instruction executed. Following is the list of conditional flags −
Carry flag − This flag indicates an overflow condition for arithmetic operations.
Carry flag − This flag indicates an overflow condition for arithmetic operations.
Auxiliary flag − When an operation is performed at ALU, it results in a carry/barrow from lower nibble (i.e. D0 – D3) to upper nibble (i.e. D4 – D7), then this flag is set, i.e. carry given by D3 bit to D4 is AF flag. The processor uses this flag to perform binary to BCD conversion.
Auxiliary flag − When an operation is performed at ALU, it results in a carry/barrow from lower nibble (i.e. D0 – D3) to upper nibble (i.e. D4 – D7), then this flag is set, i.e. carry given by D3 bit to D4 is AF flag. The processor uses this flag to perform binary to BCD conversion.
Parity flag − This flag is used to indicate the parity of the result, i.e. when the lower order 8-bits of the result contains even number of 1’s, then the Parity Flag is set. For odd number of 1’s, the Parity Flag is reset.
Parity flag − This flag is used to indicate the parity of the result, i.e. when the lower order 8-bits of the result contains even number of 1’s, then the Parity Flag is set. For odd number of 1’s, the Parity Flag is reset.
Zero flag − This flag is set to 1 when the result of arithmetic or logical operation is zero else it is set to 0.
Zero flag − This flag is set to 1 when the result of arithmetic or logical operation is zero else it is set to 0.
Sign flag − This flag holds the sign of the result, i.e. when the result of the operation is negative, then the sign flag is set to 1 else set to 0.
Sign flag − This flag holds the sign of the result, i.e. when the result of the operation is negative, then the sign flag is set to 1 else set to 0.
Overflow flag − This flag represents the result when the system capacity is exceeded.
Overflow flag − This flag represents the result when the system capacity is exceeded.
Control flags controls the operations of the execution unit. Following is the list of control flags −
Trap flag − It is used for single step control and allows the user to execute one instruction at a time for debugging. If it is set, then the program can be run in a single step mode.
Trap flag − It is used for single step control and allows the user to execute one instruction at a time for debugging. If it is set, then the program can be run in a single step mode.
Interrupt flag − It is an interrupt enable/disable flag, i.e. used to allow/prohibit the interruption of a program. It is set to 1 for interrupt enabled condition and set to 0 for interrupt disabled condition.
Interrupt flag − It is an interrupt enable/disable flag, i.e. used to allow/prohibit the interruption of a program. It is set to 1 for interrupt enabled condition and set to 0 for interrupt disabled condition.
Direction flag − It is used in string operation. As the name suggests when it is set then string bytes are accessed from the higher memory address to the lower memory address and vice-a-versa.
Direction flag − It is used in string operation. As the name suggests when it is set then string bytes are accessed from the higher memory address to the lower memory address and vice-a-versa.
There are 8 general purpose registers, i.e., AH, AL, BH, BL, CH, CL, DH, and DL. These registers can be used individually to store 8-bit data and can be used in pairs to store 16bit data. The valid register pairs are AH and AL, BH and BL, CH and CL, and DH and DL. It is referred to the AX, BX, CX, and DX respectively.
AX register − It is also known as accumulator register. It is used to store operands for arithmetic operations.
AX register − It is also known as accumulator register. It is used to store operands for arithmetic operations.
BX register − It is used as a base register. It is used to store the starting base address of the memory area within the data segment.
BX register − It is used as a base register. It is used to store the starting base address of the memory area within the data segment.
CX register − It is referred to as counter. It is used in loop instruction to store the loop counter.
CX register − It is referred to as counter. It is used in loop instruction to store the loop counter.
DX register − This register is used to hold I/O port address for I/O instruction.
DX register − This register is used to hold I/O port address for I/O instruction.
It is a 16-bit register, which holds the address from the start of the segment to the memory location, where a word was most recently stored on the stack.
BIU takes care of all data and addresses transfers on the buses for the EU like sending addresses, fetching instructions from the memory, reading data from the ports and the memory as well as writing data to the ports and the memory. EU has no direction connection with System Buses so this is possible with the BIU. EU and BIU are connected with the Internal Bus.
It has the following functional parts −
Instruction queue − BIU contains the instruction queue. BIU gets upto 6 bytes of next instructions and stores them in the instruction queue. When EU executes instructions and is ready for its next instruction, then it simply reads the instruction from this instruction queue resulting in increased execution speed.
Instruction queue − BIU contains the instruction queue. BIU gets upto 6 bytes of next instructions and stores them in the instruction queue. When EU executes instructions and is ready for its next instruction, then it simply reads the instruction from this instruction queue resulting in increased execution speed.
Fetching the next instruction while the current instruction executes is called pipelining.
Fetching the next instruction while the current instruction executes is called pipelining.
Segment register − BIU has 4 segment buses, i.e. CS, DS, SS& ES. It holds the addresses of instructions and data in memory, which are used by the processor to access memory locations. It also contains 1 pointer register IP, which holds the address of the next instruction to executed by the EU.
CS − It stands for Code Segment. It is used for addressing a memory location in the code segment of the memory, where the executable program is stored.
DS − It stands for Data Segment. It consists of data used by the program andis accessed in the data segment by an offset address or the content of other register that holds the offset address.
SS − It stands for Stack Segment. It handles memory to store data and addresses during execution.
ES − It stands for Extra Segment. ES is additional data segment, which is used by the string to hold the extra destination data.
Segment register − BIU has 4 segment buses, i.e. CS, DS, SS& ES. It holds the addresses of instructions and data in memory, which are used by the processor to access memory locations. It also contains 1 pointer register IP, which holds the address of the next instruction to executed by the EU.
CS − It stands for Code Segment. It is used for addressing a memory location in the code segment of the memory, where the executable program is stored.
CS − It stands for Code Segment. It is used for addressing a memory location in the code segment of the memory, where the executable program is stored.
DS − It stands for Data Segment. It consists of data used by the program andis accessed in the data segment by an offset address or the content of other register that holds the offset address.
DS − It stands for Data Segment. It consists of data used by the program andis accessed in the data segment by an offset address or the content of other register that holds the offset address.
SS − It stands for Stack Segment. It handles memory to store data and addresses during execution.
SS − It stands for Stack Segment. It handles memory to store data and addresses during execution.
ES − It stands for Extra Segment. ES is additional data segment, which is used by the string to hold the extra destination data.
ES − It stands for Extra Segment. ES is additional data segment, which is used by the string to hold the extra destination data.
Instruction pointer − It is a 16-bit register used to hold the address of the next instruction to be executed.
Instruction pointer − It is a 16-bit register used to hold the address of the next instruction to be executed.
8086 was the first 16-bit microprocessor available in 40-pin DIP (Dual Inline Package) chip. Let us now discuss in detail the pin configuration of a 8086 Microprocessor.
Here is the pin diagram of 8086 microprocessor −
Let us now discuss the signals in detail −
Power supply and frequency signals
It uses 5V DC supply at VCC pin 40, and uses ground at VSS pin 1 and 20 for its operation.
Clock signal
Clock signal is provided through Pin-19. It provides timing to the processor for operations. Its frequency is different for different versions, i.e. 5MHz, 8MHz and 10MHz.
Address/data bus
AD0-AD15. These are 16 address/data bus. AD0-AD7 carries low order byte data and AD8AD15 carries higher order byte data. During the first clock cycle, it carries 16-bit address and after that it carries 16-bit data.
Address/status bus
A16-A19/S3-S6. These are the 4 address/status buses. During the first clock cycle, it carries 4-bit address and later it carries status signals.
S7/BHE
BHE stands for Bus High Enable. It is available at pin 34 and used to indicate the transfer of data using data bus D8-D15. This signal is low during the first clock cycle, thereafter it is active.
Read($\overline{RD}$)
It is available at pin 32 and is used to read signal for Read operation.
Ready
It is available at pin 22. It is an acknowledgement signal from I/O devices that data is transferred. It is an active high signal. When it is high, it indicates that the device is ready to transfer data. When it is low, it indicates wait state.
RESET
It is available at pin 21 and is used to restart the execution. It causes the processor to immediately terminate its present activity. This signal is active high for the first 4 clock cycles to RESET the microprocessor.
INTR
It is available at pin 18. It is an interrupt request signal, which is sampled during the last clock cycle of each instruction to determine if the processor considered this as an interrupt or not.
NMI
It stands for non-maskable interrupt and is available at pin 17. It is an edge triggered input, which causes an interrupt request to the microprocessor.
$\overline{TEST}$
This signal is like wait state and is available at pin 23. When this signal is high, then the processor has to wait for IDLE state, else the execution continues.
MN/$\overline{MX}$
It stands for Minimum/Maximum and is available at pin 33. It indicates what mode the processor is to operate in; when it is high, it works in the minimum mode and vice-aversa.
INTA
It is an interrupt acknowledgement signal and id available at pin 24. When the microprocessor receives this signal, it acknowledges the interrupt.
ALE
It stands for address enable latch and is available at pin 25. A positive pulse is generated each time the processor begins any operation. This signal indicates the availability of a valid address on the address/data lines.
DEN
It stands for Data Enable and is available at pin 26. It is used to enable Transreceiver 8286. The transreceiver is a device used to separate data from the address/data bus.
DT/R
It stands for Data Transmit/Receive signal and is available at pin 27. It decides the direction of data flow through the transreceiver. When it is high, data is transmitted out and vice-a-versa.
M/IO
This signal is used to distinguish between memory and I/O operations. When it is high, it indicates I/O operation and when it is low indicates the memory operation. It is available at pin 28.
WR
It stands for write signal and is available at pin 29. It is used to write the data into the memory or the output device depending on the status of M/IO signal.
HLDA
It stands for Hold Acknowledgement signal and is available at pin 30. This signal acknowledges the HOLD signal.
HOLD
This signal indicates to the processor that external devices are requesting to access the address/data buses. It is available at pin 31.
QS1 and QS0
These are queue status signals and are available at pin 24 and 25. These signals provide the status of instruction queue. Their conditions are shown in the following table −
S0, S1, S2
These are the status signals that provide the status of operation, which is used by the Bus Controller 8288 to generate memory & I/O control signals. These are available at pin 26, 27, and 28. Following is the table showing their status −
LOCK
When this signal is active, it indicates to the other processors not to ask the CPU to leave the system bus. It is activated using the LOCK prefix on any instruction and is available at pin 29.
RQ/GT1 and RQ/GT0
These are the Request/Grant signals used by the other processors requesting the CPU to release the system bus. When the signal is received by CPU, then it sends acknowledgment. RQ/GT0 has a higher priority than RQ/GT1.
The 8086 microprocessor supports 8 types of instructions −
Data Transfer Instructions
Arithmetic Instructions
Bit Manipulation Instructions
String Instructions
Program Execution Transfer Instructions (Branch & Loop Instructions)
Processor Control Instructions
Iteration Control Instructions
Interrupt Instructions
Let us now discuss these instruction sets in detail.
These instructions are used to transfer the data from the source operand to the destination operand. Following are the list of instructions under this group −
MOV − Used to copy the byte or word from the provided source to the provided destination.
MOV − Used to copy the byte or word from the provided source to the provided destination.
PPUSH − Used to put a word at the top of the stack.
PPUSH − Used to put a word at the top of the stack.
POP − Used to get a word from the top of the stack to the provided location.
POP − Used to get a word from the top of the stack to the provided location.
PUSHA − Used to put all the registers into the stack.
PUSHA − Used to put all the registers into the stack.
POPA − Used to get words from the stack to all registers.
POPA − Used to get words from the stack to all registers.
XCHG − Used to exchange the data from two locations.
XCHG − Used to exchange the data from two locations.
XLAT − Used to translate a byte in AL using a table in the memory.
XLAT − Used to translate a byte in AL using a table in the memory.
IN − Used to read a byte or word from the provided port to the accumulator.
IN − Used to read a byte or word from the provided port to the accumulator.
OUT − Used to send out a byte or word from the accumulator to the provided port.
OUT − Used to send out a byte or word from the accumulator to the provided port.
LEA − Used to load the address of operand into the provided register.
LEA − Used to load the address of operand into the provided register.
LDS − Used to load DS register and other provided register from the memory
LDS − Used to load DS register and other provided register from the memory
LES − Used to load ES register and other provided register from the memory.
LES − Used to load ES register and other provided register from the memory.
LAHF − Used to load AH with the low byte of the flag register.
LAHF − Used to load AH with the low byte of the flag register.
SAHF − Used to store AH register to low byte of the flag register.
SAHF − Used to store AH register to low byte of the flag register.
PUSHF − Used to copy the flag register at the top of the stack.
PUSHF − Used to copy the flag register at the top of the stack.
POPF − Used to copy a word at the top of the stack to the flag register.
POPF − Used to copy a word at the top of the stack to the flag register.
These instructions are used to perform arithmetic operations like addition, subtraction, multiplication, division, etc.
Following is the list of instructions under this group −
ADD − Used to add the provided byte to byte/word to word.
ADD − Used to add the provided byte to byte/word to word.
ADC − Used to add with carry.
ADC − Used to add with carry.
INC − Used to increment the provided byte/word by 1.
INC − Used to increment the provided byte/word by 1.
AAA − Used to adjust ASCII after addition.
AAA − Used to adjust ASCII after addition.
DAA − Used to adjust the decimal after the addition/subtraction operation.
DAA − Used to adjust the decimal after the addition/subtraction operation.
SUB − Used to subtract the byte from byte/word from word.
SUB − Used to subtract the byte from byte/word from word.
SBB − Used to perform subtraction with borrow.
SBB − Used to perform subtraction with borrow.
DEC − Used to decrement the provided byte/word by 1.
DEC − Used to decrement the provided byte/word by 1.
NPG − Used to negate each bit of the provided byte/word and add 1/2’s complement.
NPG − Used to negate each bit of the provided byte/word and add 1/2’s complement.
CMP − Used to compare 2 provided byte/word.
CMP − Used to compare 2 provided byte/word.
AAS − Used to adjust ASCII codes after subtraction.
AAS − Used to adjust ASCII codes after subtraction.
DAS − Used to adjust decimal after subtraction.
DAS − Used to adjust decimal after subtraction.
MUL − Used to multiply unsigned byte by byte/word by word.
MUL − Used to multiply unsigned byte by byte/word by word.
IMUL − Used to multiply signed byte by byte/word by word.
IMUL − Used to multiply signed byte by byte/word by word.
AAM − Used to adjust ASCII codes after multiplication.
AAM − Used to adjust ASCII codes after multiplication.
DIV − Used to divide the unsigned word by byte or unsigned double word by word.
DIV − Used to divide the unsigned word by byte or unsigned double word by word.
IDIV − Used to divide the signed word by byte or signed double word by word.
IDIV − Used to divide the signed word by byte or signed double word by word.
AAD − Used to adjust ASCII codes after division.
AAD − Used to adjust ASCII codes after division.
CBW − Used to fill the upper byte of the word with the copies of sign bit of the lower byte.
CBW − Used to fill the upper byte of the word with the copies of sign bit of the lower byte.
CWD − Used to fill the upper word of the double word with the sign bit of the lower word.
CWD − Used to fill the upper word of the double word with the sign bit of the lower word.
These instructions are used to perform operations where data bits are involved, i.e. operations like logical, shift, etc.
Following is the list of instructions under this group −
NOT − Used to invert each bit of a byte or word.
NOT − Used to invert each bit of a byte or word.
AND − Used for adding each bit in a byte/word with the corresponding bit in another byte/word.
AND − Used for adding each bit in a byte/word with the corresponding bit in another byte/word.
OR − Used to multiply each bit in a byte/word with the corresponding bit in another byte/word.
OR − Used to multiply each bit in a byte/word with the corresponding bit in another byte/word.
XOR − Used to perform Exclusive-OR operation over each bit in a byte/word with the corresponding bit in another byte/word.
XOR − Used to perform Exclusive-OR operation over each bit in a byte/word with the corresponding bit in another byte/word.
TEST − Used to add operands to update flags, without affecting operands.
TEST − Used to add operands to update flags, without affecting operands.
SHL/SAL − Used to shift bits of a byte/word towards left and put zero(S) in LSBs.
SHL/SAL − Used to shift bits of a byte/word towards left and put zero(S) in LSBs.
SHR − Used to shift bits of a byte/word towards the right and put zero(S) in MSBs.
SHR − Used to shift bits of a byte/word towards the right and put zero(S) in MSBs.
SAR − Used to shift bits of a byte/word towards the right and copy the old MSB into the new MSB.
SAR − Used to shift bits of a byte/word towards the right and copy the old MSB into the new MSB.
ROL − Used to rotate bits of byte/word towards the left, i.e. MSB to LSB and to Carry Flag [CF].
ROL − Used to rotate bits of byte/word towards the left, i.e. MSB to LSB and to Carry Flag [CF].
ROR − Used to rotate bits of byte/word towards the right, i.e. LSB to MSB and to Carry Flag [CF].
ROR − Used to rotate bits of byte/word towards the right, i.e. LSB to MSB and to Carry Flag [CF].
RCR − Used to rotate bits of byte/word towards the right, i.e. LSB to CF and CF to MSB.
RCR − Used to rotate bits of byte/word towards the right, i.e. LSB to CF and CF to MSB.
RCL − Used to rotate bits of byte/word towards the left, i.e. MSB to CF and CF to LSB.
RCL − Used to rotate bits of byte/word towards the left, i.e. MSB to CF and CF to LSB.
String is a group of bytes/words and their memory is always allocated in a sequential order.
Following is the list of instructions under this group −
REP − Used to repeat the given instruction till CX ≠ 0.
REP − Used to repeat the given instruction till CX ≠ 0.
REPE/REPZ − Used to repeat the given instruction until CX = 0 or zero flag ZF = 1.
REPE/REPZ − Used to repeat the given instruction until CX = 0 or zero flag ZF = 1.
REPNE/REPNZ − Used to repeat the given instruction until CX = 0 or zero flag ZF = 1.
REPNE/REPNZ − Used to repeat the given instruction until CX = 0 or zero flag ZF = 1.
MOVS/MOVSB/MOVSW − Used to move the byte/word from one string to another.
MOVS/MOVSB/MOVSW − Used to move the byte/word from one string to another.
COMS/COMPSB/COMPSW − Used to compare two string bytes/words.
COMS/COMPSB/COMPSW − Used to compare two string bytes/words.
INS/INSB/INSW − Used as an input string/byte/word from the I/O port to the provided memory location.
INS/INSB/INSW − Used as an input string/byte/word from the I/O port to the provided memory location.
OUTS/OUTSB/OUTSW − Used as an output string/byte/word from the provided memory location to the I/O port.
OUTS/OUTSB/OUTSW − Used as an output string/byte/word from the provided memory location to the I/O port.
SCAS/SCASB/SCASW − Used to scan a string and compare its byte with a byte in AL or string word with a word in AX.
SCAS/SCASB/SCASW − Used to scan a string and compare its byte with a byte in AL or string word with a word in AX.
LODS/LODSB/LODSW − Used to store the string byte into AL or string word into AX.
LODS/LODSB/LODSW − Used to store the string byte into AL or string word into AX.
These instructions are used to transfer/branch the instructions during an execution. It includes the following instructions −
Instructions to transfer the instruction during an execution without any condition −
CALL − Used to call a procedure and save their return address to the stack.
CALL − Used to call a procedure and save their return address to the stack.
RET − Used to return from the procedure to the main program.
RET − Used to return from the procedure to the main program.
JMP − Used to jump to the provided address to proceed to the next instruction.
JMP − Used to jump to the provided address to proceed to the next instruction.
Instructions to transfer the instruction during an execution with some conditions −
JA/JNBE − Used to jump if above/not below/equal instruction satisfies.
JA/JNBE − Used to jump if above/not below/equal instruction satisfies.
JAE/JNB − Used to jump if above/not below instruction satisfies.
JAE/JNB − Used to jump if above/not below instruction satisfies.
JBE/JNA − Used to jump if below/equal/ not above instruction satisfies.
JBE/JNA − Used to jump if below/equal/ not above instruction satisfies.
JC − Used to jump if carry flag CF = 1
JC − Used to jump if carry flag CF = 1
JE/JZ − Used to jump if equal/zero flag ZF = 1
JE/JZ − Used to jump if equal/zero flag ZF = 1
JG/JNLE − Used to jump if greater/not less than/equal instruction satisfies.
JG/JNLE − Used to jump if greater/not less than/equal instruction satisfies.
JGE/JNL − Used to jump if greater than/equal/not less than instruction satisfies.
JGE/JNL − Used to jump if greater than/equal/not less than instruction satisfies.
JL/JNGE − Used to jump if less than/not greater than/equal instruction satisfies.
JL/JNGE − Used to jump if less than/not greater than/equal instruction satisfies.
JLE/JNG − Used to jump if less than/equal/if not greater than instruction satisfies.
JLE/JNG − Used to jump if less than/equal/if not greater than instruction satisfies.
JNC − Used to jump if no carry flag (CF = 0)
JNC − Used to jump if no carry flag (CF = 0)
JNE/JNZ − Used to jump if not equal/zero flag ZF = 0
JNE/JNZ − Used to jump if not equal/zero flag ZF = 0
JNO − Used to jump if no overflow flag OF = 0
JNO − Used to jump if no overflow flag OF = 0
JNP/JPO − Used to jump if not parity/parity odd PF = 0
JNP/JPO − Used to jump if not parity/parity odd PF = 0
JNS − Used to jump if not sign SF = 0
JNS − Used to jump if not sign SF = 0
JO − Used to jump if overflow flag OF = 1
JO − Used to jump if overflow flag OF = 1
JP/JPE − Used to jump if parity/parity even PF = 1
JP/JPE − Used to jump if parity/parity even PF = 1
JS − Used to jump if sign flag SF = 1
JS − Used to jump if sign flag SF = 1
These instructions are used to control the processor action by setting/resetting the flag values.
Following are the instructions under this group −
STC − Used to set carry flag CF to 1
STC − Used to set carry flag CF to 1
CLC − Used to clear/reset carry flag CF to 0
CLC − Used to clear/reset carry flag CF to 0
CMC − Used to put complement at the state of carry flag CF.
CMC − Used to put complement at the state of carry flag CF.
STD − Used to set the direction flag DF to 1
STD − Used to set the direction flag DF to 1
CLD − Used to clear/reset the direction flag DF to 0
CLD − Used to clear/reset the direction flag DF to 0
STI − Used to set the interrupt enable flag to 1, i.e., enable INTR input.
STI − Used to set the interrupt enable flag to 1, i.e., enable INTR input.
CLI − Used to clear the interrupt enable flag to 0, i.e., disable INTR input.
CLI − Used to clear the interrupt enable flag to 0, i.e., disable INTR input.
These instructions are used to execute the given instructions for number of times. Following is the list of instructions under this group −
LOOP − Used to loop a group of instructions until the condition satisfies, i.e., CX = 0
LOOP − Used to loop a group of instructions until the condition satisfies, i.e., CX = 0
LOOPE/LOOPZ − Used to loop a group of instructions till it satisfies ZF = 1 & CX = 0
LOOPE/LOOPZ − Used to loop a group of instructions till it satisfies ZF = 1 & CX = 0
LOOPNE/LOOPNZ − Used to loop a group of instructions till it satisfies ZF = 0 & CX = 0
LOOPNE/LOOPNZ − Used to loop a group of instructions till it satisfies ZF = 0 & CX = 0
JCXZ − Used to jump to the provided address if CX = 0
JCXZ − Used to jump to the provided address if CX = 0
These instructions are used to call the interrupt during program execution.
INT − Used to interrupt the program during execution and calling service specified.
INT − Used to interrupt the program during execution and calling service specified.
INTO − Used to interrupt the program during execution if OF = 1
INTO − Used to interrupt the program during execution if OF = 1
IRET − Used to return from interrupt service to the main program
IRET − Used to return from interrupt service to the main program
Interrupt is the method of creating a temporary halt during program execution and allows peripheral devices to access the microprocessor. The microprocessor responds to that interrupt with an ISR (Interrupt Service Routine), which is a short program to instruct the microprocessor on how to handle the interrupt.
The following image shows the types of interrupts we have in a 8086 microprocessor −
Hardware interrupt is caused by any peripheral device by sending a signal through a specified pin to the microprocessor.
The 8086 has two hardware interrupt pins, i.e. NMI and INTR. NMI is a non-maskable interrupt and INTR is a maskable interrupt having lower priority. One more interrupt pin associated is INTA called interrupt acknowledge.
It is a single non-maskable interrupt pin (NMI) having higher priority than the maskable interrupt request pin (INTR)and it is of type 2 interrupt.
When this interrupt is activated, these actions take place −
Completes the current instruction that is in progress.
Completes the current instruction that is in progress.
Pushes the Flag register values on to the stack.
Pushes the Flag register values on to the stack.
Pushes the CS (code segment) value and IP (instruction pointer) value of the return address on to the stack.
Pushes the CS (code segment) value and IP (instruction pointer) value of the return address on to the stack.
IP is loaded from the contents of the word location 00008H.
IP is loaded from the contents of the word location 00008H.
CS is loaded from the contents of the next word location 0000AH.
CS is loaded from the contents of the next word location 0000AH.
Interrupt flag and trap flag are reset to 0.
Interrupt flag and trap flag are reset to 0.
The INTR is a maskable interrupt because the microprocessor will be interrupted only if interrupts are enabled using set interrupt flag instruction. It should not be enabled using clear interrupt Flag instruction.
The INTR interrupt is activated by an I/O port. If the interrupt is enabled and NMI is disabled, then the microprocessor first completes the current execution and sends ‘0’ on INTA pin twice. The first ‘0’ means INTA informs the external device to get ready and during the second ‘0’ the microprocessor receives the 8 bit, say X, from the programmable interrupt controller.
These actions are taken by the microprocessor −
First completes the current instruction.
First completes the current instruction.
Activates INTA output and receives the interrupt type, say X.
Activates INTA output and receives the interrupt type, say X.
Flag register value, CS value of the return address and IP value of the return address are pushed on to the stack.
Flag register value, CS value of the return address and IP value of the return address are pushed on to the stack.
IP value is loaded from the contents of word location X × 4
IP value is loaded from the contents of word location X × 4
CS is loaded from the contents of the next word location.
CS is loaded from the contents of the next word location.
Interrupt flag and trap flag is reset to 0
Interrupt flag and trap flag is reset to 0
Some instructions are inserted at the desired position into the program to create interrupts. These interrupt instructions can be used to test the working of various interrupt handlers. It includes −
It is 2-byte instruction. First byte provides the op-code and the second byte provides the interrupt type number. There are 256 interrupt types under this group.
Its execution includes the following steps −
Flag register value is pushed on to the stack.
Flag register value is pushed on to the stack.
CS value of the return address and IP value of the return address are pushed on to the stack.
CS value of the return address and IP value of the return address are pushed on to the stack.
IP is loaded from the contents of the word location ‘type number’ × 4
IP is loaded from the contents of the word location ‘type number’ × 4
CS is loaded from the contents of the next word location.
CS is loaded from the contents of the next word location.
Interrupt Flag and Trap Flag are reset to 0
Interrupt Flag and Trap Flag are reset to 0
The starting address for type0 interrupt is 000000H, for type1 interrupt is 00004H similarly for type2 is 00008H and ......so on. The first five pointers are dedicated interrupt pointers. i.e. −
TYPE 0 interrupt represents division by zero situation.
TYPE 0 interrupt represents division by zero situation.
TYPE 1 interrupt represents single-step execution during the debugging of a program.
TYPE 1 interrupt represents single-step execution during the debugging of a program.
TYPE 2 interrupt represents non-maskable NMI interrupt.
TYPE 2 interrupt represents non-maskable NMI interrupt.
TYPE 3 interrupt represents break-point interrupt.
TYPE 3 interrupt represents break-point interrupt.
TYPE 4 interrupt represents overflow interrupt.
TYPE 4 interrupt represents overflow interrupt.
The interrupts from Type 5 to Type 31 are reserved for other advanced microprocessors, and interrupts from 32 to Type 255 are available for hardware and software interrupts.
It is a 1-byte instruction having op-code is CCH. These instructions are inserted into the program so that when the processor reaches there, then it stops the normal execution of program and follows the break-point procedure.
Its execution includes the following steps −
Flag register value is pushed on to the stack.
Flag register value is pushed on to the stack.
CS value of the return address and IP value of the return address are pushed on to the stack.
CS value of the return address and IP value of the return address are pushed on to the stack.
IP is loaded from the contents of the word location 3×4 = 0000CH
IP is loaded from the contents of the word location 3×4 = 0000CH
CS is loaded from the contents of the next word location.
CS is loaded from the contents of the next word location.
Interrupt Flag and Trap Flag are reset to 0
Interrupt Flag and Trap Flag are reset to 0
It is a 1-byte instruction and their mnemonic INTO. The op-code for this instruction is CEH. As the name suggests it is a conditional interrupt instruction, i.e. it is active only when the overflow flag is set to 1 and branches to the interrupt handler whose interrupt type number is 4. If the overflow flag is reset then, the execution continues to the next instruction.
Its execution includes the following steps −
Flag register values are pushed on to the stack.
Flag register values are pushed on to the stack.
CS value of the return address and IP value of the return address are pushed on to the stack.
CS value of the return address and IP value of the return address are pushed on to the stack.
IP is loaded from the contents of word location 4×4 = 00010H
IP is loaded from the contents of word location 4×4 = 00010H
CS is loaded from the contents of the next word location.
CS is loaded from the contents of the next word location.
Interrupt flag and Trap flag are reset to 0
Interrupt flag and Trap flag are reset to 0
The different ways in which a source operand is denoted in an instruction is known as addressing modes. There are 8 different addressing modes in 8086 programming −
The addressing mode in which the data operand is a part of the instruction itself is known as immediate addressing mode.
MOV CX, 4929 H, ADD AX, 2387 H, MOV AL, FFH
It means that the register is the source of an operand for an instruction.
MOV CX, AX ; copies the contents of the 16-bit AX register into
; the 16-bit CX register),
ADD BX, AX
The addressing mode in which the effective address of the memory location is written directly in the instruction.
MOV AX, [1592H], MOV AL, [0300H]
This addressing mode allows data to be addressed at any memory location through an offset address held in any of the following registers: BP, BX, DI & SI.
MOV AX, [BX] ; Suppose the register BX contains 4895H, then the contents
; 4895H are moved to AX
ADD CX, {BX}
In this addressing mode, the offset address of the operand is given by the sum of contents of the BX/BP registers and 8-bit/16-bit displacement.
MOV DX, [BX+04], ADD CL, [BX+08]
In this addressing mode, the operands offset address is found by adding the contents of SI or DI register and 8-bit/16-bit displacements.
MOV BX, [SI+16], ADD AL, [DI+16]
In this addressing mode, the offset address of the operand is computed by summing the base register to the contents of an Index register.
ADD CX, [AX+SI], MOV AX, [AX+DI]
In this addressing mode, the operands offset is computed by adding the base register contents. An Index registers contents and 8 or 16-bit displacement.
MOV AX, [BX+DI+08], ADD CX, [BX+SI+16]
Multiprocessor means a multiple set of processors that executes instructions simultaneously. There are three basic multiprocessor configurations.
Coprocessor configuration
Closely coupled configuration
Loosely coupled configuration
A Coprocessor is a specially designed circuit on microprocessor chip which can perform the same task very quickly, which the microprocessor performs. It reduces the work load of the main processor. The coprocessor shares the same memory, IO system, bus, control logic and clock generator. The coprocessor handles specialized tasks like mathematical calculations, graphical display on screen, etc.
The 8086 and 8088 can perform most of the operations but their instruction set is not able to perform complex mathematical operations, so in these cases the microprocessor requires the math coprocessor like Intel 8087 math coprocessor, which can easily perform these operations very quickly.
The coprocessor and the processor is connected via TEST, RQ-/GT- and QS0 & QS1 signals.
The coprocessor and the processor is connected via TEST, RQ-/GT- and QS0 & QS1 signals.
The TEST signal is connected to BUSY pin of coprocessor and the remaining 3 pins are connected to the coprocessor’s 3 pins of the same name.
The TEST signal is connected to BUSY pin of coprocessor and the remaining 3 pins are connected to the coprocessor’s 3 pins of the same name.
TEST signal takes care of the coprocessor’s activity, i.e. the coprocessor is busy or idle.
TEST signal takes care of the coprocessor’s activity, i.e. the coprocessor is busy or idle.
The RT-/GT-is used for bus arbitration.
The RT-/GT-is used for bus arbitration.
The coprocessor uses QS0 & QS1 to track the status of the queue of the host processor.
The coprocessor uses QS0 & QS1 to track the status of the queue of the host processor.
Closely coupled configuration is similar to the coprocessor configuration, i.e. both share the same memory, I/O system bus, control logic, and control generator with the host processor. However, the coprocessor and the host processor fetches and executes their own instructions. The system bus is controlled by the coprocessor and the host processor independently.
Communication between the host and the independent processor is done through memory space.
Communication between the host and the independent processor is done through memory space.
None of the instructions are used for communication, like WAIT, ESC, etc.
None of the instructions are used for communication, like WAIT, ESC, etc.
The host processor manages the memory and wakes up the independent processor by sending commands to one of its ports.
The host processor manages the memory and wakes up the independent processor by sending commands to one of its ports.
Then the independent processor accesses the memory to execute the task.
Then the independent processor accesses the memory to execute the task.
After completion of the task, it sends an acknowledgement to the host processor by using the status signal or an interrupt request.
After completion of the task, it sends an acknowledgement to the host processor by using the status signal or an interrupt request.
Loosely coupled configuration consists of the number of modules of the microprocessor based systems, which are connected through a common system bus. Each module consists of their own clock generator, memory, I/O devices and are connected through a local bus.
Having more than one processor results in increased efficiency.
Having more than one processor results in increased efficiency.
Each of the processors have their own local bus to access the local memory/I/O devices. This makes it easy to achieve parallel processing.
Each of the processors have their own local bus to access the local memory/I/O devices. This makes it easy to achieve parallel processing.
The system structure is flexible, i.e. the failure of one module doesn’t affect the whole system failure; faulty module can be replaced later.
The system structure is flexible, i.e. the failure of one module doesn’t affect the whole system failure; faulty module can be replaced later.
8087 numeric data processor is also known as Math co-processor, Numeric processor extension and Floating point unit. It was the first math coprocessor designed by Intel to pair with 8086/8088 resulting in easier and faster calculation.
Once the instructions are identified by the 8086/8088 processor, then it is allotted to the 8087 co-processor for further execution.
The data types supported by 8087 are −
Binary Integers
Packed decimal numbers
Real numbers
Temporary real format
The most prominent features of 8087 numeric data processor are as follows −
It supports data of type integer, float, and real types ranging from 2-10 bytes.
It supports data of type integer, float, and real types ranging from 2-10 bytes.
The processing speed is so high that it can calculate multiplication of two 64-bits real numbers in ~27 μs and can also calculate square-root in ~35 μs.
The processing speed is so high that it can calculate multiplication of two 64-bits real numbers in ~27 μs and can also calculate square-root in ~35 μs.
It follows IEEE floating point standards.
It follows IEEE floating point standards.
8087 Architecture is divided into two groups, i.e., Control Unit (CU) and Numeric Extension Unit (NEU).
The control unit handles all the communication between the processor and the memory such as it receives and decodes instructions, reads and writes memory operands, maintains parallel queue, etc. All the coprocessor instructions are ESC instructions, i.e., they start with ‘F’, the coprocessor only executes the ESC instructions while other instructions are executed by the microprocessor.
The control unit handles all the communication between the processor and the memory such as it receives and decodes instructions, reads and writes memory operands, maintains parallel queue, etc. All the coprocessor instructions are ESC instructions, i.e., they start with ‘F’, the coprocessor only executes the ESC instructions while other instructions are executed by the microprocessor.
The numeric extension unit handles all the numeric processor instructions like arithmetic, logical, transcendental, and data transfer instructions. It has 8 register stack, which holds the operands for instructions and their results.
The numeric extension unit handles all the numeric processor instructions like arithmetic, logical, transcendental, and data transfer instructions. It has 8 register stack, which holds the operands for instructions and their results.
The architecture of 8087 coprocessor is as follows −
Let us first take a look at the pin diagram of 8087 −
The following list provides the Pin Description of 8087 −
AD0 – AD15 − These are the time multiplexed address/data lines, which carry addresses during the first clock cycle and data from the second clock cycle onwards.
AD0 – AD15 − These are the time multiplexed address/data lines, which carry addresses during the first clock cycle and data from the second clock cycle onwards.
A19 / S6 – A16/S − These lines are the time multiplexed address/status lines. It functions in a similar way to the corresponding pins of 8086. The S6, S4 and S3 are permanently high, while the S5 is permanently low.
A19 / S6 – A16/S − These lines are the time multiplexed address/status lines. It functions in a similar way to the corresponding pins of 8086. The S6, S4 and S3 are permanently high, while the S5 is permanently low.
$\overline{BHE}$/S7 − During the first clock cycle, the $\overline{BHE}$/S7 is used to enable data on to the higher byte of the 8086 data bus and after that works as status line S7.
$\overline{BHE}$/S7 − During the first clock cycle, the $\overline{BHE}$/S7 is used to enable data on to the higher byte of the 8086 data bus and after that works as status line S7.
QS1, QS0 − These are queue status input signals which provides the status of instruction queue, their conditions as shown in the following table −
QS1, QS0 − These are queue status input signals which provides the status of instruction queue, their conditions as shown in the following table −
INT − It is an interrupt signal, which changes to high when an unmasked exception has been received during the execution.
INT − It is an interrupt signal, which changes to high when an unmasked exception has been received during the execution.
BUSY − It is an output signal, when it is high it indicates a busy state to the CPU.
BUSY − It is an output signal, when it is high it indicates a busy state to the CPU.
READY − It is an input signal used to inform the coprocessor whether the bus is ready to receive data or not.
READY − It is an input signal used to inform the coprocessor whether the bus is ready to receive data or not.
RESET − It is an input signal used to reject the internal activities of the coprocessor and prepare it for further execution whenever required by the CPU.
RESET − It is an input signal used to reject the internal activities of the coprocessor and prepare it for further execution whenever required by the CPU.
CLK − The CLK input provides the basic timings for the processor operation.
CLK − The CLK input provides the basic timings for the processor operation.
VCC − It is a power supply signal, which requires +5V supply for the operation of the circuit.
VCC − It is a power supply signal, which requires +5V supply for the operation of the circuit.
S0, S1, S2 − These are the status signals that provide the status of the operation which is used by the Bus Controller 8087 to generate memory and I/O control signals. These signals are active during the fourth clock cycle.
S0, S1, S2 − These are the status signals that provide the status of the operation which is used by the Bus Controller 8087 to generate memory and I/O control signals. These signals are active during the fourth clock cycle.
RQ/GT1 & RQ/GT0 − These are the Request/Grant signals used by the 8087 processors to gain control of the bus from the host processor 8086/8088 for operand transfers.
RQ/GT1 & RQ/GT0 − These are the Request/Grant signals used by the 8087 processors to gain control of the bus from the host processor 8086/8088 for operand transfers.
In this chapter, we will discuss Memory Interfacing and IO Interfacing with 8085.
Interface is the path for communication between two components. Interfacing is of two types, memory interfacing and I/O interfacing.
When we are executing any instruction, we need the microprocessor to access the memory for reading instruction codes and the data stored in the memory. For this, both the memory and the microprocessor requires some signals to read from and write to registers.
The interfacing process includes some key factors to match with the memory requirements and microprocessor signals. The interfacing circuit therefore should be designed in such a way that it matches the memory signal requirements with the signals of the microprocessor.
There are various communication devices like the keyboard, mouse, printer, etc. So, we need to interface the keyboard and other devices with the microprocessor by using latches and buffers. This type of interfacing is known as I/O interfacing.
Following is the list of 8085 pins used for interfacing with other devices −
A15 - A8 (Higher Address Bus)
AD7 - AD0(Lower Address/Data Bus)
ALE
RD
WR
READY
There are two ways of communication in which the microprocessor can connect with the outside world.
Serial Communication Interface
Parallel Communication interface
Serial Communication Interface − In this type of communication, the interface gets a single byte of data from the microprocessor and sends it bit by bit to the other system serially and vice-a-versa.
Parallel Communication Interface − In this type of communication, the interface gets a byte of data from the microprocessor and sends it bit by bit to the other systems in simultaneous (or) parallel fashion and vice-a-versa.
8279 programmable keyboard/display controller is designed by Intel that interfaces a keyboard with the CPU. The keyboard first scans the keyboard and identifies if any key has been pressed. It then sends their relative response of the pressed key to the CPU and vice-a-versa.
The Keyboard can be interfaced either in the interrupt or the polled mode. In the Interrupt mode, the processor is requested service only if any key is pressed, otherwise the CPU will continue with its main task.
In the Polled mode, the CPU periodically reads an internal flag of 8279 to check whether any key is pressed or not with key pressure.
The keyboard consists of maximum 64 keys, which are interfaced with the CPU by using the key-codes. These key-codes are de-bounced and stored in an 8-byte FIFORAM, which can be accessed by the CPU. If more than 8 characters are entered in the FIFO, then it means more than eight keys are pressed at a time. This is when the overrun status is set.
If a FIFO contains a valid key entry, then the CPU is interrupted in an interrupt mode else the CPU checks the status in polling to read the entry. Once the CPU reads a key entry, then FIFO is updated, and the key entry is pushed out of the FIFO to generate space for new entries.
This unit controls the flow of data through the microprocessor. It is enabled only when D is low. Its data buffer interfaces the external bus of the system with the internal bus of the microprocessor. The pins A0, RD, and WR are used for command, status or data read/write operations.
This unit contains registers to store the keyboard, display modes, and other operations as programmed by the CPU. The timing and control unit handles the timings for the operation of the circuit.
It has two modes i.e. Encoded mode and Decoded mode. In the encoded mode, the counter provides the binary count that is to be externally decoded to provide the scan lines for the keyboard and display.
In the decoded scan mode, the counter internally decodes the least significant 2 bits and provides a decoded 1 out of 4 scan on SL0-SL3.
This unit first scans the key closure row-wise, if found then the keyboard debounce unit debounces the key entry. In case, the same key is detected, then the code of that key is directly transferred to the sensor RAM along with SHIFT & CONTROL key status.
This unit acts as 8-byte first-in-first-out (FIFO) RAM where the key code of every pressed key is entered into the RAM as per their sequence. The status logic generates an interrupt request after each FIFO read operation till the FIFO gets empty.
In the scanned sensor matrix mode, this unit acts as sensor RAM where its each row is loaded with the status of their corresponding row of sensors into the matrix. When the sensor changes its state, the IRQ line changes to high and interrupts the CPU.
This unit consists of display address registers which holds the addresses of the word currently read/written by the CPU to/from the display RAM.
The following figure shows the pin diagram of 8279 −
These are 8 bidirectional data bus lines used to transfer the data to/from the CPU.
The clock input is used to generate internal timings required by the microprocessor.
As the name suggests this pin is used to reset the microprocessor.
When this pin is set to low, it allows read/write operations, else this pin should be set to high.
This pin indicates the transfer of command/status information. When it is low, it indicates the transfer of data.
This Read/Write pin enables the data buffer to send/receive data over the data bus.
This interrupt output line goes high when there is data in the FIFO sensor RAM. The interrupt line goes low with each FIFO RAM read operation. However, if the FIFO RAM further contains any key-code entry to be read by the CPU, this pin again goes high to generate an interrupt to the CPU.
These are the ground and power supply lines of the microprocessor.
These are the scan lines used to scan the keyboard matrix and display the digits. These lines can be programmed as encoded or decoded, using the mode control register.
These are the Return Lines which are connected to one terminal of keys, while the other terminal of the keys is connected to the decoded scan lines. These lines are set to 0 when any key is pressed.
The Shift input line status is stored along with every key code in FIFO in the scanned keyboard mode. Till it is pulled low with a key closure, it is pulled up internally to keep it high
In the keyboard mode, this line is used as a control input and stored in FIFO on a key closure. The line is a strobe line that enters the data into FIFO RAM, in the strobed input mode. It has an internal pull up. The line is pulled down with a key closure.
It stands for blank display. It is used to blank the display during digit switching.
These are the output ports for two 16x4 or one 16x8 internal display refresh registers. The data from these lines is synchronized with the scan lines to scan the display and the keyboard.
There are two modes of operation on 8279 − Input Mode and Output Mode.
This mode deals with the input given by the keyboard and this mode is further classified into 3 modes.
Scanned Keyboard Mode − In this mode, the key matrix can be interfaced using either encoded or decoded scans. In the encoded scan, an 8×8 keyboard or in the decoded scan, a 4×8 keyboard can be interfaced. The code of key pressed with SHIFT and CONTROL status is stored into the FIFO RAM.
Scanned Keyboard Mode − In this mode, the key matrix can be interfaced using either encoded or decoded scans. In the encoded scan, an 8×8 keyboard or in the decoded scan, a 4×8 keyboard can be interfaced. The code of key pressed with SHIFT and CONTROL status is stored into the FIFO RAM.
Scanned Sensor Matrix − In this mode, a sensor array can be interfaced with the processor using either encoder or decoder scans. In the encoder scan, 8×8 sensor matrix or with decoder scan 4×8 sensor matrix can be interfaced.
Scanned Sensor Matrix − In this mode, a sensor array can be interfaced with the processor using either encoder or decoder scans. In the encoder scan, 8×8 sensor matrix or with decoder scan 4×8 sensor matrix can be interfaced.
Strobed Input − In this mode, when the control line is set to 0, the data on the return lines is stored in the FIFO byte by byte.
Strobed Input − In this mode, when the control line is set to 0, the data on the return lines is stored in the FIFO byte by byte.
This mode deals with display-related operations. This mode is further classified into two output modes.
Display Scan − This mode allows 8/16 character multiplexed displays to be organized as dual 4-bit/single 8-bit display units.
Display Scan − This mode allows 8/16 character multiplexed displays to be organized as dual 4-bit/single 8-bit display units.
Display Entry − This mode allows the data to be entered for display either from the right side/left side.
Display Entry − This mode allows the data to be entered for display either from the right side/left side.
DMA stands for Direct Memory Access. It is designed by Intel to transfer data at the fastest rate. It allows the device to transfer the data directly to/from memory without any interference of the CPU.
Using a DMA controller, the device requests the CPU to hold its data, address and control bus, so the device is free to transfer data directly to/from the memory. The DMA data transfer is initiated only after receiving HLDA signal from the CPU.
Following is the sequence of operations performed by a DMA −
Initially, when any device has to send data between the device and the memory, the device has to send DMA request (DRQ) to DMA controller.
Initially, when any device has to send data between the device and the memory, the device has to send DMA request (DRQ) to DMA controller.
The DMA controller sends Hold request (HRQ) to the CPU and waits for the CPU to assert the HLDA.
The DMA controller sends Hold request (HRQ) to the CPU and waits for the CPU to assert the HLDA.
Then the microprocessor tri-states all the data bus, address bus, and control bus. The CPU leaves the control over bus and acknowledges the HOLD request through HLDA signal.
Then the microprocessor tri-states all the data bus, address bus, and control bus. The CPU leaves the control over bus and acknowledges the HOLD request through HLDA signal.
Now the CPU is in HOLD state and the DMA controller has to manage the operations over buses between the CPU, memory, and I/O devices.
Now the CPU is in HOLD state and the DMA controller has to manage the operations over buses between the CPU, memory, and I/O devices.
Here is a list of some of the prominent features of 8257 −
It has four channels which can be used over four I/O devices.
It has four channels which can be used over four I/O devices.
Each channel has 16-bit address and 14-bit counter.
Each channel has 16-bit address and 14-bit counter.
Each channel can transfer data up to 64kb.
Each channel can transfer data up to 64kb.
Each channel can be programmed independently.
Each channel can be programmed independently.
Each channel can perform read transfer, write transfer and verify transfer operations.
Each channel can perform read transfer, write transfer and verify transfer operations.
It generates MARK signal to the peripheral device that 128 bytes have been transferred.
It generates MARK signal to the peripheral device that 128 bytes have been transferred.
It requires a single phase clock.
It requires a single phase clock.
Its frequency ranges from 250Hz to 3MHz.
Its frequency ranges from 250Hz to 3MHz.
It operates in 2 modes, i.e., Master mode and Slave mode.
It operates in 2 modes, i.e., Master mode and Slave mode.
The following image shows the architecture of 8257 −
The following image shows the pin diagram of a 8257 DMA controller −
These are the four individual channel DMA request inputs, which are used by the peripheral devices for using DMA services. When the fixed priority mode is selected, then DRQ0 has the highest priority and DRQ3 has the lowest priority among them.
These are the active-low DMA acknowledge lines, which updates the requesting peripheral about the status of their request by the CPU. These lines can also act as strobe lines for the requesting devices.
These are bidirectional, data lines which are used to interface the system bus with the internal data bus of DMA controller. In the Slave mode, it carries command words to 8257 and status word from 8257. In the master mode, these lines are used to send higher byte of the generated address to the latch. This address is further latched using ADSTB signal.
It is an active-low bidirectional tri-state input line, which is used by the CPU to read internal registers of 8257 in the Slave mode. In the master mode, it is used to read data from the peripheral devices during a memory write cycle.
It is an active low bi-direction tri-state line, which is used to load the contents of the data bus to the 8-bit mode register or upper/lower byte of a 16-bit DMA address register or terminal count register. In the master mode, it is used to load the data to the peripheral devices during DMA memory read cycle.
It is a clock frequency signal which is required for the internal operation of 8257.
This signal is used to RESET the DMA controller by disabling all the DMA channels.
These are the four least significant address lines. In the slave mode, they act as an input, which selects one of the registers to be read or written. In the master mode, they are the four least significant memory address output lines generated by 8257.
It is an active-low chip select line. In the Slave mode, it enables the read/write operations to/from 8257. In the master mode, it disables the read/write operations to/from 8257.
These are the higher nibble of the lower byte address generated by DMA in the master mode.
It is an active-high asynchronous input signal, which makes DMA ready by inserting wait states.
This signal is used to receive the hold request signal from the output device. In the slave mode, it is connected with a DRQ input line 8257. In Master mode, it is connected with HOLD input of the CPU.
It is the hold acknowledgement signal which indicates the DMA controller that the bus has been granted to the requesting peripheral by the CPU when it is set to 1.
It is the low memory read signal, which is used to read the data from the addressed memory locations during DMA read cycles.
It is the active-low three state signal which is used to write the data to the addressed memory location during DMA write operation.
This signal is used to convert the higher byte of the memory address generated by the DMA controller into the latches.
This signal is used to disable the address bus/data bus.
It stands for ‘Terminal Count’, which indicates the present DMA cycle to the present peripheral devices.
The mark will be activated after each 128 cycles or integral multiples of it from the beginning. It indicates the current DMA cycle is the 128th cycle since the previous MARK output to the selected peripheral device.
It is the power signal which is required for the operation of the circuit.
A microcontroller is a small and low-cost microcomputer, which is designed to perform the specific tasks of embedded systems like displaying microwave’s information, receiving remote signals, etc.
The general microcontroller consists of the processor, the memory (RAM, ROM, EPROM), Serial ports, peripherals (timers, counters), etc.
The following table highlights the differences between a microprocessor and a microcontroller −
Microcontrollers are divided into various categories based on memory, architecture, bits and instruction sets. Following is the list of their types −
Based on bit configuration, the microcontroller is further divided into three categories.
8-bit microcontroller − This type of microcontroller is used to execute arithmetic and logical operations like addition, subtraction, multiplication division, etc. For example, Intel 8031 and 8051 are 8 bits microcontroller.
8-bit microcontroller − This type of microcontroller is used to execute arithmetic and logical operations like addition, subtraction, multiplication division, etc. For example, Intel 8031 and 8051 are 8 bits microcontroller.
16-bit microcontroller − This type of microcontroller is used to perform arithmetic and logical operations where higher accuracy and performance is required. For example, Intel 8096 is a 16-bit microcontroller.
16-bit microcontroller − This type of microcontroller is used to perform arithmetic and logical operations where higher accuracy and performance is required. For example, Intel 8096 is a 16-bit microcontroller.
32-bit microcontroller − This type of microcontroller is generally used in automatically controlled appliances like automatic operational machines, medical appliances, etc.
32-bit microcontroller − This type of microcontroller is generally used in automatically controlled appliances like automatic operational machines, medical appliances, etc.
Based on the memory configuration, the microcontroller is further divided into two categories.
External memory microcontroller − This type of microcontroller is designed in such a way that they do not have a program memory on the chip. Hence, it is named as external memory microcontroller. For example: Intel 8031 microcontroller.
External memory microcontroller − This type of microcontroller is designed in such a way that they do not have a program memory on the chip. Hence, it is named as external memory microcontroller. For example: Intel 8031 microcontroller.
Embedded memory microcontroller − This type of microcontroller is designed in such a way that the microcontroller has all programs and data memory, counters and timers, interrupts, I/O ports are embedded on the chip. For example: Intel 8051 microcontroller.
Embedded memory microcontroller − This type of microcontroller is designed in such a way that the microcontroller has all programs and data memory, counters and timers, interrupts, I/O ports are embedded on the chip. For example: Intel 8051 microcontroller.
Based on the instruction set configuration, the microcontroller is further divided into two categories.
CISC − CISC stands for complex instruction set computer. It allows the user to insert a single instruction as an alternative to many simple instructions.
CISC − CISC stands for complex instruction set computer. It allows the user to insert a single instruction as an alternative to many simple instructions.
RISC − RISC stands for Reduced Instruction Set Computers. It reduces the operational time by shortening the clock cycle per instruction.
RISC − RISC stands for Reduced Instruction Set Computers. It reduces the operational time by shortening the clock cycle per instruction.
Microcontrollers are widely used in various different devices such as −
Light sensing and controlling devices like LED.
Light sensing and controlling devices like LED.
Temperature sensing and controlling devices like microwave oven, chimneys.
Temperature sensing and controlling devices like microwave oven, chimneys.
Fire detection and safety devices like Fire alarm.
Fire detection and safety devices like Fire alarm.
Measuring devices like Volt Meter.
Measuring devices like Volt Meter.
8051 microcontroller is designed by Intel in 1981. It is an 8-bit microcontroller. It is built with 40 pins DIP (dual inline package), 4kb of ROM storage and 128 bytes of RAM storage, 2 16-bit timers. It consists of are four parallel 8-bit ports, which are programmable as well as addressable as per the requirement. An on-chip crystal oscillator is integrated in the microcontroller having crystal frequency of 12 MHz.
Let us now discuss the architecture of 8051 Microcontroller.
In the following diagram, the system bus connects all the support devices to the CPU. The system bus consists of an 8-bit data bus, a 16-bit address bus and bus control signals. All other devices like program memory, ports, data memory, serial interface, interrupt control, timers, and the CPU are all interfaced together through the system bus.
The pin diagram of 8051 microcontroller looks as follows −
Pins 1 to 8 − These pins are known as Port 1. This port doesn’t serve any other functions. It is internally pulled up, bi-directional I/O port.
Pins 1 to 8 − These pins are known as Port 1. This port doesn’t serve any other functions. It is internally pulled up, bi-directional I/O port.
Pin 9 − It is a RESET pin, which is used to reset the microcontroller to its initial values.
Pin 9 − It is a RESET pin, which is used to reset the microcontroller to its initial values.
Pins 10 to 17 − These pins are known as Port 3. This port serves some functions like interrupts, timer input, control signals, serial communication signals RxD and TxD, etc.
Pins 10 to 17 − These pins are known as Port 3. This port serves some functions like interrupts, timer input, control signals, serial communication signals RxD and TxD, etc.
Pins 18 & 19 − These pins are used for interfacing an external crystal to get the system clock.
Pins 18 & 19 − These pins are used for interfacing an external crystal to get the system clock.
Pin 20 − This pin provides the power supply to the circuit.
Pin 20 − This pin provides the power supply to the circuit.
Pins 21 to 28 − These pins are known as Port 2. It serves as I/O port. Higher order address bus signals are also multiplexed using this port.
Pins 21 to 28 − These pins are known as Port 2. It serves as I/O port. Higher order address bus signals are also multiplexed using this port.
Pin 29 − This is PSEN pin which stands for Program Store Enable. It is used to read a signal from the external program memory.
Pin 29 − This is PSEN pin which stands for Program Store Enable. It is used to read a signal from the external program memory.
Pin 30 − This is EA pin which stands for External Access input. It is used to enable/disable the external memory interfacing.
Pin 30 − This is EA pin which stands for External Access input. It is used to enable/disable the external memory interfacing.
Pin 31 − This is ALE pin which stands for Address Latch Enable. It is used to demultiplex the address-data signal of port.
Pin 31 − This is ALE pin which stands for Address Latch Enable. It is used to demultiplex the address-data signal of port.
Pins 32 to 39 − These pins are known as Port 0. It serves as I/O port. Lower order address and data bus signals are multiplexed using this port.
Pins 32 to 39 − These pins are known as Port 0. It serves as I/O port. Lower order address and data bus signals are multiplexed using this port.
Pin 40 − This pin is used to provide power supply to the circuit.
Pin 40 − This pin is used to provide power supply to the circuit.
8051 microcontrollers have 4 I/O ports each of 8-bit, which can be configured as input or output. Hence, total 32 input/output pins allow the microcontroller to be connected with the peripheral devices.
Pin configuration, i.e. the pin can be configured as 1 for input and 0 for output as per the logic state.
Input/Output (I/O) pin − All the circuits within the microcontroller must be connected to one of its pins except P0 port because it does not have pull-up resistors built-in.
Input pin − Logic 1 is applied to a bit of the P register. The output FE transistor is turned off and the other pin remains connected to the power supply voltage over a pull-up resistor of high resistance.
Pin configuration, i.e. the pin can be configured as 1 for input and 0 for output as per the logic state.
Input/Output (I/O) pin − All the circuits within the microcontroller must be connected to one of its pins except P0 port because it does not have pull-up resistors built-in.
Input/Output (I/O) pin − All the circuits within the microcontroller must be connected to one of its pins except P0 port because it does not have pull-up resistors built-in.
Input pin − Logic 1 is applied to a bit of the P register. The output FE transistor is turned off and the other pin remains connected to the power supply voltage over a pull-up resistor of high resistance.
Input pin − Logic 1 is applied to a bit of the P register. The output FE transistor is turned off and the other pin remains connected to the power supply voltage over a pull-up resistor of high resistance.
Port 0 − The P0 (zero) port is characterized by two functions −
When the external memory is used then the lower address byte (addresses A0A7) is applied on it, else all bits of this port are configured as input/output.
When P0 port is configured as an output then other ports consisting of pins with built-in pull-up resistor connected by its end to 5V power supply, the pins of this port have this resistor left out.
Port 0 − The P0 (zero) port is characterized by two functions −
When the external memory is used then the lower address byte (addresses A0A7) is applied on it, else all bits of this port are configured as input/output.
When the external memory is used then the lower address byte (addresses A0A7) is applied on it, else all bits of this port are configured as input/output.
When P0 port is configured as an output then other ports consisting of pins with built-in pull-up resistor connected by its end to 5V power supply, the pins of this port have this resistor left out.
When P0 port is configured as an output then other ports consisting of pins with built-in pull-up resistor connected by its end to 5V power supply, the pins of this port have this resistor left out.
If any pin of this port is configured as an input, then it acts as if it “floats”, i.e. the input has unlimited input resistance and in-determined potential.
When the pin is configured as an output, then it acts as an “open drain”. By applying logic 0 to a port bit, the appropriate pin will be connected to ground (0V), and applying logic 1, the external output will keep on “floating”.
In order to apply logic 1 (5V) on this output pin, it is necessary to build an external pullup resistor.
P1 is a true I/O port as it doesn’t have any alternative functions as in P0, but this port can be configured as general I/O only. It has a built-in pull-up resistor and is completely compatible with TTL circuits.
P2 is similar to P0 when the external memory is used. Pins of this port occupy addresses intended for the external memory chip. This port can be used for higher address byte with addresses A8-A15. When no memory is added then this port can be used as a general input/output port similar to Port 1.
In this port, functions are similar to other ports except that the logic 1 must be applied to appropriate bit of the P3 register.
When pins are configured as an output (i.e. logic 0), then the single port pins can receive a current of 10mA.
When pins are configured as an output (i.e. logic 0), then the single port pins can receive a current of 10mA.
When these pins are configured as inputs (i.e. logic 1), then built-in pull-up resistors provide very weak current, but can activate up to 4 TTL inputs of LS series.
When these pins are configured as inputs (i.e. logic 1), then built-in pull-up resistors provide very weak current, but can activate up to 4 TTL inputs of LS series.
If all 8 bits of a port are active, then the total current must be limited to 15mA (port P0: 26mA).
If all 8 bits of a port are active, then the total current must be limited to 15mA (port P0: 26mA).
If all ports (32 bits) are active, then the total maximum current must be limited to 71mA.
If all ports (32 bits) are active, then the total maximum current must be limited to 71mA.
Interrupts are the events that temporarily suspend the main program, pass the control to the external sources and execute their task. It then passes the control to the main program where it had left off.
8051 has 5 interrupt signals, i.e. INT0, TFO, INT1, TF1, RI/TI. Each interrupt can be enabled or disabled by setting bits of the IE register and the whole interrupt system can be disabled by clearing the EA bit of the same register.
This register is responsible for enabling and disabling the interrupt. EA register is set to one for enabling interrupts and set to 0 for disabling the interrupts. Its bit sequence and their meanings are shown in the following figure.
We can change the priority levels of the interrupts by changing the corresponding bit in the Interrupt Priority (IP) register as shown in the following figure.
A low priority interrupt can only be interrupted by the high priority interrupt, but not interrupted by another low priority interrupt.
A low priority interrupt can only be interrupted by the high priority interrupt, but not interrupted by another low priority interrupt.
If two interrupts of different priority levels are received simultaneously, the request of higher priority level is served.
If two interrupts of different priority levels are received simultaneously, the request of higher priority level is served.
If the requests of the same priority levels are received simultaneously, then the internal polling sequence determines which request is to be serviced.
If the requests of the same priority levels are received simultaneously, then the internal polling sequence determines which request is to be serviced.
TCON register specifies the type of external interrupt to the microcontroller.
The 8255A is a general purpose programmable I/O device designed to transfer the data from I/O to interrupt I/O under certain conditions as required. It can be used with almost any microprocessor.
It consists of three 8-bit bidirectional I/O ports (24I/O lines) which can be configured as per the requirement.
8255A has three ports, i.e., PORT A, PORT B, and PORT C.
Port A contains one 8-bit output latch/buffer and one 8-bit input buffer.
Port A contains one 8-bit output latch/buffer and one 8-bit input buffer.
Port B is similar to PORT A.
Port B is similar to PORT A.
Port C can be split into two parts, i.e. PORT C lower (PC0-PC3) and PORT C upper (PC7-PC4) by the control word.
Port C can be split into two parts, i.e. PORT C lower (PC0-PC3) and PORT C upper (PC7-PC4) by the control word.
These three ports are further divided into two groups, i.e. Group A includes PORT A and upper PORT C. Group B includes PORT B and lower PORT C. These two groups can be programmed in three different modes, i.e. the first mode is named as mode 0, the second mode is named as Mode 1 and the third mode is named as Mode 2.
8255A has three different operating modes −
Mode 0 − In this mode, Port A and B is used as two 8-bit ports and Port C as two 4-bit ports. Each port can be programmed in either input mode or output mode where outputs are latched and inputs are not latched. Ports do not have interrupt capability.
Mode 0 − In this mode, Port A and B is used as two 8-bit ports and Port C as two 4-bit ports. Each port can be programmed in either input mode or output mode where outputs are latched and inputs are not latched. Ports do not have interrupt capability.
Mode 1 − In this mode, Port A and B is used as 8-bit I/O ports. They can be configured as either input or output ports. Each port uses three lines from port C as handshake signals. Inputs and outputs are latched.
Mode 1 − In this mode, Port A and B is used as 8-bit I/O ports. They can be configured as either input or output ports. Each port uses three lines from port C as handshake signals. Inputs and outputs are latched.
Mode 2 − In this mode, Port A can be configured as the bidirectional port and Port B either in Mode 0 or Mode 1. Port A uses five signals from Port C as handshake signals for data transfer. The remaining three signals from Port C can be used either as simple I/O or as handshake for port B.
Mode 2 − In this mode, Port A can be configured as the bidirectional port and Port B either in Mode 0 or Mode 1. Port A uses five signals from Port C as handshake signals for data transfer. The remaining three signals from Port C can be used either as simple I/O or as handshake for port B.
The prominent features of 8255A are as follows −
It consists of 3 8-bit IO ports i.e. PA, PB, and PC.
It consists of 3 8-bit IO ports i.e. PA, PB, and PC.
Address/data bus must be externally demux'd.
Address/data bus must be externally demux'd.
It is TTL compatible.
It is TTL compatible.
It has improved DC driving capability.
It has improved DC driving capability.
The following figure shows the architecture of 8255A −
Let us first take a look at the pin diagram of Intel 8255A −
Now let us discuss the functional description of the pins in 8255A.
It is a tri-state 8-bit buffer, which is used to interface the microprocessor to the system data bus. Data is transmitted or received by the buffer as per the instructions by the CPU. Control words and status information is also transferred using this bus.
This block is responsible for controlling the internal/external transfer of data/control/status word. It accepts the input from the CPU address and control buses, and in turn issues command to both the control groups.
It stands for Chip Select. A LOW on this input selects the chip and enables the communication between the 8255A and the CPU. It is connected to the decoded address, and A0 & A1 are connected to the microprocessor address lines.
Their result depends on the following conditions −
It stands for write. This control signal enables the write operation. When this signal goes low, the microprocessor writes into a selected I/O port or control register.
This is an active high signal. It clears the control register and sets all ports in the input mode.
It stands for Read. This control signal enables the Read operation. When the signal is low, the microprocessor reads the data from the selected I/O port of the 8255.
These input signals work with RD, WR, and one of the control signal. Following is the table showing their various signals with their result.
Input Operation
Output Operation
The Intel 8253 and 8254 are Programmable Interval Timers (PTIs) designed for microprocessors to perform timing and counting functions using three 16-bit registers. Each counter has 2 input pins, i.e. Clock & Gate, and 1 pin for “OUT” output. To operate a counter, a 16-bit count is loaded in its register. On command, it begins to decrement the count until it reaches 0, then it generates a pulse that can be used to interrupt the CPU.
The following table differentiates the features of 8253 and 8254 −
The most prominent features of 8253/54 are as follows −
It has three independent 16-bit down counters.
It has three independent 16-bit down counters.
It can handle inputs from DC to 10 MHz.
It can handle inputs from DC to 10 MHz.
These three counters can be programmed for either binary or BCD count.
These three counters can be programmed for either binary or BCD count.
It is compatible with almost all microprocessors.
It is compatible with almost all microprocessors.
8254 has a powerful command called READ BACK command, which allows the user to check the count value, the programmed mode, the current mode, and the current status of the counter.
8254 has a powerful command called READ BACK command, which allows the user to check the count value, the programmed mode, the current mode, and the current status of the counter.
The architecture of 8254 looks as follows −
Here is the pin diagram of 8254 −
In the above figure, there are three counters, a data bus buffer, Read/Write control logic, and a control register. Each counter has two input signals - CLOCK & GATE, and one output signal - OUT.
It is a tri-state, bi-directional, 8-bit buffer, which is used to interface the 8253/54 to the system data bus. It has three basic functions −
Programming the modes of 8253/54.
Loading the count registers.
Reading the count values.
It includes 5 signals, i.e. RD, WR, CS, and the address lines A0 & A1. In the peripheral I/O mode, the RD and WR signals are connected to IOR and IOW, respectively. In the memorymapped I/O mode, these are connected to MEMR and MEMW.
Address lines A0 & A1 of the CPU are connected to lines A0 and A1 of the 8253/54, and CS is tied to a decoded address. The control word register and counters are selected according to the signals on lines A0 & A1.
This register is accessed when lines A0 & A1 are at logic 1. It is used to write a command word, which specifies the counter to be used, its mode, and either a read or write operation. Following table shows the result for various control inputs.
Each counter consists of a single, 16 bit-down counter, which can be operated in either binary or BCD. Its input and output is configured by the selection of modes stored in the control word register. The programmer can read the contents of any of the three counters without disturbing the actual count in process.
8253/54 can be operated in 6 different modes. In this chapter, we will discuss these operational modes.
It is used to generate an interrupt to the microprocessor after a certain interval.
It is used to generate an interrupt to the microprocessor after a certain interval.
Initially the output is low after the mode is set. The output remains LOW after the count value is loaded into the counter.
Initially the output is low after the mode is set. The output remains LOW after the count value is loaded into the counter.
The process of decrementing the counter continues till the terminal count is reached, i.e., the count become zero and the output goes HIGH and will remain high until it reloads a new count.
The process of decrementing the counter continues till the terminal count is reached, i.e., the count become zero and the output goes HIGH and will remain high until it reloads a new count.
The GATE signal is high for normal counting. When GATE goes low, counting is terminated and the current count is latched till the GATE goes high again.
The GATE signal is high for normal counting. When GATE goes low, counting is terminated and the current count is latched till the GATE goes high again.
It can be used as a mono stable multi-vibrator.
It can be used as a mono stable multi-vibrator.
The gate input is used as a trigger input in this mode.
The gate input is used as a trigger input in this mode.
The output remains high until the count is loaded and a trigger is applied.
The output remains high until the count is loaded and a trigger is applied.
The output is normally high after initialization.
The output is normally high after initialization.
Whenever the count becomes zero, another low pulse is generated at the output and the counter will be reloaded.
Whenever the count becomes zero, another low pulse is generated at the output and the counter will be reloaded.
This mode is similar to Mode 2 except the output remains low for half of the timer period and high for the other half of the period.
This mode is similar to Mode 2 except the output remains low for half of the timer period and high for the other half of the period.
In this mode, the output will remain high until the timer has counted to zero, at which point the output will pulse low and then go high again.
In this mode, the output will remain high until the timer has counted to zero, at which point the output will pulse low and then go high again.
The count is latched when the GATE signal goes LOW.
The count is latched when the GATE signal goes LOW.
On the terminal count, the output goes low for one clock cycle then goes HIGH. This low pulse can be used as a strobe.
On the terminal count, the output goes low for one clock cycle then goes HIGH. This low pulse can be used as a strobe.
This mode generates a strobe in response to an externally generated signal.
This mode generates a strobe in response to an externally generated signal.
This mode is similar to mode 4 except that the counting is initiated by a signal at the gate input, which means it is hardware triggered instead of software triggered.
This mode is similar to mode 4 except that the counting is initiated by a signal at the gate input, which means it is hardware triggered instead of software triggered.
After it is initialized, the output goes high.
After it is initialized, the output goes high.
When the terminal count is reached, the output goes low for one clock cycle.
When the terminal count is reached, the output goes low for one clock cycle.
50 Lectures
6.5 hours
Gowthami Swarna
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2667,
"s": 2461,
"text": "Microprocessor is a controlling unit of a micro-computer, fabricated on a small chip capable of performing ALU (Arithmetic Logical Unit) operations and communicating with the other devices connected to it."
},
{
"code": null,
"e": 3023,
"s": 2667,
"text": "Microprocessor consists of an ALU, register array, and a control unit. ALU performs arithmetical and logical operations on the data received from the memory or an input device. Register array consists of registers identified by letters like B, C, D, E, H, L and accumulator. The control unit controls the flow of data and instructions within the computer."
},
{
"code": null,
"e": 3095,
"s": 3023,
"text": "The microprocessor follows a sequence: Fetch, Decode, and then Execute."
},
{
"code": null,
"e": 3481,
"s": 3095,
"text": "Initially, the instructions are stored in the memory in a sequential order. The microprocessor fetches those instructions from the memory, then decodes it and executes those instructions till STOP instruction is reached. Later, it sends the result in binary to the output port. Between these processes, the register stores the temporarily data and ALU performs the computing functions."
},
{
"code": null,
"e": 3555,
"s": 3481,
"text": "Here is a list of some of the frequently used terms in a microprocessor −"
},
{
"code": null,
"e": 3643,
"s": 3555,
"text": "Instruction Set − It is the set of instructions that the microprocessor can understand."
},
{
"code": null,
"e": 3731,
"s": 3643,
"text": "Instruction Set − It is the set of instructions that the microprocessor can understand."
},
{
"code": null,
"e": 3803,
"s": 3731,
"text": "Bandwidth − It is the number of bits processed in a single instruction."
},
{
"code": null,
"e": 3875,
"s": 3803,
"text": "Bandwidth − It is the number of bits processed in a single instruction."
},
{
"code": null,
"e": 4052,
"s": 3875,
"text": "Clock Speed − It determines the number of operations per second the processor can perform. It is expressed in megahertz (MHz) or gigahertz (GHz).It is also known as Clock Rate."
},
{
"code": null,
"e": 4229,
"s": 4052,
"text": "Clock Speed − It determines the number of operations per second the processor can perform. It is expressed in megahertz (MHz) or gigahertz (GHz).It is also known as Clock Rate."
},
{
"code": null,
"e": 4462,
"s": 4229,
"text": "Word Length − It depends upon the width of internal data bus, registers, ALU, etc. An 8-bit microprocessor can process 8-bit data at a time. The word length ranges from 4 bits to 64 bits depending upon the type of the microcomputer."
},
{
"code": null,
"e": 4695,
"s": 4462,
"text": "Word Length − It depends upon the width of internal data bus, registers, ALU, etc. An 8-bit microprocessor can process 8-bit data at a time. The word length ranges from 4 bits to 64 bits depending upon the type of the microcomputer."
},
{
"code": null,
"e": 4812,
"s": 4695,
"text": "Data Types − The microprocessor has multiple data type formats like binary, BCD, ASCII, signed and unsigned numbers."
},
{
"code": null,
"e": 4929,
"s": 4812,
"text": "Data Types − The microprocessor has multiple data type formats like binary, BCD, ASCII, signed and unsigned numbers."
},
{
"code": null,
"e": 5007,
"s": 4929,
"text": "Here is a list of some of the most prominent features of any microprocessor −"
},
{
"code": null,
"e": 5103,
"s": 5007,
"text": "Cost-effective − The microprocessor chips are available at low prices and results its low cost."
},
{
"code": null,
"e": 5199,
"s": 5103,
"text": "Cost-effective − The microprocessor chips are available at low prices and results its low cost."
},
{
"code": null,
"e": 5267,
"s": 5199,
"text": "Size − The microprocessor is of small size chip, hence is portable."
},
{
"code": null,
"e": 5335,
"s": 5267,
"text": "Size − The microprocessor is of small size chip, hence is portable."
},
{
"code": null,
"e": 5471,
"s": 5335,
"text": "Low Power Consumption − Microprocessors are manufactured by using metaloxide semiconductor technology, which has low power consumption."
},
{
"code": null,
"e": 5607,
"s": 5471,
"text": "Low Power Consumption − Microprocessors are manufactured by using metaloxide semiconductor technology, which has low power consumption."
},
{
"code": null,
"e": 5748,
"s": 5607,
"text": "Versatility − The microprocessors are versatile as we can use the same chip in a number of applications by configuring the software program."
},
{
"code": null,
"e": 5889,
"s": 5748,
"text": "Versatility − The microprocessors are versatile as we can use the same chip in a number of applications by configuring the software program."
},
{
"code": null,
"e": 5983,
"s": 5889,
"text": "Reliability − The failure rate of an IC in microprocessors is very low, hence it is reliable."
},
{
"code": null,
"e": 6077,
"s": 5983,
"text": "Reliability − The failure rate of an IC in microprocessors is very low, hence it is reliable."
},
{
"code": null,
"e": 6136,
"s": 6077,
"text": "A microprocessor can be classified into three categories −"
},
{
"code": null,
"e": 6609,
"s": 6136,
"text": "RISC stands for Reduced Instruction Set Computer. It is designed to reduce the execution time by simplifying the instruction set of the computer. Using RISC processors, each instruction requires only one clock cycle to execute results in uniform execution time. This reduces the efficiency as there are more lines of code, hence more RAM is needed to store the instructions. The compiler also has to work more to convert high-level language instructions into machine code."
},
{
"code": null,
"e": 6643,
"s": 6609,
"text": "Some of the RISC processors are −"
},
{
"code": null,
"e": 6672,
"s": 6643,
"text": "Power PC: 601, 604, 615, 620"
},
{
"code": null,
"e": 6712,
"s": 6672,
"text": "DEC Alpha: 210642, 211066, 21068, 21164"
},
{
"code": null,
"e": 6745,
"s": 6712,
"text": "MIPS: TS (R10000) RISC Processor"
},
{
"code": null,
"e": 6764,
"s": 6745,
"text": "PA-RISC: HP 7100LC"
},
{
"code": null,
"e": 6916,
"s": 6764,
"text": "RISC microprocessor architecture uses highly-optimized set of instructions. It is used in portable devices like Apple iPod due to its power efficiency."
},
{
"code": null,
"e": 6979,
"s": 6916,
"text": "The major characteristics of a RISC processor are as follows −"
},
{
"code": null,
"e": 7015,
"s": 6979,
"text": "It consists of simple instructions."
},
{
"code": null,
"e": 7051,
"s": 7015,
"text": "It consists of simple instructions."
},
{
"code": null,
"e": 7090,
"s": 7051,
"text": "It supports various data-type formats."
},
{
"code": null,
"e": 7129,
"s": 7090,
"text": "It supports various data-type formats."
},
{
"code": null,
"e": 7211,
"s": 7129,
"text": "It utilizes simple addressing modes and fixed length instructions for pipelining."
},
{
"code": null,
"e": 7293,
"s": 7211,
"text": "It utilizes simple addressing modes and fixed length instructions for pipelining."
},
{
"code": null,
"e": 7337,
"s": 7293,
"text": "It supports register to use in any context."
},
{
"code": null,
"e": 7381,
"s": 7337,
"text": "It supports register to use in any context."
},
{
"code": null,
"e": 7407,
"s": 7381,
"text": "One cycle execution time."
},
{
"code": null,
"e": 7433,
"s": 7407,
"text": "One cycle execution time."
},
{
"code": null,
"e": 7505,
"s": 7433,
"text": "“LOAD” and “STORE” instructions are used to access the memory location."
},
{
"code": null,
"e": 7577,
"s": 7505,
"text": "“LOAD” and “STORE” instructions are used to access the memory location."
},
{
"code": null,
"e": 7620,
"s": 7577,
"text": "It consists of larger number of registers."
},
{
"code": null,
"e": 7663,
"s": 7620,
"text": "It consists of larger number of registers."
},
{
"code": null,
"e": 7706,
"s": 7663,
"text": "It consists of less number of transistors."
},
{
"code": null,
"e": 7749,
"s": 7706,
"text": "It consists of less number of transistors."
},
{
"code": null,
"e": 7990,
"s": 7749,
"text": "CISC stands for Complex Instruction Set Computer. It is designed to minimize the number of instructions per program, ignoring the number of cycles per instruction. The emphasis is on building complex instructions directly into the hardware."
},
{
"code": null,
"e": 8217,
"s": 7990,
"text": "The compiler has to do very little work to translate a high-level language into assembly level language/machine code because the length of the code is relatively short, so very little RAM is required to store the instructions."
},
{
"code": null,
"e": 8251,
"s": 8217,
"text": "Some of the CISC Processors are −"
},
{
"code": null,
"e": 8263,
"s": 8251,
"text": "IBM 370/168"
},
{
"code": null,
"e": 8274,
"s": 8263,
"text": "VAX 11/780"
},
{
"code": null,
"e": 8286,
"s": 8274,
"text": "Intel 80486"
},
{
"code": null,
"e": 8560,
"s": 8286,
"text": "Its architecture is designed to decrease the memory cost because more storage is needed in larger programs resulting in higher memory cost. To resolve this, the number of instructions per program can be reduced by embedding the number of operations in a single instruction."
},
{
"code": null,
"e": 8589,
"s": 8560,
"text": "Variety of addressing modes."
},
{
"code": null,
"e": 8620,
"s": 8589,
"text": "Larger number of instructions."
},
{
"code": null,
"e": 8660,
"s": 8620,
"text": "Variable length of instruction formats."
},
{
"code": null,
"e": 8719,
"s": 8660,
"text": "Several cycles may be required to execute one instruction."
},
{
"code": null,
"e": 8758,
"s": 8719,
"text": "Instruction-decoding logic is complex."
},
{
"code": null,
"e": 8824,
"s": 8758,
"text": "One instruction is required to support multiple addressing modes."
},
{
"code": null,
"e": 8949,
"s": 8824,
"text": "These are the processors which are designed for some special purposes. Few of the special processors are briefly discussed −"
},
{
"code": null,
"e": 9096,
"s": 8949,
"text": "A coprocessor is a specially designed microprocessor, which can handle its particular function many times faster than the ordinary microprocessor."
},
{
"code": null,
"e": 9128,
"s": 9096,
"text": "For example − Math Coprocessor."
},
{
"code": null,
"e": 9163,
"s": 9128,
"text": "Some Intel math-coprocessors are −"
},
{
"code": null,
"e": 9183,
"s": 9163,
"text": "8087-used with 8086"
},
{
"code": null,
"e": 9205,
"s": 9183,
"text": "80287-used with 80286"
},
{
"code": null,
"e": 9227,
"s": 9205,
"text": "80387-used with 80386"
},
{
"code": null,
"e": 9370,
"s": 9227,
"text": "It is a specially designed microprocessor having a local memory of its own, which is used to control I/O devices with minimum CPU involvement."
},
{
"code": null,
"e": 9384,
"s": 9370,
"text": "For example −"
},
{
"code": null,
"e": 9422,
"s": 9384,
"text": "DMA (direct Memory Access) controller"
},
{
"code": null,
"e": 9448,
"s": 9422,
"text": "Keyboard/mouse controller"
},
{
"code": null,
"e": 9475,
"s": 9448,
"text": "Graphic display controller"
},
{
"code": null,
"e": 9496,
"s": 9475,
"text": "SCSI port controller"
},
{
"code": null,
"e": 9769,
"s": 9496,
"text": "A transputer is a specially designed microprocessor with its own local memory and having links to connect one transputer to another transputer for inter-processor communications. It was first designed in 1980 by Inmos and is targeted to the utilization of VLSI technology."
},
{
"code": null,
"e": 9929,
"s": 9769,
"text": "A transputer can be used as a single processor system or can be connected to external links, which reduces the construction cost and increases the performance."
},
{
"code": null,
"e": 10021,
"s": 9929,
"text": "For example − 16-bit T212, 32-bit T425, the floating point (T800, T805 & T9000) processors."
},
{
"code": null,
"e": 10347,
"s": 10021,
"text": "This processor is specially designed to process the analog signals into a digital form. This is done by sampling the voltage level at regular time intervals and converting the voltage at that instant into a digital form. This process is performed by a circuit called an analogue to digital converter, A to D converter or ADC."
},
{
"code": null,
"e": 10389,
"s": 10347,
"text": "A DSP contains the following components −"
},
{
"code": null,
"e": 10464,
"s": 10389,
"text": "Program Memory − It stores the programs that DSP will use to process data."
},
{
"code": null,
"e": 10539,
"s": 10464,
"text": "Program Memory − It stores the programs that DSP will use to process data."
},
{
"code": null,
"e": 10596,
"s": 10539,
"text": "Data Memory − It stores the information to be processed."
},
{
"code": null,
"e": 10653,
"s": 10596,
"text": "Data Memory − It stores the information to be processed."
},
{
"code": null,
"e": 10792,
"s": 10653,
"text": "Compute Engine − It performs the mathematical processing, accessing the program from the program memory and the data from the data memory."
},
{
"code": null,
"e": 10931,
"s": 10792,
"text": "Compute Engine − It performs the mathematical processing, accessing the program from the program memory and the data from the data memory."
},
{
"code": null,
"e": 10980,
"s": 10931,
"text": "Input/Output − It connects to the outside world."
},
{
"code": null,
"e": 11029,
"s": 10980,
"text": "Input/Output − It connects to the outside world."
},
{
"code": null,
"e": 11052,
"s": 11029,
"text": "Its applications are −"
},
{
"code": null,
"e": 11078,
"s": 11052,
"text": "Sound and music synthesis"
},
{
"code": null,
"e": 11106,
"s": 11078,
"text": "Audio and video compression"
},
{
"code": null,
"e": 11130,
"s": 11106,
"text": "Video signal processing"
},
{
"code": null,
"e": 11163,
"s": 11130,
"text": "2D and 3d graphics acceleration."
},
{
"code": null,
"e": 11241,
"s": 11163,
"text": "For example − Texas Instrument’s TMS 320 series, e.g., TMS 320C40, TMS320C50."
},
{
"code": null,
"e": 11379,
"s": 11241,
"text": "8085 is pronounced as \"eighty-eighty-five\" microprocessor. It is an 8-bit microprocessor designed by Intel in 1977 using NMOS technology."
},
{
"code": null,
"e": 11416,
"s": 11379,
"text": "It has the following configuration −"
},
{
"code": null,
"e": 11431,
"s": 11416,
"text": "8-bit data bus"
},
{
"code": null,
"e": 11479,
"s": 11431,
"text": "16-bit address bus, which can address upto 64KB"
},
{
"code": null,
"e": 11504,
"s": 11479,
"text": "A 16-bit program counter"
},
{
"code": null,
"e": 11527,
"s": 11504,
"text": "A 16-bit stack pointer"
},
{
"code": null,
"e": 11577,
"s": 11527,
"text": "Six 8-bit registers arranged in pairs: BC, DE, HL"
},
{
"code": null,
"e": 11638,
"s": 11577,
"text": "Requires +5V supply to operate at 3.2 MHZ single phase clock"
},
{
"code": null,
"e": 11707,
"s": 11638,
"text": "It is used in washing machines, microwave ovens, mobile phones, etc."
},
{
"code": null,
"e": 11757,
"s": 11707,
"text": "8085 consists of the following functional units −"
},
{
"code": null,
"e": 11891,
"s": 11757,
"text": "It is an 8-bit register used to perform arithmetic, logical, I/O & LOAD/STORE operations. It is connected to internal data bus & ALU."
},
{
"code": null,
"e": 12016,
"s": 11891,
"text": "As the name suggests, it performs arithmetic and logical operations like Addition, Subtraction, AND, OR, etc. on 8-bit data."
},
{
"code": null,
"e": 12132,
"s": 12016,
"text": "There are 6 general purpose registers in 8085 processor, i.e. B, C, D, E, H & L. Each register can hold 8-bit data."
},
{
"code": null,
"e": 12239,
"s": 12132,
"text": "These registers can work in pair to hold 16-bit data and their pairing combination is like B-C, D-E & H-L."
},
{
"code": null,
"e": 12537,
"s": 12239,
"text": "It is a 16-bit register used to store the memory address location of the next instruction to be executed. Microprocessor increments the program whenever an instruction is being executed, so that the program counter points to the memory address of the next instruction that is going to be executed."
},
{
"code": null,
"e": 12659,
"s": 12537,
"text": "It is also a 16-bit register works like stack, which is always incremented/decremented by 2 during push & pop operations."
},
{
"code": null,
"e": 12753,
"s": 12659,
"text": "It is an 8-bit register, which holds the temporary data of arithmetic and logical operations."
},
{
"code": null,
"e": 12886,
"s": 12753,
"text": "It is an 8-bit register having five 1-bit flip-flops, which holds either 0 or 1 depending upon the result stored in the accumulator."
},
{
"code": null,
"e": 12922,
"s": 12886,
"text": "These are the set of 5 flip-flops −"
},
{
"code": null,
"e": 12931,
"s": 12922,
"text": "Sign (S)"
},
{
"code": null,
"e": 12940,
"s": 12931,
"text": "Zero (Z)"
},
{
"code": null,
"e": 12961,
"s": 12940,
"text": "Auxiliary Carry (AC)"
},
{
"code": null,
"e": 12972,
"s": 12961,
"text": "Parity (P)"
},
{
"code": null,
"e": 12982,
"s": 12972,
"text": "Carry (C)"
},
{
"code": null,
"e": 13033,
"s": 12982,
"text": "Its bit position is shown in the following table −"
},
{
"code": null,
"e": 13229,
"s": 13033,
"text": "It is an 8-bit register. When an instruction is fetched from memory then it is stored in the Instruction register. Instruction decoder decodes the information present in the Instruction register."
},
{
"code": null,
"e": 13405,
"s": 13229,
"text": "It provides timing and control signal to the microprocessor to perform operations. Following are the timing and control signals, which control external and internal circuits −"
},
{
"code": null,
"e": 13443,
"s": 13405,
"text": "Control Signals: READY, RD’, WR’, ALE"
},
{
"code": null,
"e": 13473,
"s": 13443,
"text": "Status Signals: S0, S1, IO/M’"
},
{
"code": null,
"e": 13497,
"s": 13473,
"text": "DMA Signals: HOLD, HLDA"
},
{
"code": null,
"e": 13532,
"s": 13497,
"text": "RESET Signals: RESET IN, RESET OUT"
},
{
"code": null,
"e": 13850,
"s": 13532,
"text": "As the name suggests it controls the interrupts during a process. When a microprocessor is executing a main program and whenever an interrupt occurs, the microprocessor shifts the control from the main program to process the incoming request. After the request is completed, the control goes back to the main program."
},
{
"code": null,
"e": 13943,
"s": 13850,
"text": "There are 5 interrupt signals in 8085 microprocessor: INTR, RST 7.5, RST 6.5, RST 5.5, TRAP."
},
{
"code": null,
"e": 14072,
"s": 13943,
"text": "It controls the serial data communication by using these two instructions: SID (Serial input data) and SOD (Serial output data)."
},
{
"code": null,
"e": 14343,
"s": 14072,
"text": "The content stored in the stack pointer and program counter is loaded into the address buffer and address-data buffer to communicate with the CPU. The memory and I/O chips are connected to these buses; the CPU can exchange the desired data with the memory and I/O chips."
},
{
"code": null,
"e": 14555,
"s": 14343,
"text": "Data bus carries the data to be stored. It is bidirectional, whereas address bus carries the location to where it should be stored and it is unidirectional. It is used to transfer the data & Address I/O devices."
},
{
"code": null,
"e": 14632,
"s": 14555,
"text": "We have tried to depict the architecture of 8085 with this following image −"
},
{
"code": null,
"e": 14701,
"s": 14632,
"text": "The following image depicts the pin diagram of 8085 Microprocessor −"
},
{
"code": null,
"e": 14773,
"s": 14701,
"text": "The pins of a 8085 microprocessor can be classified into seven groups −"
},
{
"code": null,
"e": 14842,
"s": 14773,
"text": "A15-A8, it carries the most significant 8-bits of memory/IO address."
},
{
"code": null,
"e": 14912,
"s": 14842,
"text": "AD7-AD0, it carries the least significant 8-bit address and data bus."
},
{
"code": null,
"e": 15021,
"s": 14912,
"text": "These signals are used to identify the nature of operation. There are 3 control signal and 3 status signals."
},
{
"code": null,
"e": 15061,
"s": 15021,
"text": "Three control signals are RD, WR & ALE."
},
{
"code": null,
"e": 15199,
"s": 15061,
"text": "RD − This signal indicates that the selected IO or memory device is to be read and is ready for accepting data available on the data bus."
},
{
"code": null,
"e": 15337,
"s": 15199,
"text": "RD − This signal indicates that the selected IO or memory device is to be read and is ready for accepting data available on the data bus."
},
{
"code": null,
"e": 15450,
"s": 15337,
"text": "WR − This signal indicates that the data on the data bus is to be written into a selected memory or IO location."
},
{
"code": null,
"e": 15563,
"s": 15450,
"text": "WR − This signal indicates that the data on the data bus is to be written into a selected memory or IO location."
},
{
"code": null,
"e": 15755,
"s": 15563,
"text": "ALE − It is a positive going pulse generated when a new operation is started by the microprocessor. When the pulse goes high, it indicates address. When the pulse goes down it indicates data."
},
{
"code": null,
"e": 15947,
"s": 15755,
"text": "ALE − It is a positive going pulse generated when a new operation is started by the microprocessor. When the pulse goes high, it indicates address. When the pulse goes down it indicates data."
},
{
"code": null,
"e": 15987,
"s": 15947,
"text": "Three status signals are IO/M, S0 & S1."
},
{
"code": null,
"e": 16157,
"s": 15987,
"text": "This signal is used to differentiate between IO and Memory operations, i.e. when it is high indicates IO operation and when it is low then it indicates memory operation."
},
{
"code": null,
"e": 16223,
"s": 16157,
"text": "These signals are used to identify the type of current operation."
},
{
"code": null,
"e": 16333,
"s": 16223,
"text": "There are 2 power supply signals − VCC & VSS. VCC indicates +5v power supply and VSS indicates ground signal."
},
{
"code": null,
"e": 16382,
"s": 16333,
"text": "There are 3 clock signals, i.e. X1, X2, CLK OUT."
},
{
"code": null,
"e": 16550,
"s": 16382,
"text": "X1, X2 − A crystal (RC, LC N/W) is connected at these two pins and is used to set frequency of the internal clock generator. This frequency is internally divided by 2."
},
{
"code": null,
"e": 16718,
"s": 16550,
"text": "X1, X2 − A crystal (RC, LC N/W) is connected at these two pins and is used to set frequency of the internal clock generator. This frequency is internally divided by 2."
},
{
"code": null,
"e": 16815,
"s": 16718,
"text": "CLK OUT − This signal is used as the system clock for devices connected with the microprocessor."
},
{
"code": null,
"e": 16912,
"s": 16815,
"text": "CLK OUT − This signal is used as the system clock for devices connected with the microprocessor."
},
{
"code": null,
"e": 17157,
"s": 16912,
"text": "Interrupts are the signals generated by external devices to request the microprocessor to perform a task. There are 5 interrupt signals, i.e. TRAP, RST 7.5, RST 6.5, RST 5.5, and INTR. We will discuss interrupts in detail in interrupts section."
},
{
"code": null,
"e": 17206,
"s": 17157,
"text": "INTA − It is an interrupt acknowledgment signal."
},
{
"code": null,
"e": 17255,
"s": 17206,
"text": "INTA − It is an interrupt acknowledgment signal."
},
{
"code": null,
"e": 17354,
"s": 17255,
"text": "RESET IN − This signal is used to reset the microprocessor by setting the program counter to zero."
},
{
"code": null,
"e": 17453,
"s": 17354,
"text": "RESET IN − This signal is used to reset the microprocessor by setting the program counter to zero."
},
{
"code": null,
"e": 17554,
"s": 17453,
"text": "RESET OUT − This signal is used to reset all the connected devices when the microprocessor is reset."
},
{
"code": null,
"e": 17655,
"s": 17554,
"text": "RESET OUT − This signal is used to reset all the connected devices when the microprocessor is reset."
},
{
"code": null,
"e": 17799,
"s": 17655,
"text": "READY − This signal indicates that the device is ready to send or receive data. If READY is low, then the CPU has to wait for READY to go high."
},
{
"code": null,
"e": 17943,
"s": 17799,
"text": "READY − This signal indicates that the device is ready to send or receive data. If READY is low, then the CPU has to wait for READY to go high."
},
{
"code": null,
"e": 18045,
"s": 17943,
"text": "HOLD − This signal indicates that another master is requesting the use of the address and data buses."
},
{
"code": null,
"e": 18147,
"s": 18045,
"text": "HOLD − This signal indicates that another master is requesting the use of the address and data buses."
},
{
"code": null,
"e": 18338,
"s": 18147,
"text": "HLDA (HOLD Acknowledge) − It indicates that the CPU has received the HOLD request and it will relinquish the bus in the next clock cycle. HLDA is set to low after the HOLD signal is removed."
},
{
"code": null,
"e": 18529,
"s": 18338,
"text": "HLDA (HOLD Acknowledge) − It indicates that the CPU has received the HOLD request and it will relinquish the bus in the next clock cycle. HLDA is set to low after the HOLD signal is removed."
},
{
"code": null,
"e": 18627,
"s": 18529,
"text": "There are 2 serial signals, i.e. SID and SOD and these signals are used for serial communication."
},
{
"code": null,
"e": 18724,
"s": 18627,
"text": "SOD (Serial output data line) − The output SOD is set/reset as specified by the SIM instruction."
},
{
"code": null,
"e": 18821,
"s": 18724,
"text": "SOD (Serial output data line) − The output SOD is set/reset as specified by the SIM instruction."
},
{
"code": null,
"e": 18941,
"s": 18821,
"text": "SID (Serial input data line) − The data on this line is loaded into accumulator whenever a RIM instruction is executed."
},
{
"code": null,
"e": 19061,
"s": 18941,
"text": "SID (Serial input data line) − The data on this line is loaded into accumulator whenever a RIM instruction is executed."
},
{
"code": null,
"e": 19125,
"s": 19061,
"text": "Now let us discuss the addressing modes in 8085 Microprocessor."
},
{
"code": null,
"e": 19380,
"s": 19125,
"text": "These are the instructions used to transfer the data from one register to another register, from the memory to the register, and from the register to the memory without any alteration in the content. Addressing modes in 8085 is classified into 5 groups −"
},
{
"code": null,
"e": 19536,
"s": 19380,
"text": "In this mode, the 8/16-bit data is specified in the instruction itself as one of its operand. For example: MVI K, 20F: means 20F is copied into register K."
},
{
"code": null,
"e": 19672,
"s": 19536,
"text": "In this mode, the data is copied from one register to another. For example: MOV K, B: means data in register B is copied to register K."
},
{
"code": null,
"e": 19835,
"s": 19672,
"text": "In this mode, the data is directly copied from the given address to the register. For example: LDB 5000K: means the data at address 5000K is copied to register B."
},
{
"code": null,
"e": 20064,
"s": 19835,
"text": "In this mode, the data is transferred from one register to another by using the address pointed by the register. For example: MOV K, B: means data is transferred from the memory address pointed by the register to the register K."
},
{
"code": null,
"e": 20165,
"s": 20064,
"text": "This mode doesn’t require any operand; the data is specified by the opcode itself. For example: CMP."
},
{
"code": null,
"e": 20354,
"s": 20165,
"text": "Interrupts are the signals generated by the external devices to request the microprocessor to perform a task. There are 5 interrupt signals, i.e. TRAP, RST 7.5, RST 6.5, RST 5.5, and INTR."
},
{
"code": null,
"e": 20428,
"s": 20354,
"text": "Interrupt are classified into following groups based on their parameter −"
},
{
"code": null,
"e": 20566,
"s": 20428,
"text": "Vector interrupt − In this type of interrupt, the interrupt address is known to the processor. For example: RST7.5, RST6.5, RST5.5, TRAP."
},
{
"code": null,
"e": 20704,
"s": 20566,
"text": "Vector interrupt − In this type of interrupt, the interrupt address is known to the processor. For example: RST7.5, RST6.5, RST5.5, TRAP."
},
{
"code": null,
"e": 20916,
"s": 20704,
"text": "Non-Vector interrupt − In this type of interrupt, the interrupt address is not known to the processor so, the interrupt address needs to be sent externally by the device to perform interrupts. For example: INTR."
},
{
"code": null,
"e": 21128,
"s": 20916,
"text": "Non-Vector interrupt − In this type of interrupt, the interrupt address is not known to the processor so, the interrupt address needs to be sent externally by the device to perform interrupts. For example: INTR."
},
{
"code": null,
"e": 21289,
"s": 21128,
"text": "Maskable interrupt − In this type of interrupt, we can disable the interrupt by writing some instructions into the program. For example: RST7.5, RST6.5, RST5.5."
},
{
"code": null,
"e": 21450,
"s": 21289,
"text": "Maskable interrupt − In this type of interrupt, we can disable the interrupt by writing some instructions into the program. For example: RST7.5, RST6.5, RST5.5."
},
{
"code": null,
"e": 21600,
"s": 21450,
"text": "Non-Maskable interrupt − In this type of interrupt, we cannot disable the interrupt by writing some instructions into the program. For example: TRAP."
},
{
"code": null,
"e": 21750,
"s": 21600,
"text": "Non-Maskable interrupt − In this type of interrupt, we cannot disable the interrupt by writing some instructions into the program. For example: TRAP."
},
{
"code": null,
"e": 21982,
"s": 21750,
"text": "Software interrupt − In this type of interrupt, the programmer has to add the instructions into the program to execute the interrupt. There are 8 software interrupts in 8085, i.e. RST0, RST1, RST2, RST3, RST4, RST5, RST6, and RST7."
},
{
"code": null,
"e": 22214,
"s": 21982,
"text": "Software interrupt − In this type of interrupt, the programmer has to add the instructions into the program to execute the interrupt. There are 8 software interrupts in 8085, i.e. RST0, RST1, RST2, RST3, RST4, RST5, RST6, and RST7."
},
{
"code": null,
"e": 22340,
"s": 22214,
"text": "Hardware interrupt − There are 5 interrupt pins in 8085 used as hardware interrupts, i.e. TRAP, RST7.5, RST6.5, RST5.5, INTA."
},
{
"code": null,
"e": 22466,
"s": 22340,
"text": "Hardware interrupt − There are 5 interrupt pins in 8085 used as hardware interrupts, i.e. TRAP, RST7.5, RST6.5, RST5.5, INTA."
},
{
"code": null,
"e": 22614,
"s": 22466,
"text": "Note − NTA is not an interrupt, it is used by the microprocessor for sending acknowledgement. TRAP has the highest priority, then RST7.5 and so on."
},
{
"code": null,
"e": 22728,
"s": 22614,
"text": "A small program or a routine that when executed, services the corresponding interrupting source is called an ISR."
},
{
"code": null,
"e": 22999,
"s": 22728,
"text": "It is a non-maskable interrupt, having the highest priority among all interrupts. Bydefault, it is enabled until it gets acknowledged. In case of failure, it executes as ISR and sends the data to backup memory. This interrupt transfers the control to the location 0024H."
},
{
"code": null,
"e": 23214,
"s": 22999,
"text": "It is a maskable interrupt, having the second highest priority among all interrupts. When this interrupt is executed, the processor saves the content of the PC register into the stack and branches to 003CH address."
},
{
"code": null,
"e": 23428,
"s": 23214,
"text": "It is a maskable interrupt, having the third highest priority among all interrupts. When this interrupt is executed, the processor saves the content of the PC register into the stack and branches to 0034H address."
},
{
"code": null,
"e": 23586,
"s": 23428,
"text": "It is a maskable interrupt. When this interrupt is executed, the processor saves the content of the PC register into the stack and branches to 002CH address."
},
{
"code": null,
"e": 23715,
"s": 23586,
"text": "It is a maskable interrupt, having the lowest priority among all interrupts. It can be disabled by resetting the microprocessor."
},
{
"code": null,
"e": 23776,
"s": 23715,
"text": "When INTR signal goes high, the following events can occur −"
},
{
"code": null,
"e": 23870,
"s": 23776,
"text": "The microprocessor checks the status of INTR signal during the execution of each instruction."
},
{
"code": null,
"e": 23964,
"s": 23870,
"text": "The microprocessor checks the status of INTR signal during the execution of each instruction."
},
{
"code": null,
"e": 24103,
"s": 23964,
"text": "When the INTR signal is high, then the microprocessor completes its current instruction and sends active low interrupt acknowledge signal."
},
{
"code": null,
"e": 24242,
"s": 24103,
"text": "When the INTR signal is high, then the microprocessor completes its current instruction and sends active low interrupt acknowledge signal."
},
{
"code": null,
"e": 24388,
"s": 24242,
"text": "When instructions are received, then the microprocessor saves the address of the next instruction on stack and executes the received instruction."
},
{
"code": null,
"e": 24534,
"s": 24388,
"text": "When instructions are received, then the microprocessor saves the address of the next instruction on stack and executes the received instruction."
},
{
"code": null,
"e": 24596,
"s": 24534,
"text": "Let us take a look at the programming of 8085 Microprocessor."
},
{
"code": null,
"e": 24696,
"s": 24596,
"text": "Instruction sets are instruction codes to perform some task. It is classified into five categories."
},
{
"code": null,
"e": 24781,
"s": 24696,
"text": "Following is the table showing the list of Control instructions with their meanings."
},
{
"code": null,
"e": 24866,
"s": 24781,
"text": "Following is the table showing the list of Logical instructions with their meanings."
},
{
"code": null,
"e": 24953,
"s": 24866,
"text": "Following is the table showing the list of Branching instructions with their meanings."
},
{
"code": null,
"e": 25041,
"s": 24953,
"text": "Following is the table showing the list of Arithmetic instructions with their meanings."
},
{
"code": null,
"e": 25132,
"s": 25041,
"text": "Following is the table showing the list of Data-transfer instructions with their meanings."
},
{
"code": null,
"e": 25218,
"s": 25132,
"text": "Now, let us take a look at some program demonstrations using the above instructions −"
},
{
"code": null,
"e": 25326,
"s": 25218,
"text": "Write a program to add data at 3005H & 3006H memory location and store the result at 3007H memory location."
},
{
"code": null,
"e": 25341,
"s": 25326,
"text": "Problem demo −"
},
{
"code": null,
"e": 25374,
"s": 25341,
"text": "(3005H) = 14H \n (3006H) = 89H\n"
},
{
"code": null,
"e": 25383,
"s": 25374,
"text": "Result −"
},
{
"code": null,
"e": 25399,
"s": 25383,
"text": "14H + 89H = 9DH"
},
{
"code": null,
"e": 25443,
"s": 25399,
"text": "The program code can be written like this −"
},
{
"code": null,
"e": 25700,
"s": 25443,
"text": "LXI H 3005H : \"HL points 3005H\" \nMOV A, M : \"Getting first operand\" \nINX H : \"HL points 3006H\" \nADD M : \"Add second operand\" \nINX H : \"HL points 3007H\" \nMOV M, A : \"Store result at 3007H\" \nHLT : \"Exit program\" "
},
{
"code": null,
"e": 25770,
"s": 25700,
"text": "Write a program to exchange the data at 5000M& 6000M memory location."
},
{
"code": null,
"e": 26163,
"s": 25770,
"text": "LDA 5000M : \"Getting the contents at5000M location into accumulator\" \nMOV B, A : \"Save the contents into B register\" \nLDA 6000M : \"Getting the contents at 6000M location into accumulator\" \nSTA 5000M : \"Store the contents of accumulator at address 5000M\" \nMOV A, B : \"Get the saved contents back into A register\" \nSTA 6000M : \"Store the contents of accumulator at address 6000M\" "
},
{
"code": null,
"e": 26256,
"s": 26163,
"text": "Write a program to arrange first 10 numbers from memory address 3000H in an ascending order."
},
{
"code": null,
"e": 26914,
"s": 26256,
"text": "MVI B, 09 :\"Initialize counter\" \nSTART :\"LXI H, 3000H: Initialize memory pointer\" \nMVI C, 09H :\"Initialize counter 2\" \nBACK: MOV A, M :\"Get the number\" \nINX H :\"Increment memory pointer\" \nCMP M :\"Compare number with next number\" \nJC SKIP :\"If less, don’t interchange\" \nJZ SKIP :\"If equal, don’t interchange\" \nMOV D, M \nMOV M, A \nDCX H \nMOV M, D \nINX H :\"Interchange two numbers\" \nSKIP:DCR C :\"Decrement counter 2\" \nJNZ BACK :\"If not zero, repeat\" \nDCR B :\"Decrement counter 1\" \nJNZ START \nHLT :\"Terminate program execution\" "
},
{
"code": null,
"e": 27227,
"s": 26914,
"text": "8086 Microprocessor is an enhanced version of 8085Microprocessor that was designed by Intel in 1976. It is a 16-bit Microprocessor having 20 address lines and16 data lines that provides up to 1MB storage. It consists of powerful instruction set, which provides operations like multiplication and division easily."
},
{
"code": null,
"e": 27429,
"s": 27227,
"text": "It supports two modes of operation, i.e. Maximum mode and Minimum mode. Maximum mode is suitable for system having multiple processors and Minimum mode is suitable for system having a single processor."
},
{
"code": null,
"e": 27499,
"s": 27429,
"text": "The most prominent features of a 8086 microprocessor are as follows −"
},
{
"code": null,
"e": 27626,
"s": 27499,
"text": "It has an instruction queue, which is capable of storing six instruction bytes from the memory resulting in faster processing."
},
{
"code": null,
"e": 27753,
"s": 27626,
"text": "It has an instruction queue, which is capable of storing six instruction bytes from the memory resulting in faster processing."
},
{
"code": null,
"e": 27904,
"s": 27753,
"text": "It was the first 16-bit processor having 16-bit ALU, 16-bit registers, internal data bus, and 16-bit external data bus resulting in faster processing."
},
{
"code": null,
"e": 28055,
"s": 27904,
"text": "It was the first 16-bit processor having 16-bit ALU, 16-bit registers, internal data bus, and 16-bit external data bus resulting in faster processing."
},
{
"code": null,
"e": 28171,
"s": 28055,
"text": "It is available in 3 versions based on the frequency of operation −\n\n8086 → 5MHz\n8086-2 → 8MHz\n(c)8086-1 → 10 MHz\n\n"
},
{
"code": null,
"e": 28239,
"s": 28171,
"text": "It is available in 3 versions based on the frequency of operation −"
},
{
"code": null,
"e": 28251,
"s": 28239,
"text": "8086 → 5MHz"
},
{
"code": null,
"e": 28263,
"s": 28251,
"text": "8086 → 5MHz"
},
{
"code": null,
"e": 28277,
"s": 28263,
"text": "8086-2 → 8MHz"
},
{
"code": null,
"e": 28291,
"s": 28277,
"text": "8086-2 → 8MHz"
},
{
"code": null,
"e": 28310,
"s": 28291,
"text": "(c)8086-1 → 10 MHz"
},
{
"code": null,
"e": 28329,
"s": 28310,
"text": "(c)8086-1 → 10 MHz"
},
{
"code": null,
"e": 28427,
"s": 28329,
"text": "It uses two stages of pipelining, i.e. Fetch Stage and Execute Stage, which improves performance."
},
{
"code": null,
"e": 28525,
"s": 28427,
"text": "It uses two stages of pipelining, i.e. Fetch Stage and Execute Stage, which improves performance."
},
{
"code": null,
"e": 28610,
"s": 28525,
"text": "Fetch stage can prefetch up to 6 bytes of instructions and stores them in the queue."
},
{
"code": null,
"e": 28695,
"s": 28610,
"text": "Fetch stage can prefetch up to 6 bytes of instructions and stores them in the queue."
},
{
"code": null,
"e": 28738,
"s": 28695,
"text": "Execute stage executes these instructions."
},
{
"code": null,
"e": 28781,
"s": 28738,
"text": "Execute stage executes these instructions."
},
{
"code": null,
"e": 28813,
"s": 28781,
"text": "It has 256 vectored interrupts."
},
{
"code": null,
"e": 28845,
"s": 28813,
"text": "It has 256 vectored interrupts."
},
{
"code": null,
"e": 28880,
"s": 28845,
"text": "It consists of 29,000 transistors."
},
{
"code": null,
"e": 28915,
"s": 28880,
"text": "It consists of 29,000 transistors."
},
{
"code": null,
"e": 28991,
"s": 28915,
"text": "Size − 8085 is 8-bit microprocessor, whereas 8086 is 16-bit microprocessor."
},
{
"code": null,
"e": 29067,
"s": 28991,
"text": "Size − 8085 is 8-bit microprocessor, whereas 8086 is 16-bit microprocessor."
},
{
"code": null,
"e": 29144,
"s": 29067,
"text": "Address Bus − 8085 has 16-bit address bus while 8086 has 20-bit address bus."
},
{
"code": null,
"e": 29221,
"s": 29144,
"text": "Address Bus − 8085 has 16-bit address bus while 8086 has 20-bit address bus."
},
{
"code": null,
"e": 29304,
"s": 29221,
"text": "Memory − 8085 can access up to 64Kb, whereas 8086 can access up to 1 Mb of memory."
},
{
"code": null,
"e": 29387,
"s": 29304,
"text": "Memory − 8085 can access up to 64Kb, whereas 8086 can access up to 1 Mb of memory."
},
{
"code": null,
"e": 29480,
"s": 29387,
"text": "Instruction − 8085 doesn’t have an instruction queue, whereas 8086 has an instruction queue."
},
{
"code": null,
"e": 29573,
"s": 29480,
"text": "Instruction − 8085 doesn’t have an instruction queue, whereas 8086 has an instruction queue."
},
{
"code": null,
"e": 29678,
"s": 29573,
"text": "Pipelining − 8085 doesn’t support a pipelined architecture while 8086 supports a pipelined architecture."
},
{
"code": null,
"e": 29783,
"s": 29678,
"text": "Pipelining − 8085 doesn’t support a pipelined architecture while 8086 supports a pipelined architecture."
},
{
"code": null,
"e": 29868,
"s": 29783,
"text": "I/O − 8085 can address 2^8 = 256 I/O's, whereas 8086 can access 2^16 = 65,536 I/O's."
},
{
"code": null,
"e": 29953,
"s": 29868,
"text": "I/O − 8085 can address 2^8 = 256 I/O's, whereas 8086 can access 2^16 = 65,536 I/O's."
},
{
"code": null,
"e": 30014,
"s": 29953,
"text": "Cost − The cost of 8085 is low whereas that of 8086 is high."
},
{
"code": null,
"e": 30075,
"s": 30014,
"text": "Cost − The cost of 8085 is low whereas that of 8086 is high."
},
{
"code": null,
"e": 30149,
"s": 30075,
"text": "The following diagram depicts the architecture of a 8086 Microprocessor −"
},
{
"code": null,
"e": 30263,
"s": 30149,
"text": "8086 Microprocessor is divided into two functional units, i.e., EU (Execution Unit) and BIU (Bus Interface Unit)."
},
{
"code": null,
"e": 30594,
"s": 30263,
"text": "Execution unit gives instructions to BIU stating from where to fetch the data and then decode and execute those instructions. Its function is to control operations on data using the instruction decoder & ALU. EU has no direct connection with system buses as shown in the above figure, it performs operations over data through BIU."
},
{
"code": null,
"e": 30659,
"s": 30594,
"text": "Let us now discuss the functional parts of 8086 microprocessors."
},
{
"code": null,
"e": 30751,
"s": 30659,
"text": "It handles all arithmetic and logical operations, like +, −, ×, /, OR, AND, NOT operations."
},
{
"code": null,
"e": 30973,
"s": 30751,
"text": "It is a 16-bit register that behaves like a flip-flop, i.e. it changes its status according to the result stored in the accumulator. It has 9 flags and they are divided into 2 groups − Conditional Flags and Control Flags."
},
{
"code": null,
"e": 31100,
"s": 30973,
"text": "It represents the result of the last arithmetic or logical instruction executed. Following is the list of conditional flags −"
},
{
"code": null,
"e": 31182,
"s": 31100,
"text": "Carry flag − This flag indicates an overflow condition for arithmetic operations."
},
{
"code": null,
"e": 31264,
"s": 31182,
"text": "Carry flag − This flag indicates an overflow condition for arithmetic operations."
},
{
"code": null,
"e": 31548,
"s": 31264,
"text": "Auxiliary flag − When an operation is performed at ALU, it results in a carry/barrow from lower nibble (i.e. D0 – D3) to upper nibble (i.e. D4 – D7), then this flag is set, i.e. carry given by D3 bit to D4 is AF flag. The processor uses this flag to perform binary to BCD conversion."
},
{
"code": null,
"e": 31832,
"s": 31548,
"text": "Auxiliary flag − When an operation is performed at ALU, it results in a carry/barrow from lower nibble (i.e. D0 – D3) to upper nibble (i.e. D4 – D7), then this flag is set, i.e. carry given by D3 bit to D4 is AF flag. The processor uses this flag to perform binary to BCD conversion."
},
{
"code": null,
"e": 32056,
"s": 31832,
"text": "Parity flag − This flag is used to indicate the parity of the result, i.e. when the lower order 8-bits of the result contains even number of 1’s, then the Parity Flag is set. For odd number of 1’s, the Parity Flag is reset."
},
{
"code": null,
"e": 32280,
"s": 32056,
"text": "Parity flag − This flag is used to indicate the parity of the result, i.e. when the lower order 8-bits of the result contains even number of 1’s, then the Parity Flag is set. For odd number of 1’s, the Parity Flag is reset."
},
{
"code": null,
"e": 32394,
"s": 32280,
"text": "Zero flag − This flag is set to 1 when the result of arithmetic or logical operation is zero else it is set to 0."
},
{
"code": null,
"e": 32508,
"s": 32394,
"text": "Zero flag − This flag is set to 1 when the result of arithmetic or logical operation is zero else it is set to 0."
},
{
"code": null,
"e": 32657,
"s": 32508,
"text": "Sign flag − This flag holds the sign of the result, i.e. when the result of the operation is negative, then the sign flag is set to 1 else set to 0."
},
{
"code": null,
"e": 32806,
"s": 32657,
"text": "Sign flag − This flag holds the sign of the result, i.e. when the result of the operation is negative, then the sign flag is set to 1 else set to 0."
},
{
"code": null,
"e": 32892,
"s": 32806,
"text": "Overflow flag − This flag represents the result when the system capacity is exceeded."
},
{
"code": null,
"e": 32978,
"s": 32892,
"text": "Overflow flag − This flag represents the result when the system capacity is exceeded."
},
{
"code": null,
"e": 33080,
"s": 32978,
"text": "Control flags controls the operations of the execution unit. Following is the list of control flags −"
},
{
"code": null,
"e": 33264,
"s": 33080,
"text": "Trap flag − It is used for single step control and allows the user to execute one instruction at a time for debugging. If it is set, then the program can be run in a single step mode."
},
{
"code": null,
"e": 33448,
"s": 33264,
"text": "Trap flag − It is used for single step control and allows the user to execute one instruction at a time for debugging. If it is set, then the program can be run in a single step mode."
},
{
"code": null,
"e": 33658,
"s": 33448,
"text": "Interrupt flag − It is an interrupt enable/disable flag, i.e. used to allow/prohibit the interruption of a program. It is set to 1 for interrupt enabled condition and set to 0 for interrupt disabled condition."
},
{
"code": null,
"e": 33868,
"s": 33658,
"text": "Interrupt flag − It is an interrupt enable/disable flag, i.e. used to allow/prohibit the interruption of a program. It is set to 1 for interrupt enabled condition and set to 0 for interrupt disabled condition."
},
{
"code": null,
"e": 34061,
"s": 33868,
"text": "Direction flag − It is used in string operation. As the name suggests when it is set then string bytes are accessed from the higher memory address to the lower memory address and vice-a-versa."
},
{
"code": null,
"e": 34254,
"s": 34061,
"text": "Direction flag − It is used in string operation. As the name suggests when it is set then string bytes are accessed from the higher memory address to the lower memory address and vice-a-versa."
},
{
"code": null,
"e": 34574,
"s": 34254,
"text": "There are 8 general purpose registers, i.e., AH, AL, BH, BL, CH, CL, DH, and DL. These registers can be used individually to store 8-bit data and can be used in pairs to store 16bit data. The valid register pairs are AH and AL, BH and BL, CH and CL, and DH and DL. It is referred to the AX, BX, CX, and DX respectively."
},
{
"code": null,
"e": 34686,
"s": 34574,
"text": "AX register − It is also known as accumulator register. It is used to store operands for arithmetic operations."
},
{
"code": null,
"e": 34798,
"s": 34686,
"text": "AX register − It is also known as accumulator register. It is used to store operands for arithmetic operations."
},
{
"code": null,
"e": 34933,
"s": 34798,
"text": "BX register − It is used as a base register. It is used to store the starting base address of the memory area within the data segment."
},
{
"code": null,
"e": 35068,
"s": 34933,
"text": "BX register − It is used as a base register. It is used to store the starting base address of the memory area within the data segment."
},
{
"code": null,
"e": 35170,
"s": 35068,
"text": "CX register − It is referred to as counter. It is used in loop instruction to store the loop counter."
},
{
"code": null,
"e": 35272,
"s": 35170,
"text": "CX register − It is referred to as counter. It is used in loop instruction to store the loop counter."
},
{
"code": null,
"e": 35354,
"s": 35272,
"text": "DX register − This register is used to hold I/O port address for I/O instruction."
},
{
"code": null,
"e": 35436,
"s": 35354,
"text": "DX register − This register is used to hold I/O port address for I/O instruction."
},
{
"code": null,
"e": 35591,
"s": 35436,
"text": "It is a 16-bit register, which holds the address from the start of the segment to the memory location, where a word was most recently stored on the stack."
},
{
"code": null,
"e": 35956,
"s": 35591,
"text": "BIU takes care of all data and addresses transfers on the buses for the EU like sending addresses, fetching instructions from the memory, reading data from the ports and the memory as well as writing data to the ports and the memory. EU has no direction connection with System Buses so this is possible with the BIU. EU and BIU are connected with the Internal Bus."
},
{
"code": null,
"e": 35996,
"s": 35956,
"text": "It has the following functional parts −"
},
{
"code": null,
"e": 36311,
"s": 35996,
"text": "Instruction queue − BIU contains the instruction queue. BIU gets upto 6 bytes of next instructions and stores them in the instruction queue. When EU executes instructions and is ready for its next instruction, then it simply reads the instruction from this instruction queue resulting in increased execution speed."
},
{
"code": null,
"e": 36626,
"s": 36311,
"text": "Instruction queue − BIU contains the instruction queue. BIU gets upto 6 bytes of next instructions and stores them in the instruction queue. When EU executes instructions and is ready for its next instruction, then it simply reads the instruction from this instruction queue resulting in increased execution speed."
},
{
"code": null,
"e": 36717,
"s": 36626,
"text": "Fetching the next instruction while the current instruction executes is called pipelining."
},
{
"code": null,
"e": 36808,
"s": 36717,
"text": "Fetching the next instruction while the current instruction executes is called pipelining."
},
{
"code": null,
"e": 37678,
"s": 36808,
"text": "Segment register − BIU has 4 segment buses, i.e. CS, DS, SS& ES. It holds the addresses of instructions and data in memory, which are used by the processor to access memory locations. It also contains 1 pointer register IP, which holds the address of the next instruction to executed by the EU.\n\nCS − It stands for Code Segment. It is used for addressing a memory location in the code segment of the memory, where the executable program is stored.\nDS − It stands for Data Segment. It consists of data used by the program andis accessed in the data segment by an offset address or the content of other register that holds the offset address.\nSS − It stands for Stack Segment. It handles memory to store data and addresses during execution.\nES − It stands for Extra Segment. ES is additional data segment, which is used by the string to hold the extra destination data.\n\n"
},
{
"code": null,
"e": 37973,
"s": 37678,
"text": "Segment register − BIU has 4 segment buses, i.e. CS, DS, SS& ES. It holds the addresses of instructions and data in memory, which are used by the processor to access memory locations. It also contains 1 pointer register IP, which holds the address of the next instruction to executed by the EU."
},
{
"code": null,
"e": 38125,
"s": 37973,
"text": "CS − It stands for Code Segment. It is used for addressing a memory location in the code segment of the memory, where the executable program is stored."
},
{
"code": null,
"e": 38277,
"s": 38125,
"text": "CS − It stands for Code Segment. It is used for addressing a memory location in the code segment of the memory, where the executable program is stored."
},
{
"code": null,
"e": 38470,
"s": 38277,
"text": "DS − It stands for Data Segment. It consists of data used by the program andis accessed in the data segment by an offset address or the content of other register that holds the offset address."
},
{
"code": null,
"e": 38663,
"s": 38470,
"text": "DS − It stands for Data Segment. It consists of data used by the program andis accessed in the data segment by an offset address or the content of other register that holds the offset address."
},
{
"code": null,
"e": 38761,
"s": 38663,
"text": "SS − It stands for Stack Segment. It handles memory to store data and addresses during execution."
},
{
"code": null,
"e": 38859,
"s": 38761,
"text": "SS − It stands for Stack Segment. It handles memory to store data and addresses during execution."
},
{
"code": null,
"e": 38988,
"s": 38859,
"text": "ES − It stands for Extra Segment. ES is additional data segment, which is used by the string to hold the extra destination data."
},
{
"code": null,
"e": 39117,
"s": 38988,
"text": "ES − It stands for Extra Segment. ES is additional data segment, which is used by the string to hold the extra destination data."
},
{
"code": null,
"e": 39228,
"s": 39117,
"text": "Instruction pointer − It is a 16-bit register used to hold the address of the next instruction to be executed."
},
{
"code": null,
"e": 39339,
"s": 39228,
"text": "Instruction pointer − It is a 16-bit register used to hold the address of the next instruction to be executed."
},
{
"code": null,
"e": 39509,
"s": 39339,
"text": "8086 was the first 16-bit microprocessor available in 40-pin DIP (Dual Inline Package) chip. Let us now discuss in detail the pin configuration of a 8086 Microprocessor."
},
{
"code": null,
"e": 39558,
"s": 39509,
"text": "Here is the pin diagram of 8086 microprocessor −"
},
{
"code": null,
"e": 39601,
"s": 39558,
"text": "Let us now discuss the signals in detail −"
},
{
"code": null,
"e": 39636,
"s": 39601,
"text": "Power supply and frequency signals"
},
{
"code": null,
"e": 39727,
"s": 39636,
"text": "It uses 5V DC supply at VCC pin 40, and uses ground at VSS pin 1 and 20 for its operation."
},
{
"code": null,
"e": 39740,
"s": 39727,
"text": "Clock signal"
},
{
"code": null,
"e": 39911,
"s": 39740,
"text": "Clock signal is provided through Pin-19. It provides timing to the processor for operations. Its frequency is different for different versions, i.e. 5MHz, 8MHz and 10MHz."
},
{
"code": null,
"e": 39928,
"s": 39911,
"text": "Address/data bus"
},
{
"code": null,
"e": 40144,
"s": 39928,
"text": "AD0-AD15. These are 16 address/data bus. AD0-AD7 carries low order byte data and AD8AD15 carries higher order byte data. During the first clock cycle, it carries 16-bit address and after that it carries 16-bit data."
},
{
"code": null,
"e": 40163,
"s": 40144,
"text": "Address/status bus"
},
{
"code": null,
"e": 40308,
"s": 40163,
"text": "A16-A19/S3-S6. These are the 4 address/status buses. During the first clock cycle, it carries 4-bit address and later it carries status signals."
},
{
"code": null,
"e": 40315,
"s": 40308,
"text": "S7/BHE"
},
{
"code": null,
"e": 40512,
"s": 40315,
"text": "BHE stands for Bus High Enable. It is available at pin 34 and used to indicate the transfer of data using data bus D8-D15. This signal is low during the first clock cycle, thereafter it is active."
},
{
"code": null,
"e": 40534,
"s": 40512,
"text": "Read($\\overline{RD}$)"
},
{
"code": null,
"e": 40607,
"s": 40534,
"text": "It is available at pin 32 and is used to read signal for Read operation."
},
{
"code": null,
"e": 40613,
"s": 40607,
"text": "Ready"
},
{
"code": null,
"e": 40858,
"s": 40613,
"text": "It is available at pin 22. It is an acknowledgement signal from I/O devices that data is transferred. It is an active high signal. When it is high, it indicates that the device is ready to transfer data. When it is low, it indicates wait state."
},
{
"code": null,
"e": 40864,
"s": 40858,
"text": "RESET"
},
{
"code": null,
"e": 41084,
"s": 40864,
"text": "It is available at pin 21 and is used to restart the execution. It causes the processor to immediately terminate its present activity. This signal is active high for the first 4 clock cycles to RESET the microprocessor."
},
{
"code": null,
"e": 41089,
"s": 41084,
"text": "INTR"
},
{
"code": null,
"e": 41286,
"s": 41089,
"text": "It is available at pin 18. It is an interrupt request signal, which is sampled during the last clock cycle of each instruction to determine if the processor considered this as an interrupt or not."
},
{
"code": null,
"e": 41290,
"s": 41286,
"text": "NMI"
},
{
"code": null,
"e": 41443,
"s": 41290,
"text": "It stands for non-maskable interrupt and is available at pin 17. It is an edge triggered input, which causes an interrupt request to the microprocessor."
},
{
"code": null,
"e": 41461,
"s": 41443,
"text": "$\\overline{TEST}$"
},
{
"code": null,
"e": 41623,
"s": 41461,
"text": "This signal is like wait state and is available at pin 23. When this signal is high, then the processor has to wait for IDLE state, else the execution continues."
},
{
"code": null,
"e": 41642,
"s": 41623,
"text": "MN/$\\overline{MX}$"
},
{
"code": null,
"e": 41818,
"s": 41642,
"text": "It stands for Minimum/Maximum and is available at pin 33. It indicates what mode the processor is to operate in; when it is high, it works in the minimum mode and vice-aversa."
},
{
"code": null,
"e": 41823,
"s": 41818,
"text": "INTA"
},
{
"code": null,
"e": 41970,
"s": 41823,
"text": "It is an interrupt acknowledgement signal and id available at pin 24. When the microprocessor receives this signal, it acknowledges the interrupt."
},
{
"code": null,
"e": 41974,
"s": 41970,
"text": "ALE"
},
{
"code": null,
"e": 42198,
"s": 41974,
"text": "It stands for address enable latch and is available at pin 25. A positive pulse is generated each time the processor begins any operation. This signal indicates the availability of a valid address on the address/data lines."
},
{
"code": null,
"e": 42202,
"s": 42198,
"text": "DEN"
},
{
"code": null,
"e": 42376,
"s": 42202,
"text": "It stands for Data Enable and is available at pin 26. It is used to enable Transreceiver 8286. The transreceiver is a device used to separate data from the address/data bus."
},
{
"code": null,
"e": 42381,
"s": 42376,
"text": "DT/R"
},
{
"code": null,
"e": 42576,
"s": 42381,
"text": "It stands for Data Transmit/Receive signal and is available at pin 27. It decides the direction of data flow through the transreceiver. When it is high, data is transmitted out and vice-a-versa."
},
{
"code": null,
"e": 42581,
"s": 42576,
"text": "M/IO"
},
{
"code": null,
"e": 42773,
"s": 42581,
"text": "This signal is used to distinguish between memory and I/O operations. When it is high, it indicates I/O operation and when it is low indicates the memory operation. It is available at pin 28."
},
{
"code": null,
"e": 42776,
"s": 42773,
"text": "WR"
},
{
"code": null,
"e": 42937,
"s": 42776,
"text": "It stands for write signal and is available at pin 29. It is used to write the data into the memory or the output device depending on the status of M/IO signal."
},
{
"code": null,
"e": 42942,
"s": 42937,
"text": "HLDA"
},
{
"code": null,
"e": 43054,
"s": 42942,
"text": "It stands for Hold Acknowledgement signal and is available at pin 30. This signal acknowledges the HOLD signal."
},
{
"code": null,
"e": 43059,
"s": 43054,
"text": "HOLD"
},
{
"code": null,
"e": 43196,
"s": 43059,
"text": "This signal indicates to the processor that external devices are requesting to access the address/data buses. It is available at pin 31."
},
{
"code": null,
"e": 43208,
"s": 43196,
"text": "QS1 and QS0"
},
{
"code": null,
"e": 43382,
"s": 43208,
"text": "These are queue status signals and are available at pin 24 and 25. These signals provide the status of instruction queue. Their conditions are shown in the following table −"
},
{
"code": null,
"e": 43393,
"s": 43382,
"text": "S0, S1, S2"
},
{
"code": null,
"e": 43632,
"s": 43393,
"text": "These are the status signals that provide the status of operation, which is used by the Bus Controller 8288 to generate memory & I/O control signals. These are available at pin 26, 27, and 28. Following is the table showing their status −"
},
{
"code": null,
"e": 43637,
"s": 43632,
"text": "LOCK"
},
{
"code": null,
"e": 43831,
"s": 43637,
"text": "When this signal is active, it indicates to the other processors not to ask the CPU to leave the system bus. It is activated using the LOCK prefix on any instruction and is available at pin 29."
},
{
"code": null,
"e": 43849,
"s": 43831,
"text": "RQ/GT1 and RQ/GT0"
},
{
"code": null,
"e": 44068,
"s": 43849,
"text": "These are the Request/Grant signals used by the other processors requesting the CPU to release the system bus. When the signal is received by CPU, then it sends acknowledgment. RQ/GT0 has a higher priority than RQ/GT1."
},
{
"code": null,
"e": 44127,
"s": 44068,
"text": "The 8086 microprocessor supports 8 types of instructions −"
},
{
"code": null,
"e": 44154,
"s": 44127,
"text": "Data Transfer Instructions"
},
{
"code": null,
"e": 44178,
"s": 44154,
"text": "Arithmetic Instructions"
},
{
"code": null,
"e": 44208,
"s": 44178,
"text": "Bit Manipulation Instructions"
},
{
"code": null,
"e": 44228,
"s": 44208,
"text": "String Instructions"
},
{
"code": null,
"e": 44297,
"s": 44228,
"text": "Program Execution Transfer Instructions (Branch & Loop Instructions)"
},
{
"code": null,
"e": 44328,
"s": 44297,
"text": "Processor Control Instructions"
},
{
"code": null,
"e": 44359,
"s": 44328,
"text": "Iteration Control Instructions"
},
{
"code": null,
"e": 44382,
"s": 44359,
"text": "Interrupt Instructions"
},
{
"code": null,
"e": 44435,
"s": 44382,
"text": "Let us now discuss these instruction sets in detail."
},
{
"code": null,
"e": 44594,
"s": 44435,
"text": "These instructions are used to transfer the data from the source operand to the destination operand. Following are the list of instructions under this group −"
},
{
"code": null,
"e": 44684,
"s": 44594,
"text": "MOV − Used to copy the byte or word from the provided source to the provided destination."
},
{
"code": null,
"e": 44774,
"s": 44684,
"text": "MOV − Used to copy the byte or word from the provided source to the provided destination."
},
{
"code": null,
"e": 44826,
"s": 44774,
"text": "PPUSH − Used to put a word at the top of the stack."
},
{
"code": null,
"e": 44878,
"s": 44826,
"text": "PPUSH − Used to put a word at the top of the stack."
},
{
"code": null,
"e": 44955,
"s": 44878,
"text": "POP − Used to get a word from the top of the stack to the provided location."
},
{
"code": null,
"e": 45032,
"s": 44955,
"text": "POP − Used to get a word from the top of the stack to the provided location."
},
{
"code": null,
"e": 45086,
"s": 45032,
"text": "PUSHA − Used to put all the registers into the stack."
},
{
"code": null,
"e": 45140,
"s": 45086,
"text": "PUSHA − Used to put all the registers into the stack."
},
{
"code": null,
"e": 45198,
"s": 45140,
"text": "POPA − Used to get words from the stack to all registers."
},
{
"code": null,
"e": 45256,
"s": 45198,
"text": "POPA − Used to get words from the stack to all registers."
},
{
"code": null,
"e": 45309,
"s": 45256,
"text": "XCHG − Used to exchange the data from two locations."
},
{
"code": null,
"e": 45362,
"s": 45309,
"text": "XCHG − Used to exchange the data from two locations."
},
{
"code": null,
"e": 45429,
"s": 45362,
"text": "XLAT − Used to translate a byte in AL using a table in the memory."
},
{
"code": null,
"e": 45496,
"s": 45429,
"text": "XLAT − Used to translate a byte in AL using a table in the memory."
},
{
"code": null,
"e": 45572,
"s": 45496,
"text": "IN − Used to read a byte or word from the provided port to the accumulator."
},
{
"code": null,
"e": 45648,
"s": 45572,
"text": "IN − Used to read a byte or word from the provided port to the accumulator."
},
{
"code": null,
"e": 45729,
"s": 45648,
"text": "OUT − Used to send out a byte or word from the accumulator to the provided port."
},
{
"code": null,
"e": 45810,
"s": 45729,
"text": "OUT − Used to send out a byte or word from the accumulator to the provided port."
},
{
"code": null,
"e": 45880,
"s": 45810,
"text": "LEA − Used to load the address of operand into the provided register."
},
{
"code": null,
"e": 45950,
"s": 45880,
"text": "LEA − Used to load the address of operand into the provided register."
},
{
"code": null,
"e": 46025,
"s": 45950,
"text": "LDS − Used to load DS register and other provided register from the memory"
},
{
"code": null,
"e": 46100,
"s": 46025,
"text": "LDS − Used to load DS register and other provided register from the memory"
},
{
"code": null,
"e": 46176,
"s": 46100,
"text": "LES − Used to load ES register and other provided register from the memory."
},
{
"code": null,
"e": 46252,
"s": 46176,
"text": "LES − Used to load ES register and other provided register from the memory."
},
{
"code": null,
"e": 46315,
"s": 46252,
"text": "LAHF − Used to load AH with the low byte of the flag register."
},
{
"code": null,
"e": 46378,
"s": 46315,
"text": "LAHF − Used to load AH with the low byte of the flag register."
},
{
"code": null,
"e": 46445,
"s": 46378,
"text": "SAHF − Used to store AH register to low byte of the flag register."
},
{
"code": null,
"e": 46512,
"s": 46445,
"text": "SAHF − Used to store AH register to low byte of the flag register."
},
{
"code": null,
"e": 46576,
"s": 46512,
"text": "PUSHF − Used to copy the flag register at the top of the stack."
},
{
"code": null,
"e": 46640,
"s": 46576,
"text": "PUSHF − Used to copy the flag register at the top of the stack."
},
{
"code": null,
"e": 46713,
"s": 46640,
"text": "POPF − Used to copy a word at the top of the stack to the flag register."
},
{
"code": null,
"e": 46786,
"s": 46713,
"text": "POPF − Used to copy a word at the top of the stack to the flag register."
},
{
"code": null,
"e": 46906,
"s": 46786,
"text": "These instructions are used to perform arithmetic operations like addition, subtraction, multiplication, division, etc."
},
{
"code": null,
"e": 46963,
"s": 46906,
"text": "Following is the list of instructions under this group −"
},
{
"code": null,
"e": 47021,
"s": 46963,
"text": "ADD − Used to add the provided byte to byte/word to word."
},
{
"code": null,
"e": 47079,
"s": 47021,
"text": "ADD − Used to add the provided byte to byte/word to word."
},
{
"code": null,
"e": 47109,
"s": 47079,
"text": "ADC − Used to add with carry."
},
{
"code": null,
"e": 47139,
"s": 47109,
"text": "ADC − Used to add with carry."
},
{
"code": null,
"e": 47192,
"s": 47139,
"text": "INC − Used to increment the provided byte/word by 1."
},
{
"code": null,
"e": 47245,
"s": 47192,
"text": "INC − Used to increment the provided byte/word by 1."
},
{
"code": null,
"e": 47288,
"s": 47245,
"text": "AAA − Used to adjust ASCII after addition."
},
{
"code": null,
"e": 47331,
"s": 47288,
"text": "AAA − Used to adjust ASCII after addition."
},
{
"code": null,
"e": 47406,
"s": 47331,
"text": "DAA − Used to adjust the decimal after the addition/subtraction operation."
},
{
"code": null,
"e": 47481,
"s": 47406,
"text": "DAA − Used to adjust the decimal after the addition/subtraction operation."
},
{
"code": null,
"e": 47539,
"s": 47481,
"text": "SUB − Used to subtract the byte from byte/word from word."
},
{
"code": null,
"e": 47597,
"s": 47539,
"text": "SUB − Used to subtract the byte from byte/word from word."
},
{
"code": null,
"e": 47644,
"s": 47597,
"text": "SBB − Used to perform subtraction with borrow."
},
{
"code": null,
"e": 47691,
"s": 47644,
"text": "SBB − Used to perform subtraction with borrow."
},
{
"code": null,
"e": 47744,
"s": 47691,
"text": "DEC − Used to decrement the provided byte/word by 1."
},
{
"code": null,
"e": 47797,
"s": 47744,
"text": "DEC − Used to decrement the provided byte/word by 1."
},
{
"code": null,
"e": 47879,
"s": 47797,
"text": "NPG − Used to negate each bit of the provided byte/word and add 1/2’s complement."
},
{
"code": null,
"e": 47961,
"s": 47879,
"text": "NPG − Used to negate each bit of the provided byte/word and add 1/2’s complement."
},
{
"code": null,
"e": 48005,
"s": 47961,
"text": "CMP − Used to compare 2 provided byte/word."
},
{
"code": null,
"e": 48049,
"s": 48005,
"text": "CMP − Used to compare 2 provided byte/word."
},
{
"code": null,
"e": 48101,
"s": 48049,
"text": "AAS − Used to adjust ASCII codes after subtraction."
},
{
"code": null,
"e": 48153,
"s": 48101,
"text": "AAS − Used to adjust ASCII codes after subtraction."
},
{
"code": null,
"e": 48201,
"s": 48153,
"text": "DAS − Used to adjust decimal after subtraction."
},
{
"code": null,
"e": 48249,
"s": 48201,
"text": "DAS − Used to adjust decimal after subtraction."
},
{
"code": null,
"e": 48308,
"s": 48249,
"text": "MUL − Used to multiply unsigned byte by byte/word by word."
},
{
"code": null,
"e": 48367,
"s": 48308,
"text": "MUL − Used to multiply unsigned byte by byte/word by word."
},
{
"code": null,
"e": 48425,
"s": 48367,
"text": "IMUL − Used to multiply signed byte by byte/word by word."
},
{
"code": null,
"e": 48483,
"s": 48425,
"text": "IMUL − Used to multiply signed byte by byte/word by word."
},
{
"code": null,
"e": 48538,
"s": 48483,
"text": "AAM − Used to adjust ASCII codes after multiplication."
},
{
"code": null,
"e": 48593,
"s": 48538,
"text": "AAM − Used to adjust ASCII codes after multiplication."
},
{
"code": null,
"e": 48673,
"s": 48593,
"text": "DIV − Used to divide the unsigned word by byte or unsigned double word by word."
},
{
"code": null,
"e": 48753,
"s": 48673,
"text": "DIV − Used to divide the unsigned word by byte or unsigned double word by word."
},
{
"code": null,
"e": 48830,
"s": 48753,
"text": "IDIV − Used to divide the signed word by byte or signed double word by word."
},
{
"code": null,
"e": 48907,
"s": 48830,
"text": "IDIV − Used to divide the signed word by byte or signed double word by word."
},
{
"code": null,
"e": 48956,
"s": 48907,
"text": "AAD − Used to adjust ASCII codes after division."
},
{
"code": null,
"e": 49005,
"s": 48956,
"text": "AAD − Used to adjust ASCII codes after division."
},
{
"code": null,
"e": 49098,
"s": 49005,
"text": "CBW − Used to fill the upper byte of the word with the copies of sign bit of the lower byte."
},
{
"code": null,
"e": 49191,
"s": 49098,
"text": "CBW − Used to fill the upper byte of the word with the copies of sign bit of the lower byte."
},
{
"code": null,
"e": 49281,
"s": 49191,
"text": "CWD − Used to fill the upper word of the double word with the sign bit of the lower word."
},
{
"code": null,
"e": 49371,
"s": 49281,
"text": "CWD − Used to fill the upper word of the double word with the sign bit of the lower word."
},
{
"code": null,
"e": 49493,
"s": 49371,
"text": "These instructions are used to perform operations where data bits are involved, i.e. operations like logical, shift, etc."
},
{
"code": null,
"e": 49550,
"s": 49493,
"text": "Following is the list of instructions under this group −"
},
{
"code": null,
"e": 49599,
"s": 49550,
"text": "NOT − Used to invert each bit of a byte or word."
},
{
"code": null,
"e": 49648,
"s": 49599,
"text": "NOT − Used to invert each bit of a byte or word."
},
{
"code": null,
"e": 49743,
"s": 49648,
"text": "AND − Used for adding each bit in a byte/word with the corresponding bit in another byte/word."
},
{
"code": null,
"e": 49838,
"s": 49743,
"text": "AND − Used for adding each bit in a byte/word with the corresponding bit in another byte/word."
},
{
"code": null,
"e": 49933,
"s": 49838,
"text": "OR − Used to multiply each bit in a byte/word with the corresponding bit in another byte/word."
},
{
"code": null,
"e": 50028,
"s": 49933,
"text": "OR − Used to multiply each bit in a byte/word with the corresponding bit in another byte/word."
},
{
"code": null,
"e": 50151,
"s": 50028,
"text": "XOR − Used to perform Exclusive-OR operation over each bit in a byte/word with the corresponding bit in another byte/word."
},
{
"code": null,
"e": 50274,
"s": 50151,
"text": "XOR − Used to perform Exclusive-OR operation over each bit in a byte/word with the corresponding bit in another byte/word."
},
{
"code": null,
"e": 50347,
"s": 50274,
"text": "TEST − Used to add operands to update flags, without affecting operands."
},
{
"code": null,
"e": 50420,
"s": 50347,
"text": "TEST − Used to add operands to update flags, without affecting operands."
},
{
"code": null,
"e": 50502,
"s": 50420,
"text": "SHL/SAL − Used to shift bits of a byte/word towards left and put zero(S) in LSBs."
},
{
"code": null,
"e": 50584,
"s": 50502,
"text": "SHL/SAL − Used to shift bits of a byte/word towards left and put zero(S) in LSBs."
},
{
"code": null,
"e": 50667,
"s": 50584,
"text": "SHR − Used to shift bits of a byte/word towards the right and put zero(S) in MSBs."
},
{
"code": null,
"e": 50750,
"s": 50667,
"text": "SHR − Used to shift bits of a byte/word towards the right and put zero(S) in MSBs."
},
{
"code": null,
"e": 50847,
"s": 50750,
"text": "SAR − Used to shift bits of a byte/word towards the right and copy the old MSB into the new MSB."
},
{
"code": null,
"e": 50944,
"s": 50847,
"text": "SAR − Used to shift bits of a byte/word towards the right and copy the old MSB into the new MSB."
},
{
"code": null,
"e": 51041,
"s": 50944,
"text": "ROL − Used to rotate bits of byte/word towards the left, i.e. MSB to LSB and to Carry Flag [CF]."
},
{
"code": null,
"e": 51138,
"s": 51041,
"text": "ROL − Used to rotate bits of byte/word towards the left, i.e. MSB to LSB and to Carry Flag [CF]."
},
{
"code": null,
"e": 51236,
"s": 51138,
"text": "ROR − Used to rotate bits of byte/word towards the right, i.e. LSB to MSB and to Carry Flag [CF]."
},
{
"code": null,
"e": 51334,
"s": 51236,
"text": "ROR − Used to rotate bits of byte/word towards the right, i.e. LSB to MSB and to Carry Flag [CF]."
},
{
"code": null,
"e": 51422,
"s": 51334,
"text": "RCR − Used to rotate bits of byte/word towards the right, i.e. LSB to CF and CF to MSB."
},
{
"code": null,
"e": 51510,
"s": 51422,
"text": "RCR − Used to rotate bits of byte/word towards the right, i.e. LSB to CF and CF to MSB."
},
{
"code": null,
"e": 51597,
"s": 51510,
"text": "RCL − Used to rotate bits of byte/word towards the left, i.e. MSB to CF and CF to LSB."
},
{
"code": null,
"e": 51684,
"s": 51597,
"text": "RCL − Used to rotate bits of byte/word towards the left, i.e. MSB to CF and CF to LSB."
},
{
"code": null,
"e": 51777,
"s": 51684,
"text": "String is a group of bytes/words and their memory is always allocated in a sequential order."
},
{
"code": null,
"e": 51834,
"s": 51777,
"text": "Following is the list of instructions under this group −"
},
{
"code": null,
"e": 51891,
"s": 51834,
"text": "REP − Used to repeat the given instruction till CX ≠ 0."
},
{
"code": null,
"e": 51948,
"s": 51891,
"text": "REP − Used to repeat the given instruction till CX ≠ 0."
},
{
"code": null,
"e": 52031,
"s": 51948,
"text": "REPE/REPZ − Used to repeat the given instruction until CX = 0 or zero flag ZF = 1."
},
{
"code": null,
"e": 52114,
"s": 52031,
"text": "REPE/REPZ − Used to repeat the given instruction until CX = 0 or zero flag ZF = 1."
},
{
"code": null,
"e": 52199,
"s": 52114,
"text": "REPNE/REPNZ − Used to repeat the given instruction until CX = 0 or zero flag ZF = 1."
},
{
"code": null,
"e": 52284,
"s": 52199,
"text": "REPNE/REPNZ − Used to repeat the given instruction until CX = 0 or zero flag ZF = 1."
},
{
"code": null,
"e": 52358,
"s": 52284,
"text": "MOVS/MOVSB/MOVSW − Used to move the byte/word from one string to another."
},
{
"code": null,
"e": 52432,
"s": 52358,
"text": "MOVS/MOVSB/MOVSW − Used to move the byte/word from one string to another."
},
{
"code": null,
"e": 52493,
"s": 52432,
"text": "COMS/COMPSB/COMPSW − Used to compare two string bytes/words."
},
{
"code": null,
"e": 52554,
"s": 52493,
"text": "COMS/COMPSB/COMPSW − Used to compare two string bytes/words."
},
{
"code": null,
"e": 52655,
"s": 52554,
"text": "INS/INSB/INSW − Used as an input string/byte/word from the I/O port to the provided memory location."
},
{
"code": null,
"e": 52756,
"s": 52655,
"text": "INS/INSB/INSW − Used as an input string/byte/word from the I/O port to the provided memory location."
},
{
"code": null,
"e": 52861,
"s": 52756,
"text": "OUTS/OUTSB/OUTSW − Used as an output string/byte/word from the provided memory location to the I/O port."
},
{
"code": null,
"e": 52966,
"s": 52861,
"text": "OUTS/OUTSB/OUTSW − Used as an output string/byte/word from the provided memory location to the I/O port."
},
{
"code": null,
"e": 53080,
"s": 52966,
"text": "SCAS/SCASB/SCASW − Used to scan a string and compare its byte with a byte in AL or string word with a word in AX."
},
{
"code": null,
"e": 53194,
"s": 53080,
"text": "SCAS/SCASB/SCASW − Used to scan a string and compare its byte with a byte in AL or string word with a word in AX."
},
{
"code": null,
"e": 53275,
"s": 53194,
"text": "LODS/LODSB/LODSW − Used to store the string byte into AL or string word into AX."
},
{
"code": null,
"e": 53356,
"s": 53275,
"text": "LODS/LODSB/LODSW − Used to store the string byte into AL or string word into AX."
},
{
"code": null,
"e": 53482,
"s": 53356,
"text": "These instructions are used to transfer/branch the instructions during an execution. It includes the following instructions −"
},
{
"code": null,
"e": 53567,
"s": 53482,
"text": "Instructions to transfer the instruction during an execution without any condition −"
},
{
"code": null,
"e": 53643,
"s": 53567,
"text": "CALL − Used to call a procedure and save their return address to the stack."
},
{
"code": null,
"e": 53719,
"s": 53643,
"text": "CALL − Used to call a procedure and save their return address to the stack."
},
{
"code": null,
"e": 53780,
"s": 53719,
"text": "RET − Used to return from the procedure to the main program."
},
{
"code": null,
"e": 53841,
"s": 53780,
"text": "RET − Used to return from the procedure to the main program."
},
{
"code": null,
"e": 53920,
"s": 53841,
"text": "JMP − Used to jump to the provided address to proceed to the next instruction."
},
{
"code": null,
"e": 53999,
"s": 53920,
"text": "JMP − Used to jump to the provided address to proceed to the next instruction."
},
{
"code": null,
"e": 54083,
"s": 53999,
"text": "Instructions to transfer the instruction during an execution with some conditions −"
},
{
"code": null,
"e": 54154,
"s": 54083,
"text": "JA/JNBE − Used to jump if above/not below/equal instruction satisfies."
},
{
"code": null,
"e": 54225,
"s": 54154,
"text": "JA/JNBE − Used to jump if above/not below/equal instruction satisfies."
},
{
"code": null,
"e": 54290,
"s": 54225,
"text": "JAE/JNB − Used to jump if above/not below instruction satisfies."
},
{
"code": null,
"e": 54355,
"s": 54290,
"text": "JAE/JNB − Used to jump if above/not below instruction satisfies."
},
{
"code": null,
"e": 54427,
"s": 54355,
"text": "JBE/JNA − Used to jump if below/equal/ not above instruction satisfies."
},
{
"code": null,
"e": 54499,
"s": 54427,
"text": "JBE/JNA − Used to jump if below/equal/ not above instruction satisfies."
},
{
"code": null,
"e": 54538,
"s": 54499,
"text": "JC − Used to jump if carry flag CF = 1"
},
{
"code": null,
"e": 54577,
"s": 54538,
"text": "JC − Used to jump if carry flag CF = 1"
},
{
"code": null,
"e": 54624,
"s": 54577,
"text": "JE/JZ − Used to jump if equal/zero flag ZF = 1"
},
{
"code": null,
"e": 54671,
"s": 54624,
"text": "JE/JZ − Used to jump if equal/zero flag ZF = 1"
},
{
"code": null,
"e": 54748,
"s": 54671,
"text": "JG/JNLE − Used to jump if greater/not less than/equal instruction satisfies."
},
{
"code": null,
"e": 54825,
"s": 54748,
"text": "JG/JNLE − Used to jump if greater/not less than/equal instruction satisfies."
},
{
"code": null,
"e": 54907,
"s": 54825,
"text": "JGE/JNL − Used to jump if greater than/equal/not less than instruction satisfies."
},
{
"code": null,
"e": 54989,
"s": 54907,
"text": "JGE/JNL − Used to jump if greater than/equal/not less than instruction satisfies."
},
{
"code": null,
"e": 55071,
"s": 54989,
"text": "JL/JNGE − Used to jump if less than/not greater than/equal instruction satisfies."
},
{
"code": null,
"e": 55153,
"s": 55071,
"text": "JL/JNGE − Used to jump if less than/not greater than/equal instruction satisfies."
},
{
"code": null,
"e": 55238,
"s": 55153,
"text": "JLE/JNG − Used to jump if less than/equal/if not greater than instruction satisfies."
},
{
"code": null,
"e": 55323,
"s": 55238,
"text": "JLE/JNG − Used to jump if less than/equal/if not greater than instruction satisfies."
},
{
"code": null,
"e": 55368,
"s": 55323,
"text": "JNC − Used to jump if no carry flag (CF = 0)"
},
{
"code": null,
"e": 55413,
"s": 55368,
"text": "JNC − Used to jump if no carry flag (CF = 0)"
},
{
"code": null,
"e": 55466,
"s": 55413,
"text": "JNE/JNZ − Used to jump if not equal/zero flag ZF = 0"
},
{
"code": null,
"e": 55519,
"s": 55466,
"text": "JNE/JNZ − Used to jump if not equal/zero flag ZF = 0"
},
{
"code": null,
"e": 55565,
"s": 55519,
"text": "JNO − Used to jump if no overflow flag OF = 0"
},
{
"code": null,
"e": 55611,
"s": 55565,
"text": "JNO − Used to jump if no overflow flag OF = 0"
},
{
"code": null,
"e": 55666,
"s": 55611,
"text": "JNP/JPO − Used to jump if not parity/parity odd PF = 0"
},
{
"code": null,
"e": 55721,
"s": 55666,
"text": "JNP/JPO − Used to jump if not parity/parity odd PF = 0"
},
{
"code": null,
"e": 55759,
"s": 55721,
"text": "JNS − Used to jump if not sign SF = 0"
},
{
"code": null,
"e": 55797,
"s": 55759,
"text": "JNS − Used to jump if not sign SF = 0"
},
{
"code": null,
"e": 55839,
"s": 55797,
"text": "JO − Used to jump if overflow flag OF = 1"
},
{
"code": null,
"e": 55881,
"s": 55839,
"text": "JO − Used to jump if overflow flag OF = 1"
},
{
"code": null,
"e": 55932,
"s": 55881,
"text": "JP/JPE − Used to jump if parity/parity even PF = 1"
},
{
"code": null,
"e": 55983,
"s": 55932,
"text": "JP/JPE − Used to jump if parity/parity even PF = 1"
},
{
"code": null,
"e": 56021,
"s": 55983,
"text": "JS − Used to jump if sign flag SF = 1"
},
{
"code": null,
"e": 56059,
"s": 56021,
"text": "JS − Used to jump if sign flag SF = 1"
},
{
"code": null,
"e": 56157,
"s": 56059,
"text": "These instructions are used to control the processor action by setting/resetting the flag values."
},
{
"code": null,
"e": 56207,
"s": 56157,
"text": "Following are the instructions under this group −"
},
{
"code": null,
"e": 56244,
"s": 56207,
"text": "STC − Used to set carry flag CF to 1"
},
{
"code": null,
"e": 56281,
"s": 56244,
"text": "STC − Used to set carry flag CF to 1"
},
{
"code": null,
"e": 56326,
"s": 56281,
"text": "CLC − Used to clear/reset carry flag CF to 0"
},
{
"code": null,
"e": 56371,
"s": 56326,
"text": "CLC − Used to clear/reset carry flag CF to 0"
},
{
"code": null,
"e": 56431,
"s": 56371,
"text": "CMC − Used to put complement at the state of carry flag CF."
},
{
"code": null,
"e": 56491,
"s": 56431,
"text": "CMC − Used to put complement at the state of carry flag CF."
},
{
"code": null,
"e": 56536,
"s": 56491,
"text": "STD − Used to set the direction flag DF to 1"
},
{
"code": null,
"e": 56581,
"s": 56536,
"text": "STD − Used to set the direction flag DF to 1"
},
{
"code": null,
"e": 56634,
"s": 56581,
"text": "CLD − Used to clear/reset the direction flag DF to 0"
},
{
"code": null,
"e": 56687,
"s": 56634,
"text": "CLD − Used to clear/reset the direction flag DF to 0"
},
{
"code": null,
"e": 56762,
"s": 56687,
"text": "STI − Used to set the interrupt enable flag to 1, i.e., enable INTR input."
},
{
"code": null,
"e": 56837,
"s": 56762,
"text": "STI − Used to set the interrupt enable flag to 1, i.e., enable INTR input."
},
{
"code": null,
"e": 56915,
"s": 56837,
"text": "CLI − Used to clear the interrupt enable flag to 0, i.e., disable INTR input."
},
{
"code": null,
"e": 56993,
"s": 56915,
"text": "CLI − Used to clear the interrupt enable flag to 0, i.e., disable INTR input."
},
{
"code": null,
"e": 57133,
"s": 56993,
"text": "These instructions are used to execute the given instructions for number of times. Following is the list of instructions under this group −"
},
{
"code": null,
"e": 57221,
"s": 57133,
"text": "LOOP − Used to loop a group of instructions until the condition satisfies, i.e., CX = 0"
},
{
"code": null,
"e": 57309,
"s": 57221,
"text": "LOOP − Used to loop a group of instructions until the condition satisfies, i.e., CX = 0"
},
{
"code": null,
"e": 57394,
"s": 57309,
"text": "LOOPE/LOOPZ − Used to loop a group of instructions till it satisfies ZF = 1 & CX = 0"
},
{
"code": null,
"e": 57479,
"s": 57394,
"text": "LOOPE/LOOPZ − Used to loop a group of instructions till it satisfies ZF = 1 & CX = 0"
},
{
"code": null,
"e": 57566,
"s": 57479,
"text": "LOOPNE/LOOPNZ − Used to loop a group of instructions till it satisfies ZF = 0 & CX = 0"
},
{
"code": null,
"e": 57653,
"s": 57566,
"text": "LOOPNE/LOOPNZ − Used to loop a group of instructions till it satisfies ZF = 0 & CX = 0"
},
{
"code": null,
"e": 57707,
"s": 57653,
"text": "JCXZ − Used to jump to the provided address if CX = 0"
},
{
"code": null,
"e": 57761,
"s": 57707,
"text": "JCXZ − Used to jump to the provided address if CX = 0"
},
{
"code": null,
"e": 57837,
"s": 57761,
"text": "These instructions are used to call the interrupt during program execution."
},
{
"code": null,
"e": 57921,
"s": 57837,
"text": "INT − Used to interrupt the program during execution and calling service specified."
},
{
"code": null,
"e": 58005,
"s": 57921,
"text": "INT − Used to interrupt the program during execution and calling service specified."
},
{
"code": null,
"e": 58069,
"s": 58005,
"text": "INTO − Used to interrupt the program during execution if OF = 1"
},
{
"code": null,
"e": 58133,
"s": 58069,
"text": "INTO − Used to interrupt the program during execution if OF = 1"
},
{
"code": null,
"e": 58198,
"s": 58133,
"text": "IRET − Used to return from interrupt service to the main program"
},
{
"code": null,
"e": 58263,
"s": 58198,
"text": "IRET − Used to return from interrupt service to the main program"
},
{
"code": null,
"e": 58576,
"s": 58263,
"text": "Interrupt is the method of creating a temporary halt during program execution and allows peripheral devices to access the microprocessor. The microprocessor responds to that interrupt with an ISR (Interrupt Service Routine), which is a short program to instruct the microprocessor on how to handle the interrupt."
},
{
"code": null,
"e": 58661,
"s": 58576,
"text": "The following image shows the types of interrupts we have in a 8086 microprocessor −"
},
{
"code": null,
"e": 58782,
"s": 58661,
"text": "Hardware interrupt is caused by any peripheral device by sending a signal through a specified pin to the microprocessor."
},
{
"code": null,
"e": 59003,
"s": 58782,
"text": "The 8086 has two hardware interrupt pins, i.e. NMI and INTR. NMI is a non-maskable interrupt and INTR is a maskable interrupt having lower priority. One more interrupt pin associated is INTA called interrupt acknowledge."
},
{
"code": null,
"e": 59151,
"s": 59003,
"text": "It is a single non-maskable interrupt pin (NMI) having higher priority than the maskable interrupt request pin (INTR)and it is of type 2 interrupt."
},
{
"code": null,
"e": 59212,
"s": 59151,
"text": "When this interrupt is activated, these actions take place −"
},
{
"code": null,
"e": 59267,
"s": 59212,
"text": "Completes the current instruction that is in progress."
},
{
"code": null,
"e": 59322,
"s": 59267,
"text": "Completes the current instruction that is in progress."
},
{
"code": null,
"e": 59371,
"s": 59322,
"text": "Pushes the Flag register values on to the stack."
},
{
"code": null,
"e": 59420,
"s": 59371,
"text": "Pushes the Flag register values on to the stack."
},
{
"code": null,
"e": 59529,
"s": 59420,
"text": "Pushes the CS (code segment) value and IP (instruction pointer) value of the return address on to the stack."
},
{
"code": null,
"e": 59638,
"s": 59529,
"text": "Pushes the CS (code segment) value and IP (instruction pointer) value of the return address on to the stack."
},
{
"code": null,
"e": 59698,
"s": 59638,
"text": "IP is loaded from the contents of the word location 00008H."
},
{
"code": null,
"e": 59758,
"s": 59698,
"text": "IP is loaded from the contents of the word location 00008H."
},
{
"code": null,
"e": 59823,
"s": 59758,
"text": "CS is loaded from the contents of the next word location 0000AH."
},
{
"code": null,
"e": 59888,
"s": 59823,
"text": "CS is loaded from the contents of the next word location 0000AH."
},
{
"code": null,
"e": 59933,
"s": 59888,
"text": "Interrupt flag and trap flag are reset to 0."
},
{
"code": null,
"e": 59978,
"s": 59933,
"text": "Interrupt flag and trap flag are reset to 0."
},
{
"code": null,
"e": 60192,
"s": 59978,
"text": "The INTR is a maskable interrupt because the microprocessor will be interrupted only if interrupts are enabled using set interrupt flag instruction. It should not be enabled using clear interrupt Flag instruction."
},
{
"code": null,
"e": 60566,
"s": 60192,
"text": "The INTR interrupt is activated by an I/O port. If the interrupt is enabled and NMI is disabled, then the microprocessor first completes the current execution and sends ‘0’ on INTA pin twice. The first ‘0’ means INTA informs the external device to get ready and during the second ‘0’ the microprocessor receives the 8 bit, say X, from the programmable interrupt controller."
},
{
"code": null,
"e": 60614,
"s": 60566,
"text": "These actions are taken by the microprocessor −"
},
{
"code": null,
"e": 60655,
"s": 60614,
"text": "First completes the current instruction."
},
{
"code": null,
"e": 60696,
"s": 60655,
"text": "First completes the current instruction."
},
{
"code": null,
"e": 60758,
"s": 60696,
"text": "Activates INTA output and receives the interrupt type, say X."
},
{
"code": null,
"e": 60820,
"s": 60758,
"text": "Activates INTA output and receives the interrupt type, say X."
},
{
"code": null,
"e": 60935,
"s": 60820,
"text": "Flag register value, CS value of the return address and IP value of the return address are pushed on to the stack."
},
{
"code": null,
"e": 61050,
"s": 60935,
"text": "Flag register value, CS value of the return address and IP value of the return address are pushed on to the stack."
},
{
"code": null,
"e": 61110,
"s": 61050,
"text": "IP value is loaded from the contents of word location X × 4"
},
{
"code": null,
"e": 61170,
"s": 61110,
"text": "IP value is loaded from the contents of word location X × 4"
},
{
"code": null,
"e": 61228,
"s": 61170,
"text": "CS is loaded from the contents of the next word location."
},
{
"code": null,
"e": 61286,
"s": 61228,
"text": "CS is loaded from the contents of the next word location."
},
{
"code": null,
"e": 61329,
"s": 61286,
"text": "Interrupt flag and trap flag is reset to 0"
},
{
"code": null,
"e": 61372,
"s": 61329,
"text": "Interrupt flag and trap flag is reset to 0"
},
{
"code": null,
"e": 61572,
"s": 61372,
"text": "Some instructions are inserted at the desired position into the program to create interrupts. These interrupt instructions can be used to test the working of various interrupt handlers. It includes −"
},
{
"code": null,
"e": 61734,
"s": 61572,
"text": "It is 2-byte instruction. First byte provides the op-code and the second byte provides the interrupt type number. There are 256 interrupt types under this group."
},
{
"code": null,
"e": 61779,
"s": 61734,
"text": "Its execution includes the following steps −"
},
{
"code": null,
"e": 61826,
"s": 61779,
"text": "Flag register value is pushed on to the stack."
},
{
"code": null,
"e": 61873,
"s": 61826,
"text": "Flag register value is pushed on to the stack."
},
{
"code": null,
"e": 61967,
"s": 61873,
"text": "CS value of the return address and IP value of the return address are pushed on to the stack."
},
{
"code": null,
"e": 62061,
"s": 61967,
"text": "CS value of the return address and IP value of the return address are pushed on to the stack."
},
{
"code": null,
"e": 62131,
"s": 62061,
"text": "IP is loaded from the contents of the word location ‘type number’ × 4"
},
{
"code": null,
"e": 62201,
"s": 62131,
"text": "IP is loaded from the contents of the word location ‘type number’ × 4"
},
{
"code": null,
"e": 62259,
"s": 62201,
"text": "CS is loaded from the contents of the next word location."
},
{
"code": null,
"e": 62317,
"s": 62259,
"text": "CS is loaded from the contents of the next word location."
},
{
"code": null,
"e": 62361,
"s": 62317,
"text": "Interrupt Flag and Trap Flag are reset to 0"
},
{
"code": null,
"e": 62405,
"s": 62361,
"text": "Interrupt Flag and Trap Flag are reset to 0"
},
{
"code": null,
"e": 62600,
"s": 62405,
"text": "The starting address for type0 interrupt is 000000H, for type1 interrupt is 00004H similarly for type2 is 00008H and ......so on. The first five pointers are dedicated interrupt pointers. i.e. −"
},
{
"code": null,
"e": 62656,
"s": 62600,
"text": "TYPE 0 interrupt represents division by zero situation."
},
{
"code": null,
"e": 62712,
"s": 62656,
"text": "TYPE 0 interrupt represents division by zero situation."
},
{
"code": null,
"e": 62797,
"s": 62712,
"text": "TYPE 1 interrupt represents single-step execution during the debugging of a program."
},
{
"code": null,
"e": 62882,
"s": 62797,
"text": "TYPE 1 interrupt represents single-step execution during the debugging of a program."
},
{
"code": null,
"e": 62938,
"s": 62882,
"text": "TYPE 2 interrupt represents non-maskable NMI interrupt."
},
{
"code": null,
"e": 62994,
"s": 62938,
"text": "TYPE 2 interrupt represents non-maskable NMI interrupt."
},
{
"code": null,
"e": 63045,
"s": 62994,
"text": "TYPE 3 interrupt represents break-point interrupt."
},
{
"code": null,
"e": 63096,
"s": 63045,
"text": "TYPE 3 interrupt represents break-point interrupt."
},
{
"code": null,
"e": 63144,
"s": 63096,
"text": "TYPE 4 interrupt represents overflow interrupt."
},
{
"code": null,
"e": 63192,
"s": 63144,
"text": "TYPE 4 interrupt represents overflow interrupt."
},
{
"code": null,
"e": 63366,
"s": 63192,
"text": "The interrupts from Type 5 to Type 31 are reserved for other advanced microprocessors, and interrupts from 32 to Type 255 are available for hardware and software interrupts."
},
{
"code": null,
"e": 63592,
"s": 63366,
"text": "It is a 1-byte instruction having op-code is CCH. These instructions are inserted into the program so that when the processor reaches there, then it stops the normal execution of program and follows the break-point procedure."
},
{
"code": null,
"e": 63637,
"s": 63592,
"text": "Its execution includes the following steps −"
},
{
"code": null,
"e": 63684,
"s": 63637,
"text": "Flag register value is pushed on to the stack."
},
{
"code": null,
"e": 63731,
"s": 63684,
"text": "Flag register value is pushed on to the stack."
},
{
"code": null,
"e": 63825,
"s": 63731,
"text": "CS value of the return address and IP value of the return address are pushed on to the stack."
},
{
"code": null,
"e": 63919,
"s": 63825,
"text": "CS value of the return address and IP value of the return address are pushed on to the stack."
},
{
"code": null,
"e": 63984,
"s": 63919,
"text": "IP is loaded from the contents of the word location 3×4 = 0000CH"
},
{
"code": null,
"e": 64049,
"s": 63984,
"text": "IP is loaded from the contents of the word location 3×4 = 0000CH"
},
{
"code": null,
"e": 64107,
"s": 64049,
"text": "CS is loaded from the contents of the next word location."
},
{
"code": null,
"e": 64165,
"s": 64107,
"text": "CS is loaded from the contents of the next word location."
},
{
"code": null,
"e": 64209,
"s": 64165,
"text": "Interrupt Flag and Trap Flag are reset to 0"
},
{
"code": null,
"e": 64253,
"s": 64209,
"text": "Interrupt Flag and Trap Flag are reset to 0"
},
{
"code": null,
"e": 64625,
"s": 64253,
"text": "It is a 1-byte instruction and their mnemonic INTO. The op-code for this instruction is CEH. As the name suggests it is a conditional interrupt instruction, i.e. it is active only when the overflow flag is set to 1 and branches to the interrupt handler whose interrupt type number is 4. If the overflow flag is reset then, the execution continues to the next instruction."
},
{
"code": null,
"e": 64670,
"s": 64625,
"text": "Its execution includes the following steps −"
},
{
"code": null,
"e": 64719,
"s": 64670,
"text": "Flag register values are pushed on to the stack."
},
{
"code": null,
"e": 64768,
"s": 64719,
"text": "Flag register values are pushed on to the stack."
},
{
"code": null,
"e": 64862,
"s": 64768,
"text": "CS value of the return address and IP value of the return address are pushed on to the stack."
},
{
"code": null,
"e": 64956,
"s": 64862,
"text": "CS value of the return address and IP value of the return address are pushed on to the stack."
},
{
"code": null,
"e": 65017,
"s": 64956,
"text": "IP is loaded from the contents of word location 4×4 = 00010H"
},
{
"code": null,
"e": 65078,
"s": 65017,
"text": "IP is loaded from the contents of word location 4×4 = 00010H"
},
{
"code": null,
"e": 65136,
"s": 65078,
"text": "CS is loaded from the contents of the next word location."
},
{
"code": null,
"e": 65194,
"s": 65136,
"text": "CS is loaded from the contents of the next word location."
},
{
"code": null,
"e": 65238,
"s": 65194,
"text": "Interrupt flag and Trap flag are reset to 0"
},
{
"code": null,
"e": 65282,
"s": 65238,
"text": "Interrupt flag and Trap flag are reset to 0"
},
{
"code": null,
"e": 65447,
"s": 65282,
"text": "The different ways in which a source operand is denoted in an instruction is known as addressing modes. There are 8 different addressing modes in 8086 programming −"
},
{
"code": null,
"e": 65568,
"s": 65447,
"text": "The addressing mode in which the data operand is a part of the instruction itself is known as immediate addressing mode."
},
{
"code": null,
"e": 65615,
"s": 65568,
"text": "MOV CX, 4929 H, ADD AX, 2387 H, MOV AL, FFH \n"
},
{
"code": null,
"e": 65690,
"s": 65615,
"text": "It means that the register is the source of an operand for an instruction."
},
{
"code": null,
"e": 65813,
"s": 65690,
"text": "MOV CX, AX ; copies the contents of the 16-bit AX register into \n ; the 16-bit CX register), \nADD BX, AX \n"
},
{
"code": null,
"e": 65927,
"s": 65813,
"text": "The addressing mode in which the effective address of the memory location is written directly in the instruction."
},
{
"code": null,
"e": 65961,
"s": 65927,
"text": "MOV AX, [1592H], MOV AL, [0300H]\n"
},
{
"code": null,
"e": 66116,
"s": 65961,
"text": "This addressing mode allows data to be addressed at any memory location through an offset address held in any of the following registers: BP, BX, DI & SI."
},
{
"code": null,
"e": 66246,
"s": 66116,
"text": "MOV AX, [BX] ; Suppose the register BX contains 4895H, then the contents \n ; 4895H are moved to AX \nADD CX, {BX} \n"
},
{
"code": null,
"e": 66391,
"s": 66246,
"text": "In this addressing mode, the offset address of the operand is given by the sum of contents of the BX/BP registers and 8-bit/16-bit displacement."
},
{
"code": null,
"e": 66425,
"s": 66391,
"text": "MOV DX, [BX+04], ADD CL, [BX+08]\n"
},
{
"code": null,
"e": 66563,
"s": 66425,
"text": "In this addressing mode, the operands offset address is found by adding the contents of SI or DI register and 8-bit/16-bit displacements."
},
{
"code": null,
"e": 66598,
"s": 66563,
"text": "MOV BX, [SI+16], ADD AL, [DI+16] \n"
},
{
"code": null,
"e": 66736,
"s": 66598,
"text": "In this addressing mode, the offset address of the operand is computed by summing the base register to the contents of an Index register."
},
{
"code": null,
"e": 66771,
"s": 66736,
"text": "ADD CX, [AX+SI], MOV AX, [AX+DI] \n"
},
{
"code": null,
"e": 66924,
"s": 66771,
"text": "In this addressing mode, the operands offset is computed by adding the base register contents. An Index registers contents and 8 or 16-bit displacement."
},
{
"code": null,
"e": 66965,
"s": 66924,
"text": "MOV AX, [BX+DI+08], ADD CX, [BX+SI+16] \n"
},
{
"code": null,
"e": 67111,
"s": 66965,
"text": "Multiprocessor means a multiple set of processors that executes instructions simultaneously. There are three basic multiprocessor configurations."
},
{
"code": null,
"e": 67137,
"s": 67111,
"text": "Coprocessor configuration"
},
{
"code": null,
"e": 67167,
"s": 67137,
"text": "Closely coupled configuration"
},
{
"code": null,
"e": 67197,
"s": 67167,
"text": "Loosely coupled configuration"
},
{
"code": null,
"e": 67594,
"s": 67197,
"text": "A Coprocessor is a specially designed circuit on microprocessor chip which can perform the same task very quickly, which the microprocessor performs. It reduces the work load of the main processor. The coprocessor shares the same memory, IO system, bus, control logic and clock generator. The coprocessor handles specialized tasks like mathematical calculations, graphical display on screen, etc."
},
{
"code": null,
"e": 67886,
"s": 67594,
"text": "The 8086 and 8088 can perform most of the operations but their instruction set is not able to perform complex mathematical operations, so in these cases the microprocessor requires the math coprocessor like Intel 8087 math coprocessor, which can easily perform these operations very quickly."
},
{
"code": null,
"e": 67974,
"s": 67886,
"text": "The coprocessor and the processor is connected via TEST, RQ-/GT- and QS0 & QS1 signals."
},
{
"code": null,
"e": 68062,
"s": 67974,
"text": "The coprocessor and the processor is connected via TEST, RQ-/GT- and QS0 & QS1 signals."
},
{
"code": null,
"e": 68203,
"s": 68062,
"text": "The TEST signal is connected to BUSY pin of coprocessor and the remaining 3 pins are connected to the coprocessor’s 3 pins of the same name."
},
{
"code": null,
"e": 68344,
"s": 68203,
"text": "The TEST signal is connected to BUSY pin of coprocessor and the remaining 3 pins are connected to the coprocessor’s 3 pins of the same name."
},
{
"code": null,
"e": 68436,
"s": 68344,
"text": "TEST signal takes care of the coprocessor’s activity, i.e. the coprocessor is busy or idle."
},
{
"code": null,
"e": 68528,
"s": 68436,
"text": "TEST signal takes care of the coprocessor’s activity, i.e. the coprocessor is busy or idle."
},
{
"code": null,
"e": 68568,
"s": 68528,
"text": "The RT-/GT-is used for bus arbitration."
},
{
"code": null,
"e": 68608,
"s": 68568,
"text": "The RT-/GT-is used for bus arbitration."
},
{
"code": null,
"e": 68695,
"s": 68608,
"text": "The coprocessor uses QS0 & QS1 to track the status of the queue of the host processor."
},
{
"code": null,
"e": 68782,
"s": 68695,
"text": "The coprocessor uses QS0 & QS1 to track the status of the queue of the host processor."
},
{
"code": null,
"e": 69147,
"s": 68782,
"text": "Closely coupled configuration is similar to the coprocessor configuration, i.e. both share the same memory, I/O system bus, control logic, and control generator with the host processor. However, the coprocessor and the host processor fetches and executes their own instructions. The system bus is controlled by the coprocessor and the host processor independently."
},
{
"code": null,
"e": 69238,
"s": 69147,
"text": "Communication between the host and the independent processor is done through memory space."
},
{
"code": null,
"e": 69329,
"s": 69238,
"text": "Communication between the host and the independent processor is done through memory space."
},
{
"code": null,
"e": 69403,
"s": 69329,
"text": "None of the instructions are used for communication, like WAIT, ESC, etc."
},
{
"code": null,
"e": 69477,
"s": 69403,
"text": "None of the instructions are used for communication, like WAIT, ESC, etc."
},
{
"code": null,
"e": 69595,
"s": 69477,
"text": "The host processor manages the memory and wakes up the independent processor by sending commands to one of its ports."
},
{
"code": null,
"e": 69713,
"s": 69595,
"text": "The host processor manages the memory and wakes up the independent processor by sending commands to one of its ports."
},
{
"code": null,
"e": 69785,
"s": 69713,
"text": "Then the independent processor accesses the memory to execute the task."
},
{
"code": null,
"e": 69857,
"s": 69785,
"text": "Then the independent processor accesses the memory to execute the task."
},
{
"code": null,
"e": 69989,
"s": 69857,
"text": "After completion of the task, it sends an acknowledgement to the host processor by using the status signal or an interrupt request."
},
{
"code": null,
"e": 70121,
"s": 69989,
"text": "After completion of the task, it sends an acknowledgement to the host processor by using the status signal or an interrupt request."
},
{
"code": null,
"e": 70381,
"s": 70121,
"text": "Loosely coupled configuration consists of the number of modules of the microprocessor based systems, which are connected through a common system bus. Each module consists of their own clock generator, memory, I/O devices and are connected through a local bus."
},
{
"code": null,
"e": 70445,
"s": 70381,
"text": "Having more than one processor results in increased efficiency."
},
{
"code": null,
"e": 70509,
"s": 70445,
"text": "Having more than one processor results in increased efficiency."
},
{
"code": null,
"e": 70648,
"s": 70509,
"text": "Each of the processors have their own local bus to access the local memory/I/O devices. This makes it easy to achieve parallel processing."
},
{
"code": null,
"e": 70787,
"s": 70648,
"text": "Each of the processors have their own local bus to access the local memory/I/O devices. This makes it easy to achieve parallel processing."
},
{
"code": null,
"e": 70930,
"s": 70787,
"text": "The system structure is flexible, i.e. the failure of one module doesn’t affect the whole system failure; faulty module can be replaced later."
},
{
"code": null,
"e": 71073,
"s": 70930,
"text": "The system structure is flexible, i.e. the failure of one module doesn’t affect the whole system failure; faulty module can be replaced later."
},
{
"code": null,
"e": 71309,
"s": 71073,
"text": "8087 numeric data processor is also known as Math co-processor, Numeric processor extension and Floating point unit. It was the first math coprocessor designed by Intel to pair with 8086/8088 resulting in easier and faster calculation."
},
{
"code": null,
"e": 71442,
"s": 71309,
"text": "Once the instructions are identified by the 8086/8088 processor, then it is allotted to the 8087 co-processor for further execution."
},
{
"code": null,
"e": 71481,
"s": 71442,
"text": "The data types supported by 8087 are −"
},
{
"code": null,
"e": 71497,
"s": 71481,
"text": "Binary Integers"
},
{
"code": null,
"e": 71520,
"s": 71497,
"text": "Packed decimal numbers"
},
{
"code": null,
"e": 71533,
"s": 71520,
"text": "Real numbers"
},
{
"code": null,
"e": 71555,
"s": 71533,
"text": "Temporary real format"
},
{
"code": null,
"e": 71631,
"s": 71555,
"text": "The most prominent features of 8087 numeric data processor are as follows −"
},
{
"code": null,
"e": 71712,
"s": 71631,
"text": "It supports data of type integer, float, and real types ranging from 2-10 bytes."
},
{
"code": null,
"e": 71793,
"s": 71712,
"text": "It supports data of type integer, float, and real types ranging from 2-10 bytes."
},
{
"code": null,
"e": 71946,
"s": 71793,
"text": "The processing speed is so high that it can calculate multiplication of two 64-bits real numbers in ~27 μs and can also calculate square-root in ~35 μs."
},
{
"code": null,
"e": 72099,
"s": 71946,
"text": "The processing speed is so high that it can calculate multiplication of two 64-bits real numbers in ~27 μs and can also calculate square-root in ~35 μs."
},
{
"code": null,
"e": 72141,
"s": 72099,
"text": "It follows IEEE floating point standards."
},
{
"code": null,
"e": 72183,
"s": 72141,
"text": "It follows IEEE floating point standards."
},
{
"code": null,
"e": 72287,
"s": 72183,
"text": "8087 Architecture is divided into two groups, i.e., Control Unit (CU) and Numeric Extension Unit (NEU)."
},
{
"code": null,
"e": 72677,
"s": 72287,
"text": "The control unit handles all the communication between the processor and the memory such as it receives and decodes instructions, reads and writes memory operands, maintains parallel queue, etc. All the coprocessor instructions are ESC instructions, i.e., they start with ‘F’, the coprocessor only executes the ESC instructions while other instructions are executed by the microprocessor."
},
{
"code": null,
"e": 73067,
"s": 72677,
"text": "The control unit handles all the communication between the processor and the memory such as it receives and decodes instructions, reads and writes memory operands, maintains parallel queue, etc. All the coprocessor instructions are ESC instructions, i.e., they start with ‘F’, the coprocessor only executes the ESC instructions while other instructions are executed by the microprocessor."
},
{
"code": null,
"e": 73301,
"s": 73067,
"text": "The numeric extension unit handles all the numeric processor instructions like arithmetic, logical, transcendental, and data transfer instructions. It has 8 register stack, which holds the operands for instructions and their results."
},
{
"code": null,
"e": 73535,
"s": 73301,
"text": "The numeric extension unit handles all the numeric processor instructions like arithmetic, logical, transcendental, and data transfer instructions. It has 8 register stack, which holds the operands for instructions and their results."
},
{
"code": null,
"e": 73588,
"s": 73535,
"text": "The architecture of 8087 coprocessor is as follows −"
},
{
"code": null,
"e": 73642,
"s": 73588,
"text": "Let us first take a look at the pin diagram of 8087 −"
},
{
"code": null,
"e": 73700,
"s": 73642,
"text": "The following list provides the Pin Description of 8087 −"
},
{
"code": null,
"e": 73861,
"s": 73700,
"text": "AD0 – AD15 − These are the time multiplexed address/data lines, which carry addresses during the first clock cycle and data from the second clock cycle onwards."
},
{
"code": null,
"e": 74022,
"s": 73861,
"text": "AD0 – AD15 − These are the time multiplexed address/data lines, which carry addresses during the first clock cycle and data from the second clock cycle onwards."
},
{
"code": null,
"e": 74238,
"s": 74022,
"text": "A19 / S6 – A16/S − These lines are the time multiplexed address/status lines. It functions in a similar way to the corresponding pins of 8086. The S6, S4 and S3 are permanently high, while the S5 is permanently low."
},
{
"code": null,
"e": 74454,
"s": 74238,
"text": "A19 / S6 – A16/S − These lines are the time multiplexed address/status lines. It functions in a similar way to the corresponding pins of 8086. The S6, S4 and S3 are permanently high, while the S5 is permanently low."
},
{
"code": null,
"e": 74637,
"s": 74454,
"text": "$\\overline{BHE}$/S7 − During the first clock cycle, the $\\overline{BHE}$/S7 is used to enable data on to the higher byte of the 8086 data bus and after that works as status line S7."
},
{
"code": null,
"e": 74820,
"s": 74637,
"text": "$\\overline{BHE}$/S7 − During the first clock cycle, the $\\overline{BHE}$/S7 is used to enable data on to the higher byte of the 8086 data bus and after that works as status line S7."
},
{
"code": null,
"e": 74967,
"s": 74820,
"text": "QS1, QS0 − These are queue status input signals which provides the status of instruction queue, their conditions as shown in the following table −"
},
{
"code": null,
"e": 75114,
"s": 74967,
"text": "QS1, QS0 − These are queue status input signals which provides the status of instruction queue, their conditions as shown in the following table −"
},
{
"code": null,
"e": 75236,
"s": 75114,
"text": "INT − It is an interrupt signal, which changes to high when an unmasked exception has been received during the execution."
},
{
"code": null,
"e": 75358,
"s": 75236,
"text": "INT − It is an interrupt signal, which changes to high when an unmasked exception has been received during the execution."
},
{
"code": null,
"e": 75443,
"s": 75358,
"text": "BUSY − It is an output signal, when it is high it indicates a busy state to the CPU."
},
{
"code": null,
"e": 75528,
"s": 75443,
"text": "BUSY − It is an output signal, when it is high it indicates a busy state to the CPU."
},
{
"code": null,
"e": 75638,
"s": 75528,
"text": "READY − It is an input signal used to inform the coprocessor whether the bus is ready to receive data or not."
},
{
"code": null,
"e": 75748,
"s": 75638,
"text": "READY − It is an input signal used to inform the coprocessor whether the bus is ready to receive data or not."
},
{
"code": null,
"e": 75903,
"s": 75748,
"text": "RESET − It is an input signal used to reject the internal activities of the coprocessor and prepare it for further execution whenever required by the CPU."
},
{
"code": null,
"e": 76058,
"s": 75903,
"text": "RESET − It is an input signal used to reject the internal activities of the coprocessor and prepare it for further execution whenever required by the CPU."
},
{
"code": null,
"e": 76134,
"s": 76058,
"text": "CLK − The CLK input provides the basic timings for the processor operation."
},
{
"code": null,
"e": 76210,
"s": 76134,
"text": "CLK − The CLK input provides the basic timings for the processor operation."
},
{
"code": null,
"e": 76305,
"s": 76210,
"text": "VCC − It is a power supply signal, which requires +5V supply for the operation of the circuit."
},
{
"code": null,
"e": 76400,
"s": 76305,
"text": "VCC − It is a power supply signal, which requires +5V supply for the operation of the circuit."
},
{
"code": null,
"e": 76624,
"s": 76400,
"text": "S0, S1, S2 − These are the status signals that provide the status of the operation which is used by the Bus Controller 8087 to generate memory and I/O control signals. These signals are active during the fourth clock cycle."
},
{
"code": null,
"e": 76848,
"s": 76624,
"text": "S0, S1, S2 − These are the status signals that provide the status of the operation which is used by the Bus Controller 8087 to generate memory and I/O control signals. These signals are active during the fourth clock cycle."
},
{
"code": null,
"e": 77014,
"s": 76848,
"text": "RQ/GT1 & RQ/GT0 − These are the Request/Grant signals used by the 8087 processors to gain control of the bus from the host processor 8086/8088 for operand transfers."
},
{
"code": null,
"e": 77180,
"s": 77014,
"text": "RQ/GT1 & RQ/GT0 − These are the Request/Grant signals used by the 8087 processors to gain control of the bus from the host processor 8086/8088 for operand transfers."
},
{
"code": null,
"e": 77262,
"s": 77180,
"text": "In this chapter, we will discuss Memory Interfacing and IO Interfacing with 8085."
},
{
"code": null,
"e": 77395,
"s": 77262,
"text": "Interface is the path for communication between two components. Interfacing is of two types, memory interfacing and I/O interfacing."
},
{
"code": null,
"e": 77655,
"s": 77395,
"text": "When we are executing any instruction, we need the microprocessor to access the memory for reading instruction codes and the data stored in the memory. For this, both the memory and the microprocessor requires some signals to read from and write to registers."
},
{
"code": null,
"e": 77925,
"s": 77655,
"text": "The interfacing process includes some key factors to match with the memory requirements and microprocessor signals. The interfacing circuit therefore should be designed in such a way that it matches the memory signal requirements with the signals of the microprocessor."
},
{
"code": null,
"e": 78169,
"s": 77925,
"text": "There are various communication devices like the keyboard, mouse, printer, etc. So, we need to interface the keyboard and other devices with the microprocessor by using latches and buffers. This type of interfacing is known as I/O interfacing."
},
{
"code": null,
"e": 78246,
"s": 78169,
"text": "Following is the list of 8085 pins used for interfacing with other devices −"
},
{
"code": null,
"e": 78276,
"s": 78246,
"text": "A15 - A8 (Higher Address Bus)"
},
{
"code": null,
"e": 78310,
"s": 78276,
"text": "AD7 - AD0(Lower Address/Data Bus)"
},
{
"code": null,
"e": 78314,
"s": 78310,
"text": "ALE"
},
{
"code": null,
"e": 78317,
"s": 78314,
"text": "RD"
},
{
"code": null,
"e": 78320,
"s": 78317,
"text": "WR"
},
{
"code": null,
"e": 78326,
"s": 78320,
"text": "READY"
},
{
"code": null,
"e": 78426,
"s": 78326,
"text": "There are two ways of communication in which the microprocessor can connect with the outside world."
},
{
"code": null,
"e": 78457,
"s": 78426,
"text": "Serial Communication Interface"
},
{
"code": null,
"e": 78490,
"s": 78457,
"text": "Parallel Communication interface"
},
{
"code": null,
"e": 78690,
"s": 78490,
"text": "Serial Communication Interface − In this type of communication, the interface gets a single byte of data from the microprocessor and sends it bit by bit to the other system serially and vice-a-versa."
},
{
"code": null,
"e": 78915,
"s": 78690,
"text": "Parallel Communication Interface − In this type of communication, the interface gets a byte of data from the microprocessor and sends it bit by bit to the other systems in simultaneous (or) parallel fashion and vice-a-versa."
},
{
"code": null,
"e": 79191,
"s": 78915,
"text": "8279 programmable keyboard/display controller is designed by Intel that interfaces a keyboard with the CPU. The keyboard first scans the keyboard and identifies if any key has been pressed. It then sends their relative response of the pressed key to the CPU and vice-a-versa."
},
{
"code": null,
"e": 79404,
"s": 79191,
"text": "The Keyboard can be interfaced either in the interrupt or the polled mode. In the Interrupt mode, the processor is requested service only if any key is pressed, otherwise the CPU will continue with its main task."
},
{
"code": null,
"e": 79538,
"s": 79404,
"text": "In the Polled mode, the CPU periodically reads an internal flag of 8279 to check whether any key is pressed or not with key pressure."
},
{
"code": null,
"e": 79885,
"s": 79538,
"text": "The keyboard consists of maximum 64 keys, which are interfaced with the CPU by using the key-codes. These key-codes are de-bounced and stored in an 8-byte FIFORAM, which can be accessed by the CPU. If more than 8 characters are entered in the FIFO, then it means more than eight keys are pressed at a time. This is when the overrun status is set."
},
{
"code": null,
"e": 80166,
"s": 79885,
"text": "If a FIFO contains a valid key entry, then the CPU is interrupted in an interrupt mode else the CPU checks the status in polling to read the entry. Once the CPU reads a key entry, then FIFO is updated, and the key entry is pushed out of the FIFO to generate space for new entries."
},
{
"code": null,
"e": 80451,
"s": 80166,
"text": "This unit controls the flow of data through the microprocessor. It is enabled only when D is low. Its data buffer interfaces the external bus of the system with the internal bus of the microprocessor. The pins A0, RD, and WR are used for command, status or data read/write operations."
},
{
"code": null,
"e": 80647,
"s": 80451,
"text": "This unit contains registers to store the keyboard, display modes, and other operations as programmed by the CPU. The timing and control unit handles the timings for the operation of the circuit."
},
{
"code": null,
"e": 80848,
"s": 80647,
"text": "It has two modes i.e. Encoded mode and Decoded mode. In the encoded mode, the counter provides the binary count that is to be externally decoded to provide the scan lines for the keyboard and display."
},
{
"code": null,
"e": 80985,
"s": 80848,
"text": "In the decoded scan mode, the counter internally decodes the least significant 2 bits and provides a decoded 1 out of 4 scan on SL0-SL3."
},
{
"code": null,
"e": 81241,
"s": 80985,
"text": "This unit first scans the key closure row-wise, if found then the keyboard debounce unit debounces the key entry. In case, the same key is detected, then the code of that key is directly transferred to the sensor RAM along with SHIFT & CONTROL key status."
},
{
"code": null,
"e": 81488,
"s": 81241,
"text": "This unit acts as 8-byte first-in-first-out (FIFO) RAM where the key code of every pressed key is entered into the RAM as per their sequence. The status logic generates an interrupt request after each FIFO read operation till the FIFO gets empty."
},
{
"code": null,
"e": 81740,
"s": 81488,
"text": "In the scanned sensor matrix mode, this unit acts as sensor RAM where its each row is loaded with the status of their corresponding row of sensors into the matrix. When the sensor changes its state, the IRQ line changes to high and interrupts the CPU."
},
{
"code": null,
"e": 81885,
"s": 81740,
"text": "This unit consists of display address registers which holds the addresses of the word currently read/written by the CPU to/from the display RAM."
},
{
"code": null,
"e": 81938,
"s": 81885,
"text": "The following figure shows the pin diagram of 8279 −"
},
{
"code": null,
"e": 82022,
"s": 81938,
"text": "These are 8 bidirectional data bus lines used to transfer the data to/from the CPU."
},
{
"code": null,
"e": 82107,
"s": 82022,
"text": "The clock input is used to generate internal timings required by the microprocessor."
},
{
"code": null,
"e": 82174,
"s": 82107,
"text": "As the name suggests this pin is used to reset the microprocessor."
},
{
"code": null,
"e": 82273,
"s": 82174,
"text": "When this pin is set to low, it allows read/write operations, else this pin should be set to high."
},
{
"code": null,
"e": 82387,
"s": 82273,
"text": "This pin indicates the transfer of command/status information. When it is low, it indicates the transfer of data."
},
{
"code": null,
"e": 82471,
"s": 82387,
"text": "This Read/Write pin enables the data buffer to send/receive data over the data bus."
},
{
"code": null,
"e": 82760,
"s": 82471,
"text": "This interrupt output line goes high when there is data in the FIFO sensor RAM. The interrupt line goes low with each FIFO RAM read operation. However, if the FIFO RAM further contains any key-code entry to be read by the CPU, this pin again goes high to generate an interrupt to the CPU."
},
{
"code": null,
"e": 82827,
"s": 82760,
"text": "These are the ground and power supply lines of the microprocessor."
},
{
"code": null,
"e": 82995,
"s": 82827,
"text": "These are the scan lines used to scan the keyboard matrix and display the digits. These lines can be programmed as encoded or decoded, using the mode control register."
},
{
"code": null,
"e": 83194,
"s": 82995,
"text": "These are the Return Lines which are connected to one terminal of keys, while the other terminal of the keys is connected to the decoded scan lines. These lines are set to 0 when any key is pressed."
},
{
"code": null,
"e": 83381,
"s": 83194,
"text": "The Shift input line status is stored along with every key code in FIFO in the scanned keyboard mode. Till it is pulled low with a key closure, it is pulled up internally to keep it high"
},
{
"code": null,
"e": 83638,
"s": 83381,
"text": "In the keyboard mode, this line is used as a control input and stored in FIFO on a key closure. The line is a strobe line that enters the data into FIFO RAM, in the strobed input mode. It has an internal pull up. The line is pulled down with a key closure."
},
{
"code": null,
"e": 83723,
"s": 83638,
"text": "It stands for blank display. It is used to blank the display during digit switching."
},
{
"code": null,
"e": 83911,
"s": 83723,
"text": "These are the output ports for two 16x4 or one 16x8 internal display refresh registers. The data from these lines is synchronized with the scan lines to scan the display and the keyboard."
},
{
"code": null,
"e": 83982,
"s": 83911,
"text": "There are two modes of operation on 8279 − Input Mode and Output Mode."
},
{
"code": null,
"e": 84085,
"s": 83982,
"text": "This mode deals with the input given by the keyboard and this mode is further classified into 3 modes."
},
{
"code": null,
"e": 84373,
"s": 84085,
"text": "Scanned Keyboard Mode − In this mode, the key matrix can be interfaced using either encoded or decoded scans. In the encoded scan, an 8×8 keyboard or in the decoded scan, a 4×8 keyboard can be interfaced. The code of key pressed with SHIFT and CONTROL status is stored into the FIFO RAM."
},
{
"code": null,
"e": 84661,
"s": 84373,
"text": "Scanned Keyboard Mode − In this mode, the key matrix can be interfaced using either encoded or decoded scans. In the encoded scan, an 8×8 keyboard or in the decoded scan, a 4×8 keyboard can be interfaced. The code of key pressed with SHIFT and CONTROL status is stored into the FIFO RAM."
},
{
"code": null,
"e": 84887,
"s": 84661,
"text": "Scanned Sensor Matrix − In this mode, a sensor array can be interfaced with the processor using either encoder or decoder scans. In the encoder scan, 8×8 sensor matrix or with decoder scan 4×8 sensor matrix can be interfaced."
},
{
"code": null,
"e": 85113,
"s": 84887,
"text": "Scanned Sensor Matrix − In this mode, a sensor array can be interfaced with the processor using either encoder or decoder scans. In the encoder scan, 8×8 sensor matrix or with decoder scan 4×8 sensor matrix can be interfaced."
},
{
"code": null,
"e": 85243,
"s": 85113,
"text": "Strobed Input − In this mode, when the control line is set to 0, the data on the return lines is stored in the FIFO byte by byte."
},
{
"code": null,
"e": 85373,
"s": 85243,
"text": "Strobed Input − In this mode, when the control line is set to 0, the data on the return lines is stored in the FIFO byte by byte."
},
{
"code": null,
"e": 85477,
"s": 85373,
"text": "This mode deals with display-related operations. This mode is further classified into two output modes."
},
{
"code": null,
"e": 85603,
"s": 85477,
"text": "Display Scan − This mode allows 8/16 character multiplexed displays to be organized as dual 4-bit/single 8-bit display units."
},
{
"code": null,
"e": 85729,
"s": 85603,
"text": "Display Scan − This mode allows 8/16 character multiplexed displays to be organized as dual 4-bit/single 8-bit display units."
},
{
"code": null,
"e": 85835,
"s": 85729,
"text": "Display Entry − This mode allows the data to be entered for display either from the right side/left side."
},
{
"code": null,
"e": 85941,
"s": 85835,
"text": "Display Entry − This mode allows the data to be entered for display either from the right side/left side."
},
{
"code": null,
"e": 86143,
"s": 85941,
"text": "DMA stands for Direct Memory Access. It is designed by Intel to transfer data at the fastest rate. It allows the device to transfer the data directly to/from memory without any interference of the CPU."
},
{
"code": null,
"e": 86388,
"s": 86143,
"text": "Using a DMA controller, the device requests the CPU to hold its data, address and control bus, so the device is free to transfer data directly to/from the memory. The DMA data transfer is initiated only after receiving HLDA signal from the CPU."
},
{
"code": null,
"e": 86449,
"s": 86388,
"text": "Following is the sequence of operations performed by a DMA −"
},
{
"code": null,
"e": 86588,
"s": 86449,
"text": "Initially, when any device has to send data between the device and the memory, the device has to send DMA request (DRQ) to DMA controller."
},
{
"code": null,
"e": 86727,
"s": 86588,
"text": "Initially, when any device has to send data between the device and the memory, the device has to send DMA request (DRQ) to DMA controller."
},
{
"code": null,
"e": 86824,
"s": 86727,
"text": "The DMA controller sends Hold request (HRQ) to the CPU and waits for the CPU to assert the HLDA."
},
{
"code": null,
"e": 86921,
"s": 86824,
"text": "The DMA controller sends Hold request (HRQ) to the CPU and waits for the CPU to assert the HLDA."
},
{
"code": null,
"e": 87095,
"s": 86921,
"text": "Then the microprocessor tri-states all the data bus, address bus, and control bus. The CPU leaves the control over bus and acknowledges the HOLD request through HLDA signal."
},
{
"code": null,
"e": 87269,
"s": 87095,
"text": "Then the microprocessor tri-states all the data bus, address bus, and control bus. The CPU leaves the control over bus and acknowledges the HOLD request through HLDA signal."
},
{
"code": null,
"e": 87403,
"s": 87269,
"text": "Now the CPU is in HOLD state and the DMA controller has to manage the operations over buses between the CPU, memory, and I/O devices."
},
{
"code": null,
"e": 87537,
"s": 87403,
"text": "Now the CPU is in HOLD state and the DMA controller has to manage the operations over buses between the CPU, memory, and I/O devices."
},
{
"code": null,
"e": 87596,
"s": 87537,
"text": "Here is a list of some of the prominent features of 8257 −"
},
{
"code": null,
"e": 87658,
"s": 87596,
"text": "It has four channels which can be used over four I/O devices."
},
{
"code": null,
"e": 87720,
"s": 87658,
"text": "It has four channels which can be used over four I/O devices."
},
{
"code": null,
"e": 87772,
"s": 87720,
"text": "Each channel has 16-bit address and 14-bit counter."
},
{
"code": null,
"e": 87824,
"s": 87772,
"text": "Each channel has 16-bit address and 14-bit counter."
},
{
"code": null,
"e": 87867,
"s": 87824,
"text": "Each channel can transfer data up to 64kb."
},
{
"code": null,
"e": 87910,
"s": 87867,
"text": "Each channel can transfer data up to 64kb."
},
{
"code": null,
"e": 87956,
"s": 87910,
"text": "Each channel can be programmed independently."
},
{
"code": null,
"e": 88002,
"s": 87956,
"text": "Each channel can be programmed independently."
},
{
"code": null,
"e": 88089,
"s": 88002,
"text": "Each channel can perform read transfer, write transfer and verify transfer operations."
},
{
"code": null,
"e": 88176,
"s": 88089,
"text": "Each channel can perform read transfer, write transfer and verify transfer operations."
},
{
"code": null,
"e": 88264,
"s": 88176,
"text": "It generates MARK signal to the peripheral device that 128 bytes have been transferred."
},
{
"code": null,
"e": 88352,
"s": 88264,
"text": "It generates MARK signal to the peripheral device that 128 bytes have been transferred."
},
{
"code": null,
"e": 88386,
"s": 88352,
"text": "It requires a single phase clock."
},
{
"code": null,
"e": 88420,
"s": 88386,
"text": "It requires a single phase clock."
},
{
"code": null,
"e": 88461,
"s": 88420,
"text": "Its frequency ranges from 250Hz to 3MHz."
},
{
"code": null,
"e": 88502,
"s": 88461,
"text": "Its frequency ranges from 250Hz to 3MHz."
},
{
"code": null,
"e": 88560,
"s": 88502,
"text": "It operates in 2 modes, i.e., Master mode and Slave mode."
},
{
"code": null,
"e": 88618,
"s": 88560,
"text": "It operates in 2 modes, i.e., Master mode and Slave mode."
},
{
"code": null,
"e": 88671,
"s": 88618,
"text": "The following image shows the architecture of 8257 −"
},
{
"code": null,
"e": 88740,
"s": 88671,
"text": "The following image shows the pin diagram of a 8257 DMA controller −"
},
{
"code": null,
"e": 88985,
"s": 88740,
"text": "These are the four individual channel DMA request inputs, which are used by the peripheral devices for using DMA services. When the fixed priority mode is selected, then DRQ0 has the highest priority and DRQ3 has the lowest priority among them."
},
{
"code": null,
"e": 89188,
"s": 88985,
"text": "These are the active-low DMA acknowledge lines, which updates the requesting peripheral about the status of their request by the CPU. These lines can also act as strobe lines for the requesting devices."
},
{
"code": null,
"e": 89544,
"s": 89188,
"text": "These are bidirectional, data lines which are used to interface the system bus with the internal data bus of DMA controller. In the Slave mode, it carries command words to 8257 and status word from 8257. In the master mode, these lines are used to send higher byte of the generated address to the latch. This address is further latched using ADSTB signal."
},
{
"code": null,
"e": 89780,
"s": 89544,
"text": "It is an active-low bidirectional tri-state input line, which is used by the CPU to read internal registers of 8257 in the Slave mode. In the master mode, it is used to read data from the peripheral devices during a memory write cycle."
},
{
"code": null,
"e": 90092,
"s": 89780,
"text": "It is an active low bi-direction tri-state line, which is used to load the contents of the data bus to the 8-bit mode register or upper/lower byte of a 16-bit DMA address register or terminal count register. In the master mode, it is used to load the data to the peripheral devices during DMA memory read cycle."
},
{
"code": null,
"e": 90177,
"s": 90092,
"text": "It is a clock frequency signal which is required for the internal operation of 8257."
},
{
"code": null,
"e": 90260,
"s": 90177,
"text": "This signal is used to RESET the DMA controller by disabling all the DMA channels."
},
{
"code": null,
"e": 90514,
"s": 90260,
"text": "These are the four least significant address lines. In the slave mode, they act as an input, which selects one of the registers to be read or written. In the master mode, they are the four least significant memory address output lines generated by 8257."
},
{
"code": null,
"e": 90694,
"s": 90514,
"text": "It is an active-low chip select line. In the Slave mode, it enables the read/write operations to/from 8257. In the master mode, it disables the read/write operations to/from 8257."
},
{
"code": null,
"e": 90785,
"s": 90694,
"text": "These are the higher nibble of the lower byte address generated by DMA in the master mode."
},
{
"code": null,
"e": 90881,
"s": 90785,
"text": "It is an active-high asynchronous input signal, which makes DMA ready by inserting wait states."
},
{
"code": null,
"e": 91083,
"s": 90881,
"text": "This signal is used to receive the hold request signal from the output device. In the slave mode, it is connected with a DRQ input line 8257. In Master mode, it is connected with HOLD input of the CPU."
},
{
"code": null,
"e": 91247,
"s": 91083,
"text": "It is the hold acknowledgement signal which indicates the DMA controller that the bus has been granted to the requesting peripheral by the CPU when it is set to 1."
},
{
"code": null,
"e": 91372,
"s": 91247,
"text": "It is the low memory read signal, which is used to read the data from the addressed memory locations during DMA read cycles."
},
{
"code": null,
"e": 91505,
"s": 91372,
"text": "It is the active-low three state signal which is used to write the data to the addressed memory location during DMA write operation."
},
{
"code": null,
"e": 91624,
"s": 91505,
"text": "This signal is used to convert the higher byte of the memory address generated by the DMA controller into the latches."
},
{
"code": null,
"e": 91681,
"s": 91624,
"text": "This signal is used to disable the address bus/data bus."
},
{
"code": null,
"e": 91786,
"s": 91681,
"text": "It stands for ‘Terminal Count’, which indicates the present DMA cycle to the present peripheral devices."
},
{
"code": null,
"e": 92003,
"s": 91786,
"text": "The mark will be activated after each 128 cycles or integral multiples of it from the beginning. It indicates the current DMA cycle is the 128th cycle since the previous MARK output to the selected peripheral device."
},
{
"code": null,
"e": 92078,
"s": 92003,
"text": "It is the power signal which is required for the operation of the circuit."
},
{
"code": null,
"e": 92275,
"s": 92078,
"text": "A microcontroller is a small and low-cost microcomputer, which is designed to perform the specific tasks of embedded systems like displaying microwave’s information, receiving remote signals, etc."
},
{
"code": null,
"e": 92411,
"s": 92275,
"text": "The general microcontroller consists of the processor, the memory (RAM, ROM, EPROM), Serial ports, peripherals (timers, counters), etc."
},
{
"code": null,
"e": 92507,
"s": 92411,
"text": "The following table highlights the differences between a microprocessor and a microcontroller −"
},
{
"code": null,
"e": 92657,
"s": 92507,
"text": "Microcontrollers are divided into various categories based on memory, architecture, bits and instruction sets. Following is the list of their types −"
},
{
"code": null,
"e": 92747,
"s": 92657,
"text": "Based on bit configuration, the microcontroller is further divided into three categories."
},
{
"code": null,
"e": 92972,
"s": 92747,
"text": "8-bit microcontroller − This type of microcontroller is used to execute arithmetic and logical operations like addition, subtraction, multiplication division, etc. For example, Intel 8031 and 8051 are 8 bits microcontroller."
},
{
"code": null,
"e": 93197,
"s": 92972,
"text": "8-bit microcontroller − This type of microcontroller is used to execute arithmetic and logical operations like addition, subtraction, multiplication division, etc. For example, Intel 8031 and 8051 are 8 bits microcontroller."
},
{
"code": null,
"e": 93408,
"s": 93197,
"text": "16-bit microcontroller − This type of microcontroller is used to perform arithmetic and logical operations where higher accuracy and performance is required. For example, Intel 8096 is a 16-bit microcontroller."
},
{
"code": null,
"e": 93619,
"s": 93408,
"text": "16-bit microcontroller − This type of microcontroller is used to perform arithmetic and logical operations where higher accuracy and performance is required. For example, Intel 8096 is a 16-bit microcontroller."
},
{
"code": null,
"e": 93792,
"s": 93619,
"text": "32-bit microcontroller − This type of microcontroller is generally used in automatically controlled appliances like automatic operational machines, medical appliances, etc."
},
{
"code": null,
"e": 93965,
"s": 93792,
"text": "32-bit microcontroller − This type of microcontroller is generally used in automatically controlled appliances like automatic operational machines, medical appliances, etc."
},
{
"code": null,
"e": 94060,
"s": 93965,
"text": "Based on the memory configuration, the microcontroller is further divided into two categories."
},
{
"code": null,
"e": 94297,
"s": 94060,
"text": "External memory microcontroller − This type of microcontroller is designed in such a way that they do not have a program memory on the chip. Hence, it is named as external memory microcontroller. For example: Intel 8031 microcontroller."
},
{
"code": null,
"e": 94534,
"s": 94297,
"text": "External memory microcontroller − This type of microcontroller is designed in such a way that they do not have a program memory on the chip. Hence, it is named as external memory microcontroller. For example: Intel 8031 microcontroller."
},
{
"code": null,
"e": 94792,
"s": 94534,
"text": "Embedded memory microcontroller − This type of microcontroller is designed in such a way that the microcontroller has all programs and data memory, counters and timers, interrupts, I/O ports are embedded on the chip. For example: Intel 8051 microcontroller."
},
{
"code": null,
"e": 95050,
"s": 94792,
"text": "Embedded memory microcontroller − This type of microcontroller is designed in such a way that the microcontroller has all programs and data memory, counters and timers, interrupts, I/O ports are embedded on the chip. For example: Intel 8051 microcontroller."
},
{
"code": null,
"e": 95154,
"s": 95050,
"text": "Based on the instruction set configuration, the microcontroller is further divided into two categories."
},
{
"code": null,
"e": 95308,
"s": 95154,
"text": "CISC − CISC stands for complex instruction set computer. It allows the user to insert a single instruction as an alternative to many simple instructions."
},
{
"code": null,
"e": 95462,
"s": 95308,
"text": "CISC − CISC stands for complex instruction set computer. It allows the user to insert a single instruction as an alternative to many simple instructions."
},
{
"code": null,
"e": 95599,
"s": 95462,
"text": "RISC − RISC stands for Reduced Instruction Set Computers. It reduces the operational time by shortening the clock cycle per instruction."
},
{
"code": null,
"e": 95736,
"s": 95599,
"text": "RISC − RISC stands for Reduced Instruction Set Computers. It reduces the operational time by shortening the clock cycle per instruction."
},
{
"code": null,
"e": 95808,
"s": 95736,
"text": "Microcontrollers are widely used in various different devices such as −"
},
{
"code": null,
"e": 95856,
"s": 95808,
"text": "Light sensing and controlling devices like LED."
},
{
"code": null,
"e": 95904,
"s": 95856,
"text": "Light sensing and controlling devices like LED."
},
{
"code": null,
"e": 95979,
"s": 95904,
"text": "Temperature sensing and controlling devices like microwave oven, chimneys."
},
{
"code": null,
"e": 96054,
"s": 95979,
"text": "Temperature sensing and controlling devices like microwave oven, chimneys."
},
{
"code": null,
"e": 96105,
"s": 96054,
"text": "Fire detection and safety devices like Fire alarm."
},
{
"code": null,
"e": 96156,
"s": 96105,
"text": "Fire detection and safety devices like Fire alarm."
},
{
"code": null,
"e": 96191,
"s": 96156,
"text": "Measuring devices like Volt Meter."
},
{
"code": null,
"e": 96226,
"s": 96191,
"text": "Measuring devices like Volt Meter."
},
{
"code": null,
"e": 96646,
"s": 96226,
"text": "8051 microcontroller is designed by Intel in 1981. It is an 8-bit microcontroller. It is built with 40 pins DIP (dual inline package), 4kb of ROM storage and 128 bytes of RAM storage, 2 16-bit timers. It consists of are four parallel 8-bit ports, which are programmable as well as addressable as per the requirement. An on-chip crystal oscillator is integrated in the microcontroller having crystal frequency of 12 MHz."
},
{
"code": null,
"e": 96707,
"s": 96646,
"text": "Let us now discuss the architecture of 8051 Microcontroller."
},
{
"code": null,
"e": 97053,
"s": 96707,
"text": "In the following diagram, the system bus connects all the support devices to the CPU. The system bus consists of an 8-bit data bus, a 16-bit address bus and bus control signals. All other devices like program memory, ports, data memory, serial interface, interrupt control, timers, and the CPU are all interfaced together through the system bus."
},
{
"code": null,
"e": 97112,
"s": 97053,
"text": "The pin diagram of 8051 microcontroller looks as follows −"
},
{
"code": null,
"e": 97256,
"s": 97112,
"text": "Pins 1 to 8 − These pins are known as Port 1. This port doesn’t serve any other functions. It is internally pulled up, bi-directional I/O port."
},
{
"code": null,
"e": 97400,
"s": 97256,
"text": "Pins 1 to 8 − These pins are known as Port 1. This port doesn’t serve any other functions. It is internally pulled up, bi-directional I/O port."
},
{
"code": null,
"e": 97493,
"s": 97400,
"text": "Pin 9 − It is a RESET pin, which is used to reset the microcontroller to its initial values."
},
{
"code": null,
"e": 97586,
"s": 97493,
"text": "Pin 9 − It is a RESET pin, which is used to reset the microcontroller to its initial values."
},
{
"code": null,
"e": 97760,
"s": 97586,
"text": "Pins 10 to 17 − These pins are known as Port 3. This port serves some functions like interrupts, timer input, control signals, serial communication signals RxD and TxD, etc."
},
{
"code": null,
"e": 97934,
"s": 97760,
"text": "Pins 10 to 17 − These pins are known as Port 3. This port serves some functions like interrupts, timer input, control signals, serial communication signals RxD and TxD, etc."
},
{
"code": null,
"e": 98030,
"s": 97934,
"text": "Pins 18 & 19 − These pins are used for interfacing an external crystal to get the system clock."
},
{
"code": null,
"e": 98126,
"s": 98030,
"text": "Pins 18 & 19 − These pins are used for interfacing an external crystal to get the system clock."
},
{
"code": null,
"e": 98186,
"s": 98126,
"text": "Pin 20 − This pin provides the power supply to the circuit."
},
{
"code": null,
"e": 98246,
"s": 98186,
"text": "Pin 20 − This pin provides the power supply to the circuit."
},
{
"code": null,
"e": 98389,
"s": 98246,
"text": "Pins 21 to 28 − These pins are known as Port 2. It serves as I/O port. Higher order address bus signals are also multiplexed using this port."
},
{
"code": null,
"e": 98532,
"s": 98389,
"text": "Pins 21 to 28 − These pins are known as Port 2. It serves as I/O port. Higher order address bus signals are also multiplexed using this port."
},
{
"code": null,
"e": 98659,
"s": 98532,
"text": "Pin 29 − This is PSEN pin which stands for Program Store Enable. It is used to read a signal from the external program memory."
},
{
"code": null,
"e": 98786,
"s": 98659,
"text": "Pin 29 − This is PSEN pin which stands for Program Store Enable. It is used to read a signal from the external program memory."
},
{
"code": null,
"e": 98912,
"s": 98786,
"text": "Pin 30 − This is EA pin which stands for External Access input. It is used to enable/disable the external memory interfacing."
},
{
"code": null,
"e": 99038,
"s": 98912,
"text": "Pin 30 − This is EA pin which stands for External Access input. It is used to enable/disable the external memory interfacing."
},
{
"code": null,
"e": 99161,
"s": 99038,
"text": "Pin 31 − This is ALE pin which stands for Address Latch Enable. It is used to demultiplex the address-data signal of port."
},
{
"code": null,
"e": 99284,
"s": 99161,
"text": "Pin 31 − This is ALE pin which stands for Address Latch Enable. It is used to demultiplex the address-data signal of port."
},
{
"code": null,
"e": 99429,
"s": 99284,
"text": "Pins 32 to 39 − These pins are known as Port 0. It serves as I/O port. Lower order address and data bus signals are multiplexed using this port."
},
{
"code": null,
"e": 99574,
"s": 99429,
"text": "Pins 32 to 39 − These pins are known as Port 0. It serves as I/O port. Lower order address and data bus signals are multiplexed using this port."
},
{
"code": null,
"e": 99640,
"s": 99574,
"text": "Pin 40 − This pin is used to provide power supply to the circuit."
},
{
"code": null,
"e": 99706,
"s": 99640,
"text": "Pin 40 − This pin is used to provide power supply to the circuit."
},
{
"code": null,
"e": 99909,
"s": 99706,
"text": "8051 microcontrollers have 4 I/O ports each of 8-bit, which can be configured as input or output. Hence, total 32 input/output pins allow the microcontroller to be connected with the peripheral devices."
},
{
"code": null,
"e": 100398,
"s": 99909,
"text": "Pin configuration, i.e. the pin can be configured as 1 for input and 0 for output as per the logic state.\n\nInput/Output (I/O) pin − All the circuits within the microcontroller must be connected to one of its pins except P0 port because it does not have pull-up resistors built-in.\nInput pin − Logic 1 is applied to a bit of the P register. The output FE transistor is turned off and the other pin remains connected to the power supply voltage over a pull-up resistor of high resistance.\n\n"
},
{
"code": null,
"e": 100504,
"s": 100398,
"text": "Pin configuration, i.e. the pin can be configured as 1 for input and 0 for output as per the logic state."
},
{
"code": null,
"e": 100678,
"s": 100504,
"text": "Input/Output (I/O) pin − All the circuits within the microcontroller must be connected to one of its pins except P0 port because it does not have pull-up resistors built-in."
},
{
"code": null,
"e": 100852,
"s": 100678,
"text": "Input/Output (I/O) pin − All the circuits within the microcontroller must be connected to one of its pins except P0 port because it does not have pull-up resistors built-in."
},
{
"code": null,
"e": 101058,
"s": 100852,
"text": "Input pin − Logic 1 is applied to a bit of the P register. The output FE transistor is turned off and the other pin remains connected to the power supply voltage over a pull-up resistor of high resistance."
},
{
"code": null,
"e": 101264,
"s": 101058,
"text": "Input pin − Logic 1 is applied to a bit of the P register. The output FE transistor is turned off and the other pin remains connected to the power supply voltage over a pull-up resistor of high resistance."
},
{
"code": null,
"e": 101685,
"s": 101264,
"text": "Port 0 − The P0 (zero) port is characterized by two functions −\n\nWhen the external memory is used then the lower address byte (addresses A0A7) is applied on it, else all bits of this port are configured as input/output.\nWhen P0 port is configured as an output then other ports consisting of pins with built-in pull-up resistor connected by its end to 5V power supply, the pins of this port have this resistor left out.\n\n"
},
{
"code": null,
"e": 101749,
"s": 101685,
"text": "Port 0 − The P0 (zero) port is characterized by two functions −"
},
{
"code": null,
"e": 101904,
"s": 101749,
"text": "When the external memory is used then the lower address byte (addresses A0A7) is applied on it, else all bits of this port are configured as input/output."
},
{
"code": null,
"e": 102059,
"s": 101904,
"text": "When the external memory is used then the lower address byte (addresses A0A7) is applied on it, else all bits of this port are configured as input/output."
},
{
"code": null,
"e": 102258,
"s": 102059,
"text": "When P0 port is configured as an output then other ports consisting of pins with built-in pull-up resistor connected by its end to 5V power supply, the pins of this port have this resistor left out."
},
{
"code": null,
"e": 102457,
"s": 102258,
"text": "When P0 port is configured as an output then other ports consisting of pins with built-in pull-up resistor connected by its end to 5V power supply, the pins of this port have this resistor left out."
},
{
"code": null,
"e": 102615,
"s": 102457,
"text": "If any pin of this port is configured as an input, then it acts as if it “floats”, i.e. the input has unlimited input resistance and in-determined potential."
},
{
"code": null,
"e": 102845,
"s": 102615,
"text": "When the pin is configured as an output, then it acts as an “open drain”. By applying logic 0 to a port bit, the appropriate pin will be connected to ground (0V), and applying logic 1, the external output will keep on “floating”."
},
{
"code": null,
"e": 102950,
"s": 102845,
"text": "In order to apply logic 1 (5V) on this output pin, it is necessary to build an external pullup resistor."
},
{
"code": null,
"e": 103163,
"s": 102950,
"text": "P1 is a true I/O port as it doesn’t have any alternative functions as in P0, but this port can be configured as general I/O only. It has a built-in pull-up resistor and is completely compatible with TTL circuits."
},
{
"code": null,
"e": 103461,
"s": 103163,
"text": "P2 is similar to P0 when the external memory is used. Pins of this port occupy addresses intended for the external memory chip. This port can be used for higher address byte with addresses A8-A15. When no memory is added then this port can be used as a general input/output port similar to Port 1."
},
{
"code": null,
"e": 103591,
"s": 103461,
"text": "In this port, functions are similar to other ports except that the logic 1 must be applied to appropriate bit of the P3 register."
},
{
"code": null,
"e": 103702,
"s": 103591,
"text": "When pins are configured as an output (i.e. logic 0), then the single port pins can receive a current of 10mA."
},
{
"code": null,
"e": 103813,
"s": 103702,
"text": "When pins are configured as an output (i.e. logic 0), then the single port pins can receive a current of 10mA."
},
{
"code": null,
"e": 103979,
"s": 103813,
"text": "When these pins are configured as inputs (i.e. logic 1), then built-in pull-up resistors provide very weak current, but can activate up to 4 TTL inputs of LS series."
},
{
"code": null,
"e": 104145,
"s": 103979,
"text": "When these pins are configured as inputs (i.e. logic 1), then built-in pull-up resistors provide very weak current, but can activate up to 4 TTL inputs of LS series."
},
{
"code": null,
"e": 104245,
"s": 104145,
"text": "If all 8 bits of a port are active, then the total current must be limited to 15mA (port P0: 26mA)."
},
{
"code": null,
"e": 104345,
"s": 104245,
"text": "If all 8 bits of a port are active, then the total current must be limited to 15mA (port P0: 26mA)."
},
{
"code": null,
"e": 104436,
"s": 104345,
"text": "If all ports (32 bits) are active, then the total maximum current must be limited to 71mA."
},
{
"code": null,
"e": 104527,
"s": 104436,
"text": "If all ports (32 bits) are active, then the total maximum current must be limited to 71mA."
},
{
"code": null,
"e": 104731,
"s": 104527,
"text": "Interrupts are the events that temporarily suspend the main program, pass the control to the external sources and execute their task. It then passes the control to the main program where it had left off."
},
{
"code": null,
"e": 104964,
"s": 104731,
"text": "8051 has 5 interrupt signals, i.e. INT0, TFO, INT1, TF1, RI/TI. Each interrupt can be enabled or disabled by setting bits of the IE register and the whole interrupt system can be disabled by clearing the EA bit of the same register."
},
{
"code": null,
"e": 105199,
"s": 104964,
"text": "This register is responsible for enabling and disabling the interrupt. EA register is set to one for enabling interrupts and set to 0 for disabling the interrupts. Its bit sequence and their meanings are shown in the following figure."
},
{
"code": null,
"e": 105359,
"s": 105199,
"text": "We can change the priority levels of the interrupts by changing the corresponding bit in the Interrupt Priority (IP) register as shown in the following figure."
},
{
"code": null,
"e": 105495,
"s": 105359,
"text": "A low priority interrupt can only be interrupted by the high priority interrupt, but not interrupted by another low priority interrupt."
},
{
"code": null,
"e": 105631,
"s": 105495,
"text": "A low priority interrupt can only be interrupted by the high priority interrupt, but not interrupted by another low priority interrupt."
},
{
"code": null,
"e": 105755,
"s": 105631,
"text": "If two interrupts of different priority levels are received simultaneously, the request of higher priority level is served."
},
{
"code": null,
"e": 105879,
"s": 105755,
"text": "If two interrupts of different priority levels are received simultaneously, the request of higher priority level is served."
},
{
"code": null,
"e": 106031,
"s": 105879,
"text": "If the requests of the same priority levels are received simultaneously, then the internal polling sequence determines which request is to be serviced."
},
{
"code": null,
"e": 106183,
"s": 106031,
"text": "If the requests of the same priority levels are received simultaneously, then the internal polling sequence determines which request is to be serviced."
},
{
"code": null,
"e": 106262,
"s": 106183,
"text": "TCON register specifies the type of external interrupt to the microcontroller."
},
{
"code": null,
"e": 106458,
"s": 106262,
"text": "The 8255A is a general purpose programmable I/O device designed to transfer the data from I/O to interrupt I/O under certain conditions as required. It can be used with almost any microprocessor."
},
{
"code": null,
"e": 106571,
"s": 106458,
"text": "It consists of three 8-bit bidirectional I/O ports (24I/O lines) which can be configured as per the requirement."
},
{
"code": null,
"e": 106628,
"s": 106571,
"text": "8255A has three ports, i.e., PORT A, PORT B, and PORT C."
},
{
"code": null,
"e": 106702,
"s": 106628,
"text": "Port A contains one 8-bit output latch/buffer and one 8-bit input buffer."
},
{
"code": null,
"e": 106776,
"s": 106702,
"text": "Port A contains one 8-bit output latch/buffer and one 8-bit input buffer."
},
{
"code": null,
"e": 106805,
"s": 106776,
"text": "Port B is similar to PORT A."
},
{
"code": null,
"e": 106834,
"s": 106805,
"text": "Port B is similar to PORT A."
},
{
"code": null,
"e": 106946,
"s": 106834,
"text": "Port C can be split into two parts, i.e. PORT C lower (PC0-PC3) and PORT C upper (PC7-PC4) by the control word."
},
{
"code": null,
"e": 107058,
"s": 106946,
"text": "Port C can be split into two parts, i.e. PORT C lower (PC0-PC3) and PORT C upper (PC7-PC4) by the control word."
},
{
"code": null,
"e": 107377,
"s": 107058,
"text": "These three ports are further divided into two groups, i.e. Group A includes PORT A and upper PORT C. Group B includes PORT B and lower PORT C. These two groups can be programmed in three different modes, i.e. the first mode is named as mode 0, the second mode is named as Mode 1 and the third mode is named as Mode 2."
},
{
"code": null,
"e": 107421,
"s": 107377,
"text": "8255A has three different operating modes −"
},
{
"code": null,
"e": 107673,
"s": 107421,
"text": "Mode 0 − In this mode, Port A and B is used as two 8-bit ports and Port C as two 4-bit ports. Each port can be programmed in either input mode or output mode where outputs are latched and inputs are not latched. Ports do not have interrupt capability."
},
{
"code": null,
"e": 107925,
"s": 107673,
"text": "Mode 0 − In this mode, Port A and B is used as two 8-bit ports and Port C as two 4-bit ports. Each port can be programmed in either input mode or output mode where outputs are latched and inputs are not latched. Ports do not have interrupt capability."
},
{
"code": null,
"e": 108138,
"s": 107925,
"text": "Mode 1 − In this mode, Port A and B is used as 8-bit I/O ports. They can be configured as either input or output ports. Each port uses three lines from port C as handshake signals. Inputs and outputs are latched."
},
{
"code": null,
"e": 108351,
"s": 108138,
"text": "Mode 1 − In this mode, Port A and B is used as 8-bit I/O ports. They can be configured as either input or output ports. Each port uses three lines from port C as handshake signals. Inputs and outputs are latched."
},
{
"code": null,
"e": 108642,
"s": 108351,
"text": "Mode 2 − In this mode, Port A can be configured as the bidirectional port and Port B either in Mode 0 or Mode 1. Port A uses five signals from Port C as handshake signals for data transfer. The remaining three signals from Port C can be used either as simple I/O or as handshake for port B."
},
{
"code": null,
"e": 108933,
"s": 108642,
"text": "Mode 2 − In this mode, Port A can be configured as the bidirectional port and Port B either in Mode 0 or Mode 1. Port A uses five signals from Port C as handshake signals for data transfer. The remaining three signals from Port C can be used either as simple I/O or as handshake for port B."
},
{
"code": null,
"e": 108982,
"s": 108933,
"text": "The prominent features of 8255A are as follows −"
},
{
"code": null,
"e": 109035,
"s": 108982,
"text": "It consists of 3 8-bit IO ports i.e. PA, PB, and PC."
},
{
"code": null,
"e": 109088,
"s": 109035,
"text": "It consists of 3 8-bit IO ports i.e. PA, PB, and PC."
},
{
"code": null,
"e": 109133,
"s": 109088,
"text": "Address/data bus must be externally demux'd."
},
{
"code": null,
"e": 109178,
"s": 109133,
"text": "Address/data bus must be externally demux'd."
},
{
"code": null,
"e": 109200,
"s": 109178,
"text": "It is TTL compatible."
},
{
"code": null,
"e": 109222,
"s": 109200,
"text": "It is TTL compatible."
},
{
"code": null,
"e": 109261,
"s": 109222,
"text": "It has improved DC driving capability."
},
{
"code": null,
"e": 109300,
"s": 109261,
"text": "It has improved DC driving capability."
},
{
"code": null,
"e": 109355,
"s": 109300,
"text": "The following figure shows the architecture of 8255A −"
},
{
"code": null,
"e": 109416,
"s": 109355,
"text": "Let us first take a look at the pin diagram of Intel 8255A −"
},
{
"code": null,
"e": 109484,
"s": 109416,
"text": "Now let us discuss the functional description of the pins in 8255A."
},
{
"code": null,
"e": 109741,
"s": 109484,
"text": "It is a tri-state 8-bit buffer, which is used to interface the microprocessor to the system data bus. Data is transmitted or received by the buffer as per the instructions by the CPU. Control words and status information is also transferred using this bus."
},
{
"code": null,
"e": 109959,
"s": 109741,
"text": "This block is responsible for controlling the internal/external transfer of data/control/status word. It accepts the input from the CPU address and control buses, and in turn issues command to both the control groups."
},
{
"code": null,
"e": 110187,
"s": 109959,
"text": "It stands for Chip Select. A LOW on this input selects the chip and enables the communication between the 8255A and the CPU. It is connected to the decoded address, and A0 & A1 are connected to the microprocessor address lines."
},
{
"code": null,
"e": 110238,
"s": 110187,
"text": "Their result depends on the following conditions −"
},
{
"code": null,
"e": 110407,
"s": 110238,
"text": "It stands for write. This control signal enables the write operation. When this signal goes low, the microprocessor writes into a selected I/O port or control register."
},
{
"code": null,
"e": 110507,
"s": 110407,
"text": "This is an active high signal. It clears the control register and sets all ports in the input mode."
},
{
"code": null,
"e": 110673,
"s": 110507,
"text": "It stands for Read. This control signal enables the Read operation. When the signal is low, the microprocessor reads the data from the selected I/O port of the 8255."
},
{
"code": null,
"e": 110814,
"s": 110673,
"text": "These input signals work with RD, WR, and one of the control signal. Following is the table showing their various signals with their result."
},
{
"code": null,
"e": 110830,
"s": 110814,
"text": "Input Operation"
},
{
"code": null,
"e": 110847,
"s": 110830,
"text": "Output Operation"
},
{
"code": null,
"e": 111283,
"s": 110847,
"text": "The Intel 8253 and 8254 are Programmable Interval Timers (PTIs) designed for microprocessors to perform timing and counting functions using three 16-bit registers. Each counter has 2 input pins, i.e. Clock & Gate, and 1 pin for “OUT” output. To operate a counter, a 16-bit count is loaded in its register. On command, it begins to decrement the count until it reaches 0, then it generates a pulse that can be used to interrupt the CPU."
},
{
"code": null,
"e": 111350,
"s": 111283,
"text": "The following table differentiates the features of 8253 and 8254 −"
},
{
"code": null,
"e": 111406,
"s": 111350,
"text": "The most prominent features of 8253/54 are as follows −"
},
{
"code": null,
"e": 111453,
"s": 111406,
"text": "It has three independent 16-bit down counters."
},
{
"code": null,
"e": 111500,
"s": 111453,
"text": "It has three independent 16-bit down counters."
},
{
"code": null,
"e": 111540,
"s": 111500,
"text": "It can handle inputs from DC to 10 MHz."
},
{
"code": null,
"e": 111580,
"s": 111540,
"text": "It can handle inputs from DC to 10 MHz."
},
{
"code": null,
"e": 111651,
"s": 111580,
"text": "These three counters can be programmed for either binary or BCD count."
},
{
"code": null,
"e": 111722,
"s": 111651,
"text": "These three counters can be programmed for either binary or BCD count."
},
{
"code": null,
"e": 111772,
"s": 111722,
"text": "It is compatible with almost all microprocessors."
},
{
"code": null,
"e": 111822,
"s": 111772,
"text": "It is compatible with almost all microprocessors."
},
{
"code": null,
"e": 112002,
"s": 111822,
"text": "8254 has a powerful command called READ BACK command, which allows the user to check the count value, the programmed mode, the current mode, and the current status of the counter."
},
{
"code": null,
"e": 112182,
"s": 112002,
"text": "8254 has a powerful command called READ BACK command, which allows the user to check the count value, the programmed mode, the current mode, and the current status of the counter."
},
{
"code": null,
"e": 112226,
"s": 112182,
"text": "The architecture of 8254 looks as follows −"
},
{
"code": null,
"e": 112260,
"s": 112226,
"text": "Here is the pin diagram of 8254 −"
},
{
"code": null,
"e": 112456,
"s": 112260,
"text": "In the above figure, there are three counters, a data bus buffer, Read/Write control logic, and a control register. Each counter has two input signals - CLOCK & GATE, and one output signal - OUT."
},
{
"code": null,
"e": 112599,
"s": 112456,
"text": "It is a tri-state, bi-directional, 8-bit buffer, which is used to interface the 8253/54 to the system data bus. It has three basic functions −"
},
{
"code": null,
"e": 112633,
"s": 112599,
"text": "Programming the modes of 8253/54."
},
{
"code": null,
"e": 112662,
"s": 112633,
"text": "Loading the count registers."
},
{
"code": null,
"e": 112688,
"s": 112662,
"text": "Reading the count values."
},
{
"code": null,
"e": 112921,
"s": 112688,
"text": "It includes 5 signals, i.e. RD, WR, CS, and the address lines A0 & A1. In the peripheral I/O mode, the RD and WR signals are connected to IOR and IOW, respectively. In the memorymapped I/O mode, these are connected to MEMR and MEMW."
},
{
"code": null,
"e": 113135,
"s": 112921,
"text": "Address lines A0 & A1 of the CPU are connected to lines A0 and A1 of the 8253/54, and CS is tied to a decoded address. The control word register and counters are selected according to the signals on lines A0 & A1."
},
{
"code": null,
"e": 113381,
"s": 113135,
"text": "This register is accessed when lines A0 & A1 are at logic 1. It is used to write a command word, which specifies the counter to be used, its mode, and either a read or write operation. Following table shows the result for various control inputs."
},
{
"code": null,
"e": 113696,
"s": 113381,
"text": "Each counter consists of a single, 16 bit-down counter, which can be operated in either binary or BCD. Its input and output is configured by the selection of modes stored in the control word register. The programmer can read the contents of any of the three counters without disturbing the actual count in process."
},
{
"code": null,
"e": 113800,
"s": 113696,
"text": "8253/54 can be operated in 6 different modes. In this chapter, we will discuss these operational modes."
},
{
"code": null,
"e": 113884,
"s": 113800,
"text": "It is used to generate an interrupt to the microprocessor after a certain interval."
},
{
"code": null,
"e": 113968,
"s": 113884,
"text": "It is used to generate an interrupt to the microprocessor after a certain interval."
},
{
"code": null,
"e": 114092,
"s": 113968,
"text": "Initially the output is low after the mode is set. The output remains LOW after the count value is loaded into the counter."
},
{
"code": null,
"e": 114216,
"s": 114092,
"text": "Initially the output is low after the mode is set. The output remains LOW after the count value is loaded into the counter."
},
{
"code": null,
"e": 114406,
"s": 114216,
"text": "The process of decrementing the counter continues till the terminal count is reached, i.e., the count become zero and the output goes HIGH and will remain high until it reloads a new count."
},
{
"code": null,
"e": 114596,
"s": 114406,
"text": "The process of decrementing the counter continues till the terminal count is reached, i.e., the count become zero and the output goes HIGH and will remain high until it reloads a new count."
},
{
"code": null,
"e": 114748,
"s": 114596,
"text": "The GATE signal is high for normal counting. When GATE goes low, counting is terminated and the current count is latched till the GATE goes high again."
},
{
"code": null,
"e": 114900,
"s": 114748,
"text": "The GATE signal is high for normal counting. When GATE goes low, counting is terminated and the current count is latched till the GATE goes high again."
},
{
"code": null,
"e": 114948,
"s": 114900,
"text": "It can be used as a mono stable multi-vibrator."
},
{
"code": null,
"e": 114996,
"s": 114948,
"text": "It can be used as a mono stable multi-vibrator."
},
{
"code": null,
"e": 115052,
"s": 114996,
"text": "The gate input is used as a trigger input in this mode."
},
{
"code": null,
"e": 115108,
"s": 115052,
"text": "The gate input is used as a trigger input in this mode."
},
{
"code": null,
"e": 115184,
"s": 115108,
"text": "The output remains high until the count is loaded and a trigger is applied."
},
{
"code": null,
"e": 115260,
"s": 115184,
"text": "The output remains high until the count is loaded and a trigger is applied."
},
{
"code": null,
"e": 115310,
"s": 115260,
"text": "The output is normally high after initialization."
},
{
"code": null,
"e": 115360,
"s": 115310,
"text": "The output is normally high after initialization."
},
{
"code": null,
"e": 115472,
"s": 115360,
"text": "Whenever the count becomes zero, another low pulse is generated at the output and the counter will be reloaded."
},
{
"code": null,
"e": 115584,
"s": 115472,
"text": "Whenever the count becomes zero, another low pulse is generated at the output and the counter will be reloaded."
},
{
"code": null,
"e": 115717,
"s": 115584,
"text": "This mode is similar to Mode 2 except the output remains low for half of the timer period and high for the other half of the period."
},
{
"code": null,
"e": 115850,
"s": 115717,
"text": "This mode is similar to Mode 2 except the output remains low for half of the timer period and high for the other half of the period."
},
{
"code": null,
"e": 115994,
"s": 115850,
"text": "In this mode, the output will remain high until the timer has counted to zero, at which point the output will pulse low and then go high again."
},
{
"code": null,
"e": 116138,
"s": 115994,
"text": "In this mode, the output will remain high until the timer has counted to zero, at which point the output will pulse low and then go high again."
},
{
"code": null,
"e": 116190,
"s": 116138,
"text": "The count is latched when the GATE signal goes LOW."
},
{
"code": null,
"e": 116242,
"s": 116190,
"text": "The count is latched when the GATE signal goes LOW."
},
{
"code": null,
"e": 116361,
"s": 116242,
"text": "On the terminal count, the output goes low for one clock cycle then goes HIGH. This low pulse can be used as a strobe."
},
{
"code": null,
"e": 116480,
"s": 116361,
"text": "On the terminal count, the output goes low for one clock cycle then goes HIGH. This low pulse can be used as a strobe."
},
{
"code": null,
"e": 116556,
"s": 116480,
"text": "This mode generates a strobe in response to an externally generated signal."
},
{
"code": null,
"e": 116632,
"s": 116556,
"text": "This mode generates a strobe in response to an externally generated signal."
},
{
"code": null,
"e": 116800,
"s": 116632,
"text": "This mode is similar to mode 4 except that the counting is initiated by a signal at the gate input, which means it is hardware triggered instead of software triggered."
},
{
"code": null,
"e": 116968,
"s": 116800,
"text": "This mode is similar to mode 4 except that the counting is initiated by a signal at the gate input, which means it is hardware triggered instead of software triggered."
},
{
"code": null,
"e": 117015,
"s": 116968,
"text": "After it is initialized, the output goes high."
},
{
"code": null,
"e": 117062,
"s": 117015,
"text": "After it is initialized, the output goes high."
},
{
"code": null,
"e": 117139,
"s": 117062,
"text": "When the terminal count is reached, the output goes low for one clock cycle."
},
{
"code": null,
"e": 117216,
"s": 117139,
"text": "When the terminal count is reached, the output goes low for one clock cycle."
},
{
"code": null,
"e": 117251,
"s": 117216,
"text": "\n 50 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 117268,
"s": 117251,
"text": " Gowthami Swarna"
},
{
"code": null,
"e": 117275,
"s": 117268,
"text": " Print"
},
{
"code": null,
"e": 117286,
"s": 117275,
"text": " Add Notes"
}
] |
VB.Net - Binary Files
|
The BinaryReader and BinaryWriter classes are used for reading from and writing to a binary file.
The BinaryReader class is used to read binary data from a file. A BinaryReader object is created by passing a FileStream object to its constructor.
The following table shows some of the commonly used methods of the BinaryReader class.
Public Overridable Sub Close
It closes the BinaryReader object and the underlying stream.
Public Overridable Function Read As Integer
Reads the characters from the underlying stream and advances the current position of the stream.
Public Overridable Function ReadBoolean As Boolean
Reads a Boolean value from the current stream and advances the current position of the stream by one byte.
Public Overridable Function ReadByte As Byte
Reads the next byte from the current stream and advances the current position of the stream by one byte.
Public Overridable Function ReadBytes (count As Integer) As Byte()
Reads the specified number of bytes from the current stream into a byte array and advances the current position by that number of bytes.
Public Overridable Function ReadChar As Char
Reads the next character from the current stream and advances the current position of the stream in accordance with the Encoding used and the specific character being read from the stream.
Public Overridable Function ReadChars (count As Integer) As Char()
Reads the specified number of characters from the current stream, returns the data in a character array, and advances the current position in accordance with the Encoding used and the specific character being read from the stream.
Public Overridable Function ReadDouble As Double
Reads an 8-byte floating point value from the current stream and advances the current position of the stream by eight bytes.
Public Overridable Function ReadInt32 As Integer
Reads a 4-byte signed integer from the current stream and advances the current position of the stream by four bytes.
Public Overridable Function ReadString As String
Reads a string from the current stream. The string is prefixed with the length, encoded as an integer seven bits at a time.
The BinaryWriter class is used to write binary data to a stream. A BinaryWriter object is created by passing a FileStream object to its constructor.
The following table shows some of the commonly used methods of the BinaryWriter class.
Public Overridable Sub Close
It closes the BinaryWriter object and the underlying stream.
Public Overridable Sub Flush
Clears all buffers for the current writer and causes any buffered data to be written to the underlying device.
Public Overridable Function Seek (offset As Integer, origin As SeekOrigin ) As Long
Sets the position within the current stream.
Public Overridable Sub Write (value As Boolean)
Writes a one-byte Boolean value to the current stream, with 0 representing false and 1 representing true.
Public Overridable Sub Write (value As Byte)
Writes an unsigned byte to the current stream and advances the stream position by one byte.
Public Overridable Sub Write (buffer As Byte())
Writes a byte array to the underlying stream.
Public Overridable Sub Write (ch As Char )
Writes a Unicode character to the current stream and advances the current position of the stream in accordance with the Encoding used and the specific characters being written to the stream.
Public Overridable Sub Write (chars As Char())
Writes a character array to the current stream and advances the current position of the stream in accordance with the Encoding used and the specific characters being written to the stream.
Public Overridable Sub Write (value As Double )
Writes an eight-byte floating-point value to the current stream and advances the stream position by eight bytes.
Public Overridable Sub Write (value As Integer )
Writes a four-byte signed integer to the current stream and advances the stream position by four bytes.
Public Overridable Sub Write (value As String )
Writes a length-prefixed string to this stream in the current encoding of the BinaryWriter and advances the current position of the stream in accordance with the encoding used and the specific characters being written to the stream.
For complete list of methods, please visit Microsoft's documentation.
The following example demonstrates reading and writing binary data −
Imports System.IO
Module fileProg
Sub Main()
Dim bw As BinaryWriter
Dim br As BinaryReader
Dim i As Integer = 25
Dim d As Double = 3.14157
Dim b As Boolean = True
Dim s As String = "I am happy"
'create the file
Try
bw = New BinaryWriter(New FileStream("mydata", FileMode.Create))
Catch e As IOException
Console.WriteLine(e.Message + "\n Cannot create file.")
Return
End Try
'writing into the file
Try
bw.Write(i)
bw.Write(d)
bw.Write(b)
bw.Write(s)
Catch e As IOException
Console.WriteLine(e.Message + "\n Cannot write to file.")
Return
End Try
bw.Close()
'reading from the file
Try
br = New BinaryReader(New FileStream("mydata", FileMode.Open))
Catch e As IOException
Console.WriteLine(e.Message + "\n Cannot open file.")
Return
End Try
Try
i = br.ReadInt32()
Console.WriteLine("Integer data: {0}", i)
d = br.ReadDouble()
Console.WriteLine("Double data: {0}", d)
b = br.ReadBoolean()
Console.WriteLine("Boolean data: {0}", b)
s = br.ReadString()
Console.WriteLine("String data: {0}", s)
Catch e As IOException
Console.WriteLine(e.Message + "\n Cannot read from file.")
Return
End Try
br.Close()
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Integer data: 25
Double data: 3.14157
Boolean data: True
String data: I am happy
63 Lectures
4 hours
Frahaan Hussain
103 Lectures
12 hours
Arnold Higuit
60 Lectures
9.5 hours
Arnold Higuit
97 Lectures
9 hours
Arnold Higuit
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2398,
"s": 2300,
"text": "The BinaryReader and BinaryWriter classes are used for reading from and writing to a binary file."
},
{
"code": null,
"e": 2546,
"s": 2398,
"text": "The BinaryReader class is used to read binary data from a file. A BinaryReader object is created by passing a FileStream object to its constructor."
},
{
"code": null,
"e": 2633,
"s": 2546,
"text": "The following table shows some of the commonly used methods of the BinaryReader class."
},
{
"code": null,
"e": 2662,
"s": 2633,
"text": "Public Overridable Sub Close"
},
{
"code": null,
"e": 2723,
"s": 2662,
"text": "It closes the BinaryReader object and the underlying stream."
},
{
"code": null,
"e": 2767,
"s": 2723,
"text": "Public Overridable Function Read As Integer"
},
{
"code": null,
"e": 2864,
"s": 2767,
"text": "Reads the characters from the underlying stream and advances the current position of the stream."
},
{
"code": null,
"e": 2915,
"s": 2864,
"text": "Public Overridable Function ReadBoolean As Boolean"
},
{
"code": null,
"e": 3022,
"s": 2915,
"text": "Reads a Boolean value from the current stream and advances the current position of the stream by one byte."
},
{
"code": null,
"e": 3067,
"s": 3022,
"text": "Public Overridable Function ReadByte As Byte"
},
{
"code": null,
"e": 3172,
"s": 3067,
"text": "Reads the next byte from the current stream and advances the current position of the stream by one byte."
},
{
"code": null,
"e": 3239,
"s": 3172,
"text": "Public Overridable Function ReadBytes (count As Integer) As Byte()"
},
{
"code": null,
"e": 3376,
"s": 3239,
"text": "Reads the specified number of bytes from the current stream into a byte array and advances the current position by that number of bytes."
},
{
"code": null,
"e": 3421,
"s": 3376,
"text": "Public Overridable Function ReadChar As Char"
},
{
"code": null,
"e": 3612,
"s": 3421,
"text": "Reads the next character from the current stream and advances the current position of the stream in accordance with the Encoding used and the specific character being read from the stream."
},
{
"code": null,
"e": 3679,
"s": 3612,
"text": "Public Overridable Function ReadChars (count As Integer) As Char()"
},
{
"code": null,
"e": 3910,
"s": 3679,
"text": "Reads the specified number of characters from the current stream, returns the data in a character array, and advances the current position in accordance with the Encoding used and the specific character being read from the stream."
},
{
"code": null,
"e": 3959,
"s": 3910,
"text": "Public Overridable Function ReadDouble As Double"
},
{
"code": null,
"e": 4084,
"s": 3959,
"text": "Reads an 8-byte floating point value from the current stream and advances the current position of the stream by eight bytes."
},
{
"code": null,
"e": 4133,
"s": 4084,
"text": "Public Overridable Function ReadInt32 As Integer"
},
{
"code": null,
"e": 4250,
"s": 4133,
"text": "Reads a 4-byte signed integer from the current stream and advances the current position of the stream by four bytes."
},
{
"code": null,
"e": 4299,
"s": 4250,
"text": "Public Overridable Function ReadString As String"
},
{
"code": null,
"e": 4423,
"s": 4299,
"text": "Reads a string from the current stream. The string is prefixed with the length, encoded as an integer seven bits at a time."
},
{
"code": null,
"e": 4572,
"s": 4423,
"text": "The BinaryWriter class is used to write binary data to a stream. A BinaryWriter object is created by passing a FileStream object to its constructor."
},
{
"code": null,
"e": 4659,
"s": 4572,
"text": "The following table shows some of the commonly used methods of the BinaryWriter class."
},
{
"code": null,
"e": 4688,
"s": 4659,
"text": "Public Overridable Sub Close"
},
{
"code": null,
"e": 4749,
"s": 4688,
"text": "It closes the BinaryWriter object and the underlying stream."
},
{
"code": null,
"e": 4778,
"s": 4749,
"text": "Public Overridable Sub Flush"
},
{
"code": null,
"e": 4889,
"s": 4778,
"text": "Clears all buffers for the current writer and causes any buffered data to be written to the underlying device."
},
{
"code": null,
"e": 4973,
"s": 4889,
"text": "Public Overridable Function Seek (offset As Integer, origin As SeekOrigin ) As Long"
},
{
"code": null,
"e": 5018,
"s": 4973,
"text": "Sets the position within the current stream."
},
{
"code": null,
"e": 5066,
"s": 5018,
"text": "Public Overridable Sub Write (value As Boolean)"
},
{
"code": null,
"e": 5172,
"s": 5066,
"text": "Writes a one-byte Boolean value to the current stream, with 0 representing false and 1 representing true."
},
{
"code": null,
"e": 5217,
"s": 5172,
"text": "Public Overridable Sub Write (value As Byte)"
},
{
"code": null,
"e": 5309,
"s": 5217,
"text": "Writes an unsigned byte to the current stream and advances the stream position by one byte."
},
{
"code": null,
"e": 5357,
"s": 5309,
"text": "Public Overridable Sub Write (buffer As Byte())"
},
{
"code": null,
"e": 5403,
"s": 5357,
"text": "Writes a byte array to the underlying stream."
},
{
"code": null,
"e": 5446,
"s": 5403,
"text": "Public Overridable Sub Write (ch As Char )"
},
{
"code": null,
"e": 5637,
"s": 5446,
"text": "Writes a Unicode character to the current stream and advances the current position of the stream in accordance with the Encoding used and the specific characters being written to the stream."
},
{
"code": null,
"e": 5684,
"s": 5637,
"text": "Public Overridable Sub Write (chars As Char())"
},
{
"code": null,
"e": 5873,
"s": 5684,
"text": "Writes a character array to the current stream and advances the current position of the stream in accordance with the Encoding used and the specific characters being written to the stream."
},
{
"code": null,
"e": 5921,
"s": 5873,
"text": "Public Overridable Sub Write (value As Double )"
},
{
"code": null,
"e": 6034,
"s": 5921,
"text": "Writes an eight-byte floating-point value to the current stream and advances the stream position by eight bytes."
},
{
"code": null,
"e": 6083,
"s": 6034,
"text": "Public Overridable Sub Write (value As Integer )"
},
{
"code": null,
"e": 6187,
"s": 6083,
"text": "Writes a four-byte signed integer to the current stream and advances the stream position by four bytes."
},
{
"code": null,
"e": 6235,
"s": 6187,
"text": "Public Overridable Sub Write (value As String )"
},
{
"code": null,
"e": 6468,
"s": 6235,
"text": "Writes a length-prefixed string to this stream in the current encoding of the BinaryWriter and advances the current position of the stream in accordance with the encoding used and the specific characters being written to the stream."
},
{
"code": null,
"e": 6538,
"s": 6468,
"text": "For complete list of methods, please visit Microsoft's documentation."
},
{
"code": null,
"e": 6607,
"s": 6538,
"text": "The following example demonstrates reading and writing binary data −"
},
{
"code": null,
"e": 8116,
"s": 6607,
"text": "Imports System.IO\nModule fileProg\n Sub Main()\n Dim bw As BinaryWriter\n Dim br As BinaryReader\n Dim i As Integer = 25\n Dim d As Double = 3.14157\n Dim b As Boolean = True\n Dim s As String = \"I am happy\"\n 'create the file\n \n Try\n bw = New BinaryWriter(New FileStream(\"mydata\", FileMode.Create))\n Catch e As IOException\n Console.WriteLine(e.Message + \"\\n Cannot create file.\")\n Return\n End Try\n 'writing into the file\n \n Try\n bw.Write(i)\n bw.Write(d)\n bw.Write(b)\n bw.Write(s)\n Catch e As IOException\n Console.WriteLine(e.Message + \"\\n Cannot write to file.\")\n Return\n End Try\n bw.Close()\n 'reading from the file\n \n Try\n br = New BinaryReader(New FileStream(\"mydata\", FileMode.Open))\n Catch e As IOException\n Console.WriteLine(e.Message + \"\\n Cannot open file.\")\n Return\n End Try\n \n Try\n i = br.ReadInt32()\n Console.WriteLine(\"Integer data: {0}\", i)\n d = br.ReadDouble()\n Console.WriteLine(\"Double data: {0}\", d)\n b = br.ReadBoolean()\n Console.WriteLine(\"Boolean data: {0}\", b)\n s = br.ReadString()\n Console.WriteLine(\"String data: {0}\", s)\n Catch e As IOException\n Console.WriteLine(e.Message + \"\\n Cannot read from file.\")\n Return\n End Try\n br.Close()\n Console.ReadKey()\n End Sub\nEnd Module"
},
{
"code": null,
"e": 8197,
"s": 8116,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 8279,
"s": 8197,
"text": "Integer data: 25\nDouble data: 3.14157\nBoolean data: True\nString data: I am happy\n"
},
{
"code": null,
"e": 8312,
"s": 8279,
"text": "\n 63 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 8329,
"s": 8312,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 8364,
"s": 8329,
"text": "\n 103 Lectures \n 12 hours \n"
},
{
"code": null,
"e": 8379,
"s": 8364,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 8414,
"s": 8379,
"text": "\n 60 Lectures \n 9.5 hours \n"
},
{
"code": null,
"e": 8429,
"s": 8414,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 8462,
"s": 8429,
"text": "\n 97 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 8477,
"s": 8462,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 8484,
"s": 8477,
"text": " Print"
},
{
"code": null,
"e": 8495,
"s": 8484,
"text": " Add Notes"
}
] |
PyQt5 – How to automate Progress Bar while downloading using urllib?
|
14 Sep, 2021
PyQt5 is one of the emerging GUI libraries in terms of developing Python GUI Desktop apps. It has rich and robust functionality which ensures production quality apps. Learning PyQt5 library is an add-on to your knowledge. You can develop your consumer quality, highly professional apps.
In this article, we will learn how to automate the Progress Bar in PyQt5. By automating what we mean is to dynamically change and set the value of progress bar. Suppose, you are downloading any file over the internet and want to show the progress of the download, then this article will surely help you.
In the present example, we are using the Urllib library to download the files as its the most common library to download files using python.
Syntax :
self.progressBar = QProgressBar(self)QProgressBar class is for creating the progress bar object.
Firstly, go through the following code, then we will explain what the whole thing does.
Code :
Python3
# importing librariesimport urllib.requestfrom PyQt5.QtWidgets import *import sys class GeeksforGeeks(QWidget): def __init__(self): super().__init__() # calling a defined method to initialize UI self.init_UI() # method for creating UI widgets def init_UI(self): # creating progress bar self.progressBar = QProgressBar(self) # setting its size self.progressBar.setGeometry(25, 45, 210, 30) # creating push button to start download self.button = QPushButton('Start', self) # assigning position to button self.button.move(50, 100) # assigning activity to push button self.button.clicked.connect(self.Download) # setting window geometry self.setGeometry(310, 310, 280, 170) # setting window action self.setWindowTitle("GeeksforGeeks") # showing all the widgets self.show() # when push button is pressed, this method is called def Handle_Progress(self, blocknum, blocksize, totalsize): ## calculate the progress readed_data = blocknum * blocksize if totalsize > 0: download_percentage = readed_data * 100 / totalsize self.progressBar.setValue(download_percentage) QApplication.processEvents() # method to download any file using urllib def Download(self): # specify the url of the file which is to be downloaded down_url = '' # specify download url here # specify save location where the file is to be saved save_loc = 'C:\Desktop\GeeksforGeeks.png' # Downloading using urllib urllib.request.urlretrieve(down_url,save_loc, self.Handle_Progress) # main method to call our appif __name__ == '__main__': # create app App = QApplication(sys.argv) # create the instance of our window window = GeeksforGeeks() # start the app sys.exit(App.exec())
Explanation :
Below is the syntax for urllib, we have to study all the parameters it takes.
Syntax: urllib.request.urlretrieve(url, filename, reporthook)
Parameters: This method will take following parameters :
The first parameter is the url of the file, which is to be downloaded.
The second parameter, if present, specifies the file location to save the file (if this argument is not passed, the location will be a temp file with an auto-generated name).
The third parameter is a callable that will be called when the file is being downloaded and once after another, each block would be read. The callable (which is a function Handle_Progress in this case) will be passed as three arguments :
a count of blocks transferred so far (blocknum)
block size in bytes (blocksize)
the total size of the file (totalsize)
The function Handle_Progress hence receives three arguments. The current downloaded size of the file is calculated dynamically by multiplying blocknum and blocksize and is stored in the variable readed_data.
The rest of the work is done by the formula for calculating the percentage. We multiply readed_data by 100 and divide it by the total size of the file. It gives us the current download percentage. Then we set this download percentage to the progress bar using setValue() method of progressBar object.
self.progressBar.setValue(download_percentage)
Output :
anikakapoor
gulshankumarar231
Python-projects
Python-PyQt
Articles
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - InkWell Widget
Asymptotic Notations and how to calculate them
How to use gotoxy() in codeblocks?
Print all subsequences of a string using ArrayList
File globbing in Linux
Read JSON file using Python
Python map() function
Adding new column to existing DataFrame in Pandas
Python Dictionary
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n14 Sep, 2021"
},
{
"code": null,
"e": 341,
"s": 54,
"text": "PyQt5 is one of the emerging GUI libraries in terms of developing Python GUI Desktop apps. It has rich and robust functionality which ensures production quality apps. Learning PyQt5 library is an add-on to your knowledge. You can develop your consumer quality, highly professional apps."
},
{
"code": null,
"e": 645,
"s": 341,
"text": "In this article, we will learn how to automate the Progress Bar in PyQt5. By automating what we mean is to dynamically change and set the value of progress bar. Suppose, you are downloading any file over the internet and want to show the progress of the download, then this article will surely help you."
},
{
"code": null,
"e": 786,
"s": 645,
"text": "In the present example, we are using the Urllib library to download the files as its the most common library to download files using python."
},
{
"code": null,
"e": 796,
"s": 786,
"text": "Syntax : "
},
{
"code": null,
"e": 894,
"s": 796,
"text": "self.progressBar = QProgressBar(self)QProgressBar class is for creating the progress bar object. "
},
{
"code": null,
"e": 982,
"s": 894,
"text": "Firstly, go through the following code, then we will explain what the whole thing does."
},
{
"code": null,
"e": 991,
"s": 982,
"text": "Code : "
},
{
"code": null,
"e": 999,
"s": 991,
"text": "Python3"
},
{
"code": "# importing librariesimport urllib.requestfrom PyQt5.QtWidgets import *import sys class GeeksforGeeks(QWidget): def __init__(self): super().__init__() # calling a defined method to initialize UI self.init_UI() # method for creating UI widgets def init_UI(self): # creating progress bar self.progressBar = QProgressBar(self) # setting its size self.progressBar.setGeometry(25, 45, 210, 30) # creating push button to start download self.button = QPushButton('Start', self) # assigning position to button self.button.move(50, 100) # assigning activity to push button self.button.clicked.connect(self.Download) # setting window geometry self.setGeometry(310, 310, 280, 170) # setting window action self.setWindowTitle(\"GeeksforGeeks\") # showing all the widgets self.show() # when push button is pressed, this method is called def Handle_Progress(self, blocknum, blocksize, totalsize): ## calculate the progress readed_data = blocknum * blocksize if totalsize > 0: download_percentage = readed_data * 100 / totalsize self.progressBar.setValue(download_percentage) QApplication.processEvents() # method to download any file using urllib def Download(self): # specify the url of the file which is to be downloaded down_url = '' # specify download url here # specify save location where the file is to be saved save_loc = 'C:\\Desktop\\GeeksforGeeks.png' # Downloading using urllib urllib.request.urlretrieve(down_url,save_loc, self.Handle_Progress) # main method to call our appif __name__ == '__main__': # create app App = QApplication(sys.argv) # create the instance of our window window = GeeksforGeeks() # start the app sys.exit(App.exec())",
"e": 2925,
"s": 999,
"text": null
},
{
"code": null,
"e": 2940,
"s": 2925,
"text": "Explanation : "
},
{
"code": null,
"e": 3020,
"s": 2940,
"text": "Below is the syntax for urllib, we have to study all the parameters it takes. "
},
{
"code": null,
"e": 3082,
"s": 3020,
"text": "Syntax: urllib.request.urlretrieve(url, filename, reporthook)"
},
{
"code": null,
"e": 3139,
"s": 3082,
"text": "Parameters: This method will take following parameters :"
},
{
"code": null,
"e": 3210,
"s": 3139,
"text": "The first parameter is the url of the file, which is to be downloaded."
},
{
"code": null,
"e": 3385,
"s": 3210,
"text": "The second parameter, if present, specifies the file location to save the file (if this argument is not passed, the location will be a temp file with an auto-generated name)."
},
{
"code": null,
"e": 3623,
"s": 3385,
"text": "The third parameter is a callable that will be called when the file is being downloaded and once after another, each block would be read. The callable (which is a function Handle_Progress in this case) will be passed as three arguments :"
},
{
"code": null,
"e": 3671,
"s": 3623,
"text": "a count of blocks transferred so far (blocknum)"
},
{
"code": null,
"e": 3703,
"s": 3671,
"text": "block size in bytes (blocksize)"
},
{
"code": null,
"e": 3742,
"s": 3703,
"text": "the total size of the file (totalsize)"
},
{
"code": null,
"e": 3950,
"s": 3742,
"text": "The function Handle_Progress hence receives three arguments. The current downloaded size of the file is calculated dynamically by multiplying blocknum and blocksize and is stored in the variable readed_data."
},
{
"code": null,
"e": 4251,
"s": 3950,
"text": "The rest of the work is done by the formula for calculating the percentage. We multiply readed_data by 100 and divide it by the total size of the file. It gives us the current download percentage. Then we set this download percentage to the progress bar using setValue() method of progressBar object."
},
{
"code": null,
"e": 4298,
"s": 4251,
"text": "self.progressBar.setValue(download_percentage)"
},
{
"code": null,
"e": 4308,
"s": 4298,
"text": "Output : "
},
{
"code": null,
"e": 4322,
"s": 4310,
"text": "anikakapoor"
},
{
"code": null,
"e": 4340,
"s": 4322,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 4356,
"s": 4340,
"text": "Python-projects"
},
{
"code": null,
"e": 4368,
"s": 4356,
"text": "Python-PyQt"
},
{
"code": null,
"e": 4377,
"s": 4368,
"text": "Articles"
},
{
"code": null,
"e": 4384,
"s": 4377,
"text": "Python"
},
{
"code": null,
"e": 4482,
"s": 4384,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4507,
"s": 4482,
"text": "Flutter - InkWell Widget"
},
{
"code": null,
"e": 4554,
"s": 4507,
"text": "Asymptotic Notations and how to calculate them"
},
{
"code": null,
"e": 4589,
"s": 4554,
"text": "How to use gotoxy() in codeblocks?"
},
{
"code": null,
"e": 4640,
"s": 4589,
"text": "Print all subsequences of a string using ArrayList"
},
{
"code": null,
"e": 4663,
"s": 4640,
"text": "File globbing in Linux"
},
{
"code": null,
"e": 4691,
"s": 4663,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 4713,
"s": 4691,
"text": "Python map() function"
},
{
"code": null,
"e": 4763,
"s": 4713,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 4781,
"s": 4763,
"text": "Python Dictionary"
}
] |
Python – reversed() VS [::-1] , Which one is faster?
|
20 Aug, 2020
Python lists can be reversed using many python method such as using slicing method or using reversed() function. This article discusses how both of these work and Which one of them seems to be the faster one and Why.
Code: Reversing a list using Slicing.
Python3
# Python code to reverse# a list using slicing ls = [110, 220, 330, 440, 550]print('Original list :', ls) # list reversels = ls[::-1] print('Reversed list elements :')for element in ls: print(element)
Output:
Original list : [110, 220, 330, 440, 550]
Reversed list elements :
550
440
330
220
110
Explanation : The format[a : b : c] in slicing states that from an inclusive to b exclusive, count in increments of c. In above code, a and b is blank and c is -1. So it iterates the entire list counting from the last element to the first element resulting in a reversed list.
Code: Reversing a list Using reversed() built-in function.
Python3
# Python code to reverse # a list using reversed() ls = [110, 220, 330, 440, 550]print('Original list :', ls) # list reversels = reversed(ls)print('Iterator object :', ls) print('Reversed list elements :')for element in ls: print(element)
Output:
Original list : [110, 220, 330, 440, 550]
Iterator object : <list_reverseiterator object at 0x7fbd84e0b630>
Reversed list elements :
550
440
330
220
110
Explanation : The built-in reversed() function in Python returns an iterator object rather than an entire list.
For a comparatively large list, under time constraints, it seems that the reversed() function performs faster than the slicing method. This is because reversed() just returns an iterator that iterates the original list in reverse order, without copying anything whereas slicing creates an entirely new list, copying every element from the original list. For a list with 106 Values, the reversed() performs almost 20,000 better than the slicing method. If there is a need to store the reverse copy of data then slicing can be used but if one only wants to iterate the list in reverse manner, reversed() is definitely the better option.
python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Aug, 2020"
},
{
"code": null,
"e": 245,
"s": 28,
"text": "Python lists can be reversed using many python method such as using slicing method or using reversed() function. This article discusses how both of these work and Which one of them seems to be the faster one and Why."
},
{
"code": null,
"e": 283,
"s": 245,
"text": "Code: Reversing a list using Slicing."
},
{
"code": null,
"e": 291,
"s": 283,
"text": "Python3"
},
{
"code": "# Python code to reverse# a list using slicing ls = [110, 220, 330, 440, 550]print('Original list :', ls) # list reversels = ls[::-1] print('Reversed list elements :')for element in ls: print(element)",
"e": 502,
"s": 291,
"text": null
},
{
"code": null,
"e": 510,
"s": 502,
"text": "Output:"
},
{
"code": null,
"e": 597,
"s": 510,
"text": "Original list : [110, 220, 330, 440, 550]\nReversed list elements :\n550\n440\n330\n220\n110"
},
{
"code": null,
"e": 874,
"s": 597,
"text": "Explanation : The format[a : b : c] in slicing states that from an inclusive to b exclusive, count in increments of c. In above code, a and b is blank and c is -1. So it iterates the entire list counting from the last element to the first element resulting in a reversed list."
},
{
"code": null,
"e": 933,
"s": 874,
"text": "Code: Reversing a list Using reversed() built-in function."
},
{
"code": null,
"e": 941,
"s": 933,
"text": "Python3"
},
{
"code": "# Python code to reverse # a list using reversed() ls = [110, 220, 330, 440, 550]print('Original list :', ls) # list reversels = reversed(ls)print('Iterator object :', ls) print('Reversed list elements :')for element in ls: print(element)",
"e": 1184,
"s": 941,
"text": null
},
{
"code": null,
"e": 1193,
"s": 1184,
"text": "Output: "
},
{
"code": null,
"e": 1346,
"s": 1193,
"text": "Original list : [110, 220, 330, 440, 550]\nIterator object : <list_reverseiterator object at 0x7fbd84e0b630>\nReversed list elements :\n550\n440\n330\n220\n110"
},
{
"code": null,
"e": 1458,
"s": 1346,
"text": "Explanation : The built-in reversed() function in Python returns an iterator object rather than an entire list."
},
{
"code": null,
"e": 2093,
"s": 1458,
"text": "For a comparatively large list, under time constraints, it seems that the reversed() function performs faster than the slicing method. This is because reversed() just returns an iterator that iterates the original list in reverse order, without copying anything whereas slicing creates an entirely new list, copying every element from the original list. For a list with 106 Values, the reversed() performs almost 20,000 better than the slicing method. If there is a need to store the reverse copy of data then slicing can be used but if one only wants to iterate the list in reverse manner, reversed() is definitely the better option."
},
{
"code": null,
"e": 2107,
"s": 2093,
"text": "python-string"
},
{
"code": null,
"e": 2114,
"s": 2107,
"text": "Python"
}
] |
Minimum Number of Platforms Required for a Railway/Bus Station
|
10 Jul, 2022
Given the arrival and departure times of all trains that reach a railway station, the task is to find the minimum number of platforms required for the railway station so that no train waits. We are given two arrays that represent the arrival and departure times of trains that stop.
Examples:
Input: arr[] = {9:00, 9:40, 9:50, 11:00, 15:00, 18:00} dep[] = {9:10, 12:00, 11:20, 11:30, 19:00, 20:00} Output: 3 Explanation: There are at-most three trains at a time (time between 9:40 to 12:00)
Input: arr[] = {9:00, 9:40} dep[] = {9:10, 12:00} Output: 1 Explanation: Only one platform is needed.
Naive Approach: The idea is to take every interval one by one and find the number of intervals that overlap with it. Keep track of the maximum number of intervals that overlap with an interval. Finally, return the maximum value.
Follow the steps mentioned below:
Run two nested loops, the outer loop from start to end and the inner loop from i+1 to end.
For every iteration of the outer loop, find the count of intervals that intersect with the current interval.
Update the answer with the maximum count of overlap in each iteration of the outer loop.
Print the answer.
Implementation:
C++14
C
Python3
Java
C#
Javascript
// C++ program to implement the above approach#include <bits/stdc++.h>using namespace std; // Function to find the minimum number// of platforms requiredint findPlatform(int arr[], int dep[], int n){ // plat_needed indicates number of platforms // needed at a time int plat_needed = 1, result = 1; int i = 1, j = 0; // run a nested loop to find overlap for (int i = 0; i < n; i++) { // minimum platform plat_needed = 1; for (int j = i + 1; j < n; j++) { // check for overlap if (max(arr[i], arr[j]) <= min(dep[i], dep[j])) plat_needed++; } // update result result = max(result, plat_needed); } return result;} // Driver Codeint main(){ int arr[] = { 9775, 494, 252, 1680 }; int dep[] = { 2052, 2254, 1395, 2130 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findPlatform(arr, dep, n); return 0;}
// C program to find minimum number of platforms required on// a railway station // Importing the required header files#include <stdio.h> // Creating MACRO for finding the maximum number#define max(x, y) (((x) > (y)) ? (x) : (y)) // Creating MACRO for finding the minimum number#define min(x, y) (((x) < (y)) ? (x) : (y)) // Function to returns the minimum number of platforms// requiredint findPlatform(int arr[], int dep[], int n){ // plat_needed indicates number of platforms // needed at a time int plat_needed = 1, result = 1; int i = 1, j = 0; // run a nested loop to find overlap for (int i = 0; i < n; i++) { // minimum platform plat_needed = 1; for (int j = i + 1; j < n; j++) { // check for overlap if (max(arr[i], arr[j]) <= min(dep[i], dep[j])) plat_needed++; } // update result result = max(result, plat_needed); } return result;} // Driver Codeint main(){ int arr[] = { 900, 940, 950, 1100, 1500, 1800 }; int dep[] = { 910, 1200, 1120, 1130, 1900, 2000 }; int n = sizeof(arr) / sizeof(arr[0]); printf("%d", findPlatform(arr, dep, n)); return 0;}
# Program to find minimum number of platforms# required on a railway station def findPlatform(arr, dep, n): ''' Accepts two arrays with arrival and departure time and the size of the array Returns minimum number of platforms required ''' # plat_needed indicates number of platforms # needed at a time plat_needed = 1 result = 1 # run a nested loop to find overlap for i in range(n): # minimum platform needed plat_needed = 1 for j in range(i+1, n): # check for overlap if (max(arr[i], arr[j]) <= min(dep[i], dep[j])): plat_needed += 1 # update result result = max(result, plat_needed) return result # Driver code def main(): arr = [900, 940, 950, 1100, 1500, 1800] dep = [910, 1200, 1120, 1130, 1900, 2000] n = len(arr) print("{}".format( findPlatform(arr, dep, n))) if __name__ == '__main__': main()
// Program to find minimum number of platforms// required on a railway stationimport java.io.*; class GFG { // Returns minimum number of platforms required public static int findPlatform(int arr[], int dep[], int n) { // plat_needed indicates number of platforms // needed at a time int plat_needed = 1, result = 1; int i = 1, j = 0; // run a nested loop to find overlap for (i = 0; i < n; i++) { // minimum platform plat_needed = 1; for (j = i + 1; j < n; j++) { // check for overlap if (Math.max(arr[i], arr[j]) <= Math.min(dep[i], dep[j])) plat_needed++; } // update result result = Math.max(result, plat_needed); } return result; } // Driver Code public static void main(String[] args) { int arr[] = { 900, 940, 950, 1100, 1500, 1800 }; int dep[] = { 910, 1200, 1120, 1130, 1900, 2000 }; int n = 6; System.out.println(findPlatform(arr, dep, n)); }}
// Program to find minimum number of platforms// required on a railway station using System; public class GFG { // Returns minimum number of platforms required public static int findPlatform(int[] arr, int[] dep, int n) { // plat_needed indicates number of platforms // needed at a time int plat_needed = 1, result = 1; int i = 1, j = 0; // run a nested loop to find overlap for (i = 0; i < n; i++) { // minimum platform plat_needed = 1; for (j = i + 1; j < n; j++) { // check for overlap if (Math.Max(arr[i], arr[j]) <= Math.Min(dep[i], dep[j])) plat_needed++; } // update result result = Math.Max(result, plat_needed); } return result; } // Driver Code static public void Main() { int[] arr = { 900, 940, 950, 1100, 1500, 1800 }; int[] dep = { 910, 1200, 1120, 1130, 1900, 2000 }; int n = 6; Console.WriteLine(findPlatform(arr, dep, n)); }}
<script>// Program to find minimum number of platforms// required on a railway station function max(a,b){ if(a==b) return a; else{ if(a>b) return a; else return b; }} // Returns minimum number of platforms requiredfunction findPlatform( arr, dep, n){ // plat_needed indicates number of platforms // needed at a time var plat_needed = 1, result = 1; var i = 1, j = 0; // run a nested loop to find overlap for (var i = 0; i < n; i++) { // minimum platform plat_needed = 1; for (var j = i + 1; j < n; j++) { // check for overlap if (max(arr[i], arr[j]) <= min(dep[i], dep[j])) plat_needed++; } // update result result = max(result, plat_needed); } return result;} var arr = [ 900, 940, 950, 1100, 1500, 1800 ]; var dep = [ 910, 1200, 1120, 1130, 1900, 2000 ]; var n =6; document.write("Minimum Number of Platforms Required = " +findPlatform(arr, dep, n)); </script>
3
Time Complexity: O(n2), Two nested loops traverse the array.Auxiliary space: O(1), As no extra space is required.
Efficient Approach: Store the arrival time and departure time and sort them based on arrival time then check if the departure time of the next train is smaller than the departure time of the previous train if it is smaller then increment the number of the platforms needed otherwise not.
Follow the steps mentioned below:
Store the arrival time and departure time in array arr and sort this array based on arrival time
Declare a priority queue(min-heap) and store the departure time of the first train and also declare a counter cnt and initialize it with 1.
Iterate over arr from 1 to n-1 check if the arrival time of current train is less than or equals to the departure time of previous train which is kept on top of the priority queueIf true, then push the new departure time and increment the counter cntotherwise, we pop() the departure timepush new departure time in the priority queue
check if the arrival time of current train is less than or equals to the departure time of previous train which is kept on top of the priority queueIf true, then push the new departure time and increment the counter cntotherwise, we pop() the departure timepush new departure time in the priority queue
If true, then push the new departure time and increment the counter cnt
otherwise, we pop() the departure time
push new departure time in the priority queue
Finally, return the cnt.
C++
Java
// C++ program to implement the above approach#include <bits/stdc++.h>using namespace std; // Function to find the minimum number// of platforms requiredint findPlatform(int arr[], int dep[], int n){ // Store the arrival and departure time vector<pair<int, int> > arr2(n); for (int i = 0; i < n; i++) { arr2[i] = { arr[i], dep[i] }; } // Sort arr2 based on arival time sort(arr2.begin(), arr2.end()); priority_queue<int, vector<int>, greater<int> > p; int count = 1; p.push(arr2[0].second); for (int i = 1; i < n; i++) { // Check if arrival time of current train // is less than or equals to depature time // of previous train if (p.top() >= arr2[i].first) { count++; } else { p.pop(); } p.push(arr2[i].second); } // Return the number of train required return count;} // Driver Codeint main(){ int arr[] = { 900, 940, 950, 1100, 1500, 1800 }; int dep[] = { 910, 1200, 1120, 1130, 1900, 2000 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findPlatform(arr, dep, n); return 0;}
// Java code to implement the approachimport java.io.*;import java.util.*; class imp3 { // Function to find the minimum number // of platforms required static int findPlatform(int arr[], int dep[], int n) { // Store the arrival and departure time int[][] arr2 = new int[n][2]; for (int i = 0; i < n; i++) { arr2[i] = new int[] { arr[i], dep[i] }; } // Sort arr2 based on arival time Arrays.sort(arr2, (A, B) -> { return A[0] - B[0]; }); PriorityQueue<Integer> p = new PriorityQueue<>(); int count = 1; p.add(arr2[0][1]); for (int i = 1; i < n; i++) { // Check if arrival time of current train // is less than or equals to depature time // of previous train if (p.peek() >= arr2[i][0]) { count++; } else { p.remove(); } p.add(arr2[i][1]); } // Return the number of platform required return count; } public static void main(String[] args) { int arr[] = { 900, 940, 950, 1100, 1500, 1800 }; int dep[] = { 910, 1200, 1120, 1130, 1900, 2000 }; int n = arr.length; System.out.println(findPlatform(arr, dep, n)); }}// This code is contributed by Karandeep1234
3
Time Complexity: O(N*log(N))Auxiliary Space: O(N)
Another efficient Approach: The idea is to consider all events in sorted order. Once the events are in sorted order, trace the number of trains at any time keeping track of trains that have arrived, but not departed.
Example:
arr[] = {9:00, 9:40, 9:50, 11:00, 15:00, 18:00}
dep[] = {9:10, 12:00, 11:20, 11:30, 19:00, 20:00}
All events are sorted by time.
Total platforms at any time can be obtained by
subtracting total departures from total arrivals
by that time.
Time Event Type Total Platforms Needed
at this Time
9:00 Arrival 1
9:10 Departure 0
9:40 Arrival 1
9:50 Arrival 2
11:00 Arrival 3
11:20 Departure 2
11:30 Departure 1
12:00 Departure 0
15:00 Arrival 1
18:00 Arrival 2
19:00 Departure 1
20:00 Departure 0
Minimum Platforms needed on railway station
= Maximum platforms needed at any time
= 3
Note: This approach assumes that trains are arriving and departing on the same date.
Algorithm:
Sort the arrival and departure times of trains.Create two pointers i=0, and j=0, and a variable to store ans and current count platRun a loop while i<n and j<n and compare the ith element of arrival array and jth element of departure array.If the arrival time is less than or equal to departure then one more platform is needed so increase the count, i.e., plat++ and increment iElse if the arrival time is greater than departure then one less platform is needed to decrease the count, i.e., plat– and increment jUpdate the ans, i.e. ans = max(ans, plat).
Sort the arrival and departure times of trains.
Create two pointers i=0, and j=0, and a variable to store ans and current count plat
Run a loop while i<n and j<n and compare the ith element of arrival array and jth element of departure array.
If the arrival time is less than or equal to departure then one more platform is needed so increase the count, i.e., plat++ and increment i
Else if the arrival time is greater than departure then one less platform is needed to decrease the count, i.e., plat– and increment j
Update the ans, i.e. ans = max(ans, plat).
Implementation: This doesn’t create a single sorted list of all events, rather it individually sorts arr[] and dep[] arrays, and then uses the merge process of merge sort to process them together as a single sorted array.
C++
C
Java
Python3
C#
PHP
Javascript
// Program to find minimum number of platforms// required on a railway station#include <algorithm>#include <iostream> using namespace std; // Returns minimum number of platforms requiredint findPlatform(int arr[], int dep[], int n){ // Sort arrival and departure arrays sort(arr, arr + n); sort(dep, dep + n); // plat_needed indicates number of platforms // needed at a time int plat_needed = 1, result = 1; int i = 1, j = 0; // Similar to merge in merge sort to process // all events in sorted order while (i < n && j < n) { // If next event in sorted order is arrival, // increment count of platforms needed if (arr[i] <= dep[j]) { plat_needed++; i++; } // Else decrement count of platforms needed else if (arr[i] > dep[j]) { plat_needed--; j++; } // Update result if needed if (plat_needed > result) result = plat_needed; } return result;} // Driver codeint main(){ int arr[] = { 900, 940, 950, 1100, 1500, 1800 }; int dep[] = { 910, 1200, 1120, 1130, 1900, 2000 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findPlatform(arr, dep, n); return 0;}
// C program to find minimum number of platforms required on a railway station // Importing the required header files#include <stdio.h>#include <stdlib.h> // Creating MACRO for finding the maximum number#define max(x, y)(((x) > (y)) ? (x) : (y))// Creating MACRO for finding the minimum number#define min(x, y)(((x) < (y)) ? (x) : (y)) // below method is needed for the sort function// compare function, compares two elementsint compare (const void * num1, const void * num2) { if(*(int*)num1 > *(int*)num2) return 1; else return -1;} // Returns minimum number of platforms requiredint findPlatform(int arr[], int dep[], int n){ // Sort arrival and departure arrays qsort(arr, n, sizeof(int), compare); qsort(dep, n, sizeof(int), compare); // plat_needed indicates number of platforms // needed at a time int plat_needed = 1, result = 1; int i = 1, j = 0; // Similar to merge in merge sort to process // all events in sorted order while (i < n && j < n) { // If next event in sorted order is arrival, // increment count of platforms needed if (arr[i] <= dep[j]) { plat_needed++; i++; } // Else decrement count of platforms needed else if (arr[i] > dep[j]) { plat_needed--; j++; } // Update result if needed if (plat_needed > result) result = plat_needed; } return result;} // Driver Codeint main(){ int arr[] = { 900, 940, 950, 1100, 1500, 1800 }; int dep[] = { 910, 1200, 1120, 1130, 1900, 2000 }; int n = sizeof(arr) / sizeof(arr[0]); printf("%d", findPlatform(arr, dep, n)); return 0;}
// Program to find minimum number of platforms import java.util.*; class GFG { // Returns minimum number of platforms required static int findPlatform(int arr[], int dep[], int n) { // Sort arrival and departure arrays Arrays.sort(arr); Arrays.sort(dep); // plat_needed indicates number of platforms // needed at a time int plat_needed = 1, result = 1; int i = 1, j = 0; // Similar to merge in merge sort to process // all events in sorted order while (i < n && j < n) { // If next event in sorted order is arrival, // increment count of platforms needed if (arr[i] <= dep[j]) { plat_needed++; i++; } // Else decrement count of platforms needed else if (arr[i] > dep[j]) { plat_needed--; j++; } // Update result if needed if (plat_needed > result) result = plat_needed; } return result; } // Driver code public static void main(String[] args) { int arr[] = { 900, 940, 950, 1100, 1500, 1800 }; int dep[] = { 910, 1200, 1120, 1130, 1900, 2000 }; int n = arr.length; System.out.println("Minimum Number of Platforms Required = " + findPlatform(arr, dep, n)); }}
# Program to find minimum# number of platforms# required on a railway# station # Returns minimum number# of platforms required def findPlatform(arr, dep, n): # Sort arrival and # departure arrays arr.sort() dep.sort() # plat_needed indicates # number of platforms # needed at a time plat_needed = 1 result = 1 i = 1 j = 0 # Similar to merge in # merge sort to process # all events in sorted order while (i < n and j < n): # If next event in sorted # order is arrival, # increment count of # platforms needed if (arr[i] <= dep[j]): plat_needed += 1 i += 1 # Else decrement count # of platforms needed elif (arr[i] > dep[j]): plat_needed -= 1 j += 1 # Update result if needed if (plat_needed > result): result = plat_needed return result # Driver code arr = [900, 940, 950, 1100, 1500, 1800]dep = [910, 1200, 1120, 1130, 1900, 2000]n = len(arr) print("Minimum Number of Platforms Required = ", findPlatform(arr, dep, n)) # This code is contributed# by Anant Agarwal.
// C# program to find minimum number// of platformsusing System; class GFG { // Returns minimum number of platforms // required static int findPlatform(int[] arr, int[] dep, int n) { // Sort arrival and departure arrays Array.Sort(arr); Array.Sort(dep); // plat_needed indicates number of // platforms needed at a time int plat_needed = 1, result = 1; int i = 1, j = 0; // Similar to merge in merge sort // to process all events in sorted // order while (i < n && j < n) { // If next event in sorted order // is arrival, increment count // of platforms needed if (arr[i] <= dep[j]) { plat_needed++; i++; } // Else decrement count of // platforms needed else if (arr[i] > dep[j]) { plat_needed--; j++; } // Update result if needed if (plat_needed > result) result = plat_needed; } return result; } // Driver code public static void Main() { int[] arr = { 900, 940, 950, 1100, 1500, 1800 }; int[] dep = { 910, 1200, 1120, 1130, 1900, 2000 }; int n = arr.Length; Console.Write("Minimum Number of " + " Platforms Required = " + findPlatform(arr, dep, n)); }} // This code os contributed by nitin mittal.
<?php// PHP Program to find minimum number// of platforms required on a railway// station // Returns minimum number of// platforms requiredfunction findPlatform($arr, $dep, $n){ // Sort arrival and // departure arrays sort($arr); sort($dep); // plat_needed indicates // number of platforms // needed at a time $plat_needed = 1; $result = 1; $i = 1; $j = 0; // Similar to merge in // merge sort to process // all events in sorted order while ($i < $n and $j < $n) { // If next event in sorted // order is arrival, increment // count of platforms needed if ($arr[$i] <= $dep[$j]) { $plat_needed++; $i++; } // Else decrement count // of platforms needed elseif ($arr[$i] > $dep[$j]) { $plat_needed--; $j++; } // Update result if needed if ($plat_needed > $result) $result = $plat_needed; } return $result;} // Driver Code $arr = array(900, 940, 950, 1100, 1500, 1800); $dep = array(910, 1200, 1120, 1130, 1900, 2000); $n = count($arr); echo "Minimum Number of Platforms Required = ", findPlatform($arr, $dep, $n); // This code is contributed by anuj_67.?>
<script>// Javascript Program to find minimum number// of platforms required on a railway// station // Returns minimum number of// platforms requiredfunction findPlatform(arr, dep, n){ // Sort arrival and // departure arrays arr = arr.sort((a,b) => a-b)); dep = dep.sort((a,b) => a-b)); // plat_needed indicates // number of platforms // needed at a time let plat_needed = 1; let result = 1; let i = 1; let j = 0; // Similar to merge in // merge sort to process // all events in sorted order while (i < n && j < n) { // If next event in sorted // order is arrival, increment // count of platforms needed if (arr[i] <= dep[j]) { plat_needed++; i++; } // Else decrement count // of platforms needed else if (arr[i] > dep[j]) { plat_needed--; j++; } // Update result if needed if (plat_needed > result) result = plat_needed; } return result;} // Driver Code let arr = new Array(900, 940, 950, 1100, 1500, 1800); let dep = new Array(910, 1200, 1120, 1130, 1900, 2000); let n = arr.length; document.write("Minimum Number of Platforms Required = " + findPlatform(arr, dep, n)); // This code is contributed by Saurabh Jaiswal.</script>
3
Time Complexity: O(N * log N), One traversal O(n) of both the array is needed after sorting O(N * log N).Auxiliary space: O(1), As no extra space is required.
Note: There is one more approach to the problem, which uses O(n) extra space and O(n) time to solve the problem: Minimum Number of Platforms Required for a Railway/Bus Station | Set 2 (Map-based approach)
This article is contributed by Shivam. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
sidsm009
nitin mittal
vt_m
harrypotter0
Vidit_Gupta
andrew1234
preinpost0
RohitOberoi
parasmadan15
akshitsaxenaa09
_saurabh_jaiswal
avanitrachhadiya2155
simmytarika5
ganesh227
nmdhussain
amnindersingh1414
abhishekpurohit838
harendrakumar123
karandeep1234
Accolite
Airtel
Amazon
Hike
Paytm
Greedy
Paytm
Accolite
Amazon
Hike
Airtel
Greedy
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n10 Jul, 2022"
},
{
"code": null,
"e": 337,
"s": 54,
"text": "Given the arrival and departure times of all trains that reach a railway station, the task is to find the minimum number of platforms required for the railway station so that no train waits. We are given two arrays that represent the arrival and departure times of trains that stop."
},
{
"code": null,
"e": 349,
"s": 337,
"text": "Examples: "
},
{
"code": null,
"e": 547,
"s": 349,
"text": "Input: arr[] = {9:00, 9:40, 9:50, 11:00, 15:00, 18:00} dep[] = {9:10, 12:00, 11:20, 11:30, 19:00, 20:00} Output: 3 Explanation: There are at-most three trains at a time (time between 9:40 to 12:00)"
},
{
"code": null,
"e": 649,
"s": 547,
"text": "Input: arr[] = {9:00, 9:40} dep[] = {9:10, 12:00} Output: 1 Explanation: Only one platform is needed."
},
{
"code": null,
"e": 878,
"s": 649,
"text": "Naive Approach: The idea is to take every interval one by one and find the number of intervals that overlap with it. Keep track of the maximum number of intervals that overlap with an interval. Finally, return the maximum value."
},
{
"code": null,
"e": 912,
"s": 878,
"text": "Follow the steps mentioned below:"
},
{
"code": null,
"e": 1003,
"s": 912,
"text": "Run two nested loops, the outer loop from start to end and the inner loop from i+1 to end."
},
{
"code": null,
"e": 1112,
"s": 1003,
"text": "For every iteration of the outer loop, find the count of intervals that intersect with the current interval."
},
{
"code": null,
"e": 1201,
"s": 1112,
"text": "Update the answer with the maximum count of overlap in each iteration of the outer loop."
},
{
"code": null,
"e": 1219,
"s": 1201,
"text": "Print the answer."
},
{
"code": null,
"e": 1236,
"s": 1219,
"text": "Implementation: "
},
{
"code": null,
"e": 1242,
"s": 1236,
"text": "C++14"
},
{
"code": null,
"e": 1244,
"s": 1242,
"text": "C"
},
{
"code": null,
"e": 1252,
"s": 1244,
"text": "Python3"
},
{
"code": null,
"e": 1257,
"s": 1252,
"text": "Java"
},
{
"code": null,
"e": 1260,
"s": 1257,
"text": "C#"
},
{
"code": null,
"e": 1271,
"s": 1260,
"text": "Javascript"
},
{
"code": "// C++ program to implement the above approach#include <bits/stdc++.h>using namespace std; // Function to find the minimum number// of platforms requiredint findPlatform(int arr[], int dep[], int n){ // plat_needed indicates number of platforms // needed at a time int plat_needed = 1, result = 1; int i = 1, j = 0; // run a nested loop to find overlap for (int i = 0; i < n; i++) { // minimum platform plat_needed = 1; for (int j = i + 1; j < n; j++) { // check for overlap if (max(arr[i], arr[j]) <= min(dep[i], dep[j])) plat_needed++; } // update result result = max(result, plat_needed); } return result;} // Driver Codeint main(){ int arr[] = { 9775, 494, 252, 1680 }; int dep[] = { 2052, 2254, 1395, 2130 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findPlatform(arr, dep, n); return 0;}",
"e": 2193,
"s": 1271,
"text": null
},
{
"code": "// C program to find minimum number of platforms required on// a railway station // Importing the required header files#include <stdio.h> // Creating MACRO for finding the maximum number#define max(x, y) (((x) > (y)) ? (x) : (y)) // Creating MACRO for finding the minimum number#define min(x, y) (((x) < (y)) ? (x) : (y)) // Function to returns the minimum number of platforms// requiredint findPlatform(int arr[], int dep[], int n){ // plat_needed indicates number of platforms // needed at a time int plat_needed = 1, result = 1; int i = 1, j = 0; // run a nested loop to find overlap for (int i = 0; i < n; i++) { // minimum platform plat_needed = 1; for (int j = i + 1; j < n; j++) { // check for overlap if (max(arr[i], arr[j]) <= min(dep[i], dep[j])) plat_needed++; } // update result result = max(result, plat_needed); } return result;} // Driver Codeint main(){ int arr[] = { 900, 940, 950, 1100, 1500, 1800 }; int dep[] = { 910, 1200, 1120, 1130, 1900, 2000 }; int n = sizeof(arr) / sizeof(arr[0]); printf(\"%d\", findPlatform(arr, dep, n)); return 0;}",
"e": 3377,
"s": 2193,
"text": null
},
{
"code": "# Program to find minimum number of platforms# required on a railway station def findPlatform(arr, dep, n): ''' Accepts two arrays with arrival and departure time and the size of the array Returns minimum number of platforms required ''' # plat_needed indicates number of platforms # needed at a time plat_needed = 1 result = 1 # run a nested loop to find overlap for i in range(n): # minimum platform needed plat_needed = 1 for j in range(i+1, n): # check for overlap if (max(arr[i], arr[j]) <= min(dep[i], dep[j])): plat_needed += 1 # update result result = max(result, plat_needed) return result # Driver code def main(): arr = [900, 940, 950, 1100, 1500, 1800] dep = [910, 1200, 1120, 1130, 1900, 2000] n = len(arr) print(\"{}\".format( findPlatform(arr, dep, n))) if __name__ == '__main__': main()",
"e": 4318,
"s": 3377,
"text": null
},
{
"code": "// Program to find minimum number of platforms// required on a railway stationimport java.io.*; class GFG { // Returns minimum number of platforms required public static int findPlatform(int arr[], int dep[], int n) { // plat_needed indicates number of platforms // needed at a time int plat_needed = 1, result = 1; int i = 1, j = 0; // run a nested loop to find overlap for (i = 0; i < n; i++) { // minimum platform plat_needed = 1; for (j = i + 1; j < n; j++) { // check for overlap if (Math.max(arr[i], arr[j]) <= Math.min(dep[i], dep[j])) plat_needed++; } // update result result = Math.max(result, plat_needed); } return result; } // Driver Code public static void main(String[] args) { int arr[] = { 900, 940, 950, 1100, 1500, 1800 }; int dep[] = { 910, 1200, 1120, 1130, 1900, 2000 }; int n = 6; System.out.println(findPlatform(arr, dep, n)); }}",
"e": 5454,
"s": 4318,
"text": null
},
{
"code": "// Program to find minimum number of platforms// required on a railway station using System; public class GFG { // Returns minimum number of platforms required public static int findPlatform(int[] arr, int[] dep, int n) { // plat_needed indicates number of platforms // needed at a time int plat_needed = 1, result = 1; int i = 1, j = 0; // run a nested loop to find overlap for (i = 0; i < n; i++) { // minimum platform plat_needed = 1; for (j = i + 1; j < n; j++) { // check for overlap if (Math.Max(arr[i], arr[j]) <= Math.Min(dep[i], dep[j])) plat_needed++; } // update result result = Math.Max(result, plat_needed); } return result; } // Driver Code static public void Main() { int[] arr = { 900, 940, 950, 1100, 1500, 1800 }; int[] dep = { 910, 1200, 1120, 1130, 1900, 2000 }; int n = 6; Console.WriteLine(findPlatform(arr, dep, n)); }}",
"e": 6583,
"s": 5454,
"text": null
},
{
"code": "<script>// Program to find minimum number of platforms// required on a railway station function max(a,b){ if(a==b) return a; else{ if(a>b) return a; else return b; }} // Returns minimum number of platforms requiredfunction findPlatform( arr, dep, n){ // plat_needed indicates number of platforms // needed at a time var plat_needed = 1, result = 1; var i = 1, j = 0; // run a nested loop to find overlap for (var i = 0; i < n; i++) { // minimum platform plat_needed = 1; for (var j = i + 1; j < n; j++) { // check for overlap if (max(arr[i], arr[j]) <= min(dep[i], dep[j])) plat_needed++; } // update result result = max(result, plat_needed); } return result;} var arr = [ 900, 940, 950, 1100, 1500, 1800 ]; var dep = [ 910, 1200, 1120, 1130, 1900, 2000 ]; var n =6; document.write(\"Minimum Number of Platforms Required = \" +findPlatform(arr, dep, n)); </script>",
"e": 7627,
"s": 6583,
"text": null
},
{
"code": null,
"e": 7629,
"s": 7627,
"text": "3"
},
{
"code": null,
"e": 7746,
"s": 7629,
"text": "Time Complexity: O(n2), Two nested loops traverse the array.Auxiliary space: O(1), As no extra space is required. "
},
{
"code": null,
"e": 8034,
"s": 7746,
"text": "Efficient Approach: Store the arrival time and departure time and sort them based on arrival time then check if the departure time of the next train is smaller than the departure time of the previous train if it is smaller then increment the number of the platforms needed otherwise not."
},
{
"code": null,
"e": 8068,
"s": 8034,
"text": "Follow the steps mentioned below:"
},
{
"code": null,
"e": 8165,
"s": 8068,
"text": "Store the arrival time and departure time in array arr and sort this array based on arrival time"
},
{
"code": null,
"e": 8305,
"s": 8165,
"text": "Declare a priority queue(min-heap) and store the departure time of the first train and also declare a counter cnt and initialize it with 1."
},
{
"code": null,
"e": 8639,
"s": 8305,
"text": "Iterate over arr from 1 to n-1 check if the arrival time of current train is less than or equals to the departure time of previous train which is kept on top of the priority queueIf true, then push the new departure time and increment the counter cntotherwise, we pop() the departure timepush new departure time in the priority queue"
},
{
"code": null,
"e": 8942,
"s": 8639,
"text": "check if the arrival time of current train is less than or equals to the departure time of previous train which is kept on top of the priority queueIf true, then push the new departure time and increment the counter cntotherwise, we pop() the departure timepush new departure time in the priority queue"
},
{
"code": null,
"e": 9014,
"s": 8942,
"text": "If true, then push the new departure time and increment the counter cnt"
},
{
"code": null,
"e": 9053,
"s": 9014,
"text": "otherwise, we pop() the departure time"
},
{
"code": null,
"e": 9099,
"s": 9053,
"text": "push new departure time in the priority queue"
},
{
"code": null,
"e": 9124,
"s": 9099,
"text": "Finally, return the cnt."
},
{
"code": null,
"e": 9128,
"s": 9124,
"text": "C++"
},
{
"code": null,
"e": 9133,
"s": 9128,
"text": "Java"
},
{
"code": "// C++ program to implement the above approach#include <bits/stdc++.h>using namespace std; // Function to find the minimum number// of platforms requiredint findPlatform(int arr[], int dep[], int n){ // Store the arrival and departure time vector<pair<int, int> > arr2(n); for (int i = 0; i < n; i++) { arr2[i] = { arr[i], dep[i] }; } // Sort arr2 based on arival time sort(arr2.begin(), arr2.end()); priority_queue<int, vector<int>, greater<int> > p; int count = 1; p.push(arr2[0].second); for (int i = 1; i < n; i++) { // Check if arrival time of current train // is less than or equals to depature time // of previous train if (p.top() >= arr2[i].first) { count++; } else { p.pop(); } p.push(arr2[i].second); } // Return the number of train required return count;} // Driver Codeint main(){ int arr[] = { 900, 940, 950, 1100, 1500, 1800 }; int dep[] = { 910, 1200, 1120, 1130, 1900, 2000 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findPlatform(arr, dep, n); return 0;}",
"e": 10256,
"s": 9133,
"text": null
},
{
"code": "// Java code to implement the approachimport java.io.*;import java.util.*; class imp3 { // Function to find the minimum number // of platforms required static int findPlatform(int arr[], int dep[], int n) { // Store the arrival and departure time int[][] arr2 = new int[n][2]; for (int i = 0; i < n; i++) { arr2[i] = new int[] { arr[i], dep[i] }; } // Sort arr2 based on arival time Arrays.sort(arr2, (A, B) -> { return A[0] - B[0]; }); PriorityQueue<Integer> p = new PriorityQueue<>(); int count = 1; p.add(arr2[0][1]); for (int i = 1; i < n; i++) { // Check if arrival time of current train // is less than or equals to depature time // of previous train if (p.peek() >= arr2[i][0]) { count++; } else { p.remove(); } p.add(arr2[i][1]); } // Return the number of platform required return count; } public static void main(String[] args) { int arr[] = { 900, 940, 950, 1100, 1500, 1800 }; int dep[] = { 910, 1200, 1120, 1130, 1900, 2000 }; int n = arr.length; System.out.println(findPlatform(arr, dep, n)); }}// This code is contributed by Karandeep1234",
"e": 11606,
"s": 10256,
"text": null
},
{
"code": null,
"e": 11608,
"s": 11606,
"text": "3"
},
{
"code": null,
"e": 11658,
"s": 11608,
"text": "Time Complexity: O(N*log(N))Auxiliary Space: O(N)"
},
{
"code": null,
"e": 11875,
"s": 11658,
"text": "Another efficient Approach: The idea is to consider all events in sorted order. Once the events are in sorted order, trace the number of trains at any time keeping track of trains that have arrived, but not departed."
},
{
"code": null,
"e": 11885,
"s": 11875,
"text": "Example: "
},
{
"code": null,
"e": 12815,
"s": 11885,
"text": "arr[] = {9:00, 9:40, 9:50, 11:00, 15:00, 18:00}\ndep[] = {9:10, 12:00, 11:20, 11:30, 19:00, 20:00}\n\nAll events are sorted by time.\nTotal platforms at any time can be obtained by\nsubtracting total departures from total arrivals\nby that time.\n\n Time Event Type Total Platforms Needed \n at this Time \n 9:00 Arrival 1\n 9:10 Departure 0\n 9:40 Arrival 1\n 9:50 Arrival 2\n 11:00 Arrival 3 \n 11:20 Departure 2\n 11:30 Departure 1\n 12:00 Departure 0\n 15:00 Arrival 1\n 18:00 Arrival 2 \n 19:00 Departure 1\n 20:00 Departure 0\n\nMinimum Platforms needed on railway station \n= Maximum platforms needed at any time \n= 3"
},
{
"code": null,
"e": 12902,
"s": 12815,
"text": "Note: This approach assumes that trains are arriving and departing on the same date. "
},
{
"code": null,
"e": 12913,
"s": 12902,
"text": "Algorithm:"
},
{
"code": null,
"e": 13469,
"s": 12913,
"text": "Sort the arrival and departure times of trains.Create two pointers i=0, and j=0, and a variable to store ans and current count platRun a loop while i<n and j<n and compare the ith element of arrival array and jth element of departure array.If the arrival time is less than or equal to departure then one more platform is needed so increase the count, i.e., plat++ and increment iElse if the arrival time is greater than departure then one less platform is needed to decrease the count, i.e., plat– and increment jUpdate the ans, i.e. ans = max(ans, plat)."
},
{
"code": null,
"e": 13517,
"s": 13469,
"text": "Sort the arrival and departure times of trains."
},
{
"code": null,
"e": 13602,
"s": 13517,
"text": "Create two pointers i=0, and j=0, and a variable to store ans and current count plat"
},
{
"code": null,
"e": 13712,
"s": 13602,
"text": "Run a loop while i<n and j<n and compare the ith element of arrival array and jth element of departure array."
},
{
"code": null,
"e": 13852,
"s": 13712,
"text": "If the arrival time is less than or equal to departure then one more platform is needed so increase the count, i.e., plat++ and increment i"
},
{
"code": null,
"e": 13987,
"s": 13852,
"text": "Else if the arrival time is greater than departure then one less platform is needed to decrease the count, i.e., plat– and increment j"
},
{
"code": null,
"e": 14030,
"s": 13987,
"text": "Update the ans, i.e. ans = max(ans, plat)."
},
{
"code": null,
"e": 14253,
"s": 14030,
"text": "Implementation: This doesn’t create a single sorted list of all events, rather it individually sorts arr[] and dep[] arrays, and then uses the merge process of merge sort to process them together as a single sorted array. "
},
{
"code": null,
"e": 14257,
"s": 14253,
"text": "C++"
},
{
"code": null,
"e": 14259,
"s": 14257,
"text": "C"
},
{
"code": null,
"e": 14264,
"s": 14259,
"text": "Java"
},
{
"code": null,
"e": 14272,
"s": 14264,
"text": "Python3"
},
{
"code": null,
"e": 14275,
"s": 14272,
"text": "C#"
},
{
"code": null,
"e": 14279,
"s": 14275,
"text": "PHP"
},
{
"code": null,
"e": 14290,
"s": 14279,
"text": "Javascript"
},
{
"code": "// Program to find minimum number of platforms// required on a railway station#include <algorithm>#include <iostream> using namespace std; // Returns minimum number of platforms requiredint findPlatform(int arr[], int dep[], int n){ // Sort arrival and departure arrays sort(arr, arr + n); sort(dep, dep + n); // plat_needed indicates number of platforms // needed at a time int plat_needed = 1, result = 1; int i = 1, j = 0; // Similar to merge in merge sort to process // all events in sorted order while (i < n && j < n) { // If next event in sorted order is arrival, // increment count of platforms needed if (arr[i] <= dep[j]) { plat_needed++; i++; } // Else decrement count of platforms needed else if (arr[i] > dep[j]) { plat_needed--; j++; } // Update result if needed if (plat_needed > result) result = plat_needed; } return result;} // Driver codeint main(){ int arr[] = { 900, 940, 950, 1100, 1500, 1800 }; int dep[] = { 910, 1200, 1120, 1130, 1900, 2000 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findPlatform(arr, dep, n); return 0;}",
"e": 15517,
"s": 14290,
"text": null
},
{
"code": "// C program to find minimum number of platforms required on a railway station // Importing the required header files#include <stdio.h>#include <stdlib.h> // Creating MACRO for finding the maximum number#define max(x, y)(((x) > (y)) ? (x) : (y))// Creating MACRO for finding the minimum number#define min(x, y)(((x) < (y)) ? (x) : (y)) // below method is needed for the sort function// compare function, compares two elementsint compare (const void * num1, const void * num2) { if(*(int*)num1 > *(int*)num2) return 1; else return -1;} // Returns minimum number of platforms requiredint findPlatform(int arr[], int dep[], int n){ // Sort arrival and departure arrays qsort(arr, n, sizeof(int), compare); qsort(dep, n, sizeof(int), compare); // plat_needed indicates number of platforms // needed at a time int plat_needed = 1, result = 1; int i = 1, j = 0; // Similar to merge in merge sort to process // all events in sorted order while (i < n && j < n) { // If next event in sorted order is arrival, // increment count of platforms needed if (arr[i] <= dep[j]) { plat_needed++; i++; } // Else decrement count of platforms needed else if (arr[i] > dep[j]) { plat_needed--; j++; } // Update result if needed if (plat_needed > result) result = plat_needed; } return result;} // Driver Codeint main(){ int arr[] = { 900, 940, 950, 1100, 1500, 1800 }; int dep[] = { 910, 1200, 1120, 1130, 1900, 2000 }; int n = sizeof(arr) / sizeof(arr[0]); printf(\"%d\", findPlatform(arr, dep, n)); return 0;}",
"e": 17193,
"s": 15517,
"text": null
},
{
"code": "// Program to find minimum number of platforms import java.util.*; class GFG { // Returns minimum number of platforms required static int findPlatform(int arr[], int dep[], int n) { // Sort arrival and departure arrays Arrays.sort(arr); Arrays.sort(dep); // plat_needed indicates number of platforms // needed at a time int plat_needed = 1, result = 1; int i = 1, j = 0; // Similar to merge in merge sort to process // all events in sorted order while (i < n && j < n) { // If next event in sorted order is arrival, // increment count of platforms needed if (arr[i] <= dep[j]) { plat_needed++; i++; } // Else decrement count of platforms needed else if (arr[i] > dep[j]) { plat_needed--; j++; } // Update result if needed if (plat_needed > result) result = plat_needed; } return result; } // Driver code public static void main(String[] args) { int arr[] = { 900, 940, 950, 1100, 1500, 1800 }; int dep[] = { 910, 1200, 1120, 1130, 1900, 2000 }; int n = arr.length; System.out.println(\"Minimum Number of Platforms Required = \" + findPlatform(arr, dep, n)); }}",
"e": 18595,
"s": 17193,
"text": null
},
{
"code": "# Program to find minimum# number of platforms# required on a railway# station # Returns minimum number# of platforms required def findPlatform(arr, dep, n): # Sort arrival and # departure arrays arr.sort() dep.sort() # plat_needed indicates # number of platforms # needed at a time plat_needed = 1 result = 1 i = 1 j = 0 # Similar to merge in # merge sort to process # all events in sorted order while (i < n and j < n): # If next event in sorted # order is arrival, # increment count of # platforms needed if (arr[i] <= dep[j]): plat_needed += 1 i += 1 # Else decrement count # of platforms needed elif (arr[i] > dep[j]): plat_needed -= 1 j += 1 # Update result if needed if (plat_needed > result): result = plat_needed return result # Driver code arr = [900, 940, 950, 1100, 1500, 1800]dep = [910, 1200, 1120, 1130, 1900, 2000]n = len(arr) print(\"Minimum Number of Platforms Required = \", findPlatform(arr, dep, n)) # This code is contributed# by Anant Agarwal.",
"e": 19749,
"s": 18595,
"text": null
},
{
"code": "// C# program to find minimum number// of platformsusing System; class GFG { // Returns minimum number of platforms // required static int findPlatform(int[] arr, int[] dep, int n) { // Sort arrival and departure arrays Array.Sort(arr); Array.Sort(dep); // plat_needed indicates number of // platforms needed at a time int plat_needed = 1, result = 1; int i = 1, j = 0; // Similar to merge in merge sort // to process all events in sorted // order while (i < n && j < n) { // If next event in sorted order // is arrival, increment count // of platforms needed if (arr[i] <= dep[j]) { plat_needed++; i++; } // Else decrement count of // platforms needed else if (arr[i] > dep[j]) { plat_needed--; j++; } // Update result if needed if (plat_needed > result) result = plat_needed; } return result; } // Driver code public static void Main() { int[] arr = { 900, 940, 950, 1100, 1500, 1800 }; int[] dep = { 910, 1200, 1120, 1130, 1900, 2000 }; int n = arr.Length; Console.Write(\"Minimum Number of \" + \" Platforms Required = \" + findPlatform(arr, dep, n)); }} // This code os contributed by nitin mittal.",
"e": 21264,
"s": 19749,
"text": null
},
{
"code": "<?php// PHP Program to find minimum number// of platforms required on a railway// station // Returns minimum number of// platforms requiredfunction findPlatform($arr, $dep, $n){ // Sort arrival and // departure arrays sort($arr); sort($dep); // plat_needed indicates // number of platforms // needed at a time $plat_needed = 1; $result = 1; $i = 1; $j = 0; // Similar to merge in // merge sort to process // all events in sorted order while ($i < $n and $j < $n) { // If next event in sorted // order is arrival, increment // count of platforms needed if ($arr[$i] <= $dep[$j]) { $plat_needed++; $i++; } // Else decrement count // of platforms needed elseif ($arr[$i] > $dep[$j]) { $plat_needed--; $j++; } // Update result if needed if ($plat_needed > $result) $result = $plat_needed; } return $result;} // Driver Code $arr = array(900, 940, 950, 1100, 1500, 1800); $dep = array(910, 1200, 1120, 1130, 1900, 2000); $n = count($arr); echo \"Minimum Number of Platforms Required = \", findPlatform($arr, $dep, $n); // This code is contributed by anuj_67.?>",
"e": 22569,
"s": 21264,
"text": null
},
{
"code": "<script>// Javascript Program to find minimum number// of platforms required on a railway// station // Returns minimum number of// platforms requiredfunction findPlatform(arr, dep, n){ // Sort arrival and // departure arrays arr = arr.sort((a,b) => a-b)); dep = dep.sort((a,b) => a-b)); // plat_needed indicates // number of platforms // needed at a time let plat_needed = 1; let result = 1; let i = 1; let j = 0; // Similar to merge in // merge sort to process // all events in sorted order while (i < n && j < n) { // If next event in sorted // order is arrival, increment // count of platforms needed if (arr[i] <= dep[j]) { plat_needed++; i++; } // Else decrement count // of platforms needed else if (arr[i] > dep[j]) { plat_needed--; j++; } // Update result if needed if (plat_needed > result) result = plat_needed; } return result;} // Driver Code let arr = new Array(900, 940, 950, 1100, 1500, 1800); let dep = new Array(910, 1200, 1120, 1130, 1900, 2000); let n = arr.length; document.write(\"Minimum Number of Platforms Required = \" + findPlatform(arr, dep, n)); // This code is contributed by Saurabh Jaiswal.</script>",
"e": 23950,
"s": 22569,
"text": null
},
{
"code": null,
"e": 23952,
"s": 23950,
"text": "3"
},
{
"code": null,
"e": 24111,
"s": 23952,
"text": "Time Complexity: O(N * log N), One traversal O(n) of both the array is needed after sorting O(N * log N).Auxiliary space: O(1), As no extra space is required."
},
{
"code": null,
"e": 24317,
"s": 24111,
"text": "Note: There is one more approach to the problem, which uses O(n) extra space and O(n) time to solve the problem: Minimum Number of Platforms Required for a Railway/Bus Station | Set 2 (Map-based approach) "
},
{
"code": null,
"e": 24480,
"s": 24317,
"text": "This article is contributed by Shivam. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 24489,
"s": 24480,
"text": "sidsm009"
},
{
"code": null,
"e": 24502,
"s": 24489,
"text": "nitin mittal"
},
{
"code": null,
"e": 24507,
"s": 24502,
"text": "vt_m"
},
{
"code": null,
"e": 24520,
"s": 24507,
"text": "harrypotter0"
},
{
"code": null,
"e": 24532,
"s": 24520,
"text": "Vidit_Gupta"
},
{
"code": null,
"e": 24543,
"s": 24532,
"text": "andrew1234"
},
{
"code": null,
"e": 24554,
"s": 24543,
"text": "preinpost0"
},
{
"code": null,
"e": 24566,
"s": 24554,
"text": "RohitOberoi"
},
{
"code": null,
"e": 24579,
"s": 24566,
"text": "parasmadan15"
},
{
"code": null,
"e": 24595,
"s": 24579,
"text": "akshitsaxenaa09"
},
{
"code": null,
"e": 24612,
"s": 24595,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 24633,
"s": 24612,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 24646,
"s": 24633,
"text": "simmytarika5"
},
{
"code": null,
"e": 24656,
"s": 24646,
"text": "ganesh227"
},
{
"code": null,
"e": 24667,
"s": 24656,
"text": "nmdhussain"
},
{
"code": null,
"e": 24685,
"s": 24667,
"text": "amnindersingh1414"
},
{
"code": null,
"e": 24704,
"s": 24685,
"text": "abhishekpurohit838"
},
{
"code": null,
"e": 24721,
"s": 24704,
"text": "harendrakumar123"
},
{
"code": null,
"e": 24735,
"s": 24721,
"text": "karandeep1234"
},
{
"code": null,
"e": 24744,
"s": 24735,
"text": "Accolite"
},
{
"code": null,
"e": 24751,
"s": 24744,
"text": "Airtel"
},
{
"code": null,
"e": 24758,
"s": 24751,
"text": "Amazon"
},
{
"code": null,
"e": 24763,
"s": 24758,
"text": "Hike"
},
{
"code": null,
"e": 24769,
"s": 24763,
"text": "Paytm"
},
{
"code": null,
"e": 24776,
"s": 24769,
"text": "Greedy"
},
{
"code": null,
"e": 24782,
"s": 24776,
"text": "Paytm"
},
{
"code": null,
"e": 24791,
"s": 24782,
"text": "Accolite"
},
{
"code": null,
"e": 24798,
"s": 24791,
"text": "Amazon"
},
{
"code": null,
"e": 24803,
"s": 24798,
"text": "Hike"
},
{
"code": null,
"e": 24810,
"s": 24803,
"text": "Airtel"
},
{
"code": null,
"e": 24817,
"s": 24810,
"text": "Greedy"
}
] |
Ways to sort list of dictionaries by values in Python – Using lambda function
|
05 Jul, 2022
In this article, we will cover how to sort a dictionary by value in Python.
Sorting has always been a useful utility in day-to-day programming. Dictionary in Python is widely used in many applications ranging from competitive domain to developer domain(e.g. handling JSON data). Having the knowledge to sort dictionaries according to their values can prove useful in such cases.
There are 2 ways to achieve this sorting:
This article deals with sorting using the lambda function and using the “sorted()” inbuilt function. Various variations can also be achieved for sorting the dictionaries.
For descending order : Use “reverse = True” in addition to the sorted() function.
For sorting w.r.t multiple values: Separate by “comma” mentioning the correct order in which sorting has to be performed.
Example:
Python3
# Python code demonstrate the working of# sorted() with lambda # Initializing list of dictionarieslis = [{"name": "Nandini", "age": 20}, {"name": "Manjeet", "age": 20}, {"name": "Nikhil", "age": 19}] # using sorted and lambda to print list sorted# by ageprint("The list printed sorting by age: ")print(sorted(lis, key=lambda i: i['age'])) print("\r") # using sorted and lambda to print list sorted# by both age and name. Notice that "Manjeet"# now comes before "Nandini"print("The list printed sorting by age and name: ")print(sorted(lis, key=lambda i: (i['age'], i['name']))) print("\r") # using sorted and lambda to print list sorted# by age in descending orderprint("The list printed sorting by age in descending order: ")print(sorted(lis, key=lambda i: i['age'], reverse=True))
Output:
The list printed sorting by age:
[{'age': 19, 'name': 'Nikhil'}, {'age': 20, 'name': 'Nandini'}, {'age': 20, 'name': 'Manjeet'}]
The list printed sorting by age and name:
[{'age': 19, 'name': 'Nikhil'}, {'age': 20, 'name': 'Manjeet'}, {'age': 20, 'name': 'Nandini'}]
The list printed sorting by age in descending order:
[{'age': 20, 'name': 'Nandini'}, {'age': 20, 'name': 'Manjeet'}, {'age': 19, 'name': 'Nikhil'}]
Next Article -> Ways to sort list of dictionaries by values in Python – Using itemgetter
shubham_singh
anshitaagarwal
amartyaghoshgfg
surajkumarguptaintern
Python dictionary-programs
python-dict
python-lambda
Python
python-dict
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": 52,
"s": 24,
"text": "\n05 Jul, 2022"
},
{
"code": null,
"e": 129,
"s": 52,
"text": "In this article, we will cover how to sort a dictionary by value in Python. "
},
{
"code": null,
"e": 432,
"s": 129,
"text": "Sorting has always been a useful utility in day-to-day programming. Dictionary in Python is widely used in many applications ranging from competitive domain to developer domain(e.g. handling JSON data). Having the knowledge to sort dictionaries according to their values can prove useful in such cases."
},
{
"code": null,
"e": 474,
"s": 432,
"text": "There are 2 ways to achieve this sorting:"
},
{
"code": null,
"e": 648,
"s": 476,
"text": "This article deals with sorting using the lambda function and using the “sorted()” inbuilt function. Various variations can also be achieved for sorting the dictionaries. "
},
{
"code": null,
"e": 730,
"s": 648,
"text": "For descending order : Use “reverse = True” in addition to the sorted() function."
},
{
"code": null,
"e": 852,
"s": 730,
"text": "For sorting w.r.t multiple values: Separate by “comma” mentioning the correct order in which sorting has to be performed."
},
{
"code": null,
"e": 861,
"s": 852,
"text": "Example:"
},
{
"code": null,
"e": 869,
"s": 861,
"text": "Python3"
},
{
"code": "# Python code demonstrate the working of# sorted() with lambda # Initializing list of dictionarieslis = [{\"name\": \"Nandini\", \"age\": 20}, {\"name\": \"Manjeet\", \"age\": 20}, {\"name\": \"Nikhil\", \"age\": 19}] # using sorted and lambda to print list sorted# by ageprint(\"The list printed sorting by age: \")print(sorted(lis, key=lambda i: i['age'])) print(\"\\r\") # using sorted and lambda to print list sorted# by both age and name. Notice that \"Manjeet\"# now comes before \"Nandini\"print(\"The list printed sorting by age and name: \")print(sorted(lis, key=lambda i: (i['age'], i['name']))) print(\"\\r\") # using sorted and lambda to print list sorted# by age in descending orderprint(\"The list printed sorting by age in descending order: \")print(sorted(lis, key=lambda i: i['age'], reverse=True))",
"e": 1663,
"s": 869,
"text": null
},
{
"code": null,
"e": 1671,
"s": 1663,
"text": "Output:"
},
{
"code": null,
"e": 2092,
"s": 1671,
"text": "The list printed sorting by age: \n[{'age': 19, 'name': 'Nikhil'}, {'age': 20, 'name': 'Nandini'}, {'age': 20, 'name': 'Manjeet'}]\n\nThe list printed sorting by age and name: \n[{'age': 19, 'name': 'Nikhil'}, {'age': 20, 'name': 'Manjeet'}, {'age': 20, 'name': 'Nandini'}]\n\nThe list printed sorting by age in descending order: \n[{'age': 20, 'name': 'Nandini'}, {'age': 20, 'name': 'Manjeet'}, {'age': 19, 'name': 'Nikhil'}]"
},
{
"code": null,
"e": 2181,
"s": 2092,
"text": "Next Article -> Ways to sort list of dictionaries by values in Python – Using itemgetter"
},
{
"code": null,
"e": 2195,
"s": 2181,
"text": "shubham_singh"
},
{
"code": null,
"e": 2210,
"s": 2195,
"text": "anshitaagarwal"
},
{
"code": null,
"e": 2226,
"s": 2210,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 2248,
"s": 2226,
"text": "surajkumarguptaintern"
},
{
"code": null,
"e": 2275,
"s": 2248,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 2287,
"s": 2275,
"text": "python-dict"
},
{
"code": null,
"e": 2301,
"s": 2287,
"text": "python-lambda"
},
{
"code": null,
"e": 2308,
"s": 2301,
"text": "Python"
},
{
"code": null,
"e": 2320,
"s": 2308,
"text": "python-dict"
},
{
"code": null,
"e": 2418,
"s": 2320,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2436,
"s": 2418,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2478,
"s": 2436,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2500,
"s": 2478,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2535,
"s": 2500,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2561,
"s": 2535,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2593,
"s": 2561,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2622,
"s": 2593,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2649,
"s": 2622,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2670,
"s": 2649,
"text": "Python OOPs Concepts"
}
] |
JavaFX | VBox Class
|
06 Sep, 2018
VBox is a part of JavaFX. VBox lays out its children in form of vertical columns. If the vbox has a border and/or padding set, then the contents will be layed out within those insets. VBox class extends Pane class.
Constructor of the class:
VBox(): Creates a VBox layout with spacing = 0 and alignment at TOP_LEFT.VBox(double s): Creates a new VBox with specified spacing between children.VBox(double s, Node... c): Creates a new VBox with specified nodes and spacing between them.VBox(Node... c): Creates an VBox layout with spacing = 0.
VBox(): Creates a VBox layout with spacing = 0 and alignment at TOP_LEFT.
VBox(double s): Creates a new VBox with specified spacing between children.
VBox(double s, Node... c): Creates a new VBox with specified nodes and spacing between them.
VBox(Node... c): Creates an VBox layout with spacing = 0.
Commonly Used Methods:
Below programs illustrate the use of VBox class:
Java Program to create a VBox and add it to the stage: In this program we will create a VBox named vbox. We will create a label and add it to the vbox. We will also create some buttons and add them to the VBox using the getChildren().add() function. Now create a scene and add the vbox to the scene and add the scene to the stage and call show() function to display the final results.// Java Program to create a VBox // and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.Group; public class VBOX_1 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("VBox"); // create a VBox VBox vbox = new VBox(); // create a label Label label = new Label("this is VBox example"); // add label to vbox vbox.getChildren().add(label); // add buttons to VBox for (int i = 0; i < 10; i++) { vbox.getChildren().add(new Button("Button " + (int)(i + 1))); } // create a scene Scene scene = new Scene(vbox, 300, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:Java Program to create a VBox, add spaces between its elements and add it to the stage: In this program we will create a VBox named vbox. We will set the spacing by passing a double value of space as an argument to the constructor. Now create a label and add it to the vbox. To add some buttons to the VBox use the getChildren().add() function. Finally, create a scene and add the vbox to the scene and add the scene to the stage and call show() function to display the final results.// Java Program to create a VBox, add // spaces between its elements and add// it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.Group; public class VBOX_2 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("VBox"); // create a VBox VBox vbox = new VBox(10); // create a label Label label = new Label("this is VBox example"); // add label to vbox vbox.getChildren().add(label); // add buttons to VBox for (int i = 0; i < 5; i++) { vbox.getChildren().add(new Button("Button " + (int)(i + 1))); } // create a scene Scene scene = new Scene(vbox, 300, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:Java Program to create a VBox, add spaces between its elements, set an alignment and add it to the stage: In this program we will create a VBox named vbox. We will set the spacing by passing a double value of space as an argument to the constructor. Set the alignment of the VBox using the setAlignment() function. Then create a label and add it to the vbox. Add some buttons to the VBox using the getChildren().add() function. Finally, create a scene and add the vbox to the scene and add the scene to the stage and call show() function to display the final results.// Java Program to create a VBox, add spaces// between its elements, set an alignment // and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.Group;import javafx.geometry.Pos; public class VBOX_3 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("VBox"); // create a VBox VBox vbox = new VBox(10); // create a label Label label = new Label("this is VBox example"); // add label to vbox vbox.getChildren().add(label); // set alignment vbox.setAlignment(Pos.CENTER); // add buttons to VBox for (int i = 0; i < 5; i++) { vbox.getChildren().add(new Button("Button " + (int)(i + 1))); } // create a scene Scene scene = new Scene(vbox, 300, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:
Java Program to create a VBox and add it to the stage: In this program we will create a VBox named vbox. We will create a label and add it to the vbox. We will also create some buttons and add them to the VBox using the getChildren().add() function. Now create a scene and add the vbox to the scene and add the scene to the stage and call show() function to display the final results.// Java Program to create a VBox // and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.Group; public class VBOX_1 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("VBox"); // create a VBox VBox vbox = new VBox(); // create a label Label label = new Label("this is VBox example"); // add label to vbox vbox.getChildren().add(label); // add buttons to VBox for (int i = 0; i < 10; i++) { vbox.getChildren().add(new Button("Button " + (int)(i + 1))); } // create a scene Scene scene = new Scene(vbox, 300, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:
// Java Program to create a VBox // and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.Group; public class VBOX_1 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("VBox"); // create a VBox VBox vbox = new VBox(); // create a label Label label = new Label("this is VBox example"); // add label to vbox vbox.getChildren().add(label); // add buttons to VBox for (int i = 0; i < 10; i++) { vbox.getChildren().add(new Button("Button " + (int)(i + 1))); } // create a scene Scene scene = new Scene(vbox, 300, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}
Output:
Java Program to create a VBox, add spaces between its elements and add it to the stage: In this program we will create a VBox named vbox. We will set the spacing by passing a double value of space as an argument to the constructor. Now create a label and add it to the vbox. To add some buttons to the VBox use the getChildren().add() function. Finally, create a scene and add the vbox to the scene and add the scene to the stage and call show() function to display the final results.// Java Program to create a VBox, add // spaces between its elements and add// it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.Group; public class VBOX_2 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("VBox"); // create a VBox VBox vbox = new VBox(10); // create a label Label label = new Label("this is VBox example"); // add label to vbox vbox.getChildren().add(label); // add buttons to VBox for (int i = 0; i < 5; i++) { vbox.getChildren().add(new Button("Button " + (int)(i + 1))); } // create a scene Scene scene = new Scene(vbox, 300, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:
// Java Program to create a VBox, add // spaces between its elements and add// it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.Group; public class VBOX_2 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("VBox"); // create a VBox VBox vbox = new VBox(10); // create a label Label label = new Label("this is VBox example"); // add label to vbox vbox.getChildren().add(label); // add buttons to VBox for (int i = 0; i < 5; i++) { vbox.getChildren().add(new Button("Button " + (int)(i + 1))); } // create a scene Scene scene = new Scene(vbox, 300, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}
Output:
Java Program to create a VBox, add spaces between its elements, set an alignment and add it to the stage: In this program we will create a VBox named vbox. We will set the spacing by passing a double value of space as an argument to the constructor. Set the alignment of the VBox using the setAlignment() function. Then create a label and add it to the vbox. Add some buttons to the VBox using the getChildren().add() function. Finally, create a scene and add the vbox to the scene and add the scene to the stage and call show() function to display the final results.// Java Program to create a VBox, add spaces// between its elements, set an alignment // and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.Group;import javafx.geometry.Pos; public class VBOX_3 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("VBox"); // create a VBox VBox vbox = new VBox(10); // create a label Label label = new Label("this is VBox example"); // add label to vbox vbox.getChildren().add(label); // set alignment vbox.setAlignment(Pos.CENTER); // add buttons to VBox for (int i = 0; i < 5; i++) { vbox.getChildren().add(new Button("Button " + (int)(i + 1))); } // create a scene Scene scene = new Scene(vbox, 300, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:
// Java Program to create a VBox, add spaces// between its elements, set an alignment // and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.Group;import javafx.geometry.Pos; public class VBOX_3 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("VBox"); // create a VBox VBox vbox = new VBox(10); // create a label Label label = new Label("this is VBox example"); // add label to vbox vbox.getChildren().add(label); // set alignment vbox.setAlignment(Pos.CENTER); // add buttons to VBox for (int i = 0; i < 5; i++) { vbox.getChildren().add(new Button("Button " + (int)(i + 1))); } // create a scene Scene scene = new Scene(vbox, 300, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}
Output:
Note: The above programs might not run in an online IDE please use an offline compiler.
Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/layout/VBox.html
JavaFX
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
Stream In Java
Collections in Java
Singleton Class in Java
Set in Java
Introduction to Java
Constructors in Java
Multithreading in Java
Initializing a List in Java
Exceptions in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Sep, 2018"
},
{
"code": null,
"e": 243,
"s": 28,
"text": "VBox is a part of JavaFX. VBox lays out its children in form of vertical columns. If the vbox has a border and/or padding set, then the contents will be layed out within those insets. VBox class extends Pane class."
},
{
"code": null,
"e": 269,
"s": 243,
"text": "Constructor of the class:"
},
{
"code": null,
"e": 567,
"s": 269,
"text": "VBox(): Creates a VBox layout with spacing = 0 and alignment at TOP_LEFT.VBox(double s): Creates a new VBox with specified spacing between children.VBox(double s, Node... c): Creates a new VBox with specified nodes and spacing between them.VBox(Node... c): Creates an VBox layout with spacing = 0."
},
{
"code": null,
"e": 641,
"s": 567,
"text": "VBox(): Creates a VBox layout with spacing = 0 and alignment at TOP_LEFT."
},
{
"code": null,
"e": 717,
"s": 641,
"text": "VBox(double s): Creates a new VBox with specified spacing between children."
},
{
"code": null,
"e": 810,
"s": 717,
"text": "VBox(double s, Node... c): Creates a new VBox with specified nodes and spacing between them."
},
{
"code": null,
"e": 868,
"s": 810,
"text": "VBox(Node... c): Creates an VBox layout with spacing = 0."
},
{
"code": null,
"e": 891,
"s": 868,
"text": "Commonly Used Methods:"
},
{
"code": null,
"e": 940,
"s": 891,
"text": "Below programs illustrate the use of VBox class:"
},
{
"code": null,
"e": 6653,
"s": 940,
"text": "Java Program to create a VBox and add it to the stage: In this program we will create a VBox named vbox. We will create a label and add it to the vbox. We will also create some buttons and add them to the VBox using the getChildren().add() function. Now create a scene and add the vbox to the scene and add the scene to the stage and call show() function to display the final results.// Java Program to create a VBox // and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.Group; public class VBOX_1 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"VBox\"); // create a VBox VBox vbox = new VBox(); // create a label Label label = new Label(\"this is VBox example\"); // add label to vbox vbox.getChildren().add(label); // add buttons to VBox for (int i = 0; i < 10; i++) { vbox.getChildren().add(new Button(\"Button \" + (int)(i + 1))); } // create a scene Scene scene = new Scene(vbox, 300, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:Java Program to create a VBox, add spaces between its elements and add it to the stage: In this program we will create a VBox named vbox. We will set the spacing by passing a double value of space as an argument to the constructor. Now create a label and add it to the vbox. To add some buttons to the VBox use the getChildren().add() function. Finally, create a scene and add the vbox to the scene and add the scene to the stage and call show() function to display the final results.// Java Program to create a VBox, add // spaces between its elements and add// it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.Group; public class VBOX_2 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"VBox\"); // create a VBox VBox vbox = new VBox(10); // create a label Label label = new Label(\"this is VBox example\"); // add label to vbox vbox.getChildren().add(label); // add buttons to VBox for (int i = 0; i < 5; i++) { vbox.getChildren().add(new Button(\"Button \" + (int)(i + 1))); } // create a scene Scene scene = new Scene(vbox, 300, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:Java Program to create a VBox, add spaces between its elements, set an alignment and add it to the stage: In this program we will create a VBox named vbox. We will set the spacing by passing a double value of space as an argument to the constructor. Set the alignment of the VBox using the setAlignment() function. Then create a label and add it to the vbox. Add some buttons to the VBox using the getChildren().add() function. Finally, create a scene and add the vbox to the scene and add the scene to the stage and call show() function to display the final results.// Java Program to create a VBox, add spaces// between its elements, set an alignment // and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.Group;import javafx.geometry.Pos; public class VBOX_3 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"VBox\"); // create a VBox VBox vbox = new VBox(10); // create a label Label label = new Label(\"this is VBox example\"); // add label to vbox vbox.getChildren().add(label); // set alignment vbox.setAlignment(Pos.CENTER); // add buttons to VBox for (int i = 0; i < 5; i++) { vbox.getChildren().add(new Button(\"Button \" + (int)(i + 1))); } // create a scene Scene scene = new Scene(vbox, 300, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:"
},
{
"code": null,
"e": 8419,
"s": 6653,
"text": "Java Program to create a VBox and add it to the stage: In this program we will create a VBox named vbox. We will create a label and add it to the vbox. We will also create some buttons and add them to the VBox using the getChildren().add() function. Now create a scene and add the vbox to the scene and add the scene to the stage and call show() function to display the final results.// Java Program to create a VBox // and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.Group; public class VBOX_1 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"VBox\"); // create a VBox VBox vbox = new VBox(); // create a label Label label = new Label(\"this is VBox example\"); // add label to vbox vbox.getChildren().add(label); // add buttons to VBox for (int i = 0; i < 10; i++) { vbox.getChildren().add(new Button(\"Button \" + (int)(i + 1))); } // create a scene Scene scene = new Scene(vbox, 300, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:"
},
{
"code": "// Java Program to create a VBox // and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.Group; public class VBOX_1 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"VBox\"); // create a VBox VBox vbox = new VBox(); // create a label Label label = new Label(\"this is VBox example\"); // add label to vbox vbox.getChildren().add(label); // add buttons to VBox for (int i = 0; i < 10; i++) { vbox.getChildren().add(new Button(\"Button \" + (int)(i + 1))); } // create a scene Scene scene = new Scene(vbox, 300, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}",
"e": 9794,
"s": 8419,
"text": null
},
{
"code": null,
"e": 9802,
"s": 9794,
"text": "Output:"
},
{
"code": null,
"e": 11704,
"s": 9802,
"text": "Java Program to create a VBox, add spaces between its elements and add it to the stage: In this program we will create a VBox named vbox. We will set the spacing by passing a double value of space as an argument to the constructor. Now create a label and add it to the vbox. To add some buttons to the VBox use the getChildren().add() function. Finally, create a scene and add the vbox to the scene and add the scene to the stage and call show() function to display the final results.// Java Program to create a VBox, add // spaces between its elements and add// it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.Group; public class VBOX_2 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"VBox\"); // create a VBox VBox vbox = new VBox(10); // create a label Label label = new Label(\"this is VBox example\"); // add label to vbox vbox.getChildren().add(label); // add buttons to VBox for (int i = 0; i < 5; i++) { vbox.getChildren().add(new Button(\"Button \" + (int)(i + 1))); } // create a scene Scene scene = new Scene(vbox, 300, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:"
},
{
"code": "// Java Program to create a VBox, add // spaces between its elements and add// it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.Group; public class VBOX_2 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"VBox\"); // create a VBox VBox vbox = new VBox(10); // create a label Label label = new Label(\"this is VBox example\"); // add label to vbox vbox.getChildren().add(label); // add buttons to VBox for (int i = 0; i < 5; i++) { vbox.getChildren().add(new Button(\"Button \" + (int)(i + 1))); } // create a scene Scene scene = new Scene(vbox, 300, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}",
"e": 13115,
"s": 11704,
"text": null
},
{
"code": null,
"e": 13123,
"s": 13115,
"text": "Output:"
},
{
"code": null,
"e": 15170,
"s": 13123,
"text": "Java Program to create a VBox, add spaces between its elements, set an alignment and add it to the stage: In this program we will create a VBox named vbox. We will set the spacing by passing a double value of space as an argument to the constructor. Set the alignment of the VBox using the setAlignment() function. Then create a label and add it to the vbox. Add some buttons to the VBox using the getChildren().add() function. Finally, create a scene and add the vbox to the scene and add the scene to the stage and call show() function to display the final results.// Java Program to create a VBox, add spaces// between its elements, set an alignment // and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.Group;import javafx.geometry.Pos; public class VBOX_3 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"VBox\"); // create a VBox VBox vbox = new VBox(10); // create a label Label label = new Label(\"this is VBox example\"); // add label to vbox vbox.getChildren().add(label); // set alignment vbox.setAlignment(Pos.CENTER); // add buttons to VBox for (int i = 0; i < 5; i++) { vbox.getChildren().add(new Button(\"Button \" + (int)(i + 1))); } // create a scene Scene scene = new Scene(vbox, 300, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:"
},
{
"code": "// Java Program to create a VBox, add spaces// between its elements, set an alignment // and add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.Group;import javafx.geometry.Pos; public class VBOX_3 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"VBox\"); // create a VBox VBox vbox = new VBox(10); // create a label Label label = new Label(\"this is VBox example\"); // add label to vbox vbox.getChildren().add(label); // set alignment vbox.setAlignment(Pos.CENTER); // add buttons to VBox for (int i = 0; i < 5; i++) { vbox.getChildren().add(new Button(\"Button \" + (int)(i + 1))); } // create a scene Scene scene = new Scene(vbox, 300, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}",
"e": 16643,
"s": 15170,
"text": null
},
{
"code": null,
"e": 16651,
"s": 16643,
"text": "Output:"
},
{
"code": null,
"e": 16739,
"s": 16651,
"text": "Note: The above programs might not run in an online IDE please use an offline compiler."
},
{
"code": null,
"e": 16824,
"s": 16739,
"text": "Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/layout/VBox.html"
},
{
"code": null,
"e": 16831,
"s": 16824,
"text": "JavaFX"
},
{
"code": null,
"e": 16836,
"s": 16831,
"text": "Java"
},
{
"code": null,
"e": 16841,
"s": 16836,
"text": "Java"
},
{
"code": null,
"e": 16939,
"s": 16841,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 16958,
"s": 16939,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 16973,
"s": 16958,
"text": "Stream In Java"
},
{
"code": null,
"e": 16993,
"s": 16973,
"text": "Collections in Java"
},
{
"code": null,
"e": 17017,
"s": 16993,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 17029,
"s": 17017,
"text": "Set in Java"
},
{
"code": null,
"e": 17050,
"s": 17029,
"text": "Introduction to Java"
},
{
"code": null,
"e": 17071,
"s": 17050,
"text": "Constructors in Java"
},
{
"code": null,
"e": 17094,
"s": 17071,
"text": "Multithreading in Java"
},
{
"code": null,
"e": 17122,
"s": 17094,
"text": "Initializing a List in Java"
}
] |
Pattern CASE_INSENSITIVE field in Java with examples
|
This CASE_INSENSITIVE field of the Pattern class matches characters irrespective of case. When you use this as flag value to the compile() method and if you search for characters using regular expressions characters of both cases will be matched.
Note − By default, this flag matches only ASCII characters
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CASE_INSENSITIVE_Example {
public static void main( String args[] ) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter input data: ");
String input = sc.nextLine();
System.out.println("Enter required character: ");
char ch = sc.next().toCharArray()[0];
//Regular expression to find the required character
String regex = "["+ch+"]";
//Compiling the regular expression
Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
//Retrieving the matcher object
Matcher matcher = pattern.matcher(input);
int count =0;
while (matcher.find()) {
count++;
}
System.out.println("The letter "+ch+" occurred "+count+" times in the given text (irrespective of case)");
}
}
Enter input data:
Tutorials Point originated from the idea that there exists a class
of readers who respond better to online content and prefer to learn
new skills at their own pace from the comforts of their drawing rooms.
Enter required character:
T
The letter T occurred 20 times in the given text (irrespective of case)
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class VerifyBoolean {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string value: ");
String str = sc.next();
Pattern pattern = Pattern.compile("true|false", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(str);
if(matcher.matches()){
System.out.println("Given string is a boolean type");
} else {
System.out.println("Given string is not a boolean type");
}
}
}
Enter a string value:
true
Given string is a boolean type
Enter a string value:
false
Given string is a boolean type
Enter a string value:
hello
Given string is not a boolean type
|
[
{
"code": null,
"e": 1434,
"s": 1187,
"text": "This CASE_INSENSITIVE field of the Pattern class matches characters irrespective of case. When you use this as flag value to the compile() method and if you search for characters using regular expressions characters of both cases will be matched."
},
{
"code": null,
"e": 1493,
"s": 1434,
"text": "Note − By default, this flag matches only ASCII characters"
},
{
"code": null,
"e": 2385,
"s": 1493,
"text": "import java.util.Scanner;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\npublic class CASE_INSENSITIVE_Example {\n public static void main( String args[] ) {\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter input data: \");\n String input = sc.nextLine();\n System.out.println(\"Enter required character: \");\n char ch = sc.next().toCharArray()[0];\n //Regular expression to find the required character\n String regex = \"[\"+ch+\"]\";\n //Compiling the regular expression\n Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);\n //Retrieving the matcher object\n Matcher matcher = pattern.matcher(input);\n int count =0;\n while (matcher.find()) {\n count++;\n }\n System.out.println(\"The letter \"+ch+\" occurred \"+count+\" times in the given text (irrespective of case)\");\n }\n}"
},
{
"code": null,
"e": 2711,
"s": 2385,
"text": "Enter input data:\nTutorials Point originated from the idea that there exists a class \nof readers who respond better to online content and prefer to learn \nnew skills at their own pace from the comforts of their drawing rooms.\nEnter required character:\nT\nThe letter T occurred 20 times in the given text (irrespective of case)"
},
{
"code": null,
"e": 3315,
"s": 2711,
"text": "import java.util.Scanner;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\npublic class VerifyBoolean {\n public static void main(String args[]) {\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter a string value: \");\n String str = sc.next();\n Pattern pattern = Pattern.compile(\"true|false\", Pattern.CASE_INSENSITIVE);\n Matcher matcher = pattern.matcher(str);\n if(matcher.matches()){\n System.out.println(\"Given string is a boolean type\");\n } else {\n System.out.println(\"Given string is not a boolean type\");\n }\n }\n}"
},
{
"code": null,
"e": 3373,
"s": 3315,
"text": "Enter a string value:\ntrue\nGiven string is a boolean type"
},
{
"code": null,
"e": 3432,
"s": 3373,
"text": "Enter a string value:\nfalse\nGiven string is a boolean type"
},
{
"code": null,
"e": 3495,
"s": 3432,
"text": "Enter a string value:\nhello\nGiven string is not a boolean type"
}
] |
Python | Pandas Index.dtype
|
20 Feb, 2019
Pandas Index is an immutable ndarray implementing an ordered, sliceable set. It is the basic object which stores the axis labels for all pandas objects.
Pandas Index.dtype attribute return the data type (dtype) of the underlying data of the given Index object.
Syntax: Index.dtype
Parameter : None
Returns : dtype
Example #1: Use Index.dtype attribute to find the dtype of the underlying data of the given Index object.
# importing pandas as pdimport pandas as pd # Creating the indexidx = pd.Index(['Jan', 'Feb', 'Mar', 'Apr', 'May']) # Print the indexprint(idx)
Output :
Now we will use Index.dtype attribute to find the data type of the underlying data of the given series object.
# return the dtyperesult = idx.dtype # Print the resultprint(result)
Output :
As we can see in the output, the Index.dtype attribute has returned object as the data type of the underlying data of the given Index object.
Example #2 : Use Index.dtype attribute to find the dtype of the underlying data of the given Index object.
# importing pandas as pdimport pandas as pd # Creating the indexidx = pd.Index([100, 200, 142, 88, 124]) # Print the indexprint(idx)
Output :
Now we will use Index.dtype attribute to find the data type of the underlying data of the given series object.
# return the dtyperesult = idx.dtype # Print the resultprint(result)
Output :
As we can see in the output, the Index.dtype attribute has returned int64 as the data type of the underlying data of the given Index object.
Python pandas-indexing
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Feb, 2019"
},
{
"code": null,
"e": 181,
"s": 28,
"text": "Pandas Index is an immutable ndarray implementing an ordered, sliceable set. It is the basic object which stores the axis labels for all pandas objects."
},
{
"code": null,
"e": 289,
"s": 181,
"text": "Pandas Index.dtype attribute return the data type (dtype) of the underlying data of the given Index object."
},
{
"code": null,
"e": 309,
"s": 289,
"text": "Syntax: Index.dtype"
},
{
"code": null,
"e": 326,
"s": 309,
"text": "Parameter : None"
},
{
"code": null,
"e": 342,
"s": 326,
"text": "Returns : dtype"
},
{
"code": null,
"e": 448,
"s": 342,
"text": "Example #1: Use Index.dtype attribute to find the dtype of the underlying data of the given Index object."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the indexidx = pd.Index(['Jan', 'Feb', 'Mar', 'Apr', 'May']) # Print the indexprint(idx)",
"e": 594,
"s": 448,
"text": null
},
{
"code": null,
"e": 603,
"s": 594,
"text": "Output :"
},
{
"code": null,
"e": 714,
"s": 603,
"text": "Now we will use Index.dtype attribute to find the data type of the underlying data of the given series object."
},
{
"code": "# return the dtyperesult = idx.dtype # Print the resultprint(result)",
"e": 784,
"s": 714,
"text": null
},
{
"code": null,
"e": 793,
"s": 784,
"text": "Output :"
},
{
"code": null,
"e": 935,
"s": 793,
"text": "As we can see in the output, the Index.dtype attribute has returned object as the data type of the underlying data of the given Index object."
},
{
"code": null,
"e": 1042,
"s": 935,
"text": "Example #2 : Use Index.dtype attribute to find the dtype of the underlying data of the given Index object."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the indexidx = pd.Index([100, 200, 142, 88, 124]) # Print the indexprint(idx)",
"e": 1177,
"s": 1042,
"text": null
},
{
"code": null,
"e": 1186,
"s": 1177,
"text": "Output :"
},
{
"code": null,
"e": 1297,
"s": 1186,
"text": "Now we will use Index.dtype attribute to find the data type of the underlying data of the given series object."
},
{
"code": "# return the dtyperesult = idx.dtype # Print the resultprint(result)",
"e": 1367,
"s": 1297,
"text": null
},
{
"code": null,
"e": 1376,
"s": 1367,
"text": "Output :"
},
{
"code": null,
"e": 1517,
"s": 1376,
"text": "As we can see in the output, the Index.dtype attribute has returned int64 as the data type of the underlying data of the given Index object."
},
{
"code": null,
"e": 1540,
"s": 1517,
"text": "Python pandas-indexing"
},
{
"code": null,
"e": 1554,
"s": 1540,
"text": "Python-pandas"
},
{
"code": null,
"e": 1561,
"s": 1554,
"text": "Python"
}
] |
Python – Sort List by Dictionary values
|
11 May, 2020
Sometimes while working with Python dictionary, we can have problem in which we need to perform a sort of list according to corresponding value in dictionary. This can have application in many domains, including data and web development. Lets discuss certain ways in which this task can be performed.
Method #1 : Using sorted() + key + lambdaThe combination of above functions can be used to solve this problem. In this, we perform the task of sorting using sorted(). The lambda function is used to get key’s values.
# Python3 code to demonstrate working of # Sort List by Dictionary values# Using sorted() + key + lambda # initializing listtest_list = ['gfg', 'is', 'best'] # initializing Dictionarytest_dict = {'gfg' : 56, 'is' : 12, 'best' : 76} # printing original listprint("The original list is : " + str(test_list)) # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Sort List by Dictionary values# Using sorted() + key + lambdares = sorted(test_list, key = lambda ele: test_dict[ele]) # printing result print("The list after sorting : " + str(res))
The original list is : ['gfg', 'is', 'best']
The original dictionary is : {'best': 76, 'gfg': 56, 'is': 12}
The list after sorting : ['is', 'gfg', 'best']
Method #2 : Using sorted() + key + get()This method performs the task in similar way as above method. The difference is that it accesses values get().
# Python3 code to demonstrate working of # Sort List by Dictionary values# Using sorted() + key + get() # initializing listtest_list = ['gfg', 'is', 'best'] # initializing Dictionarytest_dict = {'gfg' : 56, 'is' : 12, 'best' : 76} # printing original listprint("The original list is : " + str(test_list)) # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Sort List by Dictionary values# Using sorted() + key + get()res = sorted(test_list, key = test_dict.get) # printing result print("The list after sorting : " + str(res))
The original list is : ['gfg', 'is', 'best']
The original dictionary is : {'best': 76, 'gfg': 56, 'is': 12}
The list after sorting : ['is', 'gfg', 'best']
Python list-programs
Python-sort
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 May, 2020"
},
{
"code": null,
"e": 329,
"s": 28,
"text": "Sometimes while working with Python dictionary, we can have problem in which we need to perform a sort of list according to corresponding value in dictionary. This can have application in many domains, including data and web development. Lets discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 545,
"s": 329,
"text": "Method #1 : Using sorted() + key + lambdaThe combination of above functions can be used to solve this problem. In this, we perform the task of sorting using sorted(). The lambda function is used to get key’s values."
},
{
"code": "# Python3 code to demonstrate working of # Sort List by Dictionary values# Using sorted() + key + lambda # initializing listtest_list = ['gfg', 'is', 'best'] # initializing Dictionarytest_dict = {'gfg' : 56, 'is' : 12, 'best' : 76} # printing original listprint(\"The original list is : \" + str(test_list)) # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # Sort List by Dictionary values# Using sorted() + key + lambdares = sorted(test_list, key = lambda ele: test_dict[ele]) # printing result print(\"The list after sorting : \" + str(res)) ",
"e": 1129,
"s": 545,
"text": null
},
{
"code": null,
"e": 1285,
"s": 1129,
"text": "The original list is : ['gfg', 'is', 'best']\nThe original dictionary is : {'best': 76, 'gfg': 56, 'is': 12}\nThe list after sorting : ['is', 'gfg', 'best']\n"
},
{
"code": null,
"e": 1438,
"s": 1287,
"text": "Method #2 : Using sorted() + key + get()This method performs the task in similar way as above method. The difference is that it accesses values get()."
},
{
"code": "# Python3 code to demonstrate working of # Sort List by Dictionary values# Using sorted() + key + get() # initializing listtest_list = ['gfg', 'is', 'best'] # initializing Dictionarytest_dict = {'gfg' : 56, 'is' : 12, 'best' : 76} # printing original listprint(\"The original list is : \" + str(test_list)) # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # Sort List by Dictionary values# Using sorted() + key + get()res = sorted(test_list, key = test_dict.get) # printing result print(\"The list after sorting : \" + str(res)) ",
"e": 2007,
"s": 1438,
"text": null
},
{
"code": null,
"e": 2163,
"s": 2007,
"text": "The original list is : ['gfg', 'is', 'best']\nThe original dictionary is : {'best': 76, 'gfg': 56, 'is': 12}\nThe list after sorting : ['is', 'gfg', 'best']\n"
},
{
"code": null,
"e": 2184,
"s": 2163,
"text": "Python list-programs"
},
{
"code": null,
"e": 2196,
"s": 2184,
"text": "Python-sort"
},
{
"code": null,
"e": 2203,
"s": 2196,
"text": "Python"
},
{
"code": null,
"e": 2219,
"s": 2203,
"text": "Python Programs"
},
{
"code": null,
"e": 2317,
"s": 2219,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2349,
"s": 2317,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2376,
"s": 2349,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2397,
"s": 2376,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2428,
"s": 2397,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2484,
"s": 2428,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2506,
"s": 2484,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2545,
"s": 2506,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2583,
"s": 2545,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2632,
"s": 2583,
"text": "Python | Convert string dictionary to dictionary"
}
] |
Name validation using IGNORECASE in Python Regex
|
29 Dec, 2020
In this article, we will learn about how to use Python Regex to validate name using IGNORECASE.
re.IGNORECASE : This flag allows for case-insensitive matching of the Regular Expression with the given string i.e. expressions like [A-Z] will match lowercase letters, too. Generally, It’s passed as an optional argument to re.compile().
Let’s consider an example of a form where the user is asked to enter their name and we have to validate it using RegEx. The format for entering name is as follow:
Mr. or Mrs. or Ms. (Either one) followed by a single space
First Name, followed by a single space
Middle Name(optional), followed by a single space
Last Name(optional)
Examples:
Input : Mr. Albus Severus Potter
Output : Valid
Input : Lily and Mr. Harry Potter
Output : Invalid
Note : Since, we are using IGNORECASE flag, the first character of First, Second, and Last name may or may not be capital.
Below is the Python code –
# Python program to validate name using IGNORECASE in RegEx # Importing re packageimport re def validating_name(name): # RegexObject = re.compile( Regular expression, flag ) # Compiles a regular expression pattern into a regular expression object regex_name = re.compile(r'^(Mr\.|Mrs\.|Ms\.) ([a-z]+)( [a-z]+)*( [a-z]+)*$', re.IGNORECASE) # RegexObject is matched with the desired # string using search function # In case a match is found, search() returns # MatchObject Instance # If match is not found, it return None res = regex_name.search(name) # If match is found, the string is valid if res: print("Valid") # If match is not found, string is invalid else: print("Invalid") # Driver Codevalidating_name('Mr. Albus Severus Potter')validating_name('Lily and Mr. Harry Potter')validating_name('Mr. Cedric')validating_name('Mr. sirius black')
Output:
Valid
Invalid
Valid
valid
Python Regex-programs
python-regex
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
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 | os.path.join() method
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Dec, 2020"
},
{
"code": null,
"e": 124,
"s": 28,
"text": "In this article, we will learn about how to use Python Regex to validate name using IGNORECASE."
},
{
"code": null,
"e": 362,
"s": 124,
"text": "re.IGNORECASE : This flag allows for case-insensitive matching of the Regular Expression with the given string i.e. expressions like [A-Z] will match lowercase letters, too. Generally, It’s passed as an optional argument to re.compile()."
},
{
"code": null,
"e": 525,
"s": 362,
"text": "Let’s consider an example of a form where the user is asked to enter their name and we have to validate it using RegEx. The format for entering name is as follow:"
},
{
"code": null,
"e": 584,
"s": 525,
"text": "Mr. or Mrs. or Ms. (Either one) followed by a single space"
},
{
"code": null,
"e": 623,
"s": 584,
"text": "First Name, followed by a single space"
},
{
"code": null,
"e": 673,
"s": 623,
"text": "Middle Name(optional), followed by a single space"
},
{
"code": null,
"e": 693,
"s": 673,
"text": "Last Name(optional)"
},
{
"code": null,
"e": 703,
"s": 693,
"text": "Examples:"
},
{
"code": null,
"e": 804,
"s": 703,
"text": "Input : Mr. Albus Severus Potter \nOutput : Valid\n\nInput : Lily and Mr. Harry Potter\nOutput : Invalid"
},
{
"code": null,
"e": 927,
"s": 804,
"text": "Note : Since, we are using IGNORECASE flag, the first character of First, Second, and Last name may or may not be capital."
},
{
"code": null,
"e": 954,
"s": 927,
"text": "Below is the Python code –"
},
{
"code": "# Python program to validate name using IGNORECASE in RegEx # Importing re packageimport re def validating_name(name): # RegexObject = re.compile( Regular expression, flag ) # Compiles a regular expression pattern into a regular expression object regex_name = re.compile(r'^(Mr\\.|Mrs\\.|Ms\\.) ([a-z]+)( [a-z]+)*( [a-z]+)*$', re.IGNORECASE) # RegexObject is matched with the desired # string using search function # In case a match is found, search() returns # MatchObject Instance # If match is not found, it return None res = regex_name.search(name) # If match is found, the string is valid if res: print(\"Valid\") # If match is not found, string is invalid else: print(\"Invalid\") # Driver Codevalidating_name('Mr. Albus Severus Potter')validating_name('Lily and Mr. Harry Potter')validating_name('Mr. Cedric')validating_name('Mr. sirius black')",
"e": 1872,
"s": 954,
"text": null
},
{
"code": null,
"e": 1880,
"s": 1872,
"text": "Output:"
},
{
"code": null,
"e": 1907,
"s": 1880,
"text": "Valid\nInvalid\nValid\nvalid\n"
},
{
"code": null,
"e": 1929,
"s": 1907,
"text": "Python Regex-programs"
},
{
"code": null,
"e": 1942,
"s": 1929,
"text": "python-regex"
},
{
"code": null,
"e": 1949,
"s": 1942,
"text": "Python"
},
{
"code": null,
"e": 2047,
"s": 1949,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2065,
"s": 2047,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2107,
"s": 2065,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2129,
"s": 2107,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2155,
"s": 2129,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2187,
"s": 2155,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2216,
"s": 2187,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2243,
"s": 2216,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2279,
"s": 2243,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 2310,
"s": 2279,
"text": "Python | os.path.join() method"
}
] |
What is the difference between = (Assignment) and == (Equal to) operators
|
05 Apr, 2019
= operator
The “=” is an assignment operator is used to assign the value on the right to the variable on the left.
For example:
a = 10;
b = 20;
ch = 'y';
Example:
// C program to demonstrate// working of Assignment operators #include <stdio.h> int main(){ // Assigning value 10 to a // using "=" operator int a = 10; printf("Value of a is %d\n", a); return 0;}
Value of a is 10
== operator
The ‘==’ operator checks whether the two given operands are equal or not. If so, it returns true. Otherwise it returns false.For example:
5==5
This will return true.
Example:
// C program to demonstrate// working of relational operators#include <stdio.h> int main(){ int a = 10, b = 4; // equal to if (a == b) printf("a is equal to b\n"); else printf("a and b are not equal\n"); return 0;}
a and b are not equal
The differences can be shown in tabular form as follows:
Operators
Difference Between
Programming Language
Operators
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n05 Apr, 2019"
},
{
"code": null,
"e": 63,
"s": 52,
"text": "= operator"
},
{
"code": null,
"e": 167,
"s": 63,
"text": "The “=” is an assignment operator is used to assign the value on the right to the variable on the left."
},
{
"code": null,
"e": 180,
"s": 167,
"text": "For example:"
},
{
"code": null,
"e": 207,
"s": 180,
"text": "a = 10;\nb = 20;\nch = 'y';\n"
},
{
"code": null,
"e": 216,
"s": 207,
"text": "Example:"
},
{
"code": "// C program to demonstrate// working of Assignment operators #include <stdio.h> int main(){ // Assigning value 10 to a // using \"=\" operator int a = 10; printf(\"Value of a is %d\\n\", a); return 0;}",
"e": 435,
"s": 216,
"text": null
},
{
"code": null,
"e": 453,
"s": 435,
"text": "Value of a is 10\n"
},
{
"code": null,
"e": 465,
"s": 453,
"text": "== operator"
},
{
"code": null,
"e": 603,
"s": 465,
"text": "The ‘==’ operator checks whether the two given operands are equal or not. If so, it returns true. Otherwise it returns false.For example:"
},
{
"code": null,
"e": 633,
"s": 603,
"text": "5==5\n\nThis will return true.\n"
},
{
"code": null,
"e": 642,
"s": 633,
"text": "Example:"
},
{
"code": "// C program to demonstrate// working of relational operators#include <stdio.h> int main(){ int a = 10, b = 4; // equal to if (a == b) printf(\"a is equal to b\\n\"); else printf(\"a and b are not equal\\n\"); return 0;}",
"e": 891,
"s": 642,
"text": null
},
{
"code": null,
"e": 914,
"s": 891,
"text": "a and b are not equal\n"
},
{
"code": null,
"e": 971,
"s": 914,
"text": "The differences can be shown in tabular form as follows:"
},
{
"code": null,
"e": 981,
"s": 971,
"text": "Operators"
},
{
"code": null,
"e": 1000,
"s": 981,
"text": "Difference Between"
},
{
"code": null,
"e": 1021,
"s": 1000,
"text": "Programming Language"
},
{
"code": null,
"e": 1031,
"s": 1021,
"text": "Operators"
}
] |
Monitoring memory usage of a running Python program
|
23 Nov, 2021
Managing memory is important in any programming logic but this becomes necessary for python. As python is used in Ml and AI where vast data are used which needs to be managed. Memory leaks,i.e, the program is out of memory after running for several hours. To manage these memory leaks memory monitoring is essential. Monitoring memory is also called profiling. As a developer, it’s a necessity that we profile our program and use less memory allocation as much as possible.
Method 1: Using Tracemalloc
Tracemalloc is a library module that traces every memory block in python. The tracing starts by using the start() during runtime. This library module can also give information about the total size, number, and average size of allocated memory blocks. Lets its function with a proper example-
Python3
# importing the moduleimport tracemalloc # code or function for which memory# has to be monitoreddef app(): lt = [] for i in range(0, 100000): lt.append(i) # starting the monitoringtracemalloc.start() # function callapp() # displaying the memoryprint(tracemalloc.get_traced_memory()) # stopping the librarytracemalloc.stop()
Output:
The output is given in form of (current, peak),i.e, current memory is the memory the code is currently using and peak memory is the maximum space the program used while executing.
(0,3617252)
Method 2: Using Psutil
Psutil is a python system library used to keep track of various resources in the system and their utilization. The library is used for profiling, limiting, and management of process resources. In order to install this do the following-
sudo pip install psutil [Linux]
pip install psutill [Windows]
Let’s see this with an example. All you have to do is add the decorator function and the process_memory function in your code and this will give you the memory consumed by the code and it’s before and after.
Python3
# importing librariesimport osimport psutil # inner psutil functiondef process_memory(): process = psutil.Process(os.getpid()) mem_info = process.memory_info() return mem_info.rss # decorator functiondef profile(func): def wrapper(*args, **kwargs): mem_before = process_memory() result = func(*args, **kwargs) mem_after = process_memory() print("{}:consumed memory: {:,}".format( func.__name__, mem_before, mem_after, mem_after - mem_before)) return result return wrapper # instantiation of decorator function@profile # main code for which# memory has to be monitoreddef func(): x = [1] * (10 ** 7) y = [2] * (4 * 10 ** 8) del x return y func()
Output:
func: consumed memory: 307,261,440
Method 3: Using the classic memory profiler
Memory profiler from PyPI is a python library module used for monitoring process memory. It uses psutil code to create a decorator and then uses it to get the memory distribution. With this pypi module by importing one can save lines and directly call the decorator. To install use the following-
pip install -U memory_profiler
Let’s see this through a code-
Python3
# importing the libraryfrom memory_profiler import profile # instantiating the decorator@profile# code for which memory has to# be monitoreddef my_func(): x = [x for x in range(0, 1000)] y = [y*100 for y in range(0, 1500)] del x return y if __name__ == '__main__': my_func()
Output:
The output displays the memory consumed by each line in the code. Implementation of finding the memory consumption is very easy using a memory profiler as we directly call the decorator instead of writing a whole new code.
Line # Mem usage Increment Occurences Line Contents
============================================================
2 30.5 MiB 30.5 MiB 1 @profile
3 def my_func():
4 30.6 MiB 0.1 MiB 1003 x = [x for x in range(0,1000)]
5 30.7 MiB 0.1 MiB 1503 y = [y*100 for y in range(0,1500)]
6 30.7 MiB 0.0 MiB 1 del x
7 30.7 MiB 0.0 MiB 1 return y
punamsingh628700
Picked
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Nov, 2021"
},
{
"code": null,
"e": 502,
"s": 28,
"text": "Managing memory is important in any programming logic but this becomes necessary for python. As python is used in Ml and AI where vast data are used which needs to be managed. Memory leaks,i.e, the program is out of memory after running for several hours. To manage these memory leaks memory monitoring is essential. Monitoring memory is also called profiling. As a developer, it’s a necessity that we profile our program and use less memory allocation as much as possible."
},
{
"code": null,
"e": 530,
"s": 502,
"text": "Method 1: Using Tracemalloc"
},
{
"code": null,
"e": 822,
"s": 530,
"text": "Tracemalloc is a library module that traces every memory block in python. The tracing starts by using the start() during runtime. This library module can also give information about the total size, number, and average size of allocated memory blocks. Lets its function with a proper example-"
},
{
"code": null,
"e": 830,
"s": 822,
"text": "Python3"
},
{
"code": "# importing the moduleimport tracemalloc # code or function for which memory# has to be monitoreddef app(): lt = [] for i in range(0, 100000): lt.append(i) # starting the monitoringtracemalloc.start() # function callapp() # displaying the memoryprint(tracemalloc.get_traced_memory()) # stopping the librarytracemalloc.stop()",
"e": 1168,
"s": 830,
"text": null
},
{
"code": null,
"e": 1176,
"s": 1168,
"text": "Output:"
},
{
"code": null,
"e": 1356,
"s": 1176,
"text": "The output is given in form of (current, peak),i.e, current memory is the memory the code is currently using and peak memory is the maximum space the program used while executing."
},
{
"code": null,
"e": 1368,
"s": 1356,
"text": "(0,3617252)"
},
{
"code": null,
"e": 1391,
"s": 1368,
"text": "Method 2: Using Psutil"
},
{
"code": null,
"e": 1627,
"s": 1391,
"text": "Psutil is a python system library used to keep track of various resources in the system and their utilization. The library is used for profiling, limiting, and management of process resources. In order to install this do the following-"
},
{
"code": null,
"e": 1689,
"s": 1627,
"text": "sudo pip install psutil [Linux]\npip install psutill [Windows]"
},
{
"code": null,
"e": 1897,
"s": 1689,
"text": "Let’s see this with an example. All you have to do is add the decorator function and the process_memory function in your code and this will give you the memory consumed by the code and it’s before and after."
},
{
"code": null,
"e": 1905,
"s": 1897,
"text": "Python3"
},
{
"code": "# importing librariesimport osimport psutil # inner psutil functiondef process_memory(): process = psutil.Process(os.getpid()) mem_info = process.memory_info() return mem_info.rss # decorator functiondef profile(func): def wrapper(*args, **kwargs): mem_before = process_memory() result = func(*args, **kwargs) mem_after = process_memory() print(\"{}:consumed memory: {:,}\".format( func.__name__, mem_before, mem_after, mem_after - mem_before)) return result return wrapper # instantiation of decorator function@profile # main code for which# memory has to be monitoreddef func(): x = [1] * (10 ** 7) y = [2] * (4 * 10 ** 8) del x return y func()",
"e": 2636,
"s": 1905,
"text": null
},
{
"code": null,
"e": 2644,
"s": 2636,
"text": "Output:"
},
{
"code": null,
"e": 2679,
"s": 2644,
"text": "func: consumed memory: 307,261,440"
},
{
"code": null,
"e": 2724,
"s": 2679,
"text": "Method 3: Using the classic memory profiler "
},
{
"code": null,
"e": 3021,
"s": 2724,
"text": "Memory profiler from PyPI is a python library module used for monitoring process memory. It uses psutil code to create a decorator and then uses it to get the memory distribution. With this pypi module by importing one can save lines and directly call the decorator. To install use the following-"
},
{
"code": null,
"e": 3052,
"s": 3021,
"text": "pip install -U memory_profiler"
},
{
"code": null,
"e": 3083,
"s": 3052,
"text": "Let’s see this through a code-"
},
{
"code": null,
"e": 3091,
"s": 3083,
"text": "Python3"
},
{
"code": "# importing the libraryfrom memory_profiler import profile # instantiating the decorator@profile# code for which memory has to# be monitoreddef my_func(): x = [x for x in range(0, 1000)] y = [y*100 for y in range(0, 1500)] del x return y if __name__ == '__main__': my_func()",
"e": 3381,
"s": 3091,
"text": null
},
{
"code": null,
"e": 3389,
"s": 3381,
"text": "Output:"
},
{
"code": null,
"e": 3613,
"s": 3389,
"text": "The output displays the memory consumed by each line in the code. Implementation of finding the memory consumption is very easy using a memory profiler as we directly call the decorator instead of writing a whole new code. "
},
{
"code": null,
"e": 4140,
"s": 3613,
"text": "Line # Mem usage Increment Occurences Line Contents\n============================================================\n 2 30.5 MiB 30.5 MiB 1 @profile\n 3 def my_func():\n 4 30.6 MiB 0.1 MiB 1003 x = [x for x in range(0,1000)]\n 5 30.7 MiB 0.1 MiB 1503 y = [y*100 for y in range(0,1500)]\n 6 30.7 MiB 0.0 MiB 1 del x\n 7 30.7 MiB 0.0 MiB 1 return y "
},
{
"code": null,
"e": 4157,
"s": 4140,
"text": "punamsingh628700"
},
{
"code": null,
"e": 4164,
"s": 4157,
"text": "Picked"
},
{
"code": null,
"e": 4179,
"s": 4164,
"text": "python-utility"
},
{
"code": null,
"e": 4186,
"s": 4179,
"text": "Python"
}
] |
Find the frequencies of all duplicates elements in the array
|
01 Jul, 2021
Given an array of integers with duplicate elements in it, the task is to find the duplicate elements in the array and their frequencies.Examples:
Input: arr[] = {2, 3, 4, 5, 4, 6, 4, 7, 4, 5, 6, 6} Output: Below is the frequency of repeated elements – 4 –> 4 5 –> 2 6 –> 3Input: arr[] = {4, 4, 5, 5, 6} Output: Below is the frequency of repeated elements – 4 –> 2 5 –> 2
Approach:
Create a Hash Map to store the frequency of the elements.
Elements whose frequency is greater than 1 are the repeated elements.
Below is the implementation of the above approach:
CPP
Java
Python
C#
Javascript
// CPP Implementation to find the// repeating elements with there count#include<bits/stdc++.h>using namespace std; // Function to find the repeating// elements with there countmap<int,int> findRepeating(int arr[], int size){ // Hash map to store the // frequency of elements map<int,int> frequency; // Loop to store the frequency of // elements of array for (int i = 0; i < size; i++) frequency[arr[i]]++; return frequency;} // Driver Codeint main(){ int arr[] = {4, 4, 5, 5, 6}; int arr_size = sizeof(arr)/sizeof(arr[0]); map<int,int> frequency = findRepeating(arr, arr_size); cout<<"Below is the frequency of repeated elements -"<<endl; for(auto x : frequency){ if (frequency[x.first] > 1) cout<<x.first<<" --> "<<frequency[x.first]<<endl; }} // This code is contributed by Surendra_Gangwar
// Java Implementation to find the// repeating elements with there countimport java.util.*; class GFG{ // Function to find the repeating// elements with there countstatic HashMap<Integer, Integer> findRepeating(int []arr, int size){ // Hash map to store the // frequency of elements HashMap<Integer,Integer> frequency = new HashMap<Integer,Integer>(); // Loop to store the frequency of // elements of array for(int i = 0; i < size; i++) { if(frequency.containsKey(arr[i])) { frequency.put(arr[i], frequency.get(arr[i]) + 1); } else { frequency.put(arr[i], 1); } } return frequency;} // Driver Codepublic static void main(String []args){ int []arr = {4, 4, 5, 5, 6}; int arr_size = arr.length; HashMap<Integer,Integer> frequency = findRepeating(arr, arr_size); System.out.println("Below is the frequency" +"of repeated elements -"); for (Map.Entry<Integer,Integer> entry : frequency.entrySet()) if (entry.getValue() > 1) System.out.println(entry.getKey()+ " --> "+entry.getValue());}} // This code is contributed by PrinciRaj1992
# Python Implementation to find the# repeating elements with there count # Function to find the repeating# elements with there countdef findRepeating(arr, size): # Hash map to store the # frequency of elements frequency = {} # Loop to store the frequency of # elements of array for i in range (0, size): frequency[arr[i]] = \ frequency.get(arr[i], 0) + 1 return frequency # Driver Codeif __name__ == "__main__": arr = [4, 4, 5, 5, 6] arr_size = len(arr) frequency = findRepeating(arr, arr_size) print("Below is the frequency\ of repeated elements -") for i in frequency: if frequency[i] > 1: print(i, " --> ", frequency[i])
// C# Implementation to find the// repeating elements with there countusing System;using System.Collections.Generic; class GFG{ // Function to find the repeating// elements with there countstatic Dictionary<int, int> findRepeating(int []arr, int size){ // Hash map to store the // frequency of elements Dictionary<int,int> frequency = new Dictionary<int,int>(); // Loop to store the frequency of // elements of array for(int i = 0; i < size; i++) { if(frequency.ContainsKey(arr[i])) { frequency[arr[i]] = frequency[arr[i]] + 1; } else { frequency.Add(arr[i], 1); } } return frequency;} // Driver Codepublic static void Main(String []args){ int []arr = {4, 4, 5, 5, 6}; int arr_size = arr.Length; Dictionary<int,int> frequency = findRepeating(arr, arr_size); Console.WriteLine("Below is the frequency" +"of repeated elements -"); foreach (KeyValuePair<int,int> entry in frequency) if (entry.Value > 1) Console.WriteLine(entry.Key+ " --> "+entry.Value);}} // This code is contributed by 29AjayKumar
<script>// Javascript Implementation to find the// repeating elements with there count // Function to find the repeating// elements with there countfunction findRepeating(arr, size){ // Hash map to store the // frequency of elements var frequency = new Map(); // Loop to store the frequency of // elements of array for(var i = 0; i < size; i++) { if(frequency.has(arr[i])) { frequency.set(arr[i], frequency.get(arr[i])+1); } else { frequency.set(arr[i], 1); } } return frequency;} // Driver Codevar arr = [4, 4, 5, 5, 6];var arr_size = arr.length;var frequency = findRepeating(arr, arr_size);document.write("Below is the frequency" +"of repeated elements -<br>");frequency.forEach((value, key) => { if (value > 1) document.write(key+ " --> "+value + "<br>");}); // This code is contributed by rrrtnx.</script>
Below is the frequency of repeated elements -
4 --> 2
5 --> 2
princiraj1992
29AjayKumar
SURENDRA_GANGWAR
rrrtnx
Arrays
Hash
Arrays
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
What is Hashing | A Complete Tutorial
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Count pairs with given sum
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n01 Jul, 2021"
},
{
"code": null,
"e": 202,
"s": 54,
"text": "Given an array of integers with duplicate elements in it, the task is to find the duplicate elements in the array and their frequencies.Examples: "
},
{
"code": null,
"e": 429,
"s": 202,
"text": "Input: arr[] = {2, 3, 4, 5, 4, 6, 4, 7, 4, 5, 6, 6} Output: Below is the frequency of repeated elements – 4 –> 4 5 –> 2 6 –> 3Input: arr[] = {4, 4, 5, 5, 6} Output: Below is the frequency of repeated elements – 4 –> 2 5 –> 2 "
},
{
"code": null,
"e": 443,
"s": 431,
"text": "Approach: "
},
{
"code": null,
"e": 501,
"s": 443,
"text": "Create a Hash Map to store the frequency of the elements."
},
{
"code": null,
"e": 571,
"s": 501,
"text": "Elements whose frequency is greater than 1 are the repeated elements."
},
{
"code": null,
"e": 624,
"s": 571,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 628,
"s": 624,
"text": "CPP"
},
{
"code": null,
"e": 633,
"s": 628,
"text": "Java"
},
{
"code": null,
"e": 640,
"s": 633,
"text": "Python"
},
{
"code": null,
"e": 643,
"s": 640,
"text": "C#"
},
{
"code": null,
"e": 654,
"s": 643,
"text": "Javascript"
},
{
"code": "// CPP Implementation to find the// repeating elements with there count#include<bits/stdc++.h>using namespace std; // Function to find the repeating// elements with there countmap<int,int> findRepeating(int arr[], int size){ // Hash map to store the // frequency of elements map<int,int> frequency; // Loop to store the frequency of // elements of array for (int i = 0; i < size; i++) frequency[arr[i]]++; return frequency;} // Driver Codeint main(){ int arr[] = {4, 4, 5, 5, 6}; int arr_size = sizeof(arr)/sizeof(arr[0]); map<int,int> frequency = findRepeating(arr, arr_size); cout<<\"Below is the frequency of repeated elements -\"<<endl; for(auto x : frequency){ if (frequency[x.first] > 1) cout<<x.first<<\" --> \"<<frequency[x.first]<<endl; }} // This code is contributed by Surendra_Gangwar",
"e": 1525,
"s": 654,
"text": null
},
{
"code": "// Java Implementation to find the// repeating elements with there countimport java.util.*; class GFG{ // Function to find the repeating// elements with there countstatic HashMap<Integer, Integer> findRepeating(int []arr, int size){ // Hash map to store the // frequency of elements HashMap<Integer,Integer> frequency = new HashMap<Integer,Integer>(); // Loop to store the frequency of // elements of array for(int i = 0; i < size; i++) { if(frequency.containsKey(arr[i])) { frequency.put(arr[i], frequency.get(arr[i]) + 1); } else { frequency.put(arr[i], 1); } } return frequency;} // Driver Codepublic static void main(String []args){ int []arr = {4, 4, 5, 5, 6}; int arr_size = arr.length; HashMap<Integer,Integer> frequency = findRepeating(arr, arr_size); System.out.println(\"Below is the frequency\" +\"of repeated elements -\"); for (Map.Entry<Integer,Integer> entry : frequency.entrySet()) if (entry.getValue() > 1) System.out.println(entry.getKey()+ \" --> \"+entry.getValue());}} // This code is contributed by PrinciRaj1992",
"e": 2695,
"s": 1525,
"text": null
},
{
"code": "# Python Implementation to find the# repeating elements with there count # Function to find the repeating# elements with there countdef findRepeating(arr, size): # Hash map to store the # frequency of elements frequency = {} # Loop to store the frequency of # elements of array for i in range (0, size): frequency[arr[i]] = \\ frequency.get(arr[i], 0) + 1 return frequency # Driver Codeif __name__ == \"__main__\": arr = [4, 4, 5, 5, 6] arr_size = len(arr) frequency = findRepeating(arr, arr_size) print(\"Below is the frequency\\ of repeated elements -\") for i in frequency: if frequency[i] > 1: print(i, \" --> \", frequency[i])",
"e": 3404,
"s": 2695,
"text": null
},
{
"code": "// C# Implementation to find the// repeating elements with there countusing System;using System.Collections.Generic; class GFG{ // Function to find the repeating// elements with there countstatic Dictionary<int, int> findRepeating(int []arr, int size){ // Hash map to store the // frequency of elements Dictionary<int,int> frequency = new Dictionary<int,int>(); // Loop to store the frequency of // elements of array for(int i = 0; i < size; i++) { if(frequency.ContainsKey(arr[i])) { frequency[arr[i]] = frequency[arr[i]] + 1; } else { frequency.Add(arr[i], 1); } } return frequency;} // Driver Codepublic static void Main(String []args){ int []arr = {4, 4, 5, 5, 6}; int arr_size = arr.Length; Dictionary<int,int> frequency = findRepeating(arr, arr_size); Console.WriteLine(\"Below is the frequency\" +\"of repeated elements -\"); foreach (KeyValuePair<int,int> entry in frequency) if (entry.Value > 1) Console.WriteLine(entry.Key+ \" --> \"+entry.Value);}} // This code is contributed by 29AjayKumar",
"e": 4562,
"s": 3404,
"text": null
},
{
"code": "<script>// Javascript Implementation to find the// repeating elements with there count // Function to find the repeating// elements with there countfunction findRepeating(arr, size){ // Hash map to store the // frequency of elements var frequency = new Map(); // Loop to store the frequency of // elements of array for(var i = 0; i < size; i++) { if(frequency.has(arr[i])) { frequency.set(arr[i], frequency.get(arr[i])+1); } else { frequency.set(arr[i], 1); } } return frequency;} // Driver Codevar arr = [4, 4, 5, 5, 6];var arr_size = arr.length;var frequency = findRepeating(arr, arr_size);document.write(\"Below is the frequency\" +\"of repeated elements -<br>\");frequency.forEach((value, key) => { if (value > 1) document.write(key+ \" --> \"+value + \"<br>\");}); // This code is contributed by rrrtnx.</script>",
"e": 5506,
"s": 4562,
"text": null
},
{
"code": null,
"e": 5575,
"s": 5506,
"text": "Below is the frequency of repeated elements -\n4 --> 2\n5 --> 2"
},
{
"code": null,
"e": 5591,
"s": 5577,
"text": "princiraj1992"
},
{
"code": null,
"e": 5603,
"s": 5591,
"text": "29AjayKumar"
},
{
"code": null,
"e": 5620,
"s": 5603,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 5627,
"s": 5620,
"text": "rrrtnx"
},
{
"code": null,
"e": 5634,
"s": 5627,
"text": "Arrays"
},
{
"code": null,
"e": 5639,
"s": 5634,
"text": "Hash"
},
{
"code": null,
"e": 5646,
"s": 5639,
"text": "Arrays"
},
{
"code": null,
"e": 5651,
"s": 5646,
"text": "Hash"
},
{
"code": null,
"e": 5749,
"s": 5651,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5817,
"s": 5749,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 5861,
"s": 5817,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 5893,
"s": 5861,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 5941,
"s": 5893,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 5955,
"s": 5941,
"text": "Linear Search"
},
{
"code": null,
"e": 6040,
"s": 5955,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 6078,
"s": 6040,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 6114,
"s": 6078,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 6145,
"s": 6114,
"text": "Hashing | Set 1 (Introduction)"
}
] |
Python | time.time() method
|
28 Aug, 2019
Time module in Python provides various time-related functions. This module comes under Python’s standard utility modules.
time.time() method of Time module is used to get the time in seconds since epoch. The handling of leap seconds is platform dependent.
Note: The epoch is the point where the time starts, and is platform dependent. On Windows and most Unix systems, the epoch is January 1, 1970, 00:00:00 (UTC) and leap seconds are not counted towards the time in seconds since the epoch. To check what the epoch is on a given platform we can use time.gmtime(0).
Syntax: time.time()
Parameter: No parameter is required
Return type: This method returns a float value which represents the time in seconds since the epoch.
Code #1: Use of time.time() method
# Python program to explain time.time() method # importing time moduleimport time # Get the epochobj = time.gmtime(0)epoch = time.asctime(obj)print("epoch is:", epoch) # Get the time in seconds# since the epochtime_sec = time.time() # Print the time print("Time in seconds since the epoch:", time_sec)
epoch is: Thu Jan 1 00:00:00 1970
Time in seconds since the epoch: 1566454995.8361387
Code #2: Calculate seconds between two date
# Python program to explain time.time() method # importing time moduleimport time # Date 1date1 = "1 Jan 2000 00:00:00" # Date 2# Current datedate2 = "22 Aug 2019 00:00:00" # Parse the date strings# and convert it in # time.struct_time object using# time.strptime() methodobj1 = time.strptime(date1, "% d % b % Y % H:% M:% S")obj2 = time.strptime(date2, "% d % b % Y % H:% M:% S") # Get the time in seconds# since the epoch# for both time.struct_time objectstime1 = time.mktime(obj1)time2 = time.mktime(obj2) print("Date 1:", time.asctime(obj1))print("Date 2:", time.asctime(obj2)) # Seconds between Date 1 and date 2seconds = time2 - time1print("Seconds between date 1 and date 2 is % f seconds" % seconds)
Date 1: Sat Jan 1 00:00:00 2000
Date 2: Thu Aug 22 00:00:00 2019
Seconds between date 1 and date 2 is 619747200.000000 seconds
Reference: https://docs.python.org/3/library/time.html#time.time
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Aug, 2019"
},
{
"code": null,
"e": 150,
"s": 28,
"text": "Time module in Python provides various time-related functions. This module comes under Python’s standard utility modules."
},
{
"code": null,
"e": 284,
"s": 150,
"text": "time.time() method of Time module is used to get the time in seconds since epoch. The handling of leap seconds is platform dependent."
},
{
"code": null,
"e": 594,
"s": 284,
"text": "Note: The epoch is the point where the time starts, and is platform dependent. On Windows and most Unix systems, the epoch is January 1, 1970, 00:00:00 (UTC) and leap seconds are not counted towards the time in seconds since the epoch. To check what the epoch is on a given platform we can use time.gmtime(0)."
},
{
"code": null,
"e": 614,
"s": 594,
"text": "Syntax: time.time()"
},
{
"code": null,
"e": 650,
"s": 614,
"text": "Parameter: No parameter is required"
},
{
"code": null,
"e": 751,
"s": 650,
"text": "Return type: This method returns a float value which represents the time in seconds since the epoch."
},
{
"code": null,
"e": 786,
"s": 751,
"text": "Code #1: Use of time.time() method"
},
{
"code": "# Python program to explain time.time() method # importing time moduleimport time # Get the epochobj = time.gmtime(0)epoch = time.asctime(obj)print(\"epoch is:\", epoch) # Get the time in seconds# since the epochtime_sec = time.time() # Print the time print(\"Time in seconds since the epoch:\", time_sec)",
"e": 1092,
"s": 786,
"text": null
},
{
"code": null,
"e": 1180,
"s": 1092,
"text": "epoch is: Thu Jan 1 00:00:00 1970\nTime in seconds since the epoch: 1566454995.8361387\n"
},
{
"code": null,
"e": 1224,
"s": 1180,
"text": "Code #2: Calculate seconds between two date"
},
{
"code": "# Python program to explain time.time() method # importing time moduleimport time # Date 1date1 = \"1 Jan 2000 00:00:00\" # Date 2# Current datedate2 = \"22 Aug 2019 00:00:00\" # Parse the date strings# and convert it in # time.struct_time object using# time.strptime() methodobj1 = time.strptime(date1, \"% d % b % Y % H:% M:% S\")obj2 = time.strptime(date2, \"% d % b % Y % H:% M:% S\") # Get the time in seconds# since the epoch# for both time.struct_time objectstime1 = time.mktime(obj1)time2 = time.mktime(obj2) print(\"Date 1:\", time.asctime(obj1))print(\"Date 2:\", time.asctime(obj2)) # Seconds between Date 1 and date 2seconds = time2 - time1print(\"Seconds between date 1 and date 2 is % f seconds\" % seconds)",
"e": 1941,
"s": 1224,
"text": null
},
{
"code": null,
"e": 2070,
"s": 1941,
"text": "Date 1: Sat Jan 1 00:00:00 2000\nDate 2: Thu Aug 22 00:00:00 2019\nSeconds between date 1 and date 2 is 619747200.000000 seconds\n"
},
{
"code": null,
"e": 2135,
"s": 2070,
"text": "Reference: https://docs.python.org/3/library/time.html#time.time"
},
{
"code": null,
"e": 2150,
"s": 2135,
"text": "python-utility"
},
{
"code": null,
"e": 2157,
"s": 2150,
"text": "Python"
},
{
"code": null,
"e": 2255,
"s": 2157,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2273,
"s": 2255,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2315,
"s": 2273,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2337,
"s": 2315,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2372,
"s": 2337,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2398,
"s": 2372,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2430,
"s": 2398,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2459,
"s": 2430,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2486,
"s": 2459,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2516,
"s": 2486,
"text": "Iterate over a list in Python"
}
] |
Can a constructor be private in C++ ?
|
21 Jul, 2017
Prerequisite : ConstructorsA constructor is a special member function of a class which initializes objects of a class. In C++, constructor is automatically called when object of a class is created.
By default, constructors are defined in public section of class. So, question is can a constructor be defined in private section of class ?Answer : Yes, Constructor can be defined in private section of class
How to use Constructors in private section?
Using Friend Class : If we want that class should not be instantiated by anyone else but only by a friend class.// CPP program to demonstrate usage of // private constructor#include <iostream>using namespace std; // class Aclass A{private: A(){ cout << "constructor of A\n"; } friend class B;}; // class B, friend of class Aclass B{public: B(){ A a1; cout << "constructor of B\n"; }}; // Driver programint main(){ B b1; return 0;}Output:constructor of A
constructor of B
If you comment the line friend class B, you will encounter below error:test1.cpp: In constructor ‘B::B()’:
test1.cpp:9:5: error: ‘A::A()’ is private
A(){
^
test1.cpp:19:11: error: within this context
A a1;
Using Singleton design pattern: When we want to design a singleton class. This means instead of creating several objects of class, the system is driven by a single object or a very limited number of objects.Named Constructor Idiom : Since constructor has same name as of class, different constructors are differentiated by their parameter list, but if numbers of constructors is more, then implementation can become error prone.With the Named Constructor Idiom, you declare all the class’s constructors in the private or protected sections, and then for accessing objects of class, you create public static functions.For example, consider below CPP program// CPP program to demonstrate// ambiguous nature of constructor// with same no of parameters of same type#include <iostream>using namespace std;class Point { public: // Rectangular coordinates Point(float x, float y); // Polar coordinates (radius and angle) Point(float r, float a); // error: ‘Point::Point(float, float)’ cannot // be overloaded};int main(){ // Ambiguous: Which constructor to be called ? Point p = Point(5.7, 1.2); return 0;}This problem can be resolved by Named Constructor Idiom. The above CPP program can be improved as following :// CPP program to demonstrate// named constructor idiom#include <iostream>#include <cmath>using namespace std;class Point { private: float x1, y1; Point(float x, float y) { x1 = x; y1 = y; };public: // polar(radius, angle) static Point Polar(float, float); // rectangular(x, y) static Point Rectangular(float, float); void display();}; // utility function for displaying of coordinatesvoid Point :: display(){ cout << "x :: " << this->x1 <<endl; cout << "y :: " << this->y1 <<endl;} // return polar coordinatesPoint Point :: Polar(float x, float y){ return Point(x*cos(y), x*sin(y));} // return rectangular coordinatesPoint Point :: Rectangular(float x, float y){ return Point(x,y);}int main(){ // Polar coordinates Point pp = Point::Polar(5.7, 1.2); cout << "polar coordinates \n"; pp.display(); // rectangular coordinates Point pr = Point::Rectangular(5.7,1.2); cout << "rectangular coordinates \n"; pr.display(); return 0;}Output :polar coordinates
x :: 2.06544
y :: 5.31262
rectangular coordinates
x :: 5.7
y :: 1.2
Using Friend Class : If we want that class should not be instantiated by anyone else but only by a friend class.// CPP program to demonstrate usage of // private constructor#include <iostream>using namespace std; // class Aclass A{private: A(){ cout << "constructor of A\n"; } friend class B;}; // class B, friend of class Aclass B{public: B(){ A a1; cout << "constructor of B\n"; }}; // Driver programint main(){ B b1; return 0;}Output:constructor of A
constructor of B
If you comment the line friend class B, you will encounter below error:test1.cpp: In constructor ‘B::B()’:
test1.cpp:9:5: error: ‘A::A()’ is private
A(){
^
test1.cpp:19:11: error: within this context
A a1;
// CPP program to demonstrate usage of // private constructor#include <iostream>using namespace std; // class Aclass A{private: A(){ cout << "constructor of A\n"; } friend class B;}; // class B, friend of class Aclass B{public: B(){ A a1; cout << "constructor of B\n"; }}; // Driver programint main(){ B b1; return 0;}
Output:
constructor of A
constructor of B
If you comment the line friend class B, you will encounter below error:
test1.cpp: In constructor ‘B::B()’:
test1.cpp:9:5: error: ‘A::A()’ is private
A(){
^
test1.cpp:19:11: error: within this context
A a1;
Using Singleton design pattern: When we want to design a singleton class. This means instead of creating several objects of class, the system is driven by a single object or a very limited number of objects.
Named Constructor Idiom : Since constructor has same name as of class, different constructors are differentiated by their parameter list, but if numbers of constructors is more, then implementation can become error prone.With the Named Constructor Idiom, you declare all the class’s constructors in the private or protected sections, and then for accessing objects of class, you create public static functions.For example, consider below CPP program// CPP program to demonstrate// ambiguous nature of constructor// with same no of parameters of same type#include <iostream>using namespace std;class Point { public: // Rectangular coordinates Point(float x, float y); // Polar coordinates (radius and angle) Point(float r, float a); // error: ‘Point::Point(float, float)’ cannot // be overloaded};int main(){ // Ambiguous: Which constructor to be called ? Point p = Point(5.7, 1.2); return 0;}This problem can be resolved by Named Constructor Idiom. The above CPP program can be improved as following :// CPP program to demonstrate// named constructor idiom#include <iostream>#include <cmath>using namespace std;class Point { private: float x1, y1; Point(float x, float y) { x1 = x; y1 = y; };public: // polar(radius, angle) static Point Polar(float, float); // rectangular(x, y) static Point Rectangular(float, float); void display();}; // utility function for displaying of coordinatesvoid Point :: display(){ cout << "x :: " << this->x1 <<endl; cout << "y :: " << this->y1 <<endl;} // return polar coordinatesPoint Point :: Polar(float x, float y){ return Point(x*cos(y), x*sin(y));} // return rectangular coordinatesPoint Point :: Rectangular(float x, float y){ return Point(x,y);}int main(){ // Polar coordinates Point pp = Point::Polar(5.7, 1.2); cout << "polar coordinates \n"; pp.display(); // rectangular coordinates Point pr = Point::Rectangular(5.7,1.2); cout << "rectangular coordinates \n"; pr.display(); return 0;}Output :polar coordinates
x :: 2.06544
y :: 5.31262
rectangular coordinates
x :: 5.7
y :: 1.2
With the Named Constructor Idiom, you declare all the class’s constructors in the private or protected sections, and then for accessing objects of class, you create public static functions.
For example, consider below CPP program
// CPP program to demonstrate// ambiguous nature of constructor// with same no of parameters of same type#include <iostream>using namespace std;class Point { public: // Rectangular coordinates Point(float x, float y); // Polar coordinates (radius and angle) Point(float r, float a); // error: ‘Point::Point(float, float)’ cannot // be overloaded};int main(){ // Ambiguous: Which constructor to be called ? Point p = Point(5.7, 1.2); return 0;}
This problem can be resolved by Named Constructor Idiom. The above CPP program can be improved as following :
// CPP program to demonstrate// named constructor idiom#include <iostream>#include <cmath>using namespace std;class Point { private: float x1, y1; Point(float x, float y) { x1 = x; y1 = y; };public: // polar(radius, angle) static Point Polar(float, float); // rectangular(x, y) static Point Rectangular(float, float); void display();}; // utility function for displaying of coordinatesvoid Point :: display(){ cout << "x :: " << this->x1 <<endl; cout << "y :: " << this->y1 <<endl;} // return polar coordinatesPoint Point :: Polar(float x, float y){ return Point(x*cos(y), x*sin(y));} // return rectangular coordinatesPoint Point :: Rectangular(float x, float y){ return Point(x,y);}int main(){ // Polar coordinates Point pp = Point::Polar(5.7, 1.2); cout << "polar coordinates \n"; pp.display(); // rectangular coordinates Point pr = Point::Rectangular(5.7,1.2); cout << "rectangular coordinates \n"; pr.display(); return 0;}
Output :
polar coordinates
x :: 2.06544
y :: 5.31262
rectangular coordinates
x :: 5.7
y :: 1.2
References :1) Named Constructor Idiom2) can a constructor be private in cpp
This article is contributed by Mandeep Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
cpp-constructor
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
std::string class in C++
Queue in C++ Standard Template Library (STL)
Unordered Sets in C++ Standard Template Library
std::find in C++
List in C++ Standard Template Library (STL)
Inline Functions in C++
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n21 Jul, 2017"
},
{
"code": null,
"e": 252,
"s": 54,
"text": "Prerequisite : ConstructorsA constructor is a special member function of a class which initializes objects of a class. In C++, constructor is automatically called when object of a class is created."
},
{
"code": null,
"e": 460,
"s": 252,
"text": "By default, constructors are defined in public section of class. So, question is can a constructor be defined in private section of class ?Answer : Yes, Constructor can be defined in private section of class"
},
{
"code": null,
"e": 504,
"s": 460,
"text": "How to use Constructors in private section?"
},
{
"code": null,
"e": 3634,
"s": 504,
"text": "Using Friend Class : If we want that class should not be instantiated by anyone else but only by a friend class.// CPP program to demonstrate usage of // private constructor#include <iostream>using namespace std; // class Aclass A{private: A(){ cout << \"constructor of A\\n\"; } friend class B;}; // class B, friend of class Aclass B{public: B(){ A a1; cout << \"constructor of B\\n\"; }}; // Driver programint main(){ B b1; return 0;}Output:constructor of A\nconstructor of B\nIf you comment the line friend class B, you will encounter below error:test1.cpp: In constructor ‘B::B()’:\ntest1.cpp:9:5: error: ‘A::A()’ is private\n A(){\n ^\ntest1.cpp:19:11: error: within this context\n A a1;\nUsing Singleton design pattern: When we want to design a singleton class. This means instead of creating several objects of class, the system is driven by a single object or a very limited number of objects.Named Constructor Idiom : Since constructor has same name as of class, different constructors are differentiated by their parameter list, but if numbers of constructors is more, then implementation can become error prone.With the Named Constructor Idiom, you declare all the class’s constructors in the private or protected sections, and then for accessing objects of class, you create public static functions.For example, consider below CPP program// CPP program to demonstrate// ambiguous nature of constructor// with same no of parameters of same type#include <iostream>using namespace std;class Point { public: // Rectangular coordinates Point(float x, float y); // Polar coordinates (radius and angle) Point(float r, float a); // error: ‘Point::Point(float, float)’ cannot // be overloaded};int main(){ // Ambiguous: Which constructor to be called ? Point p = Point(5.7, 1.2); return 0;}This problem can be resolved by Named Constructor Idiom. The above CPP program can be improved as following :// CPP program to demonstrate// named constructor idiom#include <iostream>#include <cmath>using namespace std;class Point { private: float x1, y1; Point(float x, float y) { x1 = x; y1 = y; };public: // polar(radius, angle) static Point Polar(float, float); // rectangular(x, y) static Point Rectangular(float, float); void display();}; // utility function for displaying of coordinatesvoid Point :: display(){ cout << \"x :: \" << this->x1 <<endl; cout << \"y :: \" << this->y1 <<endl;} // return polar coordinatesPoint Point :: Polar(float x, float y){ return Point(x*cos(y), x*sin(y));} // return rectangular coordinatesPoint Point :: Rectangular(float x, float y){ return Point(x,y);}int main(){ // Polar coordinates Point pp = Point::Polar(5.7, 1.2); cout << \"polar coordinates \\n\"; pp.display(); // rectangular coordinates Point pr = Point::Rectangular(5.7,1.2); cout << \"rectangular coordinates \\n\"; pr.display(); return 0;}Output :polar coordinates \nx :: 2.06544\ny :: 5.31262\nrectangular coordinates \nx :: 5.7\ny :: 1.2\n"
},
{
"code": null,
"e": 4375,
"s": 3634,
"text": "Using Friend Class : If we want that class should not be instantiated by anyone else but only by a friend class.// CPP program to demonstrate usage of // private constructor#include <iostream>using namespace std; // class Aclass A{private: A(){ cout << \"constructor of A\\n\"; } friend class B;}; // class B, friend of class Aclass B{public: B(){ A a1; cout << \"constructor of B\\n\"; }}; // Driver programint main(){ B b1; return 0;}Output:constructor of A\nconstructor of B\nIf you comment the line friend class B, you will encounter below error:test1.cpp: In constructor ‘B::B()’:\ntest1.cpp:9:5: error: ‘A::A()’ is private\n A(){\n ^\ntest1.cpp:19:11: error: within this context\n A a1;\n"
},
{
"code": "// CPP program to demonstrate usage of // private constructor#include <iostream>using namespace std; // class Aclass A{private: A(){ cout << \"constructor of A\\n\"; } friend class B;}; // class B, friend of class Aclass B{public: B(){ A a1; cout << \"constructor of B\\n\"; }}; // Driver programint main(){ B b1; return 0;}",
"e": 4738,
"s": 4375,
"text": null
},
{
"code": null,
"e": 4746,
"s": 4738,
"text": "Output:"
},
{
"code": null,
"e": 4781,
"s": 4746,
"text": "constructor of A\nconstructor of B\n"
},
{
"code": null,
"e": 4853,
"s": 4781,
"text": "If you comment the line friend class B, you will encounter below error:"
},
{
"code": null,
"e": 5008,
"s": 4853,
"text": "test1.cpp: In constructor ‘B::B()’:\ntest1.cpp:9:5: error: ‘A::A()’ is private\n A(){\n ^\ntest1.cpp:19:11: error: within this context\n A a1;\n"
},
{
"code": null,
"e": 5216,
"s": 5008,
"text": "Using Singleton design pattern: When we want to design a singleton class. This means instead of creating several objects of class, the system is driven by a single object or a very limited number of objects."
},
{
"code": null,
"e": 7399,
"s": 5216,
"text": "Named Constructor Idiom : Since constructor has same name as of class, different constructors are differentiated by their parameter list, but if numbers of constructors is more, then implementation can become error prone.With the Named Constructor Idiom, you declare all the class’s constructors in the private or protected sections, and then for accessing objects of class, you create public static functions.For example, consider below CPP program// CPP program to demonstrate// ambiguous nature of constructor// with same no of parameters of same type#include <iostream>using namespace std;class Point { public: // Rectangular coordinates Point(float x, float y); // Polar coordinates (radius and angle) Point(float r, float a); // error: ‘Point::Point(float, float)’ cannot // be overloaded};int main(){ // Ambiguous: Which constructor to be called ? Point p = Point(5.7, 1.2); return 0;}This problem can be resolved by Named Constructor Idiom. The above CPP program can be improved as following :// CPP program to demonstrate// named constructor idiom#include <iostream>#include <cmath>using namespace std;class Point { private: float x1, y1; Point(float x, float y) { x1 = x; y1 = y; };public: // polar(radius, angle) static Point Polar(float, float); // rectangular(x, y) static Point Rectangular(float, float); void display();}; // utility function for displaying of coordinatesvoid Point :: display(){ cout << \"x :: \" << this->x1 <<endl; cout << \"y :: \" << this->y1 <<endl;} // return polar coordinatesPoint Point :: Polar(float x, float y){ return Point(x*cos(y), x*sin(y));} // return rectangular coordinatesPoint Point :: Rectangular(float x, float y){ return Point(x,y);}int main(){ // Polar coordinates Point pp = Point::Polar(5.7, 1.2); cout << \"polar coordinates \\n\"; pp.display(); // rectangular coordinates Point pr = Point::Rectangular(5.7,1.2); cout << \"rectangular coordinates \\n\"; pr.display(); return 0;}Output :polar coordinates \nx :: 2.06544\ny :: 5.31262\nrectangular coordinates \nx :: 5.7\ny :: 1.2\n"
},
{
"code": null,
"e": 7589,
"s": 7399,
"text": "With the Named Constructor Idiom, you declare all the class’s constructors in the private or protected sections, and then for accessing objects of class, you create public static functions."
},
{
"code": null,
"e": 7629,
"s": 7589,
"text": "For example, consider below CPP program"
},
{
"code": "// CPP program to demonstrate// ambiguous nature of constructor// with same no of parameters of same type#include <iostream>using namespace std;class Point { public: // Rectangular coordinates Point(float x, float y); // Polar coordinates (radius and angle) Point(float r, float a); // error: ‘Point::Point(float, float)’ cannot // be overloaded};int main(){ // Ambiguous: Which constructor to be called ? Point p = Point(5.7, 1.2); return 0;}",
"e": 8132,
"s": 7629,
"text": null
},
{
"code": null,
"e": 8242,
"s": 8132,
"text": "This problem can be resolved by Named Constructor Idiom. The above CPP program can be improved as following :"
},
{
"code": "// CPP program to demonstrate// named constructor idiom#include <iostream>#include <cmath>using namespace std;class Point { private: float x1, y1; Point(float x, float y) { x1 = x; y1 = y; };public: // polar(radius, angle) static Point Polar(float, float); // rectangular(x, y) static Point Rectangular(float, float); void display();}; // utility function for displaying of coordinatesvoid Point :: display(){ cout << \"x :: \" << this->x1 <<endl; cout << \"y :: \" << this->y1 <<endl;} // return polar coordinatesPoint Point :: Polar(float x, float y){ return Point(x*cos(y), x*sin(y));} // return rectangular coordinatesPoint Point :: Rectangular(float x, float y){ return Point(x,y);}int main(){ // Polar coordinates Point pp = Point::Polar(5.7, 1.2); cout << \"polar coordinates \\n\"; pp.display(); // rectangular coordinates Point pr = Point::Rectangular(5.7,1.2); cout << \"rectangular coordinates \\n\"; pr.display(); return 0;}",
"e": 9269,
"s": 8242,
"text": null
},
{
"code": null,
"e": 9278,
"s": 9269,
"text": "Output :"
},
{
"code": null,
"e": 9367,
"s": 9278,
"text": "polar coordinates \nx :: 2.06544\ny :: 5.31262\nrectangular coordinates \nx :: 5.7\ny :: 1.2\n"
},
{
"code": null,
"e": 9444,
"s": 9367,
"text": "References :1) Named Constructor Idiom2) can a constructor be private in cpp"
},
{
"code": null,
"e": 9745,
"s": 9444,
"text": "This article is contributed by Mandeep Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 9870,
"s": 9745,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 9886,
"s": 9870,
"text": "cpp-constructor"
},
{
"code": null,
"e": 9890,
"s": 9886,
"text": "C++"
},
{
"code": null,
"e": 9894,
"s": 9890,
"text": "CPP"
},
{
"code": null,
"e": 9992,
"s": 9894,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10016,
"s": 9992,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 10036,
"s": 10016,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 10069,
"s": 10036,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 10113,
"s": 10069,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 10138,
"s": 10113,
"text": "std::string class in C++"
},
{
"code": null,
"e": 10183,
"s": 10138,
"text": "Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 10231,
"s": 10183,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 10248,
"s": 10231,
"text": "std::find in C++"
},
{
"code": null,
"e": 10292,
"s": 10248,
"text": "List in C++ Standard Template Library (STL)"
}
] |
How to Implement Current Location Button Feature in Google Maps in Android?
|
23 May, 2021
The current location is a feature on Google Maps, that helps us locate the device’s position on the Map. Through this article, while we will be implementing Google Maps, we shall also be implementing a button, which will fetch our current location and navigate it on the map. Note that we are going to implement this project using the Kotlin language.
Screenshot of the actual Google Map App on Android device
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.
Step 2: Get and hide the API key
Our application utilizes Google’s Places API to implement Google Map, so we need to get the Places API key from Google. To get an API key, please refer to Generating API Keys For Using Any Google APIs. Hiding an API key is essential and to do so, please refer to How to Hide API and Secret Keys in Android Studio?.
Step 3: Adding the dependencies in the build.gradle file
We need to add the below dependency for importing libraries to support the implementation of the Google Map.
implementation ‘com.google.android.libraries.places:places:2.4.0’
Step 4: Adding permissions to the application in the Manifest.xml file
As the application majorly deals with the current location, we give the application the permissions to access the location. To give the application such permissions, declare permissions between the manifest and application opening tags in the following way.
XML
<manifest...> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <application ...>
Step 5: Implementing a simple Button & Google Map fragment in the activity_main.xml file (front-end)
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. 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" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical"> <fragment xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/map" tools:context=".MapsActivity" android:name="com.google.android.gms.maps.SupportMapFragment" /> <Button android:id="@+id/currentLoc" android:layout_width="30sp" android:layout_height="40sp" android:layout_alignBottom="@id/map" android:layout_alignEnd="@id/map" android:layout_alignRight="@id/map" android:layout_marginRight="30sp" android:layout_marginBottom="30sp" /> </RelativeLayout>
Step 6: Working with MainActivity.kt (back-end)
What we did in short is:
Fetched the API key that we stored in Step 2.Initialized the Places API with the use of the API key.Initialized the Map fragment in the layout (activity_main.xml).Initialized fused location client.Initialized Button in the layout (activity_main.xml).Created a function to get the last location.Created a function to request a new location.Created a function for location callback.Created a function to check if the GPS of the device is turned on.Created a function to check if permissions for accessing the location are granted.Created a function to grant requests to permissions for accessing the location.Created a function to call getLastLocation() when permissions are granted.
Fetched the API key that we stored in Step 2.
Initialized the Places API with the use of the API key.
Initialized the Map fragment in the layout (activity_main.xml).
Initialized fused location client.
Initialized Button in the layout (activity_main.xml).
Created a function to get the last location.
Created a function to request a new location.
Created a function for location callback.
Created a function to check if the GPS of the device is turned on.
Created a function to check if permissions for accessing the location are granted.
Created a function to grant requests to permissions for accessing the location.
Created a function to call getLastLocation() when permissions are granted.
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
import android.Manifestimport android.annotation.SuppressLintimport android.content.Contextimport android.content.Intentimport android.content.pm.ApplicationInfoimport android.content.pm.PackageManagerimport android.location.Locationimport android.location.LocationManagerimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.os.Looperimport android.provider.Settingsimport android.widget.Buttonimport android.widget.Toastimport androidx.core.app.ActivityCompatimport com.google.android.gms.location.*import com.google.android.gms.maps.CameraUpdateFactoryimport com.google.android.gms.maps.GoogleMapimport com.google.android.gms.maps.OnMapReadyCallbackimport com.google.android.gms.maps.SupportMapFragmentimport com.google.android.gms.maps.model.LatLngimport com.google.android.gms.maps.model.MarkerOptionsimport com.google.android.libraries.places.api.Places class MainActivity : AppCompatActivity(), OnMapReadyCallback { private val pERMISSION_ID = 42 lateinit var mFusedLocationClient: FusedLocationProviderClient lateinit var mMap: GoogleMap // Current location is set to India, this will be of no use var currentLocation: LatLng = LatLng(20.5, 78.9) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Fetching API_KEY which we wrapped val ai: ApplicationInfo = applicationContext.packageManager .getApplicationInfo(applicationContext.packageName, PackageManager.GET_META_DATA) val value = ai.metaData["com.google.android.geo.API_KEY"] val apiKey = value.toString() // Initializing the Places API with the help of our API_KEY if (!Places.isInitialized()) { Places.initialize(applicationContext, apiKey) } // Initializing Map val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment mapFragment.getMapAsync(this) // Initializing fused location client mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this) // Adding functionality to the button val btn = findViewById<Button>(R.id.currentLoc) btn.setOnClickListener { getLastLocation() } } // Services such as getLastLocation() // will only run once map is ready override fun onMapReady(p0: GoogleMap) { mMap = p0 getLastLocation() } // Get current location @SuppressLint("MissingPermission") private fun getLastLocation() { if (checkPermissions()) { if (isLocationEnabled()) { mFusedLocationClient.lastLocation.addOnCompleteListener(this) { task -> val location: Location? = task.result if (location == null) { requestNewLocationData() } else { currentLocation = LatLng(location.latitude, location.longitude) mMap.clear() mMap.addMarker(MarkerOptions().position(currentLocation)) mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentLocation, 16F)) } } } else { Toast.makeText(this, "Turn on location", Toast.LENGTH_LONG).show() val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS) startActivity(intent) } } else { requestPermissions() } } // Get current location, if shifted // from previous location @SuppressLint("MissingPermission") private fun requestNewLocationData() { val mLocationRequest = LocationRequest() mLocationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY mLocationRequest.interval = 0 mLocationRequest.fastestInterval = 0 mLocationRequest.numUpdates = 1 mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this) mFusedLocationClient.requestLocationUpdates( mLocationRequest, mLocationCallback, Looper.myLooper() ) } // If current location could not be located, use last location private val mLocationCallback = object : LocationCallback() { override fun onLocationResult(locationResult: LocationResult) { val mLastLocation: Location = locationResult.lastLocation currentLocation = LatLng(mLastLocation.latitude, mLastLocation.longitude) } } // function to check if GPS is on private fun isLocationEnabled(): Boolean { val locationManager: LocationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled( LocationManager.NETWORK_PROVIDER ) } // Check if location permissions are // granted to the application private fun checkPermissions(): Boolean { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED ) { return true } return false } // Request permissions if not granted before private fun requestPermissions() { ActivityCompat.requestPermissions( this, arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION), pERMISSION_ID ) } // What must happen when permission is granted override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { if (requestCode == pERMISSION_ID) { if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) { getLastLocation() } } }}
Output:
Note: The application will prompt for permission requests, kindly allow once. Also, keep the device connected to the internet.
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android SDK and it's Components
Flutter - Custom Bottom Navigation Bar
How to Communicate Between Fragments in Android?
Retrofit with Kotlin Coroutine in Android
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android UI Layouts
Kotlin Array
How to Communicate Between Fragments in Android?
Retrofit with Kotlin Coroutine in Android
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 May, 2021"
},
{
"code": null,
"e": 405,
"s": 52,
"text": "The current location is a feature on Google Maps, that helps us locate the device’s position on the Map. Through this article, while we will be implementing Google Maps, we shall also be implementing a button, which will fetch our current location and navigate it on the map. Note that we are going to implement this project using the Kotlin language. "
},
{
"code": null,
"e": 463,
"s": 405,
"text": "Screenshot of the actual Google Map App on Android device"
},
{
"code": null,
"e": 510,
"s": 463,
"text": "Step 1: Create a New Project in Android Studio"
},
{
"code": null,
"e": 749,
"s": 510,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project."
},
{
"code": null,
"e": 783,
"s": 749,
"text": "Step 2: Get and hide the API key"
},
{
"code": null,
"e": 1098,
"s": 783,
"text": "Our application utilizes Google’s Places API to implement Google Map, so we need to get the Places API key from Google. To get an API key, please refer to Generating API Keys For Using Any Google APIs. Hiding an API key is essential and to do so, please refer to How to Hide API and Secret Keys in Android Studio?."
},
{
"code": null,
"e": 1155,
"s": 1098,
"text": "Step 3: Adding the dependencies in the build.gradle file"
},
{
"code": null,
"e": 1264,
"s": 1155,
"text": "We need to add the below dependency for importing libraries to support the implementation of the Google Map."
},
{
"code": null,
"e": 1330,
"s": 1264,
"text": "implementation ‘com.google.android.libraries.places:places:2.4.0’"
},
{
"code": null,
"e": 1401,
"s": 1330,
"text": "Step 4: Adding permissions to the application in the Manifest.xml file"
},
{
"code": null,
"e": 1659,
"s": 1401,
"text": "As the application majorly deals with the current location, we give the application the permissions to access the location. To give the application such permissions, declare permissions between the manifest and application opening tags in the following way."
},
{
"code": null,
"e": 1663,
"s": 1659,
"text": "XML"
},
{
"code": "<manifest...> <uses-permission android:name=\"android.permission.ACCESS_COARSE_LOCATION\"/> <uses-permission android:name=\"android.permission.ACCESS_FINE_LOCATION\"/> <application ...>",
"e": 1858,
"s": 1663,
"text": null
},
{
"code": null,
"e": 1959,
"s": 1858,
"text": "Step 5: Implementing a simple Button & Google Map fragment in the activity_main.xml file (front-end)"
},
{
"code": null,
"e": 2102,
"s": 1959,
"text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. "
},
{
"code": null,
"e": 2106,
"s": 2102,
"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\" android:gravity=\"center\" android:orientation=\"vertical\"> <fragment xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:id=\"@+id/map\" tools:context=\".MapsActivity\" android:name=\"com.google.android.gms.maps.SupportMapFragment\" /> <Button android:id=\"@+id/currentLoc\" android:layout_width=\"30sp\" android:layout_height=\"40sp\" android:layout_alignBottom=\"@id/map\" android:layout_alignEnd=\"@id/map\" android:layout_alignRight=\"@id/map\" android:layout_marginRight=\"30sp\" android:layout_marginBottom=\"30sp\" /> </RelativeLayout>",
"e": 3078,
"s": 2106,
"text": null
},
{
"code": null,
"e": 3126,
"s": 3078,
"text": "Step 6: Working with MainActivity.kt (back-end)"
},
{
"code": null,
"e": 3151,
"s": 3126,
"text": "What we did in short is:"
},
{
"code": null,
"e": 3833,
"s": 3151,
"text": "Fetched the API key that we stored in Step 2.Initialized the Places API with the use of the API key.Initialized the Map fragment in the layout (activity_main.xml).Initialized fused location client.Initialized Button in the layout (activity_main.xml).Created a function to get the last location.Created a function to request a new location.Created a function for location callback.Created a function to check if the GPS of the device is turned on.Created a function to check if permissions for accessing the location are granted.Created a function to grant requests to permissions for accessing the location.Created a function to call getLastLocation() when permissions are granted."
},
{
"code": null,
"e": 3879,
"s": 3833,
"text": "Fetched the API key that we stored in Step 2."
},
{
"code": null,
"e": 3935,
"s": 3879,
"text": "Initialized the Places API with the use of the API key."
},
{
"code": null,
"e": 3999,
"s": 3935,
"text": "Initialized the Map fragment in the layout (activity_main.xml)."
},
{
"code": null,
"e": 4034,
"s": 3999,
"text": "Initialized fused location client."
},
{
"code": null,
"e": 4088,
"s": 4034,
"text": "Initialized Button in the layout (activity_main.xml)."
},
{
"code": null,
"e": 4133,
"s": 4088,
"text": "Created a function to get the last location."
},
{
"code": null,
"e": 4179,
"s": 4133,
"text": "Created a function to request a new location."
},
{
"code": null,
"e": 4221,
"s": 4179,
"text": "Created a function for location callback."
},
{
"code": null,
"e": 4288,
"s": 4221,
"text": "Created a function to check if the GPS of the device is turned on."
},
{
"code": null,
"e": 4371,
"s": 4288,
"text": "Created a function to check if permissions for accessing the location are granted."
},
{
"code": null,
"e": 4451,
"s": 4371,
"text": "Created a function to grant requests to permissions for accessing the location."
},
{
"code": null,
"e": 4526,
"s": 4451,
"text": "Created a function to call getLastLocation() when permissions are granted."
},
{
"code": null,
"e": 4712,
"s": 4526,
"text": "Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 4719,
"s": 4712,
"text": "Kotlin"
},
{
"code": "import android.Manifestimport android.annotation.SuppressLintimport android.content.Contextimport android.content.Intentimport android.content.pm.ApplicationInfoimport android.content.pm.PackageManagerimport android.location.Locationimport android.location.LocationManagerimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.os.Looperimport android.provider.Settingsimport android.widget.Buttonimport android.widget.Toastimport androidx.core.app.ActivityCompatimport com.google.android.gms.location.*import com.google.android.gms.maps.CameraUpdateFactoryimport com.google.android.gms.maps.GoogleMapimport com.google.android.gms.maps.OnMapReadyCallbackimport com.google.android.gms.maps.SupportMapFragmentimport com.google.android.gms.maps.model.LatLngimport com.google.android.gms.maps.model.MarkerOptionsimport com.google.android.libraries.places.api.Places class MainActivity : AppCompatActivity(), OnMapReadyCallback { private val pERMISSION_ID = 42 lateinit var mFusedLocationClient: FusedLocationProviderClient lateinit var mMap: GoogleMap // Current location is set to India, this will be of no use var currentLocation: LatLng = LatLng(20.5, 78.9) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Fetching API_KEY which we wrapped val ai: ApplicationInfo = applicationContext.packageManager .getApplicationInfo(applicationContext.packageName, PackageManager.GET_META_DATA) val value = ai.metaData[\"com.google.android.geo.API_KEY\"] val apiKey = value.toString() // Initializing the Places API with the help of our API_KEY if (!Places.isInitialized()) { Places.initialize(applicationContext, apiKey) } // Initializing Map val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment mapFragment.getMapAsync(this) // Initializing fused location client mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this) // Adding functionality to the button val btn = findViewById<Button>(R.id.currentLoc) btn.setOnClickListener { getLastLocation() } } // Services such as getLastLocation() // will only run once map is ready override fun onMapReady(p0: GoogleMap) { mMap = p0 getLastLocation() } // Get current location @SuppressLint(\"MissingPermission\") private fun getLastLocation() { if (checkPermissions()) { if (isLocationEnabled()) { mFusedLocationClient.lastLocation.addOnCompleteListener(this) { task -> val location: Location? = task.result if (location == null) { requestNewLocationData() } else { currentLocation = LatLng(location.latitude, location.longitude) mMap.clear() mMap.addMarker(MarkerOptions().position(currentLocation)) mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentLocation, 16F)) } } } else { Toast.makeText(this, \"Turn on location\", Toast.LENGTH_LONG).show() val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS) startActivity(intent) } } else { requestPermissions() } } // Get current location, if shifted // from previous location @SuppressLint(\"MissingPermission\") private fun requestNewLocationData() { val mLocationRequest = LocationRequest() mLocationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY mLocationRequest.interval = 0 mLocationRequest.fastestInterval = 0 mLocationRequest.numUpdates = 1 mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this) mFusedLocationClient.requestLocationUpdates( mLocationRequest, mLocationCallback, Looper.myLooper() ) } // If current location could not be located, use last location private val mLocationCallback = object : LocationCallback() { override fun onLocationResult(locationResult: LocationResult) { val mLastLocation: Location = locationResult.lastLocation currentLocation = LatLng(mLastLocation.latitude, mLastLocation.longitude) } } // function to check if GPS is on private fun isLocationEnabled(): Boolean { val locationManager: LocationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled( LocationManager.NETWORK_PROVIDER ) } // Check if location permissions are // granted to the application private fun checkPermissions(): Boolean { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED ) { return true } return false } // Request permissions if not granted before private fun requestPermissions() { ActivityCompat.requestPermissions( this, arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION), pERMISSION_ID ) } // What must happen when permission is granted override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { if (requestCode == pERMISSION_ID) { if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) { getLastLocation() } } }}",
"e": 10760,
"s": 4719,
"text": null
},
{
"code": null,
"e": 10768,
"s": 10760,
"text": "Output:"
},
{
"code": null,
"e": 10895,
"s": 10768,
"text": "Note: The application will prompt for permission requests, kindly allow once. Also, keep the device connected to the internet."
},
{
"code": null,
"e": 10903,
"s": 10895,
"text": "Android"
},
{
"code": null,
"e": 10910,
"s": 10903,
"text": "Kotlin"
},
{
"code": null,
"e": 10918,
"s": 10910,
"text": "Android"
},
{
"code": null,
"e": 11016,
"s": 10918,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11085,
"s": 11016,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 11117,
"s": 11085,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 11156,
"s": 11117,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 11205,
"s": 11156,
"text": "How to Communicate Between Fragments in Android?"
},
{
"code": null,
"e": 11247,
"s": 11205,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 11316,
"s": 11247,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 11335,
"s": 11316,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 11348,
"s": 11335,
"text": "Kotlin Array"
},
{
"code": null,
"e": 11397,
"s": 11348,
"text": "How to Communicate Between Fragments in Android?"
}
] |
Count n digit numbers divisible by given number
|
02 Jun, 2022
Given number of digit n and a number, the task is to count all the numbers which are divisible by that number and having n digit.Examples :
Input : n = 2, number = 7
Output : 9
There are nine n digit numbers that
are divisible by 7. Numbers are 14,
21, 28, 35, 42, 49, .... 70.
Input : n = 3, number = 7
Output : 128
Input : n = 4, number = 4
Output : 2250
Native Approach: Traverse through all n digit numbers. For every number check for divisibility,
C++
Java
Python3
C#
PHP
Javascript
// Simple CPP program to count n digit// divisible numbers.#include <cmath>#include <iostream>using namespace std; // Returns count of n digit numbers// divisible by 'number'int numberofterm(int n, int number){ // compute the first and last term int firstnum = pow(10, n - 1); int lastnum = pow(10, n); // count total number of which having // n digit and divisible by number int count = 0; for (int i = firstnum; i < lastnum; i++) if (i % number == 0) count++; return count;} // Driver codeint main(){ int n = 3, num = 7; cout << numberofterm(n, num) << "\n"; return 0;}
// Simple Java program to count n digit// divisible numbers.import java.io.*; class GFG { // Returns count of n digit numbers // divisible by 'number' static int numberofterm(int n, int number) { // compute the first and last term int firstnum = (int)Math.pow(10, n - 1); int lastnum = (int)Math.pow(10, n); // count total number of which having // n digit and divisible by number int count = 0; for (int i = firstnum; i < lastnum; i++) if (i % number == 0) count++; return count; } // Driver code public static void main (String[] args) { int n = 3, num = 7; System.out.println(numberofterm(n, num)); }} // This code is contributed by Ajit.
# Simple Python 3 program to count n digit# divisible numbers import math # Returns count of n digit# numbers divisible by numberdef numberofterm(n, number): # compute the first and last term firstnum = math.pow(10, n - 1) lastnum = math.pow(10, n) # count total number of which having # n digit and divisible by number count = 0 for i in range(int(firstnum), int(lastnum)): if (i % number == 0): count += 1 return count # Driver coden = 3num = 7print(numberofterm(n, num)) # This article is contributed# by Smitha Dinesh Semwal
// Simple C# program to count n digit// divisible numbers.using System; class GFG{ // Returns count of n digit numbers // divisible by 'number' static int numberofterm(int n, int number) { // compute the first and last term int firstnum = (int)Math.Pow(10, n - 1); int lastnum = (int)Math.Pow(10, n); // count total number of which having // n digit and divisible by number int count = 0; for (int i = firstnum; i < lastnum; i++) if (i % number == 0) count++; return count; } // Driver code public static void Main () { int n = 3, num = 7; Console.Write(numberofterm(n, num)); }} // This code is contributed by nitin mittal
<?php// Simple php program to count n digit// divisible numbers. // Returns count of n digit numbers// divisible by 'number'function numberofterm($n, $number){ // compute the first and last term $firstnum = pow(10, $n - 1); $lastnum = pow(10, $n); // count total number of which having // n digit and divisible by number $count = 0; for ($i = $firstnum; $i < $lastnum; $i++) if ($i % $number == 0) $count++; return $count;} // Driver code $n = 3; $num = 7; echo numberofterm($n, $num); // This code is contributed by mits?>
<script>// JavaScript program to count n digit// divisible numbers. // Returns count of n digit numbers // divisible by 'number' function numberofterm(n, number) { // compute the first and last term let firstnum = Math.pow(10, n - 1); let lastnum = Math.pow(10, n); // count total number of which having // n digit and divisible by number let count = 0; for (let i = firstnum; i < lastnum; i++) if (i % number == 0) count++; return count; } // Driver Code let n = 3, num = 7; document.write(numberofterm(n, num)); // This code is contributed by code_hunt.</script>
128
Time Complexity: O(10n), which is exponential and bad for bigger n’s.
Auxiliary Space: O(1)
Efficient Approach: Find the first and last terms divisible, then apply the below formula
Count of divisible = (lastnumber – firstnumber)/number + 1
C++
Java
Python3
C#
PHP
Javascript
// Efficient CPP program to count n digit// divisible numbers.#include <cmath>#include <iostream>using namespace std; // find the number of termint numberofterm(int digit, int number){ // compute the first and last term int firstnum = pow(10, digit - 1); int lastnum = pow(10, digit); // first number which is divisible by given number firstnum = (firstnum - firstnum % number) + number; // last number which is divisible by given number lastnum = (lastnum - lastnum % number); // Apply the formula here return ((lastnum - firstnum) / number + 1);} int main(){ int n = 3; int number = 7; cout << numberofterm(n, number) << "\n"; return 0;}
// Efficient Java program to count n digit// divisible numbers.import java.io.*; class GFG { // find the number of term static int numberofterm(int digit, int number) { // compute the first and last term int firstnum = (int)Math.pow(10, digit - 1); int lastnum = (int)Math.pow(10, digit); // first number which is divisible by given number firstnum = (firstnum - firstnum % number) + number; // last number which is divisible by given number lastnum = (lastnum - lastnum % number); // Apply the formula here return ((lastnum - firstnum) / number + 1); } // Driver code public static void main (String[] args) { int n = 3; int number = 7; System.out.println(numberofterm(n, number)); }} // This code is contributed by Ajit.
# Efficient Python program to # count n digit divisible numbers. # Find the number of termdef numberofterm(digit, number): # compute the first and last term firstnum = pow(10, digit - 1) lastnum = pow(10, digit) # First number which is divisible by given number firstnum = (firstnum - firstnum % number) + number # last number which is divisible by given number lastnum = (lastnum - lastnum % number) # Apply the formula here return ((lastnum - firstnum) // number + 1); # Driver coden = 3; number = 7print(numberofterm(n, number)) # This code is contributed by Ajit.
// Efficient C# program to count n digit// divisible numbers.using System; class GFG { // find the number of term static int numberofterm(int digit, int number) { // compute the first and // last term int firstnum = (int)Math.Pow(10, digit - 1); int lastnum = (int)Math.Pow(10, digit); // first number which is divisible // by given number firstnum = (firstnum - firstnum % number) + number; // last number which is divisible // by given number lastnum = (lastnum - lastnum % number); // Apply the formula here return ((lastnum - firstnum) / number + 1); } // Driver code public static void Main () { int n = 3; int number = 7; Console.WriteLine( numberofterm(n, number)); }} // This code is contributed by anuj_67.
<?php// Efficient PHP program// to count n digit// divisible numbers. // find the number of termfunction numberofterm($digit, $number){ // compute the first // and last term $firstnum = pow(10, $digit - 1); $lastnum = pow(10, $digit); // first number which is // divisible by given number $firstnum = ($firstnum - $firstnum % $number) + $number; // last number which is // divisible by given number $lastnum = ($lastnum - $lastnum % $number); // Apply the formula here return (($lastnum - $firstnum) / $number + 1);} // Driver Code$n = 3;$number = 7;echo (numberofterm($n, $number)); // This code is contributed by// Manish Shaw(manishshaw1)?>
<script> // Efficient Javascript program to count n digit divisible numbers. // find the number of term function numberofterm(digit, number) { // compute the first and // last term let firstnum = Math.pow(10, digit - 1); let lastnum = Math.pow(10, digit); // first number which is divisible // by given number firstnum = (firstnum - firstnum % number) + number; // last number which is divisible // by given number lastnum = (lastnum - lastnum % number); // Apply the formula here return ((lastnum - firstnum) / number + 1); } let n = 3; let number = 7; document.write(numberofterm(n, number)); // This code is contributed by divyeshrabadiya07.</script>
128
Time Complexity: O(1)
Auxiliary Space: O(1)
nitin mittal
Mithun Kumar
vt_m
manishshaw1
code_hunt
divyeshrabadiya07
rohitmishra051000
divisibility
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n02 Jun, 2022"
},
{
"code": null,
"e": 194,
"s": 52,
"text": "Given number of digit n and a number, the task is to count all the numbers which are divisible by that number and having n digit.Examples : "
},
{
"code": null,
"e": 414,
"s": 194,
"text": "Input : n = 2, number = 7\nOutput : 9\nThere are nine n digit numbers that\nare divisible by 7. Numbers are 14, \n21, 28, 35, 42, 49, .... 70.\n\nInput : n = 3, number = 7\nOutput : 128\n\nInput : n = 4, number = 4\nOutput : 2250"
},
{
"code": null,
"e": 514,
"s": 416,
"text": "Native Approach: Traverse through all n digit numbers. For every number check for divisibility, "
},
{
"code": null,
"e": 518,
"s": 514,
"text": "C++"
},
{
"code": null,
"e": 523,
"s": 518,
"text": "Java"
},
{
"code": null,
"e": 531,
"s": 523,
"text": "Python3"
},
{
"code": null,
"e": 534,
"s": 531,
"text": "C#"
},
{
"code": null,
"e": 538,
"s": 534,
"text": "PHP"
},
{
"code": null,
"e": 549,
"s": 538,
"text": "Javascript"
},
{
"code": "// Simple CPP program to count n digit// divisible numbers.#include <cmath>#include <iostream>using namespace std; // Returns count of n digit numbers// divisible by 'number'int numberofterm(int n, int number){ // compute the first and last term int firstnum = pow(10, n - 1); int lastnum = pow(10, n); // count total number of which having // n digit and divisible by number int count = 0; for (int i = firstnum; i < lastnum; i++) if (i % number == 0) count++; return count;} // Driver codeint main(){ int n = 3, num = 7; cout << numberofterm(n, num) << \"\\n\"; return 0;}",
"e": 1173,
"s": 549,
"text": null
},
{
"code": "// Simple Java program to count n digit// divisible numbers.import java.io.*; class GFG { // Returns count of n digit numbers // divisible by 'number' static int numberofterm(int n, int number) { // compute the first and last term int firstnum = (int)Math.pow(10, n - 1); int lastnum = (int)Math.pow(10, n); // count total number of which having // n digit and divisible by number int count = 0; for (int i = firstnum; i < lastnum; i++) if (i % number == 0) count++; return count; } // Driver code public static void main (String[] args) { int n = 3, num = 7; System.out.println(numberofterm(n, num)); }} // This code is contributed by Ajit.",
"e": 1953,
"s": 1173,
"text": null
},
{
"code": "# Simple Python 3 program to count n digit# divisible numbers import math # Returns count of n digit# numbers divisible by numberdef numberofterm(n, number): # compute the first and last term firstnum = math.pow(10, n - 1) lastnum = math.pow(10, n) # count total number of which having # n digit and divisible by number count = 0 for i in range(int(firstnum), int(lastnum)): if (i % number == 0): count += 1 return count # Driver coden = 3num = 7print(numberofterm(n, num)) # This article is contributed# by Smitha Dinesh Semwal",
"e": 2527,
"s": 1953,
"text": null
},
{
"code": "// Simple C# program to count n digit// divisible numbers.using System; class GFG{ // Returns count of n digit numbers // divisible by 'number' static int numberofterm(int n, int number) { // compute the first and last term int firstnum = (int)Math.Pow(10, n - 1); int lastnum = (int)Math.Pow(10, n); // count total number of which having // n digit and divisible by number int count = 0; for (int i = firstnum; i < lastnum; i++) if (i % number == 0) count++; return count; } // Driver code public static void Main () { int n = 3, num = 7; Console.Write(numberofterm(n, num)); }} // This code is contributed by nitin mittal",
"e": 3289,
"s": 2527,
"text": null
},
{
"code": "<?php// Simple php program to count n digit// divisible numbers. // Returns count of n digit numbers// divisible by 'number'function numberofterm($n, $number){ // compute the first and last term $firstnum = pow(10, $n - 1); $lastnum = pow(10, $n); // count total number of which having // n digit and divisible by number $count = 0; for ($i = $firstnum; $i < $lastnum; $i++) if ($i % $number == 0) $count++; return $count;} // Driver code $n = 3; $num = 7; echo numberofterm($n, $num); // This code is contributed by mits?>",
"e": 3878,
"s": 3289,
"text": null
},
{
"code": "<script>// JavaScript program to count n digit// divisible numbers. // Returns count of n digit numbers // divisible by 'number' function numberofterm(n, number) { // compute the first and last term let firstnum = Math.pow(10, n - 1); let lastnum = Math.pow(10, n); // count total number of which having // n digit and divisible by number let count = 0; for (let i = firstnum; i < lastnum; i++) if (i % number == 0) count++; return count; } // Driver Code let n = 3, num = 7; document.write(numberofterm(n, num)); // This code is contributed by code_hunt.</script>",
"e": 4559,
"s": 3878,
"text": null
},
{
"code": null,
"e": 4563,
"s": 4559,
"text": "128"
},
{
"code": null,
"e": 4635,
"s": 4565,
"text": "Time Complexity: O(10n), which is exponential and bad for bigger n’s."
},
{
"code": null,
"e": 4657,
"s": 4635,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 4748,
"s": 4657,
"text": "Efficient Approach: Find the first and last terms divisible, then apply the below formula "
},
{
"code": null,
"e": 4807,
"s": 4748,
"text": "Count of divisible = (lastnumber – firstnumber)/number + 1"
},
{
"code": null,
"e": 4813,
"s": 4809,
"text": "C++"
},
{
"code": null,
"e": 4818,
"s": 4813,
"text": "Java"
},
{
"code": null,
"e": 4826,
"s": 4818,
"text": "Python3"
},
{
"code": null,
"e": 4829,
"s": 4826,
"text": "C#"
},
{
"code": null,
"e": 4833,
"s": 4829,
"text": "PHP"
},
{
"code": null,
"e": 4844,
"s": 4833,
"text": "Javascript"
},
{
"code": "// Efficient CPP program to count n digit// divisible numbers.#include <cmath>#include <iostream>using namespace std; // find the number of termint numberofterm(int digit, int number){ // compute the first and last term int firstnum = pow(10, digit - 1); int lastnum = pow(10, digit); // first number which is divisible by given number firstnum = (firstnum - firstnum % number) + number; // last number which is divisible by given number lastnum = (lastnum - lastnum % number); // Apply the formula here return ((lastnum - firstnum) / number + 1);} int main(){ int n = 3; int number = 7; cout << numberofterm(n, number) << \"\\n\"; return 0;}",
"e": 5526,
"s": 4844,
"text": null
},
{
"code": "// Efficient Java program to count n digit// divisible numbers.import java.io.*; class GFG { // find the number of term static int numberofterm(int digit, int number) { // compute the first and last term int firstnum = (int)Math.pow(10, digit - 1); int lastnum = (int)Math.pow(10, digit); // first number which is divisible by given number firstnum = (firstnum - firstnum % number) + number; // last number which is divisible by given number lastnum = (lastnum - lastnum % number); // Apply the formula here return ((lastnum - firstnum) / number + 1); } // Driver code public static void main (String[] args) { int n = 3; int number = 7; System.out.println(numberofterm(n, number)); }} // This code is contributed by Ajit.",
"e": 6378,
"s": 5526,
"text": null
},
{
"code": "# Efficient Python program to # count n digit divisible numbers. # Find the number of termdef numberofterm(digit, number): # compute the first and last term firstnum = pow(10, digit - 1) lastnum = pow(10, digit) # First number which is divisible by given number firstnum = (firstnum - firstnum % number) + number # last number which is divisible by given number lastnum = (lastnum - lastnum % number) # Apply the formula here return ((lastnum - firstnum) // number + 1); # Driver coden = 3; number = 7print(numberofterm(n, number)) # This code is contributed by Ajit.",
"e": 6981,
"s": 6378,
"text": null
},
{
"code": "// Efficient C# program to count n digit// divisible numbers.using System; class GFG { // find the number of term static int numberofterm(int digit, int number) { // compute the first and // last term int firstnum = (int)Math.Pow(10, digit - 1); int lastnum = (int)Math.Pow(10, digit); // first number which is divisible // by given number firstnum = (firstnum - firstnum % number) + number; // last number which is divisible // by given number lastnum = (lastnum - lastnum % number); // Apply the formula here return ((lastnum - firstnum) / number + 1); } // Driver code public static void Main () { int n = 3; int number = 7; Console.WriteLine( numberofterm(n, number)); }} // This code is contributed by anuj_67.",
"e": 8068,
"s": 6981,
"text": null
},
{
"code": "<?php// Efficient PHP program// to count n digit// divisible numbers. // find the number of termfunction numberofterm($digit, $number){ // compute the first // and last term $firstnum = pow(10, $digit - 1); $lastnum = pow(10, $digit); // first number which is // divisible by given number $firstnum = ($firstnum - $firstnum % $number) + $number; // last number which is // divisible by given number $lastnum = ($lastnum - $lastnum % $number); // Apply the formula here return (($lastnum - $firstnum) / $number + 1);} // Driver Code$n = 3;$number = 7;echo (numberofterm($n, $number)); // This code is contributed by// Manish Shaw(manishshaw1)?>",
"e": 8837,
"s": 8068,
"text": null
},
{
"code": "<script> // Efficient Javascript program to count n digit divisible numbers. // find the number of term function numberofterm(digit, number) { // compute the first and // last term let firstnum = Math.pow(10, digit - 1); let lastnum = Math.pow(10, digit); // first number which is divisible // by given number firstnum = (firstnum - firstnum % number) + number; // last number which is divisible // by given number lastnum = (lastnum - lastnum % number); // Apply the formula here return ((lastnum - firstnum) / number + 1); } let n = 3; let number = 7; document.write(numberofterm(n, number)); // This code is contributed by divyeshrabadiya07.</script>",
"e": 9671,
"s": 8837,
"text": null
},
{
"code": null,
"e": 9675,
"s": 9671,
"text": "128"
},
{
"code": null,
"e": 9699,
"s": 9677,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 9721,
"s": 9699,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 9734,
"s": 9721,
"text": "nitin mittal"
},
{
"code": null,
"e": 9747,
"s": 9734,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 9752,
"s": 9747,
"text": "vt_m"
},
{
"code": null,
"e": 9764,
"s": 9752,
"text": "manishshaw1"
},
{
"code": null,
"e": 9774,
"s": 9764,
"text": "code_hunt"
},
{
"code": null,
"e": 9792,
"s": 9774,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 9810,
"s": 9792,
"text": "rohitmishra051000"
},
{
"code": null,
"e": 9823,
"s": 9810,
"text": "divisibility"
},
{
"code": null,
"e": 9836,
"s": 9823,
"text": "Mathematical"
},
{
"code": null,
"e": 9849,
"s": 9836,
"text": "Mathematical"
}
] |
Minimum time to burn a Tree starting from a Leaf node
|
13 Jul, 2021
Given a binary tree and a leaf node from this tree. It is known that in 1s all nodes connected to a given node (left child, right child and parent) get burned in 1 second. Then all the nodes which are connected through one intermediate get burned in 2 seconds, and so on. The task is to find the minimum time required to burn the complete binary tree.Examples:
Input :
1
/ \
2 3
/ \ \
4 5 6
/ \ \
7 8 9
\
10
Leaf = 8
Output : 7
Initially 8 is set to fire at 0th sec.
1
/ \
2 3
/ \ \
4 5 6
/ \ \
7 F 9
\
10
After 1s: 5 is set to fire.
1
/ \
2 3
/ \ \
4 F 6
/ \ \
7 F 9
\
10
After 2s: 2, 7 are set to fire.
1
/ \
F 3
/ \ \
4 F 6
/ \ \
F F 9
\
10
After 3s: 4, 1 are set to fire.
F
/ \
F 3
/ \ \
F F 6
/ \ \
F F 9
\
10
After 4s: 3 is set to fire.
F
/ \
F F
/ \ \
F F 6
/ \ \
F F 9
\
10
After 5s: 6 is set to fire.
F
/ \
F F
/ \ \
F F F
/ \ \
F F 9
\
10
After 6s: 9 is set to fire.
F
/ \
F F
/ \ \
F F F
/ \ \
F F F
\
10
After 7s: 10 is set to fire.
F
/ \
F F
/ \ \
F F F
/ \ \
F F F
\
F
It takes 7s to burn the complete tree.
The idea is to store additional information for every node:
Depth of left subtree.
Depth of right subtree.
The time required for the fire to reach the current node starting from the first leaf node burned.
A boolean variable to check if the initial burnt node is in the tree rooted under current node.
Before moving ahead with the approach let’s take a look at the tree below:
1
/ \
2 3
/ \ /
4 5 6
/ / \
8 9 10
/
11
In the above tree, if we set the leaf node 11 at fire.
In 1s, the fire will reach node 9.In 2s, the fire will reach node 5.In 3rd second, the fire will reach node 2 and 10. Here comes an observation: In 2s fire reached node 5. For node 5, the initial burned leaf is in it’s left subtree, so the time taken to burn right subtree will be the height of the right subtree which is 1. Therefore, fire reaches to node 10 in (2+1) = 3s.Again, for the node 2. Fire reached to node 2 in 3s from right subtree. Therefore, time taken to burn left subtree will be it’s height.
In 1s, the fire will reach node 9.
In 2s, the fire will reach node 5.
In 3rd second, the fire will reach node 2 and 10. Here comes an observation: In 2s fire reached node 5. For node 5, the initial burned leaf is in it’s left subtree, so the time taken to burn right subtree will be the height of the right subtree which is 1. Therefore, fire reaches to node 10 in (2+1) = 3s.Again, for the node 2. Fire reached to node 2 in 3s from right subtree. Therefore, time taken to burn left subtree will be it’s height.
In 2s fire reached node 5. For node 5, the initial burned leaf is in it’s left subtree, so the time taken to burn right subtree will be the height of the right subtree which is 1. Therefore, fire reaches to node 10 in (2+1) = 3s.
Again, for the node 2. Fire reached to node 2 in 3s from right subtree. Therefore, time taken to burn left subtree will be it’s height.
So the solution is to apply recursion and for every node calculate the below-required values:
Left Depth.
Right Depth.
The time required for fire to reach the current node.
Is the current subtree contains initial burnt leaf node.
So, for the minimum time required to burn any subtree will be:
The time required for fire to reach the root node from initial burnt leaf + depth of the opposite side
Therefore, to find time required to burn the complete tree, we need to calculate the above value for every node, and take maximum of that value.
ans = max(ans, (time required for fire to reach current node + depth of other subtree))
Below is the implementation of the above approach:
C++
Java
Python3
C#
// C++ program to find minimum time required// to burn the binary tree completely #include <bits/stdc++.h>using namespace std; // Tree Nodestruct Node { int data; Node* left; Node* right; Node() { left = NULL; right = NULL; }}; // Utility function to create a new NodeNode* newNode(int val){ Node* temp = new Node; temp->data = val; return temp;} /* ***********ADDITIONAL INFO************* lDepth - maximum height of left subtree rDepth - maximum height of right subtree contains - stores true if tree rooted at current node contains the first burnt node time - time to reach fire from the initially burnt leaf node to this node*/struct Info { int lDepth; int rDepth; bool contains; int time; Info() { lDepth = rDepth = 0; contains = false; time = -1; }}; /* Function to calculate time required to burn tree completely node - address of current node info - extra information about current node target - node that is fired res - stores the result*/Info calcTime(Node* node, Info& info, int target, int& res){ // Base case: if root is null if (node == NULL) { return info; } // If current node is leaf if (node->left == NULL && node->right == NULL) { // If current node is the first burnt node if (node->data == target) { info.contains = true; info.time = 0; } return info; } // Information about left child of root Info leftInfo; calcTime(node->left, leftInfo, target, res); // Information about right child of root Info rightInfo; calcTime(node->right, rightInfo, target, res); // If left subtree contains the fired node then // time required to reach fire to current node // will be (1 + time required for left child) info.time = (node->left && leftInfo.contains) ? (leftInfo.time + 1) : -1; // If right subtree contains the fired node then // time required to reach fire to current node // will be (1 + time required for right child) if (info.time == -1) info.time = (node->right && rightInfo.contains) ? (rightInfo.time + 1) : -1; // Storing(true or false) if the tree rooted at // current node contains the fired node info.contains = ((node->left && leftInfo.contains) || (node->right && rightInfo.contains)); // Calculate the maximum depth of left subtree info.lDepth = !(node->left) ? 0 : (1 + max(leftInfo.lDepth, leftInfo.rDepth)); // Calculate the maximum depth of right subtree info.rDepth = !(node->right) ? 0 : (1 + max(rightInfo.lDepth, rightInfo.rDepth)); // Calculating answer if (info.contains) { // If left subtree exists and // it contains the fired node if (node->left && leftInfo.contains) { // calculate result res = max(res, info.time + info.rDepth); } // If right subtree exists and it // contains the fired node if (node->right && rightInfo.contains) { // calculate result res = max(res, info.time + info.lDepth); } }} // Driver function to calculate minimum// time requiredint minTime(Node* root, int target){ int res = 0; Info info; calcTime(root, info, target, res); return res;} // Driver Codeint main(){ Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->left->left->left = newNode(8); root->left->right->left = newNode(9); root->left->right->right = newNode(10); root->left->right->left->left = newNode(11); // target node is 8 int target = 11; cout << minTime(root, target); return 0;}
// Java program to find minimum time required// to burn the binary tree completely public class GFG { // Tree Node static class Node { int data; Node left, right; Node(int data) { this.data = data; this.left = null; this.right = null; } } /* ***********ADDITIONAL INFO************* lDepth - maximum height of left subtree rDepth - maximum height of right subtree contains - stores true if tree rooted at current node contains the first burnt node time - time to reach fire from the initially burnt leaf node to this node */ static class Data { int leftDepth, rightDepth, time; boolean contains; Data() { contains = false; leftDepth = rightDepth = 0; time = -1; } } /* Function to calculate time required to burn tree completely node - address of current node info - extra information about current node target - node that is fired res - stores the result */ public static void getResult(Node node, Data data, int target) { // Base case: if root is null if (node == null) { return; } // If current node is leaf if (node.left == null && node.right == null) { // If current node is the first burnt node if (node.data == target) { data.contains = true; data.time = 0; } return; } // Information about left child Data leftData = new Data(); getResult(node.left, leftData, target); // Information about right child Data rightData = new Data(); getResult(node.right, rightData, target); // If left subtree contains the fired node then // time required to reach fire to current node // will be (1 + time required for left child) data.time = (leftData.contains) ? (leftData.time + 1) : -1; // If right subtree contains the fired node then // time required to reach fire to current node // will be (1 + time required for right child) if (data.time == -1) data.time = (rightData.contains) ? (rightData.time + 1) : -1; // Storing(true or false) if the tree rooted at // current node contains the fired node data.contains = (leftData.contains || rightData.contains); // Calculate the maximum depth of left subtree data.leftDepth = (node.left == null) ? 0 : (1 + Math.max(leftData.leftDepth, leftData.rightDepth)); // Calculate the maximum depth of right subtree data.rightDepth = (node.right == null) ? 0 : (1 + Math.max(rightData.leftDepth, rightData.rightDepth)); // Calculating answer if (data.contains) { // If left subtree exists and // it contains the fired node if (leftData.contains) { // calculate result res = Math.max(res, data.time + data.rightDepth); } // If right subtree exists and it // contains the fired node if (rightData.contains) { // calculate result res = Math.max(res, data.time + data.leftDepth); } } } // To store the result public static int res; // Driver Code public static void main(String args[]) { Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.left = new Node(6); root.left.left.left = new Node(8); root.left.right.left = new Node(9); root.left.right.right = new Node(10); root.left.right.left.left = new Node(11); int target = 11; res = 0; getResult(root, new Data(), target); System.out.println(res); }}
# Python program to find minimum time required# to burn the binary tree completely # Definition for a binary tree node class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None ''' ***********ADDITIONAL INFO************* lDepth - maximum height of left subtree rDepth - maximum height of right subtree contains - stores true if tree rooted at current node contains the first burnt node time - time to reach fire from the initially burnt leaf node to this node''' class Info: def __init__(self): self.lDepth = 0 self.rDepth = 0 self.contains = False self.time = -1 class Solution: # Class Variable res = 0 ''' Function to calculate time required to burn tree completely node - address of current node info - extra information about current node target - node that is fired res - stores the result ''' def calcTime(self, node, info, target): # Base case: if root is null if node == None: return info if node.left == None and node.right == None: # If current node is the first burnt node if node.val == target: info.contains = True info.time = 0 return info # Information about left child of root leftInfo = Info() leftInfo = self.calcTime(node.left, leftInfo, target) # Information about right child of root rightInfo = Info() rightInfo = self.calcTime(node.right, rightInfo, target) # If left subtree contains the fired node then # time required to reach fire to current node # will be (1 + time required for left child) info.time = leftInfo.time + \ 1 if (node.left and leftInfo.contains) else -1 # If right subtree contains the fired node then # time required to reach fire to current node # will be (1 + time required for right child) if info.time == -1: info.time = rightInfo.time + \ 1 if (node.right and rightInfo.contains) else -1 # Storing(true or false) if the tree rooted at # current node contains the fired node info.contains = (node.left and leftInfo.contains) or ( node.right and rightInfo.contains) # Calculate the maximum depth of left subtree info.lDepth = 0 if (not node.left) else ( 1+max(leftInfo.lDepth, leftInfo.rDepth)) # Calculate the maximum depth of right subtree info.rDepth = 0 if (not node.right) else ( 1+max(rightInfo.lDepth, rightInfo.rDepth)) # Calculating answer if info.contains: # If left subtree exists and # it contains the fired node if node.left and leftInfo.contains: # calculate result self.res = max(self.res, info.time+info.rDepth) # If right subtree exists and it # contains the fired node if node.right and rightInfo.contains: # calculate result self.res = max(self.res, info.time+info.lDepth) return info # Driver function to calculate minimum # time required def solve(self, root, target): info = Info() self.calcTime(root, info, target) return self.res # Driver Codeif __name__ == '__main__': # Construct tree shown in the above example root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(3) root.left.left = TreeNode(4) root.left.right = TreeNode(5) root.right.left = TreeNode(6) root.left.left.left = TreeNode(8) root.left.right.left = TreeNode(9) root.left.right.right = TreeNode(10) root.left.right.left.left = TreeNode(11) # Target Leaf Node target = 11 # Print min time to burn the complete tree s = Solution() print(s.solve(root, target)) # This code is contributed by Naman Taneja
// C# program to find minimum time required// to burn the binary tree completelyusing System; class GFG{ // Tree Node class Node { public int data; public Node left, right; public Node(int data) { this.data = data; this.left = null; this.right = null; } } /* ***********ADDITIONAL INFO************* lDepth - maximum height of left subtree rDepth - maximum height of right subtree contains - stores true if tree rooted at current node contains the first burnt node time - time to reach fire from the initially burnt leaf node to this node */ class Data { public int leftDepth, rightDepth, time; public bool contains; public Data() { contains = false; leftDepth = rightDepth = 0; time = -1; } } /* Function to calculate time required to burn tree completely node - address of current node info - extra information about current node target - node that is fired res - stores the result */ static void getResult(Node node, Data data, int target) { // Base case: if root is null if (node == null) { return; } // If current node is leaf if (node.left == null && node.right == null) { // If current node is the first burnt node if (node.data == target) { data.contains = true; data.time = 0; } return; } // Information about left child Data leftData = new Data(); getResult(node.left, leftData, target); // Information about right child Data rightData = new Data(); getResult(node.right, rightData, target); // If left subtree contains the fired node then // time required to reach fire to current node // will be (1 + time required for left child) data.time = (leftData.contains) ? (leftData.time + 1) : -1; // If right subtree contains the fired node then // time required to reach fire to current node // will be (1 + time required for right child) if (data.time == -1) data.time = (rightData.contains) ? (rightData.time + 1) : -1; // Storing(true or false) if the tree rooted at // current node contains the fired node data.contains = (leftData.contains || rightData.contains); // Calculate the maximum depth of left subtree data.leftDepth = (node.left == null) ? 0 : (1 + Math.Max( leftData.leftDepth, leftData.rightDepth)); // Calculate the maximum depth of right subtree data.rightDepth = (node.right == null) ? 0 : (1 + Math.Max( rightData.leftDepth, rightData.rightDepth)); // Calculating answer if (data.contains) { // If left subtree exists and // it contains the fired node if (leftData.contains) { // calculate result res = Math.Max(res, data.time + data.rightDepth); } // If right subtree exists and it // contains the fired node if (rightData.contains) { // calculate result res = Math.Max(res, data.time + data.leftDepth); } } } // To store the result public static int res; // Driver Code public static void Main(String []args) { Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.left = new Node(6); root.left.left.left = new Node(8); root.left.right.left = new Node(9); root.left.right.right = new Node(10); root.left.right.left.left = new Node(11); int target = 11; res = 0; getResult(root, new Data(), target); Console.WriteLine(res); }} // This code is contributed by PrinciRaj1992
6
princiraj1992
simmytarika5
namantaneja123
Amazon
Binary Tree
Flipkart
Grab
Tree
Flipkart
Amazon
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Introduction to Tree Data Structure
Inorder Tree Traversal without Recursion
What is Data Structure: Types, Classifications and Applications
Binary Tree | Set 3 (Types of Binary Tree)
A program to check if a binary tree is BST or not
Lowest Common Ancestor in a Binary Tree | Set 1
Binary Tree | Set 2 (Properties)
Diameter of a Binary Tree
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n13 Jul, 2021"
},
{
"code": null,
"e": 415,
"s": 52,
"text": "Given a binary tree and a leaf node from this tree. It is known that in 1s all nodes connected to a given node (left child, right child and parent) get burned in 1 second. Then all the nodes which are connected through one intermediate get burned in 2 seconds, and so on. The task is to find the minimum time required to burn the complete binary tree.Examples: "
},
{
"code": null,
"e": 2400,
"s": 415,
"text": "Input : \n 1\n / \\\n 2 3\n / \\ \\\n 4 5 6\n / \\ \\\n 7 8 9\n \\\n 10\nLeaf = 8\nOutput : 7\nInitially 8 is set to fire at 0th sec.\n 1\n / \\\n 2 3\n / \\ \\\n 4 5 6\n / \\ \\\n 7 F 9\n \\\n 10\nAfter 1s: 5 is set to fire.\n 1\n / \\\n 2 3\n / \\ \\\n 4 F 6\n / \\ \\\n 7 F 9\n \\\n 10\nAfter 2s: 2, 7 are set to fire.\n 1\n / \\\n F 3\n / \\ \\\n 4 F 6\n / \\ \\\n F F 9\n \\\n 10\nAfter 3s: 4, 1 are set to fire.\n F\n / \\\n F 3\n / \\ \\\n F F 6\n / \\ \\\n F F 9\n \\\n 10\nAfter 4s: 3 is set to fire.\n F\n / \\\n F F\n / \\ \\\n F F 6\n / \\ \\\n F F 9\n \\\n 10\nAfter 5s: 6 is set to fire.\n F\n / \\\n F F\n / \\ \\\n F F F\n / \\ \\\n F F 9\n \\\n 10\nAfter 6s: 9 is set to fire.\n F\n / \\\n F F\n / \\ \\\n F F F\n / \\ \\\n F F F\n \\\n 10\nAfter 7s: 10 is set to fire.\n F\n / \\\n F F\n / \\ \\\n F F F\n / \\ \\\n F F F\n \\\n F\nIt takes 7s to burn the complete tree."
},
{
"code": null,
"e": 2464,
"s": 2402,
"text": "The idea is to store additional information for every node: "
},
{
"code": null,
"e": 2487,
"s": 2464,
"text": "Depth of left subtree."
},
{
"code": null,
"e": 2511,
"s": 2487,
"text": "Depth of right subtree."
},
{
"code": null,
"e": 2610,
"s": 2511,
"text": "The time required for the fire to reach the current node starting from the first leaf node burned."
},
{
"code": null,
"e": 2706,
"s": 2610,
"text": "A boolean variable to check if the initial burnt node is in the tree rooted under current node."
},
{
"code": null,
"e": 2783,
"s": 2706,
"text": "Before moving ahead with the approach let’s take a look at the tree below: "
},
{
"code": null,
"e": 2938,
"s": 2783,
"text": " 1\n / \\ \n 2 3\n / \\ /\n 4 5 6 \n / / \\\n 8 9 10\n /\n 11"
},
{
"code": null,
"e": 2995,
"s": 2938,
"text": "In the above tree, if we set the leaf node 11 at fire. "
},
{
"code": null,
"e": 3507,
"s": 2995,
"text": "In 1s, the fire will reach node 9.In 2s, the fire will reach node 5.In 3rd second, the fire will reach node 2 and 10. Here comes an observation: In 2s fire reached node 5. For node 5, the initial burned leaf is in it’s left subtree, so the time taken to burn right subtree will be the height of the right subtree which is 1. Therefore, fire reaches to node 10 in (2+1) = 3s.Again, for the node 2. Fire reached to node 2 in 3s from right subtree. Therefore, time taken to burn left subtree will be it’s height. "
},
{
"code": null,
"e": 3542,
"s": 3507,
"text": "In 1s, the fire will reach node 9."
},
{
"code": null,
"e": 3577,
"s": 3542,
"text": "In 2s, the fire will reach node 5."
},
{
"code": null,
"e": 4021,
"s": 3577,
"text": "In 3rd second, the fire will reach node 2 and 10. Here comes an observation: In 2s fire reached node 5. For node 5, the initial burned leaf is in it’s left subtree, so the time taken to burn right subtree will be the height of the right subtree which is 1. Therefore, fire reaches to node 10 in (2+1) = 3s.Again, for the node 2. Fire reached to node 2 in 3s from right subtree. Therefore, time taken to burn left subtree will be it’s height. "
},
{
"code": null,
"e": 4251,
"s": 4021,
"text": "In 2s fire reached node 5. For node 5, the initial burned leaf is in it’s left subtree, so the time taken to burn right subtree will be the height of the right subtree which is 1. Therefore, fire reaches to node 10 in (2+1) = 3s."
},
{
"code": null,
"e": 4389,
"s": 4251,
"text": "Again, for the node 2. Fire reached to node 2 in 3s from right subtree. Therefore, time taken to burn left subtree will be it’s height. "
},
{
"code": null,
"e": 4485,
"s": 4389,
"text": "So the solution is to apply recursion and for every node calculate the below-required values: "
},
{
"code": null,
"e": 4497,
"s": 4485,
"text": "Left Depth."
},
{
"code": null,
"e": 4510,
"s": 4497,
"text": "Right Depth."
},
{
"code": null,
"e": 4564,
"s": 4510,
"text": "The time required for fire to reach the current node."
},
{
"code": null,
"e": 4621,
"s": 4564,
"text": "Is the current subtree contains initial burnt leaf node."
},
{
"code": null,
"e": 4686,
"s": 4621,
"text": "So, for the minimum time required to burn any subtree will be: "
},
{
"code": null,
"e": 4791,
"s": 4686,
"text": "The time required for fire to reach the root node from initial burnt leaf + depth of the opposite side "
},
{
"code": null,
"e": 4938,
"s": 4791,
"text": "Therefore, to find time required to burn the complete tree, we need to calculate the above value for every node, and take maximum of that value. "
},
{
"code": null,
"e": 5028,
"s": 4938,
"text": "ans = max(ans, (time required for fire to reach current node + depth of other subtree)) "
},
{
"code": null,
"e": 5080,
"s": 5028,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 5084,
"s": 5080,
"text": "C++"
},
{
"code": null,
"e": 5089,
"s": 5084,
"text": "Java"
},
{
"code": null,
"e": 5097,
"s": 5089,
"text": "Python3"
},
{
"code": null,
"e": 5100,
"s": 5097,
"text": "C#"
},
{
"code": "// C++ program to find minimum time required// to burn the binary tree completely #include <bits/stdc++.h>using namespace std; // Tree Nodestruct Node { int data; Node* left; Node* right; Node() { left = NULL; right = NULL; }}; // Utility function to create a new NodeNode* newNode(int val){ Node* temp = new Node; temp->data = val; return temp;} /* ***********ADDITIONAL INFO************* lDepth - maximum height of left subtree rDepth - maximum height of right subtree contains - stores true if tree rooted at current node contains the first burnt node time - time to reach fire from the initially burnt leaf node to this node*/struct Info { int lDepth; int rDepth; bool contains; int time; Info() { lDepth = rDepth = 0; contains = false; time = -1; }}; /* Function to calculate time required to burn tree completely node - address of current node info - extra information about current node target - node that is fired res - stores the result*/Info calcTime(Node* node, Info& info, int target, int& res){ // Base case: if root is null if (node == NULL) { return info; } // If current node is leaf if (node->left == NULL && node->right == NULL) { // If current node is the first burnt node if (node->data == target) { info.contains = true; info.time = 0; } return info; } // Information about left child of root Info leftInfo; calcTime(node->left, leftInfo, target, res); // Information about right child of root Info rightInfo; calcTime(node->right, rightInfo, target, res); // If left subtree contains the fired node then // time required to reach fire to current node // will be (1 + time required for left child) info.time = (node->left && leftInfo.contains) ? (leftInfo.time + 1) : -1; // If right subtree contains the fired node then // time required to reach fire to current node // will be (1 + time required for right child) if (info.time == -1) info.time = (node->right && rightInfo.contains) ? (rightInfo.time + 1) : -1; // Storing(true or false) if the tree rooted at // current node contains the fired node info.contains = ((node->left && leftInfo.contains) || (node->right && rightInfo.contains)); // Calculate the maximum depth of left subtree info.lDepth = !(node->left) ? 0 : (1 + max(leftInfo.lDepth, leftInfo.rDepth)); // Calculate the maximum depth of right subtree info.rDepth = !(node->right) ? 0 : (1 + max(rightInfo.lDepth, rightInfo.rDepth)); // Calculating answer if (info.contains) { // If left subtree exists and // it contains the fired node if (node->left && leftInfo.contains) { // calculate result res = max(res, info.time + info.rDepth); } // If right subtree exists and it // contains the fired node if (node->right && rightInfo.contains) { // calculate result res = max(res, info.time + info.lDepth); } }} // Driver function to calculate minimum// time requiredint minTime(Node* root, int target){ int res = 0; Info info; calcTime(root, info, target, res); return res;} // Driver Codeint main(){ Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->left->left->left = newNode(8); root->left->right->left = newNode(9); root->left->right->right = newNode(10); root->left->right->left->left = newNode(11); // target node is 8 int target = 11; cout << minTime(root, target); return 0;}",
"e": 9131,
"s": 5100,
"text": null
},
{
"code": "// Java program to find minimum time required// to burn the binary tree completely public class GFG { // Tree Node static class Node { int data; Node left, right; Node(int data) { this.data = data; this.left = null; this.right = null; } } /* ***********ADDITIONAL INFO************* lDepth - maximum height of left subtree rDepth - maximum height of right subtree contains - stores true if tree rooted at current node contains the first burnt node time - time to reach fire from the initially burnt leaf node to this node */ static class Data { int leftDepth, rightDepth, time; boolean contains; Data() { contains = false; leftDepth = rightDepth = 0; time = -1; } } /* Function to calculate time required to burn tree completely node - address of current node info - extra information about current node target - node that is fired res - stores the result */ public static void getResult(Node node, Data data, int target) { // Base case: if root is null if (node == null) { return; } // If current node is leaf if (node.left == null && node.right == null) { // If current node is the first burnt node if (node.data == target) { data.contains = true; data.time = 0; } return; } // Information about left child Data leftData = new Data(); getResult(node.left, leftData, target); // Information about right child Data rightData = new Data(); getResult(node.right, rightData, target); // If left subtree contains the fired node then // time required to reach fire to current node // will be (1 + time required for left child) data.time = (leftData.contains) ? (leftData.time + 1) : -1; // If right subtree contains the fired node then // time required to reach fire to current node // will be (1 + time required for right child) if (data.time == -1) data.time = (rightData.contains) ? (rightData.time + 1) : -1; // Storing(true or false) if the tree rooted at // current node contains the fired node data.contains = (leftData.contains || rightData.contains); // Calculate the maximum depth of left subtree data.leftDepth = (node.left == null) ? 0 : (1 + Math.max(leftData.leftDepth, leftData.rightDepth)); // Calculate the maximum depth of right subtree data.rightDepth = (node.right == null) ? 0 : (1 + Math.max(rightData.leftDepth, rightData.rightDepth)); // Calculating answer if (data.contains) { // If left subtree exists and // it contains the fired node if (leftData.contains) { // calculate result res = Math.max(res, data.time + data.rightDepth); } // If right subtree exists and it // contains the fired node if (rightData.contains) { // calculate result res = Math.max(res, data.time + data.leftDepth); } } } // To store the result public static int res; // Driver Code public static void main(String args[]) { Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.left = new Node(6); root.left.left.left = new Node(8); root.left.right.left = new Node(9); root.left.right.right = new Node(10); root.left.right.left.left = new Node(11); int target = 11; res = 0; getResult(root, new Data(), target); System.out.println(res); }}",
"e": 13137,
"s": 9131,
"text": null
},
{
"code": "# Python program to find minimum time required# to burn the binary tree completely # Definition for a binary tree node class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None ''' ***********ADDITIONAL INFO************* lDepth - maximum height of left subtree rDepth - maximum height of right subtree contains - stores true if tree rooted at current node contains the first burnt node time - time to reach fire from the initially burnt leaf node to this node''' class Info: def __init__(self): self.lDepth = 0 self.rDepth = 0 self.contains = False self.time = -1 class Solution: # Class Variable res = 0 ''' Function to calculate time required to burn tree completely node - address of current node info - extra information about current node target - node that is fired res - stores the result ''' def calcTime(self, node, info, target): # Base case: if root is null if node == None: return info if node.left == None and node.right == None: # If current node is the first burnt node if node.val == target: info.contains = True info.time = 0 return info # Information about left child of root leftInfo = Info() leftInfo = self.calcTime(node.left, leftInfo, target) # Information about right child of root rightInfo = Info() rightInfo = self.calcTime(node.right, rightInfo, target) # If left subtree contains the fired node then # time required to reach fire to current node # will be (1 + time required for left child) info.time = leftInfo.time + \\ 1 if (node.left and leftInfo.contains) else -1 # If right subtree contains the fired node then # time required to reach fire to current node # will be (1 + time required for right child) if info.time == -1: info.time = rightInfo.time + \\ 1 if (node.right and rightInfo.contains) else -1 # Storing(true or false) if the tree rooted at # current node contains the fired node info.contains = (node.left and leftInfo.contains) or ( node.right and rightInfo.contains) # Calculate the maximum depth of left subtree info.lDepth = 0 if (not node.left) else ( 1+max(leftInfo.lDepth, leftInfo.rDepth)) # Calculate the maximum depth of right subtree info.rDepth = 0 if (not node.right) else ( 1+max(rightInfo.lDepth, rightInfo.rDepth)) # Calculating answer if info.contains: # If left subtree exists and # it contains the fired node if node.left and leftInfo.contains: # calculate result self.res = max(self.res, info.time+info.rDepth) # If right subtree exists and it # contains the fired node if node.right and rightInfo.contains: # calculate result self.res = max(self.res, info.time+info.lDepth) return info # Driver function to calculate minimum # time required def solve(self, root, target): info = Info() self.calcTime(root, info, target) return self.res # Driver Codeif __name__ == '__main__': # Construct tree shown in the above example root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(3) root.left.left = TreeNode(4) root.left.right = TreeNode(5) root.right.left = TreeNode(6) root.left.left.left = TreeNode(8) root.left.right.left = TreeNode(9) root.left.right.right = TreeNode(10) root.left.right.left.left = TreeNode(11) # Target Leaf Node target = 11 # Print min time to burn the complete tree s = Solution() print(s.solve(root, target)) # This code is contributed by Naman Taneja",
"e": 17127,
"s": 13137,
"text": null
},
{
"code": "// C# program to find minimum time required// to burn the binary tree completelyusing System; class GFG{ // Tree Node class Node { public int data; public Node left, right; public Node(int data) { this.data = data; this.left = null; this.right = null; } } /* ***********ADDITIONAL INFO************* lDepth - maximum height of left subtree rDepth - maximum height of right subtree contains - stores true if tree rooted at current node contains the first burnt node time - time to reach fire from the initially burnt leaf node to this node */ class Data { public int leftDepth, rightDepth, time; public bool contains; public Data() { contains = false; leftDepth = rightDepth = 0; time = -1; } } /* Function to calculate time required to burn tree completely node - address of current node info - extra information about current node target - node that is fired res - stores the result */ static void getResult(Node node, Data data, int target) { // Base case: if root is null if (node == null) { return; } // If current node is leaf if (node.left == null && node.right == null) { // If current node is the first burnt node if (node.data == target) { data.contains = true; data.time = 0; } return; } // Information about left child Data leftData = new Data(); getResult(node.left, leftData, target); // Information about right child Data rightData = new Data(); getResult(node.right, rightData, target); // If left subtree contains the fired node then // time required to reach fire to current node // will be (1 + time required for left child) data.time = (leftData.contains) ? (leftData.time + 1) : -1; // If right subtree contains the fired node then // time required to reach fire to current node // will be (1 + time required for right child) if (data.time == -1) data.time = (rightData.contains) ? (rightData.time + 1) : -1; // Storing(true or false) if the tree rooted at // current node contains the fired node data.contains = (leftData.contains || rightData.contains); // Calculate the maximum depth of left subtree data.leftDepth = (node.left == null) ? 0 : (1 + Math.Max( leftData.leftDepth, leftData.rightDepth)); // Calculate the maximum depth of right subtree data.rightDepth = (node.right == null) ? 0 : (1 + Math.Max( rightData.leftDepth, rightData.rightDepth)); // Calculating answer if (data.contains) { // If left subtree exists and // it contains the fired node if (leftData.contains) { // calculate result res = Math.Max(res, data.time + data.rightDepth); } // If right subtree exists and it // contains the fired node if (rightData.contains) { // calculate result res = Math.Max(res, data.time + data.leftDepth); } } } // To store the result public static int res; // Driver Code public static void Main(String []args) { Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.left = new Node(6); root.left.left.left = new Node(8); root.left.right.left = new Node(9); root.left.right.right = new Node(10); root.left.right.left.left = new Node(11); int target = 11; res = 0; getResult(root, new Data(), target); Console.WriteLine(res); }} // This code is contributed by PrinciRaj1992",
"e": 21563,
"s": 17127,
"text": null
},
{
"code": null,
"e": 21565,
"s": 21563,
"text": "6"
},
{
"code": null,
"e": 21581,
"s": 21567,
"text": "princiraj1992"
},
{
"code": null,
"e": 21594,
"s": 21581,
"text": "simmytarika5"
},
{
"code": null,
"e": 21609,
"s": 21594,
"text": "namantaneja123"
},
{
"code": null,
"e": 21616,
"s": 21609,
"text": "Amazon"
},
{
"code": null,
"e": 21628,
"s": 21616,
"text": "Binary Tree"
},
{
"code": null,
"e": 21637,
"s": 21628,
"text": "Flipkart"
},
{
"code": null,
"e": 21642,
"s": 21637,
"text": "Grab"
},
{
"code": null,
"e": 21647,
"s": 21642,
"text": "Tree"
},
{
"code": null,
"e": 21656,
"s": 21647,
"text": "Flipkart"
},
{
"code": null,
"e": 21663,
"s": 21656,
"text": "Amazon"
},
{
"code": null,
"e": 21668,
"s": 21663,
"text": "Tree"
},
{
"code": null,
"e": 21766,
"s": 21668,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 21798,
"s": 21766,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 21834,
"s": 21798,
"text": "Introduction to Tree Data Structure"
},
{
"code": null,
"e": 21875,
"s": 21834,
"text": "Inorder Tree Traversal without Recursion"
},
{
"code": null,
"e": 21939,
"s": 21875,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 21982,
"s": 21939,
"text": "Binary Tree | Set 3 (Types of Binary Tree)"
},
{
"code": null,
"e": 22032,
"s": 21982,
"text": "A program to check if a binary tree is BST or not"
},
{
"code": null,
"e": 22080,
"s": 22032,
"text": "Lowest Common Ancestor in a Binary Tree | Set 1"
},
{
"code": null,
"e": 22113,
"s": 22080,
"text": "Binary Tree | Set 2 (Properties)"
}
] |
Operations required to make the string empty
|
28 Jun, 2022
Given a string str, the task is to make the string empty with the given operation. In a single operation, you can pick some characters of the string (each of the picked characters should have the same frequency) and remove them from the string. Print the total operations required to make the string empty.Examples:
Input: str = “aabbccc” Output: 2 In one operation, characters ‘a’ and ‘b’ can be removed since both have the same frequency. Second operation can remove character ‘c’ having frequency 3. Total 2 operations are required.Input: str = “geeksforgeeks” Output: 3
Approach: Find unique frequencies of the characters of the string. Total count of unique frequencies will be the number of operations required to make the string empty. For str = “aaabbbcccc”, unique frequencies are 3 and 4. Total count of unique frequencies is 2. HashMap can be used to store the characters and their frequencies then HashSet can be used to find the count of unique frequencies which is the number of operations required.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// CPP implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count of operations requiredint totalOperations(string str, int len){ // HashMap to store characters and their frequencies unordered_map<char, int> h; for (int i = 0; i < len; i++) // If already contains the character then // increment its frequency by 1 h[str[i]]++; // HashSet to store unique frequency unordered_set<int> hs; // Insert frequencies into HashSet for (auto i : h) hs.insert(i.second); // Count of unique frequencies return hs.size();} // Driver Codeint main(){ string str = "geeksforgeeks"; int len = str.length(); cout << totalOperations(str, len) << endl; return 0;} // This code is contributed by// sanjeev2552
// Java implementation of the approachimport java.util.*;class GFG { // Function to return the count of operations required static int totalOperations(String str, int len) { // HashMap to store characters and their frequencies HashMap<Character, Integer> h = new HashMap<Character, Integer>(); for (int i = 0; i < len; i++) { // If already contains the character then // increment its frequency by 1 if (h.containsKey(str.charAt(i))) h.put(str.charAt(i), h.get(str.charAt(i)) + 1); // Else add the character to the HashMap with frequency 1 else h.put(str.charAt(i), 1); } // Set to iterate over HashMap Set<Map.Entry<Character, Integer> > set = h.entrySet(); // HashSet to store unique frequency HashSet<Integer> hs = new HashSet<Integer>(); // Insert frequencies into HashSet for (Map.Entry<Character, Integer> me : set) hs.add(me.getValue()); // Count of unique frequencies return hs.size(); } // Driver code public static void main(String[] args) { String str = "geeksforgeeks"; int len = str.length(); System.out.println(totalOperations(str, len)); }}
# Python implementation of the approach # Function to return the count of operations requireddef totalOperations(st, length): # Dictionary to store characters and their frequencies d = {} for i in range(length): # If already contains the character then # increment its frequency by 1 if st[i] in d: d[st[i]] += 1 # Else add the character to the HashMap with frequency 1 else: d[st[i]] = 1 # Set to Store unique frequency valueSet = set() # Insert frequencies into HashSet for key in d.keys(): valueSet.add(d[key]) # Count of unique frequencies return len(valueSet) # Driver Codest = "geeksforgeeks"l = len(st)print(totalOperations(st, l)) # This code is contributed by Vivekkumar Singh
// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Function to return// the count of operations requiredstatic int totalOperations(String str, int len){ // HashMap to store characters // and their frequencies Dictionary<char, int> h = new Dictionary<char, int>(); for (int i = 0; i < len; i++) { // If already contains the character then // increment its frequency by 1 if (h.ContainsKey(str[i])) h[str[i]] = h[str[i]] + 1; // Else add the character // to the HashMap with frequency 1 else h.Add(str[i], 1); } // Set to iterate over HashMap // HashSet to store unique frequency HashSet<int> hs = new HashSet<int>(); // Insert frequencies into HashSet foreach(KeyValuePair<char, int> me in h) hs.Add(me.Value); // Count of unique frequencies return hs.Count;} // Driver codepublic static void Main(String[] args){ String str = "geeksforgeeks"; int len = str.Length; Console.WriteLine(totalOperations(str, len));}} // This code is contributed by Rajput-Ji
<script> // Javascript implementation of the approach // Function to return the count of operations requiredfunction totalOperations(str, len){ // HashMap to store characters and their frequencies var h = new Map(); for (var i = 0; i < len; i++) // If already contains the character then // increment its frequency by 1 if(h.has(str[i])) h.set(str[i], h.get(str[i])+1) else h.set(str[i], 1) // HashSet to store unique frequency var hs = new Set(); // Insert frequencies into HashSet h.forEach((value, key) => { hs.add(value); }); // Count of unique frequencies return hs.size;} // Driver Codevar str = "geeksforgeeks";var len = str.length;document.write( totalOperations(str, len)); // This code is contributed by itsok.</script>
3
Time complexity: O(n)
Auxiliary Space: O(n)
Vivekkumar Singh
Rajput-Ji
sanjeev2552
itsok
krishnav4
HashSet
Thoughtworks
Competitive Programming
Java
Strings
Thoughtworks
Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Hacks for Competitive Programming
Container with Most Water
Most important type of Algorithms
Find two numbers from their sum and XOR
The Ultimate Beginner's Guide For DSA
Arrays in Java
Split() String method in Java with examples
Arrays.sort() in Java with examples
Object Oriented Programming (OOPs) Concept in Java
Reverse a string in Java
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 Jun, 2022"
},
{
"code": null,
"e": 370,
"s": 52,
"text": "Given a string str, the task is to make the string empty with the given operation. In a single operation, you can pick some characters of the string (each of the picked characters should have the same frequency) and remove them from the string. Print the total operations required to make the string empty.Examples: "
},
{
"code": null,
"e": 630,
"s": 370,
"text": "Input: str = “aabbccc” Output: 2 In one operation, characters ‘a’ and ‘b’ can be removed since both have the same frequency. Second operation can remove character ‘c’ having frequency 3. Total 2 operations are required.Input: str = “geeksforgeeks” Output: 3 "
},
{
"code": null,
"e": 1124,
"s": 632,
"text": "Approach: Find unique frequencies of the characters of the string. Total count of unique frequencies will be the number of operations required to make the string empty. For str = “aaabbbcccc”, unique frequencies are 3 and 4. Total count of unique frequencies is 2. HashMap can be used to store the characters and their frequencies then HashSet can be used to find the count of unique frequencies which is the number of operations required.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1128,
"s": 1124,
"text": "C++"
},
{
"code": null,
"e": 1133,
"s": 1128,
"text": "Java"
},
{
"code": null,
"e": 1141,
"s": 1133,
"text": "Python3"
},
{
"code": null,
"e": 1144,
"s": 1141,
"text": "C#"
},
{
"code": null,
"e": 1155,
"s": 1144,
"text": "Javascript"
},
{
"code": "// CPP implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count of operations requiredint totalOperations(string str, int len){ // HashMap to store characters and their frequencies unordered_map<char, int> h; for (int i = 0; i < len; i++) // If already contains the character then // increment its frequency by 1 h[str[i]]++; // HashSet to store unique frequency unordered_set<int> hs; // Insert frequencies into HashSet for (auto i : h) hs.insert(i.second); // Count of unique frequencies return hs.size();} // Driver Codeint main(){ string str = \"geeksforgeeks\"; int len = str.length(); cout << totalOperations(str, len) << endl; return 0;} // This code is contributed by// sanjeev2552",
"e": 1965,
"s": 1155,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*;class GFG { // Function to return the count of operations required static int totalOperations(String str, int len) { // HashMap to store characters and their frequencies HashMap<Character, Integer> h = new HashMap<Character, Integer>(); for (int i = 0; i < len; i++) { // If already contains the character then // increment its frequency by 1 if (h.containsKey(str.charAt(i))) h.put(str.charAt(i), h.get(str.charAt(i)) + 1); // Else add the character to the HashMap with frequency 1 else h.put(str.charAt(i), 1); } // Set to iterate over HashMap Set<Map.Entry<Character, Integer> > set = h.entrySet(); // HashSet to store unique frequency HashSet<Integer> hs = new HashSet<Integer>(); // Insert frequencies into HashSet for (Map.Entry<Character, Integer> me : set) hs.add(me.getValue()); // Count of unique frequencies return hs.size(); } // Driver code public static void main(String[] args) { String str = \"geeksforgeeks\"; int len = str.length(); System.out.println(totalOperations(str, len)); }}",
"e": 3255,
"s": 1965,
"text": null
},
{
"code": "# Python implementation of the approach # Function to return the count of operations requireddef totalOperations(st, length): # Dictionary to store characters and their frequencies d = {} for i in range(length): # If already contains the character then # increment its frequency by 1 if st[i] in d: d[st[i]] += 1 # Else add the character to the HashMap with frequency 1 else: d[st[i]] = 1 # Set to Store unique frequency valueSet = set() # Insert frequencies into HashSet for key in d.keys(): valueSet.add(d[key]) # Count of unique frequencies return len(valueSet) # Driver Codest = \"geeksforgeeks\"l = len(st)print(totalOperations(st, l)) # This code is contributed by Vivekkumar Singh",
"e": 4062,
"s": 3255,
"text": null
},
{
"code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Function to return// the count of operations requiredstatic int totalOperations(String str, int len){ // HashMap to store characters // and their frequencies Dictionary<char, int> h = new Dictionary<char, int>(); for (int i = 0; i < len; i++) { // If already contains the character then // increment its frequency by 1 if (h.ContainsKey(str[i])) h[str[i]] = h[str[i]] + 1; // Else add the character // to the HashMap with frequency 1 else h.Add(str[i], 1); } // Set to iterate over HashMap // HashSet to store unique frequency HashSet<int> hs = new HashSet<int>(); // Insert frequencies into HashSet foreach(KeyValuePair<char, int> me in h) hs.Add(me.Value); // Count of unique frequencies return hs.Count;} // Driver codepublic static void Main(String[] args){ String str = \"geeksforgeeks\"; int len = str.Length; Console.WriteLine(totalOperations(str, len));}} // This code is contributed by Rajput-Ji",
"e": 5239,
"s": 4062,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function to return the count of operations requiredfunction totalOperations(str, len){ // HashMap to store characters and their frequencies var h = new Map(); for (var i = 0; i < len; i++) // If already contains the character then // increment its frequency by 1 if(h.has(str[i])) h.set(str[i], h.get(str[i])+1) else h.set(str[i], 1) // HashSet to store unique frequency var hs = new Set(); // Insert frequencies into HashSet h.forEach((value, key) => { hs.add(value); }); // Count of unique frequencies return hs.size;} // Driver Codevar str = \"geeksforgeeks\";var len = str.length;document.write( totalOperations(str, len)); // This code is contributed by itsok.</script>",
"e": 6069,
"s": 5239,
"text": null
},
{
"code": null,
"e": 6071,
"s": 6069,
"text": "3"
},
{
"code": null,
"e": 6095,
"s": 6073,
"text": "Time complexity: O(n)"
},
{
"code": null,
"e": 6117,
"s": 6095,
"text": "Auxiliary Space: O(n)"
},
{
"code": null,
"e": 6134,
"s": 6117,
"text": "Vivekkumar Singh"
},
{
"code": null,
"e": 6144,
"s": 6134,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 6156,
"s": 6144,
"text": "sanjeev2552"
},
{
"code": null,
"e": 6162,
"s": 6156,
"text": "itsok"
},
{
"code": null,
"e": 6172,
"s": 6162,
"text": "krishnav4"
},
{
"code": null,
"e": 6180,
"s": 6172,
"text": "HashSet"
},
{
"code": null,
"e": 6193,
"s": 6180,
"text": "Thoughtworks"
},
{
"code": null,
"e": 6217,
"s": 6193,
"text": "Competitive Programming"
},
{
"code": null,
"e": 6222,
"s": 6217,
"text": "Java"
},
{
"code": null,
"e": 6230,
"s": 6222,
"text": "Strings"
},
{
"code": null,
"e": 6243,
"s": 6230,
"text": "Thoughtworks"
},
{
"code": null,
"e": 6251,
"s": 6243,
"text": "Strings"
},
{
"code": null,
"e": 6256,
"s": 6251,
"text": "Java"
},
{
"code": null,
"e": 6354,
"s": 6256,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6396,
"s": 6354,
"text": "Bitwise Hacks for Competitive Programming"
},
{
"code": null,
"e": 6422,
"s": 6396,
"text": "Container with Most Water"
},
{
"code": null,
"e": 6456,
"s": 6422,
"text": "Most important type of Algorithms"
},
{
"code": null,
"e": 6496,
"s": 6456,
"text": "Find two numbers from their sum and XOR"
},
{
"code": null,
"e": 6534,
"s": 6496,
"text": "The Ultimate Beginner's Guide For DSA"
},
{
"code": null,
"e": 6549,
"s": 6534,
"text": "Arrays in Java"
},
{
"code": null,
"e": 6593,
"s": 6549,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 6629,
"s": 6593,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 6680,
"s": 6629,
"text": "Object Oriented Programming (OOPs) Concept in Java"
}
] |
Dynamic Type in C#
|
10 Apr, 2019
In C# 4.0, a new type is introduced that is known as a dynamic type. It is used to avoid the compile-time type checking. The compiler does not check the type of the dynamic type variable at compile time, instead of this, the compiler gets the type at the run time. The dynamic type variable is created using dynamic keyword.
Example:
dynamic value = 123;
Important Points:
In most of the cases, the dynamic type behaves like object types.
You can get the actual type of the dynamic variable at runtime by using GetType() method. The dynamic type changes its type at the run time based on the value present on the right-hand side. As shown in the below example.Example:// C# program to illustrate how to get the// actual type of the dynamic type variableusing System; class GFG { // Main Method static public void Main() { // Dynamic variables dynamic value1 = "GeeksforGeeks"; dynamic value2 = 123234; dynamic value3 = 2132.55; dynamic value4 = false; // Get the actual type of // dynamic variables // Using GetType() method Console.WriteLine("Get the actual type of value1: {0}", value1.GetType().ToString()); Console.WriteLine("Get the actual type of value2: {0}", value2.GetType().ToString()); Console.WriteLine("Get the actual type of value3: {0}", value3.GetType().ToString()); Console.WriteLine("Get the actual type of value4: {0}", value4.GetType().ToString()); }}Output:Get the actual type of value1: System.String
Get the actual type of value2: System.Int32
Get the actual type of value3: System.Double
Get the actual type of value4: System.Boolean
Example:
// C# program to illustrate how to get the// actual type of the dynamic type variableusing System; class GFG { // Main Method static public void Main() { // Dynamic variables dynamic value1 = "GeeksforGeeks"; dynamic value2 = 123234; dynamic value3 = 2132.55; dynamic value4 = false; // Get the actual type of // dynamic variables // Using GetType() method Console.WriteLine("Get the actual type of value1: {0}", value1.GetType().ToString()); Console.WriteLine("Get the actual type of value2: {0}", value2.GetType().ToString()); Console.WriteLine("Get the actual type of value3: {0}", value3.GetType().ToString()); Console.WriteLine("Get the actual type of value4: {0}", value4.GetType().ToString()); }}
Output:
Get the actual type of value1: System.String
Get the actual type of value2: System.Int32
Get the actual type of value3: System.Double
Get the actual type of value4: System.Boolean
When you assign a class object to the dynamic type, then the compiler does not check for the right method and property name of the dynamic type which holds the custom class object.
You can also pass a dynamic type parameter in the method so that the method can accept any type of parameter at run time. As shown in the below example.Example:// C# program to illustrate how to pass// dynamic type parameters in the methodusing System; class GFG { // Method which contains dynamic parameters public static void addstr(dynamic s1, dynamic s2) { Console.WriteLine(s1 + s2); } // Main method static public void Main() { // Calling addstr method addstr("G", "G"); addstr("Geeks", "forGeeks"); addstr("Cat", "Dog"); addstr("Hello", 1232); addstr(12, 30); }}Output:GG
GeeksforGeeks
CatDog
Hello1232
42
Example:
// C# program to illustrate how to pass// dynamic type parameters in the methodusing System; class GFG { // Method which contains dynamic parameters public static void addstr(dynamic s1, dynamic s2) { Console.WriteLine(s1 + s2); } // Main method static public void Main() { // Calling addstr method addstr("G", "G"); addstr("Geeks", "forGeeks"); addstr("Cat", "Dog"); addstr("Hello", 1232); addstr(12, 30); }}
Output:
GG
GeeksforGeeks
CatDog
Hello1232
42
The compiler will throw an exception at runtime if the methods and the properties are not compatible.
It does not support the intellisense in visual studio.
The compiler does not throw an error on dynamic type at compile time if there is no type checking for dynamic type.
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
Introduction to .NET Framework
C# | Delegates
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
C# | Method Overriding
C# | String.IndexOf( ) Method | Set - 1
Extension Method in C#
Difference between Ref and Out keywords in C#
C# | Replace() Method
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n10 Apr, 2019"
},
{
"code": null,
"e": 377,
"s": 52,
"text": "In C# 4.0, a new type is introduced that is known as a dynamic type. It is used to avoid the compile-time type checking. The compiler does not check the type of the dynamic type variable at compile time, instead of this, the compiler gets the type at the run time. The dynamic type variable is created using dynamic keyword."
},
{
"code": null,
"e": 386,
"s": 377,
"text": "Example:"
},
{
"code": null,
"e": 407,
"s": 386,
"text": "dynamic value = 123;"
},
{
"code": null,
"e": 425,
"s": 407,
"text": "Important Points:"
},
{
"code": null,
"e": 491,
"s": 425,
"text": "In most of the cases, the dynamic type behaves like object types."
},
{
"code": null,
"e": 1854,
"s": 491,
"text": "You can get the actual type of the dynamic variable at runtime by using GetType() method. The dynamic type changes its type at the run time based on the value present on the right-hand side. As shown in the below example.Example:// C# program to illustrate how to get the// actual type of the dynamic type variableusing System; class GFG { // Main Method static public void Main() { // Dynamic variables dynamic value1 = \"GeeksforGeeks\"; dynamic value2 = 123234; dynamic value3 = 2132.55; dynamic value4 = false; // Get the actual type of // dynamic variables // Using GetType() method Console.WriteLine(\"Get the actual type of value1: {0}\", value1.GetType().ToString()); Console.WriteLine(\"Get the actual type of value2: {0}\", value2.GetType().ToString()); Console.WriteLine(\"Get the actual type of value3: {0}\", value3.GetType().ToString()); Console.WriteLine(\"Get the actual type of value4: {0}\", value4.GetType().ToString()); }}Output:Get the actual type of value1: System.String\nGet the actual type of value2: System.Int32\nGet the actual type of value3: System.Double\nGet the actual type of value4: System.Boolean\n"
},
{
"code": null,
"e": 1863,
"s": 1854,
"text": "Example:"
},
{
"code": "// C# program to illustrate how to get the// actual type of the dynamic type variableusing System; class GFG { // Main Method static public void Main() { // Dynamic variables dynamic value1 = \"GeeksforGeeks\"; dynamic value2 = 123234; dynamic value3 = 2132.55; dynamic value4 = false; // Get the actual type of // dynamic variables // Using GetType() method Console.WriteLine(\"Get the actual type of value1: {0}\", value1.GetType().ToString()); Console.WriteLine(\"Get the actual type of value2: {0}\", value2.GetType().ToString()); Console.WriteLine(\"Get the actual type of value3: {0}\", value3.GetType().ToString()); Console.WriteLine(\"Get the actual type of value4: {0}\", value4.GetType().ToString()); }}",
"e": 2810,
"s": 1863,
"text": null
},
{
"code": null,
"e": 2818,
"s": 2810,
"text": "Output:"
},
{
"code": null,
"e": 2999,
"s": 2818,
"text": "Get the actual type of value1: System.String\nGet the actual type of value2: System.Int32\nGet the actual type of value3: System.Double\nGet the actual type of value4: System.Boolean\n"
},
{
"code": null,
"e": 3180,
"s": 2999,
"text": "When you assign a class object to the dynamic type, then the compiler does not check for the right method and property name of the dynamic type which holds the custom class object."
},
{
"code": null,
"e": 3874,
"s": 3180,
"text": "You can also pass a dynamic type parameter in the method so that the method can accept any type of parameter at run time. As shown in the below example.Example:// C# program to illustrate how to pass// dynamic type parameters in the methodusing System; class GFG { // Method which contains dynamic parameters public static void addstr(dynamic s1, dynamic s2) { Console.WriteLine(s1 + s2); } // Main method static public void Main() { // Calling addstr method addstr(\"G\", \"G\"); addstr(\"Geeks\", \"forGeeks\"); addstr(\"Cat\", \"Dog\"); addstr(\"Hello\", 1232); addstr(12, 30); }}Output:GG\nGeeksforGeeks\nCatDog\nHello1232\n42\n"
},
{
"code": null,
"e": 3883,
"s": 3874,
"text": "Example:"
},
{
"code": "// C# program to illustrate how to pass// dynamic type parameters in the methodusing System; class GFG { // Method which contains dynamic parameters public static void addstr(dynamic s1, dynamic s2) { Console.WriteLine(s1 + s2); } // Main method static public void Main() { // Calling addstr method addstr(\"G\", \"G\"); addstr(\"Geeks\", \"forGeeks\"); addstr(\"Cat\", \"Dog\"); addstr(\"Hello\", 1232); addstr(12, 30); }}",
"e": 4373,
"s": 3883,
"text": null
},
{
"code": null,
"e": 4381,
"s": 4373,
"text": "Output:"
},
{
"code": null,
"e": 4419,
"s": 4381,
"text": "GG\nGeeksforGeeks\nCatDog\nHello1232\n42\n"
},
{
"code": null,
"e": 4521,
"s": 4419,
"text": "The compiler will throw an exception at runtime if the methods and the properties are not compatible."
},
{
"code": null,
"e": 4576,
"s": 4521,
"text": "It does not support the intellisense in visual studio."
},
{
"code": null,
"e": 4692,
"s": 4576,
"text": "The compiler does not throw an error on dynamic type at compile time if there is no type checking for dynamic type."
},
{
"code": null,
"e": 4695,
"s": 4692,
"text": "C#"
},
{
"code": null,
"e": 4793,
"s": 4695,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4821,
"s": 4793,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 4852,
"s": 4821,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 4867,
"s": 4852,
"text": "C# | Delegates"
},
{
"code": null,
"e": 4910,
"s": 4867,
"text": "C# | Multiple inheritance using interfaces"
},
{
"code": null,
"e": 4959,
"s": 4910,
"text": "Differences Between .NET Core and .NET Framework"
},
{
"code": null,
"e": 4982,
"s": 4959,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 5022,
"s": 4982,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 5045,
"s": 5022,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 5091,
"s": 5045,
"text": "Difference between Ref and Out keywords in C#"
}
] |
GATE | GATE CS 2019 | Question 61
|
19 Feb, 2019
A relational database contains two tables Student and Performance as shown below:The primary key of the Student table is Roll_no. For the Performance table, the columns Roll_no. and Subject_code together from the primary key. Consider the SQL query given below:
SELECT S.Student_name, sum(P.Marks)
FROM Student S, Performance P
WHERE P.Marks > 84
GROUP BY S.Student_name;
The number of rows returned by the above SQL query is _________ .
Note: This was Numerical Type question.(A) 5(B) 4(C) 3(D) None of these.Answer: (A)Explanation: In where condition no condition over Roll_no so query produces all groups.
Total 5 different student names all 5 group records in result. See: http://sqlfiddle.com/#!9/8a79d3/1/0Quiz of this Question
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-1) | Question 65
GATE | Gate IT 2005 | Question 11
GATE | GATE MOCK 2017 | Question 45
GATE | GATE-CS-2004 | Question 90
GATE | GATE-CS-2000 | Question 2
GATE | GATE CS 2013 | Question 50
GATE | GATE CS 2012 | Question 65
GATE | GATE-CS-2003 | Question 64
GATE | GATE-CS-2004 | Question 90
GATE | GATE-CS-2015 (Set 1) | Question 30
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n19 Feb, 2019"
},
{
"code": null,
"e": 314,
"s": 52,
"text": "A relational database contains two tables Student and Performance as shown below:The primary key of the Student table is Roll_no. For the Performance table, the columns Roll_no. and Subject_code together from the primary key. Consider the SQL query given below:"
},
{
"code": null,
"e": 427,
"s": 314,
"text": "SELECT S.Student_name, sum(P.Marks)\nFROM Student S, Performance P\nWHERE P.Marks > 84\nGROUP BY S.Student_name;"
},
{
"code": null,
"e": 493,
"s": 427,
"text": "The number of rows returned by the above SQL query is _________ ."
},
{
"code": null,
"e": 664,
"s": 493,
"text": "Note: This was Numerical Type question.(A) 5(B) 4(C) 3(D) None of these.Answer: (A)Explanation: In where condition no condition over Roll_no so query produces all groups."
},
{
"code": null,
"e": 789,
"s": 664,
"text": "Total 5 different student names all 5 group records in result. See: http://sqlfiddle.com/#!9/8a79d3/1/0Quiz of this Question"
},
{
"code": null,
"e": 794,
"s": 789,
"text": "GATE"
},
{
"code": null,
"e": 892,
"s": 794,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 934,
"s": 892,
"text": "GATE | GATE-CS-2014-(Set-1) | Question 65"
},
{
"code": null,
"e": 968,
"s": 934,
"text": "GATE | Gate IT 2005 | Question 11"
},
{
"code": null,
"e": 1004,
"s": 968,
"text": "GATE | GATE MOCK 2017 | Question 45"
},
{
"code": null,
"e": 1038,
"s": 1004,
"text": "GATE | GATE-CS-2004 | Question 90"
},
{
"code": null,
"e": 1071,
"s": 1038,
"text": "GATE | GATE-CS-2000 | Question 2"
},
{
"code": null,
"e": 1105,
"s": 1071,
"text": "GATE | GATE CS 2013 | Question 50"
},
{
"code": null,
"e": 1139,
"s": 1105,
"text": "GATE | GATE CS 2012 | Question 65"
},
{
"code": null,
"e": 1173,
"s": 1139,
"text": "GATE | GATE-CS-2003 | Question 64"
},
{
"code": null,
"e": 1207,
"s": 1173,
"text": "GATE | GATE-CS-2004 | Question 90"
}
] |
Why start + (end – start)/2 is preferable method for calculating middle of an array over (start + end)/2 ?
|
27 Jul, 2021
I am very sure that everyone is able to find middle index of array once you know start index and end index of array, but there are certain benefits of using start + (end – start)/2 over (start + end)/2, which are described below :
The very first way of finding middle index is
mid = (start + end)/2
But there is problem with this approach, what if value of start or end or both is INT_MAX, it will cause integer overflow.The better way of calculating mid index is :
mid = start + (end - start)/2
Let’s try these both methods in C program :
C
// program for calculating mid of array#include <stdio.h>#include <limits.h>int main(){ int start = INT_MAX, end = INT_MAX; printf("start = %dn", start); printf("end = %dn", end); // method 1 int mid1 = (start + end) / 2; printf("mid using (start + end)/2 = %dn", mid1); // method 2 int mid2 = start + (end - start) / 2; printf("mid using start + (end - start)/2 = %dn", mid2); return 0;}
Output:
start = 2147483647
end = 2147483647
mid using (start + end)/2 = -1
mid using start + (end - start)/2 = 2147483647
Note : (end – start) may overflow if end < 0 or start < 0If you see the output, by using second method you get correct output and first method fails to calculate mid and if you use this index (-1 in this case), it can cause segmentation fault because of invalid index of array.
start + (end – start)/2 also works even if you are using pointers :
Example : Method 1
C
int s = 2, e = 3;int* start = &s;int* end = &e;int* mid = (start + end) / 2;
Output :
error: invalid operands of types ‘int*’ and ‘int*’ to binary ‘operator+’
int *mid = (start + end)/2;
Method 2
C
int s = 2, e = 3;int* start = &s;int* end = &e;int* mid = start + (end - start) / 2;
Output :
It will compile and give expected results
Explanation: pointer addition is not supported in C while pointer subtraction is supported, the reason being the result of subtraction is the difference (in array elements) between the operands. The subtraction expression yields a signed integral result of type ptrdiff_t (defined in the standard include file STDDEF.H)(in short subtraction gives memory distance), but addition of two pointers in not meaningful, that’s why not supported
References : 1) Additive Operators: + and – 2) why-prefer-start-end-start-2-over-start-end-2-when-calculating-the 3) pointer-addition-vs-subtraction
This article is contributed by Mandeep Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
msdeep14
sagar0719kumar
Misc
Misc
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n27 Jul, 2021"
},
{
"code": null,
"e": 283,
"s": 52,
"text": "I am very sure that everyone is able to find middle index of array once you know start index and end index of array, but there are certain benefits of using start + (end – start)/2 over (start + end)/2, which are described below :"
},
{
"code": null,
"e": 330,
"s": 283,
"text": "The very first way of finding middle index is "
},
{
"code": null,
"e": 352,
"s": 330,
"text": "mid = (start + end)/2"
},
{
"code": null,
"e": 520,
"s": 352,
"text": "But there is problem with this approach, what if value of start or end or both is INT_MAX, it will cause integer overflow.The better way of calculating mid index is : "
},
{
"code": null,
"e": 550,
"s": 520,
"text": "mid = start + (end - start)/2"
},
{
"code": null,
"e": 596,
"s": 550,
"text": "Let’s try these both methods in C program : "
},
{
"code": null,
"e": 598,
"s": 596,
"text": "C"
},
{
"code": "// program for calculating mid of array#include <stdio.h>#include <limits.h>int main(){ int start = INT_MAX, end = INT_MAX; printf(\"start = %dn\", start); printf(\"end = %dn\", end); // method 1 int mid1 = (start + end) / 2; printf(\"mid using (start + end)/2 = %dn\", mid1); // method 2 int mid2 = start + (end - start) / 2; printf(\"mid using start + (end - start)/2 = %dn\", mid2); return 0;}",
"e": 1019,
"s": 598,
"text": null
},
{
"code": null,
"e": 1028,
"s": 1019,
"text": "Output: "
},
{
"code": null,
"e": 1142,
"s": 1028,
"text": "start = 2147483647\nend = 2147483647\nmid using (start + end)/2 = -1\nmid using start + (end - start)/2 = 2147483647"
},
{
"code": null,
"e": 1420,
"s": 1142,
"text": "Note : (end – start) may overflow if end < 0 or start < 0If you see the output, by using second method you get correct output and first method fails to calculate mid and if you use this index (-1 in this case), it can cause segmentation fault because of invalid index of array."
},
{
"code": null,
"e": 1489,
"s": 1420,
"text": "start + (end – start)/2 also works even if you are using pointers : "
},
{
"code": null,
"e": 1510,
"s": 1489,
"text": "Example : Method 1 "
},
{
"code": null,
"e": 1512,
"s": 1510,
"text": "C"
},
{
"code": "int s = 2, e = 3;int* start = &s;int* end = &e;int* mid = (start + end) / 2;",
"e": 1589,
"s": 1512,
"text": null
},
{
"code": null,
"e": 1599,
"s": 1589,
"text": "Output : "
},
{
"code": null,
"e": 1705,
"s": 1599,
"text": "error: invalid operands of types ‘int*’ and ‘int*’ to binary ‘operator+’\n int *mid = (start + end)/2;"
},
{
"code": null,
"e": 1716,
"s": 1705,
"text": "Method 2 "
},
{
"code": null,
"e": 1718,
"s": 1716,
"text": "C"
},
{
"code": "int s = 2, e = 3;int* start = &s;int* end = &e;int* mid = start + (end - start) / 2;",
"e": 1803,
"s": 1718,
"text": null
},
{
"code": null,
"e": 1813,
"s": 1803,
"text": "Output : "
},
{
"code": null,
"e": 1855,
"s": 1813,
"text": "It will compile and give expected results"
},
{
"code": null,
"e": 2293,
"s": 1855,
"text": "Explanation: pointer addition is not supported in C while pointer subtraction is supported, the reason being the result of subtraction is the difference (in array elements) between the operands. The subtraction expression yields a signed integral result of type ptrdiff_t (defined in the standard include file STDDEF.H)(in short subtraction gives memory distance), but addition of two pointers in not meaningful, that’s why not supported"
},
{
"code": null,
"e": 2442,
"s": 2293,
"text": "References : 1) Additive Operators: + and – 2) why-prefer-start-end-start-2-over-start-end-2-when-calculating-the 3) pointer-addition-vs-subtraction"
},
{
"code": null,
"e": 2864,
"s": 2442,
"text": "This article is contributed by Mandeep Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 2873,
"s": 2864,
"text": "msdeep14"
},
{
"code": null,
"e": 2888,
"s": 2873,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 2893,
"s": 2888,
"text": "Misc"
},
{
"code": null,
"e": 2898,
"s": 2893,
"text": "Misc"
},
{
"code": null,
"e": 2903,
"s": 2898,
"text": "Misc"
}
] |
Angular Material 7 - Form Field
|
The <mat-form-field>, an Angular Directive, is used to create a wrapper over angular components and is used to apply text styles like underline, bold, hints etc.
Following angular component can be used within <mat-form-field>.
<input matNativeControl>
<input matNativeControl>
<textarea matNativeControl>
<textarea matNativeControl>
<select matNativeControl>
<select matNativeControl>
<mat-select>
<mat-select>
<mat-chip-list>
<mat-chip-list>
In this chapter, we will showcase the configuration required to use a mat-form-field control in Angular Material.
Follow the following steps to update the Angular application we created in Angular 6 - Project Setup chapter −
Following is the content of the modified module descriptor app.module.ts.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MatInputModule,MatOptionModule, MatSelectModule, MatIconModule} from '@angular/material'
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
MatInputModule,MatOptionModule, MatSelectModule, MatIconModule,
FormsModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Following is the content of the modified CSS file app.component.css.
.tp-container {
display: flex;
flex-direction: column;
}
.tp-container > * {
width: 100%;
}
Following is the content of the modified HTML host file app.component.html.
<div class = "tp-container">
<mat-form-field appearance = "standard">
<input matInput placeholder = "Input">
<mat-icon matSuffix>sentiment_very_satisfied</mat-icon>
<mat-hint>Sample Hint</mat-hint>
</mat-form-field>
<mat-form-field appearance = "fill">
<textarea matInput placeholder = "Textarea"></textarea>
</mat-form-field>
<mat-form-field appearance = "outline">
<mat-select placeholder = "Select">
<mat-option value = "A">A</mat-option>
<mat-option value = "B">B</mat-option>
<mat-option value = "C">C</mat-option>
</mat-select>
</mat-form-field>
</div>
Verify the result.
As first, we've created an form field using mat-form-field wrapper. We've changed the appearance of form field using appearance attribute.
As first, we've created an form field using mat-form-field wrapper. We've changed the appearance of form field using appearance attribute.
Then, a form control is added to the form field.
Then, a form control is added to the form field.
16 Lectures
1.5 hours
Anadi Sharma
28 Lectures
2.5 hours
Anadi Sharma
11 Lectures
7.5 hours
SHIVPRASAD KOIRALA
16 Lectures
2.5 hours
Frahaan Hussain
69 Lectures
5 hours
Senol Atac
53 Lectures
3.5 hours
Senol Atac
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2918,
"s": 2755,
"text": "The <mat-form-field>, an Angular Directive, is used to create a wrapper over angular components and is used to apply text styles like underline, bold, hints etc. "
},
{
"code": null,
"e": 2983,
"s": 2918,
"text": "Following angular component can be used within <mat-form-field>."
},
{
"code": null,
"e": 3008,
"s": 2983,
"text": "<input matNativeControl>"
},
{
"code": null,
"e": 3033,
"s": 3008,
"text": "<input matNativeControl>"
},
{
"code": null,
"e": 3061,
"s": 3033,
"text": "<textarea matNativeControl>"
},
{
"code": null,
"e": 3089,
"s": 3061,
"text": "<textarea matNativeControl>"
},
{
"code": null,
"e": 3115,
"s": 3089,
"text": "<select matNativeControl>"
},
{
"code": null,
"e": 3141,
"s": 3115,
"text": "<select matNativeControl>"
},
{
"code": null,
"e": 3154,
"s": 3141,
"text": "<mat-select>"
},
{
"code": null,
"e": 3167,
"s": 3154,
"text": "<mat-select>"
},
{
"code": null,
"e": 3183,
"s": 3167,
"text": "<mat-chip-list>"
},
{
"code": null,
"e": 3199,
"s": 3183,
"text": "<mat-chip-list>"
},
{
"code": null,
"e": 3313,
"s": 3199,
"text": "In this chapter, we will showcase the configuration required to use a mat-form-field control in Angular Material."
},
{
"code": null,
"e": 3424,
"s": 3313,
"text": "Follow the following steps to update the Angular application we created in Angular 6 - Project Setup chapter −"
},
{
"code": null,
"e": 3498,
"s": 3424,
"text": "Following is the content of the modified module descriptor app.module.ts."
},
{
"code": null,
"e": 4207,
"s": 3498,
"text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { AppComponent } from './app.component';\nimport {BrowserAnimationsModule} from '@angular/platform-browser/animations';\nimport {MatInputModule,MatOptionModule, MatSelectModule, MatIconModule} from '@angular/material'\nimport {FormsModule, ReactiveFormsModule} from '@angular/forms';\n@NgModule({\n declarations: [\n AppComponent\n ],\n imports: [\n BrowserModule,\n BrowserAnimationsModule,\n MatInputModule,MatOptionModule, MatSelectModule, MatIconModule,\n FormsModule,\n ReactiveFormsModule\n ],\n providers: [],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }"
},
{
"code": null,
"e": 4276,
"s": 4207,
"text": "Following is the content of the modified CSS file app.component.css."
},
{
"code": null,
"e": 4377,
"s": 4276,
"text": ".tp-container {\n display: flex;\n flex-direction: column;\n}\n.tp-container > * {\n width: 100%;\n}"
},
{
"code": null,
"e": 4453,
"s": 4377,
"text": "Following is the content of the modified HTML host file app.component.html."
},
{
"code": null,
"e": 5099,
"s": 4453,
"text": "<div class = \"tp-container\">\n <mat-form-field appearance = \"standard\">\n <input matInput placeholder = \"Input\">\n <mat-icon matSuffix>sentiment_very_satisfied</mat-icon>\n <mat-hint>Sample Hint</mat-hint>\n </mat-form-field>\n <mat-form-field appearance = \"fill\">\n <textarea matInput placeholder = \"Textarea\"></textarea>\n </mat-form-field>\n <mat-form-field appearance = \"outline\">\n <mat-select placeholder = \"Select\">\n <mat-option value = \"A\">A</mat-option>\n <mat-option value = \"B\">B</mat-option>\n <mat-option value = \"C\">C</mat-option> \n </mat-select>\n </mat-form-field>\n</div>"
},
{
"code": null,
"e": 5118,
"s": 5099,
"text": "Verify the result."
},
{
"code": null,
"e": 5257,
"s": 5118,
"text": "As first, we've created an form field using mat-form-field wrapper. We've changed the appearance of form field using appearance attribute."
},
{
"code": null,
"e": 5396,
"s": 5257,
"text": "As first, we've created an form field using mat-form-field wrapper. We've changed the appearance of form field using appearance attribute."
},
{
"code": null,
"e": 5445,
"s": 5396,
"text": "Then, a form control is added to the form field."
},
{
"code": null,
"e": 5494,
"s": 5445,
"text": "Then, a form control is added to the form field."
},
{
"code": null,
"e": 5529,
"s": 5494,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5543,
"s": 5529,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5578,
"s": 5543,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5592,
"s": 5578,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5627,
"s": 5592,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 5647,
"s": 5627,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 5682,
"s": 5647,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5699,
"s": 5682,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5732,
"s": 5699,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 5744,
"s": 5732,
"text": " Senol Atac"
},
{
"code": null,
"e": 5779,
"s": 5744,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5791,
"s": 5779,
"text": " Senol Atac"
},
{
"code": null,
"e": 5798,
"s": 5791,
"text": " Print"
},
{
"code": null,
"e": 5809,
"s": 5798,
"text": " Add Notes"
}
] |
Android - Audio Manager
|
You can easily control your ringer volume and ringer profile i-e:(silent,vibrate,loud e.t.c) in android. Android provides AudioManager class that provides access to these controls.
In order to use AndroidManager class, you have to first create an object of AudioManager class by calling the getSystemService() method. Its syntax is given below.
private AudioManager myAudioManager;
myAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
Once you instantiate the object of AudioManager class, you can use setRingerMode method to set the audio or ringer profile of your device. Its syntax is given below.
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
The method setRingerMode takes an integer number as a parameter. For each mode , an integer number is assigned that will differentiate between different modes. The possible modes are.
RINGER_MODE_VIBRATE
This Mode sets the device at vibrate mode.
RINGER_MODE_NORMAL
This Mode sets the device at normal(loud) mode.
RINGER_MODE_SILENT
This Mode sets the device at silent mode.
Once you have set the mode , you can call the getRingerMode() method to get the set state of the system. Its syntax is given below.
int mod = myAudioManager.getRingerMode();
Apart from the getRingerMode method, there are other methods available in the AudioManager class to control the volume and other modes. They are listed below.
adjustVolume(int direction, int flags)
This method adjusts the volume of the most relevant stream
getMode()
This method returns the current audio mode
getStreamMaxVolume(int streamType)
This method returns the maximum volume index for a particular stream
getStreamVolume(int streamType)
This method returns the current volume index for a particular stream
isMusicActive()
This method checks whether any music is active.
startBluetoothSco()
This method Start bluetooth SCO audio connection
stopBluetoothSco()
This method stop bluetooth SCO audio connection.
The below example demonstrates the use of AudioManager class. It creates a application that allows you to set different ringer modes for your device.
To experiment with this example , you need to run this on an actual device.
Here is the content of src/MainActivity.java
package com.example.sairamkrishna.myapplication;
import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
Button mode,ring,vibrate,silent;
private AudioManager myAudioManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
vibrate=(Button)findViewById(R.id.button3);
ring=(Button)findViewById(R.id.button2);
mode=(Button)findViewById(R.id.button);
silent=(Button)findViewById(R.id.button4);
myAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
vibrate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
Toast.makeText(MainActivity.this,"Now in Vibrate Mode",
Toast.LENGTH_LONG).show();
}
});
ring.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
Toast.makeText(MainActivity.this,"Now in Ringing Mode",
Toast.LENGTH_LONG).show();
}
});
silent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
Toast.makeText(MainActivity.this,"Now in silent Mode",
Toast.LENGTH_LONG).show();
}
});
mode.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int mod=myAudioManager.getRingerMode();
if(mod==AudioManager.RINGER_MODE_VIBRATE){
Toast.makeText(MainActivity.this,"Now in Vibrate Mode",
Toast.LENGTH_LONG).show();
} else if(mod==AudioManager.RINGER_MODE_NORMAL){
Toast.makeText(MainActivity.this,"Now in Ringing Mode",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this,"Now in Vibrate Mode",
Toast.LENGTH_LONG).show();
}
}
});
}
}
Here is the content of activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Android Audio Recording"
android:id="@+id/textView"
android:textSize="30dp"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorialspoint"
android:id="@+id/textView2"
android:textColor="#ff3eff0f"
android:textSize="35dp"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_below="@+id/textView2"
android:layout_alignLeft="@+id/textView2"
android:layout_alignStart="@+id/textView2"
android:layout_alignRight="@+id/textView2"
android:layout_alignEnd="@+id/textView2" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Mode"
android:id="@+id/button"
android:layout_below="@+id/imageView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="59dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ring"
android:id="@+id/button2"
android:layout_alignTop="@+id/button"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="vibrate"
android:id="@+id/button3"
android:layout_alignTop="@+id/button2"
android:layout_alignRight="@+id/textView"
android:layout_alignEnd="@+id/textView" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Silent"
android:id="@+id/button4"
android:layout_below="@+id/button2"
android:layout_alignLeft="@+id/button2"
android:layout_alignStart="@+id/button2" />
</RelativeLayout>
Here is the content of Strings.xml
<resources>
<string name="app_name">My Application</string>
</resources>
Here is the content of AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.sairamkrishna.myapplication"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your 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 tool bar. Android studio will display Images
Now select silent button, you would get silent icon at Notification bar
Now just select the ring button and then press the current mode button to see that if its status has been set.
Now press the Vibrate button and then press the current mode button to see that if it is set or not.It will display the following screen.
46 Lectures
7.5 hours
Aditya Dua
32 Lectures
3.5 hours
Sharad Kumar
9 Lectures
1 hours
Abhilash Nelson
14 Lectures
1.5 hours
Abhilash Nelson
15 Lectures
1.5 hours
Abhilash Nelson
10 Lectures
1 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3788,
"s": 3607,
"text": "You can easily control your ringer volume and ringer profile i-e:(silent,vibrate,loud e.t.c) in android. Android provides AudioManager class that provides access to these controls."
},
{
"code": null,
"e": 3952,
"s": 3788,
"text": "In order to use AndroidManager class, you have to first create an object of AudioManager class by calling the getSystemService() method. Its syntax is given below."
},
{
"code": null,
"e": 4063,
"s": 3952,
"text": "private AudioManager myAudioManager;\nmyAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE); "
},
{
"code": null,
"e": 4229,
"s": 4063,
"text": "Once you instantiate the object of AudioManager class, you can use setRingerMode method to set the audio or ringer profile of your device. Its syntax is given below."
},
{
"code": null,
"e": 4293,
"s": 4229,
"text": "myAudioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);"
},
{
"code": null,
"e": 4477,
"s": 4293,
"text": "The method setRingerMode takes an integer number as a parameter. For each mode , an integer number is assigned that will differentiate between different modes. The possible modes are."
},
{
"code": null,
"e": 4497,
"s": 4477,
"text": "RINGER_MODE_VIBRATE"
},
{
"code": null,
"e": 4540,
"s": 4497,
"text": "This Mode sets the device at vibrate mode."
},
{
"code": null,
"e": 4559,
"s": 4540,
"text": "RINGER_MODE_NORMAL"
},
{
"code": null,
"e": 4607,
"s": 4559,
"text": "This Mode sets the device at normal(loud) mode."
},
{
"code": null,
"e": 4626,
"s": 4607,
"text": "RINGER_MODE_SILENT"
},
{
"code": null,
"e": 4668,
"s": 4626,
"text": "This Mode sets the device at silent mode."
},
{
"code": null,
"e": 4800,
"s": 4668,
"text": "Once you have set the mode , you can call the getRingerMode() method to get the set state of the system. Its syntax is given below."
},
{
"code": null,
"e": 4842,
"s": 4800,
"text": "int mod = myAudioManager.getRingerMode();"
},
{
"code": null,
"e": 5001,
"s": 4842,
"text": "Apart from the getRingerMode method, there are other methods available in the AudioManager class to control the volume and other modes. They are listed below."
},
{
"code": null,
"e": 5040,
"s": 5001,
"text": "adjustVolume(int direction, int flags)"
},
{
"code": null,
"e": 5099,
"s": 5040,
"text": "This method adjusts the volume of the most relevant stream"
},
{
"code": null,
"e": 5109,
"s": 5099,
"text": "getMode()"
},
{
"code": null,
"e": 5152,
"s": 5109,
"text": "This method returns the current audio mode"
},
{
"code": null,
"e": 5187,
"s": 5152,
"text": "getStreamMaxVolume(int streamType)"
},
{
"code": null,
"e": 5256,
"s": 5187,
"text": "This method returns the maximum volume index for a particular stream"
},
{
"code": null,
"e": 5288,
"s": 5256,
"text": "getStreamVolume(int streamType)"
},
{
"code": null,
"e": 5357,
"s": 5288,
"text": "This method returns the current volume index for a particular stream"
},
{
"code": null,
"e": 5373,
"s": 5357,
"text": "isMusicActive()"
},
{
"code": null,
"e": 5421,
"s": 5373,
"text": "This method checks whether any music is active."
},
{
"code": null,
"e": 5441,
"s": 5421,
"text": "startBluetoothSco()"
},
{
"code": null,
"e": 5490,
"s": 5441,
"text": "This method Start bluetooth SCO audio connection"
},
{
"code": null,
"e": 5509,
"s": 5490,
"text": "stopBluetoothSco()"
},
{
"code": null,
"e": 5558,
"s": 5509,
"text": "This method stop bluetooth SCO audio connection."
},
{
"code": null,
"e": 5709,
"s": 5558,
"text": "The below example demonstrates the use of AudioManager class. It creates a application that allows you to set different ringer modes for your device."
},
{
"code": null,
"e": 5785,
"s": 5709,
"text": "To experiment with this example , you need to run this on an actual device."
},
{
"code": null,
"e": 5830,
"s": 5785,
"text": "Here is the content of src/MainActivity.java"
},
{
"code": null,
"e": 8315,
"s": 5830,
"text": "package com.example.sairamkrishna.myapplication;\n\nimport android.app.Activity;\nimport android.content.Context;\nimport android.media.AudioManager;\nimport android.os.Bundle;\nimport android.view.View;\n\nimport android.widget.Button;\nimport android.widget.Toast;\n\n\npublic class MainActivity extends Activity {\n Button mode,ring,vibrate,silent;\n private AudioManager myAudioManager;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n vibrate=(Button)findViewById(R.id.button3);\n ring=(Button)findViewById(R.id.button2);\n\n mode=(Button)findViewById(R.id.button);\n silent=(Button)findViewById(R.id.button4);\n myAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);\n\n vibrate.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n myAudioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);\n Toast.makeText(MainActivity.this,\"Now in Vibrate Mode\",\n Toast.LENGTH_LONG).show();\n }\n });\n\n ring.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n myAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);\n Toast.makeText(MainActivity.this,\"Now in Ringing Mode\",\n Toast.LENGTH_LONG).show();\n }\n });\n\n silent.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n myAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);\n Toast.makeText(MainActivity.this,\"Now in silent Mode\",\n Toast.LENGTH_LONG).show();\n }\n });\n\n mode.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n int mod=myAudioManager.getRingerMode();\n if(mod==AudioManager.RINGER_MODE_VIBRATE){\n Toast.makeText(MainActivity.this,\"Now in Vibrate Mode\",\n Toast.LENGTH_LONG).show();\n } else if(mod==AudioManager.RINGER_MODE_NORMAL){\n Toast.makeText(MainActivity.this,\"Now in Ringing Mode\",\n Toast.LENGTH_LONG).show();\n } else {\n Toast.makeText(MainActivity.this,\"Now in Vibrate Mode\",\n Toast.LENGTH_LONG).show();\n }\n }\n });\n }\n}"
},
{
"code": null,
"e": 8356,
"s": 8315,
"text": "Here is the content of activity_main.xml"
},
{
"code": null,
"e": 11178,
"s": 8356,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout \n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\" \n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\" \n android:paddingLeft=\"@dimen/activity_horizontal_margin\"\n android:paddingRight=\"@dimen/activity_horizontal_margin\"\n android:paddingTop=\"@dimen/activity_vertical_margin\"\n android:paddingBottom=\"@dimen/activity_vertical_margin\" \n tools:context=\".MainActivity\">\n\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Android Audio Recording\"\n android:id=\"@+id/textView\"\n android:textSize=\"30dp\"\n android:layout_alignParentTop=\"true\"\n android:layout_alignParentRight=\"true\"\n android:layout_alignParentEnd=\"true\" />\n \n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Tutorialspoint\"\n android:id=\"@+id/textView2\"\n android:textColor=\"#ff3eff0f\"\n android:textSize=\"35dp\"\n android:layout_below=\"@+id/textView\"\n android:layout_centerHorizontal=\"true\" />\n \n <ImageView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/imageView\"\n android:src=\"@drawable/abc\"\n android:layout_below=\"@+id/textView2\"\n android:layout_alignLeft=\"@+id/textView2\"\n android:layout_alignStart=\"@+id/textView2\"\n android:layout_alignRight=\"@+id/textView2\"\n android:layout_alignEnd=\"@+id/textView2\" />\n \n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Mode\"\n android:id=\"@+id/button\"\n android:layout_below=\"@+id/imageView\"\n android:layout_alignParentLeft=\"true\"\n android:layout_alignParentStart=\"true\"\n android:layout_marginTop=\"59dp\" />\n \n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Ring\"\n android:id=\"@+id/button2\"\n android:layout_alignTop=\"@+id/button\"\n android:layout_centerHorizontal=\"true\" />\n \n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"vibrate\"\n android:id=\"@+id/button3\"\n android:layout_alignTop=\"@+id/button2\"\n android:layout_alignRight=\"@+id/textView\"\n android:layout_alignEnd=\"@+id/textView\" />\n \n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Silent\"\n android:id=\"@+id/button4\"\n android:layout_below=\"@+id/button2\"\n android:layout_alignLeft=\"@+id/button2\"\n android:layout_alignStart=\"@+id/button2\" /> \n</RelativeLayout>"
},
{
"code": null,
"e": 11213,
"s": 11178,
"text": "Here is the content of Strings.xml"
},
{
"code": null,
"e": 11289,
"s": 11213,
"text": "<resources>\n <string name=\"app_name\">My Application</string>\n</resources>"
},
{
"code": null,
"e": 11332,
"s": 11289,
"text": "Here is the content of AndroidManifest.xml"
},
{
"code": null,
"e": 12056,
"s": 11332,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.sairamkrishna.myapplication\" >\n\n <application\n android:allowBackup=\"true\"\n android:icon=\"@drawable/ic_launcher\"\n android:label=\"@string/app_name\"\n android:theme=\"@style/AppTheme\" >\n \n <activity\n android:name=\"com.example.sairamkrishna.myapplication\"\n android:label=\"@string/app_name\" >\n \n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n \n </activity>\n \n </application>\n</manifest>"
},
{
"code": null,
"e": 12326,
"s": 12056,
"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 tool bar. Android studio will display Images"
},
{
"code": null,
"e": 12398,
"s": 12326,
"text": "Now select silent button, you would get silent icon at Notification bar"
},
{
"code": null,
"e": 12509,
"s": 12398,
"text": "Now just select the ring button and then press the current mode button to see that if its status has been set."
},
{
"code": null,
"e": 12647,
"s": 12509,
"text": "Now press the Vibrate button and then press the current mode button to see that if it is set or not.It will display the following screen."
},
{
"code": null,
"e": 12682,
"s": 12647,
"text": "\n 46 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 12694,
"s": 12682,
"text": " Aditya Dua"
},
{
"code": null,
"e": 12729,
"s": 12694,
"text": "\n 32 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 12743,
"s": 12729,
"text": " Sharad Kumar"
},
{
"code": null,
"e": 12775,
"s": 12743,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 12792,
"s": 12775,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 12827,
"s": 12792,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 12844,
"s": 12827,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 12879,
"s": 12844,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 12896,
"s": 12879,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 12929,
"s": 12896,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 12946,
"s": 12929,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 12953,
"s": 12946,
"text": " Print"
},
{
"code": null,
"e": 12964,
"s": 12953,
"text": " Add Notes"
}
] |
Python break statement
|
It terminates the current loop and resumes execution at the next statement, just like the traditional break statement in C.
The most common use for break is when some external condition is triggered requiring a hasty exit from a loop. The break statement can be used in both while and for loops.
If you are using nested loops, the break statement stops the execution of the innermost loop and start executing the next line of code after the block.
The syntax for a break statement in Python is as follows −
break
#!/usr/bin/python
for letter in 'Python': # First Example
if letter == 'h':
break
print 'Current Letter :', letter
var = 10 # Second Example
while var > 0:
print 'Current variable value :', var
var = var -1
if var == 5:
break
print "Good bye!"
When the above code is executed, it produces the following result −
Current Letter : P
Current Letter : y
Current Letter : t
Current variable value : 10
Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6
Good bye!
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": 2368,
"s": 2244,
"text": "It terminates the current loop and resumes execution at the next statement, just like the traditional break statement in C."
},
{
"code": null,
"e": 2540,
"s": 2368,
"text": "The most common use for break is when some external condition is triggered requiring a hasty exit from a loop. The break statement can be used in both while and for loops."
},
{
"code": null,
"e": 2692,
"s": 2540,
"text": "If you are using nested loops, the break statement stops the execution of the innermost loop and start executing the next line of code after the block."
},
{
"code": null,
"e": 2751,
"s": 2692,
"text": "The syntax for a break statement in Python is as follows −"
},
{
"code": null,
"e": 2758,
"s": 2751,
"text": "break\n"
},
{
"code": null,
"e": 3071,
"s": 2758,
"text": "#!/usr/bin/python\n\nfor letter in 'Python': # First Example\n if letter == 'h':\n break\n print 'Current Letter :', letter\n \nvar = 10 # Second Example\nwhile var > 0: \n print 'Current variable value :', var\n var = var -1\n if var == 5:\n break\n\nprint \"Good bye!\""
},
{
"code": null,
"e": 3139,
"s": 3071,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 3343,
"s": 3139,
"text": "Current Letter : P\nCurrent Letter : y\nCurrent Letter : t\nCurrent variable value : 10\nCurrent variable value : 9\nCurrent variable value : 8\nCurrent variable value : 7\nCurrent variable value : 6\nGood bye!\n"
},
{
"code": null,
"e": 3380,
"s": 3343,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3396,
"s": 3380,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3429,
"s": 3396,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3448,
"s": 3429,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3483,
"s": 3448,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3505,
"s": 3483,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3539,
"s": 3505,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3567,
"s": 3539,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3602,
"s": 3567,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3616,
"s": 3602,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3649,
"s": 3616,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3666,
"s": 3649,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3673,
"s": 3666,
"text": " Print"
},
{
"code": null,
"e": 3684,
"s": 3673,
"text": " Add Notes"
}
] |
C++ Program For Reversing A Linked List In Groups Of Given Size - Set 1 - GeeksforGeeks
|
16 Dec, 2021
Given a linked list, write a function to reverse every k nodes (where k is an input to the function).
Example:
Input: 1->2->3->4->5->6->7->8->NULL, K = 3 Output: 3->2->1->6->5->4->8->7->NULL Input: 1->2->3->4->5->6->7->8->NULL, K = 5 Output: 5->4->3->2->1->8->7->6->NULL
Algorithm: reverse(head, k)
Reverse the first sub-list of size k. While reversing keep track of the next node and previous node. Let the pointer to the next node be next and pointer to the previous node be prev. See this post for reversing a linked list.
head->next = reverse(next, k) ( Recursively call for rest of the list and link the two sub-lists )
Return prev ( prev becomes the new head of the list (see the diagrams of an iterative method of this post )
Below is image shows how the reverse function works:
Below is the implementation of the above approach:
C++
// C++ program to reverse a linked list// in groups of given size#include <bits/stdc++.h>using namespace std; // Link list node class Node { public: int data; Node* next;}; /* Reverses the linked list in groups of size k and returns the pointer to the new head node. */Node* reverse(Node* head, int k){ // Base case if (!head) return NULL; Node* current = head; Node* next = NULL; Node* prev = NULL; int count = 0; // Reverse first k nodes of the // linked list while (current != NULL && count < k) { next = current->next; current->next = prev; prev = current; current = next; count++; } /* next is now a pointer to (k+1)th node Recursively call for the list starting from current. And make rest of the list as next of first node */ if (next != NULL) head->next = reverse(next, k); // prev is new head of the input list return prev;} // UTILITY FUNCTIONS // Function to push a node void push(Node** head_ref, int new_data){ // Allocate node Node* new_node = new Node(); // Put in the data new_node->data = new_data; // Link the old list off the // new node new_node->next = (*head_ref); // Move the head to point to // the new node (*head_ref) = new_node;} // Function to print linked list void printList(Node* node){ while (node != NULL) { cout << node->data << " "; node = node->next; }} // Driver codeint main(){ // Start with the empty list Node* head = NULL; /* Create Linked list 1->2->3->4->5->6->7->8->9 */ push(&head, 9); push(&head, 8); push(&head, 7); push(&head, 6); push(&head, 5); push(&head, 4); push(&head, 3); push(&head, 2); push(&head, 1); cout << "Given linked list "; printList(head); head = reverse(head, 3); cout << "Reversed Linked list "; printList(head); return (0);}// This code is contributed by rathbhupendra
Output:
Given Linked List
1 2 3 4 5 6 7 8 9
Reversed list
3 2 1 6 5 4 9 8 7
Complexity Analysis:
Time Complexity: O(n). Traversal of list is done only once and it has ‘n’ elements.
Auxiliary Space: O(n/k). For each Linked List of size n, n/k or (n/k)+1 calls will be made during the recursion.
Please refer complete article on Reverse a Linked List in groups of given size | Set 1 for more details!
Accolite
Adobe
Amazon
Amazon-Question
Hike
Linked Lists
MakeMyTrip
Microsoft
Paytm
Reverse
SAP Labs
Snapdeal
Snapdeal-Question
VMWare
Yatra.com-Question
C++
C++ Programs
Linked List
Paytm
VMWare
Accolite
Amazon
Microsoft
Snapdeal
Hike
MakeMyTrip
Adobe
SAP Labs
Linked List
Reverse
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Iterators in C++ STL
Operator Overloading in C++
Friend class and function in C++
Destructors in C++
Polymorphism in C++
Header files in C/C++ and its uses
C++ Program for QuickSort
How to return multiple values from a function in C or C++?
Program to print ASCII Value of a character
C++ program for hashing with chaining
|
[
{
"code": null,
"e": 23785,
"s": 23757,
"text": "\n16 Dec, 2021"
},
{
"code": null,
"e": 23888,
"s": 23785,
"text": "Given a linked list, write a function to reverse every k nodes (where k is an input to the function). "
},
{
"code": null,
"e": 23898,
"s": 23888,
"text": "Example: "
},
{
"code": null,
"e": 24059,
"s": 23898,
"text": "Input: 1->2->3->4->5->6->7->8->NULL, K = 3 Output: 3->2->1->6->5->4->8->7->NULL Input: 1->2->3->4->5->6->7->8->NULL, K = 5 Output: 5->4->3->2->1->8->7->6->NULL "
},
{
"code": null,
"e": 24088,
"s": 24059,
"text": "Algorithm: reverse(head, k) "
},
{
"code": null,
"e": 24315,
"s": 24088,
"text": "Reverse the first sub-list of size k. While reversing keep track of the next node and previous node. Let the pointer to the next node be next and pointer to the previous node be prev. See this post for reversing a linked list."
},
{
"code": null,
"e": 24414,
"s": 24315,
"text": "head->next = reverse(next, k) ( Recursively call for rest of the list and link the two sub-lists )"
},
{
"code": null,
"e": 24522,
"s": 24414,
"text": "Return prev ( prev becomes the new head of the list (see the diagrams of an iterative method of this post )"
},
{
"code": null,
"e": 24576,
"s": 24522,
"text": "Below is image shows how the reverse function works: "
},
{
"code": null,
"e": 24627,
"s": 24576,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 24631,
"s": 24627,
"text": "C++"
},
{
"code": "// C++ program to reverse a linked list// in groups of given size#include <bits/stdc++.h>using namespace std; // Link list node class Node { public: int data; Node* next;}; /* Reverses the linked list in groups of size k and returns the pointer to the new head node. */Node* reverse(Node* head, int k){ // Base case if (!head) return NULL; Node* current = head; Node* next = NULL; Node* prev = NULL; int count = 0; // Reverse first k nodes of the // linked list while (current != NULL && count < k) { next = current->next; current->next = prev; prev = current; current = next; count++; } /* next is now a pointer to (k+1)th node Recursively call for the list starting from current. And make rest of the list as next of first node */ if (next != NULL) head->next = reverse(next, k); // prev is new head of the input list return prev;} // UTILITY FUNCTIONS // Function to push a node void push(Node** head_ref, int new_data){ // Allocate node Node* new_node = new Node(); // Put in the data new_node->data = new_data; // Link the old list off the // new node new_node->next = (*head_ref); // Move the head to point to // the new node (*head_ref) = new_node;} // Function to print linked list void printList(Node* node){ while (node != NULL) { cout << node->data << \" \"; node = node->next; }} // Driver codeint main(){ // Start with the empty list Node* head = NULL; /* Create Linked list 1->2->3->4->5->6->7->8->9 */ push(&head, 9); push(&head, 8); push(&head, 7); push(&head, 6); push(&head, 5); push(&head, 4); push(&head, 3); push(&head, 2); push(&head, 1); cout << \"Given linked list \"; printList(head); head = reverse(head, 3); cout << \"Reversed Linked list \"; printList(head); return (0);}// This code is contributed by rathbhupendra",
"e": 26667,
"s": 24631,
"text": null
},
{
"code": null,
"e": 26676,
"s": 26667,
"text": "Output: "
},
{
"code": null,
"e": 26746,
"s": 26676,
"text": "Given Linked List\n1 2 3 4 5 6 7 8 9 \nReversed list\n3 2 1 6 5 4 9 8 7 "
},
{
"code": null,
"e": 26768,
"s": 26746,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 26852,
"s": 26768,
"text": "Time Complexity: O(n). Traversal of list is done only once and it has ‘n’ elements."
},
{
"code": null,
"e": 26965,
"s": 26852,
"text": "Auxiliary Space: O(n/k). For each Linked List of size n, n/k or (n/k)+1 calls will be made during the recursion."
},
{
"code": null,
"e": 27070,
"s": 26965,
"text": "Please refer complete article on Reverse a Linked List in groups of given size | Set 1 for more details!"
},
{
"code": null,
"e": 27079,
"s": 27070,
"text": "Accolite"
},
{
"code": null,
"e": 27085,
"s": 27079,
"text": "Adobe"
},
{
"code": null,
"e": 27092,
"s": 27085,
"text": "Amazon"
},
{
"code": null,
"e": 27108,
"s": 27092,
"text": "Amazon-Question"
},
{
"code": null,
"e": 27113,
"s": 27108,
"text": "Hike"
},
{
"code": null,
"e": 27126,
"s": 27113,
"text": "Linked Lists"
},
{
"code": null,
"e": 27137,
"s": 27126,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 27147,
"s": 27137,
"text": "Microsoft"
},
{
"code": null,
"e": 27153,
"s": 27147,
"text": "Paytm"
},
{
"code": null,
"e": 27161,
"s": 27153,
"text": "Reverse"
},
{
"code": null,
"e": 27170,
"s": 27161,
"text": "SAP Labs"
},
{
"code": null,
"e": 27179,
"s": 27170,
"text": "Snapdeal"
},
{
"code": null,
"e": 27197,
"s": 27179,
"text": "Snapdeal-Question"
},
{
"code": null,
"e": 27204,
"s": 27197,
"text": "VMWare"
},
{
"code": null,
"e": 27223,
"s": 27204,
"text": "Yatra.com-Question"
},
{
"code": null,
"e": 27227,
"s": 27223,
"text": "C++"
},
{
"code": null,
"e": 27240,
"s": 27227,
"text": "C++ Programs"
},
{
"code": null,
"e": 27252,
"s": 27240,
"text": "Linked List"
},
{
"code": null,
"e": 27258,
"s": 27252,
"text": "Paytm"
},
{
"code": null,
"e": 27265,
"s": 27258,
"text": "VMWare"
},
{
"code": null,
"e": 27274,
"s": 27265,
"text": "Accolite"
},
{
"code": null,
"e": 27281,
"s": 27274,
"text": "Amazon"
},
{
"code": null,
"e": 27291,
"s": 27281,
"text": "Microsoft"
},
{
"code": null,
"e": 27300,
"s": 27291,
"text": "Snapdeal"
},
{
"code": null,
"e": 27305,
"s": 27300,
"text": "Hike"
},
{
"code": null,
"e": 27316,
"s": 27305,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 27322,
"s": 27316,
"text": "Adobe"
},
{
"code": null,
"e": 27331,
"s": 27322,
"text": "SAP Labs"
},
{
"code": null,
"e": 27343,
"s": 27331,
"text": "Linked List"
},
{
"code": null,
"e": 27351,
"s": 27343,
"text": "Reverse"
},
{
"code": null,
"e": 27355,
"s": 27351,
"text": "CPP"
},
{
"code": null,
"e": 27453,
"s": 27355,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27462,
"s": 27453,
"text": "Comments"
},
{
"code": null,
"e": 27475,
"s": 27462,
"text": "Old Comments"
},
{
"code": null,
"e": 27496,
"s": 27475,
"text": "Iterators in C++ STL"
},
{
"code": null,
"e": 27524,
"s": 27496,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 27557,
"s": 27524,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 27576,
"s": 27557,
"text": "Destructors in C++"
},
{
"code": null,
"e": 27596,
"s": 27576,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 27631,
"s": 27596,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 27657,
"s": 27631,
"text": "C++ Program for QuickSort"
},
{
"code": null,
"e": 27716,
"s": 27657,
"text": "How to return multiple values from a function in C or C++?"
},
{
"code": null,
"e": 27760,
"s": 27716,
"text": "Program to print ASCII Value of a character"
}
] |
How to apply a 3×3 convolution matrix using imageconvolution() in PHP?
|
imageconvolution() is an inbuilt function in PHP that is used to apply a 3×3 convolution matrix, using the coefficient and offset in the image.
bool imageconvolution ( $image, $matrix, $div, $offset)
imageconvolution() takes four parameters: $image, $matrix, $div, and $offset.
$image − This parameter is used to create the size of the image by using an image creation function such as imagecreatetruecolor().
$image − This parameter is used to create the size of the image by using an image creation function such as imagecreatetruecolor().
$matrix − This parameter contains an array of 3×3 matrix of floats.
$matrix − This parameter contains an array of 3×3 matrix of floats.
$div − It is used for normalization.
$div − It is used for normalization.
$offset − This parameter is used to set the color offset.
$offset − This parameter is used to set the color offset.
imageconvolution() returns True on success and False on failure.
<?php
// load the PNG image by using imagecreatefrompng function.
$image = imagecreatefrompng('C:\xampp\htdocs\Images\img59.png');
// Applied the 3X3 array matrix
$matrix = array(
array(2, 0, 0),
array(0, -1, 0),
array(0, 0, -1)
);
// imageconvolution function to modify image elements
imageconvolution($image, $matrix, 1, 127);
// show the output image in the browser
header('Content-Type: image/png');
imagepng($image, null, 9);
?>
Input PNG image before using imageconvolution() function
Output PNG image after using imageconvolution() function
<?php
$image = imagecreatetruecolor(700, 300);
// Writes the text and apply a gaussian blur on the image
imagestring($image, 50, 25, 8, 'Gaussian Blur Text image', 0x00ff00);
$gaussian = array(
array(1.0, 2.0, 1.0),
array(2.0, 4.0, 2.0),
array(1.0, 2.0, 1.0)
);
imageconvolution($image, $gaussian, 16, 0);
// Rewrites the text for comparison
imagestring($image, 15, 20, 18, 'Gaussian Blur Text image', 0x00ff00);
header('Content-Type: image/png');
imagepng($image, null, 9);
?>
|
[
{
"code": null,
"e": 1206,
"s": 1062,
"text": "imageconvolution() is an inbuilt function in PHP that is used to apply a 3×3 convolution matrix, using the coefficient and offset in the image."
},
{
"code": null,
"e": 1262,
"s": 1206,
"text": "bool imageconvolution ( $image, $matrix, $div, $offset)"
},
{
"code": null,
"e": 1340,
"s": 1262,
"text": "imageconvolution() takes four parameters: $image, $matrix, $div, and $offset."
},
{
"code": null,
"e": 1472,
"s": 1340,
"text": "$image − This parameter is used to create the size of the image by using an image creation function such as imagecreatetruecolor()."
},
{
"code": null,
"e": 1604,
"s": 1472,
"text": "$image − This parameter is used to create the size of the image by using an image creation function such as imagecreatetruecolor()."
},
{
"code": null,
"e": 1672,
"s": 1604,
"text": "$matrix − This parameter contains an array of 3×3 matrix of floats."
},
{
"code": null,
"e": 1740,
"s": 1672,
"text": "$matrix − This parameter contains an array of 3×3 matrix of floats."
},
{
"code": null,
"e": 1777,
"s": 1740,
"text": "$div − It is used for normalization."
},
{
"code": null,
"e": 1814,
"s": 1777,
"text": "$div − It is used for normalization."
},
{
"code": null,
"e": 1872,
"s": 1814,
"text": "$offset − This parameter is used to set the color offset."
},
{
"code": null,
"e": 1930,
"s": 1872,
"text": "$offset − This parameter is used to set the color offset."
},
{
"code": null,
"e": 1995,
"s": 1930,
"text": "imageconvolution() returns True on success and False on failure."
},
{
"code": null,
"e": 2482,
"s": 1995,
"text": "<?php\n // load the PNG image by using imagecreatefrompng function.\n $image = imagecreatefrompng('C:\\xampp\\htdocs\\Images\\img59.png');\n \n // Applied the 3X3 array matrix\n $matrix = array(\n array(2, 0, 0),\n array(0, -1, 0),\n array(0, 0, -1)\n );\n // imageconvolution function to modify image elements\n imageconvolution($image, $matrix, 1, 127);\n\n // show the output image in the browser\n header('Content-Type: image/png');\n imagepng($image, null, 9);\n?>"
},
{
"code": null,
"e": 2539,
"s": 2482,
"text": "Input PNG image before using imageconvolution() function"
},
{
"code": null,
"e": 2596,
"s": 2539,
"text": "Output PNG image after using imageconvolution() function"
},
{
"code": null,
"e": 3127,
"s": 2596,
"text": "<?php\n $image = imagecreatetruecolor(700, 300);\n \n // Writes the text and apply a gaussian blur on the image\n imagestring($image, 50, 25, 8, 'Gaussian Blur Text image', 0x00ff00);\n $gaussian = array(\n array(1.0, 2.0, 1.0),\n array(2.0, 4.0, 2.0),\n array(1.0, 2.0, 1.0)\n );\n imageconvolution($image, $gaussian, 16, 0);\n\n // Rewrites the text for comparison\n imagestring($image, 15, 20, 18, 'Gaussian Blur Text image', 0x00ff00);\n header('Content-Type: image/png');\n imagepng($image, null, 9);\n?>"
}
] |
ThreadPoolExecutor Class
|
java.util.concurrent.ThreadPoolExecutor is an ExecutorService to execute each submitted task using one of possibly several pooled threads, normally configured using Executors factory methods. It also provides various utility methods to check current threads statistics and control them.
protected void afterExecute(Runnable r, Throwable t)
Method invoked upon completion of execution of the given Runnable.
void allowCoreThreadTimeOut(boolean value)
Sets the policy governing whether core threads may time out and terminate if no tasks arrive within the keep-alive time, being replaced if needed when new tasks arrive.
boolean allowsCoreThreadTimeOut()
Returns true if this pool allows core threads to time out and terminate if no tasks arrive within the keepAlive time, being replaced if needed when new tasks arrive.
boolean awaitTermination(long timeout, TimeUnit unit)
Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.
protected void beforeExecute(Thread t, Runnable r)
Method invoked prior to executing the given Runnable in the given thread.
void execute(Runnable command)
Executes the given task sometime in the future.
protected void finalize()
Invokes shutdown when this executor is no longer referenced and it has no threads.
int getActiveCount()
Returns the approximate number of threads that are actively executing tasks.
long getCompletedTaskCount()
Returns the approximate total number of tasks that have completed execution.
int getCorePoolSize()
Returns the core number of threads.
long getKeepAliveTime(TimeUnit unit)
Returns the thread keep-alive time, which is the amount of time that threads in excess of the core pool size may remain idle before being terminated.
int getLargestPoolSize()
Returns the largest number of threads that have ever simultaneously been in the pool.
int getMaximumPoolSize()
Returns the maximum allowed number of threads.
int getPoolSize()
Returns the current number of threads in the pool.
BlockingQueue getQueue()
Returns the task queue used by this executor.
RejectedExecutionHandler getRejectedExecutionHandler()
Returns the current handler for unexecutable tasks.
long getTaskCount()
Returns the approximate total number of tasks that have ever been scheduled for execution.
ThreadFactory getThreadFactory()
Returns the thread factory used to create new threads.
boolean isShutdown()
Returns true if this executor has been shut down.
boolean isTerminated()
Returns true if all tasks have completed following shut down.
boolean isTerminating()
Returns true if this executor is in the process of terminating after shutdown() or shutdownNow() but has not completely terminated.
int prestartAllCoreThreads()
Starts all core threads, causing them to idly wait for work.
boolean prestartCoreThread()
Starts a core thread, causing it to idly wait for work.
void purge()
Tries to remove from the work queue all Future tasks that have been cancelled.
boolean remove(Runnable task)
Removes this task from the executor's internal queue if it is present, thus causing it not to be run if it has not already started.
void setCorePoolSize(int corePoolSize)
Sets the core number of threads.
void setKeepAliveTime(long time, TimeUnit unit)
Sets the time limit for which threads may remain idle before being terminated.
void setMaximumPoolSize(int maximumPoolSize)
Sets the maximum allowed number of threads.
void setRejectedExecutionHandler(RejectedExecutionHandler handler)
Sets a new handler for unexecutable tasks.
void setThreadFactory(ThreadFactory threadFactory)
Sets the thread factory used to create new threads.
void shutdown()
Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.
List<Runnable> shutdownNow()
Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.
protected void terminated()
Method invoked when the Executor has terminated.
String toString()
Returns a string identifying this pool, as well as its state, including indications of run state and estimated worker and task counts.
The following TestThread program shows usage of ThreadPoolExecutor interface in thread based environment.
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class TestThread {
public static void main(final String[] arguments) throws InterruptedException {
ThreadPoolExecutor executor = (ThreadPoolExecutor)Executors.newCachedThreadPool();
//Stats before tasks execution
System.out.println("Largest executions: "
+ executor.getLargestPoolSize());
System.out.println("Maximum allowed threads: "
+ executor.getMaximumPoolSize());
System.out.println("Current threads in pool: "
+ executor.getPoolSize());
System.out.println("Currently executing threads: "
+ executor.getActiveCount());
System.out.println("Total number of threads(ever scheduled): "
+ executor.getTaskCount());
executor.submit(new Task());
executor.submit(new Task());
//Stats after tasks execution
System.out.println("Core threads: " + executor.getCorePoolSize());
System.out.println("Largest executions: "
+ executor.getLargestPoolSize());
System.out.println("Maximum allowed threads: "
+ executor.getMaximumPoolSize());
System.out.println("Current threads in pool: "
+ executor.getPoolSize());
System.out.println("Currently executing threads: "
+ executor.getActiveCount());
System.out.println("Total number of threads(ever scheduled): "
+ executor.getTaskCount());
executor.shutdown();
}
static class Task implements Runnable {
public void run() {
try {
Long duration = (long) (Math.random() * 5);
System.out.println("Running Task! Thread Name: " +
Thread.currentThread().getName());
TimeUnit.SECONDS.sleep(duration);
System.out.println("Task Completed! Thread Name: " +
Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
This will produce the following result.
Largest executions: 0
Maximum allowed threads: 2147483647
Current threads in pool: 0
Currently executing threads: 0
Total number of threads(ever scheduled): 0
Core threads: 0
Largest executions: 2
Maximum allowed threads: 2147483647
Current threads in pool: 2
Currently executing threads: 2
Total number of threads(ever scheduled): 2
Running Task! Thread Name: pool-1-thread-2
Running Task! Thread Name: pool-1-thread-1
Task Completed! Thread Name: pool-1-thread-1
Task Completed! Thread Name: pool-1-thread-2
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2944,
"s": 2657,
"text": "java.util.concurrent.ThreadPoolExecutor is an ExecutorService to execute each submitted task using one of possibly several pooled threads, normally configured using Executors factory methods. It also provides various utility methods to check current threads statistics and control them."
},
{
"code": null,
"e": 2997,
"s": 2944,
"text": "protected void afterExecute(Runnable r, Throwable t)"
},
{
"code": null,
"e": 3064,
"s": 2997,
"text": "Method invoked upon completion of execution of the given Runnable."
},
{
"code": null,
"e": 3107,
"s": 3064,
"text": "void allowCoreThreadTimeOut(boolean value)"
},
{
"code": null,
"e": 3276,
"s": 3107,
"text": "Sets the policy governing whether core threads may time out and terminate if no tasks arrive within the keep-alive time, being replaced if needed when new tasks arrive."
},
{
"code": null,
"e": 3310,
"s": 3276,
"text": "boolean\tallowsCoreThreadTimeOut()"
},
{
"code": null,
"e": 3476,
"s": 3310,
"text": "Returns true if this pool allows core threads to time out and terminate if no tasks arrive within the keepAlive time, being replaced if needed when new tasks arrive."
},
{
"code": null,
"e": 3530,
"s": 3476,
"text": "boolean\tawaitTermination(long timeout, TimeUnit unit)"
},
{
"code": null,
"e": 3690,
"s": 3530,
"text": "Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first."
},
{
"code": null,
"e": 3741,
"s": 3690,
"text": "protected void beforeExecute(Thread t, Runnable r)"
},
{
"code": null,
"e": 3815,
"s": 3741,
"text": "Method invoked prior to executing the given Runnable in the given thread."
},
{
"code": null,
"e": 3846,
"s": 3815,
"text": "void execute(Runnable command)"
},
{
"code": null,
"e": 3894,
"s": 3846,
"text": "Executes the given task sometime in the future."
},
{
"code": null,
"e": 3920,
"s": 3894,
"text": "protected void finalize()"
},
{
"code": null,
"e": 4003,
"s": 3920,
"text": "Invokes shutdown when this executor is no longer referenced and it has no threads."
},
{
"code": null,
"e": 4024,
"s": 4003,
"text": "int\tgetActiveCount()"
},
{
"code": null,
"e": 4101,
"s": 4024,
"text": "Returns the approximate number of threads that are actively executing tasks."
},
{
"code": null,
"e": 4130,
"s": 4101,
"text": "long getCompletedTaskCount()"
},
{
"code": null,
"e": 4207,
"s": 4130,
"text": "Returns the approximate total number of tasks that have completed execution."
},
{
"code": null,
"e": 4229,
"s": 4207,
"text": "int\tgetCorePoolSize()"
},
{
"code": null,
"e": 4265,
"s": 4229,
"text": "Returns the core number of threads."
},
{
"code": null,
"e": 4302,
"s": 4265,
"text": "long\tgetKeepAliveTime(TimeUnit unit)"
},
{
"code": null,
"e": 4452,
"s": 4302,
"text": "Returns the thread keep-alive time, which is the amount of time that threads in excess of the core pool size may remain idle before being terminated."
},
{
"code": null,
"e": 4477,
"s": 4452,
"text": "int\tgetLargestPoolSize()"
},
{
"code": null,
"e": 4563,
"s": 4477,
"text": "Returns the largest number of threads that have ever simultaneously been in the pool."
},
{
"code": null,
"e": 4588,
"s": 4563,
"text": "int\tgetMaximumPoolSize()"
},
{
"code": null,
"e": 4635,
"s": 4588,
"text": "Returns the maximum allowed number of threads."
},
{
"code": null,
"e": 4653,
"s": 4635,
"text": "int\tgetPoolSize()"
},
{
"code": null,
"e": 4704,
"s": 4653,
"text": "Returns the current number of threads in the pool."
},
{
"code": null,
"e": 4729,
"s": 4704,
"text": "BlockingQueue getQueue()"
},
{
"code": null,
"e": 4775,
"s": 4729,
"text": "Returns the task queue used by this executor."
},
{
"code": null,
"e": 4830,
"s": 4775,
"text": "RejectedExecutionHandler getRejectedExecutionHandler()"
},
{
"code": null,
"e": 4882,
"s": 4830,
"text": "Returns the current handler for unexecutable tasks."
},
{
"code": null,
"e": 4902,
"s": 4882,
"text": "long getTaskCount()"
},
{
"code": null,
"e": 4993,
"s": 4902,
"text": "Returns the approximate total number of tasks that have ever been scheduled for execution."
},
{
"code": null,
"e": 5026,
"s": 4993,
"text": "ThreadFactory getThreadFactory()"
},
{
"code": null,
"e": 5081,
"s": 5026,
"text": "Returns the thread factory used to create new threads."
},
{
"code": null,
"e": 5102,
"s": 5081,
"text": "boolean\tisShutdown()"
},
{
"code": null,
"e": 5152,
"s": 5102,
"text": "Returns true if this executor has been shut down."
},
{
"code": null,
"e": 5175,
"s": 5152,
"text": "boolean\tisTerminated()"
},
{
"code": null,
"e": 5237,
"s": 5175,
"text": "Returns true if all tasks have completed following shut down."
},
{
"code": null,
"e": 5261,
"s": 5237,
"text": "boolean\tisTerminating()"
},
{
"code": null,
"e": 5393,
"s": 5261,
"text": "Returns true if this executor is in the process of terminating after shutdown() or shutdownNow() but has not completely terminated."
},
{
"code": null,
"e": 5422,
"s": 5393,
"text": "int\tprestartAllCoreThreads()"
},
{
"code": null,
"e": 5483,
"s": 5422,
"text": "Starts all core threads, causing them to idly wait for work."
},
{
"code": null,
"e": 5512,
"s": 5483,
"text": "boolean\tprestartCoreThread()"
},
{
"code": null,
"e": 5568,
"s": 5512,
"text": "Starts a core thread, causing it to idly wait for work."
},
{
"code": null,
"e": 5581,
"s": 5568,
"text": "void purge()"
},
{
"code": null,
"e": 5660,
"s": 5581,
"text": "Tries to remove from the work queue all Future tasks that have been cancelled."
},
{
"code": null,
"e": 5690,
"s": 5660,
"text": "boolean\tremove(Runnable task)"
},
{
"code": null,
"e": 5822,
"s": 5690,
"text": "Removes this task from the executor's internal queue if it is present, thus causing it not to be run if it has not already started."
},
{
"code": null,
"e": 5861,
"s": 5822,
"text": "void setCorePoolSize(int corePoolSize)"
},
{
"code": null,
"e": 5894,
"s": 5861,
"text": "Sets the core number of threads."
},
{
"code": null,
"e": 5942,
"s": 5894,
"text": "void setKeepAliveTime(long time, TimeUnit unit)"
},
{
"code": null,
"e": 6021,
"s": 5942,
"text": "Sets the time limit for which threads may remain idle before being terminated."
},
{
"code": null,
"e": 6066,
"s": 6021,
"text": "void setMaximumPoolSize(int maximumPoolSize)"
},
{
"code": null,
"e": 6110,
"s": 6066,
"text": "Sets the maximum allowed number of threads."
},
{
"code": null,
"e": 6177,
"s": 6110,
"text": "void setRejectedExecutionHandler(RejectedExecutionHandler handler)"
},
{
"code": null,
"e": 6220,
"s": 6177,
"text": "Sets a new handler for unexecutable tasks."
},
{
"code": null,
"e": 6271,
"s": 6220,
"text": "void setThreadFactory(ThreadFactory threadFactory)"
},
{
"code": null,
"e": 6323,
"s": 6271,
"text": "Sets the thread factory used to create new threads."
},
{
"code": null,
"e": 6339,
"s": 6323,
"text": "void shutdown()"
},
{
"code": null,
"e": 6454,
"s": 6339,
"text": "Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted."
},
{
"code": null,
"e": 6483,
"s": 6454,
"text": "List<Runnable> shutdownNow()"
},
{
"code": null,
"e": 6631,
"s": 6483,
"text": "Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution."
},
{
"code": null,
"e": 6659,
"s": 6631,
"text": "protected void terminated()"
},
{
"code": null,
"e": 6708,
"s": 6659,
"text": "Method invoked when the Executor has terminated."
},
{
"code": null,
"e": 6726,
"s": 6708,
"text": "String toString()"
},
{
"code": null,
"e": 6861,
"s": 6726,
"text": "Returns a string identifying this pool, as well as its state, including indications of run state and estimated worker and task counts."
},
{
"code": null,
"e": 6967,
"s": 6861,
"text": "The following TestThread program shows usage of ThreadPoolExecutor interface in thread based environment."
},
{
"code": null,
"e": 9023,
"s": 6967,
"text": "import java.util.concurrent.Executors;\nimport java.util.concurrent.ThreadPoolExecutor;\nimport java.util.concurrent.TimeUnit;\n\npublic class TestThread {\n\t\n public static void main(final String[] arguments) throws InterruptedException {\n ThreadPoolExecutor executor = (ThreadPoolExecutor)Executors.newCachedThreadPool();\n\n //Stats before tasks execution\n System.out.println(\"Largest executions: \"\n + executor.getLargestPoolSize());\n System.out.println(\"Maximum allowed threads: \"\n + executor.getMaximumPoolSize());\n System.out.println(\"Current threads in pool: \"\n + executor.getPoolSize());\n System.out.println(\"Currently executing threads: \"\n + executor.getActiveCount());\n System.out.println(\"Total number of threads(ever scheduled): \"\n + executor.getTaskCount());\n\n executor.submit(new Task());\n executor.submit(new Task());\n\n //Stats after tasks execution\n System.out.println(\"Core threads: \" + executor.getCorePoolSize());\n System.out.println(\"Largest executions: \"\n + executor.getLargestPoolSize());\n System.out.println(\"Maximum allowed threads: \"\n + executor.getMaximumPoolSize());\n System.out.println(\"Current threads in pool: \"\n + executor.getPoolSize());\n System.out.println(\"Currently executing threads: \"\n + executor.getActiveCount());\n System.out.println(\"Total number of threads(ever scheduled): \"\n + executor.getTaskCount());\n\n executor.shutdown();\n } \n\n static class Task implements Runnable {\n\n public void run() {\n\n try {\n Long duration = (long) (Math.random() * 5);\n System.out.println(\"Running Task! Thread Name: \" +\n Thread.currentThread().getName());\n TimeUnit.SECONDS.sleep(duration);\n System.out.println(\"Task Completed! Thread Name: \" +\n Thread.currentThread().getName());\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n }\n}"
},
{
"code": null,
"e": 9063,
"s": 9023,
"text": "This will produce the following result."
},
{
"code": null,
"e": 9574,
"s": 9063,
"text": "Largest executions: 0\nMaximum allowed threads: 2147483647\nCurrent threads in pool: 0\nCurrently executing threads: 0\nTotal number of threads(ever scheduled): 0\nCore threads: 0\nLargest executions: 2\nMaximum allowed threads: 2147483647\nCurrent threads in pool: 2\nCurrently executing threads: 2\nTotal number of threads(ever scheduled): 2\nRunning Task! Thread Name: pool-1-thread-2\nRunning Task! Thread Name: pool-1-thread-1\nTask Completed! Thread Name: pool-1-thread-1\nTask Completed! Thread Name: pool-1-thread-2\n"
},
{
"code": null,
"e": 9607,
"s": 9574,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 9623,
"s": 9607,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 9656,
"s": 9623,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 9672,
"s": 9656,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 9707,
"s": 9672,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 9721,
"s": 9707,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 9755,
"s": 9721,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 9769,
"s": 9755,
"text": " Tushar Kale"
},
{
"code": null,
"e": 9806,
"s": 9769,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 9821,
"s": 9806,
"text": " Monica Mittal"
},
{
"code": null,
"e": 9854,
"s": 9821,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 9873,
"s": 9854,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 9880,
"s": 9873,
"text": " Print"
},
{
"code": null,
"e": 9891,
"s": 9880,
"text": " Add Notes"
}
] |
SymPy - Symbolic Computation
|
Symbolic computation refers to development of algorithms for manipulating mathematical expressions and other mathematical objects. Symbolic computation integrates mathematics with computer science to solve mathematical expressions using mathematical symbols. A Computer Algebra System (CAS) such as SymPy evaluates algebraic expressions exactly (not approximately) using the same symbols that are used in traditional manual method. For example, we calculate square root of a number using Python's math module as given below −
>>> import math
>>> print (math.sqrt(25), math.sqrt(7))
The output for the above code snippet is as follows −
5.0 2.6457513110645907
As you can see, square root of 7 is calculated approximately. But in SymPy square roots of numbers that are not perfect squares are left unevaluated by default as given below −
>>> import sympy
>>> print (sympy.sqrt(7))
The output for the above code snippet is as follows −
sqrt(7)
It is possible to simplify and show result of expression symbolically with the code snippet below −
>>> import math
>>> print (math.sqrt(12))
The output for the above code snippet is as follows −
3.4641016151377544
You need to use the below code snippet to execute the same using sympy −
##sympy output
>>> print (sympy.sqrt(12))
And the output for that is as follows −
2*sqrt(3)
SymPy code, when run in Jupyter notebook, makes use of MathJax library to render mathematical symbols in LatEx form. It is shown in the below code snippet −
>>> from sympy import *
>>> x=Symbol ('x')
>>> expr = integrate(x**x, x)
>>> expr
On executing the above command in python shell, following output will be generated −
Integral(x**x, x)
Which is equivalent to
∫xxdx
The square root of a non-perfect square can be represented by Latex as follows using traditional symbol −
>>> from sympy import *
>>> x=7
>>> sqrt(x)
The output for the above code snippet is as follows −
7
A symbolic computation system such as SymPy does all sorts of computations (such as derivatives, integrals, and limits, solve equations, work with matrices) symbolically. SymPy package has different modules that support plotting, printing (like LATEX), physics, statistics, combinatorics, number theory, geometry, logic, etc.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2545,
"s": 2019,
"text": "Symbolic computation refers to development of algorithms for manipulating mathematical expressions and other mathematical objects. Symbolic computation integrates mathematics with computer science to solve mathematical expressions using mathematical symbols. A Computer Algebra System (CAS) such as SymPy evaluates algebraic expressions exactly (not approximately) using the same symbols that are used in traditional manual method. For example, we calculate square root of a number using Python's math module as given below −"
},
{
"code": null,
"e": 2603,
"s": 2545,
"text": ">>> import math \n>>> print (math.sqrt(25), math.sqrt(7))\n"
},
{
"code": null,
"e": 2657,
"s": 2603,
"text": "The output for the above code snippet is as follows −"
},
{
"code": null,
"e": 2680,
"s": 2657,
"text": "5.0 2.6457513110645907"
},
{
"code": null,
"e": 2857,
"s": 2680,
"text": "As you can see, square root of 7 is calculated approximately. But in SymPy square roots of numbers that are not perfect squares are left unevaluated by default as given below −"
},
{
"code": null,
"e": 2902,
"s": 2857,
"text": ">>> import sympy \n>>> print (sympy.sqrt(7))\n"
},
{
"code": null,
"e": 2956,
"s": 2902,
"text": "The output for the above code snippet is as follows −"
},
{
"code": null,
"e": 2964,
"s": 2956,
"text": "sqrt(7)"
},
{
"code": null,
"e": 3064,
"s": 2964,
"text": "It is possible to simplify and show result of expression symbolically with the code snippet below −"
},
{
"code": null,
"e": 3107,
"s": 3064,
"text": ">>> import math\n>>> print (math.sqrt(12))\n"
},
{
"code": null,
"e": 3161,
"s": 3107,
"text": "The output for the above code snippet is as follows −"
},
{
"code": null,
"e": 3180,
"s": 3161,
"text": "3.4641016151377544"
},
{
"code": null,
"e": 3253,
"s": 3180,
"text": "You need to use the below code snippet to execute the same using sympy −"
},
{
"code": null,
"e": 3297,
"s": 3253,
"text": "##sympy output \n>>> print (sympy.sqrt(12))\n"
},
{
"code": null,
"e": 3337,
"s": 3297,
"text": "And the output for that is as follows −"
},
{
"code": null,
"e": 3347,
"s": 3337,
"text": "2*sqrt(3)"
},
{
"code": null,
"e": 3504,
"s": 3347,
"text": "SymPy code, when run in Jupyter notebook, makes use of MathJax library to render mathematical symbols in LatEx form. It is shown in the below code snippet −"
},
{
"code": null,
"e": 3590,
"s": 3504,
"text": ">>> from sympy import * \n>>> x=Symbol ('x') \n>>> expr = integrate(x**x, x) \n>>> expr\n"
},
{
"code": null,
"e": 3675,
"s": 3590,
"text": "On executing the above command in python shell, following output will be generated −"
},
{
"code": null,
"e": 3694,
"s": 3675,
"text": "Integral(x**x, x)\n"
},
{
"code": null,
"e": 3717,
"s": 3694,
"text": "Which is equivalent to"
},
{
"code": null,
"e": 3723,
"s": 3717,
"text": "∫xxdx"
},
{
"code": null,
"e": 3829,
"s": 3723,
"text": "The square root of a non-perfect square can be represented by Latex as follows using traditional symbol −"
},
{
"code": null,
"e": 3876,
"s": 3829,
"text": ">>> from sympy import * \n>>> x=7 \n>>> sqrt(x)\n"
},
{
"code": null,
"e": 3930,
"s": 3876,
"text": "The output for the above code snippet is as follows −"
},
{
"code": null,
"e": 3932,
"s": 3930,
"text": "7"
},
{
"code": null,
"e": 4258,
"s": 3932,
"text": "A symbolic computation system such as SymPy does all sorts of computations (such as derivatives, integrals, and limits, solve equations, work with matrices) symbolically. SymPy package has different modules that support plotting, printing (like LATEX), physics, statistics, combinatorics, number theory, geometry, logic, etc."
},
{
"code": null,
"e": 4265,
"s": 4258,
"text": " Print"
},
{
"code": null,
"e": 4276,
"s": 4265,
"text": " Add Notes"
}
] |
Count rows based on condition in Pyspark Dataframe - GeeksforGeeks
|
29 Jun, 2021
In this article, we will discuss how to count rows based on conditions in Pyspark dataframe.
For this, we are going to use these methods:
Using where() function.
Using filter() function.
Creating Dataframe for demonstration:
Python3
# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of students data data =[["1","sravan","vignan"], ["2","ojaswi","vvit"], ["3","rohith","vvit"], ["4","sridevi","vignan"], ["1","sravan","vignan"], ["5","gnanesh","iit"]] # specify column namescolumns = ['ID','NAME','college'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data,columns) print('Actual data in dataframe')dataframe.show()
Output:
Note: If we want to get all row count we can use count() function
Syntax: dataframe.count()
Where, dataframe is the pyspark input dataframe
Example: Python program to get all row count
Python3
print('Total rows in dataframe')dataframe.count()
Output:
Total rows in dataframe
6
where(): This clause is used to check the condition and give the results
Syntax: dataframe.where(condition)
Where the condition is the dataframe condition
Example 1: Condition to get rows in dataframe where ID =1
Python3
# condition to get rows in dataframe # where ID =1print('Total rows in dataframe where\ID = 1 with where clause')print(dataframe.where(dataframe.ID == '1').count()) print('They are ')dataframe.where(dataframe.ID == '1').show()
Output:
Example 2: Condition to get rows in dataframe with multiple conditions.
Python3
# condition to get rows in dataframe# where ID not equal to 1print('Total rows in dataframe where\ID except 1 with where clause') print(dataframe.where(dataframe.ID != '1').count()) # condition to get rows in dataframe# where college is equal to vignanprint('Total rows in dataframe where\college is vignan with where clause')print(dataframe.where(dataframe.college == 'vignan').count()) # condition to get rows in dataframe# where id greater than 2print('Total rows in dataframe where ID greater\than 2 with where clause')print(dataframe.where(dataframe.ID > 2).count())
Output:
Total rows in dataframe where ID except 1 with where clause
4
Total rows in dataframe where college is vignan with where clause
3
Total rows in dataframe where ID greater than 2 with where clause
3
Example 3: Python program for multiple conditions
Python3
# condition to get rows in dataframe# where ID not equal to 1 and name is srideviprint('Total rows in dataframe where ID \not equal to 1 and name is sridevi')print(dataframe.where((dataframe.ID != '1') & (dataframe.NAME == 'sridevi') ).count()) # condition to get rows in dataframe# where college is equal to vignan or iitprint('Total rows in dataframe where college is\vignan or iit with where clause')print(dataframe.where((dataframe.college == 'vignan') | (dataframe.college == 'iit')).count())
Output:
Total rows in dataframe where ID not equal to 1 and name is sridevi
1
Total rows in dataframe where college is vignan or iit with where clause
4
filter(): This clause is used to check the condition and give the results, Both are similar
Syntax: dataframe.filter(condition)
Example 1: Python program to get rows where id = 1
Python3
# condition to get rows in# dataframe where ID =1print('Total rows in dataframe where\ID = 1 with filter clause')print(dataframe.filter(dataframe.ID == '1').count()) print('They are ')dataframe.filter(dataframe.ID == '1').show()
Output:
Example 2: Python program for multiple conditions
Python3
# condition to get rows in dataframe# where ID not equal to 1 and name is srideviprint('Total rows in dataframe where ID not\equal to 1 and name is sridevi')print(dataframe.filter((dataframe.ID != '1') & (dataframe.NAME == 'sridevi')).count()) # condition to get rows in dataframe# where college is equal to vignan or iitprint('Total rows in dataframe where college\is vignan or iit with filter clause')print(dataframe.filter((dataframe.college == 'vignan') | (dataframe.college == 'iit')).count())
Output:
Total rows in dataframe where ID not equal to 1 and name is sridevi
1
Total rows in dataframe where college is vignan or iit with filter clause
4
Picked
Python-Pyspark
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Defaultdict in Python
Selecting rows in pandas DataFrame based on conditions
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n29 Jun, 2021"
},
{
"code": null,
"e": 24385,
"s": 24292,
"text": "In this article, we will discuss how to count rows based on conditions in Pyspark dataframe."
},
{
"code": null,
"e": 24430,
"s": 24385,
"text": "For this, we are going to use these methods:"
},
{
"code": null,
"e": 24454,
"s": 24430,
"text": "Using where() function."
},
{
"code": null,
"e": 24479,
"s": 24454,
"text": "Using filter() function."
},
{
"code": null,
"e": 24517,
"s": 24479,
"text": "Creating Dataframe for demonstration:"
},
{
"code": null,
"e": 24525,
"s": 24517,
"text": "Python3"
},
{
"code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of students data data =[[\"1\",\"sravan\",\"vignan\"], [\"2\",\"ojaswi\",\"vvit\"], [\"3\",\"rohith\",\"vvit\"], [\"4\",\"sridevi\",\"vignan\"], [\"1\",\"sravan\",\"vignan\"], [\"5\",\"gnanesh\",\"iit\"]] # specify column namescolumns = ['ID','NAME','college'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data,columns) print('Actual data in dataframe')dataframe.show()",
"e": 25165,
"s": 24525,
"text": null
},
{
"code": null,
"e": 25173,
"s": 25165,
"text": "Output:"
},
{
"code": null,
"e": 25239,
"s": 25173,
"text": "Note: If we want to get all row count we can use count() function"
},
{
"code": null,
"e": 25265,
"s": 25239,
"text": "Syntax: dataframe.count()"
},
{
"code": null,
"e": 25313,
"s": 25265,
"text": "Where, dataframe is the pyspark input dataframe"
},
{
"code": null,
"e": 25358,
"s": 25313,
"text": "Example: Python program to get all row count"
},
{
"code": null,
"e": 25366,
"s": 25358,
"text": "Python3"
},
{
"code": "print('Total rows in dataframe')dataframe.count()",
"e": 25416,
"s": 25366,
"text": null
},
{
"code": null,
"e": 25424,
"s": 25416,
"text": "Output:"
},
{
"code": null,
"e": 25450,
"s": 25424,
"text": "Total rows in dataframe\n6"
},
{
"code": null,
"e": 25523,
"s": 25450,
"text": "where(): This clause is used to check the condition and give the results"
},
{
"code": null,
"e": 25558,
"s": 25523,
"text": "Syntax: dataframe.where(condition)"
},
{
"code": null,
"e": 25605,
"s": 25558,
"text": "Where the condition is the dataframe condition"
},
{
"code": null,
"e": 25663,
"s": 25605,
"text": "Example 1: Condition to get rows in dataframe where ID =1"
},
{
"code": null,
"e": 25671,
"s": 25663,
"text": "Python3"
},
{
"code": "# condition to get rows in dataframe # where ID =1print('Total rows in dataframe where\\ID = 1 with where clause')print(dataframe.where(dataframe.ID == '1').count()) print('They are ')dataframe.where(dataframe.ID == '1').show()",
"e": 25900,
"s": 25671,
"text": null
},
{
"code": null,
"e": 25908,
"s": 25900,
"text": "Output:"
},
{
"code": null,
"e": 25980,
"s": 25908,
"text": "Example 2: Condition to get rows in dataframe with multiple conditions."
},
{
"code": null,
"e": 25988,
"s": 25980,
"text": "Python3"
},
{
"code": "# condition to get rows in dataframe# where ID not equal to 1print('Total rows in dataframe where\\ID except 1 with where clause') print(dataframe.where(dataframe.ID != '1').count()) # condition to get rows in dataframe# where college is equal to vignanprint('Total rows in dataframe where\\college is vignan with where clause')print(dataframe.where(dataframe.college == 'vignan').count()) # condition to get rows in dataframe# where id greater than 2print('Total rows in dataframe where ID greater\\than 2 with where clause')print(dataframe.where(dataframe.ID > 2).count())",
"e": 26565,
"s": 25988,
"text": null
},
{
"code": null,
"e": 26573,
"s": 26565,
"text": "Output:"
},
{
"code": null,
"e": 26633,
"s": 26573,
"text": "Total rows in dataframe where ID except 1 with where clause"
},
{
"code": null,
"e": 26635,
"s": 26633,
"text": "4"
},
{
"code": null,
"e": 26701,
"s": 26635,
"text": "Total rows in dataframe where college is vignan with where clause"
},
{
"code": null,
"e": 26703,
"s": 26701,
"text": "3"
},
{
"code": null,
"e": 26769,
"s": 26703,
"text": "Total rows in dataframe where ID greater than 2 with where clause"
},
{
"code": null,
"e": 26771,
"s": 26769,
"text": "3"
},
{
"code": null,
"e": 26821,
"s": 26771,
"text": "Example 3: Python program for multiple conditions"
},
{
"code": null,
"e": 26829,
"s": 26821,
"text": "Python3"
},
{
"code": "# condition to get rows in dataframe# where ID not equal to 1 and name is srideviprint('Total rows in dataframe where ID \\not equal to 1 and name is sridevi')print(dataframe.where((dataframe.ID != '1') & (dataframe.NAME == 'sridevi') ).count()) # condition to get rows in dataframe# where college is equal to vignan or iitprint('Total rows in dataframe where college is\\vignan or iit with where clause')print(dataframe.where((dataframe.college == 'vignan') | (dataframe.college == 'iit')).count())",
"e": 27390,
"s": 26829,
"text": null
},
{
"code": null,
"e": 27398,
"s": 27390,
"text": "Output:"
},
{
"code": null,
"e": 27466,
"s": 27398,
"text": "Total rows in dataframe where ID not equal to 1 and name is sridevi"
},
{
"code": null,
"e": 27468,
"s": 27466,
"text": "1"
},
{
"code": null,
"e": 27541,
"s": 27468,
"text": "Total rows in dataframe where college is vignan or iit with where clause"
},
{
"code": null,
"e": 27543,
"s": 27541,
"text": "4"
},
{
"code": null,
"e": 27635,
"s": 27543,
"text": "filter(): This clause is used to check the condition and give the results, Both are similar"
},
{
"code": null,
"e": 27671,
"s": 27635,
"text": "Syntax: dataframe.filter(condition)"
},
{
"code": null,
"e": 27722,
"s": 27671,
"text": "Example 1: Python program to get rows where id = 1"
},
{
"code": null,
"e": 27730,
"s": 27722,
"text": "Python3"
},
{
"code": "# condition to get rows in# dataframe where ID =1print('Total rows in dataframe where\\ID = 1 with filter clause')print(dataframe.filter(dataframe.ID == '1').count()) print('They are ')dataframe.filter(dataframe.ID == '1').show()",
"e": 27961,
"s": 27730,
"text": null
},
{
"code": null,
"e": 27969,
"s": 27961,
"text": "Output:"
},
{
"code": null,
"e": 28019,
"s": 27969,
"text": "Example 2: Python program for multiple conditions"
},
{
"code": null,
"e": 28027,
"s": 28019,
"text": "Python3"
},
{
"code": "# condition to get rows in dataframe# where ID not equal to 1 and name is srideviprint('Total rows in dataframe where ID not\\equal to 1 and name is sridevi')print(dataframe.filter((dataframe.ID != '1') & (dataframe.NAME == 'sridevi')).count()) # condition to get rows in dataframe# where college is equal to vignan or iitprint('Total rows in dataframe where college\\is vignan or iit with filter clause')print(dataframe.filter((dataframe.college == 'vignan') | (dataframe.college == 'iit')).count())",
"e": 28571,
"s": 28027,
"text": null
},
{
"code": null,
"e": 28579,
"s": 28571,
"text": "Output:"
},
{
"code": null,
"e": 28647,
"s": 28579,
"text": "Total rows in dataframe where ID not equal to 1 and name is sridevi"
},
{
"code": null,
"e": 28649,
"s": 28647,
"text": "1"
},
{
"code": null,
"e": 28723,
"s": 28649,
"text": "Total rows in dataframe where college is vignan or iit with filter clause"
},
{
"code": null,
"e": 28725,
"s": 28723,
"text": "4"
},
{
"code": null,
"e": 28732,
"s": 28725,
"text": "Picked"
},
{
"code": null,
"e": 28747,
"s": 28732,
"text": "Python-Pyspark"
},
{
"code": null,
"e": 28754,
"s": 28747,
"text": "Python"
},
{
"code": null,
"e": 28852,
"s": 28754,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28884,
"s": 28852,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28926,
"s": 28884,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28982,
"s": 28926,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 29024,
"s": 28982,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 29046,
"s": 29024,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 29101,
"s": 29046,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 29132,
"s": 29101,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 29171,
"s": 29132,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 29200,
"s": 29171,
"text": "Create a directory in Python"
}
] |
PYGLET – Accessing Label Text Color Property - GeeksforGeeks
|
16 Jan, 2022
In this article we will see how we can access the label text color property in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc. A window is a “heavyweight” object occupying operating system resources. Windows may appear as floating regions or can be set to fill an entire screen (fullscreen). In order to show text or message we use html label object. A label is a graphical control element which displays text on a form. It is usually a static control; having no interactivity. By default the text color of the label is of white color although we can change this any time by accessing the color property.We can create a window and label with the help of commands given below
# creating window
window = pyglet.window.Window(width, height, title)
# creating a label
label = pyglet.text.Label(text, font_name, font_size, x, y)
In order to create window we use color attribute with the label objectSyntax : label.colorArgument : It takes no argumentReturn : It returns tuple of having four values varying from 0-255
Below is the implementation
Python3
# importing pyglet moduleimport pygletimport pyglet.window.key # width of windowwidth = 500 # height of windowheight = 500 # caption i.e title of the windowtitle = "Geeksforgeeks" # creating a windowwindow = pyglet.window.Window(width, height, title) # texttext = "Welcome to GeeksforGeeks" # creating a label with font = times roman# font size = 36# aligning it to the centrelabel = pyglet.text.Label(text, font_name ='Times New Roman', font_size = 28, x = 20, y = window.height//2, ) # accessing color property of the label# setting new colorlabel.color = (100, 255, 100, 255) # on draw event@window.eventdef on_draw(): # clearing the window window.clear() # drawing the label on the window label.draw() # key press event @window.eventdef on_key_press(symbol, modifier): # key "C" get press if symbol == pyglet.window.key.C: # closing the window window.close() # image for iconimg = image = pyglet.resource.image("logo.png") # setting image as iconwindow.set_icon(img) # start running the applicationpyglet.app.run()
Output :
adnanirshad158
Python-gui
Python-Pyglet
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25555,
"s": 25527,
"text": "\n16 Jan, 2022"
},
{
"code": null,
"e": 26326,
"s": 25555,
"text": "In this article we will see how we can access the label text color property in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc. A window is a “heavyweight” object occupying operating system resources. Windows may appear as floating regions or can be set to fill an entire screen (fullscreen). In order to show text or message we use html label object. A label is a graphical control element which displays text on a form. It is usually a static control; having no interactivity. By default the text color of the label is of white color although we can change this any time by accessing the color property.We can create a window and label with the help of commands given below "
},
{
"code": null,
"e": 26476,
"s": 26326,
"text": "# creating window\nwindow = pyglet.window.Window(width, height, title)\n\n# creating a label\nlabel = pyglet.text.Label(text, font_name, font_size, x, y)"
},
{
"code": null,
"e": 26668,
"s": 26478,
"text": "In order to create window we use color attribute with the label objectSyntax : label.colorArgument : It takes no argumentReturn : It returns tuple of having four values varying from 0-255 "
},
{
"code": null,
"e": 26698,
"s": 26668,
"text": "Below is the implementation "
},
{
"code": null,
"e": 26706,
"s": 26698,
"text": "Python3"
},
{
"code": "# importing pyglet moduleimport pygletimport pyglet.window.key # width of windowwidth = 500 # height of windowheight = 500 # caption i.e title of the windowtitle = \"Geeksforgeeks\" # creating a windowwindow = pyglet.window.Window(width, height, title) # texttext = \"Welcome to GeeksforGeeks\" # creating a label with font = times roman# font size = 36# aligning it to the centrelabel = pyglet.text.Label(text, font_name ='Times New Roman', font_size = 28, x = 20, y = window.height//2, ) # accessing color property of the label# setting new colorlabel.color = (100, 255, 100, 255) # on draw event@window.eventdef on_draw(): # clearing the window window.clear() # drawing the label on the window label.draw() # key press event @window.eventdef on_key_press(symbol, modifier): # key \"C\" get press if symbol == pyglet.window.key.C: # closing the window window.close() # image for iconimg = image = pyglet.resource.image(\"logo.png\") # setting image as iconwindow.set_icon(img) # start running the applicationpyglet.app.run()",
"e": 27884,
"s": 26706,
"text": null
},
{
"code": null,
"e": 27895,
"s": 27884,
"text": "Output : "
},
{
"code": null,
"e": 27912,
"s": 27897,
"text": "adnanirshad158"
},
{
"code": null,
"e": 27923,
"s": 27912,
"text": "Python-gui"
},
{
"code": null,
"e": 27937,
"s": 27923,
"text": "Python-Pyglet"
},
{
"code": null,
"e": 27944,
"s": 27937,
"text": "Python"
},
{
"code": null,
"e": 28042,
"s": 27944,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28074,
"s": 28042,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28116,
"s": 28074,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28158,
"s": 28116,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28214,
"s": 28158,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28241,
"s": 28214,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28272,
"s": 28241,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28311,
"s": 28272,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28340,
"s": 28311,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 28362,
"s": 28340,
"text": "Defaultdict in Python"
}
] |
How to setup firewall in Linux? - GeeksforGeeks
|
12 Feb, 2019
What is a Firewall?Firewall is a network security system that filters and controls the traffic on a predetermined set of rules. This is an intermediary system between the device and the internet.
NOTE:- If you already know about the working of Firewall in Linux and just want to know the Commands, then please go the end of the tutorial.
How the Firewall of Linux works :Most of the Linux distro’s ship with default firewall tools that can be used to configure them. We will be using “IPTables” the default tool provided in Linux to establish a firewall. Iptables is used to set up, maintain and inspect the tables of the IPv4 and IPv6 packet filter rules in the Linux Kernel.
Note:- All the command below need sudo privileges.
Chains are a set of rules defined for a particular task.
We have three chains(set of rules) which are used to process the traffic:-
INPUT ChainsOUTPUT ChainsFORWARD Chains
INPUT Chains
OUTPUT Chains
FORWARD Chains
1. INPUT ChainsAny traffic coming from the internet(network) towards your local machine has to go through the input chains. That means they have to go through all the rules that have been set up in the Input chain.
2. OUTPUT ChainsAny traffic going from your local machine to the internet needs to go through the output chains.
3. FORWARD ChainAny traffic which is coming from the external network and going to another network needs to go through the forward chain. It is used when two or more computers are connected and we want to send data between them.
There are three actions which the iptables can perform on the traffic
ACCEPTDROPREJECT
ACCEPT
DROP
REJECT
1. ACCEPTWhen traffic passes the rules in its specified chain, then the iptable accepts the traffic.That means it opens up the gate and allows the person to go inside the kingdom of Thanos.
2. DROPWhen the traffic is unable to pass the rules in its specified chain, the iptable blocks that traffic.That means the firewall is closed.
3. REJECTThis type of action is similar to the drop action but it sends a message to the sender of the traffic stating that the data transfer has failed.As a general rule, use REJECT when you want the other end to know the port is unreachable’ use DROP for connections to hosts you don’t want people to see.
NOTE:-You need to keep in mind a simple rule here:-The Rules you set in the iptables are checked from the topmost rules to the bottom. Whenever a packet passes any of the top rules, it is allowed to pass the firewall. The lower rules are not checked. So be careful while setting up rules.
To list the rules of the current iptables:-
sudo iptables -L
The Output would be:-
As you can see, we have three chains (INPUT, FORWARD, OUTPUT). We can also see column headers, but they are no actual rules. This is because most of the Linux come with no predefined rules.
Let see what each column mean.
Target:-This defines what action needs to be done on the packet (ACCEPT,DROP,etc..)
prot:-This defines the protocol (TCP,IP) of the packet.
source:-This tells the source address of the packet.
destination:-This defines the destination address of the packet
If you ever want to clear/flush out all the existing rules. Run the following command:-
sudo iptables -F
This will reset the iptables.
sudo iptables -P Chain_name Action_to_be_taken
As you can see in the above picture, the default policy of each of the chain is ACCEPT.
For eg:–If you see the forward chain, you will see “Chain FORWARD (policy ACCEPT)”.This means your computer allows any traffic to be forwarded to another computer.
In order to change the policy of forwarding to drop:-
sudo iptables -P FORWARD DROP
The above command will stop any traffic to be forwarded through your system. That means no other system can your system as an intermediary to pass the data.
We’ll now start building our firewall policies.We’ll first work on the input chain since that is where the incoming traffic will be sent through.Syntax:-
sudo iptables -A/-I chain_name -s source_ip -j action_to_take
We’ll take an example to understand the topic.
Let’s assume we want to block the traffic coming from an IP address 192.168.1.3. The following command can be used:-
sudo iptables -A INPUT -s 192.168.1.3 -j DROP
This may look complicated, but most of it will make sense when we go over the components:--A INPUT :-
The flag -A is used to append a rule to the end of a chain. This part of the command tells the iptable that we want to add a rule to the end of the INPUT chain.
-I INPUT:-In this flag the rules are added to the top of the chain.
-s 192.168.1.3:-The flag -s is used to specify the source of the packet. This tells the iptable to look for the packets coming from the source 192.168.1.3
-j DROPThis specifies what the iptable should do with the packet.
In short, the above command adds a rule to the INPUT chain which says, if any packet arrives whose source address is 192.168.1.3 then drop that packet, that means do not allow the packet reach the computer.
Once you execute the above command you can see the changes by using the command:-
sudo iptables -L
The Output would be:-
If you want to add rules to specific ports of your network,then the following commands can be used.Syntax:-
sudo iptables -A/-I chain_name -s source_ip -p protocol_name --dport port_number -j Action_to_take
-p protocol_name:-This option is used to match the packets that follow the protocol protocol_name.
-dport port_number:This is option is available only if you give the -p protocol_name option. It specifies to look for the packets that are going to the port “port_number”.
Example:-Let’s say we want to keep our SSH port open (we will assume in this guide that the default SSH port is 22) from the 192.168.1.3 network we blocked in the above case. That is we only want to allow those packets coming from 192.168.1.3 and which wants to go to the port 22.
What do we do:-Let’s try the below command:-
sudo iptables -A INPUT -s 192.168.1.3 -p tcp --dport 22 -j ACCEPT
The above command says looks for the packets originating from the IP address 192.168.1.3, having a TCP protocol and who wants to deliver something at the port 22 of my computer. If you find those packets then Accept them.
The Output for the command is:-
But, There is a problem with the above command. It actually does not allow the packets. Can You Guess What it is?HINT:- It is related to the way the rules are accessed.
Remember as we discussed earlier, The Rules you set in the iptables are checked from the top to the bottom. Whenever a packet is processed to one of the top rules, it is not checked with the lower rules.
Okay! Here’s The Answer:-In our case, The packet was checked with the topmost rule, which says that the iptable must drop any packet coming from 192.168.1.3. Hence once the packet got accessed through this rule, it did not go to the next rule which allowed packets to the port 22. Therefore it failed.
What could be done?The easiest answer is, Add the rule to the top of the chain. All you need to do is change the -A option to -I option. ( In our scenario we first delete the rule [refer the next section] added in the above section and then add the below rule again )
The command to do that is:-
sudo iptables -I INPUT -s 192.168.1.3 -p tcp --dport 22 -j ACCEPT
Now check the iptable configuration using -L command. The output would be:-Therefore, any packet coming from 192.168.1.3 is first checked if it is going to the port 22 if it isn’t then itis run through the next rule in the chain. Else it is allowed to pass the firewall.
Now that you have understood how to block and accept the incoming traffic let’s see how to delete rules:-
Syntax:-
sudo iptables -D chain_name rule_number
Example:-If we want to delete the rule which accepts the traffic to port 22 and which we have added in the previous section, then:-
sudo iptables -D INPUT 1
Remember the rule number starts from 1The Output :-
This part is unnecessary if you are implementing it on a personal computer which is not a server, but ifyou are implementing a firewall on a server, then there are high chances that your server might get corrupted andyou might lose all your data. So, it’s always better to save your configurations.
There are a lot of ways to do this, but the easiest way I find is with iptables-persistent package. You can download the package from Ubuntu’s default repositories:
sudo apt-get update
sudo apt-get install iptables-persistent
Once the installation is complete, you can save your configuration using the command:-
sudo invoke-rc.d iptables-persistent save
Well, this is the end of the tutorial.Let’s just brief up all the commands we have learned so far:-
sudo iptables -L
sudo iptables -P Chain_name Action_to_be_taken
Example:-
sudo iptables -P FORWARD DROP
sudo iptables -F
sudo iptables -A
sudo iptables -I
sudo iptables -A/-I chain_name -s source_ip -j action_to_take
Example:-
iptables -A INPUT -s 192.168.1.3 -j ACCEPT
sudo iptables -A/-I chain_name -s source_ip -j action_to_take
Example:-
iptables -A INPUT -s 192.168.1.3 -j DROP
sudo iptables -A/-I chain_name -s source_ip -p protocol_name --dport port_number -j Action_to_take
Example:-
sudo iptables -I INPUT -s 192.168.1.3 -p tcp --dport 22 -j ACCEPT
sudo iptables -D chain_name rule_number
Example:-
sudo iptables -D INPUT 1
sudo invoke-rc.d iptables-persistent save
And that’s the end of the tutorial. We have seen all the necessary commands that you need to implement a firewall on your local machine. There are various other actions we can make our firewall do, but it is impossible to cover all of those in a single article. So, I will be writing a few more articles explaining all the commands. Until then, Keep experimenting!!
Naveen_Naidu
Hasanul Islam
Picked
Computer Networks
GBlog
Linux-Unix
TechTips
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Differences between TCP and UDP
TCP Server-Client implementation in C
Differences between IPv4 and IPv6
Types of Network Topology
Socket Programming in Python
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
DSA Sheet by Love Babbar
Socket Programming in C/C++
GET and POST requests using Python
Must Do Coding Questions for Product Based Companies
|
[
{
"code": null,
"e": 25783,
"s": 25755,
"text": "\n12 Feb, 2019"
},
{
"code": null,
"e": 25979,
"s": 25783,
"text": "What is a Firewall?Firewall is a network security system that filters and controls the traffic on a predetermined set of rules. This is an intermediary system between the device and the internet."
},
{
"code": null,
"e": 26121,
"s": 25979,
"text": "NOTE:- If you already know about the working of Firewall in Linux and just want to know the Commands, then please go the end of the tutorial."
},
{
"code": null,
"e": 26460,
"s": 26121,
"text": "How the Firewall of Linux works :Most of the Linux distro’s ship with default firewall tools that can be used to configure them. We will be using “IPTables” the default tool provided in Linux to establish a firewall. Iptables is used to set up, maintain and inspect the tables of the IPv4 and IPv6 packet filter rules in the Linux Kernel."
},
{
"code": null,
"e": 26511,
"s": 26460,
"text": "Note:- All the command below need sudo privileges."
},
{
"code": null,
"e": 26568,
"s": 26511,
"text": "Chains are a set of rules defined for a particular task."
},
{
"code": null,
"e": 26643,
"s": 26568,
"text": "We have three chains(set of rules) which are used to process the traffic:-"
},
{
"code": null,
"e": 26683,
"s": 26643,
"text": "INPUT ChainsOUTPUT ChainsFORWARD Chains"
},
{
"code": null,
"e": 26696,
"s": 26683,
"text": "INPUT Chains"
},
{
"code": null,
"e": 26710,
"s": 26696,
"text": "OUTPUT Chains"
},
{
"code": null,
"e": 26725,
"s": 26710,
"text": "FORWARD Chains"
},
{
"code": null,
"e": 26940,
"s": 26725,
"text": "1. INPUT ChainsAny traffic coming from the internet(network) towards your local machine has to go through the input chains. That means they have to go through all the rules that have been set up in the Input chain."
},
{
"code": null,
"e": 27053,
"s": 26940,
"text": "2. OUTPUT ChainsAny traffic going from your local machine to the internet needs to go through the output chains."
},
{
"code": null,
"e": 27282,
"s": 27053,
"text": "3. FORWARD ChainAny traffic which is coming from the external network and going to another network needs to go through the forward chain. It is used when two or more computers are connected and we want to send data between them."
},
{
"code": null,
"e": 27352,
"s": 27282,
"text": "There are three actions which the iptables can perform on the traffic"
},
{
"code": null,
"e": 27369,
"s": 27352,
"text": "ACCEPTDROPREJECT"
},
{
"code": null,
"e": 27376,
"s": 27369,
"text": "ACCEPT"
},
{
"code": null,
"e": 27381,
"s": 27376,
"text": "DROP"
},
{
"code": null,
"e": 27388,
"s": 27381,
"text": "REJECT"
},
{
"code": null,
"e": 27578,
"s": 27388,
"text": "1. ACCEPTWhen traffic passes the rules in its specified chain, then the iptable accepts the traffic.That means it opens up the gate and allows the person to go inside the kingdom of Thanos."
},
{
"code": null,
"e": 27721,
"s": 27578,
"text": "2. DROPWhen the traffic is unable to pass the rules in its specified chain, the iptable blocks that traffic.That means the firewall is closed."
},
{
"code": null,
"e": 28029,
"s": 27721,
"text": "3. REJECTThis type of action is similar to the drop action but it sends a message to the sender of the traffic stating that the data transfer has failed.As a general rule, use REJECT when you want the other end to know the port is unreachable’ use DROP for connections to hosts you don’t want people to see."
},
{
"code": null,
"e": 28318,
"s": 28029,
"text": "NOTE:-You need to keep in mind a simple rule here:-The Rules you set in the iptables are checked from the topmost rules to the bottom. Whenever a packet passes any of the top rules, it is allowed to pass the firewall. The lower rules are not checked. So be careful while setting up rules."
},
{
"code": null,
"e": 28362,
"s": 28318,
"text": "To list the rules of the current iptables:-"
},
{
"code": null,
"e": 28379,
"s": 28362,
"text": "sudo iptables -L"
},
{
"code": null,
"e": 28401,
"s": 28379,
"text": "The Output would be:-"
},
{
"code": null,
"e": 28591,
"s": 28401,
"text": "As you can see, we have three chains (INPUT, FORWARD, OUTPUT). We can also see column headers, but they are no actual rules. This is because most of the Linux come with no predefined rules."
},
{
"code": null,
"e": 28622,
"s": 28591,
"text": "Let see what each column mean."
},
{
"code": null,
"e": 28706,
"s": 28622,
"text": "Target:-This defines what action needs to be done on the packet (ACCEPT,DROP,etc..)"
},
{
"code": null,
"e": 28762,
"s": 28706,
"text": "prot:-This defines the protocol (TCP,IP) of the packet."
},
{
"code": null,
"e": 28815,
"s": 28762,
"text": "source:-This tells the source address of the packet."
},
{
"code": null,
"e": 28879,
"s": 28815,
"text": "destination:-This defines the destination address of the packet"
},
{
"code": null,
"e": 28967,
"s": 28879,
"text": "If you ever want to clear/flush out all the existing rules. Run the following command:-"
},
{
"code": null,
"e": 28984,
"s": 28967,
"text": "sudo iptables -F"
},
{
"code": null,
"e": 29014,
"s": 28984,
"text": "This will reset the iptables."
},
{
"code": null,
"e": 29062,
"s": 29014,
"text": "sudo iptables -P Chain_name Action_to_be_taken\n"
},
{
"code": null,
"e": 29150,
"s": 29062,
"text": "As you can see in the above picture, the default policy of each of the chain is ACCEPT."
},
{
"code": null,
"e": 29314,
"s": 29150,
"text": "For eg:–If you see the forward chain, you will see “Chain FORWARD (policy ACCEPT)”.This means your computer allows any traffic to be forwarded to another computer."
},
{
"code": null,
"e": 29368,
"s": 29314,
"text": "In order to change the policy of forwarding to drop:-"
},
{
"code": null,
"e": 29398,
"s": 29368,
"text": "sudo iptables -P FORWARD DROP"
},
{
"code": null,
"e": 29555,
"s": 29398,
"text": "The above command will stop any traffic to be forwarded through your system. That means no other system can your system as an intermediary to pass the data."
},
{
"code": null,
"e": 29709,
"s": 29555,
"text": "We’ll now start building our firewall policies.We’ll first work on the input chain since that is where the incoming traffic will be sent through.Syntax:-"
},
{
"code": null,
"e": 29771,
"s": 29709,
"text": "sudo iptables -A/-I chain_name -s source_ip -j action_to_take"
},
{
"code": null,
"e": 29818,
"s": 29771,
"text": "We’ll take an example to understand the topic."
},
{
"code": null,
"e": 29935,
"s": 29818,
"text": "Let’s assume we want to block the traffic coming from an IP address 192.168.1.3. The following command can be used:-"
},
{
"code": null,
"e": 29981,
"s": 29935,
"text": "sudo iptables -A INPUT -s 192.168.1.3 -j DROP"
},
{
"code": null,
"e": 30083,
"s": 29981,
"text": "This may look complicated, but most of it will make sense when we go over the components:--A INPUT :-"
},
{
"code": null,
"e": 30244,
"s": 30083,
"text": "The flag -A is used to append a rule to the end of a chain. This part of the command tells the iptable that we want to add a rule to the end of the INPUT chain."
},
{
"code": null,
"e": 30312,
"s": 30244,
"text": "-I INPUT:-In this flag the rules are added to the top of the chain."
},
{
"code": null,
"e": 30467,
"s": 30312,
"text": "-s 192.168.1.3:-The flag -s is used to specify the source of the packet. This tells the iptable to look for the packets coming from the source 192.168.1.3"
},
{
"code": null,
"e": 30533,
"s": 30467,
"text": "-j DROPThis specifies what the iptable should do with the packet."
},
{
"code": null,
"e": 30740,
"s": 30533,
"text": "In short, the above command adds a rule to the INPUT chain which says, if any packet arrives whose source address is 192.168.1.3 then drop that packet, that means do not allow the packet reach the computer."
},
{
"code": null,
"e": 30822,
"s": 30740,
"text": "Once you execute the above command you can see the changes by using the command:-"
},
{
"code": null,
"e": 30839,
"s": 30822,
"text": "sudo iptables -L"
},
{
"code": null,
"e": 30861,
"s": 30839,
"text": "The Output would be:-"
},
{
"code": null,
"e": 30969,
"s": 30861,
"text": "If you want to add rules to specific ports of your network,then the following commands can be used.Syntax:-"
},
{
"code": null,
"e": 31068,
"s": 30969,
"text": "sudo iptables -A/-I chain_name -s source_ip -p protocol_name --dport port_number -j Action_to_take"
},
{
"code": null,
"e": 31167,
"s": 31068,
"text": "-p protocol_name:-This option is used to match the packets that follow the protocol protocol_name."
},
{
"code": null,
"e": 31339,
"s": 31167,
"text": "-dport port_number:This is option is available only if you give the -p protocol_name option. It specifies to look for the packets that are going to the port “port_number”."
},
{
"code": null,
"e": 31620,
"s": 31339,
"text": "Example:-Let’s say we want to keep our SSH port open (we will assume in this guide that the default SSH port is 22) from the 192.168.1.3 network we blocked in the above case. That is we only want to allow those packets coming from 192.168.1.3 and which wants to go to the port 22."
},
{
"code": null,
"e": 31665,
"s": 31620,
"text": "What do we do:-Let’s try the below command:-"
},
{
"code": null,
"e": 31731,
"s": 31665,
"text": "sudo iptables -A INPUT -s 192.168.1.3 -p tcp --dport 22 -j ACCEPT"
},
{
"code": null,
"e": 31953,
"s": 31731,
"text": "The above command says looks for the packets originating from the IP address 192.168.1.3, having a TCP protocol and who wants to deliver something at the port 22 of my computer. If you find those packets then Accept them."
},
{
"code": null,
"e": 31985,
"s": 31953,
"text": "The Output for the command is:-"
},
{
"code": null,
"e": 32154,
"s": 31985,
"text": "But, There is a problem with the above command. It actually does not allow the packets. Can You Guess What it is?HINT:- It is related to the way the rules are accessed."
},
{
"code": null,
"e": 32358,
"s": 32154,
"text": "Remember as we discussed earlier, The Rules you set in the iptables are checked from the top to the bottom. Whenever a packet is processed to one of the top rules, it is not checked with the lower rules."
},
{
"code": null,
"e": 32660,
"s": 32358,
"text": "Okay! Here’s The Answer:-In our case, The packet was checked with the topmost rule, which says that the iptable must drop any packet coming from 192.168.1.3. Hence once the packet got accessed through this rule, it did not go to the next rule which allowed packets to the port 22. Therefore it failed."
},
{
"code": null,
"e": 32928,
"s": 32660,
"text": "What could be done?The easiest answer is, Add the rule to the top of the chain. All you need to do is change the -A option to -I option. ( In our scenario we first delete the rule [refer the next section] added in the above section and then add the below rule again )"
},
{
"code": null,
"e": 32956,
"s": 32928,
"text": "The command to do that is:-"
},
{
"code": null,
"e": 33022,
"s": 32956,
"text": "sudo iptables -I INPUT -s 192.168.1.3 -p tcp --dport 22 -j ACCEPT"
},
{
"code": null,
"e": 33293,
"s": 33022,
"text": "Now check the iptable configuration using -L command. The output would be:-Therefore, any packet coming from 192.168.1.3 is first checked if it is going to the port 22 if it isn’t then itis run through the next rule in the chain. Else it is allowed to pass the firewall."
},
{
"code": null,
"e": 33399,
"s": 33293,
"text": "Now that you have understood how to block and accept the incoming traffic let’s see how to delete rules:-"
},
{
"code": null,
"e": 33408,
"s": 33399,
"text": "Syntax:-"
},
{
"code": null,
"e": 33448,
"s": 33408,
"text": "sudo iptables -D chain_name rule_number"
},
{
"code": null,
"e": 33580,
"s": 33448,
"text": "Example:-If we want to delete the rule which accepts the traffic to port 22 and which we have added in the previous section, then:-"
},
{
"code": null,
"e": 33605,
"s": 33580,
"text": "sudo iptables -D INPUT 1"
},
{
"code": null,
"e": 33657,
"s": 33605,
"text": "Remember the rule number starts from 1The Output :-"
},
{
"code": null,
"e": 33956,
"s": 33657,
"text": "This part is unnecessary if you are implementing it on a personal computer which is not a server, but ifyou are implementing a firewall on a server, then there are high chances that your server might get corrupted andyou might lose all your data. So, it’s always better to save your configurations."
},
{
"code": null,
"e": 34121,
"s": 33956,
"text": "There are a lot of ways to do this, but the easiest way I find is with iptables-persistent package. You can download the package from Ubuntu’s default repositories:"
},
{
"code": null,
"e": 34183,
"s": 34121,
"text": "sudo apt-get update\nsudo apt-get install iptables-persistent\n"
},
{
"code": null,
"e": 34270,
"s": 34183,
"text": "Once the installation is complete, you can save your configuration using the command:-"
},
{
"code": null,
"e": 34312,
"s": 34270,
"text": "sudo invoke-rc.d iptables-persistent save"
},
{
"code": null,
"e": 34412,
"s": 34312,
"text": "Well, this is the end of the tutorial.Let’s just brief up all the commands we have learned so far:-"
},
{
"code": null,
"e": 34429,
"s": 34412,
"text": "sudo iptables -L"
},
{
"code": null,
"e": 34476,
"s": 34429,
"text": "sudo iptables -P Chain_name Action_to_be_taken"
},
{
"code": null,
"e": 34486,
"s": 34476,
"text": "Example:-"
},
{
"code": null,
"e": 34516,
"s": 34486,
"text": "sudo iptables -P FORWARD DROP"
},
{
"code": null,
"e": 34533,
"s": 34516,
"text": "sudo iptables -F"
},
{
"code": null,
"e": 34550,
"s": 34533,
"text": "sudo iptables -A"
},
{
"code": null,
"e": 34567,
"s": 34550,
"text": "sudo iptables -I"
},
{
"code": null,
"e": 34629,
"s": 34567,
"text": "sudo iptables -A/-I chain_name -s source_ip -j action_to_take"
},
{
"code": null,
"e": 34639,
"s": 34629,
"text": "Example:-"
},
{
"code": null,
"e": 34682,
"s": 34639,
"text": "iptables -A INPUT -s 192.168.1.3 -j ACCEPT"
},
{
"code": null,
"e": 34744,
"s": 34682,
"text": "sudo iptables -A/-I chain_name -s source_ip -j action_to_take"
},
{
"code": null,
"e": 34754,
"s": 34744,
"text": "Example:-"
},
{
"code": null,
"e": 34795,
"s": 34754,
"text": "iptables -A INPUT -s 192.168.1.3 -j DROP"
},
{
"code": null,
"e": 34894,
"s": 34795,
"text": "sudo iptables -A/-I chain_name -s source_ip -p protocol_name --dport port_number -j Action_to_take"
},
{
"code": null,
"e": 34904,
"s": 34894,
"text": "Example:-"
},
{
"code": null,
"e": 34970,
"s": 34904,
"text": "sudo iptables -I INPUT -s 192.168.1.3 -p tcp --dport 22 -j ACCEPT"
},
{
"code": null,
"e": 35010,
"s": 34970,
"text": "sudo iptables -D chain_name rule_number"
},
{
"code": null,
"e": 35020,
"s": 35010,
"text": "Example:-"
},
{
"code": null,
"e": 35045,
"s": 35020,
"text": "sudo iptables -D INPUT 1"
},
{
"code": null,
"e": 35087,
"s": 35045,
"text": "sudo invoke-rc.d iptables-persistent save"
},
{
"code": null,
"e": 35453,
"s": 35087,
"text": "And that’s the end of the tutorial. We have seen all the necessary commands that you need to implement a firewall on your local machine. There are various other actions we can make our firewall do, but it is impossible to cover all of those in a single article. So, I will be writing a few more articles explaining all the commands. Until then, Keep experimenting!!"
},
{
"code": null,
"e": 35466,
"s": 35453,
"text": "Naveen_Naidu"
},
{
"code": null,
"e": 35480,
"s": 35466,
"text": "Hasanul Islam"
},
{
"code": null,
"e": 35487,
"s": 35480,
"text": "Picked"
},
{
"code": null,
"e": 35505,
"s": 35487,
"text": "Computer Networks"
},
{
"code": null,
"e": 35511,
"s": 35505,
"text": "GBlog"
},
{
"code": null,
"e": 35522,
"s": 35511,
"text": "Linux-Unix"
},
{
"code": null,
"e": 35531,
"s": 35522,
"text": "TechTips"
},
{
"code": null,
"e": 35549,
"s": 35531,
"text": "Computer Networks"
},
{
"code": null,
"e": 35647,
"s": 35549,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35679,
"s": 35647,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 35717,
"s": 35679,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 35751,
"s": 35717,
"text": "Differences between IPv4 and IPv6"
},
{
"code": null,
"e": 35777,
"s": 35751,
"text": "Types of Network Topology"
},
{
"code": null,
"e": 35806,
"s": 35777,
"text": "Socket Programming in Python"
},
{
"code": null,
"e": 35880,
"s": 35806,
"text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..."
},
{
"code": null,
"e": 35905,
"s": 35880,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 35933,
"s": 35905,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 35968,
"s": 35933,
"text": "GET and POST requests using Python"
}
] |
Accessing Grandparent’s member in Java using super - GeeksforGeeks
|
05 Feb, 2021
Directly accessing Grandparent’s member in Java:
Predict the output of the following Java program.
Java
// filename Main.javaclass Grandparent { public void Print() { System.out.println("Grandparent's Print()"); }} class Parent extends Grandparent { public void Print() { System.out.println("Parent's Print()"); }} class Child extends Parent { public void Print() { // Trying to access Grandparent's Print() super.super.Print(); System.out.println("Child's Print()"); }} public class Main { public static void main(String[] args) { Child c = new Child(); c.Print(); }}
Output:
prog.java:20: error: <identifier> expected
super.super.Print();
^
prog.java:20: error: not a statement
super.super.Print();
There is an error at the line “super.super.print();”. In Java, a class cannot directly access the grandparent’s members. It is allowed in C++ though. In C++, we can use scope resolution operator (::) to access any ancestor’s member in the inheritance hierarchy. In Java, we can access grandparent’s members only through the parent class.
For example, the following program compiles and runs fine.
Java
// filename Main.javaclass Grandparent { public void Print() { System.out.println("Grandparent's Print()"); }} class Parent extends Grandparent { public void Print() { super.Print(); System.out.println("Parent's Print()"); }} class Child extends Parent { public void Print() { super.Print(); System.out.println("Child's Print()"); }} public class Main { public static void main(String[] args) { Child c = new Child(); c.Print(); }}
Grandparent's Print()
Parent's Print()
Child's Print()
Why doesn’t java allow accessing grandparent’s methods?
It violates encapsulation. You shouldn’t be able to bypass the parent class’s behavior. It makes sense to sometimes be able to bypass your own class’s behavior (particularly from within the same method) but not your parent’s.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
guruism056
java-inheritance
Java-Object Oriented
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java
|
[
{
"code": null,
"e": 25797,
"s": 25769,
"text": "\n05 Feb, 2021"
},
{
"code": null,
"e": 25846,
"s": 25797,
"text": "Directly accessing Grandparent’s member in Java:"
},
{
"code": null,
"e": 25896,
"s": 25846,
"text": "Predict the output of the following Java program."
},
{
"code": null,
"e": 25901,
"s": 25896,
"text": "Java"
},
{
"code": "// filename Main.javaclass Grandparent { public void Print() { System.out.println(\"Grandparent's Print()\"); }} class Parent extends Grandparent { public void Print() { System.out.println(\"Parent's Print()\"); }} class Child extends Parent { public void Print() { // Trying to access Grandparent's Print() super.super.Print(); System.out.println(\"Child's Print()\"); }} public class Main { public static void main(String[] args) { Child c = new Child(); c.Print(); }}",
"e": 26451,
"s": 25901,
"text": null
},
{
"code": null,
"e": 26459,
"s": 26451,
"text": "Output:"
},
{
"code": null,
"e": 26614,
"s": 26459,
"text": "prog.java:20: error: <identifier> expected\n super.super.Print();\n ^\nprog.java:20: error: not a statement\n super.super.Print(); "
},
{
"code": null,
"e": 26953,
"s": 26614,
"text": "There is an error at the line “super.super.print();”. In Java, a class cannot directly access the grandparent’s members. It is allowed in C++ though. In C++, we can use scope resolution operator (::) to access any ancestor’s member in the inheritance hierarchy. In Java, we can access grandparent’s members only through the parent class. "
},
{
"code": null,
"e": 27013,
"s": 26953,
"text": "For example, the following program compiles and runs fine. "
},
{
"code": null,
"e": 27018,
"s": 27013,
"text": "Java"
},
{
"code": "// filename Main.javaclass Grandparent { public void Print() { System.out.println(\"Grandparent's Print()\"); }} class Parent extends Grandparent { public void Print() { super.Print(); System.out.println(\"Parent's Print()\"); }} class Child extends Parent { public void Print() { super.Print(); System.out.println(\"Child's Print()\"); }} public class Main { public static void main(String[] args) { Child c = new Child(); c.Print(); }}",
"e": 27535,
"s": 27018,
"text": null
},
{
"code": null,
"e": 27591,
"s": 27535,
"text": "Grandparent's Print()\nParent's Print()\nChild's Print()\n"
},
{
"code": null,
"e": 27650,
"s": 27593,
"text": "Why doesn’t java allow accessing grandparent’s methods? "
},
{
"code": null,
"e": 27877,
"s": 27650,
"text": "It violates encapsulation. You shouldn’t be able to bypass the parent class’s behavior. It makes sense to sometimes be able to bypass your own class’s behavior (particularly from within the same method) but not your parent’s. "
},
{
"code": null,
"e": 28003,
"s": 27877,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 28014,
"s": 28003,
"text": "guruism056"
},
{
"code": null,
"e": 28031,
"s": 28014,
"text": "java-inheritance"
},
{
"code": null,
"e": 28052,
"s": 28031,
"text": "Java-Object Oriented"
},
{
"code": null,
"e": 28057,
"s": 28052,
"text": "Java"
},
{
"code": null,
"e": 28062,
"s": 28057,
"text": "Java"
},
{
"code": null,
"e": 28160,
"s": 28062,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28190,
"s": 28160,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 28205,
"s": 28190,
"text": "Stream In Java"
},
{
"code": null,
"e": 28224,
"s": 28205,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 28255,
"s": 28224,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 28273,
"s": 28255,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 28305,
"s": 28273,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 28325,
"s": 28305,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 28357,
"s": 28325,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 28381,
"s": 28357,
"text": "Singleton Class in Java"
}
] |
Double Order Traversal of a Binary Tree - GeeksforGeeks
|
11 Oct, 2021
Given a Binary Tree consisting of N nodes, the task is to print its Double Order Traversal.
Double Order Traversal is a tree traversal technique in which every node is traversed twice in the following order:
Visit the Node.
Traverse the Left Subtree.
Visit the Node.
Traverse the Right Subtree.
Examples:
Input:
1
/ \
7 3
/ \ /
4 5 6
Output: 1 7 4 4 7 5 5 1 3 6 6 3
Input:
1
/ \
7 3
/ \ \
4 5 6
Output: 1 7 4 4 7 5 5 1 3 3 6 6
Approach: The idea is to perform Inorder Traversal recursively on the given Binary Tree and print the node value on visiting a vertex and after the recursive call to the left subtree during the traversal.
Follow the steps below to solve the problem:
Start Inorder traversal from the root.
If the current node does not exist, simply return from it.
Otherwise:Print the value of the current node.Recursively traverse the left subtree.Again, print the current node.Recursively traverse the right subtree.
Print the value of the current node.
Recursively traverse the left subtree.
Again, print the current node.
Recursively traverse the right subtree.
Repeat the above steps until all nodes in the tree are visited.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ Program to implement// the above approach#include <iostream>using namespace std; // Node Structurestruct node { char data; struct node *left, *right;}; // Function to create new nodestruct node* newNode(char ch){ // Allocate a new node in memory struct node* Node = new node(); Node->data = ch; Node->left = NULL; Node->right = NULL; return Node;} // Function to print Double Order traversalvoid doubleOrderTraversal(struct node* root){ if (!root) return; // Print Node Value cout << root->data << " "; // Traverse Left Subtree doubleOrderTraversal(root->left); // Print Node Value cout << root->data << " "; // Traverse Right SubTree doubleOrderTraversal(root->right);} // Driver Codeint main(){ struct node* root = newNode('1'); root->left = newNode('7'); root->right = newNode('3'); root->left->left = newNode('4'); root->left->right = newNode('5'); root->right->right = newNode('6'); doubleOrderTraversal(root); return 0;}
// Java program to implement// the above approachclass GFG{ // Node Structurestatic class node{ char data; node left, right;}; // Function to create new nodestatic node newNode(char ch){ // Allocate a new node in memory node n = new node(); n.data = ch; n.left = null; n.right = null; return n;} // Function to print Double Order traversalstatic void doubleOrderTraversal(node root){ if (root == null) return; // Print Node Value System.out.print(root.data + " "); // Traverse Left Subtree doubleOrderTraversal(root.left); // Print Node Value System.out.print(root.data + " "); // Traverse Right SubTree doubleOrderTraversal(root.right);} // Driver Codepublic static void main(String[] args){ node root = newNode('1'); root.left = newNode('7'); root.right = newNode('3'); root.left.left = newNode('4'); root.left.right = newNode('5'); root.right.right = newNode('6'); doubleOrderTraversal(root);}} // This code is contributed by gauravrajput1
# Python3 program to implement# the above approach # Node Structureclass Node: # Initialise new node def __init__(self, ch): self.data = ch self.left = None self.right = None # Function to print Double Order traversaldef doubleOrderTraveersal(root): if not root: return # Print node value print(root.data, end = " ") # Traverse left subtree doubleOrderTraveersal(root.left) # Print node value print(root.data, end = " ") # Traverse right subtree doubleOrderTraveersal(root.right) # Driver codeif __name__ == '__main__': root = Node(1) root.left = Node(7) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.right.right = Node(6) doubleOrderTraveersal(root) # This code is contributed by Shivam Singh
// C# program to implement// the above approachusing System;class GFG{ // Node Structureclass node{ public char data; public node left, right;}; // Function to create new nodestatic node newNode(char ch){ // Allocate a new node in memory node n = new node(); n.data = ch; n.left = null; n.right = null; return n;} // Function to print Double Order traversalstatic void doubleOrderTraversal(node root){ if (root == null) return; // Print Node Value Console.Write(root.data + " "); // Traverse Left Subtree doubleOrderTraversal(root.left); // Print Node Value Console.Write(root.data + " "); // Traverse Right SubTree doubleOrderTraversal(root.right);} // Driver Codepublic static void Main(String[] args){ node root = newNode('1'); root.left = newNode('7'); root.right = newNode('3'); root.left.left = newNode('4'); root.left.right = newNode('5'); root.right.right = newNode('6'); doubleOrderTraversal(root);}} // This code is contributed by gauravrajput1
<script> // Javascript program to implement// the above approach // Node Structureclass node{ constructor() { this.data = 0; this.left = null; this.right = null; }}; // Function to create new nodefunction newNode(ch){ // Allocate a new node in memory var n = new node(); n.data = ch; n.left = null; n.right = null; return n;} // Function to print Double Order traversalfunction doubleOrderTraversal(root){ if (root == null) return; // Print Node Value document.write(root.data + " "); // Traverse Left Subtree doubleOrderTraversal(root.left); // Print Node Value document.write(root.data + " "); // Traverse Right SubTree doubleOrderTraversal(root.right);} // Driver Codevar root = newNode('1');root.left = newNode('7');root.right = newNode('3');root.left.left = newNode('4');root.left.right = newNode('5');root.right.right = newNode('6');doubleOrderTraversal(root); </script>
1 7 4 4 7 5 5 1 3 3 6 6
Time Complexity: O(N) Auxiliary Space: O(1)
SHIVAMSINGH67
GauravRajput1
rutvik_56
gabaa406
ashutoshsinghgeeksforgeeks
Binary Tree
Inorder Traversal
Data Structures
Recursion
Tree
Data Structures
Recursion
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Start Learning DSA?
Introduction to Tree Data Structure
Program to implement Singly Linked List in C++ using class
Hash Functions and list/types of Hash functions
What Should I Learn First: Data Structures or Algorithms?
Write a program to print all permutations of a given string
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Recursion
Program for Tower of Hanoi
Backtracking | Introduction
|
[
{
"code": null,
"e": 26273,
"s": 26245,
"text": "\n11 Oct, 2021"
},
{
"code": null,
"e": 26365,
"s": 26273,
"text": "Given a Binary Tree consisting of N nodes, the task is to print its Double Order Traversal."
},
{
"code": null,
"e": 26482,
"s": 26365,
"text": "Double Order Traversal is a tree traversal technique in which every node is traversed twice in the following order: "
},
{
"code": null,
"e": 26498,
"s": 26482,
"text": "Visit the Node."
},
{
"code": null,
"e": 26525,
"s": 26498,
"text": "Traverse the Left Subtree."
},
{
"code": null,
"e": 26541,
"s": 26525,
"text": "Visit the Node."
},
{
"code": null,
"e": 26569,
"s": 26541,
"text": "Traverse the Right Subtree."
},
{
"code": null,
"e": 26579,
"s": 26569,
"text": "Examples:"
},
{
"code": null,
"e": 26781,
"s": 26579,
"text": "Input:\n 1\n / \\\n 7 3\n / \\ /\n 4 5 6\nOutput: 1 7 4 4 7 5 5 1 3 6 6 3 \n\nInput:\n 1\n / \\\n 7 3\n / \\ \\\n 4 5 6\nOutput: 1 7 4 4 7 5 5 1 3 3 6 6"
},
{
"code": null,
"e": 26987,
"s": 26781,
"text": "Approach: The idea is to perform Inorder Traversal recursively on the given Binary Tree and print the node value on visiting a vertex and after the recursive call to the left subtree during the traversal. "
},
{
"code": null,
"e": 27033,
"s": 26987,
"text": "Follow the steps below to solve the problem: "
},
{
"code": null,
"e": 27073,
"s": 27033,
"text": "Start Inorder traversal from the root. "
},
{
"code": null,
"e": 27132,
"s": 27073,
"text": "If the current node does not exist, simply return from it."
},
{
"code": null,
"e": 27286,
"s": 27132,
"text": "Otherwise:Print the value of the current node.Recursively traverse the left subtree.Again, print the current node.Recursively traverse the right subtree."
},
{
"code": null,
"e": 27323,
"s": 27286,
"text": "Print the value of the current node."
},
{
"code": null,
"e": 27362,
"s": 27323,
"text": "Recursively traverse the left subtree."
},
{
"code": null,
"e": 27393,
"s": 27362,
"text": "Again, print the current node."
},
{
"code": null,
"e": 27433,
"s": 27393,
"text": "Recursively traverse the right subtree."
},
{
"code": null,
"e": 27497,
"s": 27433,
"text": "Repeat the above steps until all nodes in the tree are visited."
},
{
"code": null,
"e": 27549,
"s": 27497,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27553,
"s": 27549,
"text": "C++"
},
{
"code": null,
"e": 27558,
"s": 27553,
"text": "Java"
},
{
"code": null,
"e": 27566,
"s": 27558,
"text": "Python3"
},
{
"code": null,
"e": 27569,
"s": 27566,
"text": "C#"
},
{
"code": null,
"e": 27580,
"s": 27569,
"text": "Javascript"
},
{
"code": "// C++ Program to implement// the above approach#include <iostream>using namespace std; // Node Structurestruct node { char data; struct node *left, *right;}; // Function to create new nodestruct node* newNode(char ch){ // Allocate a new node in memory struct node* Node = new node(); Node->data = ch; Node->left = NULL; Node->right = NULL; return Node;} // Function to print Double Order traversalvoid doubleOrderTraversal(struct node* root){ if (!root) return; // Print Node Value cout << root->data << \" \"; // Traverse Left Subtree doubleOrderTraversal(root->left); // Print Node Value cout << root->data << \" \"; // Traverse Right SubTree doubleOrderTraversal(root->right);} // Driver Codeint main(){ struct node* root = newNode('1'); root->left = newNode('7'); root->right = newNode('3'); root->left->left = newNode('4'); root->left->right = newNode('5'); root->right->right = newNode('6'); doubleOrderTraversal(root); return 0;}",
"e": 28601,
"s": 27580,
"text": null
},
{
"code": "// Java program to implement// the above approachclass GFG{ // Node Structurestatic class node{ char data; node left, right;}; // Function to create new nodestatic node newNode(char ch){ // Allocate a new node in memory node n = new node(); n.data = ch; n.left = null; n.right = null; return n;} // Function to print Double Order traversalstatic void doubleOrderTraversal(node root){ if (root == null) return; // Print Node Value System.out.print(root.data + \" \"); // Traverse Left Subtree doubleOrderTraversal(root.left); // Print Node Value System.out.print(root.data + \" \"); // Traverse Right SubTree doubleOrderTraversal(root.right);} // Driver Codepublic static void main(String[] args){ node root = newNode('1'); root.left = newNode('7'); root.right = newNode('3'); root.left.left = newNode('4'); root.left.right = newNode('5'); root.right.right = newNode('6'); doubleOrderTraversal(root);}} // This code is contributed by gauravrajput1",
"e": 29633,
"s": 28601,
"text": null
},
{
"code": "# Python3 program to implement# the above approach # Node Structureclass Node: # Initialise new node def __init__(self, ch): self.data = ch self.left = None self.right = None # Function to print Double Order traversaldef doubleOrderTraveersal(root): if not root: return # Print node value print(root.data, end = \" \") # Traverse left subtree doubleOrderTraveersal(root.left) # Print node value print(root.data, end = \" \") # Traverse right subtree doubleOrderTraveersal(root.right) # Driver codeif __name__ == '__main__': root = Node(1) root.left = Node(7) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.right.right = Node(6) doubleOrderTraveersal(root) # This code is contributed by Shivam Singh",
"e": 30465,
"s": 29633,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System;class GFG{ // Node Structureclass node{ public char data; public node left, right;}; // Function to create new nodestatic node newNode(char ch){ // Allocate a new node in memory node n = new node(); n.data = ch; n.left = null; n.right = null; return n;} // Function to print Double Order traversalstatic void doubleOrderTraversal(node root){ if (root == null) return; // Print Node Value Console.Write(root.data + \" \"); // Traverse Left Subtree doubleOrderTraversal(root.left); // Print Node Value Console.Write(root.data + \" \"); // Traverse Right SubTree doubleOrderTraversal(root.right);} // Driver Codepublic static void Main(String[] args){ node root = newNode('1'); root.left = newNode('7'); root.right = newNode('3'); root.left.left = newNode('4'); root.left.right = newNode('5'); root.right.right = newNode('6'); doubleOrderTraversal(root);}} // This code is contributed by gauravrajput1",
"e": 31509,
"s": 30465,
"text": null
},
{
"code": "<script> // Javascript program to implement// the above approach // Node Structureclass node{ constructor() { this.data = 0; this.left = null; this.right = null; }}; // Function to create new nodefunction newNode(ch){ // Allocate a new node in memory var n = new node(); n.data = ch; n.left = null; n.right = null; return n;} // Function to print Double Order traversalfunction doubleOrderTraversal(root){ if (root == null) return; // Print Node Value document.write(root.data + \" \"); // Traverse Left Subtree doubleOrderTraversal(root.left); // Print Node Value document.write(root.data + \" \"); // Traverse Right SubTree doubleOrderTraversal(root.right);} // Driver Codevar root = newNode('1');root.left = newNode('7');root.right = newNode('3');root.left.left = newNode('4');root.left.right = newNode('5');root.right.right = newNode('6');doubleOrderTraversal(root); </script>",
"e": 32478,
"s": 31509,
"text": null
},
{
"code": null,
"e": 32502,
"s": 32478,
"text": "1 7 4 4 7 5 5 1 3 3 6 6"
},
{
"code": null,
"e": 32549,
"s": 32504,
"text": "Time Complexity: O(N) Auxiliary Space: O(1) "
},
{
"code": null,
"e": 32563,
"s": 32549,
"text": "SHIVAMSINGH67"
},
{
"code": null,
"e": 32577,
"s": 32563,
"text": "GauravRajput1"
},
{
"code": null,
"e": 32587,
"s": 32577,
"text": "rutvik_56"
},
{
"code": null,
"e": 32596,
"s": 32587,
"text": "gabaa406"
},
{
"code": null,
"e": 32623,
"s": 32596,
"text": "ashutoshsinghgeeksforgeeks"
},
{
"code": null,
"e": 32635,
"s": 32623,
"text": "Binary Tree"
},
{
"code": null,
"e": 32653,
"s": 32635,
"text": "Inorder Traversal"
},
{
"code": null,
"e": 32669,
"s": 32653,
"text": "Data Structures"
},
{
"code": null,
"e": 32679,
"s": 32669,
"text": "Recursion"
},
{
"code": null,
"e": 32684,
"s": 32679,
"text": "Tree"
},
{
"code": null,
"e": 32700,
"s": 32684,
"text": "Data Structures"
},
{
"code": null,
"e": 32710,
"s": 32700,
"text": "Recursion"
},
{
"code": null,
"e": 32715,
"s": 32710,
"text": "Tree"
},
{
"code": null,
"e": 32813,
"s": 32715,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32840,
"s": 32813,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 32876,
"s": 32840,
"text": "Introduction to Tree Data Structure"
},
{
"code": null,
"e": 32935,
"s": 32876,
"text": "Program to implement Singly Linked List in C++ using class"
},
{
"code": null,
"e": 32983,
"s": 32935,
"text": "Hash Functions and list/types of Hash functions"
},
{
"code": null,
"e": 33041,
"s": 32983,
"text": "What Should I Learn First: Data Structures or Algorithms?"
},
{
"code": null,
"e": 33101,
"s": 33041,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 33186,
"s": 33101,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 33196,
"s": 33186,
"text": "Recursion"
},
{
"code": null,
"e": 33223,
"s": 33196,
"text": "Program for Tower of Hanoi"
}
] |
DateTime.GetDateTimeFormats() Method in C# | Set - 1 - GeeksforGeeks
|
30 Jan, 2019
This method is used to convert the value of this instance to all the string representations supported by the standard date and time format specifiers. There are total 4 methods in the overload list of this method:
GetDateTimeFormats()
GetDateTimeFormats(Char)
GetDateTimeFormats(IFormatProvider)
GetDateTimeFormats(Char, IFormatProvider)
This method is used to convert the value of this instance to all the string representations supported by the standard date and time format specifiers.
Syntax: public string[] GetDateTimeFormats ()
Return Value: This method returns a string array where each element is the representation of the value of this instance formatted with one of the standard date and time format specifiers.
Below programs illustrate the use of GetDateTimeFormats() Method:
Example 1:
// C# program to demonstrate the// DateTime.GetDateTimeFormats()// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // creating object of DateTime DateTime date = new DateTime(2010, 1, 1, 4, 0, 15); // getting format in string array // using GetDateTimeFormats() method; string[] value = date.GetDateTimeFormats(); // Print out value in all DateTime // formats using the default culture. foreach(string format in value) Console.WriteLine(format); }}
01/01/2010
2010-01-01
Friday, 01 January 2010
Friday, 01 January 2010 04:00
Friday, 01 January 2010 04:00 AM
Friday, 01 January 2010 4:00
Friday, 01 January 2010 4:00 AM
Friday, 01 January 2010 04:00:15
01/01/2010 04:00
01/01/2010 04:00 AM
01/01/2010 4:00
01/01/2010 4:00 AM
2010-01-01 04:00
2010-01-01 04:00 AM
2010-01-01 4:00
2010-01-01 4:00 AM
01/01/2010 04:00:15
2010-01-01 04:00:15
January 01
January 01
2010-01-01T04:00:15.0000000
2010-01-01T04:00:15.0000000
Fri, 01 Jan 2010 04:00:15 GMT
Fri, 01 Jan 2010 04:00:15 GMT
2010-01-01T04:00:15
04:00
04:00 AM
4:00
4:00 AM
04:00:15
2010-01-01 04:00:15Z
Friday, 01 January 2010 04:00:15
2010 January
2010 January
Example 2:
// C# program to demonstrate the// DateTime.GetDateTimeFormats()// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // creating object of DateTime DateTime date = new DateTime(2019, 1, 30, 9, 49, 15); // getting format in string array // using GetDateTimeFormats() method; string[] value = date.GetDateTimeFormats(); // Print out value in all DateTime // formats using the default culture. for (int i = 1; i <= 6; i++) Console.WriteLine(value[i]); }}
2019-01-30
Wednesday, 30 January 2019
Wednesday, 30 January 2019 09:49
Wednesday, 30 January 2019 09:49 AM
Wednesday, 30 January 2019 9:49
Wednesday, 30 January 2019 9:49 AM
This method is used to convert the value of this instance to all the string representations supported by the specified standard date and time format specifier.
Syntax: public string[] GetDateTimeFormats (char format);Here it takes a standard date and time format string.
Return Value: This method returns a string array where each element is the representation of the value of this instance formatted with the format standard date and time format specifier.
Exceptions: This method will give FormatException if the format is not a valid standard date and time format specifier character.
Below programs illustrate the use of GetDateTimeFormats(Char) Method:
Example 1:
// C# program to demonstrate the// DateTime.GetDateTimeFormats(Char)// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // creating object of DateTime DateTime date = new DateTime(2010, 1, 1, 4, 0, 15); // Get the long date formats using the current // culture. using GetDateTimeFormats() method string[] value = date.GetDateTimeFormats('D'); // Print out value in all DateTime // formats using the default culture. foreach(string format in value) Console.WriteLine(format); } catch (FormatException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }}
Friday, 01 January 2010
Example 2: For FormatException
// C# program to demonstrate the// DateTime.GetDateTimeFormats(Char)// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // creating object of DateTime DateTime date = new DateTime(2010, 1, 1, 4, 0, 15); // Get the date format // using GetDateTimeFormats(Char) method; string[] value = date.GetDateTimeFormats('X'); // Print out value in all DateTime // formats using the default culture. foreach(string format in value) Console.WriteLine(format); } catch (FormatException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }}
Exception Thrown: System.FormatException
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.datetime.getdatetimeformats?view=netframework-4.7.2
CSharp DateTime Struct
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Delegates
C# | Method Overriding
C# | Abstract Classes
Difference between Ref and Out keywords in C#
C# | Class and Object
C# | Constructors
Extension Method in C#
Introduction to .NET Framework
C# | String.IndexOf( ) Method | Set - 1
|
[
{
"code": null,
"e": 25699,
"s": 25671,
"text": "\n30 Jan, 2019"
},
{
"code": null,
"e": 25913,
"s": 25699,
"text": "This method is used to convert the value of this instance to all the string representations supported by the standard date and time format specifiers. There are total 4 methods in the overload list of this method:"
},
{
"code": null,
"e": 25934,
"s": 25913,
"text": "GetDateTimeFormats()"
},
{
"code": null,
"e": 25959,
"s": 25934,
"text": "GetDateTimeFormats(Char)"
},
{
"code": null,
"e": 25995,
"s": 25959,
"text": "GetDateTimeFormats(IFormatProvider)"
},
{
"code": null,
"e": 26037,
"s": 25995,
"text": "GetDateTimeFormats(Char, IFormatProvider)"
},
{
"code": null,
"e": 26188,
"s": 26037,
"text": "This method is used to convert the value of this instance to all the string representations supported by the standard date and time format specifiers."
},
{
"code": null,
"e": 26234,
"s": 26188,
"text": "Syntax: public string[] GetDateTimeFormats ()"
},
{
"code": null,
"e": 26422,
"s": 26234,
"text": "Return Value: This method returns a string array where each element is the representation of the value of this instance formatted with one of the standard date and time format specifiers."
},
{
"code": null,
"e": 26488,
"s": 26422,
"text": "Below programs illustrate the use of GetDateTimeFormats() Method:"
},
{
"code": null,
"e": 26499,
"s": 26488,
"text": "Example 1:"
},
{
"code": "// C# program to demonstrate the// DateTime.GetDateTimeFormats()// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // creating object of DateTime DateTime date = new DateTime(2010, 1, 1, 4, 0, 15); // getting format in string array // using GetDateTimeFormats() method; string[] value = date.GetDateTimeFormats(); // Print out value in all DateTime // formats using the default culture. foreach(string format in value) Console.WriteLine(format); }}",
"e": 27125,
"s": 26499,
"text": null
},
{
"code": null,
"e": 27788,
"s": 27125,
"text": "01/01/2010\n2010-01-01\nFriday, 01 January 2010\nFriday, 01 January 2010 04:00\nFriday, 01 January 2010 04:00 AM\nFriday, 01 January 2010 4:00\nFriday, 01 January 2010 4:00 AM\nFriday, 01 January 2010 04:00:15\n01/01/2010 04:00\n01/01/2010 04:00 AM\n01/01/2010 4:00\n01/01/2010 4:00 AM\n2010-01-01 04:00\n2010-01-01 04:00 AM\n2010-01-01 4:00\n2010-01-01 4:00 AM\n01/01/2010 04:00:15\n2010-01-01 04:00:15\nJanuary 01\nJanuary 01\n2010-01-01T04:00:15.0000000\n2010-01-01T04:00:15.0000000\nFri, 01 Jan 2010 04:00:15 GMT\nFri, 01 Jan 2010 04:00:15 GMT\n2010-01-01T04:00:15\n04:00\n04:00 AM\n4:00\n4:00 AM\n04:00:15\n2010-01-01 04:00:15Z\nFriday, 01 January 2010 04:00:15\n2010 January\n2010 January\n"
},
{
"code": null,
"e": 27799,
"s": 27788,
"text": "Example 2:"
},
{
"code": "// C# program to demonstrate the// DateTime.GetDateTimeFormats()// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // creating object of DateTime DateTime date = new DateTime(2019, 1, 30, 9, 49, 15); // getting format in string array // using GetDateTimeFormats() method; string[] value = date.GetDateTimeFormats(); // Print out value in all DateTime // formats using the default culture. for (int i = 1; i <= 6; i++) Console.WriteLine(value[i]); }}",
"e": 28419,
"s": 27799,
"text": null
},
{
"code": null,
"e": 28594,
"s": 28419,
"text": "2019-01-30\nWednesday, 30 January 2019\nWednesday, 30 January 2019 09:49\nWednesday, 30 January 2019 09:49 AM\nWednesday, 30 January 2019 9:49\nWednesday, 30 January 2019 9:49 AM\n"
},
{
"code": null,
"e": 28754,
"s": 28594,
"text": "This method is used to convert the value of this instance to all the string representations supported by the specified standard date and time format specifier."
},
{
"code": null,
"e": 28865,
"s": 28754,
"text": "Syntax: public string[] GetDateTimeFormats (char format);Here it takes a standard date and time format string."
},
{
"code": null,
"e": 29052,
"s": 28865,
"text": "Return Value: This method returns a string array where each element is the representation of the value of this instance formatted with the format standard date and time format specifier."
},
{
"code": null,
"e": 29182,
"s": 29052,
"text": "Exceptions: This method will give FormatException if the format is not a valid standard date and time format specifier character."
},
{
"code": null,
"e": 29252,
"s": 29182,
"text": "Below programs illustrate the use of GetDateTimeFormats(Char) Method:"
},
{
"code": null,
"e": 29263,
"s": 29252,
"text": "Example 1:"
},
{
"code": "// C# program to demonstrate the// DateTime.GetDateTimeFormats(Char)// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // creating object of DateTime DateTime date = new DateTime(2010, 1, 1, 4, 0, 15); // Get the long date formats using the current // culture. using GetDateTimeFormats() method string[] value = date.GetDateTimeFormats('D'); // Print out value in all DateTime // formats using the default culture. foreach(string format in value) Console.WriteLine(format); } catch (FormatException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}",
"e": 30123,
"s": 29263,
"text": null
},
{
"code": null,
"e": 30148,
"s": 30123,
"text": "Friday, 01 January 2010\n"
},
{
"code": null,
"e": 30179,
"s": 30148,
"text": "Example 2: For FormatException"
},
{
"code": "// C# program to demonstrate the// DateTime.GetDateTimeFormats(Char)// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // creating object of DateTime DateTime date = new DateTime(2010, 1, 1, 4, 0, 15); // Get the date format // using GetDateTimeFormats(Char) method; string[] value = date.GetDateTimeFormats('X'); // Print out value in all DateTime // formats using the default culture. foreach(string format in value) Console.WriteLine(format); } catch (FormatException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}",
"e": 31016,
"s": 30179,
"text": null
},
{
"code": null,
"e": 31058,
"s": 31016,
"text": "Exception Thrown: System.FormatException\n"
},
{
"code": null,
"e": 31069,
"s": 31058,
"text": "Reference:"
},
{
"code": null,
"e": 31172,
"s": 31069,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.datetime.getdatetimeformats?view=netframework-4.7.2"
},
{
"code": null,
"e": 31195,
"s": 31172,
"text": "CSharp DateTime Struct"
},
{
"code": null,
"e": 31209,
"s": 31195,
"text": "CSharp-method"
},
{
"code": null,
"e": 31212,
"s": 31209,
"text": "C#"
},
{
"code": null,
"e": 31310,
"s": 31212,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31338,
"s": 31310,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 31353,
"s": 31338,
"text": "C# | Delegates"
},
{
"code": null,
"e": 31376,
"s": 31353,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 31398,
"s": 31376,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 31444,
"s": 31398,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 31466,
"s": 31444,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 31484,
"s": 31466,
"text": "C# | Constructors"
},
{
"code": null,
"e": 31507,
"s": 31484,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 31538,
"s": 31507,
"text": "Introduction to .NET Framework"
}
] |
Escaping XML Special Characters in Java String - GeeksforGeeks
|
22 Feb, 2021
When we read an XML file and try writing to another XML file it is important for us to take care of special characters in the XML. There are some reserved characters in Java that need to be transformed or escaped to be considered as a string literal. If we don’t escape these special characters then parsers like DOM or SAX parsers in java would consider them as XML tags specifically in the case of < and >. Even if we use XSLT transform these parsers would fail. Hence, we need to escape or transform these special characters before reading them as a String literal in Java.
Special characters in XML
There are 5 mostly used special characters in XML that needs to be escaped when used as a Java String
& — &
< — <
> — >
” — "
‘ — '
These special characters are also referred to as XML Metacharacters. By the process of escaping, we would be replacing these characters with alternate strings to give the literal result of special characters.
Example:
<GeeksForGeeks> Data Structures & Java </GeeksForGeeks>
// is an invalid string in java because '&' is a reserved literal
// in XML that is used to import other XML entity. For converting this
// to a valid String literal we need to & instead of & here.
<GeeksForGeeks> Data Structure & Java </GeeksForGeeks>
// now becomes a valid String.
In Java, we could always write our own functions to escape XML special characters with its equivalent String literals, but we could also use the Java library “StringEscapeUtils” provided by Apache Commons. This library provides us with a common API that does the XML escaping for us.
Code:
Java
// Java program to escape all the five characters// mentioned above using the StringEscapeUtils class import java.io.*;import org.apache.commons.lang.StringEscapeUtils; class GeeksForGeeks { public static void main (String[] args) { System.out.println("Program to escape XML Special Characters !!"); // Escape & character in XML String String unescapedXMLString = "DataStructures & Java"; System.out.println("Unescaped String: " + unescapedXMLString); // using StringEscapeUtils System.out.println("Escaped String: " + StringEscapeUtils.escapeXml(unescapedXMLString)); // Escape > character in XML String unescapedXMLString = "DataStructures > Java"; System.out.println("Unescaped String: " + unescapedXMLString); // using StringEscapeUtils System.out.println("Escaped String: " + StringEscapeUtils.escapeXml(unescapedXMLString)); // Escape < character in XML String unescapedXMLString = "DataStructures < Java"; System.out.println("Unescaped String: " + unescapedXMLString); // using StringEscapeUtils System.out.println("Escaped String: " + StringEscapeUtils.escapeXml(unescapedXMLString)); // Escape " character in XML String unescapedXMLString = "DataStructures \" Java"; System.out.println("Unescaped String: " + unescapedXMLString); // using StringEscapeUtils System.out.println("Escaped String: " + StringEscapeUtils.escapeXml(unescapedXMLString)); // Escape ' character in XML String unescapedXMLString = "DataStructures ' Java"; System.out.println("Unescaped String: " + unescapedXMLString); // using StringEscapeUtils System.out.println("Escaped String: " + StringEscapeUtils.escapeXml(unescapedXMLString)); }}
Output:
Program to escape XML Special Characters !!
Unescaped String: DataStructures & Java
Escaped String: DataStructures & Java
Unescaped String: DataStructures > Java
Escaped String: DataStructures > Java
Unescaped String: DataStructures < Java
Escaped String: DataStructures < Java
Unescaped String: DataStructures " Java
Escaped String: DataStructures " Java
Unescaped String: DataStructures ' Java
Escaped String: DataStructures ' Java
Java-Strings
Picked
Java
Java Programs
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
7 Things You Didn’t Know About Java
Different ways of Reading a text file in Java
Generics in Java
Constructors in Java
length vs length() in Java
How to Iterate HashMap in Java?
Iterate Over the Characters of a String in Java
Implementing a Linked List in Java using Class
Convert Double to Integer in Java
Java Program to find largest element in an array
|
[
{
"code": null,
"e": 25225,
"s": 25197,
"text": "\n22 Feb, 2021"
},
{
"code": null,
"e": 25802,
"s": 25225,
"text": "When we read an XML file and try writing to another XML file it is important for us to take care of special characters in the XML. There are some reserved characters in Java that need to be transformed or escaped to be considered as a string literal. If we don’t escape these special characters then parsers like DOM or SAX parsers in java would consider them as XML tags specifically in the case of < and >. Even if we use XSLT transform these parsers would fail. Hence, we need to escape or transform these special characters before reading them as a String literal in Java."
},
{
"code": null,
"e": 25828,
"s": 25802,
"text": "Special characters in XML"
},
{
"code": null,
"e": 25930,
"s": 25828,
"text": "There are 5 mostly used special characters in XML that needs to be escaped when used as a Java String"
},
{
"code": null,
"e": 25940,
"s": 25930,
"text": "& — &"
},
{
"code": null,
"e": 25949,
"s": 25940,
"text": "< — <"
},
{
"code": null,
"e": 25958,
"s": 25949,
"text": "> — >"
},
{
"code": null,
"e": 25964,
"s": 25958,
"text": "” — \""
},
{
"code": null,
"e": 25975,
"s": 25964,
"text": "‘ — '"
},
{
"code": null,
"e": 26184,
"s": 25975,
"text": "These special characters are also referred to as XML Metacharacters. By the process of escaping, we would be replacing these characters with alternate strings to give the literal result of special characters."
},
{
"code": null,
"e": 26193,
"s": 26184,
"text": "Example:"
},
{
"code": null,
"e": 26546,
"s": 26193,
"text": "<GeeksForGeeks> Data Structures & Java </GeeksForGeeks>\n\n// is an invalid string in java because '&' is a reserved literal \n// in XML that is used to import other XML entity. For converting this \n// to a valid String literal we need to & instead of & here.\n\n<GeeksForGeeks> Data Structure & Java </GeeksForGeeks>\n\n// now becomes a valid String."
},
{
"code": null,
"e": 26830,
"s": 26546,
"text": "In Java, we could always write our own functions to escape XML special characters with its equivalent String literals, but we could also use the Java library “StringEscapeUtils” provided by Apache Commons. This library provides us with a common API that does the XML escaping for us."
},
{
"code": null,
"e": 26836,
"s": 26830,
"text": "Code:"
},
{
"code": null,
"e": 26841,
"s": 26836,
"text": "Java"
},
{
"code": "// Java program to escape all the five characters// mentioned above using the StringEscapeUtils class import java.io.*;import org.apache.commons.lang.StringEscapeUtils; class GeeksForGeeks { public static void main (String[] args) { System.out.println(\"Program to escape XML Special Characters !!\"); // Escape & character in XML String String unescapedXMLString = \"DataStructures & Java\"; System.out.println(\"Unescaped String: \" + unescapedXMLString); // using StringEscapeUtils System.out.println(\"Escaped String: \" + StringEscapeUtils.escapeXml(unescapedXMLString)); // Escape > character in XML String unescapedXMLString = \"DataStructures > Java\"; System.out.println(\"Unescaped String: \" + unescapedXMLString); // using StringEscapeUtils System.out.println(\"Escaped String: \" + StringEscapeUtils.escapeXml(unescapedXMLString)); // Escape < character in XML String unescapedXMLString = \"DataStructures < Java\"; System.out.println(\"Unescaped String: \" + unescapedXMLString); // using StringEscapeUtils System.out.println(\"Escaped String: \" + StringEscapeUtils.escapeXml(unescapedXMLString)); // Escape \" character in XML String unescapedXMLString = \"DataStructures \\\" Java\"; System.out.println(\"Unescaped String: \" + unescapedXMLString); // using StringEscapeUtils System.out.println(\"Escaped String: \" + StringEscapeUtils.escapeXml(unescapedXMLString)); // Escape ' character in XML String unescapedXMLString = \"DataStructures ' Java\"; System.out.println(\"Unescaped String: \" + unescapedXMLString); // using StringEscapeUtils System.out.println(\"Escaped String: \" + StringEscapeUtils.escapeXml(unescapedXMLString)); }}",
"e": 28873,
"s": 26841,
"text": null
},
{
"code": null,
"e": 28881,
"s": 28873,
"text": "Output:"
},
{
"code": null,
"e": 29330,
"s": 28881,
"text": "Program to escape XML Special Characters !!\nUnescaped String: DataStructures & Java\nEscaped String: DataStructures & Java\nUnescaped String: DataStructures > Java\nEscaped String: DataStructures > Java\nUnescaped String: DataStructures < Java\nEscaped String: DataStructures < Java\nUnescaped String: DataStructures \" Java\nEscaped String: DataStructures \" Java\nUnescaped String: DataStructures ' Java\nEscaped String: DataStructures ' Java"
},
{
"code": null,
"e": 29343,
"s": 29330,
"text": "Java-Strings"
},
{
"code": null,
"e": 29350,
"s": 29343,
"text": "Picked"
},
{
"code": null,
"e": 29355,
"s": 29350,
"text": "Java"
},
{
"code": null,
"e": 29369,
"s": 29355,
"text": "Java Programs"
},
{
"code": null,
"e": 29382,
"s": 29369,
"text": "Java-Strings"
},
{
"code": null,
"e": 29387,
"s": 29382,
"text": "Java"
},
{
"code": null,
"e": 29485,
"s": 29387,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29521,
"s": 29485,
"text": "7 Things You Didn’t Know About Java"
},
{
"code": null,
"e": 29567,
"s": 29521,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 29584,
"s": 29567,
"text": "Generics in Java"
},
{
"code": null,
"e": 29605,
"s": 29584,
"text": "Constructors in Java"
},
{
"code": null,
"e": 29632,
"s": 29605,
"text": "length vs length() in Java"
},
{
"code": null,
"e": 29664,
"s": 29632,
"text": "How to Iterate HashMap in Java?"
},
{
"code": null,
"e": 29712,
"s": 29664,
"text": "Iterate Over the Characters of a String in Java"
},
{
"code": null,
"e": 29759,
"s": 29712,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 29793,
"s": 29759,
"text": "Convert Double to Integer in Java"
}
] |
Scala Map filterKeys() method with example - GeeksforGeeks
|
13 Aug, 2019
The filterKeys() method is utilized to find all the pairs where the keys satisfies the given predicate.
Method Definition: def filterKeys(p: (A) => Boolean): Map[A, B]
Return Type: It returns all the “key-value” pairs of the map where, the keys satisfies the given predicate.
Example #1:
// Scala program of filterKeys()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating map val m1 = Map(5 -> "geeks", 4 -> "for", 2 -> "cs") // Applying filterKeys method val result = m1.filterKeys(_ > 2) // Displays output println(result) }}
Map(5 -> geeks, 4 -> for)
Here, only two key-value pairs are returned as their keys are greater than two as per the stated predicate.Example #2:
// Scala program of filterKeys()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating map val m1 = Map(3 -> "geeks", 1 -> "for", 2 -> "cs") // Applying filterKeys method val result = m1.filterKeys(_ > 3) // Displays output println(result) }}
Map()
Here, no pair is returned as none of the keys satisfies the stated predicate.
Scala
Scala-Map
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Type Casting in Scala
Class and Object in Scala
Scala Lists
Scala Tutorial – Learn Scala with Step By Step Guide
Inheritance in Scala
Operators in Scala
Scala Constructors
Scala | Arrays
Scala String substring() method with example
Lambda Expression in Scala
|
[
{
"code": null,
"e": 25257,
"s": 25229,
"text": "\n13 Aug, 2019"
},
{
"code": null,
"e": 25361,
"s": 25257,
"text": "The filterKeys() method is utilized to find all the pairs where the keys satisfies the given predicate."
},
{
"code": null,
"e": 25425,
"s": 25361,
"text": "Method Definition: def filterKeys(p: (A) => Boolean): Map[A, B]"
},
{
"code": null,
"e": 25533,
"s": 25425,
"text": "Return Type: It returns all the “key-value” pairs of the map where, the keys satisfies the given predicate."
},
{
"code": null,
"e": 25545,
"s": 25533,
"text": "Example #1:"
},
{
"code": "// Scala program of filterKeys()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating map val m1 = Map(5 -> \"geeks\", 4 -> \"for\", 2 -> \"cs\") // Applying filterKeys method val result = m1.filterKeys(_ > 2) // Displays output println(result) }}",
"e": 25921,
"s": 25545,
"text": null
},
{
"code": null,
"e": 25948,
"s": 25921,
"text": "Map(5 -> geeks, 4 -> for)\n"
},
{
"code": null,
"e": 26067,
"s": 25948,
"text": "Here, only two key-value pairs are returned as their keys are greater than two as per the stated predicate.Example #2:"
},
{
"code": "// Scala program of filterKeys()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating map val m1 = Map(3 -> \"geeks\", 1 -> \"for\", 2 -> \"cs\") // Applying filterKeys method val result = m1.filterKeys(_ > 3) // Displays output println(result) }}",
"e": 26443,
"s": 26067,
"text": null
},
{
"code": null,
"e": 26450,
"s": 26443,
"text": "Map()\n"
},
{
"code": null,
"e": 26528,
"s": 26450,
"text": "Here, no pair is returned as none of the keys satisfies the stated predicate."
},
{
"code": null,
"e": 26534,
"s": 26528,
"text": "Scala"
},
{
"code": null,
"e": 26544,
"s": 26534,
"text": "Scala-Map"
},
{
"code": null,
"e": 26557,
"s": 26544,
"text": "Scala-Method"
},
{
"code": null,
"e": 26563,
"s": 26557,
"text": "Scala"
},
{
"code": null,
"e": 26661,
"s": 26563,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26683,
"s": 26661,
"text": "Type Casting in Scala"
},
{
"code": null,
"e": 26709,
"s": 26683,
"text": "Class and Object in Scala"
},
{
"code": null,
"e": 26721,
"s": 26709,
"text": "Scala Lists"
},
{
"code": null,
"e": 26774,
"s": 26721,
"text": "Scala Tutorial – Learn Scala with Step By Step Guide"
},
{
"code": null,
"e": 26795,
"s": 26774,
"text": "Inheritance in Scala"
},
{
"code": null,
"e": 26814,
"s": 26795,
"text": "Operators in Scala"
},
{
"code": null,
"e": 26833,
"s": 26814,
"text": "Scala Constructors"
},
{
"code": null,
"e": 26848,
"s": 26833,
"text": "Scala | Arrays"
},
{
"code": null,
"e": 26893,
"s": 26848,
"text": "Scala String substring() method with example"
}
] |
Python Program for Cycle Sort - GeeksforGeeks
|
20 Apr, 2022
Cycle sort is an in-place sorting Algorithm, unstable sorting algorithm, a comparison sort that is theoretically optimal in terms of the total number of writes to the original array.
It is optimal in terms of number of memory writes. It minimizes the number of memory writes to sort (Each value is either written zero times, if it’s already in its correct position, or written one time to its correct position.)
It is based on the idea that array to be sorted can be divided into cycles. Cycles can be visualized as a graph. We have n nodes and an edge directed from node i to node j if the element at i-th index must be present at j-th index in the sorted array.Cycle in arr[] = {4, 5, 2, 1, 5}Cycle in arr[] = {4, 3, 2, 1}
Cycle in arr[] = {4, 3, 2, 1}
We one by one consider all cycles. We first consider the cycle that includes first element. We find correct position of first element, place it at its correct position, say j. We consider old value of arr[j] and find its correct position, we keep doing this till all elements of current cycle are placed at correct position, i.e., we don\’t come back to cycle starting point.
# Python program to implement cycle sort def cycleSort(array): writes = 0 # Loop through the array to find cycles to rotate. for cycleStart in range(0, len(array) - 1): item = array[cycleStart] # Find where to put the item. pos = cycleStart for i in range(cycleStart + 1, len(array)): if array[i] < item: pos += 1 # If the item is already there, this is not a cycle. if pos == cycleStart: continue # Otherwise, put the item there or right after any duplicates. while item == array[pos]: pos += 1 array[pos], item = item, array[pos] writes += 1 # Rotate the rest of the cycle. while pos != cycleStart: # Find where to put the item. pos = cycleStart for i in range(cycleStart + 1, len(array)): if array[i] < item: pos += 1 # Put the item there or right after any duplicates. while item == array[pos]: pos += 1 array[pos], item = item, array[pos] writes += 1 return writes # driver code arr = [1, 8, 3, 9, 10, 10, 2, 4 ]n = len(arr) cycleSort(arr) print("After sort : ")for i in range(0, n) : print(arr[i], end = \' \') # Code Contributed by Mohit Gupta_OMG <(0_o)>
Output:
After sort :
1 2 3 4 8 9 10 10
Please refer complete article on Cycle Sort for more details!
simmytarika5
python sorting-exercises
Python Programs
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Appending to list in Python dictionary
Python program to interchange first and last elements in a list
How to inverse a matrix using NumPy
Python | Get the first key in dictionary
Differences and Applications of List, Tuple, Set and Dictionary in Python
|
[
{
"code": null,
"e": 26201,
"s": 26173,
"text": "\n20 Apr, 2022"
},
{
"code": null,
"e": 26384,
"s": 26201,
"text": "Cycle sort is an in-place sorting Algorithm, unstable sorting algorithm, a comparison sort that is theoretically optimal in terms of the total number of writes to the original array."
},
{
"code": null,
"e": 26613,
"s": 26384,
"text": "It is optimal in terms of number of memory writes. It minimizes the number of memory writes to sort (Each value is either written zero times, if it’s already in its correct position, or written one time to its correct position.)"
},
{
"code": null,
"e": 26926,
"s": 26613,
"text": "It is based on the idea that array to be sorted can be divided into cycles. Cycles can be visualized as a graph. We have n nodes and an edge directed from node i to node j if the element at i-th index must be present at j-th index in the sorted array.Cycle in arr[] = {4, 5, 2, 1, 5}Cycle in arr[] = {4, 3, 2, 1}"
},
{
"code": null,
"e": 26956,
"s": 26926,
"text": "Cycle in arr[] = {4, 3, 2, 1}"
},
{
"code": null,
"e": 27332,
"s": 26956,
"text": "We one by one consider all cycles. We first consider the cycle that includes first element. We find correct position of first element, place it at its correct position, say j. We consider old value of arr[j] and find its correct position, we keep doing this till all elements of current cycle are placed at correct position, i.e., we don\\’t come back to cycle starting point."
},
{
"code": "# Python program to implement cycle sort def cycleSort(array): writes = 0 # Loop through the array to find cycles to rotate. for cycleStart in range(0, len(array) - 1): item = array[cycleStart] # Find where to put the item. pos = cycleStart for i in range(cycleStart + 1, len(array)): if array[i] < item: pos += 1 # If the item is already there, this is not a cycle. if pos == cycleStart: continue # Otherwise, put the item there or right after any duplicates. while item == array[pos]: pos += 1 array[pos], item = item, array[pos] writes += 1 # Rotate the rest of the cycle. while pos != cycleStart: # Find where to put the item. pos = cycleStart for i in range(cycleStart + 1, len(array)): if array[i] < item: pos += 1 # Put the item there or right after any duplicates. while item == array[pos]: pos += 1 array[pos], item = item, array[pos] writes += 1 return writes # driver code arr = [1, 8, 3, 9, 10, 10, 2, 4 ]n = len(arr) cycleSort(arr) print(\"After sort : \")for i in range(0, n) : print(arr[i], end = \\' \\') # Code Contributed by Mohit Gupta_OMG <(0_o)>",
"e": 28574,
"s": 27332,
"text": null
},
{
"code": null,
"e": 28582,
"s": 28574,
"text": "Output:"
},
{
"code": null,
"e": 28616,
"s": 28582,
"text": "After sort : \n1 2 3 4 8 9 10 10 \n"
},
{
"code": null,
"e": 28678,
"s": 28616,
"text": "Please refer complete article on Cycle Sort for more details!"
},
{
"code": null,
"e": 28691,
"s": 28678,
"text": "simmytarika5"
},
{
"code": null,
"e": 28716,
"s": 28691,
"text": "python sorting-exercises"
},
{
"code": null,
"e": 28732,
"s": 28716,
"text": "Python Programs"
},
{
"code": null,
"e": 28740,
"s": 28732,
"text": "Sorting"
},
{
"code": null,
"e": 28748,
"s": 28740,
"text": "Sorting"
},
{
"code": null,
"e": 28846,
"s": 28748,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28885,
"s": 28846,
"text": "Appending to list in Python dictionary"
},
{
"code": null,
"e": 28949,
"s": 28885,
"text": "Python program to interchange first and last elements in a list"
},
{
"code": null,
"e": 28985,
"s": 28949,
"text": "How to inverse a matrix using NumPy"
},
{
"code": null,
"e": 29026,
"s": 28985,
"text": "Python | Get the first key in dictionary"
}
] |
CSS border-color Property - GeeksforGeeks
|
03 Nov, 2021
The border-color property is used to add color to the border of an element. The border-color property will only work when the border-style property is defined first, which is used to set the borders. This property will not work alone. This can take one to four values for the top border, right border, bottom border, and left border respectively. If this property is not set then it inherits the color of the element.
Syntax:
border-color: color-value;
Default Value : The current color of the element
Property values: Where color-value can be any of the following:
name: It specifies a color name, like “blue”.
Hex: It specifies a hex value, like “#0000ff”.
RGB: It specifies a RGB value, like “rgb(0, 0, 255)”.
transparent: It sets the border color of the corresponding element to transparent.
The border-color property can be used to set individually using the following properties:
CSS border-left-color Property: It is used to set the color of the left-border in an Element.
CSS border-top-color Property: It can provide an option to fill different color from parent border-color to top border of the container.
CSS border-right-color Property: It is used to set the color of the right-border in an Element.
CSS border-bottom-color Property: It is used to set the color of the bottom border of an element.
CSS border-block-color Property: It sed to set the individual logical block border-color property values in a single place in the style sheet.
CSS border-inline-color Property: It is used to set the individual logical inline border-color property values in a single place in the style sheet.
We will understand each property value through the examples.
Set color-value by name: All the 140 valid CSS color names can be assigned to the border color.
Syntax:
border-color: blue;
Example: This example illustrates the border-color property by setting the color using the name value.
HTML
<!DOCTYPE html><html><head> <title>CSS border-color property</title> <style> h1 { color: #009900; } p.one { border-style: solid; border-color: blue; } p.two { border-style: solid; border-color: blue red yellow green; } p.three { border-style: solid; color: green; } </style></head> <body> <h1 align="center">GeeksforGeeks</h1> <p class="one">A solid blue border</p> <p class="two">A solid multicolor border</p> <p class="three">A solid inherited color border</p> </body></html>
Output:
Set color-value by HEX: HEX color value can be assigned to the border color. The pair of values in #rrggbb represent RGB values in the hexadecimal system.
Syntax:
border-color: #0000ff;
Example: This example illustrates the border-color property by setting the color using the hexadecimal value.
HTML
<!DOCTYPE html><html><head> <title>CSS border-color property</title> <style> h1 { color: #009900; } p.one { border-style: solid; border-color: #0000ff; } p.two { border-style: solid; border-color: #0000ff #ff0000 #ffff00 #00ff00; } </style></head> <body> <h1 align="center">GeeksforGeeks</h1> <p class="one">A solid blue border</p> <p class="two">A solid multicolor border</p> </body></html>
Output:
Set color-value by RGB: RGB color value can be assigned to the border color. In rgb(r, g, b) values r, g, and b can vary from 0 to 255 for each of three.
Syntax:
border-color: rgb(0, 0, 255);
Example: This example illustrates the border-color property by setting the color using the RGB value.
HTML
<!DOCTYPE html><html><head> <title>CSS border-color property</title> <style> h1 { color: #009900; } p.one { border-style: solid; border-color: rgb(0, 0, 255); } p.two { border-style: solid; border-color: rgb(0, 0, 255) rgb(255, 0, 0) rgb(255, 255, 0) rgb(0, 255, 0); } </style></head> <body> <h1 align="center">GeeksforGeeks</h1> <p class="one">A solid blue border</p> <p class="two">A solid multicolor border</p> </body></html>
Output:
Set color-value to transparent: Transparent value can be assigned to the border color. The transparent value effect is not observed as it lets pass the background color pass through it.
Syntax:
border-color: transparent;
Example: This example illustrates the border-color property by setting the color using the transparent value.
HTML
<!DOCTYPE html><html><head> <title>CSS border-color property</title> <style> h1 { color: #009900; } p.one { border-style: solid; border-color: transparent; } </style></head> <body> <h1 align="center">GeeksforGeeks</h1> <p class="one">A transparent border</p> </body></html>
Output:
Notes: The border-color property may be defined by using one, two, three, or four values, as given below:
If a single color value is assigned, it will set it to all sides.
If two color values are assigned, the first color is set to the top and bottom sides and the second color will be set to the left & right sides.
If three color values are assigned, the first color is set to the top, the second to the left and right, the third is set to the bottom.
If four-color values are assigned, the colors are set to the top, right, bottom, and left, which follows the clockwise order.
Supported Browsers: The browsers supported by CSS | border-color Property are listed below:
Google Chrome 1.0
Internet Explorer 4.0
Microsoft Edge 12.0
Firefox 1.0
Opera 3.5
Safari 1.0
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
bhaskargeeksforgeeks
ManasChhabra2
CSS-Properties
Picked
Technical Scripter 2018
CSS
HTML
Technical Scripter
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to create footer to stay at the bottom of a Web page?
How to apply style to parent if it has child with CSS?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
|
[
{
"code": null,
"e": 24939,
"s": 24911,
"text": "\n03 Nov, 2021"
},
{
"code": null,
"e": 25357,
"s": 24939,
"text": "The border-color property is used to add color to the border of an element. The border-color property will only work when the border-style property is defined first, which is used to set the borders. This property will not work alone. This can take one to four values for the top border, right border, bottom border, and left border respectively. If this property is not set then it inherits the color of the element."
},
{
"code": null,
"e": 25365,
"s": 25357,
"text": "Syntax:"
},
{
"code": null,
"e": 25392,
"s": 25365,
"text": "border-color: color-value;"
},
{
"code": null,
"e": 25441,
"s": 25392,
"text": "Default Value : The current color of the element"
},
{
"code": null,
"e": 25505,
"s": 25441,
"text": "Property values: Where color-value can be any of the following:"
},
{
"code": null,
"e": 25551,
"s": 25505,
"text": "name: It specifies a color name, like “blue”."
},
{
"code": null,
"e": 25598,
"s": 25551,
"text": "Hex: It specifies a hex value, like “#0000ff”."
},
{
"code": null,
"e": 25652,
"s": 25598,
"text": "RGB: It specifies a RGB value, like “rgb(0, 0, 255)”."
},
{
"code": null,
"e": 25735,
"s": 25652,
"text": "transparent: It sets the border color of the corresponding element to transparent."
},
{
"code": null,
"e": 25825,
"s": 25735,
"text": "The border-color property can be used to set individually using the following properties:"
},
{
"code": null,
"e": 25919,
"s": 25825,
"text": "CSS border-left-color Property: It is used to set the color of the left-border in an Element."
},
{
"code": null,
"e": 26056,
"s": 25919,
"text": "CSS border-top-color Property: It can provide an option to fill different color from parent border-color to top border of the container."
},
{
"code": null,
"e": 26152,
"s": 26056,
"text": "CSS border-right-color Property: It is used to set the color of the right-border in an Element."
},
{
"code": null,
"e": 26250,
"s": 26152,
"text": "CSS border-bottom-color Property: It is used to set the color of the bottom border of an element."
},
{
"code": null,
"e": 26393,
"s": 26250,
"text": "CSS border-block-color Property: It sed to set the individual logical block border-color property values in a single place in the style sheet."
},
{
"code": null,
"e": 26542,
"s": 26393,
"text": "CSS border-inline-color Property: It is used to set the individual logical inline border-color property values in a single place in the style sheet."
},
{
"code": null,
"e": 26603,
"s": 26542,
"text": "We will understand each property value through the examples."
},
{
"code": null,
"e": 26699,
"s": 26603,
"text": "Set color-value by name: All the 140 valid CSS color names can be assigned to the border color."
},
{
"code": null,
"e": 26707,
"s": 26699,
"text": "Syntax:"
},
{
"code": null,
"e": 26727,
"s": 26707,
"text": "border-color: blue;"
},
{
"code": null,
"e": 26830,
"s": 26727,
"text": "Example: This example illustrates the border-color property by setting the color using the name value."
},
{
"code": null,
"e": 26835,
"s": 26830,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title>CSS border-color property</title> <style> h1 { color: #009900; } p.one { border-style: solid; border-color: blue; } p.two { border-style: solid; border-color: blue red yellow green; } p.three { border-style: solid; color: green; } </style></head> <body> <h1 align=\"center\">GeeksforGeeks</h1> <p class=\"one\">A solid blue border</p> <p class=\"two\">A solid multicolor border</p> <p class=\"three\">A solid inherited color border</p> </body></html>",
"e": 27427,
"s": 26835,
"text": null
},
{
"code": null,
"e": 27435,
"s": 27427,
"text": "Output:"
},
{
"code": null,
"e": 27590,
"s": 27435,
"text": "Set color-value by HEX: HEX color value can be assigned to the border color. The pair of values in #rrggbb represent RGB values in the hexadecimal system."
},
{
"code": null,
"e": 27598,
"s": 27590,
"text": "Syntax:"
},
{
"code": null,
"e": 27621,
"s": 27598,
"text": "border-color: #0000ff;"
},
{
"code": null,
"e": 27731,
"s": 27621,
"text": "Example: This example illustrates the border-color property by setting the color using the hexadecimal value."
},
{
"code": null,
"e": 27736,
"s": 27731,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title>CSS border-color property</title> <style> h1 { color: #009900; } p.one { border-style: solid; border-color: #0000ff; } p.two { border-style: solid; border-color: #0000ff #ff0000 #ffff00 #00ff00; } </style></head> <body> <h1 align=\"center\">GeeksforGeeks</h1> <p class=\"one\">A solid blue border</p> <p class=\"two\">A solid multicolor border</p> </body></html>",
"e": 28212,
"s": 27736,
"text": null
},
{
"code": null,
"e": 28220,
"s": 28212,
"text": "Output:"
},
{
"code": null,
"e": 28374,
"s": 28220,
"text": "Set color-value by RGB: RGB color value can be assigned to the border color. In rgb(r, g, b) values r, g, and b can vary from 0 to 255 for each of three."
},
{
"code": null,
"e": 28382,
"s": 28374,
"text": "Syntax:"
},
{
"code": null,
"e": 28412,
"s": 28382,
"text": "border-color: rgb(0, 0, 255);"
},
{
"code": null,
"e": 28514,
"s": 28412,
"text": "Example: This example illustrates the border-color property by setting the color using the RGB value."
},
{
"code": null,
"e": 28519,
"s": 28514,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title>CSS border-color property</title> <style> h1 { color: #009900; } p.one { border-style: solid; border-color: rgb(0, 0, 255); } p.two { border-style: solid; border-color: rgb(0, 0, 255) rgb(255, 0, 0) rgb(255, 255, 0) rgb(0, 255, 0); } </style></head> <body> <h1 align=\"center\">GeeksforGeeks</h1> <p class=\"one\">A solid blue border</p> <p class=\"two\">A solid multicolor border</p> </body></html>",
"e": 29095,
"s": 28519,
"text": null
},
{
"code": null,
"e": 29103,
"s": 29095,
"text": "Output:"
},
{
"code": null,
"e": 29289,
"s": 29103,
"text": "Set color-value to transparent: Transparent value can be assigned to the border color. The transparent value effect is not observed as it lets pass the background color pass through it."
},
{
"code": null,
"e": 29297,
"s": 29289,
"text": "Syntax:"
},
{
"code": null,
"e": 29324,
"s": 29297,
"text": "border-color: transparent;"
},
{
"code": null,
"e": 29434,
"s": 29324,
"text": "Example: This example illustrates the border-color property by setting the color using the transparent value."
},
{
"code": null,
"e": 29439,
"s": 29434,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title>CSS border-color property</title> <style> h1 { color: #009900; } p.one { border-style: solid; border-color: transparent; } </style></head> <body> <h1 align=\"center\">GeeksforGeeks</h1> <p class=\"one\">A transparent border</p> </body></html>",
"e": 29767,
"s": 29439,
"text": null
},
{
"code": null,
"e": 29775,
"s": 29767,
"text": "Output:"
},
{
"code": null,
"e": 29881,
"s": 29775,
"text": "Notes: The border-color property may be defined by using one, two, three, or four values, as given below:"
},
{
"code": null,
"e": 29947,
"s": 29881,
"text": "If a single color value is assigned, it will set it to all sides."
},
{
"code": null,
"e": 30092,
"s": 29947,
"text": "If two color values are assigned, the first color is set to the top and bottom sides and the second color will be set to the left & right sides."
},
{
"code": null,
"e": 30229,
"s": 30092,
"text": "If three color values are assigned, the first color is set to the top, the second to the left and right, the third is set to the bottom."
},
{
"code": null,
"e": 30355,
"s": 30229,
"text": "If four-color values are assigned, the colors are set to the top, right, bottom, and left, which follows the clockwise order."
},
{
"code": null,
"e": 30447,
"s": 30355,
"text": "Supported Browsers: The browsers supported by CSS | border-color Property are listed below:"
},
{
"code": null,
"e": 30465,
"s": 30447,
"text": "Google Chrome 1.0"
},
{
"code": null,
"e": 30487,
"s": 30465,
"text": "Internet Explorer 4.0"
},
{
"code": null,
"e": 30507,
"s": 30487,
"text": "Microsoft Edge 12.0"
},
{
"code": null,
"e": 30519,
"s": 30507,
"text": "Firefox 1.0"
},
{
"code": null,
"e": 30529,
"s": 30519,
"text": "Opera 3.5"
},
{
"code": null,
"e": 30540,
"s": 30529,
"text": "Safari 1.0"
},
{
"code": null,
"e": 30677,
"s": 30540,
"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": 30698,
"s": 30677,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 30712,
"s": 30698,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 30727,
"s": 30712,
"text": "CSS-Properties"
},
{
"code": null,
"e": 30734,
"s": 30727,
"text": "Picked"
},
{
"code": null,
"e": 30758,
"s": 30734,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 30762,
"s": 30758,
"text": "CSS"
},
{
"code": null,
"e": 30767,
"s": 30762,
"text": "HTML"
},
{
"code": null,
"e": 30786,
"s": 30767,
"text": "Technical Scripter"
},
{
"code": null,
"e": 30803,
"s": 30786,
"text": "Web Technologies"
},
{
"code": null,
"e": 30808,
"s": 30803,
"text": "HTML"
},
{
"code": null,
"e": 30906,
"s": 30808,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30956,
"s": 30906,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 31018,
"s": 30956,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 31066,
"s": 31018,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 31124,
"s": 31066,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 31179,
"s": 31124,
"text": "How to apply style to parent if it has child with CSS?"
},
{
"code": null,
"e": 31229,
"s": 31179,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 31291,
"s": 31229,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 31339,
"s": 31291,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 31399,
"s": 31339,
"text": "How to set the default value for an HTML <select> element ?"
}
] |
How to remove portion of a string after certain character in JavaScript ? - GeeksforGeeks
|
29 May, 2019
Given a URL and the task is to remove a portion of URL after a certain character using JavaScript.
split() method: This method is used to split a string into an array of substrings, and returns the new array.Syntax:string.split(separator, limit)Parameters:separator: It is optional parameter. It specifies the character, or the regular expression, to use for splitting the string. If not used, the whole string will be returned (an array with only one item).limit: It is optional parameter. It specifies the integer that specifies the number of splits, items beyond the split limit will be excluded from the array.Return value: Returns a new array, having the splitted items.
Syntax:
string.split(separator, limit)
Parameters:
separator: It is optional parameter. It specifies the character, or the regular expression, to use for splitting the string. If not used, the whole string will be returned (an array with only one item).
limit: It is optional parameter. It specifies the integer that specifies the number of splits, items beyond the split limit will be excluded from the array.
Return value: Returns a new array, having the splitted items.
JavaScript String substring() Method: This method gets the characters from a string, between two defined indices, and returns the new sub string. This method gets the characters in a string between “start” and “end”, excluding “end” itself.Syntax:string.substring(start, end)Parameters:start: It is required parameter. It specifies the position from where to start the extraction. Index of first character starts from 0.end: It is optional parameter. It specifies the position (eccluding) where to stop the extraction. If not used, it extracts the whole string.Return value: It returns a new string containing the extracted characters.
Syntax:
string.substring(start, end)
Parameters:
start: It is required parameter. It specifies the position from where to start the extraction. Index of first character starts from 0.
end: It is optional parameter. It specifies the position (eccluding) where to stop the extraction. If not used, it extracts the whole string.
Return value: It returns a new string containing the extracted characters.
Example 1: This example uses the substring() method to remove the portion of the string after certain character (?).
<!DOCTYPE HTML> <html> <head> <title> Remove portion of string after certain characters </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <button onclick = "GFG_click()"> click to remove </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var s = '/path/action?id=11612&value=44944'; el_up.innerHTML = s; function GFG_click() { s = s.substring(0, s.indexOf('?')); el_down.innerHTML = "String = "+s; } </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Example 2: This example uses the split() method to remove the portion of the string after certain character (?).
<!DOCTYPE HTML> <html> <head> <title> Remove portion of string after certain character </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <button onclick = "GFG_click()"> click to remove </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var s = '/path/action?id=11612&value=44944'; el_up.innerHTML = s; function GFG_click() { s = s.split('?')[0] el_down.innerHTML = "String = " + s; } </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 26299,
"s": 26271,
"text": "\n29 May, 2019"
},
{
"code": null,
"e": 26398,
"s": 26299,
"text": "Given a URL and the task is to remove a portion of URL after a certain character using JavaScript."
},
{
"code": null,
"e": 26975,
"s": 26398,
"text": "split() method: This method is used to split a string into an array of substrings, and returns the new array.Syntax:string.split(separator, limit)Parameters:separator: It is optional parameter. It specifies the character, or the regular expression, to use for splitting the string. If not used, the whole string will be returned (an array with only one item).limit: It is optional parameter. It specifies the integer that specifies the number of splits, items beyond the split limit will be excluded from the array.Return value: Returns a new array, having the splitted items."
},
{
"code": null,
"e": 26983,
"s": 26975,
"text": "Syntax:"
},
{
"code": null,
"e": 27014,
"s": 26983,
"text": "string.split(separator, limit)"
},
{
"code": null,
"e": 27026,
"s": 27014,
"text": "Parameters:"
},
{
"code": null,
"e": 27229,
"s": 27026,
"text": "separator: It is optional parameter. It specifies the character, or the regular expression, to use for splitting the string. If not used, the whole string will be returned (an array with only one item)."
},
{
"code": null,
"e": 27386,
"s": 27229,
"text": "limit: It is optional parameter. It specifies the integer that specifies the number of splits, items beyond the split limit will be excluded from the array."
},
{
"code": null,
"e": 27448,
"s": 27386,
"text": "Return value: Returns a new array, having the splitted items."
},
{
"code": null,
"e": 28084,
"s": 27448,
"text": "JavaScript String substring() Method: This method gets the characters from a string, between two defined indices, and returns the new sub string. This method gets the characters in a string between “start” and “end”, excluding “end” itself.Syntax:string.substring(start, end)Parameters:start: It is required parameter. It specifies the position from where to start the extraction. Index of first character starts from 0.end: It is optional parameter. It specifies the position (eccluding) where to stop the extraction. If not used, it extracts the whole string.Return value: It returns a new string containing the extracted characters."
},
{
"code": null,
"e": 28092,
"s": 28084,
"text": "Syntax:"
},
{
"code": null,
"e": 28121,
"s": 28092,
"text": "string.substring(start, end)"
},
{
"code": null,
"e": 28133,
"s": 28121,
"text": "Parameters:"
},
{
"code": null,
"e": 28268,
"s": 28133,
"text": "start: It is required parameter. It specifies the position from where to start the extraction. Index of first character starts from 0."
},
{
"code": null,
"e": 28410,
"s": 28268,
"text": "end: It is optional parameter. It specifies the position (eccluding) where to stop the extraction. If not used, it extracts the whole string."
},
{
"code": null,
"e": 28485,
"s": 28410,
"text": "Return value: It returns a new string containing the extracted characters."
},
{
"code": null,
"e": 28602,
"s": 28485,
"text": "Example 1: This example uses the substring() method to remove the portion of the string after certain character (?)."
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> Remove portion of string after certain characters </title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <button onclick = \"GFG_click()\"> click to remove </button> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var s = '/path/action?id=11612&value=44944'; el_up.innerHTML = s; function GFG_click() { s = s.substring(0, s.indexOf('?')); el_down.innerHTML = \"String = \"+s; } </script> </body> </html> ",
"e": 29651,
"s": 28602,
"text": null
},
{
"code": null,
"e": 29659,
"s": 29651,
"text": "Output:"
},
{
"code": null,
"e": 29690,
"s": 29659,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 29720,
"s": 29690,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 29833,
"s": 29720,
"text": "Example 2: This example uses the split() method to remove the portion of the string after certain character (?)."
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> Remove portion of string after certain character </title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <button onclick = \"GFG_click()\"> click to remove </button> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var s = '/path/action?id=11612&value=44944'; el_up.innerHTML = s; function GFG_click() { s = s.split('?')[0] el_down.innerHTML = \"String = \" + s; } </script> </body> </html> ",
"e": 30862,
"s": 29833,
"text": null
},
{
"code": null,
"e": 30870,
"s": 30862,
"text": "Output:"
},
{
"code": null,
"e": 30901,
"s": 30870,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 30931,
"s": 30901,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 30942,
"s": 30931,
"text": "JavaScript"
},
{
"code": null,
"e": 30959,
"s": 30942,
"text": "Web Technologies"
},
{
"code": null,
"e": 30986,
"s": 30959,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 31084,
"s": 30986,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31124,
"s": 31084,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 31169,
"s": 31124,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 31230,
"s": 31169,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 31302,
"s": 31230,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 31354,
"s": 31302,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 31394,
"s": 31354,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 31427,
"s": 31394,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 31472,
"s": 31427,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 31515,
"s": 31472,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Remove Objects from Memory in R Programming - rm() Function - GeeksforGeeks
|
19 Jun, 2020
rm() function in R Language is used to delete objects from the memory. It can be used with ls() function to delete all objects. remove() function is also similar to rm() function.
Syntax: rm(x)
Parameters:x: Object name
Example 1:
# R Program to remove # objects from Memory # Creating a vectorvec <- c(1, 2, 3, 4)vec # Creating a listlist1 = list("Number" = c(1, 2, 3), "Characters" = c("a", "b", "c"))list1 # Creating a matrixmat <- matrix(c(1:9), 3, 3)mat # Calling rm() Functionrm(list1) # Calling ls() to check object listls()
Output:
[1] 1 2 3 4
$Number
[1] 1 2 3
$Characters
[1] "a" "b" "c"
[, 1] [, 2] [, 3]
[1, ] 1 4 7
[2, ] 2 5 8
[3, ] 3 6 9
[1] "mat" "vec"
Example 2:
# R Program to remove # objects from Memory # Creating a vectorvec <- c(1, 2, 3, 4) # Creating a listlist1 = list("Number" = c(1, 2, 3), "Characters" = c("a", "b", "c")) # Creating a matrixmat <- matrix(c(1:9), 3, 3) # Calling rm() Function# to remove all objectsrm(list = ls()) # Calling ls() to check object listls()
Output:
character(0)
R Object-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Replace specific values in column in R DataFrame ?
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 Row Names of DataFrame in R ?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
R Programming Language - Introduction
K-Means Clustering in R Programming
|
[
{
"code": null,
"e": 26274,
"s": 26246,
"text": "\n19 Jun, 2020"
},
{
"code": null,
"e": 26454,
"s": 26274,
"text": "rm() function in R Language is used to delete objects from the memory. It can be used with ls() function to delete all objects. remove() function is also similar to rm() function."
},
{
"code": null,
"e": 26468,
"s": 26454,
"text": "Syntax: rm(x)"
},
{
"code": null,
"e": 26494,
"s": 26468,
"text": "Parameters:x: Object name"
},
{
"code": null,
"e": 26505,
"s": 26494,
"text": "Example 1:"
},
{
"code": "# R Program to remove # objects from Memory # Creating a vectorvec <- c(1, 2, 3, 4)vec # Creating a listlist1 = list(\"Number\" = c(1, 2, 3), \"Characters\" = c(\"a\", \"b\", \"c\"))list1 # Creating a matrixmat <- matrix(c(1:9), 3, 3)mat # Calling rm() Functionrm(list1) # Calling ls() to check object listls()",
"e": 26823,
"s": 26505,
"text": null
},
{
"code": null,
"e": 26831,
"s": 26823,
"text": "Output:"
},
{
"code": null,
"e": 26994,
"s": 26831,
"text": "[1] 1 2 3 4\n$Number\n[1] 1 2 3\n\n$Characters\n[1] \"a\" \"b\" \"c\"\n\n [, 1] [, 2] [, 3]\n[1, ] 1 4 7\n[2, ] 2 5 8\n[3, ] 3 6 9\n[1] \"mat\" \"vec\"\n"
},
{
"code": null,
"e": 27005,
"s": 26994,
"text": "Example 2:"
},
{
"code": "# R Program to remove # objects from Memory # Creating a vectorvec <- c(1, 2, 3, 4) # Creating a listlist1 = list(\"Number\" = c(1, 2, 3), \"Characters\" = c(\"a\", \"b\", \"c\")) # Creating a matrixmat <- matrix(c(1:9), 3, 3) # Calling rm() Function# to remove all objectsrm(list = ls()) # Calling ls() to check object listls()",
"e": 27341,
"s": 27005,
"text": null
},
{
"code": null,
"e": 27349,
"s": 27341,
"text": "Output:"
},
{
"code": null,
"e": 27363,
"s": 27349,
"text": "character(0)\n"
},
{
"code": null,
"e": 27381,
"s": 27363,
"text": "R Object-Function"
},
{
"code": null,
"e": 27392,
"s": 27381,
"text": "R Language"
},
{
"code": null,
"e": 27490,
"s": 27392,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27548,
"s": 27490,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 27600,
"s": 27548,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 27632,
"s": 27600,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 27684,
"s": 27632,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 27728,
"s": 27684,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 27763,
"s": 27728,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 27801,
"s": 27763,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 27859,
"s": 27801,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 27897,
"s": 27859,
"text": "R Programming Language - Introduction"
}
] |
Check whether a given Binary Tree is Complete or not | Set 1 (Iterative Solution) - GeeksforGeeks
|
10 May, 2022
Given a Binary Tree, write a function to check whether the given Binary Tree is Complete Binary Tree or not.A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible. See the following examples.
The following trees are examples of Complete Binary Trees
1
/ \
2 3
1
/ \
2 3
/
4
1
/ \
2 3
/ \ /
4 5 6
The following trees are examples of Non-Complete Binary Trees
1
\
3
1
/ \
2 3
\ / \
4 5 6
1
/ \
2 3
/ \
4 5
The method 2 of level order traversal post can be easily modified to check whether a tree is Complete or not. To understand the approach, let us first define the term ‘Full Node’. A node is ‘Full Node’ if both left and right children are not empty (or not NULL).
The approach is to do a level order traversal starting from the root. In the traversal, once a node is found which is NOT a Full Node, all the following nodes must be leaf nodes.
Also, one more thing needs to be checked to handle the below case: If a node has an empty left child, then the right child must be empty.
1
/ \
2 3
\
4
Thanks to Guddu Sharma for suggesting this simple and efficient approach.
C++
C
Java
Python
C#
Javascript
// C++ program to check if a given// binary tree is complete or not#include <bits/stdc++.h>using namespace std; /* A binary tree node has data,pointer to left child and apointer to right child */struct node{ int data; struct node* left; struct node* right;}; /* Given a binary tree, returntrue if the tree is completeelse false */bool isCompleteBT(node* root){ // Base Case: An empty tree // is complete Binary Tree if (root == NULL) return true; // Create an empty queue //int rear, front; //node **queue = createQueue(&front, &rear); queue<node *> q; q.push(root); // Create a flag variable which will be set true // when a non full node is seen bool flag = false; // Do level order traversal using queue. //enQueue(queue, &rear, root); while(!q.empty()) { node *temp =q.front(); q.pop(); /* Check if left child is present*/ if(temp->left) { // If we have seen a non full node, // and we see a node with non-empty // left child, then the given tree is not // a complete Binary Tree if (flag == true) return false; q.push(temp->left);// Enqueue Left Child } else // If this a non-full node, set the flag as true flag = true; /* Check if right child is present*/ if(temp->right) { // If we have seen a non full node, // and we see a node with non-empty // right child, then the given tree is not // a complete Binary Tree if(flag == true) return false; q.push(temp->right); // Enqueue Right Child } else // If this a non-full node, set the flag as true flag = true; } // If we reach here, then the // tree is complete Binary Tree return true;} /* Helper function that allocates a new node with thegiven data and NULL left and right pointers. */struct node* newNode(int data){ struct node* node = (struct node*)malloc( sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node);} /* Driver code*/int main(){ /* Let us construct the following Binary Tree which is not a complete Binary Tree 1 / \ 2 3 / \ / 4 5 6 */ node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); if ( isCompleteBT(root) == true ) cout << "Complete Binary Tree"; else cout << "NOT Complete Binary Tree"; return 0;} // This code is contributed by izuna_894
// A program to check if a given binary tree is complete or not#include <stdio.h>#include <stdlib.h>#include <stdbool.h>#define MAX_Q_SIZE 500 /* A binary tree node has data, a pointer to left child and a pointer to right child */struct node{ int data; struct node* left; struct node* right;}; /* function prototypes for functions needed for Queue data structure. A queue is needed for level order traversal */struct node** createQueue(int *, int *);void enQueue(struct node **, int *, struct node *);struct node *deQueue(struct node **, int *);bool isQueueEmpty(int *front, int *rear); /* Given a binary tree, return true if the tree is complete else false */bool isCompleteBT(struct node* root){ // Base Case: An empty tree is complete Binary Tree if (root == NULL) return true; // Create an empty queue int rear, front; struct node **queue = createQueue(&front, &rear); // Create a flag variable which will be set true // when a non full node is seen bool flag = false; // Do level order traversal using queue. enQueue(queue, &rear, root); while(!isQueueEmpty(&front, &rear)) { struct node *temp_node = deQueue(queue, &front); /* Check if left child is present*/ if(temp_node->left) { // If we have seen a non full node, and we see a node // with non-empty left child, then the given tree is not // a complete Binary Tree if (flag == true) return false; enQueue(queue, &rear, temp_node->left); // Enqueue Left Child } else // If this a non-full node, set the flag as true flag = true; /* Check if right child is present*/ if(temp_node->right) { // If we have seen a non full node, and we see a node // with non-empty right child, then the given tree is not // a complete Binary Tree if(flag == true) return false; enQueue(queue, &rear, temp_node->right); // Enqueue Right Child } else // If this a non-full node, set the flag as true flag = true; } // If we reach here, then the tree is complete Binary Tree return true;} /*UTILITY FUNCTIONS*/struct node** createQueue(int *front, int *rear){ struct node **queue = (struct node **)malloc(sizeof(struct node*)*MAX_Q_SIZE); *front = *rear = 0; return queue;} void enQueue(struct node **queue, int *rear, struct node *new_node){ queue[*rear] = new_node; (*rear)++;} struct node *deQueue(struct node **queue, int *front){ (*front)++; return queue[*front - 1];} bool isQueueEmpty(int *front, int *rear){ return (*rear == *front);} /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct node* newNode(int data){ struct node* node = (struct node*) malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node);} /* Driver program to test above functions*/int main(){ /* Let us construct the following Binary Tree which is not a complete Binary Tree 1 / \ 2 3 / \ \ 4 5 6 */ struct node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->right = newNode(6); if ( isCompleteBT(root) == true ) printf ("Complete Binary Tree"); else printf ("NOT Complete Binary Tree"); return 0;}
//A Java program to check if a given binary tree is complete or not import java.util.LinkedList;import java.util.Queue; public class CompleteBTree{ /* A binary tree node has data, a pointer to left child and a pointer to right child */ static class Node { int data; Node left; Node right; // Constructor Node(int d) { data = d; left = null; right = null; } } /* Given a binary tree, return true if the tree is complete else false */ static boolean isCompleteBT(Node root) { // Base Case: An empty tree is complete Binary Tree if(root == null) return true; // Create an empty queue Queue<Node> queue =new LinkedList<>(); // Create a flag variable which will be set true // when a non full node is seen boolean flag = false; // Do level order traversal using queue. queue.add(root); while(!queue.isEmpty()) { Node temp_node = queue.remove(); /* Check if left child is present*/ if(temp_node.left != null) { // If we have seen a non full node, and we see a node // with non-empty left child, then the given tree is not // a complete Binary Tree if(flag == true) return false; // Enqueue Left Child queue.add(temp_node.left); } // If this a non-full node, set the flag as true else flag = true; /* Check if right child is present*/ if(temp_node.right != null) { // If we have seen a non full node, and we see a node // with non-empty right child, then the given tree is not // a complete Binary Tree if(flag == true) return false; // Enqueue Right Child queue.add(temp_node.right); } // If this a non-full node, set the flag as true else flag = true; } // If we reach here, then the tree is complete Binary Tree return true; } /* Driver program to test above functions*/ public static void main(String[] args) { /* Let us construct the following Binary Tree which is not a complete Binary Tree 1 / \ 2 3 / \ \ 4 5 6 */ Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.right = new Node(6); if(isCompleteBT(root) == true) System.out.println("Complete Binary Tree"); else System.out.println("NOT Complete Binary Tree"); } }//This code is contributed by Sumit Ghosh
# Check whether a binary tree is complete or not # A binary tree nodeclass Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # Given a binary tree, return true if the tree is complete# else return falsedef isCompleteBT(root): # Base Case: An empty tree is complete Binary tree if root is None: return True # Create an empty queue queue = [] # Create a flag variable which will be set True # when a non-full node is seen flag = False # Do level order traversal using queue queue.append(root) while(len(queue) > 0): tempNode = queue.pop(0) # Dequeue # Check if left child is present if (tempNode.left): # If we have seen a non-full node, and we see # a node with non-empty left child, then the # given tree is not a complete binary tree if flag == True : return False # Enqueue left child queue.append(tempNode.left) # If this a non-full node, set the flag as true else: flag = True # Check if right child is present if(tempNode.right): # If we have seen a non full node, and we # see a node with non-empty right child, then # the given tree is not a complete BT if flag == True: return False # Enqueue right child queue.append(tempNode.right) # If this is non-full node, set the flag as True else: flag = True # If we reach here, then the tree is complete BT return True # Driver program to test above function """ Let us construct the following Binary Tree which is not a complete Binary Tree 1 / \ 2 3 / \ \ 4 5 6 """root = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5)root.right.right = Node(6) if (isCompleteBT(root)): print "Complete Binary Tree"else: print "NOT Complete Binary Tree" # This code is contributed by Nikhil Kumar Singh(nickzuck_007)
// C# program to check if a given// binary tree is complete or notusing System;using System.Collections.Generic; public class CompleteBTree{ /* A binary tree node has data, pointer to left child and a pointer to right child */ public class Node { public int data; public Node left; public Node right; // Constructor public Node(int d) { data = d; left = null; right = null; } } /* Given a binary tree, return true if the tree is complete else false */ static bool isCompleteBT(Node root) { // Base Case: An empty tree // is complete Binary Tree if(root == null) return true; // Create an empty queue Queue<Node> queue = new Queue<Node>(); // Create a flag variable which will be set true // when a non full node is seen bool flag = false; // Do level order traversal using queue. queue.Enqueue(root); while(queue.Count != 0) { Node temp_node = queue.Dequeue(); /* Check if left child is present*/ if(temp_node.left != null) { // If we have seen a non full node, // and we see a node with non-empty // left child, then the given tree is not // a complete Binary Tree if(flag == true) return false; // Enqueue Left Child queue.Enqueue(temp_node.left); } // If this a non-full node, set the flag as true else flag = true; /* Check if right child is present*/ if(temp_node.right != null) { // If we have seen a non full node, // and we see a node with non-empty // right child, then the given tree // is not a complete Binary Tree if(flag == true) return false; // Enqueue Right Child queue.Enqueue(temp_node.right); } // If this a non-full node, // set the flag as true else flag = true; } // If we reach here, then the // tree is complete Binary Tree return true; } /* Driver code*/ public static void Main() { /* Let us construct the following Binary Tree which is not a complete Binary Tree 1 / \ 2 3 / \ \ 4 5 6 */ Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.right = new Node(6); if(isCompleteBT(root) == true) Console.WriteLine("Complete Binary Tree"); else Console.WriteLine("NOT Complete Binary Tree"); }} /* This code contributed by PrinciRaj1992 */
<script> // JavaScript program to check if a given// binary tree is complete or not /* A binary tree node has data,pointer to left child and a pointer to right child */class Node{ // Constructor constructor(d) { this.data = d; this.left = null; this.right = null; }} /* Given a binary tree, returntrue if the tree is completeelse false */function isCompleteBT(root){ // Base Case: An empty tree // is complete Binary Tree if(root == null) return true; // Create an empty queue var queue = []; // Create a flag variable which will be set true // when a non full node is seen var flag = false; // Do level order traversal using queue. queue.push(root); while(queue.length != 0) { var temp_node = queue.shift(); /* Check if left child is present*/ if(temp_node.left != null) { // If we have seen a non full node, // and we see a node with non-empty // left child, then the given tree is not // a complete Binary Tree if(flag == true) return false; // push Left Child queue.push(temp_node.left); } // If this a non-full node, set the flag as true else flag = true; /* Check if right child is present*/ if(temp_node.right != null) { // If we have seen a non full node, // and we see a node with non-empty // right child, then the given tree // is not a complete Binary Tree if(flag == true) return false; // push Right Child queue.push(temp_node.right); } // If this a non-full node, // set the flag as true else flag = true; } // If we reach here, then the // tree is complete Binary Tree return true;} /* Driver code*//* Let us construct the following Binary Tree whichis not a complete Binary Tree 1 / \ 2 3 / \ \4 5 6*/var root = new Node(1);root.left = new Node(2);root.right = new Node(3);root.left.left = new Node(4);root.left.right = new Node(5);root.right.right = new Node(6); if(isCompleteBT(root) == true) document.write("Complete Binary Tree");else document.write("NOT Complete Binary Tree"); </script>
Complete Binary Tree
Time Complexity: O(n) where n is the number of nodes in given Binary TreeAuxiliary Space: O(n) for queue.
Method 2 : A more simple approach would be to check whether the NULL Node encountered is the last node of the Binary Tree. If the null node encountered in the binary tree is the last node then it is a complete binary tree and if there exists a valid node even after encountering a null node then the tree is not a complete binary tree.
C++
Java
C#
// C++ program to check if a given// binary tree is complete or not#include <bits/stdc++.h>using namespace std; /* A binary tree node has data,pointer to left child and apointer to right child */struct node{ int data; struct node* left; struct node* right;}; /* Given a binary tree, returntrue if the tree is completeelse false */bool isCompleteBT(node* root){ // Base Case: An empty tree // is complete Binary Tree if (root == NULL) return true; // Create an empty queue queue<node *> q; q.push(root); // Create a flag variable which will be set true // when a non full node is seen bool flag = false; // Do level order traversal using queue. //enQueue(queue, &rear, root); while(!q.empty()) { node *temp =q.front(); q.pop(); if(temp == NULL){ // If we have seen a NULL node, // we set the flag to true flag = true ; }else{ // If that NULL node // is not the last node // then return false if(flag == true){ return false ; } // Push both nodes // even if there are null q.push(temp->left) ; q.push(temp->right) ; } } // If we reach here, then the // tree is complete Binary Tree return true;} /* Helper function that allocates a new node with thegiven data and NULL left and right pointers. */struct node* newNode(int data){ struct node* node = (struct node*)malloc( sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node);} /* Driver code*/int main(){ /* Let us construct the following Binary Tree which is not a complete Binary Tree 1 / \ 2 3 / \ / 4 5 6 */ struct node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); if ( isCompleteBT(root) == true ) cout << "Complete Binary Tree"; else cout << "NOT Complete Binary Tree"; return 0;}
// Java program to check if a given// binary tree is complete or notimport java.util.*; class GFG{ /* A binary tree node has data,pointer to left child and apointer to right child */static class node{ int data; node left; node right;}; /* Given a binary tree, returntrue if the tree is completeelse false */static boolean isCompleteBT(node root){ // Base Case: An empty tree // is complete Binary Tree if (root == null) return true; // Create an empty queue Queue<node > q = new LinkedList<>(); q.add(root); // Create a flag variable which will be set true // when a non full node is seen boolean flag = false; // Do level order traversal using queue. //enQueue(queue, &rear, root); while(!q.isEmpty()) { node temp =q.peek(); q.remove(); if(temp == null) { // If we have seen a null node, // we set the flag to true flag = true ; } else { // If that null node // is not the last node // then return false if(flag == true) { return false ; } // Push both nodes // even if there are null q.add(temp.left) ; q.add(temp.right) ; } } // If we reach here, then the // tree is complete Binary Tree return true;} /* Helper function that allocates a new node with thegiven data and null left and right pointers. */static node newNode(int data){ node node = new node(); node.data = data; node.left = null; node.right = null; return(node);} /* Driver code*/public static void main(String[] args){ /* Let us construct the following Binary Tree which is not a complete Binary Tree 1 / \ 2 3 / \ / 4 5 6 */ node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.left = newNode(6); if ( isCompleteBT(root) == true ) System.out.print("Complete Binary Tree"); else System.out.print("NOT Complete Binary Tree"); }} // This code is contributed by Rajput-Ji
// C# program to check if a given// binary tree is complete or notusing System;using System.Collections.Generic; class GFG{ /* A binary tree node has data,pointer to left child and apointer to right child */ public class node{ public int data; public node left; public node right;} /* Given a binary tree, returntrue if the tree is completeelse false */static bool isCompleteBT(node root){ // Base Case: An empty tree // is complete Binary Tree if (root == null) return true; // Create an empty queue Queue<node > q = new Queue<node>(); q.Enqueue(root); // Create a flag variable which will be set true // when a non full node is seen bool flag = false; // Do level order traversal using queue. //enQueue(queue, &rear, root); while(q.Count!=0) { node temp =q.Peek(); q.Dequeue(); if(temp == null) { // If we have seen a null node, // we set the flag to true flag = true ; } else { // If that null node // is not the last node // then return false if(flag == true) { return false ; } // Push both nodes // even if there are null q.Enqueue(temp.left) ; q.Enqueue(temp.right) ; } } // If we reach here, then the // tree is complete Binary Tree return true;} /* Helper function that allocates a new node with thegiven data and null left and right pointers. */public static node newNode(int data){ node node = new node(); node.data = data; node.left = null; node.right = null; return(node);} // Driver Codepublic static void Main(){ /* Let us construct the following Binary Tree which is not a complete Binary Tree 1 / \ 2 3 / \ / 4 5 6 */ node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.left = newNode(6); if ( isCompleteBT(root) == true ) Console.Write("Complete Binary Tree"); else Console.Write("NOT Complete Binary Tree"); }} // This code is contributed by jana_sayantan.
Complete Binary Tree
Time Complexity: O(n) where n is the number of nodes in given Binary Tree
Auxiliary Space: O(n) for queue.
YouTubeGeeksforGeeks507K subscribersCheck whether a given Binary Tree is Complete or not | Set 1 (Iterative Solution) | 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 / 4:51•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=IPak9nF_64k" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Please write comments if you find any of the above codes/algorithms incorrect, or find other ways to solve the same problem.
princiraj1992
rathbhupendra
Akanksha_Rai
IZUNA_894
anikakapoor
rutvik_56
surindertarika1234
surinderdawra388
prasanna1995
kk9826225
GauravRajput1
sagartomar9927
jana_sayantan
Queue
Tree
Queue
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Queue | Set 1 (Introduction and Array Implementation)
Priority Queue | Set 1 (Introduction)
LRU Cache Implementation
Queue - Linked List Implementation
Circular Queue | Set 1 (Introduction and Array Implementation)
Tree Traversals (Inorder, Preorder and Postorder)
Binary Tree | Set 1 (Introduction)
AVL Tree | Set 1 (Insertion)
Binary Tree | Set 3 (Types of Binary Tree)
Inorder Tree Traversal without Recursion
|
[
{
"code": null,
"e": 26505,
"s": 26477,
"text": "\n10 May, 2022"
},
{
"code": null,
"e": 26794,
"s": 26505,
"text": "Given a Binary Tree, write a function to check whether the given Binary Tree is Complete Binary Tree or not.A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible. See the following examples."
},
{
"code": null,
"e": 26974,
"s": 26794,
"text": "The following trees are examples of Complete Binary Trees\n 1\n / \\\n 2 3\n \n 1\n / \\\n 2 3\n /\n 4\n\n 1\n / \\\n 2 3\n / \\ /\n 4 5 6"
},
{
"code": null,
"e": 27192,
"s": 26974,
"text": "The following trees are examples of Non-Complete Binary Trees\n 1\n \\\n 3\n \n 1\n / \\\n 2 3\n \\ / \\ \n 4 5 6\n\n 1\n / \\\n 2 3\n / \\\n 4 5 "
},
{
"code": null,
"e": 27456,
"s": 27192,
"text": "The method 2 of level order traversal post can be easily modified to check whether a tree is Complete or not. To understand the approach, let us first define the term ‘Full Node’. A node is ‘Full Node’ if both left and right children are not empty (or not NULL). "
},
{
"code": null,
"e": 27636,
"s": 27456,
"text": "The approach is to do a level order traversal starting from the root. In the traversal, once a node is found which is NOT a Full Node, all the following nodes must be leaf nodes. "
},
{
"code": null,
"e": 27776,
"s": 27636,
"text": "Also, one more thing needs to be checked to handle the below case: If a node has an empty left child, then the right child must be empty. "
},
{
"code": null,
"e": 27808,
"s": 27776,
"text": " 1\n / \\\n 2 3\n \\\n 4"
},
{
"code": null,
"e": 27883,
"s": 27808,
"text": "Thanks to Guddu Sharma for suggesting this simple and efficient approach. "
},
{
"code": null,
"e": 27887,
"s": 27883,
"text": "C++"
},
{
"code": null,
"e": 27889,
"s": 27887,
"text": "C"
},
{
"code": null,
"e": 27894,
"s": 27889,
"text": "Java"
},
{
"code": null,
"e": 27901,
"s": 27894,
"text": "Python"
},
{
"code": null,
"e": 27904,
"s": 27901,
"text": "C#"
},
{
"code": null,
"e": 27915,
"s": 27904,
"text": "Javascript"
},
{
"code": "// C++ program to check if a given// binary tree is complete or not#include <bits/stdc++.h>using namespace std; /* A binary tree node has data,pointer to left child and apointer to right child */struct node{ int data; struct node* left; struct node* right;}; /* Given a binary tree, returntrue if the tree is completeelse false */bool isCompleteBT(node* root){ // Base Case: An empty tree // is complete Binary Tree if (root == NULL) return true; // Create an empty queue //int rear, front; //node **queue = createQueue(&front, &rear); queue<node *> q; q.push(root); // Create a flag variable which will be set true // when a non full node is seen bool flag = false; // Do level order traversal using queue. //enQueue(queue, &rear, root); while(!q.empty()) { node *temp =q.front(); q.pop(); /* Check if left child is present*/ if(temp->left) { // If we have seen a non full node, // and we see a node with non-empty // left child, then the given tree is not // a complete Binary Tree if (flag == true) return false; q.push(temp->left);// Enqueue Left Child } else // If this a non-full node, set the flag as true flag = true; /* Check if right child is present*/ if(temp->right) { // If we have seen a non full node, // and we see a node with non-empty // right child, then the given tree is not // a complete Binary Tree if(flag == true) return false; q.push(temp->right); // Enqueue Right Child } else // If this a non-full node, set the flag as true flag = true; } // If we reach here, then the // tree is complete Binary Tree return true;} /* Helper function that allocates a new node with thegiven data and NULL left and right pointers. */struct node* newNode(int data){ struct node* node = (struct node*)malloc( sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node);} /* Driver code*/int main(){ /* Let us construct the following Binary Tree which is not a complete Binary Tree 1 / \\ 2 3 / \\ / 4 5 6 */ node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); if ( isCompleteBT(root) == true ) cout << \"Complete Binary Tree\"; else cout << \"NOT Complete Binary Tree\"; return 0;} // This code is contributed by izuna_894",
"e": 30623,
"s": 27915,
"text": null
},
{
"code": "// A program to check if a given binary tree is complete or not#include <stdio.h>#include <stdlib.h>#include <stdbool.h>#define MAX_Q_SIZE 500 /* A binary tree node has data, a pointer to left child and a pointer to right child */struct node{ int data; struct node* left; struct node* right;}; /* function prototypes for functions needed for Queue data structure. A queue is needed for level order traversal */struct node** createQueue(int *, int *);void enQueue(struct node **, int *, struct node *);struct node *deQueue(struct node **, int *);bool isQueueEmpty(int *front, int *rear); /* Given a binary tree, return true if the tree is complete else false */bool isCompleteBT(struct node* root){ // Base Case: An empty tree is complete Binary Tree if (root == NULL) return true; // Create an empty queue int rear, front; struct node **queue = createQueue(&front, &rear); // Create a flag variable which will be set true // when a non full node is seen bool flag = false; // Do level order traversal using queue. enQueue(queue, &rear, root); while(!isQueueEmpty(&front, &rear)) { struct node *temp_node = deQueue(queue, &front); /* Check if left child is present*/ if(temp_node->left) { // If we have seen a non full node, and we see a node // with non-empty left child, then the given tree is not // a complete Binary Tree if (flag == true) return false; enQueue(queue, &rear, temp_node->left); // Enqueue Left Child } else // If this a non-full node, set the flag as true flag = true; /* Check if right child is present*/ if(temp_node->right) { // If we have seen a non full node, and we see a node // with non-empty right child, then the given tree is not // a complete Binary Tree if(flag == true) return false; enQueue(queue, &rear, temp_node->right); // Enqueue Right Child } else // If this a non-full node, set the flag as true flag = true; } // If we reach here, then the tree is complete Binary Tree return true;} /*UTILITY FUNCTIONS*/struct node** createQueue(int *front, int *rear){ struct node **queue = (struct node **)malloc(sizeof(struct node*)*MAX_Q_SIZE); *front = *rear = 0; return queue;} void enQueue(struct node **queue, int *rear, struct node *new_node){ queue[*rear] = new_node; (*rear)++;} struct node *deQueue(struct node **queue, int *front){ (*front)++; return queue[*front - 1];} bool isQueueEmpty(int *front, int *rear){ return (*rear == *front);} /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct node* newNode(int data){ struct node* node = (struct node*) malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node);} /* Driver program to test above functions*/int main(){ /* Let us construct the following Binary Tree which is not a complete Binary Tree 1 / \\ 2 3 / \\ \\ 4 5 6 */ struct node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->right = newNode(6); if ( isCompleteBT(root) == true ) printf (\"Complete Binary Tree\"); else printf (\"NOT Complete Binary Tree\"); return 0;}",
"e": 34048,
"s": 30623,
"text": null
},
{
"code": "//A Java program to check if a given binary tree is complete or not import java.util.LinkedList;import java.util.Queue; public class CompleteBTree{ /* A binary tree node has data, a pointer to left child and a pointer to right child */ static class Node { int data; Node left; Node right; // Constructor Node(int d) { data = d; left = null; right = null; } } /* Given a binary tree, return true if the tree is complete else false */ static boolean isCompleteBT(Node root) { // Base Case: An empty tree is complete Binary Tree if(root == null) return true; // Create an empty queue Queue<Node> queue =new LinkedList<>(); // Create a flag variable which will be set true // when a non full node is seen boolean flag = false; // Do level order traversal using queue. queue.add(root); while(!queue.isEmpty()) { Node temp_node = queue.remove(); /* Check if left child is present*/ if(temp_node.left != null) { // If we have seen a non full node, and we see a node // with non-empty left child, then the given tree is not // a complete Binary Tree if(flag == true) return false; // Enqueue Left Child queue.add(temp_node.left); } // If this a non-full node, set the flag as true else flag = true; /* Check if right child is present*/ if(temp_node.right != null) { // If we have seen a non full node, and we see a node // with non-empty right child, then the given tree is not // a complete Binary Tree if(flag == true) return false; // Enqueue Right Child queue.add(temp_node.right); } // If this a non-full node, set the flag as true else flag = true; } // If we reach here, then the tree is complete Binary Tree return true; } /* Driver program to test above functions*/ public static void main(String[] args) { /* Let us construct the following Binary Tree which is not a complete Binary Tree 1 / \\ 2 3 / \\ \\ 4 5 6 */ Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.right = new Node(6); if(isCompleteBT(root) == true) System.out.println(\"Complete Binary Tree\"); else System.out.println(\"NOT Complete Binary Tree\"); } }//This code is contributed by Sumit Ghosh",
"e": 37166,
"s": 34048,
"text": null
},
{
"code": "# Check whether a binary tree is complete or not # A binary tree nodeclass Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # Given a binary tree, return true if the tree is complete# else return falsedef isCompleteBT(root): # Base Case: An empty tree is complete Binary tree if root is None: return True # Create an empty queue queue = [] # Create a flag variable which will be set True # when a non-full node is seen flag = False # Do level order traversal using queue queue.append(root) while(len(queue) > 0): tempNode = queue.pop(0) # Dequeue # Check if left child is present if (tempNode.left): # If we have seen a non-full node, and we see # a node with non-empty left child, then the # given tree is not a complete binary tree if flag == True : return False # Enqueue left child queue.append(tempNode.left) # If this a non-full node, set the flag as true else: flag = True # Check if right child is present if(tempNode.right): # If we have seen a non full node, and we # see a node with non-empty right child, then # the given tree is not a complete BT if flag == True: return False # Enqueue right child queue.append(tempNode.right) # If this is non-full node, set the flag as True else: flag = True # If we reach here, then the tree is complete BT return True # Driver program to test above function \"\"\" Let us construct the following Binary Tree which is not a complete Binary Tree 1 / \\ 2 3 / \\ \\ 4 5 6 \"\"\"root = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5)root.right.right = Node(6) if (isCompleteBT(root)): print \"Complete Binary Tree\"else: print \"NOT Complete Binary Tree\" # This code is contributed by Nikhil Kumar Singh(nickzuck_007)",
"e": 39396,
"s": 37166,
"text": null
},
{
"code": "// C# program to check if a given// binary tree is complete or notusing System;using System.Collections.Generic; public class CompleteBTree{ /* A binary tree node has data, pointer to left child and a pointer to right child */ public class Node { public int data; public Node left; public Node right; // Constructor public Node(int d) { data = d; left = null; right = null; } } /* Given a binary tree, return true if the tree is complete else false */ static bool isCompleteBT(Node root) { // Base Case: An empty tree // is complete Binary Tree if(root == null) return true; // Create an empty queue Queue<Node> queue = new Queue<Node>(); // Create a flag variable which will be set true // when a non full node is seen bool flag = false; // Do level order traversal using queue. queue.Enqueue(root); while(queue.Count != 0) { Node temp_node = queue.Dequeue(); /* Check if left child is present*/ if(temp_node.left != null) { // If we have seen a non full node, // and we see a node with non-empty // left child, then the given tree is not // a complete Binary Tree if(flag == true) return false; // Enqueue Left Child queue.Enqueue(temp_node.left); } // If this a non-full node, set the flag as true else flag = true; /* Check if right child is present*/ if(temp_node.right != null) { // If we have seen a non full node, // and we see a node with non-empty // right child, then the given tree // is not a complete Binary Tree if(flag == true) return false; // Enqueue Right Child queue.Enqueue(temp_node.right); } // If this a non-full node, // set the flag as true else flag = true; } // If we reach here, then the // tree is complete Binary Tree return true; } /* Driver code*/ public static void Main() { /* Let us construct the following Binary Tree which is not a complete Binary Tree 1 / \\ 2 3 / \\ \\ 4 5 6 */ Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.right = new Node(6); if(isCompleteBT(root) == true) Console.WriteLine(\"Complete Binary Tree\"); else Console.WriteLine(\"NOT Complete Binary Tree\"); }} /* This code contributed by PrinciRaj1992 */",
"e": 42588,
"s": 39396,
"text": null
},
{
"code": "<script> // JavaScript program to check if a given// binary tree is complete or not /* A binary tree node has data,pointer to left child and a pointer to right child */class Node{ // Constructor constructor(d) { this.data = d; this.left = null; this.right = null; }} /* Given a binary tree, returntrue if the tree is completeelse false */function isCompleteBT(root){ // Base Case: An empty tree // is complete Binary Tree if(root == null) return true; // Create an empty queue var queue = []; // Create a flag variable which will be set true // when a non full node is seen var flag = false; // Do level order traversal using queue. queue.push(root); while(queue.length != 0) { var temp_node = queue.shift(); /* Check if left child is present*/ if(temp_node.left != null) { // If we have seen a non full node, // and we see a node with non-empty // left child, then the given tree is not // a complete Binary Tree if(flag == true) return false; // push Left Child queue.push(temp_node.left); } // If this a non-full node, set the flag as true else flag = true; /* Check if right child is present*/ if(temp_node.right != null) { // If we have seen a non full node, // and we see a node with non-empty // right child, then the given tree // is not a complete Binary Tree if(flag == true) return false; // push Right Child queue.push(temp_node.right); } // If this a non-full node, // set the flag as true else flag = true; } // If we reach here, then the // tree is complete Binary Tree return true;} /* Driver code*//* Let us construct the following Binary Tree whichis not a complete Binary Tree 1 / \\ 2 3 / \\ \\4 5 6*/var root = new Node(1);root.left = new Node(2);root.right = new Node(3);root.left.left = new Node(4);root.left.right = new Node(5);root.right.right = new Node(6); if(isCompleteBT(root) == true) document.write(\"Complete Binary Tree\");else document.write(\"NOT Complete Binary Tree\"); </script>",
"e": 45021,
"s": 42588,
"text": null
},
{
"code": null,
"e": 45042,
"s": 45021,
"text": "Complete Binary Tree"
},
{
"code": null,
"e": 45149,
"s": 45042,
"text": "Time Complexity: O(n) where n is the number of nodes in given Binary TreeAuxiliary Space: O(n) for queue. "
},
{
"code": null,
"e": 45486,
"s": 45149,
"text": "Method 2 : A more simple approach would be to check whether the NULL Node encountered is the last node of the Binary Tree. If the null node encountered in the binary tree is the last node then it is a complete binary tree and if there exists a valid node even after encountering a null node then the tree is not a complete binary tree."
},
{
"code": null,
"e": 45490,
"s": 45486,
"text": "C++"
},
{
"code": null,
"e": 45495,
"s": 45490,
"text": "Java"
},
{
"code": null,
"e": 45498,
"s": 45495,
"text": "C#"
},
{
"code": "// C++ program to check if a given// binary tree is complete or not#include <bits/stdc++.h>using namespace std; /* A binary tree node has data,pointer to left child and apointer to right child */struct node{ int data; struct node* left; struct node* right;}; /* Given a binary tree, returntrue if the tree is completeelse false */bool isCompleteBT(node* root){ // Base Case: An empty tree // is complete Binary Tree if (root == NULL) return true; // Create an empty queue queue<node *> q; q.push(root); // Create a flag variable which will be set true // when a non full node is seen bool flag = false; // Do level order traversal using queue. //enQueue(queue, &rear, root); while(!q.empty()) { node *temp =q.front(); q.pop(); if(temp == NULL){ // If we have seen a NULL node, // we set the flag to true flag = true ; }else{ // If that NULL node // is not the last node // then return false if(flag == true){ return false ; } // Push both nodes // even if there are null q.push(temp->left) ; q.push(temp->right) ; } } // If we reach here, then the // tree is complete Binary Tree return true;} /* Helper function that allocates a new node with thegiven data and NULL left and right pointers. */struct node* newNode(int data){ struct node* node = (struct node*)malloc( sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node);} /* Driver code*/int main(){ /* Let us construct the following Binary Tree which is not a complete Binary Tree 1 / \\ 2 3 / \\ / 4 5 6 */ struct node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); if ( isCompleteBT(root) == true ) cout << \"Complete Binary Tree\"; else cout << \"NOT Complete Binary Tree\"; return 0;}",
"e": 47709,
"s": 45498,
"text": null
},
{
"code": "// Java program to check if a given// binary tree is complete or notimport java.util.*; class GFG{ /* A binary tree node has data,pointer to left child and apointer to right child */static class node{ int data; node left; node right;}; /* Given a binary tree, returntrue if the tree is completeelse false */static boolean isCompleteBT(node root){ // Base Case: An empty tree // is complete Binary Tree if (root == null) return true; // Create an empty queue Queue<node > q = new LinkedList<>(); q.add(root); // Create a flag variable which will be set true // when a non full node is seen boolean flag = false; // Do level order traversal using queue. //enQueue(queue, &rear, root); while(!q.isEmpty()) { node temp =q.peek(); q.remove(); if(temp == null) { // If we have seen a null node, // we set the flag to true flag = true ; } else { // If that null node // is not the last node // then return false if(flag == true) { return false ; } // Push both nodes // even if there are null q.add(temp.left) ; q.add(temp.right) ; } } // If we reach here, then the // tree is complete Binary Tree return true;} /* Helper function that allocates a new node with thegiven data and null left and right pointers. */static node newNode(int data){ node node = new node(); node.data = data; node.left = null; node.right = null; return(node);} /* Driver code*/public static void main(String[] args){ /* Let us construct the following Binary Tree which is not a complete Binary Tree 1 / \\ 2 3 / \\ / 4 5 6 */ node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.left = newNode(6); if ( isCompleteBT(root) == true ) System.out.print(\"Complete Binary Tree\"); else System.out.print(\"NOT Complete Binary Tree\"); }} // This code is contributed by Rajput-Ji",
"e": 49990,
"s": 47709,
"text": null
},
{
"code": "// C# program to check if a given// binary tree is complete or notusing System;using System.Collections.Generic; class GFG{ /* A binary tree node has data,pointer to left child and apointer to right child */ public class node{ public int data; public node left; public node right;} /* Given a binary tree, returntrue if the tree is completeelse false */static bool isCompleteBT(node root){ // Base Case: An empty tree // is complete Binary Tree if (root == null) return true; // Create an empty queue Queue<node > q = new Queue<node>(); q.Enqueue(root); // Create a flag variable which will be set true // when a non full node is seen bool flag = false; // Do level order traversal using queue. //enQueue(queue, &rear, root); while(q.Count!=0) { node temp =q.Peek(); q.Dequeue(); if(temp == null) { // If we have seen a null node, // we set the flag to true flag = true ; } else { // If that null node // is not the last node // then return false if(flag == true) { return false ; } // Push both nodes // even if there are null q.Enqueue(temp.left) ; q.Enqueue(temp.right) ; } } // If we reach here, then the // tree is complete Binary Tree return true;} /* Helper function that allocates a new node with thegiven data and null left and right pointers. */public static node newNode(int data){ node node = new node(); node.data = data; node.left = null; node.right = null; return(node);} // Driver Codepublic static void Main(){ /* Let us construct the following Binary Tree which is not a complete Binary Tree 1 / \\ 2 3 / \\ / 4 5 6 */ node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.left = newNode(6); if ( isCompleteBT(root) == true ) Console.Write(\"Complete Binary Tree\"); else Console.Write(\"NOT Complete Binary Tree\"); }} // This code is contributed by jana_sayantan.",
"e": 52274,
"s": 49990,
"text": null
},
{
"code": null,
"e": 52295,
"s": 52274,
"text": "Complete Binary Tree"
},
{
"code": null,
"e": 52369,
"s": 52295,
"text": "Time Complexity: O(n) where n is the number of nodes in given Binary Tree"
},
{
"code": null,
"e": 52403,
"s": 52369,
"text": "Auxiliary Space: O(n) for queue. "
},
{
"code": null,
"e": 53283,
"s": 52403,
"text": "YouTubeGeeksforGeeks507K subscribersCheck whether a given Binary Tree is Complete or not | Set 1 (Iterative Solution) | 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 / 4:51•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=IPak9nF_64k\" 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": 53409,
"s": 53283,
"text": "Please write comments if you find any of the above codes/algorithms incorrect, or find other ways to solve the same problem. "
},
{
"code": null,
"e": 53423,
"s": 53409,
"text": "princiraj1992"
},
{
"code": null,
"e": 53437,
"s": 53423,
"text": "rathbhupendra"
},
{
"code": null,
"e": 53450,
"s": 53437,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 53460,
"s": 53450,
"text": "IZUNA_894"
},
{
"code": null,
"e": 53472,
"s": 53460,
"text": "anikakapoor"
},
{
"code": null,
"e": 53482,
"s": 53472,
"text": "rutvik_56"
},
{
"code": null,
"e": 53501,
"s": 53482,
"text": "surindertarika1234"
},
{
"code": null,
"e": 53518,
"s": 53501,
"text": "surinderdawra388"
},
{
"code": null,
"e": 53531,
"s": 53518,
"text": "prasanna1995"
},
{
"code": null,
"e": 53541,
"s": 53531,
"text": "kk9826225"
},
{
"code": null,
"e": 53555,
"s": 53541,
"text": "GauravRajput1"
},
{
"code": null,
"e": 53570,
"s": 53555,
"text": "sagartomar9927"
},
{
"code": null,
"e": 53584,
"s": 53570,
"text": "jana_sayantan"
},
{
"code": null,
"e": 53590,
"s": 53584,
"text": "Queue"
},
{
"code": null,
"e": 53595,
"s": 53590,
"text": "Tree"
},
{
"code": null,
"e": 53601,
"s": 53595,
"text": "Queue"
},
{
"code": null,
"e": 53606,
"s": 53601,
"text": "Tree"
},
{
"code": null,
"e": 53704,
"s": 53606,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 53758,
"s": 53704,
"text": "Queue | Set 1 (Introduction and Array Implementation)"
},
{
"code": null,
"e": 53796,
"s": 53758,
"text": "Priority Queue | Set 1 (Introduction)"
},
{
"code": null,
"e": 53821,
"s": 53796,
"text": "LRU Cache Implementation"
},
{
"code": null,
"e": 53856,
"s": 53821,
"text": "Queue - Linked List Implementation"
},
{
"code": null,
"e": 53919,
"s": 53856,
"text": "Circular Queue | Set 1 (Introduction and Array Implementation)"
},
{
"code": null,
"e": 53969,
"s": 53919,
"text": "Tree Traversals (Inorder, Preorder and Postorder)"
},
{
"code": null,
"e": 54004,
"s": 53969,
"text": "Binary Tree | Set 1 (Introduction)"
},
{
"code": null,
"e": 54033,
"s": 54004,
"text": "AVL Tree | Set 1 (Insertion)"
},
{
"code": null,
"e": 54076,
"s": 54033,
"text": "Binary Tree | Set 3 (Types of Binary Tree)"
}
] |
ReactJS getDerivedStateFromError() Method - GeeksforGeeks
|
16 Oct, 2021
The getDerivedStateFromError() method is invoked if some error occurs during the rendering phase of any lifecycle methods or any children components. This method is used to implement the Error Boundaries for the React application. It is called during the render phase, so side-effects are not permitted in this method. For side-effects, use componentDidCatch() instead.
Syntax:
static getDerivedStateFromError(error)
Parameters: It accepts the error that was thrown as a parameter.
Creating React Application:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. folder name, move to it using the following command:
cd foldername
Example: Program to demonstrate the use of getDerivedStateFromError() method.
Project Structure: It will look like the following.
Filename: App.js
Javascript
import React, { Component } from 'react'; export default class App extends Component { // Initializing the state state = { error: false }; static getDerivedStateFromError(error) { // Changing the state to true if some error occurs return { error: true, }; } render() { return ( <React.StrictMode> <div> {this.state.error ? <div>Some error</div> : <GFGComponent />} </div> </React.StrictMode> ); }} class GFGComponent extends Component { // GFGComponent throws error as state of GFGCompnonent is not defined render() { return <h1>{this.state.heading}</h1>; }}
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output:
Reference: https://reactjs.org/docs/react-component.html#static-getderivedstatefromerror
ruhelaa48
react-js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to apply style to parent if it has child with CSS?
How to execute PHP code using command line ?
Difference Between PUT and PATCH Request
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
|
[
{
"code": null,
"e": 26169,
"s": 26141,
"text": "\n16 Oct, 2021"
},
{
"code": null,
"e": 26540,
"s": 26169,
"text": "The getDerivedStateFromError() method is invoked if some error occurs during the rendering phase of any lifecycle methods or any children components. This method is used to implement the Error Boundaries for the React application. It is called during the render phase, so side-effects are not permitted in this method. For side-effects, use componentDidCatch() instead. "
},
{
"code": null,
"e": 26548,
"s": 26540,
"text": "Syntax:"
},
{
"code": null,
"e": 26587,
"s": 26548,
"text": "static getDerivedStateFromError(error)"
},
{
"code": null,
"e": 26652,
"s": 26587,
"text": "Parameters: It accepts the error that was thrown as a parameter."
},
{
"code": null,
"e": 26680,
"s": 26652,
"text": "Creating React Application:"
},
{
"code": null,
"e": 26744,
"s": 26680,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 26776,
"s": 26744,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 26877,
"s": 26776,
"text": "Step 2: After creating your project folder i.e. folder name, move to it using the following command:"
},
{
"code": null,
"e": 26891,
"s": 26877,
"text": "cd foldername"
},
{
"code": null,
"e": 26969,
"s": 26891,
"text": "Example: Program to demonstrate the use of getDerivedStateFromError() method."
},
{
"code": null,
"e": 27023,
"s": 26969,
"text": "Project Structure: It will look like the following. "
},
{
"code": null,
"e": 27042,
"s": 27025,
"text": "Filename: App.js"
},
{
"code": null,
"e": 27053,
"s": 27042,
"text": "Javascript"
},
{
"code": "import React, { Component } from 'react'; export default class App extends Component { // Initializing the state state = { error: false }; static getDerivedStateFromError(error) { // Changing the state to true if some error occurs return { error: true, }; } render() { return ( <React.StrictMode> <div> {this.state.error ? <div>Some error</div> : <GFGComponent />} </div> </React.StrictMode> ); }} class GFGComponent extends Component { // GFGComponent throws error as state of GFGCompnonent is not defined render() { return <h1>{this.state.heading}</h1>; }}",
"e": 27685,
"s": 27053,
"text": null
},
{
"code": null,
"e": 27801,
"s": 27688,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 27811,
"s": 27801,
"text": "npm start"
},
{
"code": null,
"e": 27819,
"s": 27811,
"text": "Output:"
},
{
"code": null,
"e": 27910,
"s": 27821,
"text": "Reference: https://reactjs.org/docs/react-component.html#static-getderivedstatefromerror"
},
{
"code": null,
"e": 27920,
"s": 27910,
"text": "ruhelaa48"
},
{
"code": null,
"e": 27929,
"s": 27920,
"text": "react-js"
},
{
"code": null,
"e": 27946,
"s": 27929,
"text": "Web Technologies"
},
{
"code": null,
"e": 28044,
"s": 27946,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28084,
"s": 28044,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28129,
"s": 28084,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28172,
"s": 28129,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28233,
"s": 28172,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28305,
"s": 28233,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 28360,
"s": 28305,
"text": "How to apply style to parent if it has child with CSS?"
},
{
"code": null,
"e": 28405,
"s": 28360,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 28446,
"s": 28405,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 28470,
"s": 28446,
"text": "REST API (Introduction)"
}
] |
Detecting COVID-19 From Chest X-Ray Images using CNN - GeeksforGeeks
|
15 Feb, 2022
A Django Based Web Application built for the purpose of detecting the presence of COVID-19 from Chest X-Ray images with multiple machine learning models trained on pre-built architectures. Three different machine learning models were used to build this project namely Xception, ResNet50, and VGG16. The Deep Learning model was trained on a publicly available dataset, the SARS-COV-2-Ct-Scan Dataset. The purpose of this project is to apply Convolutional Neural Network (CNN) Architectures in solving problems of the pandemic on a preliminary stage.
Some important libraries and technologies used are listed below
Programming Language: Python
Web Framework: Django
Machine Learning Framework: Tensorflow
Frontend Dev: HTML, CSS (BootStrap)
Essential Libraries: keras, sklearn, venv, seaborn, matplotlib
A detailed list of all the libraries can be found here.
1) Convert Dataset into Dataframe
Download the dataset from here
Convert the data into a pandas dataframe with the corresponding columnsFile [Image File]DiseaseID [Serial Number]DiseaseType [COVID, non-COVID]
File [Image File]
DiseaseID [Serial Number]
DiseaseType [COVID, non-COVID]
Python3
train_dir = 'path/to/dataset'train_data = [] for defects_id, sp in enumerate(disease_types): for file in os.listdir(os.path.join(train_dir, sp)): train_data.append(['{}/{}'.format(sp, file), defects_id, sp]) train = pd.DataFrame(train_data, columns=['File', 'DiseaseID', 'Disease Type'])
2) Read and Preprocess the Dataframe
Read the Images
Convert the Images into the standard size of (64 x 64)
Create numpy arrays for input/output X_Train & Y_Train
Normalize the RGB values by dividing with 255.
Python3
IMAGE_SIZE = 64 def read_image(filepath): return cv2.imread(os.path.join(data_dir, filepath)) def resize_image(image, image_size): return cv2.resize(image.copy(), image_size, interpolation=cv2.INTER_AREA) X_train = np.zeros((train.shape[0], IMAGE_SIZE, IMAGE_SIZE, 3)) for i, file in tqdm(enumerate(train['File'].values)): image = read_image(file) if image is not None: X_train[i] = resize_image(image, (IMAGE_SIZE, IMAGE_SIZE)) X_Train = X_train / 255. Y_train = train['DiseaseID'].valuesY_train = to_categorical(Y_train, num_classes=2)
3) Split the Dataset into Train/Validation
Split into Train, Validation datasets
Select split percentage & random state accordingly
Python3
X_train, X_val, Y_train, Y_val = train_test_split( X_Train, Y_train, test_size=0.2, random_state = 42)
4) Define Model Architecture
We are going to import three different architectures listed below :VGG16ResNet50Xception
VGG16
ResNet50
Xception
Structure of Model ArchitectureConv2D of Input Shape (3,3)ResNet50/Xception/VGG16 ArchitectureAdd a GlobalAveragePooling2D()Add a Dropout LayerFinal DenseNet Layer with relu activationFor Multiple Output add a Softmax layer
Conv2D of Input Shape (3,3)
ResNet50/Xception/VGG16 Architecture
Add a GlobalAveragePooling2D()
Add a Dropout Layer
Final DenseNet Layer with relu activation
For Multiple Output add a Softmax layer
Use an ‘adam’ optimizer, hyperparameters can be tuned accordingly
The following code proposes a sample code for building a model
Python3
def build_model(): # Use Any One of the Following Lines resnet50 = ResNet50(weights='imagenet', include_top=False) xception = Xception(weights='imagenet', include_top=False) vgg16 = VGG16(weights='imagenet', include_top=False) input = Input(shape=(SIZE, SIZE, N_ch)) x = Conv2D(3, (3, 3), padding='same')(input) # Use Any One of the Following Lines x = resnet50(x) x = xception(x) x = vgg16(x) x = GlobalAveragePooling2D()(x) x = BatchNormalization()(x) x = Dropout(0.5)(x) x = Dense(256, activation='relu')(x) x = BatchNormalization()(x) x = Dropout(0.5)(x) # multi output output = Dense(2, activation='softmax', name='root')(x) # model model = Model(input, output) optimizer = Adam(lr=0.003, beta_1=0.9, beta_2=0.999, epsilon=0.1, decay=0.0) model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['accuracy']) model.summary() return model
5) Train the Model
Call build_model() function
Use an annealer, a callback that monitors a quantity and if no improvement is seen for a ‘patience’ number of epochs, the learning rate is reduced.
Use an ImageDataGenerator to carry out real time image data augmentation
Train the model on x_train, y_train
Save the model weights in .hdf5 format and model graph in .json format
Python3
# Use Any one of the Lines Belowhdf5_save = 'ResNet50_Model.hdf5'hdf5_save = 'Xception_Model.hdf5'hdf5_save = 'VGG16_Model.hdf5' model = build_model()annealer = ReduceLROnPlateau( monitor='val_accuracy', factor=0.70, patience=5, verbose=1, min_lr=1e-4) checkpoint = ModelCheckpoint(h5f5_save, verbose=1, save_best_only=True) datagen = ImageDataGenerator(rotation_range=360, width_shift_range=0.2, height_shift_range=0.2, zoom_range=0.2, horizontal_flip=True, vertical_flip=True) datagen.fit(X_train) # Use Any one of the lines Belowmodel_graph = 'ResNet50.json'model_graph = 'Xception.json'model_graph = 'VGG16.json' model_json = model.to_json()with open(model_graph, "w") as json_file: json_file.write(model_json)
Create a Django Project with an application initialized inside it which would be using the saved model weights to predict uploaded Chest X-Ray Images
Create a basic Static Page with a form to send the image file to the backend
HTML
<form method="post" id="imageForm" enctype="multipart/form-data"> {% csrf_token %} <label for="ImgFile">Upload Image</label> <input type="file" name="ImgFile" class="form-control"/> <input type="submit" id="submitButton" class="btn" name="submit" value="Solve"/></form>
Inside the views.py folder, handle the uploaded image. Load the model files and send the response back to the front end.
The response would contain the following detailsModel PredictionConfidence ScorePrediction Duration (in s)
Model Prediction
Confidence Score
Prediction Duration (in s)
Add styling to the frontend using CSS (Bootstrap) accordingly
Note: Loading multiple models and using model.predict() takes a lot of time and it’d be much more in the absence of GPU services in the Cloud instance. For scaling this application to a higher server load consider using TensorFlow Serving
A Demo Version of the project built and tested on localhost is demonstrated in the video below
COV-CNN Demo
The project built in the previous lines cannot be directly applied, however, a lot of such applications can be built on a similar tangent for serving the purpose of preliminary medical diagnosis based on inputs of patients saving a lot of screening stage costs to the medical industry. The machine learning pipeline presented in the project can be taken up a notch by making it dynamic in nature. By adding more training data dynamically to the model and train it on them to improve its accuracy. The ML Model can be converted into a REST API making the application more robust in nature and scalable. A MySQL Database could be used for storing patient data with diagnosis details and other parameters. I’ve presented a use-sketch diagram for illustrating the architecture of the application which could be built in the near future to be applied in the medical industry.
GitHub Repository : https://github.com/dwaipayan05/CovCNN-WebApp
Google Drive Link : Notebook/Weight Files/Dataset
rkbhola5
ProGeek 2021
Machine Learning
ProGeek
Project
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Recurrent Neural Network
Support Vector Machine Algorithm
Intuition of Adam Optimizer
CNN | Introduction to Pooling Layer
Convolutional Neural Network (CNN) in Machine Learning
E-commerce Website using Django
College Management System using Django - Python Project
How to Build a Simple Note Android App using MVVM and Room Database?
Handwritten Digit Recognition using Neural Network
AI Driven Snake Game using Deep Q Learning
|
[
{
"code": null,
"e": 25615,
"s": 25587,
"text": "\n15 Feb, 2022"
},
{
"code": null,
"e": 26164,
"s": 25615,
"text": "A Django Based Web Application built for the purpose of detecting the presence of COVID-19 from Chest X-Ray images with multiple machine learning models trained on pre-built architectures. Three different machine learning models were used to build this project namely Xception, ResNet50, and VGG16. The Deep Learning model was trained on a publicly available dataset, the SARS-COV-2-Ct-Scan Dataset. The purpose of this project is to apply Convolutional Neural Network (CNN) Architectures in solving problems of the pandemic on a preliminary stage."
},
{
"code": null,
"e": 26228,
"s": 26164,
"text": "Some important libraries and technologies used are listed below"
},
{
"code": null,
"e": 26257,
"s": 26228,
"text": "Programming Language: Python"
},
{
"code": null,
"e": 26279,
"s": 26257,
"text": "Web Framework: Django"
},
{
"code": null,
"e": 26318,
"s": 26279,
"text": "Machine Learning Framework: Tensorflow"
},
{
"code": null,
"e": 26354,
"s": 26318,
"text": "Frontend Dev: HTML, CSS (BootStrap)"
},
{
"code": null,
"e": 26417,
"s": 26354,
"text": "Essential Libraries: keras, sklearn, venv, seaborn, matplotlib"
},
{
"code": null,
"e": 26473,
"s": 26417,
"text": "A detailed list of all the libraries can be found here."
},
{
"code": null,
"e": 26507,
"s": 26473,
"text": "1) Convert Dataset into Dataframe"
},
{
"code": null,
"e": 26538,
"s": 26507,
"text": "Download the dataset from here"
},
{
"code": null,
"e": 26682,
"s": 26538,
"text": "Convert the data into a pandas dataframe with the corresponding columnsFile [Image File]DiseaseID [Serial Number]DiseaseType [COVID, non-COVID]"
},
{
"code": null,
"e": 26700,
"s": 26682,
"text": "File [Image File]"
},
{
"code": null,
"e": 26726,
"s": 26700,
"text": "DiseaseID [Serial Number]"
},
{
"code": null,
"e": 26757,
"s": 26726,
"text": "DiseaseType [COVID, non-COVID]"
},
{
"code": null,
"e": 26765,
"s": 26757,
"text": "Python3"
},
{
"code": "train_dir = 'path/to/dataset'train_data = [] for defects_id, sp in enumerate(disease_types): for file in os.listdir(os.path.join(train_dir, sp)): train_data.append(['{}/{}'.format(sp, file), defects_id, sp]) train = pd.DataFrame(train_data, columns=['File', 'DiseaseID', 'Disease Type'])",
"e": 27073,
"s": 26765,
"text": null
},
{
"code": null,
"e": 27110,
"s": 27073,
"text": "2) Read and Preprocess the Dataframe"
},
{
"code": null,
"e": 27126,
"s": 27110,
"text": "Read the Images"
},
{
"code": null,
"e": 27181,
"s": 27126,
"text": "Convert the Images into the standard size of (64 x 64)"
},
{
"code": null,
"e": 27236,
"s": 27181,
"text": "Create numpy arrays for input/output X_Train & Y_Train"
},
{
"code": null,
"e": 27283,
"s": 27236,
"text": "Normalize the RGB values by dividing with 255."
},
{
"code": null,
"e": 27291,
"s": 27283,
"text": "Python3"
},
{
"code": "IMAGE_SIZE = 64 def read_image(filepath): return cv2.imread(os.path.join(data_dir, filepath)) def resize_image(image, image_size): return cv2.resize(image.copy(), image_size, interpolation=cv2.INTER_AREA) X_train = np.zeros((train.shape[0], IMAGE_SIZE, IMAGE_SIZE, 3)) for i, file in tqdm(enumerate(train['File'].values)): image = read_image(file) if image is not None: X_train[i] = resize_image(image, (IMAGE_SIZE, IMAGE_SIZE)) X_Train = X_train / 255. Y_train = train['DiseaseID'].valuesY_train = to_categorical(Y_train, num_classes=2)",
"e": 27884,
"s": 27291,
"text": null
},
{
"code": null,
"e": 27927,
"s": 27884,
"text": "3) Split the Dataset into Train/Validation"
},
{
"code": null,
"e": 27965,
"s": 27927,
"text": "Split into Train, Validation datasets"
},
{
"code": null,
"e": 28016,
"s": 27965,
"text": "Select split percentage & random state accordingly"
},
{
"code": null,
"e": 28024,
"s": 28016,
"text": "Python3"
},
{
"code": "X_train, X_val, Y_train, Y_val = train_test_split( X_Train, Y_train, test_size=0.2, random_state = 42)",
"e": 28128,
"s": 28024,
"text": null
},
{
"code": null,
"e": 28157,
"s": 28128,
"text": "4) Define Model Architecture"
},
{
"code": null,
"e": 28246,
"s": 28157,
"text": "We are going to import three different architectures listed below :VGG16ResNet50Xception"
},
{
"code": null,
"e": 28252,
"s": 28246,
"text": "VGG16"
},
{
"code": null,
"e": 28261,
"s": 28252,
"text": "ResNet50"
},
{
"code": null,
"e": 28270,
"s": 28261,
"text": "Xception"
},
{
"code": null,
"e": 28494,
"s": 28270,
"text": "Structure of Model ArchitectureConv2D of Input Shape (3,3)ResNet50/Xception/VGG16 ArchitectureAdd a GlobalAveragePooling2D()Add a Dropout LayerFinal DenseNet Layer with relu activationFor Multiple Output add a Softmax layer"
},
{
"code": null,
"e": 28522,
"s": 28494,
"text": "Conv2D of Input Shape (3,3)"
},
{
"code": null,
"e": 28559,
"s": 28522,
"text": "ResNet50/Xception/VGG16 Architecture"
},
{
"code": null,
"e": 28590,
"s": 28559,
"text": "Add a GlobalAveragePooling2D()"
},
{
"code": null,
"e": 28610,
"s": 28590,
"text": "Add a Dropout Layer"
},
{
"code": null,
"e": 28652,
"s": 28610,
"text": "Final DenseNet Layer with relu activation"
},
{
"code": null,
"e": 28692,
"s": 28652,
"text": "For Multiple Output add a Softmax layer"
},
{
"code": null,
"e": 28758,
"s": 28692,
"text": "Use an ‘adam’ optimizer, hyperparameters can be tuned accordingly"
},
{
"code": null,
"e": 28821,
"s": 28758,
"text": "The following code proposes a sample code for building a model"
},
{
"code": null,
"e": 28829,
"s": 28821,
"text": "Python3"
},
{
"code": "def build_model(): # Use Any One of the Following Lines resnet50 = ResNet50(weights='imagenet', include_top=False) xception = Xception(weights='imagenet', include_top=False) vgg16 = VGG16(weights='imagenet', include_top=False) input = Input(shape=(SIZE, SIZE, N_ch)) x = Conv2D(3, (3, 3), padding='same')(input) # Use Any One of the Following Lines x = resnet50(x) x = xception(x) x = vgg16(x) x = GlobalAveragePooling2D()(x) x = BatchNormalization()(x) x = Dropout(0.5)(x) x = Dense(256, activation='relu')(x) x = BatchNormalization()(x) x = Dropout(0.5)(x) # multi output output = Dense(2, activation='softmax', name='root')(x) # model model = Model(input, output) optimizer = Adam(lr=0.003, beta_1=0.9, beta_2=0.999, epsilon=0.1, decay=0.0) model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['accuracy']) model.summary() return model",
"e": 29829,
"s": 28829,
"text": null
},
{
"code": null,
"e": 29848,
"s": 29829,
"text": "5) Train the Model"
},
{
"code": null,
"e": 29876,
"s": 29848,
"text": "Call build_model() function"
},
{
"code": null,
"e": 30024,
"s": 29876,
"text": "Use an annealer, a callback that monitors a quantity and if no improvement is seen for a ‘patience’ number of epochs, the learning rate is reduced."
},
{
"code": null,
"e": 30097,
"s": 30024,
"text": "Use an ImageDataGenerator to carry out real time image data augmentation"
},
{
"code": null,
"e": 30133,
"s": 30097,
"text": "Train the model on x_train, y_train"
},
{
"code": null,
"e": 30204,
"s": 30133,
"text": "Save the model weights in .hdf5 format and model graph in .json format"
},
{
"code": null,
"e": 30212,
"s": 30204,
"text": "Python3"
},
{
"code": "# Use Any one of the Lines Belowhdf5_save = 'ResNet50_Model.hdf5'hdf5_save = 'Xception_Model.hdf5'hdf5_save = 'VGG16_Model.hdf5' model = build_model()annealer = ReduceLROnPlateau( monitor='val_accuracy', factor=0.70, patience=5, verbose=1, min_lr=1e-4) checkpoint = ModelCheckpoint(h5f5_save, verbose=1, save_best_only=True) datagen = ImageDataGenerator(rotation_range=360, width_shift_range=0.2, height_shift_range=0.2, zoom_range=0.2, horizontal_flip=True, vertical_flip=True) datagen.fit(X_train) # Use Any one of the lines Belowmodel_graph = 'ResNet50.json'model_graph = 'Xception.json'model_graph = 'VGG16.json' model_json = model.to_json()with open(model_graph, \"w\") as json_file: json_file.write(model_json)",
"e": 31082,
"s": 30212,
"text": null
},
{
"code": null,
"e": 31232,
"s": 31082,
"text": "Create a Django Project with an application initialized inside it which would be using the saved model weights to predict uploaded Chest X-Ray Images"
},
{
"code": null,
"e": 31309,
"s": 31232,
"text": "Create a basic Static Page with a form to send the image file to the backend"
},
{
"code": null,
"e": 31314,
"s": 31309,
"text": "HTML"
},
{
"code": "<form method=\"post\" id=\"imageForm\" enctype=\"multipart/form-data\"> {% csrf_token %} <label for=\"ImgFile\">Upload Image</label> <input type=\"file\" name=\"ImgFile\" class=\"form-control\"/> <input type=\"submit\" id=\"submitButton\" class=\"btn\" name=\"submit\" value=\"Solve\"/></form>",
"e": 31592,
"s": 31314,
"text": null
},
{
"code": null,
"e": 31713,
"s": 31592,
"text": "Inside the views.py folder, handle the uploaded image. Load the model files and send the response back to the front end."
},
{
"code": null,
"e": 31820,
"s": 31713,
"text": "The response would contain the following detailsModel PredictionConfidence ScorePrediction Duration (in s)"
},
{
"code": null,
"e": 31837,
"s": 31820,
"text": "Model Prediction"
},
{
"code": null,
"e": 31854,
"s": 31837,
"text": "Confidence Score"
},
{
"code": null,
"e": 31881,
"s": 31854,
"text": "Prediction Duration (in s)"
},
{
"code": null,
"e": 31943,
"s": 31881,
"text": "Add styling to the frontend using CSS (Bootstrap) accordingly"
},
{
"code": null,
"e": 32182,
"s": 31943,
"text": "Note: Loading multiple models and using model.predict() takes a lot of time and it’d be much more in the absence of GPU services in the Cloud instance. For scaling this application to a higher server load consider using TensorFlow Serving"
},
{
"code": null,
"e": 32277,
"s": 32182,
"text": "A Demo Version of the project built and tested on localhost is demonstrated in the video below"
},
{
"code": null,
"e": 32290,
"s": 32277,
"text": "COV-CNN Demo"
},
{
"code": null,
"e": 33161,
"s": 32290,
"text": "The project built in the previous lines cannot be directly applied, however, a lot of such applications can be built on a similar tangent for serving the purpose of preliminary medical diagnosis based on inputs of patients saving a lot of screening stage costs to the medical industry. The machine learning pipeline presented in the project can be taken up a notch by making it dynamic in nature. By adding more training data dynamically to the model and train it on them to improve its accuracy. The ML Model can be converted into a REST API making the application more robust in nature and scalable. A MySQL Database could be used for storing patient data with diagnosis details and other parameters. I’ve presented a use-sketch diagram for illustrating the architecture of the application which could be built in the near future to be applied in the medical industry."
},
{
"code": null,
"e": 33226,
"s": 33161,
"text": "GitHub Repository : https://github.com/dwaipayan05/CovCNN-WebApp"
},
{
"code": null,
"e": 33277,
"s": 33226,
"text": "Google Drive Link : Notebook/Weight Files/Dataset"
},
{
"code": null,
"e": 33286,
"s": 33277,
"text": "rkbhola5"
},
{
"code": null,
"e": 33299,
"s": 33286,
"text": "ProGeek 2021"
},
{
"code": null,
"e": 33316,
"s": 33299,
"text": "Machine Learning"
},
{
"code": null,
"e": 33324,
"s": 33316,
"text": "ProGeek"
},
{
"code": null,
"e": 33332,
"s": 33324,
"text": "Project"
},
{
"code": null,
"e": 33349,
"s": 33332,
"text": "Machine Learning"
},
{
"code": null,
"e": 33447,
"s": 33349,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33488,
"s": 33447,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 33521,
"s": 33488,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 33549,
"s": 33521,
"text": "Intuition of Adam Optimizer"
},
{
"code": null,
"e": 33585,
"s": 33549,
"text": "CNN | Introduction to Pooling Layer"
},
{
"code": null,
"e": 33640,
"s": 33585,
"text": "Convolutional Neural Network (CNN) in Machine Learning"
},
{
"code": null,
"e": 33672,
"s": 33640,
"text": "E-commerce Website using Django"
},
{
"code": null,
"e": 33728,
"s": 33672,
"text": "College Management System using Django - Python Project"
},
{
"code": null,
"e": 33797,
"s": 33728,
"text": "How to Build a Simple Note Android App using MVVM and Room Database?"
},
{
"code": null,
"e": 33848,
"s": 33797,
"text": "Handwritten Digit Recognition using Neural Network"
}
] |
How to merge lists in Scala - GeeksforGeeks
|
13 Jul, 2021
A list is a collection which contains immutable data. List represents linked list in Scala. The Scala List class holds a sequenced, linear list of items. Lists are immutable and represents a linked list.Syntax of List:
val variable_name: List[type] = List(item1, item2, item3)
or
val variable_name = List(item1, item2, item3)
Below are three different way to merge lists:
using the ++
Using :::
Using concat
Following are the various ways to merge two lists in Scala:
Example:
Scala
// Scala program to merge lists // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Creating Lists val a = List("geeks", "for", "geeks") val b = List("is", "a", "computer science", "portal") val c = List("for", "geeks") // Merging Lists val d = a ++ b ++ c println("After merging lists ") println(d) }}
After merging lists
List(geeks, for, geeks, is, a, computer science, portal, for, geeks)
In above example we are using ++ method to concatenate lists. This method is used consistently across immutable collections
If we using the List class frequently, we may prefer using ::: method.Example:
Scala
// Scala program to merging two lists // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Creating a List. val a = List("Languages", "are") val b = List("C++", "Java", "C#", "Python", "Scala") // Merging two lists val c = a ::: b println("After merging lists") println(c) }}
Example:
Scala
// Scala program merging two lists // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Creating a List. val a = List(1, 2, 3) val b = List(4, 5, 6) // concatenate two lists val c = List.concat(a, b) println("After merging lists") println(c) }}
After merging lists
List(1, 2, 3, 4, 5, 6)
gabaa406
Scala list-program
Scala-list
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Class and Object in Scala
Scala Lists
Scala Tutorial – Learn Scala with Step By Step Guide
Operators in Scala
Inheritance in Scala
Scala Constructors
Scala | Arrays
Lambda Expression in Scala
How to get the first element of List in Scala
Break statement in Scala
|
[
{
"code": null,
"e": 25205,
"s": 25177,
"text": "\n13 Jul, 2021"
},
{
"code": null,
"e": 25426,
"s": 25205,
"text": "A list is a collection which contains immutable data. List represents linked list in Scala. The Scala List class holds a sequenced, linear list of items. Lists are immutable and represents a linked list.Syntax of List: "
},
{
"code": null,
"e": 25533,
"s": 25426,
"text": "val variable_name: List[type] = List(item1, item2, item3)\nor\nval variable_name = List(item1, item2, item3)"
},
{
"code": null,
"e": 25581,
"s": 25533,
"text": "Below are three different way to merge lists: "
},
{
"code": null,
"e": 25594,
"s": 25581,
"text": "using the ++"
},
{
"code": null,
"e": 25604,
"s": 25594,
"text": "Using :::"
},
{
"code": null,
"e": 25617,
"s": 25604,
"text": "Using concat"
},
{
"code": null,
"e": 25678,
"s": 25617,
"text": "Following are the various ways to merge two lists in Scala: "
},
{
"code": null,
"e": 25689,
"s": 25678,
"text": "Example: "
},
{
"code": null,
"e": 25695,
"s": 25689,
"text": "Scala"
},
{
"code": "// Scala program to merge lists // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Creating Lists val a = List(\"geeks\", \"for\", \"geeks\") val b = List(\"is\", \"a\", \"computer science\", \"portal\") val c = List(\"for\", \"geeks\") // Merging Lists val d = a ++ b ++ c println(\"After merging lists \") println(d) }} ",
"e": 26110,
"s": 25695,
"text": null
},
{
"code": null,
"e": 26200,
"s": 26110,
"text": "After merging lists \nList(geeks, for, geeks, is, a, computer science, portal, for, geeks)"
},
{
"code": null,
"e": 26329,
"s": 26202,
"text": "In above example we are using ++ method to concatenate lists. This method is used consistently across immutable collections "
},
{
"code": null,
"e": 26410,
"s": 26329,
"text": "If we using the List class frequently, we may prefer using ::: method.Example: "
},
{
"code": null,
"e": 26416,
"s": 26410,
"text": "Scala"
},
{
"code": "// Scala program to merging two lists // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Creating a List. val a = List(\"Languages\", \"are\") val b = List(\"C++\", \"Java\", \"C#\", \"Python\", \"Scala\") // Merging two lists val c = a ::: b println(\"After merging lists\") println(c) }} ",
"e": 26805,
"s": 26416,
"text": null
},
{
"code": null,
"e": 26819,
"s": 26809,
"text": "Example: "
},
{
"code": null,
"e": 26825,
"s": 26819,
"text": "Scala"
},
{
"code": "// Scala program merging two lists // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Creating a List. val a = List(1, 2, 3) val b = List(4, 5, 6) // concatenate two lists val c = List.concat(a, b) println(\"After merging lists\") println(c) }} ",
"e": 27170,
"s": 26825,
"text": null
},
{
"code": null,
"e": 27213,
"s": 27170,
"text": "After merging lists\nList(1, 2, 3, 4, 5, 6)"
},
{
"code": null,
"e": 27224,
"s": 27215,
"text": "gabaa406"
},
{
"code": null,
"e": 27243,
"s": 27224,
"text": "Scala list-program"
},
{
"code": null,
"e": 27254,
"s": 27243,
"text": "Scala-list"
},
{
"code": null,
"e": 27260,
"s": 27254,
"text": "Scala"
},
{
"code": null,
"e": 27358,
"s": 27260,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27384,
"s": 27358,
"text": "Class and Object in Scala"
},
{
"code": null,
"e": 27396,
"s": 27384,
"text": "Scala Lists"
},
{
"code": null,
"e": 27449,
"s": 27396,
"text": "Scala Tutorial – Learn Scala with Step By Step Guide"
},
{
"code": null,
"e": 27468,
"s": 27449,
"text": "Operators in Scala"
},
{
"code": null,
"e": 27489,
"s": 27468,
"text": "Inheritance in Scala"
},
{
"code": null,
"e": 27508,
"s": 27489,
"text": "Scala Constructors"
},
{
"code": null,
"e": 27523,
"s": 27508,
"text": "Scala | Arrays"
},
{
"code": null,
"e": 27550,
"s": 27523,
"text": "Lambda Expression in Scala"
},
{
"code": null,
"e": 27596,
"s": 27550,
"text": "How to get the first element of List in Scala"
}
] |
How I got Matplotlib to plot Apple Color Emojis | by Brienna Herold | Towards Data Science
|
If you try to plot emojis, you might see something like this:
Although we explicitly specified it as the font, these emojis are not Apple Color Emoji. They are from the font DejaVu Sans, the default font that took over after Matplotlib failed to process our specified font, throwing the following error:
RuntimeError: In FT2Font: Could not set the fontsize.
A few of many related questions on Stack Overflow about plotting emojis in Matplotlib:
How to plot (high quality) emoji in matplotlib?
matplotlib: annotate plot with Emoji labels
Emoji in Matplotlib figures on OS X
Emojis in matplotlibs xticks
Could not load the emoji font in Matplotlib
All remain unanswered. It simply cannot be done with recent versions of Matplotlib. A look at Matplotlib’s GitHub repo reveals Issues #3135, #4492, and #12830, the first of which has been open for almost eight years as of 2022.
Why can’t Matplotlib plot emojis from the Apple Color Emoji font? How can we overcome this lack of functionality to get the emojis plotted? This post answers these questions.
Apple Color Emoji is a TrueType Collection (TTC) file. This format combines multiple fonts into a single file, to save space. FT2Font, the dependency which threw that runtime error we saw earlier, only supports getting the first font from a TTC file. While this might work, limitations of the conversion dependency, ttconv, prevent the backends from actually using this font.
There’s a solution coming in the form of pull request #9787. It currently awaits further review.
While we wait for the pull request to be merged, there exists an immediate solution in which we can successfully plot emojis using Matplotlib.
Enter Mplcairo. A “new, essentially complete implementation of a cairo backend for Matplotlib,” Mplcairo improves on several points in the original backend. Most notably, Mplcairo introduces support for using the first font in a TTC file.
It seems like we should be able to easily install Mplcairo via pip install mplcairo, but for me this installation continued to throw errors when I tried to import it into my code.
Instead, I git cloned the repo onto my machine (git clone https://github.com/matplotlib/mplcairo.git), and then followed the build and installation instructions. I summarize my process below.
Since wheels are not available for OS X, we need to build the OS X wheel ourselves using Terminal. To do this, we need the following dependencies:
C++ compiler with C++17 support, e.g. GCC ≥ 7.2 or Clang ≥ 5.0. I installed the latter using brew install llvm.
Cairo and FreeType headers, and pkg-config information to locate them. Since cairo introduced color support for emojis in version 1.15.8, we need a cairo version no earlier than that. Until conda-forge updates its cairo, brew install cairo. Then pip install pycairo.
Once we have acquired the dependencies, we can activate llvm (as documented by brew info llvm) and build the OS X wheels, while in the root folder of mplcairo:
echo 'export PATH="/usr/local/opt/llvm/bin:$PATH"' >> ~/.bash_profile source ~/.bash_profileexport LDFLAGS="-L/usr/local/opt/llvm/lib"export CPPFLAGS="-I/usr/local/opt/llvm/include"export CC='/usr/local/opt/llvm/bin/clang'export CXX='/usr/local/opt/llvm/bin/clang++'tools/build-macos-wheel.sh
Now that we’ve built Mplcairo, we can install it systemwide (or in our virtual environment) with pip install dist/mplcairo-0.1.post47+g109b19f-cp37-cp37m-macosx_10_9_x86_64.whl.
This might be an anomaly, but while building in Terminal, my Python downgraded from version 3.7.0 to 3.6.5. When I opened a new Terminal window, Python was at 3.7.0 again and I was able to install the wheel.
Note (August 16, 2020): Confirm that tools/build-macos-wheel.sh and dist/mplcairo-0.1.post47+g109b19f-cp37-cp37m-macosx_10_9_x86_64.whl are the correct filepaths — when I first published this article in 2018, they were named differently.
To plot our emojis, we simply import Mplcairo and set it as the new backend of Matplotlib.
import matplotlib, mplcairoprint('Default backend: ' + matplotlib.get_backend()) matplotlib.use("module://mplcairo.macosx")print('Backend is now ' + matplotlib.get_backend())
After running the script above, you should see this output:
Default backend: module://ipykernel.pylab.backend_inlineBackend is now module://mplcairo.macosx
Your default backend may differ depending on where you are running your script. My default backend is from Jupyter Notebook. (If you are using Jupyter Notebook, you must reset the kernel before you can reset the backend. You also must reset the backend before importing matplotlib.pyplot.)
Once you get Mplcairo up and running, Matplotlib plots emojis beautifully.
Complete code:
If you’d like to read more of my articles or explore millions of other articles, you can sign up for Medium membership:
brienna.medium.com
You can also subscribe to my email list to get notified whenever I publish a new article:
brienna.medium.com
Some other stories from me that might interest you:
|
[
{
"code": null,
"e": 234,
"s": 172,
"text": "If you try to plot emojis, you might see something like this:"
},
{
"code": null,
"e": 476,
"s": 234,
"text": "Although we explicitly specified it as the font, these emojis are not Apple Color Emoji. They are from the font DejaVu Sans, the default font that took over after Matplotlib failed to process our specified font, throwing the following error:"
},
{
"code": null,
"e": 530,
"s": 476,
"text": "RuntimeError: In FT2Font: Could not set the fontsize."
},
{
"code": null,
"e": 617,
"s": 530,
"text": "A few of many related questions on Stack Overflow about plotting emojis in Matplotlib:"
},
{
"code": null,
"e": 665,
"s": 617,
"text": "How to plot (high quality) emoji in matplotlib?"
},
{
"code": null,
"e": 709,
"s": 665,
"text": "matplotlib: annotate plot with Emoji labels"
},
{
"code": null,
"e": 745,
"s": 709,
"text": "Emoji in Matplotlib figures on OS X"
},
{
"code": null,
"e": 774,
"s": 745,
"text": "Emojis in matplotlibs xticks"
},
{
"code": null,
"e": 818,
"s": 774,
"text": "Could not load the emoji font in Matplotlib"
},
{
"code": null,
"e": 1046,
"s": 818,
"text": "All remain unanswered. It simply cannot be done with recent versions of Matplotlib. A look at Matplotlib’s GitHub repo reveals Issues #3135, #4492, and #12830, the first of which has been open for almost eight years as of 2022."
},
{
"code": null,
"e": 1221,
"s": 1046,
"text": "Why can’t Matplotlib plot emojis from the Apple Color Emoji font? How can we overcome this lack of functionality to get the emojis plotted? This post answers these questions."
},
{
"code": null,
"e": 1597,
"s": 1221,
"text": "Apple Color Emoji is a TrueType Collection (TTC) file. This format combines multiple fonts into a single file, to save space. FT2Font, the dependency which threw that runtime error we saw earlier, only supports getting the first font from a TTC file. While this might work, limitations of the conversion dependency, ttconv, prevent the backends from actually using this font."
},
{
"code": null,
"e": 1694,
"s": 1597,
"text": "There’s a solution coming in the form of pull request #9787. It currently awaits further review."
},
{
"code": null,
"e": 1837,
"s": 1694,
"text": "While we wait for the pull request to be merged, there exists an immediate solution in which we can successfully plot emojis using Matplotlib."
},
{
"code": null,
"e": 2076,
"s": 1837,
"text": "Enter Mplcairo. A “new, essentially complete implementation of a cairo backend for Matplotlib,” Mplcairo improves on several points in the original backend. Most notably, Mplcairo introduces support for using the first font in a TTC file."
},
{
"code": null,
"e": 2256,
"s": 2076,
"text": "It seems like we should be able to easily install Mplcairo via pip install mplcairo, but for me this installation continued to throw errors when I tried to import it into my code."
},
{
"code": null,
"e": 2448,
"s": 2256,
"text": "Instead, I git cloned the repo onto my machine (git clone https://github.com/matplotlib/mplcairo.git), and then followed the build and installation instructions. I summarize my process below."
},
{
"code": null,
"e": 2595,
"s": 2448,
"text": "Since wheels are not available for OS X, we need to build the OS X wheel ourselves using Terminal. To do this, we need the following dependencies:"
},
{
"code": null,
"e": 2707,
"s": 2595,
"text": "C++ compiler with C++17 support, e.g. GCC ≥ 7.2 or Clang ≥ 5.0. I installed the latter using brew install llvm."
},
{
"code": null,
"e": 2974,
"s": 2707,
"text": "Cairo and FreeType headers, and pkg-config information to locate them. Since cairo introduced color support for emojis in version 1.15.8, we need a cairo version no earlier than that. Until conda-forge updates its cairo, brew install cairo. Then pip install pycairo."
},
{
"code": null,
"e": 3134,
"s": 2974,
"text": "Once we have acquired the dependencies, we can activate llvm (as documented by brew info llvm) and build the OS X wheels, while in the root folder of mplcairo:"
},
{
"code": null,
"e": 3442,
"s": 3134,
"text": "echo 'export PATH=\"/usr/local/opt/llvm/bin:$PATH\"' >> ~/.bash_profile source ~/.bash_profileexport LDFLAGS=\"-L/usr/local/opt/llvm/lib\"export CPPFLAGS=\"-I/usr/local/opt/llvm/include\"export CC='/usr/local/opt/llvm/bin/clang'export CXX='/usr/local/opt/llvm/bin/clang++'tools/build-macos-wheel.sh"
},
{
"code": null,
"e": 3620,
"s": 3442,
"text": "Now that we’ve built Mplcairo, we can install it systemwide (or in our virtual environment) with pip install dist/mplcairo-0.1.post47+g109b19f-cp37-cp37m-macosx_10_9_x86_64.whl."
},
{
"code": null,
"e": 3828,
"s": 3620,
"text": "This might be an anomaly, but while building in Terminal, my Python downgraded from version 3.7.0 to 3.6.5. When I opened a new Terminal window, Python was at 3.7.0 again and I was able to install the wheel."
},
{
"code": null,
"e": 4066,
"s": 3828,
"text": "Note (August 16, 2020): Confirm that tools/build-macos-wheel.sh and dist/mplcairo-0.1.post47+g109b19f-cp37-cp37m-macosx_10_9_x86_64.whl are the correct filepaths — when I first published this article in 2018, they were named differently."
},
{
"code": null,
"e": 4157,
"s": 4066,
"text": "To plot our emojis, we simply import Mplcairo and set it as the new backend of Matplotlib."
},
{
"code": null,
"e": 4332,
"s": 4157,
"text": "import matplotlib, mplcairoprint('Default backend: ' + matplotlib.get_backend()) matplotlib.use(\"module://mplcairo.macosx\")print('Backend is now ' + matplotlib.get_backend())"
},
{
"code": null,
"e": 4392,
"s": 4332,
"text": "After running the script above, you should see this output:"
},
{
"code": null,
"e": 4488,
"s": 4392,
"text": "Default backend: module://ipykernel.pylab.backend_inlineBackend is now module://mplcairo.macosx"
},
{
"code": null,
"e": 4778,
"s": 4488,
"text": "Your default backend may differ depending on where you are running your script. My default backend is from Jupyter Notebook. (If you are using Jupyter Notebook, you must reset the kernel before you can reset the backend. You also must reset the backend before importing matplotlib.pyplot.)"
},
{
"code": null,
"e": 4853,
"s": 4778,
"text": "Once you get Mplcairo up and running, Matplotlib plots emojis beautifully."
},
{
"code": null,
"e": 4868,
"s": 4853,
"text": "Complete code:"
},
{
"code": null,
"e": 4988,
"s": 4868,
"text": "If you’d like to read more of my articles or explore millions of other articles, you can sign up for Medium membership:"
},
{
"code": null,
"e": 5007,
"s": 4988,
"text": "brienna.medium.com"
},
{
"code": null,
"e": 5097,
"s": 5007,
"text": "You can also subscribe to my email list to get notified whenever I publish a new article:"
},
{
"code": null,
"e": 5116,
"s": 5097,
"text": "brienna.medium.com"
}
] |
How to determine if running on a rooted device or not in Android?
|
In some cases, we should not allow application should run on rooted devices for payment gateways. This example demonstrates how to determine if running on a rooted device or not.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:id = "@+id/parent"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity"
android:gravity = "center"
android:orientation = "vertical">
<TextView
android:id = "@+id/rootFinder"
android:layout_margin = "20dp"
android:textAlignment = "center"
android:layout_width = "match_parent"
android:layout_height = "wrap_content" />
</LinearLayout>
In the above code, we have taken a text view. It contains information about root.
Step 3 − Add the following code to src/MainActivity.java
package com.example.andy.myapplication;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
int view = R.layout.activity_main;
TextView rootFinder;
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(view);
rootFinder = findViewById(R.id.rootFinder);
executeShellCommand("su");
}
private void executeShellCommand(String su) {
Process process = null;
try {
process = Runtime.getRuntime().exec(su);
rootFinder.setText("It is rooted device");
Toast.makeText(MainActivity.this, "It is rooted device", Toast.LENGTH_LONG).show();
} catch (Exception e) {
rootFinder.setText("It is not rooted device");
} finally {
if (process ! = null) {
try {
process.destroy();
} catch (Exception e) { }
}
}
}
}
In the above code, we are testing device is rooted or not and appending text to the text view. To check android device is rooted or not, use the following code-
executeShellCommand("su");
..........................................................................................
private void executeShellCommand(String su) {
Process process = null;
try {
process = Runtime.getRuntime().exec(su);
rootFinder.setText("It is rooted device");
Toast.makeText(MainActivity.this, "It is rooted device", Toast.LENGTH_LONG).show();
} catch (Exception e) {
rootFinder.setText("It is not rooted device");
} finally {
if (process ! = null) {
try {
process.destroy();
} catch (Exception e) { }
}
}
}
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 shown, out device is not yet rooted.
Click here to download the project code
|
[
{
"code": null,
"e": 1241,
"s": 1062,
"text": "In some cases, we should not allow application should run on rooted devices for payment gateways. This example demonstrates how to determine if running on a rooted device or not."
},
{
"code": null,
"e": 1370,
"s": 1241,
"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": 1435,
"s": 1370,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2054,
"s": 1435,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n android:id = \"@+id/parent\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\"\n android:gravity = \"center\"\n android:orientation = \"vertical\">\n <TextView\n android:id = \"@+id/rootFinder\"\n android:layout_margin = \"20dp\"\n android:textAlignment = \"center\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\" />\n</LinearLayout>"
},
{
"code": null,
"e": 2136,
"s": 2054,
"text": "In the above code, we have taken a text view. It contains information about root."
},
{
"code": null,
"e": 2193,
"s": 2136,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3377,
"s": 2193,
"text": "package com.example.andy.myapplication;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.RequiresApi;\nimport android.support.v7.app.AppCompatActivity;\nimport android.widget.TextView;\nimport android.widget.Toast;\npublic class MainActivity extends AppCompatActivity {\n int view = R.layout.activity_main;\n TextView rootFinder;\n @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(view);\n rootFinder = findViewById(R.id.rootFinder);\n executeShellCommand(\"su\");\n }\n private void executeShellCommand(String su) {\n Process process = null;\n try {\n process = Runtime.getRuntime().exec(su);\n rootFinder.setText(\"It is rooted device\");\n Toast.makeText(MainActivity.this, \"It is rooted device\", Toast.LENGTH_LONG).show();\n } catch (Exception e) {\n rootFinder.setText(\"It is not rooted device\");\n } finally {\n if (process ! = null) {\n try {\n process.destroy();\n } catch (Exception e) { }\n }\n }\n }\n}"
},
{
"code": null,
"e": 3538,
"s": 3377,
"text": "In the above code, we are testing device is rooted or not and appending text to the text view. To check android device is rooted or not, use the following code-"
},
{
"code": null,
"e": 4146,
"s": 3538,
"text": "executeShellCommand(\"su\");\n\n..........................................................................................\nprivate void executeShellCommand(String su) {\n Process process = null;\n try {\n process = Runtime.getRuntime().exec(su);\n rootFinder.setText(\"It is rooted device\");\n Toast.makeText(MainActivity.this, \"It is rooted device\", Toast.LENGTH_LONG).show();\n } catch (Exception e) {\n rootFinder.setText(\"It is not rooted device\");\n } finally {\n if (process ! = null) {\n try {\n process.destroy();\n } catch (Exception e) { }\n }\n }\n}"
},
{
"code": null,
"e": 4493,
"s": 4146,
"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": 4550,
"s": 4493,
"text": "In the above result shown, out device is not yet rooted."
},
{
"code": null,
"e": 4590,
"s": 4550,
"text": "Click here to download the project code"
}
] |
How to get Wi-Fi connected state in android?
|
This example demonstrates How to get Wi-Fi connected state in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:app = "http://schemas.android.com/apk/res-auto"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:gravity = "center"
android:layout_height = "match_parent"
tools:context = ".MainActivity">
<TextView
android:id = "@+id/text"
android:textSize = "30sp"
android:layout_width = "match_parent"
android:layout_height = "match_parent" />
</LinearLayout>
In the above code, we have taken text view to show wifi connected state.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textView;
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text);
ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
textView.setText("" + networkInfo.getDetailedState());
}
@Override
protected void onStop() {
super.onStop();
}
@Override
protected void onResume() {
super.onResume();
}
}
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 = "com.example.myapplication">
<uses-permission android:name = "android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name = "android.permission.ACCESS_WIFI_STATE" />
<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" />
<action android:name = "android.net.conn.CONNECTIVITY_CHANGE" />
<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 the android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code
|
[
{
"code": null,
"e": 1133,
"s": 1062,
"text": "This example demonstrates How to get Wi-Fi connected state in android."
},
{
"code": null,
"e": 1262,
"s": 1133,
"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": 1327,
"s": 1262,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1887,
"s": 1327,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout 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:gravity = \"center\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\">\n <TextView\n android:id = \"@+id/text\"\n android:textSize = \"30sp\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\" />\n</LinearLayout>"
},
{
"code": null,
"e": 1960,
"s": 1887,
"text": "In the above code, we have taken text view to show wifi connected state."
},
{
"code": null,
"e": 2017,
"s": 1960,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3069,
"s": 2017,
"text": "package com.example.myapplication;\nimport android.content.Context;\nimport android.net.ConnectivityManager;\nimport android.net.NetworkInfo;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.RequiresApi;\nimport android.support.v7.app.AppCompatActivity;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n TextView textView;\n @RequiresApi(api = Build.VERSION_CODES.N)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n textView = findViewById(R.id.text);\n ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);\n NetworkInfo networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);\n textView.setText(\"\" + networkInfo.getDetailedState());\n }\n @Override\n protected void onStop() {\n super.onStop();\n }\n @Override\n protected void onResume() {\n super.onResume();\n }\n}"
},
{
"code": null,
"e": 3124,
"s": 3069,
"text": "Step 4 − Add the following code to AndroidManifest.xml"
},
{
"code": null,
"e": 4068,
"s": 3124,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\"\n package = \"com.example.myapplication\">\n <uses-permission android:name = \"android.permission.ACCESS_NETWORK_STATE\" />\n <uses-permission android:name = \"android.permission.ACCESS_WIFI_STATE\" />\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 <action android:name = \"android.net.conn.CONNECTIVITY_CHANGE\" />\n <category android:name = \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 4419,
"s": 4068,
"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 the 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": 4459,
"s": 4419,
"text": "Click here to download the project code"
}
] |
Java NIO - Path
|
As name suggests Path is the particular location of an entity such as file or a directory in a file system so that one can search and access it at that particular location.
Technically in terms of Java, Path is an interface which is introduced in Java NIO file package during Java version 7,and is the representation of location in particular file system.As path interface is in Java NIO package so it get its qualified name as java.nio.file.Path.
In general path of an entity could be of two types one is absolute path and other is relative path.As name of both paths suggests that absolute path is the location address from the root to the entity where it locates while relative path is the location address which is relative to some other path.Path uses delimiters in its definition as "\" for Windows and "/" for unix operating systems.
In order to get the instance of Path we can use static method of java.nio.file.Paths class get().This method converts a path string, or a sequence of strings that when joined form a path string, to a Path instance.This method also throws runtime InvalidPathException if the arguments passed contains illegal characters.
As mentioned above absolute path is retrieved by passing root element and the complete directory list required to locate the file.While relative path could be retrieved by combining the base path with the relative path.Retrieval of both paths would be illustrated in following example
package com.java.nio;
import java.io.IOException;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.file.FileSystem;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
public class PathDemo {
public static void main(String[] args) throws IOException {
Path relative = Paths.get("file2.txt");
System.out.println("Relative path: " + relative);
Path absolute = relative.toAbsolutePath();
System.out.println("Absolute path: " + absolute);
}
}
So far we know that what is path interface why do we need that and how could we access it.Now we would know what are the important methods which Path interface provide us.
getFileName() − Returns the file system that created this object.
getFileName() − Returns the file system that created this object.
getName() − Returns a name element of this path as a Path object.
getName() − Returns a name element of this path as a Path object.
getNameCount() − Returns the number of name elements in the path.
getNameCount() − Returns the number of name elements in the path.
subpath() − Returns a relative Path that is a subsequence of the name elements of this path.
subpath() − Returns a relative Path that is a subsequence of the name elements of this path.
getParent() − Returns the parent path, or null if this path does not have a parent.
getParent() − Returns the parent path, or null if this path does not have a parent.
getRoot() − Returns the root component of this path as a Path object, or null if this path does not have a root component.
getRoot() − Returns the root component of this path as a Path object, or null if this path does not have a root component.
toAbsolutePath() − Returns a Path object representing the absolute path of this path.
toAbsolutePath() − Returns a Path object representing the absolute path of this path.
toRealPath() − Returns the real path of an existing file.
toRealPath() − Returns the real path of an existing file.
toFile() − Returns a File object representing this path.
toFile() − Returns a File object representing this path.
normalize() − Returns a path that is this path with redundant name elements eliminated.
normalize() − Returns a path that is this path with redundant name elements eliminated.
compareTo(Path other) − Compares two abstract paths lexicographically.This method returns zero if the argument is equal to this path, a value less than zero if this path is lexicographically less than the argument, or a value greater than zero if this path is lexicographically greater than the argument.
compareTo(Path other) − Compares two abstract paths lexicographically.This method returns zero if the argument is equal to this path, a value less than zero if this path is lexicographically less than the argument, or a value greater than zero if this path is lexicographically greater than the argument.
endsWith(Path other) − Tests if this path ends with the given path.If the given path has N elements, and no root component, and this path has N or more elements, then this path ends with the given path if the last N elements of each path, starting at the element farthest from the root, are equal.
endsWith(Path other) − Tests if this path ends with the given path.If the given path has N elements, and no root component, and this path has N or more elements, then this path ends with the given path if the last N elements of each path, starting at the element farthest from the root, are equal.
endsWith(String other) − Tests if this path ends with a Path, constructed by converting the given path string, in exactly the manner specified by the endsWith(Path) method.
endsWith(String other) − Tests if this path ends with a Path, constructed by converting the given path string, in exactly the manner specified by the endsWith(Path) method.
Following example illustartes the different methods of Path interface which are mentioned above −
package com.java.nio;
import java.io.IOException;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.file.FileSystem;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
public class PathDemo {
public static void main(String[] args) throws IOException {
Path path = Paths.get("D:/workspace/ContentW/Saurav_CV.docx");
FileSystem fs = path.getFileSystem();
System.out.println(fs.toString());
System.out.println(path.isAbsolute());
System.out.println(path.getFileName());
System.out.println(path.toAbsolutePath().toString());
System.out.println(path.getRoot());
System.out.println(path.getParent());
System.out.println(path.getNameCount());
System.out.println(path.getName(0));
System.out.println(path.subpath(0, 2));
System.out.println(path.toString());
System.out.println(path.getNameCount());
Path realPath = path.toRealPath(LinkOption.NOFOLLOW_LINKS);
System.out.println(realPath.toString());
String originalPath = "d:\\data\\projects\\a-project\\..\\another-project";
Path path1 = Paths.get(originalPath);
Path path2 = path1.normalize();
System.out.println("path2 = " + path2);
}
}
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2157,
"s": 1984,
"text": "As name suggests Path is the particular location of an entity such as file or a directory in a file system so that one can search and access it at that particular location."
},
{
"code": null,
"e": 2432,
"s": 2157,
"text": "Technically in terms of Java, Path is an interface which is introduced in Java NIO file package during Java version 7,and is the representation of location in particular file system.As path interface is in Java NIO package so it get its qualified name as java.nio.file.Path."
},
{
"code": null,
"e": 2825,
"s": 2432,
"text": "In general path of an entity could be of two types one is absolute path and other is relative path.As name of both paths suggests that absolute path is the location address from the root to the entity where it locates while relative path is the location address which is relative to some other path.Path uses delimiters in its definition as \"\\\" for Windows and \"/\" for unix operating systems."
},
{
"code": null,
"e": 3146,
"s": 2825,
"text": "In order to get the instance of Path we can use static method of java.nio.file.Paths class get().This method converts a path string, or a sequence of strings that when joined form a path string, to a Path instance.This method also throws runtime InvalidPathException if the arguments passed contains illegal characters."
},
{
"code": null,
"e": 3431,
"s": 3146,
"text": "As mentioned above absolute path is retrieved by passing root element and the complete directory list required to locate the file.While relative path could be retrieved by combining the base path with the relative path.Retrieval of both paths would be illustrated in following example"
},
{
"code": null,
"e": 3955,
"s": 3431,
"text": "package com.java.nio;\nimport java.io.IOException;\nimport java.nio.Buffer;\nimport java.nio.ByteBuffer;\nimport java.nio.file.FileSystem;\nimport java.nio.file.LinkOption;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\npublic class PathDemo {\n public static void main(String[] args) throws IOException {\n Path relative = Paths.get(\"file2.txt\");\n System.out.println(\"Relative path: \" + relative);\n Path absolute = relative.toAbsolutePath();\n System.out.println(\"Absolute path: \" + absolute);\n }\n}"
},
{
"code": null,
"e": 4127,
"s": 3955,
"text": "So far we know that what is path interface why do we need that and how could we access it.Now we would know what are the important methods which Path interface provide us."
},
{
"code": null,
"e": 4193,
"s": 4127,
"text": "getFileName() − Returns the file system that created this object."
},
{
"code": null,
"e": 4259,
"s": 4193,
"text": "getFileName() − Returns the file system that created this object."
},
{
"code": null,
"e": 4325,
"s": 4259,
"text": "getName() − Returns a name element of this path as a Path object."
},
{
"code": null,
"e": 4391,
"s": 4325,
"text": "getName() − Returns a name element of this path as a Path object."
},
{
"code": null,
"e": 4458,
"s": 4391,
"text": "getNameCount() − Returns the number of name elements in the path."
},
{
"code": null,
"e": 4525,
"s": 4458,
"text": "getNameCount() − Returns the number of name elements in the path."
},
{
"code": null,
"e": 4618,
"s": 4525,
"text": "subpath() − Returns a relative Path that is a subsequence of the name elements of this path."
},
{
"code": null,
"e": 4711,
"s": 4618,
"text": "subpath() − Returns a relative Path that is a subsequence of the name elements of this path."
},
{
"code": null,
"e": 4795,
"s": 4711,
"text": "getParent() − Returns the parent path, or null if this path does not have a parent."
},
{
"code": null,
"e": 4879,
"s": 4795,
"text": "getParent() − Returns the parent path, or null if this path does not have a parent."
},
{
"code": null,
"e": 5002,
"s": 4879,
"text": "getRoot() − Returns the root component of this path as a Path object, or null if this path does not have a root component."
},
{
"code": null,
"e": 5125,
"s": 5002,
"text": "getRoot() − Returns the root component of this path as a Path object, or null if this path does not have a root component."
},
{
"code": null,
"e": 5211,
"s": 5125,
"text": "toAbsolutePath() − Returns a Path object representing the absolute path of this path."
},
{
"code": null,
"e": 5297,
"s": 5211,
"text": "toAbsolutePath() − Returns a Path object representing the absolute path of this path."
},
{
"code": null,
"e": 5355,
"s": 5297,
"text": "toRealPath() − Returns the real path of an existing file."
},
{
"code": null,
"e": 5413,
"s": 5355,
"text": "toRealPath() − Returns the real path of an existing file."
},
{
"code": null,
"e": 5470,
"s": 5413,
"text": "toFile() − Returns a File object representing this path."
},
{
"code": null,
"e": 5527,
"s": 5470,
"text": "toFile() − Returns a File object representing this path."
},
{
"code": null,
"e": 5615,
"s": 5527,
"text": "normalize() − Returns a path that is this path with redundant name elements eliminated."
},
{
"code": null,
"e": 5703,
"s": 5615,
"text": "normalize() − Returns a path that is this path with redundant name elements eliminated."
},
{
"code": null,
"e": 6008,
"s": 5703,
"text": "compareTo(Path other) − Compares two abstract paths lexicographically.This method returns zero if the argument is equal to this path, a value less than zero if this path is lexicographically less than the argument, or a value greater than zero if this path is lexicographically greater than the argument."
},
{
"code": null,
"e": 6313,
"s": 6008,
"text": "compareTo(Path other) − Compares two abstract paths lexicographically.This method returns zero if the argument is equal to this path, a value less than zero if this path is lexicographically less than the argument, or a value greater than zero if this path is lexicographically greater than the argument."
},
{
"code": null,
"e": 6611,
"s": 6313,
"text": "endsWith(Path other) − Tests if this path ends with the given path.If the given path has N elements, and no root component, and this path has N or more elements, then this path ends with the given path if the last N elements of each path, starting at the element farthest from the root, are equal."
},
{
"code": null,
"e": 6909,
"s": 6611,
"text": "endsWith(Path other) − Tests if this path ends with the given path.If the given path has N elements, and no root component, and this path has N or more elements, then this path ends with the given path if the last N elements of each path, starting at the element farthest from the root, are equal."
},
{
"code": null,
"e": 7082,
"s": 6909,
"text": "endsWith(String other) − Tests if this path ends with a Path, constructed by converting the given path string, in exactly the manner specified by the endsWith(Path) method."
},
{
"code": null,
"e": 7255,
"s": 7082,
"text": "endsWith(String other) − Tests if this path ends with a Path, constructed by converting the given path string, in exactly the manner specified by the endsWith(Path) method."
},
{
"code": null,
"e": 7353,
"s": 7255,
"text": "Following example illustartes the different methods of Path interface which are mentioned above −"
},
{
"code": null,
"e": 8611,
"s": 7353,
"text": "package com.java.nio;\nimport java.io.IOException;\nimport java.nio.Buffer;\nimport java.nio.ByteBuffer;\nimport java.nio.file.FileSystem;\nimport java.nio.file.LinkOption;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\npublic class PathDemo {\n public static void main(String[] args) throws IOException {\n Path path = Paths.get(\"D:/workspace/ContentW/Saurav_CV.docx\");\n FileSystem fs = path.getFileSystem();\n System.out.println(fs.toString());\n System.out.println(path.isAbsolute());\n System.out.println(path.getFileName());\n System.out.println(path.toAbsolutePath().toString());\n System.out.println(path.getRoot());\n System.out.println(path.getParent());\n System.out.println(path.getNameCount());\n System.out.println(path.getName(0));\n System.out.println(path.subpath(0, 2));\n System.out.println(path.toString());\n System.out.println(path.getNameCount());\n Path realPath = path.toRealPath(LinkOption.NOFOLLOW_LINKS);\n System.out.println(realPath.toString());\n String originalPath = \"d:\\\\data\\\\projects\\\\a-project\\\\..\\\\another-project\";\n Path path1 = Paths.get(originalPath);\n Path path2 = path1.normalize();\n System.out.println(\"path2 = \" + path2);\n }\n}"
},
{
"code": null,
"e": 8644,
"s": 8611,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 8660,
"s": 8644,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 8693,
"s": 8660,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 8709,
"s": 8693,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 8744,
"s": 8709,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8758,
"s": 8744,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 8792,
"s": 8758,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 8806,
"s": 8792,
"text": " Tushar Kale"
},
{
"code": null,
"e": 8843,
"s": 8806,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 8858,
"s": 8843,
"text": " Monica Mittal"
},
{
"code": null,
"e": 8891,
"s": 8858,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 8910,
"s": 8891,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 8917,
"s": 8910,
"text": " Print"
},
{
"code": null,
"e": 8928,
"s": 8917,
"text": " Add Notes"
}
] |
Counting number of elements in an array in Julia - count() Method - GeeksforGeeks
|
26 Mar, 2020
The count() is an inbuilt function in julia which is used to count the number of elements in the specified array for which the given predicate p returns true and if p is omitted, counts the number of true elements in the given collection of boolean values.
Syntax:count(p, itr)orcount(itr)
Parameters:
p: Specified set of instructions.
itr: Specified collection of boolean values.
Returns: It returns the count of the number of elements in the specified array for which the given predicate p returns true and if p is omitted, counts the number of true elements in the given collection of boolean values.
Example 1:
# Julia program to illustrate # the use of count() method # Getting the count of the number# of elements in the specified array# for which the given predicate p # returns true.println(count(i->(i<= 3), [1, 2, 3, 4, 5]))println(count(i->(i>3), [1, 2, 3, 4, 5]))println(count(i->(2<= i<= 5), [1, 2, 3, 4, 5]))println(count(i->(i>= 0), [1, 2, 3]))
Output:
3
2
4
3
Example 2:
# Julia program to illustrate # the use of count() method # Getting the counts of number of true elements# in the given collection of boolean values.println(count([false, false, false]))println(count([true, false, true]))println(count([true, true, true]))
Output:
0
2
3
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Vectors in Julia
Getting rounded value of a number in Julia - round() Method
Storing Output on a File in Julia
Manipulating matrices in Julia
Reshaping array dimensions in Julia | Array reshape() Method
Comments in Julia
while loop in Julia
Tuples in Julia
Searching in Array for a given element in Julia
Get array dimensions and size of a dimension in Julia - size() Method
|
[
{
"code": null,
"e": 24180,
"s": 24152,
"text": "\n26 Mar, 2020"
},
{
"code": null,
"e": 24437,
"s": 24180,
"text": "The count() is an inbuilt function in julia which is used to count the number of elements in the specified array for which the given predicate p returns true and if p is omitted, counts the number of true elements in the given collection of boolean values."
},
{
"code": null,
"e": 24470,
"s": 24437,
"text": "Syntax:count(p, itr)orcount(itr)"
},
{
"code": null,
"e": 24482,
"s": 24470,
"text": "Parameters:"
},
{
"code": null,
"e": 24516,
"s": 24482,
"text": "p: Specified set of instructions."
},
{
"code": null,
"e": 24561,
"s": 24516,
"text": "itr: Specified collection of boolean values."
},
{
"code": null,
"e": 24784,
"s": 24561,
"text": "Returns: It returns the count of the number of elements in the specified array for which the given predicate p returns true and if p is omitted, counts the number of true elements in the given collection of boolean values."
},
{
"code": null,
"e": 24795,
"s": 24784,
"text": "Example 1:"
},
{
"code": "# Julia program to illustrate # the use of count() method # Getting the count of the number# of elements in the specified array# for which the given predicate p # returns true.println(count(i->(i<= 3), [1, 2, 3, 4, 5]))println(count(i->(i>3), [1, 2, 3, 4, 5]))println(count(i->(2<= i<= 5), [1, 2, 3, 4, 5]))println(count(i->(i>= 0), [1, 2, 3]))",
"e": 25141,
"s": 24795,
"text": null
},
{
"code": null,
"e": 25149,
"s": 25141,
"text": "Output:"
},
{
"code": null,
"e": 25158,
"s": 25149,
"text": "3\n2\n4\n3\n"
},
{
"code": null,
"e": 25169,
"s": 25158,
"text": "Example 2:"
},
{
"code": "# Julia program to illustrate # the use of count() method # Getting the counts of number of true elements# in the given collection of boolean values.println(count([false, false, false]))println(count([true, false, true]))println(count([true, true, true]))",
"e": 25426,
"s": 25169,
"text": null
},
{
"code": null,
"e": 25434,
"s": 25426,
"text": "Output:"
},
{
"code": null,
"e": 25441,
"s": 25434,
"text": "0\n2\n3\n"
},
{
"code": null,
"e": 25447,
"s": 25441,
"text": "Julia"
},
{
"code": null,
"e": 25545,
"s": 25447,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25562,
"s": 25545,
"text": "Vectors in Julia"
},
{
"code": null,
"e": 25622,
"s": 25562,
"text": "Getting rounded value of a number in Julia - round() Method"
},
{
"code": null,
"e": 25656,
"s": 25622,
"text": "Storing Output on a File in Julia"
},
{
"code": null,
"e": 25687,
"s": 25656,
"text": "Manipulating matrices in Julia"
},
{
"code": null,
"e": 25748,
"s": 25687,
"text": "Reshaping array dimensions in Julia | Array reshape() Method"
},
{
"code": null,
"e": 25766,
"s": 25748,
"text": "Comments in Julia"
},
{
"code": null,
"e": 25786,
"s": 25766,
"text": "while loop in Julia"
},
{
"code": null,
"e": 25802,
"s": 25786,
"text": "Tuples in Julia"
},
{
"code": null,
"e": 25850,
"s": 25802,
"text": "Searching in Array for a given element in Julia"
}
] |
Java Math cos() method with Examples - GeeksforGeeks
|
06 Apr, 2018
The java.lang.Math.cos() returns the trigonometric cosine of an angle. If the argument is NaN or an infinity, then the result returned is NaN. The returned value will be in range [-1, 1].
Syntax :
public static double cos(double angle)
Parameters:
The function has one mandatory parameter angle which is in radians.
Returns :The function returns the trigonometric cosine of an angle.
Example 1 : To show working of java.lang.Math.cos() method.
// Java program to demonstrate working// of java.lang.Math.cos() methodimport java.lang.Math; class Gfg { // driver code public static void main(String args[]) { double a = 30; // converting values to radians double b = Math.toRadians(a); System.out.println(Math.cos(b)); a = 45; // converting values to radians b = Math.toRadians(a); System.out.println(Math.cos(b)); a = 60; // converting values to radians b = Math.toRadians(a); System.out.println(Math.cos(b)); a = 0; // converting values to radians b = Math.toRadians(a); System.out.println(Math.cos(b)); }}
0.8660254037844387
0.7071067811865476
0.5000000000000001
1.0
Example 2 : To show working of java.lang.Math.cos() method when argument is NAN or infinity.
// Java program to demonstrate working// of java.lang.Math.cos() method infinity caseimport java.lang.Math; // importing java.lang package public class GFG { public static void main(String[] args) { double positiveInfinity = Double.POSITIVE_INFINITY; double negativeInfinity = Double.NEGATIVE_INFINITY; double nan = Double.NaN; double result; // Here argument is negative infinity, // output will be NaN result = Math.cos(negativeInfinity); System.out.println(result); // Here argument is positive infinity, // output will also be NaN result = Math.cos(positiveInfinity); System.out.println(result); // Here argument is NaN, output will be NaN result = Math.cos(nan); System.out.println(result); }}
NaN
NaN
NaN
Java-lang package
Java-Library
java-math
Java
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Initialize an ArrayList in Java
HashMap in Java with Examples
Interfaces in Java
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
ArrayList in Java
Multidimensional Arrays in Java
Stack Class in Java
Set in Java
LinkedList in Java
|
[
{
"code": null,
"e": 24522,
"s": 24494,
"text": "\n06 Apr, 2018"
},
{
"code": null,
"e": 24710,
"s": 24522,
"text": "The java.lang.Math.cos() returns the trigonometric cosine of an angle. If the argument is NaN or an infinity, then the result returned is NaN. The returned value will be in range [-1, 1]."
},
{
"code": null,
"e": 24719,
"s": 24710,
"text": "Syntax :"
},
{
"code": null,
"e": 24840,
"s": 24719,
"text": "public static double cos(double angle)\nParameters:\nThe function has one mandatory parameter angle which is in radians. \n"
},
{
"code": null,
"e": 24908,
"s": 24840,
"text": "Returns :The function returns the trigonometric cosine of an angle."
},
{
"code": null,
"e": 24968,
"s": 24908,
"text": "Example 1 : To show working of java.lang.Math.cos() method."
},
{
"code": "// Java program to demonstrate working// of java.lang.Math.cos() methodimport java.lang.Math; class Gfg { // driver code public static void main(String args[]) { double a = 30; // converting values to radians double b = Math.toRadians(a); System.out.println(Math.cos(b)); a = 45; // converting values to radians b = Math.toRadians(a); System.out.println(Math.cos(b)); a = 60; // converting values to radians b = Math.toRadians(a); System.out.println(Math.cos(b)); a = 0; // converting values to radians b = Math.toRadians(a); System.out.println(Math.cos(b)); }}",
"e": 25711,
"s": 24968,
"text": null
},
{
"code": null,
"e": 25773,
"s": 25711,
"text": "0.8660254037844387\n0.7071067811865476\n0.5000000000000001\n1.0\n"
},
{
"code": null,
"e": 25866,
"s": 25773,
"text": "Example 2 : To show working of java.lang.Math.cos() method when argument is NAN or infinity."
},
{
"code": "// Java program to demonstrate working// of java.lang.Math.cos() method infinity caseimport java.lang.Math; // importing java.lang package public class GFG { public static void main(String[] args) { double positiveInfinity = Double.POSITIVE_INFINITY; double negativeInfinity = Double.NEGATIVE_INFINITY; double nan = Double.NaN; double result; // Here argument is negative infinity, // output will be NaN result = Math.cos(negativeInfinity); System.out.println(result); // Here argument is positive infinity, // output will also be NaN result = Math.cos(positiveInfinity); System.out.println(result); // Here argument is NaN, output will be NaN result = Math.cos(nan); System.out.println(result); }}",
"e": 26720,
"s": 25866,
"text": null
},
{
"code": null,
"e": 26733,
"s": 26720,
"text": "NaN\nNaN\nNaN\n"
},
{
"code": null,
"e": 26751,
"s": 26733,
"text": "Java-lang package"
},
{
"code": null,
"e": 26764,
"s": 26751,
"text": "Java-Library"
},
{
"code": null,
"e": 26774,
"s": 26764,
"text": "java-math"
},
{
"code": null,
"e": 26779,
"s": 26774,
"text": "Java"
},
{
"code": null,
"e": 26798,
"s": 26779,
"text": "Technical Scripter"
},
{
"code": null,
"e": 26803,
"s": 26798,
"text": "Java"
},
{
"code": null,
"e": 26901,
"s": 26803,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26910,
"s": 26901,
"text": "Comments"
},
{
"code": null,
"e": 26923,
"s": 26910,
"text": "Old Comments"
},
{
"code": null,
"e": 26955,
"s": 26923,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 26985,
"s": 26955,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 27004,
"s": 26985,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 27055,
"s": 27004,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 27086,
"s": 27055,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 27104,
"s": 27086,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 27136,
"s": 27104,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 27156,
"s": 27136,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 27168,
"s": 27156,
"text": "Set in Java"
}
] |
Building a Dice Game using JavaScript - GeeksforGeeks
|
11 May, 2020
We will be building a Dice Game Project using HTML, CSS, and JavaScript. The Dice Game is based on a two-player. Both players roll the dice and the player who gets the highest phase value will win the game.
Images of Dice Phases: The list of dice phases images are given below. Save all the images in a folder where you save your HTML, CSS, and JavaScript files. You can save all HTML, CSS, and JavaScript files separately and link CSS and JavaScript files to the HTML file or combine all codes (HTML, CSS and JavaScript) in a single file and execute it.
Dice 1
Dice 2
Dice 3
Dice 4
Dice 5
Dice 6
HTML Code: HTML code is used to design the basic structure of the project. The HTML code contains the container class that holds the player’s name and initial dice phase. Another bottom div contains the two buttons (one button for roll the dice and another button for rename the player name).
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <title>Dice Game</title></head> <body> <div class="container"> <h1>Let's Play</h1> <div class="dice"> <p class="Player1">Player 1</p> <img class="img1" src="dice6.png"> </div> <div class="dice"> <p class="Player2">Player 2</p> <img class="img2" src="dice6.png"> </div> </div> <div class="container bottom"> <button type="button" class="butn" onClick="rollTheDice()"> Roll the Dice </button> </div> <div class="container bottom"> <button type="button" class="butn" onClick="editNames()"> Edit Names </button> </div></body> </html>
CSS Code: In this section, we will use some CSS property to style the Dice Game.
<style> .container { width: 70%; margin: auto; text-align: center; } .dice { text-align: center; display: inline-block; margin: 10px; } body { background-color: #042f4b; margin: 0; } h1 { margin: 30px; font-family: "Lobster", cursive; text-shadow: 5px 0 #232931; font-size: 4.5rem; color: #4ecca3; text-align: center; } p { font-size: 2rem; color: #4ecca3; font-family: "Indie Flower", cursive; } img { width: 100%; } .bottom { padding-top: 30px; } .butn { background: #4ecca3; font-family: "Indie Flower", cursive; border-radius: 7px; color: #ffff; font-size: 30px; padding: 16px 25px 16px 25px; text-decoration: none; } .butn:hover { background: #232931; text-decoration: none; }</style>
JavaScript Code: The JavaScript code contains the functionality of Dice Game. The first functionality is to rename the player name after clicking the button. Another functionality is to roll the dice after clicking the button. After rolling the dice by both the player, anyone player will win who get the highest phase value. If both players get the same phase value then the game will draw.
<script> // Player name var player1 = "Player 1"; var player2 = "Player 2"; // Function to change the player name function editNames() { player1 = prompt("Change Player1 name"); player2 = prompt("Change player2 name"); document.querySelector("p.Player1").innerHTML = player1; document.querySelector("p.Player2").innerHTML = player2; } // Function to roll the dice function rollTheDice() { setTimeout(function () { var randomNumber1 = Math.floor(Math.random() * 6) + 1; var randomNumber2 = Math.floor(Math.random() * 6) + 1; document.querySelector(".img1").setAttribute("src", "dice" + randomNumber1 + ".png"); document.querySelector(".img2").setAttribute("src", "dice" + randomNumber2 + ".png"); if (randomNumber1 === randomNumber2) { document.querySelector("h1").innerHTML = "Draw!"; } else if (randomNumber1 < randomNumber2) { document.querySelector("h1").innerHTML = (player2 + " WINS!"); } else { document.querySelector("h1").innerHTML = (player1 + " WINS!"); } }, 2500); }</script>
Complete Code: After combining the above three sections (HTML, CSS, and JavaScript) code, we will get the complete Dice Game.
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content ="width=device-width, initial-scale=1.0"> <title>Dice Game</title> <style> .container { width: 70%; margin: auto; text-align: center; } .dice { text-align: center; display: inline-block; margin: 10px; } body { background-color: #042f4b; margin: 0; } h1 { margin: 30px; font-family: "Lobster", cursive; text-shadow: 5px 0 #232931; font-size: 4.5rem; color: #4ecca3; text-align: center; } p { font-size: 2rem; color: #4ecca3; font-family: "Indie Flower", cursive; } img { width: 100%; } .bottom { padding-top: 30px; } .butn { background: #4ecca3; font-family: "Indie Flower", cursive; border-radius: 7px; color: #ffff; font-size: 30px; padding: 16px 25px 16px 25px; text-decoration: none; } .butn:hover { background: #232931; text-decoration: none; } </style></head> <body> <div class="container"> <h1>Let's Play</h1> <div class="dice"> <p class="Player1">Player 1</p> <img class="img1" src="dice6.png"> </div> <div class="dice"> <p class="Player2">Player 2</p> <img class="img2" src="dice6.png"> </div> </div> <div class="container bottom"> <button type="button" class="butn" onClick="rollTheDice()"> Roll the Dice </button> </div> <div class="container bottom"> <button type="button" class="butn" onClick="editNames()"> Edit Names </button> </div> <script> // Player name var player1 = "Player 1"; var player2 = "Player 2"; // Function to change the player name function editNames() { player1 = prompt("Change Player1 name"); player2 = prompt("Change player2 name"); document.querySelector("p.Player1") .innerHTML = player1; document.querySelector("p.Player2") .innerHTML = player2; } // Function to roll the dice function rollTheDice() { setTimeout(function () { var randomNumber1 = Math.floor(Math.random() * 6) + 1; var randomNumber2 = Math.floor(Math.random() * 6) + 1; document.querySelector(".img1").setAttribute("src", "dice" + randomNumber1 + ".png"); document.querySelector(".img2").setAttribute("src", "dice" + randomNumber2 + ".png"); if (randomNumber1 === randomNumber2) { document.querySelector("h1").innerHTML = "Draw!"; } else if (randomNumber1 < randomNumber2) { document.querySelector("h1").innerHTML = (player2 + " WINS!"); } else { document.querySelector("h1").innerHTML = (player1 + " WINS!"); } }, 2500); } </script></body> </html>
Output:
CSS-Misc
HTML-Misc
JavaScript-Misc
CSS
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to create footer to stay at the bottom of a Web page?
Types of CSS (Cascading Style Sheet)
How to position a div at the bottom of its container using CSS?
Create a Responsive Navbar using ReactJS
Design a web page using HTML and CSS
Convert a string to an integer in JavaScript
How to calculate the number of days between two dates in javascript?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
File uploading in React.js
|
[
{
"code": null,
"e": 24958,
"s": 24930,
"text": "\n11 May, 2020"
},
{
"code": null,
"e": 25165,
"s": 24958,
"text": "We will be building a Dice Game Project using HTML, CSS, and JavaScript. The Dice Game is based on a two-player. Both players roll the dice and the player who gets the highest phase value will win the game."
},
{
"code": null,
"e": 25513,
"s": 25165,
"text": "Images of Dice Phases: The list of dice phases images are given below. Save all the images in a folder where you save your HTML, CSS, and JavaScript files. You can save all HTML, CSS, and JavaScript files separately and link CSS and JavaScript files to the HTML file or combine all codes (HTML, CSS and JavaScript) in a single file and execute it."
},
{
"code": null,
"e": 25520,
"s": 25513,
"text": "Dice 1"
},
{
"code": null,
"e": 25527,
"s": 25520,
"text": "Dice 2"
},
{
"code": null,
"e": 25534,
"s": 25527,
"text": "Dice 3"
},
{
"code": null,
"e": 25541,
"s": 25534,
"text": "Dice 4"
},
{
"code": null,
"e": 25548,
"s": 25541,
"text": "Dice 5"
},
{
"code": null,
"e": 25555,
"s": 25548,
"text": "Dice 6"
},
{
"code": null,
"e": 25848,
"s": 25555,
"text": "HTML Code: HTML code is used to design the basic structure of the project. The HTML code contains the container class that holds the player’s name and initial dice phase. Another bottom div contains the two buttons (one button for roll the dice and another button for rename the player name)."
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <title>Dice Game</title></head> <body> <div class=\"container\"> <h1>Let's Play</h1> <div class=\"dice\"> <p class=\"Player1\">Player 1</p> <img class=\"img1\" src=\"dice6.png\"> </div> <div class=\"dice\"> <p class=\"Player2\">Player 2</p> <img class=\"img2\" src=\"dice6.png\"> </div> </div> <div class=\"container bottom\"> <button type=\"button\" class=\"butn\" onClick=\"rollTheDice()\"> Roll the Dice </button> </div> <div class=\"container bottom\"> <button type=\"button\" class=\"butn\" onClick=\"editNames()\"> Edit Names </button> </div></body> </html>",
"e": 26707,
"s": 25848,
"text": null
},
{
"code": null,
"e": 26788,
"s": 26707,
"text": "CSS Code: In this section, we will use some CSS property to style the Dice Game."
},
{
"code": "<style> .container { width: 70%; margin: auto; text-align: center; } .dice { text-align: center; display: inline-block; margin: 10px; } body { background-color: #042f4b; margin: 0; } h1 { margin: 30px; font-family: \"Lobster\", cursive; text-shadow: 5px 0 #232931; font-size: 4.5rem; color: #4ecca3; text-align: center; } p { font-size: 2rem; color: #4ecca3; font-family: \"Indie Flower\", cursive; } img { width: 100%; } .bottom { padding-top: 30px; } .butn { background: #4ecca3; font-family: \"Indie Flower\", cursive; border-radius: 7px; color: #ffff; font-size: 30px; padding: 16px 25px 16px 25px; text-decoration: none; } .butn:hover { background: #232931; text-decoration: none; }</style>",
"e": 27744,
"s": 26788,
"text": null
},
{
"code": null,
"e": 28136,
"s": 27744,
"text": "JavaScript Code: The JavaScript code contains the functionality of Dice Game. The first functionality is to rename the player name after clicking the button. Another functionality is to roll the dice after clicking the button. After rolling the dice by both the player, anyone player will win who get the highest phase value. If both players get the same phase value then the game will draw."
},
{
"code": "<script> // Player name var player1 = \"Player 1\"; var player2 = \"Player 2\"; // Function to change the player name function editNames() { player1 = prompt(\"Change Player1 name\"); player2 = prompt(\"Change player2 name\"); document.querySelector(\"p.Player1\").innerHTML = player1; document.querySelector(\"p.Player2\").innerHTML = player2; } // Function to roll the dice function rollTheDice() { setTimeout(function () { var randomNumber1 = Math.floor(Math.random() * 6) + 1; var randomNumber2 = Math.floor(Math.random() * 6) + 1; document.querySelector(\".img1\").setAttribute(\"src\", \"dice\" + randomNumber1 + \".png\"); document.querySelector(\".img2\").setAttribute(\"src\", \"dice\" + randomNumber2 + \".png\"); if (randomNumber1 === randomNumber2) { document.querySelector(\"h1\").innerHTML = \"Draw!\"; } else if (randomNumber1 < randomNumber2) { document.querySelector(\"h1\").innerHTML = (player2 + \" WINS!\"); } else { document.querySelector(\"h1\").innerHTML = (player1 + \" WINS!\"); } }, 2500); }</script>",
"e": 29457,
"s": 28136,
"text": null
},
{
"code": null,
"e": 29583,
"s": 29457,
"text": "Complete Code: After combining the above three sections (HTML, CSS, and JavaScript) code, we will get the complete Dice Game."
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content =\"width=device-width, initial-scale=1.0\"> <title>Dice Game</title> <style> .container { width: 70%; margin: auto; text-align: center; } .dice { text-align: center; display: inline-block; margin: 10px; } body { background-color: #042f4b; margin: 0; } h1 { margin: 30px; font-family: \"Lobster\", cursive; text-shadow: 5px 0 #232931; font-size: 4.5rem; color: #4ecca3; text-align: center; } p { font-size: 2rem; color: #4ecca3; font-family: \"Indie Flower\", cursive; } img { width: 100%; } .bottom { padding-top: 30px; } .butn { background: #4ecca3; font-family: \"Indie Flower\", cursive; border-radius: 7px; color: #ffff; font-size: 30px; padding: 16px 25px 16px 25px; text-decoration: none; } .butn:hover { background: #232931; text-decoration: none; } </style></head> <body> <div class=\"container\"> <h1>Let's Play</h1> <div class=\"dice\"> <p class=\"Player1\">Player 1</p> <img class=\"img1\" src=\"dice6.png\"> </div> <div class=\"dice\"> <p class=\"Player2\">Player 2</p> <img class=\"img2\" src=\"dice6.png\"> </div> </div> <div class=\"container bottom\"> <button type=\"button\" class=\"butn\" onClick=\"rollTheDice()\"> Roll the Dice </button> </div> <div class=\"container bottom\"> <button type=\"button\" class=\"butn\" onClick=\"editNames()\"> Edit Names </button> </div> <script> // Player name var player1 = \"Player 1\"; var player2 = \"Player 2\"; // Function to change the player name function editNames() { player1 = prompt(\"Change Player1 name\"); player2 = prompt(\"Change player2 name\"); document.querySelector(\"p.Player1\") .innerHTML = player1; document.querySelector(\"p.Player2\") .innerHTML = player2; } // Function to roll the dice function rollTheDice() { setTimeout(function () { var randomNumber1 = Math.floor(Math.random() * 6) + 1; var randomNumber2 = Math.floor(Math.random() * 6) + 1; document.querySelector(\".img1\").setAttribute(\"src\", \"dice\" + randomNumber1 + \".png\"); document.querySelector(\".img2\").setAttribute(\"src\", \"dice\" + randomNumber2 + \".png\"); if (randomNumber1 === randomNumber2) { document.querySelector(\"h1\").innerHTML = \"Draw!\"; } else if (randomNumber1 < randomNumber2) { document.querySelector(\"h1\").innerHTML = (player2 + \" WINS!\"); } else { document.querySelector(\"h1\").innerHTML = (player1 + \" WINS!\"); } }, 2500); } </script></body> </html>",
"e": 33110,
"s": 29583,
"text": null
},
{
"code": null,
"e": 33118,
"s": 33110,
"text": "Output:"
},
{
"code": null,
"e": 33127,
"s": 33118,
"text": "CSS-Misc"
},
{
"code": null,
"e": 33137,
"s": 33127,
"text": "HTML-Misc"
},
{
"code": null,
"e": 33153,
"s": 33137,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 33157,
"s": 33153,
"text": "CSS"
},
{
"code": null,
"e": 33168,
"s": 33157,
"text": "JavaScript"
},
{
"code": null,
"e": 33185,
"s": 33168,
"text": "Web Technologies"
},
{
"code": null,
"e": 33212,
"s": 33185,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 33310,
"s": 33212,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33319,
"s": 33310,
"text": "Comments"
},
{
"code": null,
"e": 33332,
"s": 33319,
"text": "Old Comments"
},
{
"code": null,
"e": 33390,
"s": 33332,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 33427,
"s": 33390,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 33491,
"s": 33427,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 33532,
"s": 33491,
"text": "Create a Responsive Navbar using ReactJS"
},
{
"code": null,
"e": 33569,
"s": 33532,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 33614,
"s": 33569,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 33683,
"s": 33614,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 33744,
"s": 33683,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 33816,
"s": 33744,
"text": "Differences between Functional Components and Class Components in React"
}
] |
AIML - <random> Tag
|
<random> Tag is used to get random responses. This tag enables AIML to respond differently for the same input. <random> tag is used along with <li> tags. <li> tags carry different responses that are to be delivered to the user on a random basis.
<random>
<li> pattern1 </li>
<li> pattern2 </li>
...
<li> patternN </li>
</random>
For example, consider the following conversation.
Human: Hi
Robot: Hello!
Human: Hi
Robot: Hi! Nice to meet you!
Create random.aiml inside C > ab > bots > test > aiml and random.aiml.csv inside C > ab > bots > test > aimlif directories.
<?xml version = "1.0" encoding = "UTF-8"?>
<aiml version = "1.0.1" encoding ="UTF-8"?>
<category>
<pattern>HI</pattern>
<template>
<random>
<li> Hello! </li>
<li> Hi! Nice to meet you! </li>
</random>
</template>
<category>
</aiml>
0,HI,*,*, <random><li> Hello! </li><li> Hi! Nice to meet you! </li></random>,random.aiml
Open the command prompt. Go to C > ab > and type the following command −
java -cp lib/Ab.jar Main bot = test action = chat trace = false
You will see the following output −
Human: Hi
Robot: Hi! Nice to meet you!
Human: Hi
Robot: Hello!
Here, the response may vary considering random responses.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2057,
"s": 1811,
"text": "<random> Tag is used to get random responses. This tag enables AIML to respond differently for the same input. <random> tag is used along with <li> tags. <li> tags carry different responses that are to be delivered to the user on a random basis."
},
{
"code": null,
"e": 2152,
"s": 2057,
"text": "<random>\n <li> pattern1 </li>\n <li> pattern2 </li>\n ...\n <li> patternN </li>\n</random>"
},
{
"code": null,
"e": 2202,
"s": 2152,
"text": "For example, consider the following conversation."
},
{
"code": null,
"e": 2266,
"s": 2202,
"text": "Human: Hi\nRobot: Hello!\nHuman: Hi\nRobot: Hi! Nice to meet you!\n"
},
{
"code": null,
"e": 2390,
"s": 2266,
"text": "Create random.aiml inside C > ab > bots > test > aiml and random.aiml.csv inside C > ab > bots > test > aimlif directories."
},
{
"code": null,
"e": 2708,
"s": 2390,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<aiml version = \"1.0.1\" encoding =\"UTF-8\"?>\n <category>\n <pattern>HI</pattern>\n \n <template>\n <random>\n <li> Hello! </li>\n <li> Hi! Nice to meet you! </li>\n </random>\n </template>\n \n <category> \n</aiml>"
},
{
"code": null,
"e": 2797,
"s": 2708,
"text": "0,HI,*,*, <random><li> Hello! </li><li> Hi! Nice to meet you! </li></random>,random.aiml"
},
{
"code": null,
"e": 2870,
"s": 2797,
"text": "Open the command prompt. Go to C > ab > and type the following command −"
},
{
"code": null,
"e": 2935,
"s": 2870,
"text": "java -cp lib/Ab.jar Main bot = test action = chat trace = false\n"
},
{
"code": null,
"e": 2971,
"s": 2935,
"text": "You will see the following output −"
},
{
"code": null,
"e": 3035,
"s": 2971,
"text": "Human: Hi\nRobot: Hi! Nice to meet you!\nHuman: Hi\nRobot: Hello!\n"
},
{
"code": null,
"e": 3093,
"s": 3035,
"text": "Here, the response may vary considering random responses."
},
{
"code": null,
"e": 3100,
"s": 3093,
"text": " Print"
},
{
"code": null,
"e": 3111,
"s": 3100,
"text": " Add Notes"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.